diff --git a/MLPY/Lib/site-packages/tensorboard/__init__.py b/MLPY/Lib/site-packages/tensorboard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..95bc174e64d652d19d4353a28dc1c51858f922b9 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/__init__.py @@ -0,0 +1,113 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TensorBoard is a webapp for understanding TensorFlow runs and graphs.""" + + +from tensorboard import lazy as _lazy +from tensorboard import version as _version + +# TensorBoard public API. +__all__ = [ + "__version__", + "errors", + "notebook", + "program", + "summary", +] + + +# Please be careful when changing the structure of this file. +# +# The lazy imports in this file must use `importlib.import_module`, not +# `import tensorboard.foo` or `from tensorboard import foo`, or it will +# be impossible to reload the TensorBoard module without breaking these +# top-level public APIs. This has to do with the gory details of +# Python's module system. Take `tensorboard.notebook` as an example: +# +# - When the `tensorboard` module (that's us!) is initialized, its +# `notebook` attribute is initialized to a new LazyModule. The +# actual `tensorboard.notebook` submodule is not loaded. +# +# - When the `tensorboard.notebook` submodule is first loaded, Python +# _reassigns_ the `notebook` attribute on the `tensorboard` module +# object to point to the underlying `tensorboard.notebook` module +# object, rather than its former LazyModule value. This occurs +# whether the module is loaded via the lazy module or directly as an +# import: +# +# - import tensorboard; tensorboard.notebook.start(...) # one way +# - from tensorboard import notebook # other way; same effect +# +# - When the `tensorboard` module is reloaded, its `notebook` +# attribute is once again bound to a (new) LazyModule, while the +# `tensorboard.notebook` module object is unaffected and still +# exists in `sys.modules`. But then... +# +# - When the new LazyModule is forced, it must resolve to the existing +# `tensorboard.notebook` module object rather than itself (which +# just creates a stack overflow). If the LazyModule load function +# uses `import tensorboard.notebook; return tensorboard.notebook`, +# then the first statement will do _nothing_ because the +# `tensorboard.notebook` module is already loaded, and the second +# statement will return the LazyModule itself. The same goes for the +# `from tensorboard import notebook` form. We need to ensure that +# the submodule is loaded and then pull the actual module object out +# of `sys.modules`... which is exactly what `importlib` handles for +# us. +# +# See for +# additional discussion. + + +@_lazy.lazy_load("tensorboard.errors") +def errors(): + import importlib + + return importlib.import_module("tensorboard.errors") + + +@_lazy.lazy_load("tensorboard.notebook") +def notebook(): + import importlib + + return importlib.import_module("tensorboard.notebook") + + +@_lazy.lazy_load("tensorboard.program") +def program(): + import importlib + + return importlib.import_module("tensorboard.program") + + +@_lazy.lazy_load("tensorboard.summary") +def summary(): + import importlib + + return importlib.import_module("tensorboard.summary") + + +def load_ipython_extension(ipython): + """IPython API entry point. + + Only intended to be called by the IPython runtime. + + See: + https://ipython.readthedocs.io/en/stable/config/extensions/index.html + """ + notebook._load_ipython_extension(ipython) + + +__version__ = _version.VERSION diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/__init__.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7e43ea083622c03e980a6904196c7f3bf666221 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/__init__.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/assets.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/assets.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21e57a262394807de12caa51c39e3f7929d10f75 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/assets.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/auth.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/auth.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cb8ab4a45c7643bd8a4dff9621b6b7e68a8147b Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/auth.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/context.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/context.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0251cdf08b46a193ebde093c14a2b3a68010cb23 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/context.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/data_compat.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/data_compat.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec61c586bc821e1778c49a4470c4cd5f2dddf288 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/data_compat.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/dataclass_compat.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/dataclass_compat.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7584c07bff1535fc35e39eedf734a7cf47c2eb1d Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/dataclass_compat.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/default.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/default.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6ca232e4242e2659ea13c6a43cacd88e514c9e3 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/default.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/errors.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/errors.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b40204ea0098fc6e1de80fc7fcbe5cbc0ed750de Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/errors.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/lazy.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/lazy.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6d88ccc5ac4390789677dc8fc5ac5e63731c42b Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/lazy.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/main.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/main.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d011418b51e05fe302f26e29751b7f8bcd058eb5 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/main.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/main_lib.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/main_lib.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee188ef1a80145784b0f33da4fe984596123c9da Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/main_lib.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/manager.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/manager.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83a1bd056bdf8b21afbf312279aa67901cc2cafc Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/manager.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/notebook.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/notebook.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59583d8563d0666518037a8c6612271254572acb Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/notebook.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/plugin_util.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/plugin_util.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b88972648e818ed79e8aef8e36964ef0d449635 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/plugin_util.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/program.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/program.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14bbeaab2bcce21bfcd631de3bf4a2533569daea Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/program.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/__pycache__/version.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/__pycache__/version.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..895b4b63cd6d32d0bd80065690a83a70b3c765b3 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/__pycache__/version.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/__init__.py b/MLPY/Lib/site-packages/tensorboard/_vendor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/__pycache__/__init__.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a47c537da072aebf3137704a0e04d7f2efafb0bf Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/__pycache__/__init__.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__init__.py b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c39ef09c5fcd86a27d4a76f35e9a6d19807707b2 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__init__.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +from tensorboard._vendor.bleach.linkifier import ( + DEFAULT_CALLBACKS, + Linker, + LinkifyFilter, +) +from tensorboard._vendor.bleach.sanitizer import ( + ALLOWED_ATTRIBUTES, + ALLOWED_PROTOCOLS, + ALLOWED_STYLES, + ALLOWED_TAGS, + BleachSanitizerFilter, + Cleaner, +) +from tensorboard._vendor.bleach.version import __version__, VERSION # flake8: noqa + +__all__ = ['clean', 'linkify'] + + +def clean(text, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, + styles=ALLOWED_STYLES, protocols=ALLOWED_PROTOCOLS, strip=False, + strip_comments=True): + """Clean an HTML fragment of malicious content and return it + + This function is a security-focused function whose sole purpose is to + remove malicious content from a string such that it can be displayed as + content in a web page. + + This function is not designed to use to transform content to be used in + non-web-page contexts. + + Example:: + + import bleach + + better_text = bleach.clean(yucky_text) + + + .. Note:: + + If you're cleaning a lot of text and passing the same argument values or + you want more configurability, consider using a + :py:class:`bleach.sanitizer.Cleaner` instance. + + :arg str text: the text to clean + + :arg list tags: allowed list of tags; defaults to + ``bleach.sanitizer.ALLOWED_TAGS`` + + :arg dict attributes: allowed attributes; can be a callable, list or dict; + defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` + + :arg list styles: allowed list of css styles; defaults to + ``bleach.sanitizer.ALLOWED_STYLES`` + + :arg list protocols: allowed list of protocols for links; defaults + to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` + + :arg bool strip: whether or not to strip disallowed elements + + :arg bool strip_comments: whether or not to strip HTML comments + + :returns: cleaned text as unicode + + """ + cleaner = Cleaner( + tags=tags, + attributes=attributes, + styles=styles, + protocols=protocols, + strip=strip, + strip_comments=strip_comments, + ) + return cleaner.clean(text) + + +def linkify(text, callbacks=DEFAULT_CALLBACKS, skip_tags=None, parse_email=False): + """Convert URL-like strings in an HTML fragment to links + + This function converts strings that look like URLs, domain names and email + addresses in text that may be an HTML fragment to links, while preserving: + + 1. links already in the string + 2. urls found in attributes + 3. email addresses + + linkify does a best-effort approach and tries to recover from bad + situations due to crazy text. + + .. Note:: + + If you're linking a lot of text and passing the same argument values or + you want more configurability, consider using a + :py:class:`bleach.linkifier.Linker` instance. + + .. Note:: + + If you have text that you want to clean and then linkify, consider using + the :py:class:`bleach.linkifier.LinkifyFilter` as a filter in the clean + pass. That way you're not parsing the HTML twice. + + :arg str text: the text to linkify + + :arg list callbacks: list of callbacks to run when adjusting tag attributes; + defaults to ``bleach.linkifier.DEFAULT_CALLBACKS`` + + :arg list skip_tags: list of tags that you don't want to linkify the + contents of; for example, you could set this to ``['pre']`` to skip + linkifying contents of ``pre`` tags + + :arg bool parse_email: whether or not to linkify email addresses + + :returns: linkified text as unicode + + """ + linker = Linker( + callbacks=callbacks, + skip_tags=skip_tags, + parse_email=parse_email + ) + return linker.linkify(text) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/__init__.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9fe6f807e8cbe409cd6cfd1b12750c565e65e48 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/__init__.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/callbacks.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/callbacks.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc58c1d83c53479e8cffa596f34201a4b1cf0b08 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/callbacks.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/encoding.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/encoding.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c68af4c0db22ed3cb1e01c4af7a3d82310bc772 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/encoding.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/linkifier.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/linkifier.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15b3f61b51387bb9d37310158f957b6f8805bc4b Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/linkifier.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/sanitizer.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/sanitizer.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47726f426e5e53be397ddb425d638166d8f305be Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/sanitizer.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/utils.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..898c0ad2e6149e9bad11a895d7eb0ebc3dfe128f Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/utils.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/version.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/version.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42d7faf4137966aad54deb6c5c03e03970740f32 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/__pycache__/version.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/callbacks.py b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..d2ba1014ed8c901445c1d94046cccc763fd79e4d --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/callbacks.py @@ -0,0 +1,25 @@ +"""A set of basic callbacks for bleach.linkify.""" +from __future__ import unicode_literals + + +def nofollow(attrs, new=False): + href_key = (None, u'href') + if href_key not in attrs or attrs[href_key].startswith(u'mailto:'): + return attrs + + rel_key = (None, u'rel') + rel_values = [val for val in attrs.get(rel_key, u'').split(u' ') if val] + if u'nofollow' not in [rel_val.lower() for rel_val in rel_values]: + rel_values.append(u'nofollow') + attrs[rel_key] = u' '.join(rel_values) + + return attrs + + +def target_blank(attrs, new=False): + href_key = (None, u'href') + if attrs[href_key].startswith(u'mailto:'): + return attrs + + attrs[(None, u'target')] = u'_blank' + return attrs diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/encoding.py b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..707adaa2bbecd4ce7b5488d02c82a02bd965bd01 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/encoding.py @@ -0,0 +1,62 @@ +import datetime +from decimal import Decimal +import types +import six + + +def is_protected_type(obj): + """Determine if the object instance is of a protected type. + + Objects of protected types are preserved as-is when passed to + force_unicode(strings_only=True). + """ + return isinstance(obj, ( + six.integer_types + + (types.NoneType, + datetime.datetime, datetime.date, datetime.time, + float, Decimal)) + ) + + +def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): + """ + Similar to smart_text, except that lazy instances are resolved to + strings, rather than kept as lazy objects. + + If strings_only is True, don't convert (some) non-string-like objects. + """ + # Handle the common case first, saves 30-40% when s is an instance of + # six.text_type. This function gets called often in that setting. + if isinstance(s, six.text_type): + return s + if strings_only and is_protected_type(s): + return s + try: + if not isinstance(s, six.string_types): + if hasattr(s, '__unicode__'): + s = s.__unicode__() + else: + if six.PY3: + if isinstance(s, bytes): + s = six.text_type(s, encoding, errors) + else: + s = six.text_type(s) + else: + s = six.text_type(bytes(s), encoding, errors) + else: + # Note: We use .decode() here, instead of six.text_type(s, + # encoding, errors), so that if s is a SafeBytes, it ends up being + # a SafeText at the end. + s = s.decode(encoding, errors) + except UnicodeDecodeError as e: + if not isinstance(s, Exception): + raise UnicodeDecodeError(*e.args) + else: + # If we get to here, the caller has passed in an Exception + # subclass populated with non-ASCII bytestring data without a + # working unicode method. Try to handle this without raising a + # further exception by individually forcing the exception args + # to unicode. + s = ' '.join([force_unicode(arg, encoding, strings_only, + errors) for arg in s]) + return s diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/linkifier.py b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/linkifier.py new file mode 100644 index 0000000000000000000000000000000000000000..ec13bb50ecc19ba6c03f2ee5206bb10e9dfe3236 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/linkifier.py @@ -0,0 +1,526 @@ +from __future__ import unicode_literals +import re + +from tensorboard._vendor import html5lib +from tensorboard._vendor.html5lib.filters.base import Filter +from tensorboard._vendor.html5lib.filters.sanitizer import allowed_protocols +from tensorboard._vendor.html5lib.serializer import HTMLSerializer + +from tensorboard._vendor.bleach import callbacks as linkify_callbacks +from tensorboard._vendor.bleach.encoding import force_unicode +from tensorboard._vendor.bleach.utils import alphabetize_attributes + + +#: List of default callbacks +DEFAULT_CALLBACKS = [linkify_callbacks.nofollow] + + +TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az + ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat + cc cd cf cg ch ci ck cl cm cn co com coop cr cu cv cx cy cz de dj dk + dm do dz ec edu ee eg er es et eu fi fj fk fm fo fr ga gb gd ge gf gg + gh gi gl gm gn gov gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il + im in info int io iq ir is it je jm jo jobs jp ke kg kh ki km kn kp + kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mg mh mil mk + ml mm mn mo mobi mp mq mr ms mt mu museum mv mw mx my mz na name nc ne + net nf ng ni nl no np nr nu nz om org pa pe pf pg ph pk pl pm pn post + pr pro ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl + sm sn so sr ss st su sv sx sy sz tc td tel tf tg th tj tk tl tm tn to + tp tr travel tt tv tw tz ua ug uk us uy uz va vc ve vg vi vn vu wf ws + xn xxx ye yt yu za zm zw""".split() + +# Make sure that .com doesn't get matched by .co first +TLDS.reverse() + + +def build_url_re(tlds=TLDS, protocols=allowed_protocols): + """Builds the url regex used by linkifier + + If you want a different set of tlds or allowed protocols, pass those in + and stomp on the existing ``url_re``:: + + from bleach import linkifier + + my_url_re = linkifier.build_url_re(my_tlds_list, my_protocols) + + linker = LinkifyFilter(url_re=my_url_re) + + """ + return re.compile( + r"""\(* # Match any opening parentheses. + \b(?"]*)? + # /path/zz (excluding "unsafe" chars from RFC 1738, + # except for # and ~, which happen in practice) + """.format('|'.join(protocols), '|'.join(tlds)), + re.IGNORECASE | re.VERBOSE | re.UNICODE) + + +URL_RE = build_url_re() + + +PROTO_RE = re.compile(r'^[\w-]+:/{0,3}', re.IGNORECASE) + + +EMAIL_RE = re.compile( + r"""(? ``value`` + + :arg bool is_new: whether or not this link was added by linkify + + :returns: adjusted attrs dict or ``None`` + + """ + for cb in self.callbacks: + attrs = cb(attrs, is_new) + if attrs is None: + return None + return attrs + + def extract_character_data(self, token_list): + """Extracts and squashes character sequences in a token stream""" + # FIXME(willkg): This is a terrible idea. What it does is drop all the + # tags from the token list and merge the Characters and SpaceCharacters + # tokens into a single text. + # + # So something like this:: + # + # "" "" "some text" "" "" + # + # gets converted to "some text". + # + # This gets used to figure out the ``_text`` fauxttribute value for + # linkify callables. + # + # I'm not really sure how else to support that ``_text`` fauxttribute and + # maintain some modicum of backwards compatability with previous versions + # of Bleach. + + out = [] + for token in token_list: + token_type = token['type'] + if token_type in ['Characters', 'SpaceCharacters']: + out.append(token['data']) + + return u''.join(out) + + def handle_email_addresses(self, src_iter): + """Handle email addresses in character tokens""" + for token in src_iter: + if token['type'] == 'Characters': + text = token['data'] + new_tokens = [] + end = 0 + + # For each email address we find in the text + for match in self.email_re.finditer(text): + if match.start() > end: + new_tokens.append( + {u'type': u'Characters', u'data': text[end:match.start()]} + ) + + # Run attributes through the callbacks to see what we + # should do with this match + attrs = { + (None, u'href'): u'mailto:%s' % match.group(0), + u'_text': match.group(0) + } + attrs = self.apply_callbacks(attrs, True) + + if attrs is None: + # Just add the text--but not as a link + new_tokens.append( + {u'type': u'Characters', u'data': match.group(0)} + ) + + else: + # Add an "a" tag for the new link + _text = attrs.pop(u'_text', '') + attrs = alphabetize_attributes(attrs) + new_tokens.extend([ + {u'type': u'StartTag', u'name': u'a', u'data': attrs}, + {u'type': u'Characters', u'data': force_unicode(_text)}, + {u'type': u'EndTag', u'name': 'a'} + ]) + end = match.end() + + if new_tokens: + # Yield the adjusted set of tokens and then continue + # through the loop + if end < len(text): + new_tokens.append({u'type': u'Characters', u'data': text[end:]}) + + for new_token in new_tokens: + yield new_token + + continue + + yield token + + def strip_non_url_bits(self, fragment): + """Strips non-url bits from the url + + This accounts for over-eager matching by the regex. + + """ + prefix = suffix = '' + + while fragment: + # Try removing ( from the beginning and, if it's balanced, from the + # end, too + if fragment.startswith(u'('): + prefix = prefix + u'(' + fragment = fragment[1:] + + if fragment.endswith(u')'): + suffix = u')' + suffix + fragment = fragment[:-1] + continue + + # Now try extraneous things from the end. For example, sometimes we + # pick up ) at the end of a url, but the url is in a parenthesized + # phrase like: + # + # "i looked at the site (at http://example.com)" + + if fragment.endswith(u')') and u'(' not in fragment: + fragment = fragment[:-1] + suffix = u')' + suffix + continue + + # Handle commas + if fragment.endswith(u','): + fragment = fragment[:-1] + suffix = u',' + suffix + continue + + # Handle periods + if fragment.endswith(u'.'): + fragment = fragment[:-1] + suffix = u'.' + suffix + continue + + # Nothing matched, so we're done + break + + return fragment, prefix, suffix + + def handle_links(self, src_iter): + """Handle links in character tokens""" + for token in src_iter: + if token['type'] == 'Characters': + text = token['data'] + new_tokens = [] + end = 0 + + for match in self.url_re.finditer(text): + if match.start() > end: + new_tokens.append( + {u'type': u'Characters', u'data': text[end:match.start()]} + ) + + url = match.group(0) + prefix = suffix = '' + + # Sometimes we pick up too much in the url match, so look for + # bits we should drop and remove them from the match + url, prefix, suffix = self.strip_non_url_bits(url) + + # If there's no protocol, add one + if PROTO_RE.search(url): + href = url + else: + href = u'http://%s' % url + + attrs = { + (None, u'href'): href, + u'_text': url + } + attrs = self.apply_callbacks(attrs, True) + + if attrs is None: + # Just add the text + new_tokens.append( + {u'type': u'Characters', u'data': prefix + url + suffix} + ) + + else: + # Add the "a" tag! + if prefix: + new_tokens.append( + {u'type': u'Characters', u'data': prefix} + ) + + _text = attrs.pop(u'_text', '') + attrs = alphabetize_attributes(attrs) + + new_tokens.extend([ + {u'type': u'StartTag', u'name': u'a', u'data': attrs}, + {u'type': u'Characters', u'data': force_unicode(_text)}, + {u'type': u'EndTag', u'name': 'a'}, + ]) + + if suffix: + new_tokens.append( + {u'type': u'Characters', u'data': suffix} + ) + + end = match.end() + + if new_tokens: + # Yield the adjusted set of tokens and then continue + # through the loop + if end < len(text): + new_tokens.append({u'type': u'Characters', u'data': text[end:]}) + + for new_token in new_tokens: + yield new_token + + continue + + yield token + + def handle_a_tag(self, token_buffer): + """Handle the "a" tag + + This could adjust the link or drop it altogether depending on what the + callbacks return. + + This yields the new set of tokens. + + """ + a_token = token_buffer[0] + if a_token['data']: + attrs = a_token['data'] + else: + attrs = {} + text = self.extract_character_data(token_buffer) + attrs['_text'] = text + + attrs = self.apply_callbacks(attrs, False) + + if attrs is None: + # We're dropping the "a" tag and everything else and replacing + # it with character data. So emit that token. + yield {'type': 'Characters', 'data': text} + + else: + new_text = attrs.pop('_text', '') + a_token['data'] = alphabetize_attributes(attrs) + + if text == new_text: + # The callbacks didn't change the text, so we yield the new "a" + # token, then whatever else was there, then the end "a" token + yield a_token + for mem in token_buffer[1:]: + yield mem + + else: + # If the callbacks changed the text, then we're going to drop + # all the tokens between the start and end "a" tags and replace + # it with the new text + yield a_token + yield {'type': 'Characters', 'data': force_unicode(new_text)} + yield token_buffer[-1] + + def __iter__(self): + in_a = False + in_skip_tag = None + + token_buffer = [] + + for token in super(LinkifyFilter, self).__iter__(): + if in_a: + # Handle the case where we're in an "a" tag--we want to buffer tokens + # until we hit an end "a" tag. + if token['type'] == 'EndTag' and token['name'] == 'a': + # Add the end tag to the token buffer and then handle them + # and yield anything returned + token_buffer.append(token) + for new_token in self.handle_a_tag(token_buffer): + yield new_token + + # Clear "a" related state and continue since we've yielded all + # the tokens we're going to yield + in_a = False + token_buffer = [] + continue + + else: + token_buffer.append(token) + continue + + elif token['type'] in ['StartTag', 'EmptyTag']: + if token['name'] in self.skip_tags: + # Skip tags start a "special mode" where we don't linkify + # anything until the end tag. + in_skip_tag = token['name'] + + elif token['name'] == 'a': + # The "a" tag is special--we switch to a slurp mode and + # slurp all the tokens until the end "a" tag and then + # figure out what to do with them there. + in_a = True + token_buffer.append(token) + + # We buffer the start tag, so we don't want to yield it, + # yet + continue + + elif in_skip_tag and self.skip_tags: + # NOTE(willkg): We put this clause here since in_a and + # switching in and out of in_a takes precedence. + if token['type'] == 'EndTag' and token['name'] == in_skip_tag: + in_skip_tag = None + + elif not in_a and not in_skip_tag and token['type'] == 'Characters': + new_stream = iter([token]) + if self.parse_email: + new_stream = self.handle_email_addresses(new_stream) + + new_stream = self.handle_links(new_stream) + + for token in new_stream: + yield token + + # We've already yielded this token, so continue + continue + + yield token diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/sanitizer.py b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/sanitizer.py new file mode 100644 index 0000000000000000000000000000000000000000..1d4d4a5794fccce0eb779d12656cb3dffc940ee3 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/sanitizer.py @@ -0,0 +1,368 @@ +from __future__ import unicode_literals +import re +from xml.sax.saxutils import unescape + +from tensorboard._vendor import html5lib +from tensorboard._vendor.html5lib.constants import namespaces +from tensorboard._vendor.html5lib.filters import sanitizer +from tensorboard._vendor.html5lib.serializer import HTMLSerializer + +from tensorboard._vendor.bleach.encoding import force_unicode +from tensorboard._vendor.bleach.utils import alphabetize_attributes + + +#: List of allowed tags +ALLOWED_TAGS = [ + 'a', + 'abbr', + 'acronym', + 'b', + 'blockquote', + 'code', + 'em', + 'i', + 'li', + 'ol', + 'strong', + 'ul', +] + + +#: Map of allowed attributes by tag +ALLOWED_ATTRIBUTES = { + 'a': ['href', 'title'], + 'abbr': ['title'], + 'acronym': ['title'], +} + + +#: List of allowed styles +ALLOWED_STYLES = [] + + +#: List of allowed protocols +ALLOWED_PROTOCOLS = ['http', 'https', 'mailto'] + + +class Cleaner(object): + """Cleaner for cleaning HTML fragments of malicious content + + This cleaner is a security-focused function whose sole purpose is to remove + malicious content from a string such that it can be displayed as content in + a web page. + + This cleaner is not designed to use to transform content to be used in + non-web-page contexts. + + To use:: + + from bleach.sanitizer import Cleaner + + cleaner = Cleaner() + + for text in all_the_yucky_things: + sanitized = cleaner.clean(text) + + """ + + def __init__(self, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, + styles=ALLOWED_STYLES, protocols=ALLOWED_PROTOCOLS, strip=False, + strip_comments=True, filters=None): + """Initializes a Cleaner + + :arg list tags: allowed list of tags; defaults to + ``bleach.sanitizer.ALLOWED_TAGS`` + + :arg dict attributes: allowed attributes; can be a callable, list or dict; + defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` + + :arg list styles: allowed list of css styles; defaults to + ``bleach.sanitizer.ALLOWED_STYLES`` + + :arg list protocols: allowed list of protocols for links; defaults + to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` + + :arg bool strip: whether or not to strip disallowed elements + + :arg bool strip_comments: whether or not to strip HTML comments + + :arg list filters: list of html5lib Filter classes to pass streamed content through + + .. seealso:: http://html5lib.readthedocs.io/en/latest/movingparts.html#filters + + .. Warning:: + + Using filters changes the output of ``bleach.Cleaner.clean``. + Make sure the way the filters change the output are secure. + + """ + self.tags = tags + self.attributes = attributes + self.styles = styles + self.protocols = protocols + self.strip = strip + self.strip_comments = strip_comments + self.filters = filters or [] + + self.parser = html5lib.HTMLParser(namespaceHTMLElements=False) + self.walker = html5lib.getTreeWalker('etree') + self.serializer = HTMLSerializer( + quote_attr_values='always', + omit_optional_tags=False, + + # Bleach has its own sanitizer, so don't use the html5lib one + sanitize=False, + + # Bleach sanitizer alphabetizes already, so don't use the html5lib one + alphabetical_attributes=False, + ) + + def clean(self, text): + """Cleans text and returns sanitized result as unicode + + :arg str text: text to be cleaned + + :returns: sanitized text as unicode + + """ + if not text: + return u'' + + text = force_unicode(text) + + dom = self.parser.parseFragment(text) + filtered = BleachSanitizerFilter( + source=self.walker(dom), + + # Bleach-sanitizer-specific things + attributes=self.attributes, + strip_disallowed_elements=self.strip, + strip_html_comments=self.strip_comments, + + # html5lib-sanitizer things + allowed_elements=self.tags, + allowed_css_properties=self.styles, + allowed_protocols=self.protocols, + allowed_svg_properties=[], + ) + + # Apply any filters after the BleachSanitizerFilter + for filter_class in self.filters: + filtered = filter_class(source=filtered) + + return self.serializer.render(filtered) + + +def attribute_filter_factory(attributes): + """Generates attribute filter function for the given attributes value + + The attributes value can take one of several shapes. This returns a filter + function appropriate to the attributes value. One nice thing about this is + that there's less if/then shenanigans in the ``allow_token`` method. + + """ + if callable(attributes): + return attributes + + if isinstance(attributes, dict): + def _attr_filter(tag, attr, value): + if tag in attributes: + attr_val = attributes[tag] + if callable(attr_val): + return attr_val(tag, attr, value) + + if attr in attr_val: + return True + + if '*' in attributes: + attr_val = attributes['*'] + if callable(attr_val): + return attr_val(tag, attr, value) + + return attr in attr_val + + return False + + return _attr_filter + + if isinstance(attributes, list): + def _attr_filter(tag, attr, value): + return attr in attributes + + return _attr_filter + + raise ValueError('attributes needs to be a callable, a list or a dict') + + +class BleachSanitizerFilter(sanitizer.Filter): + """html5lib Filter that sanitizes text + + This filter can be used anywhere html5lib filters can be used. + + """ + def __init__(self, source, attributes=ALLOWED_ATTRIBUTES, + strip_disallowed_elements=False, strip_html_comments=True, + **kwargs): + """Creates a BleachSanitizerFilter instance + + :arg Treewalker source: stream + + :arg list tags: allowed list of tags; defaults to + ``bleach.sanitizer.ALLOWED_TAGS`` + + :arg dict attributes: allowed attributes; can be a callable, list or dict; + defaults to ``bleach.sanitizer.ALLOWED_ATTRIBUTES`` + + :arg list styles: allowed list of css styles; defaults to + ``bleach.sanitizer.ALLOWED_STYLES`` + + :arg list protocols: allowed list of protocols for links; defaults + to ``bleach.sanitizer.ALLOWED_PROTOCOLS`` + + :arg bool strip_disallowed_elements: whether or not to strip disallowed + elements + + :arg bool strip_html_comments: whether or not to strip HTML comments + + """ + self.attr_filter = attribute_filter_factory(attributes) + + self.strip_disallowed_elements = strip_disallowed_elements + self.strip_html_comments = strip_html_comments + + return super(BleachSanitizerFilter, self).__init__(source, **kwargs) + + def sanitize_token(self, token): + """Sanitize a token either by HTML-encoding or dropping. + + Unlike sanitizer.Filter, allowed_attributes can be a dict of {'tag': + ['attribute', 'pairs'], 'tag': callable}. + + Here callable is a function with two arguments of attribute name and + value. It should return true of false. + + Also gives the option to strip tags instead of encoding. + + """ + token_type = token['type'] + if token_type in ['StartTag', 'EndTag', 'EmptyTag']: + if token['name'] in self.allowed_elements: + return self.allow_token(token) + + elif self.strip_disallowed_elements: + pass + + else: + if 'data' in token: + # Alphabetize the attributes before calling .disallowed_token() + # so that the resulting string is stable + token['data'] = alphabetize_attributes(token['data']) + return self.disallowed_token(token) + + elif token_type == 'Comment': + if not self.strip_html_comments: + return token + + else: + return token + + def allow_token(self, token): + """Handles the case where we're allowing the tag""" + if 'data' in token: + # Loop through all the attributes and drop the ones that are not + # allowed, are unsafe or break other rules. Additionally, fix + # attribute values that need fixing. + # + # At the end of this loop, we have the final set of attributes + # we're keeping. + attrs = {} + for namespaced_name, val in token['data'].items(): + namespace, name = namespaced_name + + # Drop attributes that are not explicitly allowed + # + # NOTE(willkg): We pass in the attribute name--not a namespaced + # name. + if not self.attr_filter(token['name'], name, val): + continue + + # Look at attributes that have uri values + if namespaced_name in self.attr_val_is_uri: + val_unescaped = re.sub( + "[`\000-\040\177-\240\s]+", + '', + unescape(val)).lower() + + # Remove replacement characters from unescaped characters. + val_unescaped = val_unescaped.replace("\ufffd", "") + + # Drop attributes with uri values that have protocols that + # aren't allowed + if (re.match(r'^[a-z0-9][-+.a-z0-9]*:', val_unescaped) and + (val_unescaped.split(':')[0] not in self.allowed_protocols)): + continue + + # Drop values in svg attrs with non-local IRIs + if namespaced_name in self.svg_attr_val_allows_ref: + new_val = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', + ' ', + unescape(val)) + new_val = new_val.strip() + if not new_val: + continue + + else: + # Replace the val with the unescaped version because + # it's a iri + val = new_val + + # Drop href and xlink:href attr for svg elements with non-local IRIs + if (None, token['name']) in self.svg_allow_local_href: + if namespaced_name in [(None, 'href'), (namespaces['xlink'], 'href')]: + if re.search(r'^\s*[^#\s]', val): + continue + + # If it's a style attribute, sanitize it + if namespaced_name == (None, u'style'): + val = self.sanitize_css(val) + + # At this point, we want to keep the attribute, so add it in + attrs[namespaced_name] = val + + token['data'] = alphabetize_attributes(attrs) + + return token + + def sanitize_css(self, style): + """Sanitizes css in style tags""" + # disallow urls + style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) + + # gauntlet + + # Validate the css in the style tag and if it's not valid, then drop + # the whole thing. + parts = style.split(';') + gauntlet = re.compile( + r"""^([-/:,#%.'"\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'\s*|"[\s\w]+"|\([\d,%\.\s]+\))*$""" + ) + + for part in parts: + if not gauntlet.match(part): + return '' + + if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): + return '' + + clean = [] + for prop, value in re.findall('([-\w]+)\s*:\s*([^:;]*)', style): + if not value: + continue + + if prop.lower() in self.allowed_css_properties: + clean.append(prop + ': ' + value + ';') + + elif prop.lower() in self.allowed_svg_properties: + clean.append(prop + ': ' + value + ';') + + return ' '.join(clean) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/utils.py b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d9c211fce945eaf9980064ba606c57f27746e120 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/utils.py @@ -0,0 +1,23 @@ +from collections import OrderedDict + + +def _attr_key(attr): + """Returns appropriate key for sorting attribute names + + Attribute names are a tuple of ``(namespace, name)`` where namespace can be + ``None`` or a string. These can't be compared in Python 3, so we conver the + ``None`` to an empty string. + + """ + key = (attr[0][0] or ''), attr[0][1] + return key + + +def alphabetize_attributes(attrs): + """Takes a dict of attributes (or None) and returns them alphabetized""" + if not attrs: + return attrs + + return OrderedDict( + [(k, v) for k, v in sorted(attrs.items(), key=_attr_key)] + ) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/version.py b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/version.py new file mode 100644 index 0000000000000000000000000000000000000000..bcd8affc49014a4da35bc36cd3c451dedad0c94d --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/bleach/version.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +VERSION = (2, 0, 0) +__version__ = '.'.join([str(n) for n in VERSION]) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__init__.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..320e0c3b43a1514ee7e96d46269e90660b90e9db --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__init__.py @@ -0,0 +1,35 @@ +""" +HTML parsing library based on the `WHATWG HTML specification +`_. The parser is designed to be compatible with +existing HTML found in the wild and implements well-defined error recovery that +is largely compatible with modern desktop web browsers. + +Example usage:: + + import html5lib + with open("my_document.html", "rb") as f: + tree = html5lib.parse(f) + +For convenience, this module re-exports the following names: + +* :func:`~.html5parser.parse` +* :func:`~.html5parser.parseFragment` +* :class:`~.html5parser.HTMLParser` +* :func:`~.treebuilders.getTreeBuilder` +* :func:`~.treewalkers.getTreeWalker` +* :func:`~.serializer.serialize` +""" + +from __future__ import absolute_import, division, unicode_literals + +from .html5parser import HTMLParser, parse, parseFragment +from .treebuilders import getTreeBuilder +from .treewalkers import getTreeWalker +from .serializer import serialize + +__all__ = ["HTMLParser", "parse", "parseFragment", "getTreeBuilder", + "getTreeWalker", "serialize"] + +# this has to be at the top level, see how setup.py parses this +#: Distribution version number. +__version__ = "1.1" diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/__init__.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fcd4d4acab3d6719d5c1ce2331ab840362ac4aa Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/__init__.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_ihatexml.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_ihatexml.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de1513be78f8827f8cd42097744e02e2063fe8fd Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_ihatexml.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_inputstream.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_inputstream.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f4f69aecf8b06058f915be9218d65be795d7d61 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_inputstream.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_tokenizer.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_tokenizer.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a8fe1a27070366b6d7dec708b09cedbfc5ad747 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_tokenizer.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_utils.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc63abfeb2034b0df69de4a7339d85b30cc198a8 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/_utils.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/constants.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/constants.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb830e88316816767867ff69ee37b08785a4e1ba Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/constants.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/html5parser.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/html5parser.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf860d72277047452381af05e5c5cbfaab2f5fc5 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/html5parser.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/serializer.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/serializer.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd0a9fd2fd3726d3c4582a9ba264f2f8e268b5c8 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/__pycache__/serializer.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_ihatexml.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_ihatexml.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff803c195243984738c6f3f328c78d9c4999cfc --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_ihatexml.py @@ -0,0 +1,289 @@ +from __future__ import absolute_import, division, unicode_literals + +import re +import warnings + +from .constants import DataLossWarning + +baseChar = """ +[#x0041-#x005A] | [#x0061-#x007A] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | +[#x00F8-#x00FF] | [#x0100-#x0131] | [#x0134-#x013E] | [#x0141-#x0148] | +[#x014A-#x017E] | [#x0180-#x01C3] | [#x01CD-#x01F0] | [#x01F4-#x01F5] | +[#x01FA-#x0217] | [#x0250-#x02A8] | [#x02BB-#x02C1] | #x0386 | +[#x0388-#x038A] | #x038C | [#x038E-#x03A1] | [#x03A3-#x03CE] | +[#x03D0-#x03D6] | #x03DA | #x03DC | #x03DE | #x03E0 | [#x03E2-#x03F3] | +[#x0401-#x040C] | [#x040E-#x044F] | [#x0451-#x045C] | [#x045E-#x0481] | +[#x0490-#x04C4] | [#x04C7-#x04C8] | [#x04CB-#x04CC] | [#x04D0-#x04EB] | +[#x04EE-#x04F5] | [#x04F8-#x04F9] | [#x0531-#x0556] | #x0559 | +[#x0561-#x0586] | [#x05D0-#x05EA] | [#x05F0-#x05F2] | [#x0621-#x063A] | +[#x0641-#x064A] | [#x0671-#x06B7] | [#x06BA-#x06BE] | [#x06C0-#x06CE] | +[#x06D0-#x06D3] | #x06D5 | [#x06E5-#x06E6] | [#x0905-#x0939] | #x093D | +[#x0958-#x0961] | [#x0985-#x098C] | [#x098F-#x0990] | [#x0993-#x09A8] | +[#x09AA-#x09B0] | #x09B2 | [#x09B6-#x09B9] | [#x09DC-#x09DD] | +[#x09DF-#x09E1] | [#x09F0-#x09F1] | [#x0A05-#x0A0A] | [#x0A0F-#x0A10] | +[#x0A13-#x0A28] | [#x0A2A-#x0A30] | [#x0A32-#x0A33] | [#x0A35-#x0A36] | +[#x0A38-#x0A39] | [#x0A59-#x0A5C] | #x0A5E | [#x0A72-#x0A74] | +[#x0A85-#x0A8B] | #x0A8D | [#x0A8F-#x0A91] | [#x0A93-#x0AA8] | +[#x0AAA-#x0AB0] | [#x0AB2-#x0AB3] | [#x0AB5-#x0AB9] | #x0ABD | #x0AE0 | +[#x0B05-#x0B0C] | [#x0B0F-#x0B10] | [#x0B13-#x0B28] | [#x0B2A-#x0B30] | +[#x0B32-#x0B33] | [#x0B36-#x0B39] | #x0B3D | [#x0B5C-#x0B5D] | +[#x0B5F-#x0B61] | [#x0B85-#x0B8A] | [#x0B8E-#x0B90] | [#x0B92-#x0B95] | +[#x0B99-#x0B9A] | #x0B9C | [#x0B9E-#x0B9F] | [#x0BA3-#x0BA4] | +[#x0BA8-#x0BAA] | [#x0BAE-#x0BB5] | [#x0BB7-#x0BB9] | [#x0C05-#x0C0C] | +[#x0C0E-#x0C10] | [#x0C12-#x0C28] | [#x0C2A-#x0C33] | [#x0C35-#x0C39] | +[#x0C60-#x0C61] | [#x0C85-#x0C8C] | [#x0C8E-#x0C90] | [#x0C92-#x0CA8] | +[#x0CAA-#x0CB3] | [#x0CB5-#x0CB9] | #x0CDE | [#x0CE0-#x0CE1] | +[#x0D05-#x0D0C] | [#x0D0E-#x0D10] | [#x0D12-#x0D28] | [#x0D2A-#x0D39] | +[#x0D60-#x0D61] | [#x0E01-#x0E2E] | #x0E30 | [#x0E32-#x0E33] | +[#x0E40-#x0E45] | [#x0E81-#x0E82] | #x0E84 | [#x0E87-#x0E88] | #x0E8A | +#x0E8D | [#x0E94-#x0E97] | [#x0E99-#x0E9F] | [#x0EA1-#x0EA3] | #x0EA5 | +#x0EA7 | [#x0EAA-#x0EAB] | [#x0EAD-#x0EAE] | #x0EB0 | [#x0EB2-#x0EB3] | +#x0EBD | [#x0EC0-#x0EC4] | [#x0F40-#x0F47] | [#x0F49-#x0F69] | +[#x10A0-#x10C5] | [#x10D0-#x10F6] | #x1100 | [#x1102-#x1103] | +[#x1105-#x1107] | #x1109 | [#x110B-#x110C] | [#x110E-#x1112] | #x113C | +#x113E | #x1140 | #x114C | #x114E | #x1150 | [#x1154-#x1155] | #x1159 | +[#x115F-#x1161] | #x1163 | #x1165 | #x1167 | #x1169 | [#x116D-#x116E] | +[#x1172-#x1173] | #x1175 | #x119E | #x11A8 | #x11AB | [#x11AE-#x11AF] | +[#x11B7-#x11B8] | #x11BA | [#x11BC-#x11C2] | #x11EB | #x11F0 | #x11F9 | +[#x1E00-#x1E9B] | [#x1EA0-#x1EF9] | [#x1F00-#x1F15] | [#x1F18-#x1F1D] | +[#x1F20-#x1F45] | [#x1F48-#x1F4D] | [#x1F50-#x1F57] | #x1F59 | #x1F5B | +#x1F5D | [#x1F5F-#x1F7D] | [#x1F80-#x1FB4] | [#x1FB6-#x1FBC] | #x1FBE | +[#x1FC2-#x1FC4] | [#x1FC6-#x1FCC] | [#x1FD0-#x1FD3] | [#x1FD6-#x1FDB] | +[#x1FE0-#x1FEC] | [#x1FF2-#x1FF4] | [#x1FF6-#x1FFC] | #x2126 | +[#x212A-#x212B] | #x212E | [#x2180-#x2182] | [#x3041-#x3094] | +[#x30A1-#x30FA] | [#x3105-#x312C] | [#xAC00-#xD7A3]""" + +ideographic = """[#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029]""" + +combiningCharacter = """ +[#x0300-#x0345] | [#x0360-#x0361] | [#x0483-#x0486] | [#x0591-#x05A1] | +[#x05A3-#x05B9] | [#x05BB-#x05BD] | #x05BF | [#x05C1-#x05C2] | #x05C4 | +[#x064B-#x0652] | #x0670 | [#x06D6-#x06DC] | [#x06DD-#x06DF] | +[#x06E0-#x06E4] | [#x06E7-#x06E8] | [#x06EA-#x06ED] | [#x0901-#x0903] | +#x093C | [#x093E-#x094C] | #x094D | [#x0951-#x0954] | [#x0962-#x0963] | +[#x0981-#x0983] | #x09BC | #x09BE | #x09BF | [#x09C0-#x09C4] | +[#x09C7-#x09C8] | [#x09CB-#x09CD] | #x09D7 | [#x09E2-#x09E3] | #x0A02 | +#x0A3C | #x0A3E | #x0A3F | [#x0A40-#x0A42] | [#x0A47-#x0A48] | +[#x0A4B-#x0A4D] | [#x0A70-#x0A71] | [#x0A81-#x0A83] | #x0ABC | +[#x0ABE-#x0AC5] | [#x0AC7-#x0AC9] | [#x0ACB-#x0ACD] | [#x0B01-#x0B03] | +#x0B3C | [#x0B3E-#x0B43] | [#x0B47-#x0B48] | [#x0B4B-#x0B4D] | +[#x0B56-#x0B57] | [#x0B82-#x0B83] | [#x0BBE-#x0BC2] | [#x0BC6-#x0BC8] | +[#x0BCA-#x0BCD] | #x0BD7 | [#x0C01-#x0C03] | [#x0C3E-#x0C44] | +[#x0C46-#x0C48] | [#x0C4A-#x0C4D] | [#x0C55-#x0C56] | [#x0C82-#x0C83] | +[#x0CBE-#x0CC4] | [#x0CC6-#x0CC8] | [#x0CCA-#x0CCD] | [#x0CD5-#x0CD6] | +[#x0D02-#x0D03] | [#x0D3E-#x0D43] | [#x0D46-#x0D48] | [#x0D4A-#x0D4D] | +#x0D57 | #x0E31 | [#x0E34-#x0E3A] | [#x0E47-#x0E4E] | #x0EB1 | +[#x0EB4-#x0EB9] | [#x0EBB-#x0EBC] | [#x0EC8-#x0ECD] | [#x0F18-#x0F19] | +#x0F35 | #x0F37 | #x0F39 | #x0F3E | #x0F3F | [#x0F71-#x0F84] | +[#x0F86-#x0F8B] | [#x0F90-#x0F95] | #x0F97 | [#x0F99-#x0FAD] | +[#x0FB1-#x0FB7] | #x0FB9 | [#x20D0-#x20DC] | #x20E1 | [#x302A-#x302F] | +#x3099 | #x309A""" + +digit = """ +[#x0030-#x0039] | [#x0660-#x0669] | [#x06F0-#x06F9] | [#x0966-#x096F] | +[#x09E6-#x09EF] | [#x0A66-#x0A6F] | [#x0AE6-#x0AEF] | [#x0B66-#x0B6F] | +[#x0BE7-#x0BEF] | [#x0C66-#x0C6F] | [#x0CE6-#x0CEF] | [#x0D66-#x0D6F] | +[#x0E50-#x0E59] | [#x0ED0-#x0ED9] | [#x0F20-#x0F29]""" + +extender = """ +#x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | #x0E46 | #x0EC6 | #x3005 | +#[#x3031-#x3035] | [#x309D-#x309E] | [#x30FC-#x30FE]""" + +letter = " | ".join([baseChar, ideographic]) + +# Without the +name = " | ".join([letter, digit, ".", "-", "_", combiningCharacter, + extender]) +nameFirst = " | ".join([letter, "_"]) + +reChar = re.compile(r"#x([\d|A-F]{4,4})") +reCharRange = re.compile(r"\[#x([\d|A-F]{4,4})-#x([\d|A-F]{4,4})\]") + + +def charStringToList(chars): + charRanges = [item.strip() for item in chars.split(" | ")] + rv = [] + for item in charRanges: + foundMatch = False + for regexp in (reChar, reCharRange): + match = regexp.match(item) + if match is not None: + rv.append([hexToInt(item) for item in match.groups()]) + if len(rv[-1]) == 1: + rv[-1] = rv[-1] * 2 + foundMatch = True + break + if not foundMatch: + assert len(item) == 1 + + rv.append([ord(item)] * 2) + rv = normaliseCharList(rv) + return rv + + +def normaliseCharList(charList): + charList = sorted(charList) + for item in charList: + assert item[1] >= item[0] + rv = [] + i = 0 + while i < len(charList): + j = 1 + rv.append(charList[i]) + while i + j < len(charList) and charList[i + j][0] <= rv[-1][1] + 1: + rv[-1][1] = charList[i + j][1] + j += 1 + i += j + return rv + + +# We don't really support characters above the BMP :( +max_unicode = int("FFFF", 16) + + +def missingRanges(charList): + rv = [] + if charList[0] != 0: + rv.append([0, charList[0][0] - 1]) + for i, item in enumerate(charList[:-1]): + rv.append([item[1] + 1, charList[i + 1][0] - 1]) + if charList[-1][1] != max_unicode: + rv.append([charList[-1][1] + 1, max_unicode]) + return rv + + +def listToRegexpStr(charList): + rv = [] + for item in charList: + if item[0] == item[1]: + rv.append(escapeRegexp(chr(item[0]))) + else: + rv.append(escapeRegexp(chr(item[0])) + "-" + + escapeRegexp(chr(item[1]))) + return "[%s]" % "".join(rv) + + +def hexToInt(hex_str): + return int(hex_str, 16) + + +def escapeRegexp(string): + specialCharacters = (".", "^", "$", "*", "+", "?", "{", "}", + "[", "]", "|", "(", ")", "-") + for char in specialCharacters: + string = string.replace(char, "\\" + char) + + return string + +# output from the above +nonXmlNameBMPRegexp = re.compile('[\x00-,/:-@\\[-\\^`\\{-\xb6\xb8-\xbf\xd7\xf7\u0132-\u0133\u013f-\u0140\u0149\u017f\u01c4-\u01cc\u01f1-\u01f3\u01f6-\u01f9\u0218-\u024f\u02a9-\u02ba\u02c2-\u02cf\u02d2-\u02ff\u0346-\u035f\u0362-\u0385\u038b\u038d\u03a2\u03cf\u03d7-\u03d9\u03db\u03dd\u03df\u03e1\u03f4-\u0400\u040d\u0450\u045d\u0482\u0487-\u048f\u04c5-\u04c6\u04c9-\u04ca\u04cd-\u04cf\u04ec-\u04ed\u04f6-\u04f7\u04fa-\u0530\u0557-\u0558\u055a-\u0560\u0587-\u0590\u05a2\u05ba\u05be\u05c0\u05c3\u05c5-\u05cf\u05eb-\u05ef\u05f3-\u0620\u063b-\u063f\u0653-\u065f\u066a-\u066f\u06b8-\u06b9\u06bf\u06cf\u06d4\u06e9\u06ee-\u06ef\u06fa-\u0900\u0904\u093a-\u093b\u094e-\u0950\u0955-\u0957\u0964-\u0965\u0970-\u0980\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09bb\u09bd\u09c5-\u09c6\u09c9-\u09ca\u09ce-\u09d6\u09d8-\u09db\u09de\u09e4-\u09e5\u09f2-\u0a01\u0a03-\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a3b\u0a3d\u0a43-\u0a46\u0a49-\u0a4a\u0a4e-\u0a58\u0a5d\u0a5f-\u0a65\u0a75-\u0a80\u0a84\u0a8c\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abb\u0ac6\u0aca\u0ace-\u0adf\u0ae1-\u0ae5\u0af0-\u0b00\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34-\u0b35\u0b3a-\u0b3b\u0b44-\u0b46\u0b49-\u0b4a\u0b4e-\u0b55\u0b58-\u0b5b\u0b5e\u0b62-\u0b65\u0b70-\u0b81\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bb6\u0bba-\u0bbd\u0bc3-\u0bc5\u0bc9\u0bce-\u0bd6\u0bd8-\u0be6\u0bf0-\u0c00\u0c04\u0c0d\u0c11\u0c29\u0c34\u0c3a-\u0c3d\u0c45\u0c49\u0c4e-\u0c54\u0c57-\u0c5f\u0c62-\u0c65\u0c70-\u0c81\u0c84\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cbd\u0cc5\u0cc9\u0cce-\u0cd4\u0cd7-\u0cdd\u0cdf\u0ce2-\u0ce5\u0cf0-\u0d01\u0d04\u0d0d\u0d11\u0d29\u0d3a-\u0d3d\u0d44-\u0d45\u0d49\u0d4e-\u0d56\u0d58-\u0d5f\u0d62-\u0d65\u0d70-\u0e00\u0e2f\u0e3b-\u0e3f\u0e4f\u0e5a-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eaf\u0eba\u0ebe-\u0ebf\u0ec5\u0ec7\u0ece-\u0ecf\u0eda-\u0f17\u0f1a-\u0f1f\u0f2a-\u0f34\u0f36\u0f38\u0f3a-\u0f3d\u0f48\u0f6a-\u0f70\u0f85\u0f8c-\u0f8f\u0f96\u0f98\u0fae-\u0fb0\u0fb8\u0fba-\u109f\u10c6-\u10cf\u10f7-\u10ff\u1101\u1104\u1108\u110a\u110d\u1113-\u113b\u113d\u113f\u1141-\u114b\u114d\u114f\u1151-\u1153\u1156-\u1158\u115a-\u115e\u1162\u1164\u1166\u1168\u116a-\u116c\u116f-\u1171\u1174\u1176-\u119d\u119f-\u11a7\u11a9-\u11aa\u11ac-\u11ad\u11b0-\u11b6\u11b9\u11bb\u11c3-\u11ea\u11ec-\u11ef\u11f1-\u11f8\u11fa-\u1dff\u1e9c-\u1e9f\u1efa-\u1eff\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fbd\u1fbf-\u1fc1\u1fc5\u1fcd-\u1fcf\u1fd4-\u1fd5\u1fdc-\u1fdf\u1fed-\u1ff1\u1ff5\u1ffd-\u20cf\u20dd-\u20e0\u20e2-\u2125\u2127-\u2129\u212c-\u212d\u212f-\u217f\u2183-\u3004\u3006\u3008-\u3020\u3030\u3036-\u3040\u3095-\u3098\u309b-\u309c\u309f-\u30a0\u30fb\u30ff-\u3104\u312d-\u4dff\u9fa6-\uabff\ud7a4-\uffff]') # noqa + +nonXmlNameFirstBMPRegexp = re.compile('[\x00-@\\[-\\^`\\{-\xbf\xd7\xf7\u0132-\u0133\u013f-\u0140\u0149\u017f\u01c4-\u01cc\u01f1-\u01f3\u01f6-\u01f9\u0218-\u024f\u02a9-\u02ba\u02c2-\u0385\u0387\u038b\u038d\u03a2\u03cf\u03d7-\u03d9\u03db\u03dd\u03df\u03e1\u03f4-\u0400\u040d\u0450\u045d\u0482-\u048f\u04c5-\u04c6\u04c9-\u04ca\u04cd-\u04cf\u04ec-\u04ed\u04f6-\u04f7\u04fa-\u0530\u0557-\u0558\u055a-\u0560\u0587-\u05cf\u05eb-\u05ef\u05f3-\u0620\u063b-\u0640\u064b-\u0670\u06b8-\u06b9\u06bf\u06cf\u06d4\u06d6-\u06e4\u06e7-\u0904\u093a-\u093c\u093e-\u0957\u0962-\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09db\u09de\u09e2-\u09ef\u09f2-\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a58\u0a5d\u0a5f-\u0a71\u0a75-\u0a84\u0a8c\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abc\u0abe-\u0adf\u0ae1-\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34-\u0b35\u0b3a-\u0b3c\u0b3e-\u0b5b\u0b5e\u0b62-\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bb6\u0bba-\u0c04\u0c0d\u0c11\u0c29\u0c34\u0c3a-\u0c5f\u0c62-\u0c84\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cdd\u0cdf\u0ce2-\u0d04\u0d0d\u0d11\u0d29\u0d3a-\u0d5f\u0d62-\u0e00\u0e2f\u0e31\u0e34-\u0e3f\u0e46-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eaf\u0eb1\u0eb4-\u0ebc\u0ebe-\u0ebf\u0ec5-\u0f3f\u0f48\u0f6a-\u109f\u10c6-\u10cf\u10f7-\u10ff\u1101\u1104\u1108\u110a\u110d\u1113-\u113b\u113d\u113f\u1141-\u114b\u114d\u114f\u1151-\u1153\u1156-\u1158\u115a-\u115e\u1162\u1164\u1166\u1168\u116a-\u116c\u116f-\u1171\u1174\u1176-\u119d\u119f-\u11a7\u11a9-\u11aa\u11ac-\u11ad\u11b0-\u11b6\u11b9\u11bb\u11c3-\u11ea\u11ec-\u11ef\u11f1-\u11f8\u11fa-\u1dff\u1e9c-\u1e9f\u1efa-\u1eff\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fbd\u1fbf-\u1fc1\u1fc5\u1fcd-\u1fcf\u1fd4-\u1fd5\u1fdc-\u1fdf\u1fed-\u1ff1\u1ff5\u1ffd-\u2125\u2127-\u2129\u212c-\u212d\u212f-\u217f\u2183-\u3006\u3008-\u3020\u302a-\u3040\u3095-\u30a0\u30fb-\u3104\u312d-\u4dff\u9fa6-\uabff\ud7a4-\uffff]') # noqa + +# Simpler things +nonPubidCharRegexp = re.compile("[^\x20\x0D\x0Aa-zA-Z0-9\\-'()+,./:=?;!*#@$_%]") + + +class InfosetFilter(object): + replacementRegexp = re.compile(r"U[\dA-F]{5,5}") + + def __init__(self, + dropXmlnsLocalName=False, + dropXmlnsAttrNs=False, + preventDoubleDashComments=False, + preventDashAtCommentEnd=False, + replaceFormFeedCharacters=True, + preventSingleQuotePubid=False): + + self.dropXmlnsLocalName = dropXmlnsLocalName + self.dropXmlnsAttrNs = dropXmlnsAttrNs + + self.preventDoubleDashComments = preventDoubleDashComments + self.preventDashAtCommentEnd = preventDashAtCommentEnd + + self.replaceFormFeedCharacters = replaceFormFeedCharacters + + self.preventSingleQuotePubid = preventSingleQuotePubid + + self.replaceCache = {} + + def coerceAttribute(self, name, namespace=None): + if self.dropXmlnsLocalName and name.startswith("xmlns:"): + warnings.warn("Attributes cannot begin with xmlns", DataLossWarning) + return None + elif (self.dropXmlnsAttrNs and + namespace == "http://www.w3.org/2000/xmlns/"): + warnings.warn("Attributes cannot be in the xml namespace", DataLossWarning) + return None + else: + return self.toXmlName(name) + + def coerceElement(self, name): + return self.toXmlName(name) + + def coerceComment(self, data): + if self.preventDoubleDashComments: + while "--" in data: + warnings.warn("Comments cannot contain adjacent dashes", DataLossWarning) + data = data.replace("--", "- -") + if data.endswith("-"): + warnings.warn("Comments cannot end in a dash", DataLossWarning) + data += " " + return data + + def coerceCharacters(self, data): + if self.replaceFormFeedCharacters: + for _ in range(data.count("\x0C")): + warnings.warn("Text cannot contain U+000C", DataLossWarning) + data = data.replace("\x0C", " ") + # Other non-xml characters + return data + + def coercePubid(self, data): + dataOutput = data + for char in nonPubidCharRegexp.findall(data): + warnings.warn("Coercing non-XML pubid", DataLossWarning) + replacement = self.getReplacementCharacter(char) + dataOutput = dataOutput.replace(char, replacement) + if self.preventSingleQuotePubid and dataOutput.find("'") >= 0: + warnings.warn("Pubid cannot contain single quote", DataLossWarning) + dataOutput = dataOutput.replace("'", self.getReplacementCharacter("'")) + return dataOutput + + def toXmlName(self, name): + nameFirst = name[0] + nameRest = name[1:] + m = nonXmlNameFirstBMPRegexp.match(nameFirst) + if m: + warnings.warn("Coercing non-XML name: %s" % name, DataLossWarning) + nameFirstOutput = self.getReplacementCharacter(nameFirst) + else: + nameFirstOutput = nameFirst + + nameRestOutput = nameRest + replaceChars = set(nonXmlNameBMPRegexp.findall(nameRest)) + for char in replaceChars: + warnings.warn("Coercing non-XML name: %s" % name, DataLossWarning) + replacement = self.getReplacementCharacter(char) + nameRestOutput = nameRestOutput.replace(char, replacement) + return nameFirstOutput + nameRestOutput + + def getReplacementCharacter(self, char): + if char in self.replaceCache: + replacement = self.replaceCache[char] + else: + replacement = self.escapeChar(char) + return replacement + + def fromXmlName(self, name): + for item in set(self.replacementRegexp.findall(name)): + name = name.replace(item, self.unescapeChar(item)) + return name + + def escapeChar(self, char): + replacement = "U%05X" % ord(char) + self.replaceCache[char] = replacement + return replacement + + def unescapeChar(self, charcode): + return chr(int(charcode[1:], 16)) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_inputstream.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_inputstream.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc987ac2d90d8f9a4bdc97fac3f233b4b8fa3f7 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_inputstream.py @@ -0,0 +1,918 @@ +from __future__ import absolute_import, division, unicode_literals + +from six import text_type +from six.moves import http_client, urllib + +import codecs +import re +from io import BytesIO, StringIO + +from tensorboard._vendor import webencodings + +from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase +from .constants import _ReparseException +from . import _utils + +# Non-unicode versions of constants for use in the pre-parser +spaceCharactersBytes = frozenset([item.encode("ascii") for item in spaceCharacters]) +asciiLettersBytes = frozenset([item.encode("ascii") for item in asciiLetters]) +asciiUppercaseBytes = frozenset([item.encode("ascii") for item in asciiUppercase]) +spacesAngleBrackets = spaceCharactersBytes | frozenset([b">", b"<"]) + + +invalid_unicode_no_surrogate = "[\u0001-\u0008\u000B\u000E-\u001F\u007F-\u009F\uFDD0-\uFDEF\uFFFE\uFFFF\U0001FFFE\U0001FFFF\U0002FFFE\U0002FFFF\U0003FFFE\U0003FFFF\U0004FFFE\U0004FFFF\U0005FFFE\U0005FFFF\U0006FFFE\U0006FFFF\U0007FFFE\U0007FFFF\U0008FFFE\U0008FFFF\U0009FFFE\U0009FFFF\U000AFFFE\U000AFFFF\U000BFFFE\U000BFFFF\U000CFFFE\U000CFFFF\U000DFFFE\U000DFFFF\U000EFFFE\U000EFFFF\U000FFFFE\U000FFFFF\U0010FFFE\U0010FFFF]" # noqa + +if _utils.supports_lone_surrogates: + # Use one extra step of indirection and create surrogates with + # eval. Not using this indirection would introduce an illegal + # unicode literal on platforms not supporting such lone + # surrogates. + assert invalid_unicode_no_surrogate[-1] == "]" and invalid_unicode_no_surrogate.count("]") == 1 + invalid_unicode_re = re.compile(invalid_unicode_no_surrogate[:-1] + + eval('"\\uD800-\\uDFFF"') + # pylint:disable=eval-used + "]") +else: + invalid_unicode_re = re.compile(invalid_unicode_no_surrogate) + +non_bmp_invalid_codepoints = {0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, + 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, + 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, + 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, + 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, + 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, + 0x10FFFE, 0x10FFFF} + +ascii_punctuation_re = re.compile("[\u0009-\u000D\u0020-\u002F\u003A-\u0040\u005C\u005B-\u0060\u007B-\u007E]") + +# Cache for charsUntil() +charsUntilRegEx = {} + + +class BufferedStream(object): + """Buffering for streams that do not have buffering of their own + + The buffer is implemented as a list of chunks on the assumption that + joining many strings will be slow since it is O(n**2) + """ + + def __init__(self, stream): + self.stream = stream + self.buffer = [] + self.position = [-1, 0] # chunk number, offset + + def tell(self): + pos = 0 + for chunk in self.buffer[:self.position[0]]: + pos += len(chunk) + pos += self.position[1] + return pos + + def seek(self, pos): + assert pos <= self._bufferedBytes() + offset = pos + i = 0 + while len(self.buffer[i]) < offset: + offset -= len(self.buffer[i]) + i += 1 + self.position = [i, offset] + + def read(self, bytes): + if not self.buffer: + return self._readStream(bytes) + elif (self.position[0] == len(self.buffer) and + self.position[1] == len(self.buffer[-1])): + return self._readStream(bytes) + else: + return self._readFromBuffer(bytes) + + def _bufferedBytes(self): + return sum([len(item) for item in self.buffer]) + + def _readStream(self, bytes): + data = self.stream.read(bytes) + self.buffer.append(data) + self.position[0] += 1 + self.position[1] = len(data) + return data + + def _readFromBuffer(self, bytes): + remainingBytes = bytes + rv = [] + bufferIndex = self.position[0] + bufferOffset = self.position[1] + while bufferIndex < len(self.buffer) and remainingBytes != 0: + assert remainingBytes > 0 + bufferedData = self.buffer[bufferIndex] + + if remainingBytes <= len(bufferedData) - bufferOffset: + bytesToRead = remainingBytes + self.position = [bufferIndex, bufferOffset + bytesToRead] + else: + bytesToRead = len(bufferedData) - bufferOffset + self.position = [bufferIndex, len(bufferedData)] + bufferIndex += 1 + rv.append(bufferedData[bufferOffset:bufferOffset + bytesToRead]) + remainingBytes -= bytesToRead + + bufferOffset = 0 + + if remainingBytes: + rv.append(self._readStream(remainingBytes)) + + return b"".join(rv) + + +def HTMLInputStream(source, **kwargs): + # Work around Python bug #20007: read(0) closes the connection. + # http://bugs.python.org/issue20007 + if (isinstance(source, http_client.HTTPResponse) or + # Also check for addinfourl wrapping HTTPResponse + (isinstance(source, urllib.response.addbase) and + isinstance(source.fp, http_client.HTTPResponse))): + isUnicode = False + elif hasattr(source, "read"): + isUnicode = isinstance(source.read(0), text_type) + else: + isUnicode = isinstance(source, text_type) + + if isUnicode: + encodings = [x for x in kwargs if x.endswith("_encoding")] + if encodings: + raise TypeError("Cannot set an encoding with a unicode input, set %r" % encodings) + + return HTMLUnicodeInputStream(source, **kwargs) + else: + return HTMLBinaryInputStream(source, **kwargs) + + +class HTMLUnicodeInputStream(object): + """Provides a unicode stream of characters to the HTMLTokenizer. + + This class takes care of character encoding and removing or replacing + incorrect byte-sequences and also provides column and line tracking. + + """ + + _defaultChunkSize = 10240 + + def __init__(self, source): + """Initialises the HTMLInputStream. + + HTMLInputStream(source, [encoding]) -> Normalized stream from source + for use by html5lib. + + source can be either a file-object, local filename or a string. + + The optional encoding parameter must be a string that indicates + the encoding. If specified, that encoding will be used, + regardless of any BOM or later declaration (such as in a meta + element) + + """ + + if not _utils.supports_lone_surrogates: + # Such platforms will have already checked for such + # surrogate errors, so no need to do this checking. + self.reportCharacterErrors = None + elif len("\U0010FFFF") == 1: + self.reportCharacterErrors = self.characterErrorsUCS4 + else: + self.reportCharacterErrors = self.characterErrorsUCS2 + + # List of where new lines occur + self.newLines = [0] + + self.charEncoding = (lookupEncoding("utf-8"), "certain") + self.dataStream = self.openStream(source) + + self.reset() + + def reset(self): + self.chunk = "" + self.chunkSize = 0 + self.chunkOffset = 0 + self.errors = [] + + # number of (complete) lines in previous chunks + self.prevNumLines = 0 + # number of columns in the last line of the previous chunk + self.prevNumCols = 0 + + # Deal with CR LF and surrogates split over chunk boundaries + self._bufferedCharacter = None + + def openStream(self, source): + """Produces a file object from source. + + source can be either a file object, local filename or a string. + + """ + # Already a file object + if hasattr(source, 'read'): + stream = source + else: + stream = StringIO(source) + + return stream + + def _position(self, offset): + chunk = self.chunk + nLines = chunk.count('\n', 0, offset) + positionLine = self.prevNumLines + nLines + lastLinePos = chunk.rfind('\n', 0, offset) + if lastLinePos == -1: + positionColumn = self.prevNumCols + offset + else: + positionColumn = offset - (lastLinePos + 1) + return (positionLine, positionColumn) + + def position(self): + """Returns (line, col) of the current position in the stream.""" + line, col = self._position(self.chunkOffset) + return (line + 1, col) + + def char(self): + """ Read one character from the stream or queue if available. Return + EOF when EOF is reached. + """ + # Read a new chunk from the input stream if necessary + if self.chunkOffset >= self.chunkSize: + if not self.readChunk(): + return EOF + + chunkOffset = self.chunkOffset + char = self.chunk[chunkOffset] + self.chunkOffset = chunkOffset + 1 + + return char + + def readChunk(self, chunkSize=None): + if chunkSize is None: + chunkSize = self._defaultChunkSize + + self.prevNumLines, self.prevNumCols = self._position(self.chunkSize) + + self.chunk = "" + self.chunkSize = 0 + self.chunkOffset = 0 + + data = self.dataStream.read(chunkSize) + + # Deal with CR LF and surrogates broken across chunks + if self._bufferedCharacter: + data = self._bufferedCharacter + data + self._bufferedCharacter = None + elif not data: + # We have no more data, bye-bye stream + return False + + if len(data) > 1: + lastv = ord(data[-1]) + if lastv == 0x0D or 0xD800 <= lastv <= 0xDBFF: + self._bufferedCharacter = data[-1] + data = data[:-1] + + if self.reportCharacterErrors: + self.reportCharacterErrors(data) + + # Replace invalid characters + data = data.replace("\r\n", "\n") + data = data.replace("\r", "\n") + + self.chunk = data + self.chunkSize = len(data) + + return True + + def characterErrorsUCS4(self, data): + for _ in range(len(invalid_unicode_re.findall(data))): + self.errors.append("invalid-codepoint") + + def characterErrorsUCS2(self, data): + # Someone picked the wrong compile option + # You lose + skip = False + for match in invalid_unicode_re.finditer(data): + if skip: + continue + codepoint = ord(match.group()) + pos = match.start() + # Pretty sure there should be endianness issues here + if _utils.isSurrogatePair(data[pos:pos + 2]): + # We have a surrogate pair! + char_val = _utils.surrogatePairToCodepoint(data[pos:pos + 2]) + if char_val in non_bmp_invalid_codepoints: + self.errors.append("invalid-codepoint") + skip = True + elif (codepoint >= 0xD800 and codepoint <= 0xDFFF and + pos == len(data) - 1): + self.errors.append("invalid-codepoint") + else: + skip = False + self.errors.append("invalid-codepoint") + + def charsUntil(self, characters, opposite=False): + """ Returns a string of characters from the stream up to but not + including any character in 'characters' or EOF. 'characters' must be + a container that supports the 'in' method and iteration over its + characters. + """ + + # Use a cache of regexps to find the required characters + try: + chars = charsUntilRegEx[(characters, opposite)] + except KeyError: + if __debug__: + for c in characters: + assert(ord(c) < 128) + regex = "".join(["\\x%02x" % ord(c) for c in characters]) + if not opposite: + regex = "^%s" % regex + chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex) + + rv = [] + + while True: + # Find the longest matching prefix + m = chars.match(self.chunk, self.chunkOffset) + if m is None: + # If nothing matched, and it wasn't because we ran out of chunk, + # then stop + if self.chunkOffset != self.chunkSize: + break + else: + end = m.end() + # If not the whole chunk matched, return everything + # up to the part that didn't match + if end != self.chunkSize: + rv.append(self.chunk[self.chunkOffset:end]) + self.chunkOffset = end + break + # If the whole remainder of the chunk matched, + # use it all and read the next chunk + rv.append(self.chunk[self.chunkOffset:]) + if not self.readChunk(): + # Reached EOF + break + + r = "".join(rv) + return r + + def unget(self, char): + # Only one character is allowed to be ungotten at once - it must + # be consumed again before any further call to unget + if char is not EOF: + if self.chunkOffset == 0: + # unget is called quite rarely, so it's a good idea to do + # more work here if it saves a bit of work in the frequently + # called char and charsUntil. + # So, just prepend the ungotten character onto the current + # chunk: + self.chunk = char + self.chunk + self.chunkSize += 1 + else: + self.chunkOffset -= 1 + assert self.chunk[self.chunkOffset] == char + + +class HTMLBinaryInputStream(HTMLUnicodeInputStream): + """Provides a unicode stream of characters to the HTMLTokenizer. + + This class takes care of character encoding and removing or replacing + incorrect byte-sequences and also provides column and line tracking. + + """ + + def __init__(self, source, override_encoding=None, transport_encoding=None, + same_origin_parent_encoding=None, likely_encoding=None, + default_encoding="windows-1252", useChardet=True): + """Initialises the HTMLInputStream. + + HTMLInputStream(source, [encoding]) -> Normalized stream from source + for use by html5lib. + + source can be either a file-object, local filename or a string. + + The optional encoding parameter must be a string that indicates + the encoding. If specified, that encoding will be used, + regardless of any BOM or later declaration (such as in a meta + element) + + """ + # Raw Stream - for unicode objects this will encode to utf-8 and set + # self.charEncoding as appropriate + self.rawStream = self.openStream(source) + + HTMLUnicodeInputStream.__init__(self, self.rawStream) + + # Encoding Information + # Number of bytes to use when looking for a meta element with + # encoding information + self.numBytesMeta = 1024 + # Number of bytes to use when using detecting encoding using chardet + self.numBytesChardet = 100 + # Things from args + self.override_encoding = override_encoding + self.transport_encoding = transport_encoding + self.same_origin_parent_encoding = same_origin_parent_encoding + self.likely_encoding = likely_encoding + self.default_encoding = default_encoding + + # Determine encoding + self.charEncoding = self.determineEncoding(useChardet) + assert self.charEncoding[0] is not None + + # Call superclass + self.reset() + + def reset(self): + self.dataStream = self.charEncoding[0].codec_info.streamreader(self.rawStream, 'replace') + HTMLUnicodeInputStream.reset(self) + + def openStream(self, source): + """Produces a file object from source. + + source can be either a file object, local filename or a string. + + """ + # Already a file object + if hasattr(source, 'read'): + stream = source + else: + stream = BytesIO(source) + + try: + stream.seek(stream.tell()) + except Exception: + stream = BufferedStream(stream) + + return stream + + def determineEncoding(self, chardet=True): + # BOMs take precedence over everything + # This will also read past the BOM if present + charEncoding = self.detectBOM(), "certain" + if charEncoding[0] is not None: + return charEncoding + + # If we've been overridden, we've been overridden + charEncoding = lookupEncoding(self.override_encoding), "certain" + if charEncoding[0] is not None: + return charEncoding + + # Now check the transport layer + charEncoding = lookupEncoding(self.transport_encoding), "certain" + if charEncoding[0] is not None: + return charEncoding + + # Look for meta elements with encoding information + charEncoding = self.detectEncodingMeta(), "tentative" + if charEncoding[0] is not None: + return charEncoding + + # Parent document encoding + charEncoding = lookupEncoding(self.same_origin_parent_encoding), "tentative" + if charEncoding[0] is not None and not charEncoding[0].name.startswith("utf-16"): + return charEncoding + + # "likely" encoding + charEncoding = lookupEncoding(self.likely_encoding), "tentative" + if charEncoding[0] is not None: + return charEncoding + + # Guess with chardet, if available + if chardet: + try: + from chardet.universaldetector import UniversalDetector + except ImportError: + pass + else: + buffers = [] + detector = UniversalDetector() + while not detector.done: + buffer = self.rawStream.read(self.numBytesChardet) + assert isinstance(buffer, bytes) + if not buffer: + break + buffers.append(buffer) + detector.feed(buffer) + detector.close() + encoding = lookupEncoding(detector.result['encoding']) + self.rawStream.seek(0) + if encoding is not None: + return encoding, "tentative" + + # Try the default encoding + charEncoding = lookupEncoding(self.default_encoding), "tentative" + if charEncoding[0] is not None: + return charEncoding + + # Fallback to html5lib's default if even that hasn't worked + return lookupEncoding("windows-1252"), "tentative" + + def changeEncoding(self, newEncoding): + assert self.charEncoding[1] != "certain" + newEncoding = lookupEncoding(newEncoding) + if newEncoding is None: + return + if newEncoding.name in ("utf-16be", "utf-16le"): + newEncoding = lookupEncoding("utf-8") + assert newEncoding is not None + elif newEncoding == self.charEncoding[0]: + self.charEncoding = (self.charEncoding[0], "certain") + else: + self.rawStream.seek(0) + self.charEncoding = (newEncoding, "certain") + self.reset() + raise _ReparseException("Encoding changed from %s to %s" % (self.charEncoding[0], newEncoding)) + + def detectBOM(self): + """Attempts to detect at BOM at the start of the stream. If + an encoding can be determined from the BOM return the name of the + encoding otherwise return None""" + bomDict = { + codecs.BOM_UTF8: 'utf-8', + codecs.BOM_UTF16_LE: 'utf-16le', codecs.BOM_UTF16_BE: 'utf-16be', + codecs.BOM_UTF32_LE: 'utf-32le', codecs.BOM_UTF32_BE: 'utf-32be' + } + + # Go to beginning of file and read in 4 bytes + string = self.rawStream.read(4) + assert isinstance(string, bytes) + + # Try detecting the BOM using bytes from the string + encoding = bomDict.get(string[:3]) # UTF-8 + seek = 3 + if not encoding: + # Need to detect UTF-32 before UTF-16 + encoding = bomDict.get(string) # UTF-32 + seek = 4 + if not encoding: + encoding = bomDict.get(string[:2]) # UTF-16 + seek = 2 + + # Set the read position past the BOM if one was found, otherwise + # set it to the start of the stream + if encoding: + self.rawStream.seek(seek) + return lookupEncoding(encoding) + else: + self.rawStream.seek(0) + return None + + def detectEncodingMeta(self): + """Report the encoding declared by the meta element + """ + buffer = self.rawStream.read(self.numBytesMeta) + assert isinstance(buffer, bytes) + parser = EncodingParser(buffer) + self.rawStream.seek(0) + encoding = parser.getEncoding() + + if encoding is not None and encoding.name in ("utf-16be", "utf-16le"): + encoding = lookupEncoding("utf-8") + + return encoding + + +class EncodingBytes(bytes): + """String-like object with an associated position and various extra methods + If the position is ever greater than the string length then an exception is + raised""" + def __new__(self, value): + assert isinstance(value, bytes) + return bytes.__new__(self, value.lower()) + + def __init__(self, value): + # pylint:disable=unused-argument + self._position = -1 + + def __iter__(self): + return self + + def __next__(self): + p = self._position = self._position + 1 + if p >= len(self): + raise StopIteration + elif p < 0: + raise TypeError + return self[p:p + 1] + + def next(self): + # Py2 compat + return self.__next__() + + def previous(self): + p = self._position + if p >= len(self): + raise StopIteration + elif p < 0: + raise TypeError + self._position = p = p - 1 + return self[p:p + 1] + + def setPosition(self, position): + if self._position >= len(self): + raise StopIteration + self._position = position + + def getPosition(self): + if self._position >= len(self): + raise StopIteration + if self._position >= 0: + return self._position + else: + return None + + position = property(getPosition, setPosition) + + def getCurrentByte(self): + return self[self.position:self.position + 1] + + currentByte = property(getCurrentByte) + + def skip(self, chars=spaceCharactersBytes): + """Skip past a list of characters""" + p = self.position # use property for the error-checking + while p < len(self): + c = self[p:p + 1] + if c not in chars: + self._position = p + return c + p += 1 + self._position = p + return None + + def skipUntil(self, chars): + p = self.position + while p < len(self): + c = self[p:p + 1] + if c in chars: + self._position = p + return c + p += 1 + self._position = p + return None + + def matchBytes(self, bytes): + """Look for a sequence of bytes at the start of a string. If the bytes + are found return True and advance the position to the byte after the + match. Otherwise return False and leave the position alone""" + rv = self.startswith(bytes, self.position) + if rv: + self.position += len(bytes) + return rv + + def jumpTo(self, bytes): + """Look for the next sequence of bytes matching a given sequence. If + a match is found advance the position to the last byte of the match""" + try: + self._position = self.index(bytes, self.position) + len(bytes) - 1 + except ValueError: + raise StopIteration + return True + + +class EncodingParser(object): + """Mini parser for detecting character encoding from meta elements""" + + def __init__(self, data): + """string - the data to work on for encoding detection""" + self.data = EncodingBytes(data) + self.encoding = None + + def getEncoding(self): + if b"") + + def handleMeta(self): + if self.data.currentByte not in spaceCharactersBytes: + # if we have ") + + def getAttribute(self): + """Return a name,value pair for the next attribute in the stream, + if one is found, or None""" + data = self.data + # Step 1 (skip chars) + c = data.skip(spaceCharactersBytes | frozenset([b"/"])) + assert c is None or len(c) == 1 + # Step 2 + if c in (b">", None): + return None + # Step 3 + attrName = [] + attrValue = [] + # Step 4 attribute name + while True: + if c == b"=" and attrName: + break + elif c in spaceCharactersBytes: + # Step 6! + c = data.skip() + break + elif c in (b"/", b">"): + return b"".join(attrName), b"" + elif c in asciiUppercaseBytes: + attrName.append(c.lower()) + elif c is None: + return None + else: + attrName.append(c) + # Step 5 + c = next(data) + # Step 7 + if c != b"=": + data.previous() + return b"".join(attrName), b"" + # Step 8 + next(data) + # Step 9 + c = data.skip() + # Step 10 + if c in (b"'", b'"'): + # 10.1 + quoteChar = c + while True: + # 10.2 + c = next(data) + # 10.3 + if c == quoteChar: + next(data) + return b"".join(attrName), b"".join(attrValue) + # 10.4 + elif c in asciiUppercaseBytes: + attrValue.append(c.lower()) + # 10.5 + else: + attrValue.append(c) + elif c == b">": + return b"".join(attrName), b"" + elif c in asciiUppercaseBytes: + attrValue.append(c.lower()) + elif c is None: + return None + else: + attrValue.append(c) + # Step 11 + while True: + c = next(data) + if c in spacesAngleBrackets: + return b"".join(attrName), b"".join(attrValue) + elif c in asciiUppercaseBytes: + attrValue.append(c.lower()) + elif c is None: + return None + else: + attrValue.append(c) + + +class ContentAttrParser(object): + def __init__(self, data): + assert isinstance(data, bytes) + self.data = data + + def parse(self): + try: + # Check if the attr name is charset + # otherwise return + self.data.jumpTo(b"charset") + self.data.position += 1 + self.data.skip() + if not self.data.currentByte == b"=": + # If there is no = sign keep looking for attrs + return None + self.data.position += 1 + self.data.skip() + # Look for an encoding between matching quote marks + if self.data.currentByte in (b'"', b"'"): + quoteMark = self.data.currentByte + self.data.position += 1 + oldPosition = self.data.position + if self.data.jumpTo(quoteMark): + return self.data[oldPosition:self.data.position] + else: + return None + else: + # Unquoted value + oldPosition = self.data.position + try: + self.data.skipUntil(spaceCharactersBytes) + return self.data[oldPosition:self.data.position] + except StopIteration: + # Return the whole remaining value + return self.data[oldPosition:] + except StopIteration: + return None + + +def lookupEncoding(encoding): + """Return the python codec name corresponding to an encoding or None if the + string doesn't correspond to a valid encoding.""" + if isinstance(encoding, bytes): + try: + encoding = encoding.decode("ascii") + except UnicodeDecodeError: + return None + + if encoding is not None: + try: + return webencodings.lookup(encoding) + except AttributeError: + return None + else: + return None diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_tokenizer.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..4748a19795e8e1bf0c6282e7ac81a17fb047f9ef --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_tokenizer.py @@ -0,0 +1,1735 @@ +from __future__ import absolute_import, division, unicode_literals + +from six import unichr as chr + +from collections import deque, OrderedDict +from sys import version_info + +from .constants import spaceCharacters +from .constants import entities +from .constants import asciiLetters, asciiUpper2Lower +from .constants import digits, hexDigits, EOF +from .constants import tokenTypes, tagTokenTypes +from .constants import replacementCharacters + +from ._inputstream import HTMLInputStream + +from ._trie import Trie + +entitiesTrie = Trie(entities) + +if version_info >= (3, 7): + attributeMap = dict +else: + attributeMap = OrderedDict + + +class HTMLTokenizer(object): + """ This class takes care of tokenizing HTML. + + * self.currentToken + Holds the token that is currently being processed. + + * self.state + Holds a reference to the method to be invoked... XXX + + * self.stream + Points to HTMLInputStream object. + """ + + def __init__(self, stream, parser=None, **kwargs): + + self.stream = HTMLInputStream(stream, **kwargs) + self.parser = parser + + # Setup the initial tokenizer state + self.escapeFlag = False + self.lastFourChars = [] + self.state = self.dataState + self.escape = False + + # The current token being created + self.currentToken = None + super(HTMLTokenizer, self).__init__() + + def __iter__(self): + """ This is where the magic happens. + + We do our usually processing through the states and when we have a token + to return we yield the token which pauses processing until the next token + is requested. + """ + self.tokenQueue = deque([]) + # Start processing. When EOF is reached self.state will return False + # instead of True and the loop will terminate. + while self.state(): + while self.stream.errors: + yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)} + while self.tokenQueue: + yield self.tokenQueue.popleft() + + def consumeNumberEntity(self, isHex): + """This function returns either U+FFFD or the character based on the + decimal or hexadecimal representation. It also discards ";" if present. + If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked. + """ + + allowed = digits + radix = 10 + if isHex: + allowed = hexDigits + radix = 16 + + charStack = [] + + # Consume all the characters that are in range while making sure we + # don't hit an EOF. + c = self.stream.char() + while c in allowed and c is not EOF: + charStack.append(c) + c = self.stream.char() + + # Convert the set of characters consumed to an int. + charAsInt = int("".join(charStack), radix) + + # Certain characters get replaced with others + if charAsInt in replacementCharacters: + char = replacementCharacters[charAsInt] + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "illegal-codepoint-for-numeric-entity", + "datavars": {"charAsInt": charAsInt}}) + elif ((0xD800 <= charAsInt <= 0xDFFF) or + (charAsInt > 0x10FFFF)): + char = "\uFFFD" + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "illegal-codepoint-for-numeric-entity", + "datavars": {"charAsInt": charAsInt}}) + else: + # Should speed up this check somehow (e.g. move the set to a constant) + if ((0x0001 <= charAsInt <= 0x0008) or + (0x000E <= charAsInt <= 0x001F) or + (0x007F <= charAsInt <= 0x009F) or + (0xFDD0 <= charAsInt <= 0xFDEF) or + charAsInt in frozenset([0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, + 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, + 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, + 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, + 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, + 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, + 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, + 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, + 0xFFFFF, 0x10FFFE, 0x10FFFF])): + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": + "illegal-codepoint-for-numeric-entity", + "datavars": {"charAsInt": charAsInt}}) + try: + # Try/except needed as UCS-2 Python builds' unichar only works + # within the BMP. + char = chr(charAsInt) + except ValueError: + v = charAsInt - 0x10000 + char = chr(0xD800 | (v >> 10)) + chr(0xDC00 | (v & 0x3FF)) + + # Discard the ; if present. Otherwise, put it back on the queue and + # invoke parseError on parser. + if c != ";": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "numeric-entity-without-semicolon"}) + self.stream.unget(c) + + return char + + def consumeEntity(self, allowedChar=None, fromAttribute=False): + # Initialise to the default output for when no entity is matched + output = "&" + + charStack = [self.stream.char()] + if (charStack[0] in spaceCharacters or charStack[0] in (EOF, "<", "&") or + (allowedChar is not None and allowedChar == charStack[0])): + self.stream.unget(charStack[0]) + + elif charStack[0] == "#": + # Read the next character to see if it's hex or decimal + hex = False + charStack.append(self.stream.char()) + if charStack[-1] in ("x", "X"): + hex = True + charStack.append(self.stream.char()) + + # charStack[-1] should be the first digit + if (hex and charStack[-1] in hexDigits) \ + or (not hex and charStack[-1] in digits): + # At least one digit found, so consume the whole number + self.stream.unget(charStack[-1]) + output = self.consumeNumberEntity(hex) + else: + # No digits found + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "expected-numeric-entity"}) + self.stream.unget(charStack.pop()) + output = "&" + "".join(charStack) + + else: + # At this point in the process might have named entity. Entities + # are stored in the global variable "entities". + # + # Consume characters and compare to these to a substring of the + # entity names in the list until the substring no longer matches. + while (charStack[-1] is not EOF): + if not entitiesTrie.has_keys_with_prefix("".join(charStack)): + break + charStack.append(self.stream.char()) + + # At this point we have a string that starts with some characters + # that may match an entity + # Try to find the longest entity the string will match to take care + # of ¬i for instance. + try: + entityName = entitiesTrie.longest_prefix("".join(charStack[:-1])) + entityLength = len(entityName) + except KeyError: + entityName = None + + if entityName is not None: + if entityName[-1] != ";": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "named-entity-without-semicolon"}) + if (entityName[-1] != ";" and fromAttribute and + (charStack[entityLength] in asciiLetters or + charStack[entityLength] in digits or + charStack[entityLength] == "=")): + self.stream.unget(charStack.pop()) + output = "&" + "".join(charStack) + else: + output = entities[entityName] + self.stream.unget(charStack.pop()) + output += "".join(charStack[entityLength:]) + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-named-entity"}) + self.stream.unget(charStack.pop()) + output = "&" + "".join(charStack) + + if fromAttribute: + self.currentToken["data"][-1][1] += output + else: + if output in spaceCharacters: + tokenType = "SpaceCharacters" + else: + tokenType = "Characters" + self.tokenQueue.append({"type": tokenTypes[tokenType], "data": output}) + + def processEntityInAttribute(self, allowedChar): + """This method replaces the need for "entityInAttributeValueState". + """ + self.consumeEntity(allowedChar=allowedChar, fromAttribute=True) + + def emitCurrentToken(self): + """This method is a generic handler for emitting the tags. It also sets + the state to "data" because that's what's needed after a token has been + emitted. + """ + token = self.currentToken + # Add token to the queue to be yielded + if (token["type"] in tagTokenTypes): + token["name"] = token["name"].translate(asciiUpper2Lower) + if token["type"] == tokenTypes["StartTag"]: + raw = token["data"] + data = attributeMap(raw) + if len(raw) > len(data): + # we had some duplicated attribute, fix so first wins + data.update(raw[::-1]) + token["data"] = data + + if token["type"] == tokenTypes["EndTag"]: + if token["data"]: + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "attributes-in-end-tag"}) + if token["selfClosing"]: + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "self-closing-flag-on-end-tag"}) + self.tokenQueue.append(token) + self.state = self.dataState + + # Below are the various tokenizer states worked out. + def dataState(self): + data = self.stream.char() + if data == "&": + self.state = self.entityDataState + elif data == "<": + self.state = self.tagOpenState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\u0000"}) + elif data is EOF: + # Tokenization ends. + return False + elif data in spaceCharacters: + # Directly after emitting a token you switch back to the "data + # state". At that point spaceCharacters are important so they are + # emitted separately. + self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data": + data + self.stream.charsUntil(spaceCharacters, True)}) + # No need to update lastFourChars here, since the first space will + # have already been appended to lastFourChars and will have broken + # any sequences + else: + chars = self.stream.charsUntil(("&", "<", "\u0000")) + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": + data + chars}) + return True + + def entityDataState(self): + self.consumeEntity() + self.state = self.dataState + return True + + def rcdataState(self): + data = self.stream.char() + if data == "&": + self.state = self.characterReferenceInRcdata + elif data == "<": + self.state = self.rcdataLessThanSignState + elif data == EOF: + # Tokenization ends. + return False + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\uFFFD"}) + elif data in spaceCharacters: + # Directly after emitting a token you switch back to the "data + # state". At that point spaceCharacters are important so they are + # emitted separately. + self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data": + data + self.stream.charsUntil(spaceCharacters, True)}) + # No need to update lastFourChars here, since the first space will + # have already been appended to lastFourChars and will have broken + # any sequences + else: + chars = self.stream.charsUntil(("&", "<", "\u0000")) + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": + data + chars}) + return True + + def characterReferenceInRcdata(self): + self.consumeEntity() + self.state = self.rcdataState + return True + + def rawtextState(self): + data = self.stream.char() + if data == "<": + self.state = self.rawtextLessThanSignState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\uFFFD"}) + elif data == EOF: + # Tokenization ends. + return False + else: + chars = self.stream.charsUntil(("<", "\u0000")) + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": + data + chars}) + return True + + def scriptDataState(self): + data = self.stream.char() + if data == "<": + self.state = self.scriptDataLessThanSignState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\uFFFD"}) + elif data == EOF: + # Tokenization ends. + return False + else: + chars = self.stream.charsUntil(("<", "\u0000")) + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": + data + chars}) + return True + + def plaintextState(self): + data = self.stream.char() + if data == EOF: + # Tokenization ends. + return False + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\uFFFD"}) + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": + data + self.stream.charsUntil("\u0000")}) + return True + + def tagOpenState(self): + data = self.stream.char() + if data == "!": + self.state = self.markupDeclarationOpenState + elif data == "/": + self.state = self.closeTagOpenState + elif data in asciiLetters: + self.currentToken = {"type": tokenTypes["StartTag"], + "name": data, "data": [], + "selfClosing": False, + "selfClosingAcknowledged": False} + self.state = self.tagNameState + elif data == ">": + # XXX In theory it could be something besides a tag name. But + # do we really care? + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-tag-name-but-got-right-bracket"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<>"}) + self.state = self.dataState + elif data == "?": + # XXX In theory it could be something besides a tag name. But + # do we really care? + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-tag-name-but-got-question-mark"}) + self.stream.unget(data) + self.state = self.bogusCommentState + else: + # XXX + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-tag-name"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) + self.stream.unget(data) + self.state = self.dataState + return True + + def closeTagOpenState(self): + data = self.stream.char() + if data in asciiLetters: + self.currentToken = {"type": tokenTypes["EndTag"], "name": data, + "data": [], "selfClosing": False} + self.state = self.tagNameState + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-closing-tag-but-got-right-bracket"}) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-closing-tag-but-got-eof"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "": + self.emitCurrentToken() + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-tag-name"}) + self.state = self.dataState + elif data == "/": + self.state = self.selfClosingStartTagState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["name"] += "\uFFFD" + else: + self.currentToken["name"] += data + # (Don't use charsUntil here, because tag names are + # very short and it's faster to not do anything fancy) + return True + + def rcdataLessThanSignState(self): + data = self.stream.char() + if data == "/": + self.temporaryBuffer = "" + self.state = self.rcdataEndTagOpenState + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) + self.stream.unget(data) + self.state = self.rcdataState + return True + + def rcdataEndTagOpenState(self): + data = self.stream.char() + if data in asciiLetters: + self.temporaryBuffer += data + self.state = self.rcdataEndTagNameState + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "" and appropriate: + self.currentToken = {"type": tokenTypes["EndTag"], + "name": self.temporaryBuffer, + "data": [], "selfClosing": False} + self.emitCurrentToken() + self.state = self.dataState + elif data in asciiLetters: + self.temporaryBuffer += data + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "" and appropriate: + self.currentToken = {"type": tokenTypes["EndTag"], + "name": self.temporaryBuffer, + "data": [], "selfClosing": False} + self.emitCurrentToken() + self.state = self.dataState + elif data in asciiLetters: + self.temporaryBuffer += data + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "" and appropriate: + self.currentToken = {"type": tokenTypes["EndTag"], + "name": self.temporaryBuffer, + "data": [], "selfClosing": False} + self.emitCurrentToken() + self.state = self.dataState + elif data in asciiLetters: + self.temporaryBuffer += data + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"}) + self.state = self.scriptDataState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\uFFFD"}) + self.state = self.scriptDataEscapedState + elif data == EOF: + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) + self.state = self.scriptDataEscapedState + return True + + def scriptDataEscapedLessThanSignState(self): + data = self.stream.char() + if data == "/": + self.temporaryBuffer = "" + self.state = self.scriptDataEscapedEndTagOpenState + elif data in asciiLetters: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<" + data}) + self.temporaryBuffer = data + self.state = self.scriptDataDoubleEscapeStartState + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) + self.stream.unget(data) + self.state = self.scriptDataEscapedState + return True + + def scriptDataEscapedEndTagOpenState(self): + data = self.stream.char() + if data in asciiLetters: + self.temporaryBuffer = data + self.state = self.scriptDataEscapedEndTagNameState + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "" and appropriate: + self.currentToken = {"type": tokenTypes["EndTag"], + "name": self.temporaryBuffer, + "data": [], "selfClosing": False} + self.emitCurrentToken() + self.state = self.dataState + elif data in asciiLetters: + self.temporaryBuffer += data + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": ""))): + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) + if self.temporaryBuffer.lower() == "script": + self.state = self.scriptDataDoubleEscapedState + else: + self.state = self.scriptDataEscapedState + elif data in asciiLetters: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) + self.temporaryBuffer += data + else: + self.stream.unget(data) + self.state = self.scriptDataEscapedState + return True + + def scriptDataDoubleEscapedState(self): + data = self.stream.char() + if data == "-": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) + self.state = self.scriptDataDoubleEscapedDashState + elif data == "<": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) + self.state = self.scriptDataDoubleEscapedLessThanSignState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\uFFFD"}) + elif data == EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-script-in-script"}) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) + return True + + def scriptDataDoubleEscapedDashState(self): + data = self.stream.char() + if data == "-": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) + self.state = self.scriptDataDoubleEscapedDashDashState + elif data == "<": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) + self.state = self.scriptDataDoubleEscapedLessThanSignState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\uFFFD"}) + self.state = self.scriptDataDoubleEscapedState + elif data == EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-script-in-script"}) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) + self.state = self.scriptDataDoubleEscapedState + return True + + def scriptDataDoubleEscapedDashDashState(self): + data = self.stream.char() + if data == "-": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) + elif data == "<": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) + self.state = self.scriptDataDoubleEscapedLessThanSignState + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"}) + self.state = self.scriptDataState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": "\uFFFD"}) + self.state = self.scriptDataDoubleEscapedState + elif data == EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-script-in-script"}) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) + self.state = self.scriptDataDoubleEscapedState + return True + + def scriptDataDoubleEscapedLessThanSignState(self): + data = self.stream.char() + if data == "/": + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "/"}) + self.temporaryBuffer = "" + self.state = self.scriptDataDoubleEscapeEndState + else: + self.stream.unget(data) + self.state = self.scriptDataDoubleEscapedState + return True + + def scriptDataDoubleEscapeEndState(self): + data = self.stream.char() + if data in (spaceCharacters | frozenset(("/", ">"))): + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) + if self.temporaryBuffer.lower() == "script": + self.state = self.scriptDataEscapedState + else: + self.state = self.scriptDataDoubleEscapedState + elif data in asciiLetters: + self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) + self.temporaryBuffer += data + else: + self.stream.unget(data) + self.state = self.scriptDataDoubleEscapedState + return True + + def beforeAttributeNameState(self): + data = self.stream.char() + if data in spaceCharacters: + self.stream.charsUntil(spaceCharacters, True) + elif data in asciiLetters: + self.currentToken["data"].append([data, ""]) + self.state = self.attributeNameState + elif data == ">": + self.emitCurrentToken() + elif data == "/": + self.state = self.selfClosingStartTagState + elif data in ("'", '"', "=", "<"): + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "invalid-character-in-attribute-name"}) + self.currentToken["data"].append([data, ""]) + self.state = self.attributeNameState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"].append(["\uFFFD", ""]) + self.state = self.attributeNameState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-attribute-name-but-got-eof"}) + self.state = self.dataState + else: + self.currentToken["data"].append([data, ""]) + self.state = self.attributeNameState + return True + + def attributeNameState(self): + data = self.stream.char() + leavingThisState = True + emitToken = False + if data == "=": + self.state = self.beforeAttributeValueState + elif data in asciiLetters: + self.currentToken["data"][-1][0] += data +\ + self.stream.charsUntil(asciiLetters, True) + leavingThisState = False + elif data == ">": + # XXX If we emit here the attributes are converted to a dict + # without being checked and when the code below runs we error + # because data is a dict not a list + emitToken = True + elif data in spaceCharacters: + self.state = self.afterAttributeNameState + elif data == "/": + self.state = self.selfClosingStartTagState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"][-1][0] += "\uFFFD" + leavingThisState = False + elif data in ("'", '"', "<"): + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": + "invalid-character-in-attribute-name"}) + self.currentToken["data"][-1][0] += data + leavingThisState = False + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "eof-in-attribute-name"}) + self.state = self.dataState + else: + self.currentToken["data"][-1][0] += data + leavingThisState = False + + if leavingThisState: + # Attributes are not dropped at this stage. That happens when the + # start tag token is emitted so values can still be safely appended + # to attributes, but we do want to report the parse error in time. + self.currentToken["data"][-1][0] = ( + self.currentToken["data"][-1][0].translate(asciiUpper2Lower)) + for name, _ in self.currentToken["data"][:-1]: + if self.currentToken["data"][-1][0] == name: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "duplicate-attribute"}) + break + # XXX Fix for above XXX + if emitToken: + self.emitCurrentToken() + return True + + def afterAttributeNameState(self): + data = self.stream.char() + if data in spaceCharacters: + self.stream.charsUntil(spaceCharacters, True) + elif data == "=": + self.state = self.beforeAttributeValueState + elif data == ">": + self.emitCurrentToken() + elif data in asciiLetters: + self.currentToken["data"].append([data, ""]) + self.state = self.attributeNameState + elif data == "/": + self.state = self.selfClosingStartTagState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"].append(["\uFFFD", ""]) + self.state = self.attributeNameState + elif data in ("'", '"', "<"): + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "invalid-character-after-attribute-name"}) + self.currentToken["data"].append([data, ""]) + self.state = self.attributeNameState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-end-of-tag-but-got-eof"}) + self.state = self.dataState + else: + self.currentToken["data"].append([data, ""]) + self.state = self.attributeNameState + return True + + def beforeAttributeValueState(self): + data = self.stream.char() + if data in spaceCharacters: + self.stream.charsUntil(spaceCharacters, True) + elif data == "\"": + self.state = self.attributeValueDoubleQuotedState + elif data == "&": + self.state = self.attributeValueUnQuotedState + self.stream.unget(data) + elif data == "'": + self.state = self.attributeValueSingleQuotedState + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-attribute-value-but-got-right-bracket"}) + self.emitCurrentToken() + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"][-1][1] += "\uFFFD" + self.state = self.attributeValueUnQuotedState + elif data in ("=", "<", "`"): + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "equals-in-unquoted-attribute-value"}) + self.currentToken["data"][-1][1] += data + self.state = self.attributeValueUnQuotedState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-attribute-value-but-got-eof"}) + self.state = self.dataState + else: + self.currentToken["data"][-1][1] += data + self.state = self.attributeValueUnQuotedState + return True + + def attributeValueDoubleQuotedState(self): + data = self.stream.char() + if data == "\"": + self.state = self.afterAttributeValueState + elif data == "&": + self.processEntityInAttribute('"') + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"][-1][1] += "\uFFFD" + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-attribute-value-double-quote"}) + self.state = self.dataState + else: + self.currentToken["data"][-1][1] += data +\ + self.stream.charsUntil(("\"", "&", "\u0000")) + return True + + def attributeValueSingleQuotedState(self): + data = self.stream.char() + if data == "'": + self.state = self.afterAttributeValueState + elif data == "&": + self.processEntityInAttribute("'") + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"][-1][1] += "\uFFFD" + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-attribute-value-single-quote"}) + self.state = self.dataState + else: + self.currentToken["data"][-1][1] += data +\ + self.stream.charsUntil(("'", "&", "\u0000")) + return True + + def attributeValueUnQuotedState(self): + data = self.stream.char() + if data in spaceCharacters: + self.state = self.beforeAttributeNameState + elif data == "&": + self.processEntityInAttribute(">") + elif data == ">": + self.emitCurrentToken() + elif data in ('"', "'", "=", "<", "`"): + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-character-in-unquoted-attribute-value"}) + self.currentToken["data"][-1][1] += data + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"][-1][1] += "\uFFFD" + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-attribute-value-no-quotes"}) + self.state = self.dataState + else: + self.currentToken["data"][-1][1] += data + self.stream.charsUntil( + frozenset(("&", ">", '"', "'", "=", "<", "`", "\u0000")) | spaceCharacters) + return True + + def afterAttributeValueState(self): + data = self.stream.char() + if data in spaceCharacters: + self.state = self.beforeAttributeNameState + elif data == ">": + self.emitCurrentToken() + elif data == "/": + self.state = self.selfClosingStartTagState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-EOF-after-attribute-value"}) + self.stream.unget(data) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-character-after-attribute-value"}) + self.stream.unget(data) + self.state = self.beforeAttributeNameState + return True + + def selfClosingStartTagState(self): + data = self.stream.char() + if data == ">": + self.currentToken["selfClosing"] = True + self.emitCurrentToken() + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": + "unexpected-EOF-after-solidus-in-tag"}) + self.stream.unget(data) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-character-after-solidus-in-tag"}) + self.stream.unget(data) + self.state = self.beforeAttributeNameState + return True + + def bogusCommentState(self): + # Make a new comment token and give it as value all the characters + # until the first > or EOF (charsUntil checks for EOF automatically) + # and emit it. + data = self.stream.charsUntil(">") + data = data.replace("\u0000", "\uFFFD") + self.tokenQueue.append( + {"type": tokenTypes["Comment"], "data": data}) + + # Eat the character directly after the bogus comment which is either a + # ">" or an EOF. + self.stream.char() + self.state = self.dataState + return True + + def markupDeclarationOpenState(self): + charStack = [self.stream.char()] + if charStack[-1] == "-": + charStack.append(self.stream.char()) + if charStack[-1] == "-": + self.currentToken = {"type": tokenTypes["Comment"], "data": ""} + self.state = self.commentStartState + return True + elif charStack[-1] in ('d', 'D'): + matched = True + for expected in (('o', 'O'), ('c', 'C'), ('t', 'T'), + ('y', 'Y'), ('p', 'P'), ('e', 'E')): + charStack.append(self.stream.char()) + if charStack[-1] not in expected: + matched = False + break + if matched: + self.currentToken = {"type": tokenTypes["Doctype"], + "name": "", + "publicId": None, "systemId": None, + "correct": True} + self.state = self.doctypeState + return True + elif (charStack[-1] == "[" and + self.parser is not None and + self.parser.tree.openElements and + self.parser.tree.openElements[-1].namespace != self.parser.tree.defaultNamespace): + matched = True + for expected in ["C", "D", "A", "T", "A", "["]: + charStack.append(self.stream.char()) + if charStack[-1] != expected: + matched = False + break + if matched: + self.state = self.cdataSectionState + return True + + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-dashes-or-doctype"}) + + while charStack: + self.stream.unget(charStack.pop()) + self.state = self.bogusCommentState + return True + + def commentStartState(self): + data = self.stream.char() + if data == "-": + self.state = self.commentStartDashState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"] += "\uFFFD" + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "incorrect-comment"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-comment"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["data"] += data + self.state = self.commentState + return True + + def commentStartDashState(self): + data = self.stream.char() + if data == "-": + self.state = self.commentEndState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"] += "-\uFFFD" + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "incorrect-comment"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-comment"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["data"] += "-" + data + self.state = self.commentState + return True + + def commentState(self): + data = self.stream.char() + if data == "-": + self.state = self.commentEndDashState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"] += "\uFFFD" + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "eof-in-comment"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["data"] += data + \ + self.stream.charsUntil(("-", "\u0000")) + return True + + def commentEndDashState(self): + data = self.stream.char() + if data == "-": + self.state = self.commentEndState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"] += "-\uFFFD" + self.state = self.commentState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-comment-end-dash"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["data"] += "-" + data + self.state = self.commentState + return True + + def commentEndState(self): + data = self.stream.char() + if data == ">": + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"] += "--\uFFFD" + self.state = self.commentState + elif data == "!": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-bang-after-double-dash-in-comment"}) + self.state = self.commentEndBangState + elif data == "-": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-dash-after-double-dash-in-comment"}) + self.currentToken["data"] += data + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-comment-double-dash"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + # XXX + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-comment"}) + self.currentToken["data"] += "--" + data + self.state = self.commentState + return True + + def commentEndBangState(self): + data = self.stream.char() + if data == ">": + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data == "-": + self.currentToken["data"] += "--!" + self.state = self.commentEndDashState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["data"] += "--!\uFFFD" + self.state = self.commentState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-comment-end-bang-state"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["data"] += "--!" + data + self.state = self.commentState + return True + + def doctypeState(self): + data = self.stream.char() + if data in spaceCharacters: + self.state = self.beforeDoctypeNameState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-doctype-name-but-got-eof"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "need-space-after-doctype"}) + self.stream.unget(data) + self.state = self.beforeDoctypeNameState + return True + + def beforeDoctypeNameState(self): + data = self.stream.char() + if data in spaceCharacters: + pass + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-doctype-name-but-got-right-bracket"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["name"] = "\uFFFD" + self.state = self.doctypeNameState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-doctype-name-but-got-eof"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["name"] = data + self.state = self.doctypeNameState + return True + + def doctypeNameState(self): + data = self.stream.char() + if data in spaceCharacters: + self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) + self.state = self.afterDoctypeNameState + elif data == ">": + self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["name"] += "\uFFFD" + self.state = self.doctypeNameState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype-name"}) + self.currentToken["correct"] = False + self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["name"] += data + return True + + def afterDoctypeNameState(self): + data = self.stream.char() + if data in spaceCharacters: + pass + elif data == ">": + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.currentToken["correct"] = False + self.stream.unget(data) + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + if data in ("p", "P"): + matched = True + for expected in (("u", "U"), ("b", "B"), ("l", "L"), + ("i", "I"), ("c", "C")): + data = self.stream.char() + if data not in expected: + matched = False + break + if matched: + self.state = self.afterDoctypePublicKeywordState + return True + elif data in ("s", "S"): + matched = True + for expected in (("y", "Y"), ("s", "S"), ("t", "T"), + ("e", "E"), ("m", "M")): + data = self.stream.char() + if data not in expected: + matched = False + break + if matched: + self.state = self.afterDoctypeSystemKeywordState + return True + + # All the characters read before the current 'data' will be + # [a-zA-Z], so they're garbage in the bogus doctype and can be + # discarded; only the latest character might be '>' or EOF + # and needs to be ungetted + self.stream.unget(data) + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "expected-space-or-right-bracket-in-doctype", "datavars": + {"data": data}}) + self.currentToken["correct"] = False + self.state = self.bogusDoctypeState + + return True + + def afterDoctypePublicKeywordState(self): + data = self.stream.char() + if data in spaceCharacters: + self.state = self.beforeDoctypePublicIdentifierState + elif data in ("'", '"'): + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.stream.unget(data) + self.state = self.beforeDoctypePublicIdentifierState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.stream.unget(data) + self.state = self.beforeDoctypePublicIdentifierState + return True + + def beforeDoctypePublicIdentifierState(self): + data = self.stream.char() + if data in spaceCharacters: + pass + elif data == "\"": + self.currentToken["publicId"] = "" + self.state = self.doctypePublicIdentifierDoubleQuotedState + elif data == "'": + self.currentToken["publicId"] = "" + self.state = self.doctypePublicIdentifierSingleQuotedState + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-end-of-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.currentToken["correct"] = False + self.state = self.bogusDoctypeState + return True + + def doctypePublicIdentifierDoubleQuotedState(self): + data = self.stream.char() + if data == "\"": + self.state = self.afterDoctypePublicIdentifierState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["publicId"] += "\uFFFD" + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-end-of-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["publicId"] += data + return True + + def doctypePublicIdentifierSingleQuotedState(self): + data = self.stream.char() + if data == "'": + self.state = self.afterDoctypePublicIdentifierState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["publicId"] += "\uFFFD" + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-end-of-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["publicId"] += data + return True + + def afterDoctypePublicIdentifierState(self): + data = self.stream.char() + if data in spaceCharacters: + self.state = self.betweenDoctypePublicAndSystemIdentifiersState + elif data == ">": + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data == '"': + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.currentToken["systemId"] = "" + self.state = self.doctypeSystemIdentifierDoubleQuotedState + elif data == "'": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.currentToken["systemId"] = "" + self.state = self.doctypeSystemIdentifierSingleQuotedState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.currentToken["correct"] = False + self.state = self.bogusDoctypeState + return True + + def betweenDoctypePublicAndSystemIdentifiersState(self): + data = self.stream.char() + if data in spaceCharacters: + pass + elif data == ">": + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data == '"': + self.currentToken["systemId"] = "" + self.state = self.doctypeSystemIdentifierDoubleQuotedState + elif data == "'": + self.currentToken["systemId"] = "" + self.state = self.doctypeSystemIdentifierSingleQuotedState + elif data == EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.currentToken["correct"] = False + self.state = self.bogusDoctypeState + return True + + def afterDoctypeSystemKeywordState(self): + data = self.stream.char() + if data in spaceCharacters: + self.state = self.beforeDoctypeSystemIdentifierState + elif data in ("'", '"'): + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.stream.unget(data) + self.state = self.beforeDoctypeSystemIdentifierState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.stream.unget(data) + self.state = self.beforeDoctypeSystemIdentifierState + return True + + def beforeDoctypeSystemIdentifierState(self): + data = self.stream.char() + if data in spaceCharacters: + pass + elif data == "\"": + self.currentToken["systemId"] = "" + self.state = self.doctypeSystemIdentifierDoubleQuotedState + elif data == "'": + self.currentToken["systemId"] = "" + self.state = self.doctypeSystemIdentifierSingleQuotedState + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.currentToken["correct"] = False + self.state = self.bogusDoctypeState + return True + + def doctypeSystemIdentifierDoubleQuotedState(self): + data = self.stream.char() + if data == "\"": + self.state = self.afterDoctypeSystemIdentifierState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["systemId"] += "\uFFFD" + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-end-of-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["systemId"] += data + return True + + def doctypeSystemIdentifierSingleQuotedState(self): + data = self.stream.char() + if data == "'": + self.state = self.afterDoctypeSystemIdentifierState + elif data == "\u0000": + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + self.currentToken["systemId"] += "\uFFFD" + elif data == ">": + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-end-of-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.currentToken["systemId"] += data + return True + + def afterDoctypeSystemIdentifierState(self): + data = self.stream.char() + if data in spaceCharacters: + pass + elif data == ">": + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "eof-in-doctype"}) + self.currentToken["correct"] = False + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": + "unexpected-char-in-doctype"}) + self.state = self.bogusDoctypeState + return True + + def bogusDoctypeState(self): + data = self.stream.char() + if data == ">": + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + elif data is EOF: + # XXX EMIT + self.stream.unget(data) + self.tokenQueue.append(self.currentToken) + self.state = self.dataState + else: + pass + return True + + def cdataSectionState(self): + data = [] + while True: + data.append(self.stream.charsUntil("]")) + data.append(self.stream.charsUntil(">")) + char = self.stream.char() + if char == EOF: + break + else: + assert char == ">" + if data[-1][-2:] == "]]": + data[-1] = data[-1][:-2] + break + else: + data.append(char) + + data = "".join(data) # pylint:disable=redefined-variable-type + # Deal with null here rather than in the parser + nullCount = data.count("\u0000") + if nullCount > 0: + for _ in range(nullCount): + self.tokenQueue.append({"type": tokenTypes["ParseError"], + "data": "invalid-codepoint"}) + data = data.replace("\u0000", "\uFFFD") + if data: + self.tokenQueue.append({"type": tokenTypes["Characters"], + "data": data}) + self.state = self.dataState + return True diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__init__.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07bad5d31c1ec7aa7ac081dac5586db91f3c5a99 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__init__.py @@ -0,0 +1,5 @@ +from __future__ import absolute_import, division, unicode_literals + +from .py import Trie + +__all__ = ["Trie"] diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/__init__.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92d5429901fb6e43dcd73fe2fadb147db9d4b154 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/__init__.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/_base.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/_base.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5bb36cb394bc6370980ffb72d6b22522c138a49 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/_base.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/py.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/py.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18adcc36b2dfd58b6cd9ee98bdcd1183da910623 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/__pycache__/py.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/_base.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..6b71975f08587ca8861acc2380f17701b7c7c656 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/_base.py @@ -0,0 +1,40 @@ +from __future__ import absolute_import, division, unicode_literals + +try: + from collections.abc import Mapping +except ImportError: # Python 2.7 + from collections import Mapping + + +class Trie(Mapping): + """Abstract base class for tries""" + + def keys(self, prefix=None): + # pylint:disable=arguments-differ + keys = super(Trie, self).keys() + + if prefix is None: + return set(keys) + + return {x for x in keys if x.startswith(prefix)} + + def has_keys_with_prefix(self, prefix): + for key in self.keys(): + if key.startswith(prefix): + return True + + return False + + def longest_prefix(self, prefix): + if prefix in self: + return prefix + + for i in range(1, len(prefix) + 1): + if prefix[:-i] in self: + return prefix[:-i] + + raise KeyError(prefix) + + def longest_prefix_item(self, prefix): + lprefix = self.longest_prefix(prefix) + return (lprefix, self[lprefix]) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/py.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/py.py new file mode 100644 index 0000000000000000000000000000000000000000..c2ba3da757646ea1bbd5386c51590cf378db2cd8 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_trie/py.py @@ -0,0 +1,67 @@ +from __future__ import absolute_import, division, unicode_literals +from six import text_type + +from bisect import bisect_left + +from ._base import Trie as ABCTrie + + +class Trie(ABCTrie): + def __init__(self, data): + if not all(isinstance(x, text_type) for x in data.keys()): + raise TypeError("All keys must be strings") + + self._data = data + self._keys = sorted(data.keys()) + self._cachestr = "" + self._cachepoints = (0, len(data)) + + def __contains__(self, key): + return key in self._data + + def __len__(self): + return len(self._data) + + def __iter__(self): + return iter(self._data) + + def __getitem__(self, key): + return self._data[key] + + def keys(self, prefix=None): + if prefix is None or prefix == "" or not self._keys: + return set(self._keys) + + if prefix.startswith(self._cachestr): + lo, hi = self._cachepoints + start = i = bisect_left(self._keys, prefix, lo, hi) + else: + start = i = bisect_left(self._keys, prefix) + + keys = set() + if start == len(self._keys): + return keys + + while self._keys[i].startswith(prefix): + keys.add(self._keys[i]) + i += 1 + + self._cachestr = prefix + self._cachepoints = (start, i) + + return keys + + def has_keys_with_prefix(self, prefix): + if prefix in self._data: + return True + + if prefix.startswith(self._cachestr): + lo, hi = self._cachepoints + i = bisect_left(self._keys, prefix, lo, hi) + else: + i = bisect_left(self._keys, prefix) + + if i == len(self._keys): + return False + + return self._keys[i].startswith(prefix) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_utils.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea5794214eccfe1d34b72f7b3e865256a8a5d1c --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/_utils.py @@ -0,0 +1,159 @@ +from __future__ import absolute_import, division, unicode_literals + +from types import ModuleType + +try: + from collections.abc import Mapping +except ImportError: + from collections import Mapping + +from six import text_type, PY3 + +if PY3: + import xml.etree.ElementTree as default_etree +else: + try: + import xml.etree.cElementTree as default_etree + except ImportError: + import xml.etree.ElementTree as default_etree + + +__all__ = ["default_etree", "MethodDispatcher", "isSurrogatePair", + "surrogatePairToCodepoint", "moduleFactoryFactory", + "supports_lone_surrogates"] + + +# Platforms not supporting lone surrogates (\uD800-\uDFFF) should be +# caught by the below test. In general this would be any platform +# using UTF-16 as its encoding of unicode strings, such as +# Jython. This is because UTF-16 itself is based on the use of such +# surrogates, and there is no mechanism to further escape such +# escapes. +try: + _x = eval('"\\uD800"') # pylint:disable=eval-used + if not isinstance(_x, text_type): + # We need this with u"" because of http://bugs.jython.org/issue2039 + _x = eval('u"\\uD800"') # pylint:disable=eval-used + assert isinstance(_x, text_type) +except Exception: + supports_lone_surrogates = False +else: + supports_lone_surrogates = True + + +class MethodDispatcher(dict): + """Dict with 2 special properties: + + On initiation, keys that are lists, sets or tuples are converted to + multiple keys so accessing any one of the items in the original + list-like object returns the matching value + + md = MethodDispatcher({("foo", "bar"):"baz"}) + md["foo"] == "baz" + + A default value which can be set through the default attribute. + """ + + def __init__(self, items=()): + _dictEntries = [] + for name, value in items: + if isinstance(name, (list, tuple, frozenset, set)): + for item in name: + _dictEntries.append((item, value)) + else: + _dictEntries.append((name, value)) + dict.__init__(self, _dictEntries) + assert len(self) == len(_dictEntries) + self.default = None + + def __getitem__(self, key): + return dict.get(self, key, self.default) + + def __get__(self, instance, owner=None): + return BoundMethodDispatcher(instance, self) + + +class BoundMethodDispatcher(Mapping): + """Wraps a MethodDispatcher, binding its return values to `instance`""" + def __init__(self, instance, dispatcher): + self.instance = instance + self.dispatcher = dispatcher + + def __getitem__(self, key): + # see https://docs.python.org/3/reference/datamodel.html#object.__get__ + # on a function, __get__ is used to bind a function to an instance as a bound method + return self.dispatcher[key].__get__(self.instance) + + def get(self, key, default): + if key in self.dispatcher: + return self[key] + else: + return default + + def __iter__(self): + return iter(self.dispatcher) + + def __len__(self): + return len(self.dispatcher) + + def __contains__(self, key): + return key in self.dispatcher + + +# Some utility functions to deal with weirdness around UCS2 vs UCS4 +# python builds + +def isSurrogatePair(data): + return (len(data) == 2 and + ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and + ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF) + + +def surrogatePairToCodepoint(data): + char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 + + (ord(data[1]) - 0xDC00)) + return char_val + +# Module Factory Factory (no, this isn't Java, I know) +# Here to stop this being duplicated all over the place. + + +def moduleFactoryFactory(factory): + moduleCache = {} + + def moduleFactory(baseModule, *args, **kwargs): + if isinstance(ModuleType.__name__, type("")): + name = "_%s_factory" % baseModule.__name__ + else: + name = b"_%s_factory" % baseModule.__name__ + + kwargs_tuple = tuple(kwargs.items()) + + try: + return moduleCache[name][args][kwargs_tuple] + except KeyError: + mod = ModuleType(name) + objs = factory(baseModule, *args, **kwargs) + mod.__dict__.update(objs) + if "name" not in moduleCache: + moduleCache[name] = {} + if "args" not in moduleCache[name]: + moduleCache[name][args] = {} + if "kwargs" not in moduleCache[name][args]: + moduleCache[name][args][kwargs_tuple] = {} + moduleCache[name][args][kwargs_tuple] = mod + return mod + + return moduleFactory + + +def memoize(func): + cache = {} + + def wrapped(*args, **kwargs): + key = (tuple(args), tuple(kwargs.items())) + if key not in cache: + cache[key] = func(*args, **kwargs) + return cache[key] + + return wrapped diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/constants.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..fe3e237cd8a118da1c707412fe8251d2e19477c5 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/constants.py @@ -0,0 +1,2946 @@ +from __future__ import absolute_import, division, unicode_literals + +import string + +EOF = None + +E = { + "null-character": + "Null character in input stream, replaced with U+FFFD.", + "invalid-codepoint": + "Invalid codepoint in stream.", + "incorrectly-placed-solidus": + "Solidus (/) incorrectly placed in tag.", + "incorrect-cr-newline-entity": + "Incorrect CR newline entity, replaced with LF.", + "illegal-windows-1252-entity": + "Entity used with illegal number (windows-1252 reference).", + "cant-convert-numeric-entity": + "Numeric entity couldn't be converted to character " + "(codepoint U+%(charAsInt)08x).", + "illegal-codepoint-for-numeric-entity": + "Numeric entity represents an illegal codepoint: " + "U+%(charAsInt)08x.", + "numeric-entity-without-semicolon": + "Numeric entity didn't end with ';'.", + "expected-numeric-entity-but-got-eof": + "Numeric entity expected. Got end of file instead.", + "expected-numeric-entity": + "Numeric entity expected but none found.", + "named-entity-without-semicolon": + "Named entity didn't end with ';'.", + "expected-named-entity": + "Named entity expected. Got none.", + "attributes-in-end-tag": + "End tag contains unexpected attributes.", + 'self-closing-flag-on-end-tag': + "End tag contains unexpected self-closing flag.", + "expected-tag-name-but-got-right-bracket": + "Expected tag name. Got '>' instead.", + "expected-tag-name-but-got-question-mark": + "Expected tag name. Got '?' instead. (HTML doesn't " + "support processing instructions.)", + "expected-tag-name": + "Expected tag name. Got something else instead", + "expected-closing-tag-but-got-right-bracket": + "Expected closing tag. Got '>' instead. Ignoring ''.", + "expected-closing-tag-but-got-eof": + "Expected closing tag. Unexpected end of file.", + "expected-closing-tag-but-got-char": + "Expected closing tag. Unexpected character '%(data)s' found.", + "eof-in-tag-name": + "Unexpected end of file in the tag name.", + "expected-attribute-name-but-got-eof": + "Unexpected end of file. Expected attribute name instead.", + "eof-in-attribute-name": + "Unexpected end of file in attribute name.", + "invalid-character-in-attribute-name": + "Invalid character in attribute name", + "duplicate-attribute": + "Dropped duplicate attribute on tag.", + "expected-end-of-tag-name-but-got-eof": + "Unexpected end of file. Expected = or end of tag.", + "expected-attribute-value-but-got-eof": + "Unexpected end of file. Expected attribute value.", + "expected-attribute-value-but-got-right-bracket": + "Expected attribute value. Got '>' instead.", + 'equals-in-unquoted-attribute-value': + "Unexpected = in unquoted attribute", + 'unexpected-character-in-unquoted-attribute-value': + "Unexpected character in unquoted attribute", + "invalid-character-after-attribute-name": + "Unexpected character after attribute name.", + "unexpected-character-after-attribute-value": + "Unexpected character after attribute value.", + "eof-in-attribute-value-double-quote": + "Unexpected end of file in attribute value (\").", + "eof-in-attribute-value-single-quote": + "Unexpected end of file in attribute value (').", + "eof-in-attribute-value-no-quotes": + "Unexpected end of file in attribute value.", + "unexpected-EOF-after-solidus-in-tag": + "Unexpected end of file in tag. Expected >", + "unexpected-character-after-solidus-in-tag": + "Unexpected character after / in tag. Expected >", + "expected-dashes-or-doctype": + "Expected '--' or 'DOCTYPE'. Not found.", + "unexpected-bang-after-double-dash-in-comment": + "Unexpected ! after -- in comment", + "unexpected-space-after-double-dash-in-comment": + "Unexpected space after -- in comment", + "incorrect-comment": + "Incorrect comment.", + "eof-in-comment": + "Unexpected end of file in comment.", + "eof-in-comment-end-dash": + "Unexpected end of file in comment (-)", + "unexpected-dash-after-double-dash-in-comment": + "Unexpected '-' after '--' found in comment.", + "eof-in-comment-double-dash": + "Unexpected end of file in comment (--).", + "eof-in-comment-end-space-state": + "Unexpected end of file in comment.", + "eof-in-comment-end-bang-state": + "Unexpected end of file in comment.", + "unexpected-char-in-comment": + "Unexpected character in comment found.", + "need-space-after-doctype": + "No space after literal string 'DOCTYPE'.", + "expected-doctype-name-but-got-right-bracket": + "Unexpected > character. Expected DOCTYPE name.", + "expected-doctype-name-but-got-eof": + "Unexpected end of file. Expected DOCTYPE name.", + "eof-in-doctype-name": + "Unexpected end of file in DOCTYPE name.", + "eof-in-doctype": + "Unexpected end of file in DOCTYPE.", + "expected-space-or-right-bracket-in-doctype": + "Expected space or '>'. Got '%(data)s'", + "unexpected-end-of-doctype": + "Unexpected end of DOCTYPE.", + "unexpected-char-in-doctype": + "Unexpected character in DOCTYPE.", + "eof-in-innerhtml": + "XXX innerHTML EOF", + "unexpected-doctype": + "Unexpected DOCTYPE. Ignored.", + "non-html-root": + "html needs to be the first start tag.", + "expected-doctype-but-got-eof": + "Unexpected End of file. Expected DOCTYPE.", + "unknown-doctype": + "Erroneous DOCTYPE.", + "expected-doctype-but-got-chars": + "Unexpected non-space characters. Expected DOCTYPE.", + "expected-doctype-but-got-start-tag": + "Unexpected start tag (%(name)s). Expected DOCTYPE.", + "expected-doctype-but-got-end-tag": + "Unexpected end tag (%(name)s). Expected DOCTYPE.", + "end-tag-after-implied-root": + "Unexpected end tag (%(name)s) after the (implied) root element.", + "expected-named-closing-tag-but-got-eof": + "Unexpected end of file. Expected end tag (%(name)s).", + "two-heads-are-not-better-than-one": + "Unexpected start tag head in existing head. Ignored.", + "unexpected-end-tag": + "Unexpected end tag (%(name)s). Ignored.", + "unexpected-start-tag-out-of-my-head": + "Unexpected start tag (%(name)s) that can be in head. Moved.", + "unexpected-start-tag": + "Unexpected start tag (%(name)s).", + "missing-end-tag": + "Missing end tag (%(name)s).", + "missing-end-tags": + "Missing end tags (%(name)s).", + "unexpected-start-tag-implies-end-tag": + "Unexpected start tag (%(startName)s) " + "implies end tag (%(endName)s).", + "unexpected-start-tag-treated-as": + "Unexpected start tag (%(originalName)s). Treated as %(newName)s.", + "deprecated-tag": + "Unexpected start tag %(name)s. Don't use it!", + "unexpected-start-tag-ignored": + "Unexpected start tag %(name)s. Ignored.", + "expected-one-end-tag-but-got-another": + "Unexpected end tag (%(gotName)s). " + "Missing end tag (%(expectedName)s).", + "end-tag-too-early": + "End tag (%(name)s) seen too early. Expected other end tag.", + "end-tag-too-early-named": + "Unexpected end tag (%(gotName)s). Expected end tag (%(expectedName)s).", + "end-tag-too-early-ignored": + "End tag (%(name)s) seen too early. Ignored.", + "adoption-agency-1.1": + "End tag (%(name)s) violates step 1, " + "paragraph 1 of the adoption agency algorithm.", + "adoption-agency-1.2": + "End tag (%(name)s) violates step 1, " + "paragraph 2 of the adoption agency algorithm.", + "adoption-agency-1.3": + "End tag (%(name)s) violates step 1, " + "paragraph 3 of the adoption agency algorithm.", + "adoption-agency-4.4": + "End tag (%(name)s) violates step 4, " + "paragraph 4 of the adoption agency algorithm.", + "unexpected-end-tag-treated-as": + "Unexpected end tag (%(originalName)s). Treated as %(newName)s.", + "no-end-tag": + "This element (%(name)s) has no end tag.", + "unexpected-implied-end-tag-in-table": + "Unexpected implied end tag (%(name)s) in the table phase.", + "unexpected-implied-end-tag-in-table-body": + "Unexpected implied end tag (%(name)s) in the table body phase.", + "unexpected-char-implies-table-voodoo": + "Unexpected non-space characters in " + "table context caused voodoo mode.", + "unexpected-hidden-input-in-table": + "Unexpected input with type hidden in table context.", + "unexpected-form-in-table": + "Unexpected form in table context.", + "unexpected-start-tag-implies-table-voodoo": + "Unexpected start tag (%(name)s) in " + "table context caused voodoo mode.", + "unexpected-end-tag-implies-table-voodoo": + "Unexpected end tag (%(name)s) in " + "table context caused voodoo mode.", + "unexpected-cell-in-table-body": + "Unexpected table cell start tag (%(name)s) " + "in the table body phase.", + "unexpected-cell-end-tag": + "Got table cell end tag (%(name)s) " + "while required end tags are missing.", + "unexpected-end-tag-in-table-body": + "Unexpected end tag (%(name)s) in the table body phase. Ignored.", + "unexpected-implied-end-tag-in-table-row": + "Unexpected implied end tag (%(name)s) in the table row phase.", + "unexpected-end-tag-in-table-row": + "Unexpected end tag (%(name)s) in the table row phase. Ignored.", + "unexpected-select-in-select": + "Unexpected select start tag in the select phase " + "treated as select end tag.", + "unexpected-input-in-select": + "Unexpected input start tag in the select phase.", + "unexpected-start-tag-in-select": + "Unexpected start tag token (%(name)s in the select phase. " + "Ignored.", + "unexpected-end-tag-in-select": + "Unexpected end tag (%(name)s) in the select phase. Ignored.", + "unexpected-table-element-start-tag-in-select-in-table": + "Unexpected table element start tag (%(name)s) in the select in table phase.", + "unexpected-table-element-end-tag-in-select-in-table": + "Unexpected table element end tag (%(name)s) in the select in table phase.", + "unexpected-char-after-body": + "Unexpected non-space characters in the after body phase.", + "unexpected-start-tag-after-body": + "Unexpected start tag token (%(name)s)" + " in the after body phase.", + "unexpected-end-tag-after-body": + "Unexpected end tag token (%(name)s)" + " in the after body phase.", + "unexpected-char-in-frameset": + "Unexpected characters in the frameset phase. Characters ignored.", + "unexpected-start-tag-in-frameset": + "Unexpected start tag token (%(name)s)" + " in the frameset phase. Ignored.", + "unexpected-frameset-in-frameset-innerhtml": + "Unexpected end tag token (frameset) " + "in the frameset phase (innerHTML).", + "unexpected-end-tag-in-frameset": + "Unexpected end tag token (%(name)s)" + " in the frameset phase. Ignored.", + "unexpected-char-after-frameset": + "Unexpected non-space characters in the " + "after frameset phase. Ignored.", + "unexpected-start-tag-after-frameset": + "Unexpected start tag (%(name)s)" + " in the after frameset phase. Ignored.", + "unexpected-end-tag-after-frameset": + "Unexpected end tag (%(name)s)" + " in the after frameset phase. Ignored.", + "unexpected-end-tag-after-body-innerhtml": + "Unexpected end tag after body(innerHtml)", + "expected-eof-but-got-char": + "Unexpected non-space characters. Expected end of file.", + "expected-eof-but-got-start-tag": + "Unexpected start tag (%(name)s)" + ". Expected end of file.", + "expected-eof-but-got-end-tag": + "Unexpected end tag (%(name)s)" + ". Expected end of file.", + "eof-in-table": + "Unexpected end of file. Expected table content.", + "eof-in-select": + "Unexpected end of file. Expected select content.", + "eof-in-frameset": + "Unexpected end of file. Expected frameset content.", + "eof-in-script-in-script": + "Unexpected end of file. Expected script content.", + "eof-in-foreign-lands": + "Unexpected end of file. Expected foreign content", + "non-void-element-with-trailing-solidus": + "Trailing solidus not allowed on element %(name)s", + "unexpected-html-element-in-foreign-content": + "Element %(name)s not allowed in a non-html context", + "unexpected-end-tag-before-html": + "Unexpected end tag (%(name)s) before html.", + "unexpected-inhead-noscript-tag": + "Element %(name)s not allowed in a inhead-noscript context", + "eof-in-head-noscript": + "Unexpected end of file. Expected inhead-noscript content", + "char-in-head-noscript": + "Unexpected non-space character. Expected inhead-noscript content", + "XXX-undefined-error": + "Undefined error (this sucks and should be fixed)", +} + +namespaces = { + "html": "http://www.w3.org/1999/xhtml", + "mathml": "http://www.w3.org/1998/Math/MathML", + "svg": "http://www.w3.org/2000/svg", + "xlink": "http://www.w3.org/1999/xlink", + "xml": "http://www.w3.org/XML/1998/namespace", + "xmlns": "http://www.w3.org/2000/xmlns/" +} + +scopingElements = frozenset([ + (namespaces["html"], "applet"), + (namespaces["html"], "caption"), + (namespaces["html"], "html"), + (namespaces["html"], "marquee"), + (namespaces["html"], "object"), + (namespaces["html"], "table"), + (namespaces["html"], "td"), + (namespaces["html"], "th"), + (namespaces["mathml"], "mi"), + (namespaces["mathml"], "mo"), + (namespaces["mathml"], "mn"), + (namespaces["mathml"], "ms"), + (namespaces["mathml"], "mtext"), + (namespaces["mathml"], "annotation-xml"), + (namespaces["svg"], "foreignObject"), + (namespaces["svg"], "desc"), + (namespaces["svg"], "title"), +]) + +formattingElements = frozenset([ + (namespaces["html"], "a"), + (namespaces["html"], "b"), + (namespaces["html"], "big"), + (namespaces["html"], "code"), + (namespaces["html"], "em"), + (namespaces["html"], "font"), + (namespaces["html"], "i"), + (namespaces["html"], "nobr"), + (namespaces["html"], "s"), + (namespaces["html"], "small"), + (namespaces["html"], "strike"), + (namespaces["html"], "strong"), + (namespaces["html"], "tt"), + (namespaces["html"], "u") +]) + +specialElements = frozenset([ + (namespaces["html"], "address"), + (namespaces["html"], "applet"), + (namespaces["html"], "area"), + (namespaces["html"], "article"), + (namespaces["html"], "aside"), + (namespaces["html"], "base"), + (namespaces["html"], "basefont"), + (namespaces["html"], "bgsound"), + (namespaces["html"], "blockquote"), + (namespaces["html"], "body"), + (namespaces["html"], "br"), + (namespaces["html"], "button"), + (namespaces["html"], "caption"), + (namespaces["html"], "center"), + (namespaces["html"], "col"), + (namespaces["html"], "colgroup"), + (namespaces["html"], "command"), + (namespaces["html"], "dd"), + (namespaces["html"], "details"), + (namespaces["html"], "dir"), + (namespaces["html"], "div"), + (namespaces["html"], "dl"), + (namespaces["html"], "dt"), + (namespaces["html"], "embed"), + (namespaces["html"], "fieldset"), + (namespaces["html"], "figure"), + (namespaces["html"], "footer"), + (namespaces["html"], "form"), + (namespaces["html"], "frame"), + (namespaces["html"], "frameset"), + (namespaces["html"], "h1"), + (namespaces["html"], "h2"), + (namespaces["html"], "h3"), + (namespaces["html"], "h4"), + (namespaces["html"], "h5"), + (namespaces["html"], "h6"), + (namespaces["html"], "head"), + (namespaces["html"], "header"), + (namespaces["html"], "hr"), + (namespaces["html"], "html"), + (namespaces["html"], "iframe"), + # Note that image is commented out in the spec as "this isn't an + # element that can end up on the stack, so it doesn't matter," + (namespaces["html"], "image"), + (namespaces["html"], "img"), + (namespaces["html"], "input"), + (namespaces["html"], "isindex"), + (namespaces["html"], "li"), + (namespaces["html"], "link"), + (namespaces["html"], "listing"), + (namespaces["html"], "marquee"), + (namespaces["html"], "menu"), + (namespaces["html"], "meta"), + (namespaces["html"], "nav"), + (namespaces["html"], "noembed"), + (namespaces["html"], "noframes"), + (namespaces["html"], "noscript"), + (namespaces["html"], "object"), + (namespaces["html"], "ol"), + (namespaces["html"], "p"), + (namespaces["html"], "param"), + (namespaces["html"], "plaintext"), + (namespaces["html"], "pre"), + (namespaces["html"], "script"), + (namespaces["html"], "section"), + (namespaces["html"], "select"), + (namespaces["html"], "style"), + (namespaces["html"], "table"), + (namespaces["html"], "tbody"), + (namespaces["html"], "td"), + (namespaces["html"], "textarea"), + (namespaces["html"], "tfoot"), + (namespaces["html"], "th"), + (namespaces["html"], "thead"), + (namespaces["html"], "title"), + (namespaces["html"], "tr"), + (namespaces["html"], "ul"), + (namespaces["html"], "wbr"), + (namespaces["html"], "xmp"), + (namespaces["svg"], "foreignObject") +]) + +htmlIntegrationPointElements = frozenset([ + (namespaces["mathml"], "annotation-xml"), + (namespaces["svg"], "foreignObject"), + (namespaces["svg"], "desc"), + (namespaces["svg"], "title") +]) + +mathmlTextIntegrationPointElements = frozenset([ + (namespaces["mathml"], "mi"), + (namespaces["mathml"], "mo"), + (namespaces["mathml"], "mn"), + (namespaces["mathml"], "ms"), + (namespaces["mathml"], "mtext") +]) + +adjustSVGAttributes = { + "attributename": "attributeName", + "attributetype": "attributeType", + "basefrequency": "baseFrequency", + "baseprofile": "baseProfile", + "calcmode": "calcMode", + "clippathunits": "clipPathUnits", + "contentscripttype": "contentScriptType", + "contentstyletype": "contentStyleType", + "diffuseconstant": "diffuseConstant", + "edgemode": "edgeMode", + "externalresourcesrequired": "externalResourcesRequired", + "filterres": "filterRes", + "filterunits": "filterUnits", + "glyphref": "glyphRef", + "gradienttransform": "gradientTransform", + "gradientunits": "gradientUnits", + "kernelmatrix": "kernelMatrix", + "kernelunitlength": "kernelUnitLength", + "keypoints": "keyPoints", + "keysplines": "keySplines", + "keytimes": "keyTimes", + "lengthadjust": "lengthAdjust", + "limitingconeangle": "limitingConeAngle", + "markerheight": "markerHeight", + "markerunits": "markerUnits", + "markerwidth": "markerWidth", + "maskcontentunits": "maskContentUnits", + "maskunits": "maskUnits", + "numoctaves": "numOctaves", + "pathlength": "pathLength", + "patterncontentunits": "patternContentUnits", + "patterntransform": "patternTransform", + "patternunits": "patternUnits", + "pointsatx": "pointsAtX", + "pointsaty": "pointsAtY", + "pointsatz": "pointsAtZ", + "preservealpha": "preserveAlpha", + "preserveaspectratio": "preserveAspectRatio", + "primitiveunits": "primitiveUnits", + "refx": "refX", + "refy": "refY", + "repeatcount": "repeatCount", + "repeatdur": "repeatDur", + "requiredextensions": "requiredExtensions", + "requiredfeatures": "requiredFeatures", + "specularconstant": "specularConstant", + "specularexponent": "specularExponent", + "spreadmethod": "spreadMethod", + "startoffset": "startOffset", + "stddeviation": "stdDeviation", + "stitchtiles": "stitchTiles", + "surfacescale": "surfaceScale", + "systemlanguage": "systemLanguage", + "tablevalues": "tableValues", + "targetx": "targetX", + "targety": "targetY", + "textlength": "textLength", + "viewbox": "viewBox", + "viewtarget": "viewTarget", + "xchannelselector": "xChannelSelector", + "ychannelselector": "yChannelSelector", + "zoomandpan": "zoomAndPan" +} + +adjustMathMLAttributes = {"definitionurl": "definitionURL"} + +adjustForeignAttributes = { + "xlink:actuate": ("xlink", "actuate", namespaces["xlink"]), + "xlink:arcrole": ("xlink", "arcrole", namespaces["xlink"]), + "xlink:href": ("xlink", "href", namespaces["xlink"]), + "xlink:role": ("xlink", "role", namespaces["xlink"]), + "xlink:show": ("xlink", "show", namespaces["xlink"]), + "xlink:title": ("xlink", "title", namespaces["xlink"]), + "xlink:type": ("xlink", "type", namespaces["xlink"]), + "xml:base": ("xml", "base", namespaces["xml"]), + "xml:lang": ("xml", "lang", namespaces["xml"]), + "xml:space": ("xml", "space", namespaces["xml"]), + "xmlns": (None, "xmlns", namespaces["xmlns"]), + "xmlns:xlink": ("xmlns", "xlink", namespaces["xmlns"]) +} + +unadjustForeignAttributes = {(ns, local): qname for qname, (prefix, local, ns) in + adjustForeignAttributes.items()} + +spaceCharacters = frozenset([ + "\t", + "\n", + "\u000C", + " ", + "\r" +]) + +tableInsertModeElements = frozenset([ + "table", + "tbody", + "tfoot", + "thead", + "tr" +]) + +asciiLowercase = frozenset(string.ascii_lowercase) +asciiUppercase = frozenset(string.ascii_uppercase) +asciiLetters = frozenset(string.ascii_letters) +digits = frozenset(string.digits) +hexDigits = frozenset(string.hexdigits) + +asciiUpper2Lower = {ord(c): ord(c.lower()) for c in string.ascii_uppercase} + +# Heading elements need to be ordered +headingElements = ( + "h1", + "h2", + "h3", + "h4", + "h5", + "h6" +) + +voidElements = frozenset([ + "base", + "command", + "event-source", + "link", + "meta", + "hr", + "br", + "img", + "embed", + "param", + "area", + "col", + "input", + "source", + "track" +]) + +cdataElements = frozenset(['title', 'textarea']) + +rcdataElements = frozenset([ + 'style', + 'script', + 'xmp', + 'iframe', + 'noembed', + 'noframes', + 'noscript' +]) + +booleanAttributes = { + "": frozenset(["irrelevant", "itemscope"]), + "style": frozenset(["scoped"]), + "img": frozenset(["ismap"]), + "audio": frozenset(["autoplay", "controls"]), + "video": frozenset(["autoplay", "controls"]), + "script": frozenset(["defer", "async"]), + "details": frozenset(["open"]), + "datagrid": frozenset(["multiple", "disabled"]), + "command": frozenset(["hidden", "disabled", "checked", "default"]), + "hr": frozenset(["noshade"]), + "menu": frozenset(["autosubmit"]), + "fieldset": frozenset(["disabled", "readonly"]), + "option": frozenset(["disabled", "readonly", "selected"]), + "optgroup": frozenset(["disabled", "readonly"]), + "button": frozenset(["disabled", "autofocus"]), + "input": frozenset(["disabled", "readonly", "required", "autofocus", "checked", "ismap"]), + "select": frozenset(["disabled", "readonly", "autofocus", "multiple"]), + "output": frozenset(["disabled", "readonly"]), + "iframe": frozenset(["seamless"]), +} + +# entitiesWindows1252 has to be _ordered_ and needs to have an index. It +# therefore can't be a frozenset. +entitiesWindows1252 = ( + 8364, # 0x80 0x20AC EURO SIGN + 65533, # 0x81 UNDEFINED + 8218, # 0x82 0x201A SINGLE LOW-9 QUOTATION MARK + 402, # 0x83 0x0192 LATIN SMALL LETTER F WITH HOOK + 8222, # 0x84 0x201E DOUBLE LOW-9 QUOTATION MARK + 8230, # 0x85 0x2026 HORIZONTAL ELLIPSIS + 8224, # 0x86 0x2020 DAGGER + 8225, # 0x87 0x2021 DOUBLE DAGGER + 710, # 0x88 0x02C6 MODIFIER LETTER CIRCUMFLEX ACCENT + 8240, # 0x89 0x2030 PER MILLE SIGN + 352, # 0x8A 0x0160 LATIN CAPITAL LETTER S WITH CARON + 8249, # 0x8B 0x2039 SINGLE LEFT-POINTING ANGLE QUOTATION MARK + 338, # 0x8C 0x0152 LATIN CAPITAL LIGATURE OE + 65533, # 0x8D UNDEFINED + 381, # 0x8E 0x017D LATIN CAPITAL LETTER Z WITH CARON + 65533, # 0x8F UNDEFINED + 65533, # 0x90 UNDEFINED + 8216, # 0x91 0x2018 LEFT SINGLE QUOTATION MARK + 8217, # 0x92 0x2019 RIGHT SINGLE QUOTATION MARK + 8220, # 0x93 0x201C LEFT DOUBLE QUOTATION MARK + 8221, # 0x94 0x201D RIGHT DOUBLE QUOTATION MARK + 8226, # 0x95 0x2022 BULLET + 8211, # 0x96 0x2013 EN DASH + 8212, # 0x97 0x2014 EM DASH + 732, # 0x98 0x02DC SMALL TILDE + 8482, # 0x99 0x2122 TRADE MARK SIGN + 353, # 0x9A 0x0161 LATIN SMALL LETTER S WITH CARON + 8250, # 0x9B 0x203A SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + 339, # 0x9C 0x0153 LATIN SMALL LIGATURE OE + 65533, # 0x9D UNDEFINED + 382, # 0x9E 0x017E LATIN SMALL LETTER Z WITH CARON + 376 # 0x9F 0x0178 LATIN CAPITAL LETTER Y WITH DIAERESIS +) + +xmlEntities = frozenset(['lt;', 'gt;', 'amp;', 'apos;', 'quot;']) + +entities = { + "AElig": "\xc6", + "AElig;": "\xc6", + "AMP": "&", + "AMP;": "&", + "Aacute": "\xc1", + "Aacute;": "\xc1", + "Abreve;": "\u0102", + "Acirc": "\xc2", + "Acirc;": "\xc2", + "Acy;": "\u0410", + "Afr;": "\U0001d504", + "Agrave": "\xc0", + "Agrave;": "\xc0", + "Alpha;": "\u0391", + "Amacr;": "\u0100", + "And;": "\u2a53", + "Aogon;": "\u0104", + "Aopf;": "\U0001d538", + "ApplyFunction;": "\u2061", + "Aring": "\xc5", + "Aring;": "\xc5", + "Ascr;": "\U0001d49c", + "Assign;": "\u2254", + "Atilde": "\xc3", + "Atilde;": "\xc3", + "Auml": "\xc4", + "Auml;": "\xc4", + "Backslash;": "\u2216", + "Barv;": "\u2ae7", + "Barwed;": "\u2306", + "Bcy;": "\u0411", + "Because;": "\u2235", + "Bernoullis;": "\u212c", + "Beta;": "\u0392", + "Bfr;": "\U0001d505", + "Bopf;": "\U0001d539", + "Breve;": "\u02d8", + "Bscr;": "\u212c", + "Bumpeq;": "\u224e", + "CHcy;": "\u0427", + "COPY": "\xa9", + "COPY;": "\xa9", + "Cacute;": "\u0106", + "Cap;": "\u22d2", + "CapitalDifferentialD;": "\u2145", + "Cayleys;": "\u212d", + "Ccaron;": "\u010c", + "Ccedil": "\xc7", + "Ccedil;": "\xc7", + "Ccirc;": "\u0108", + "Cconint;": "\u2230", + "Cdot;": "\u010a", + "Cedilla;": "\xb8", + "CenterDot;": "\xb7", + "Cfr;": "\u212d", + "Chi;": "\u03a7", + "CircleDot;": "\u2299", + "CircleMinus;": "\u2296", + "CirclePlus;": "\u2295", + "CircleTimes;": "\u2297", + "ClockwiseContourIntegral;": "\u2232", + "CloseCurlyDoubleQuote;": "\u201d", + "CloseCurlyQuote;": "\u2019", + "Colon;": "\u2237", + "Colone;": "\u2a74", + "Congruent;": "\u2261", + "Conint;": "\u222f", + "ContourIntegral;": "\u222e", + "Copf;": "\u2102", + "Coproduct;": "\u2210", + "CounterClockwiseContourIntegral;": "\u2233", + "Cross;": "\u2a2f", + "Cscr;": "\U0001d49e", + "Cup;": "\u22d3", + "CupCap;": "\u224d", + "DD;": "\u2145", + "DDotrahd;": "\u2911", + "DJcy;": "\u0402", + "DScy;": "\u0405", + "DZcy;": "\u040f", + "Dagger;": "\u2021", + "Darr;": "\u21a1", + "Dashv;": "\u2ae4", + "Dcaron;": "\u010e", + "Dcy;": "\u0414", + "Del;": "\u2207", + "Delta;": "\u0394", + "Dfr;": "\U0001d507", + "DiacriticalAcute;": "\xb4", + "DiacriticalDot;": "\u02d9", + "DiacriticalDoubleAcute;": "\u02dd", + "DiacriticalGrave;": "`", + "DiacriticalTilde;": "\u02dc", + "Diamond;": "\u22c4", + "DifferentialD;": "\u2146", + "Dopf;": "\U0001d53b", + "Dot;": "\xa8", + "DotDot;": "\u20dc", + "DotEqual;": "\u2250", + "DoubleContourIntegral;": "\u222f", + "DoubleDot;": "\xa8", + "DoubleDownArrow;": "\u21d3", + "DoubleLeftArrow;": "\u21d0", + "DoubleLeftRightArrow;": "\u21d4", + "DoubleLeftTee;": "\u2ae4", + "DoubleLongLeftArrow;": "\u27f8", + "DoubleLongLeftRightArrow;": "\u27fa", + "DoubleLongRightArrow;": "\u27f9", + "DoubleRightArrow;": "\u21d2", + "DoubleRightTee;": "\u22a8", + "DoubleUpArrow;": "\u21d1", + "DoubleUpDownArrow;": "\u21d5", + "DoubleVerticalBar;": "\u2225", + "DownArrow;": "\u2193", + "DownArrowBar;": "\u2913", + "DownArrowUpArrow;": "\u21f5", + "DownBreve;": "\u0311", + "DownLeftRightVector;": "\u2950", + "DownLeftTeeVector;": "\u295e", + "DownLeftVector;": "\u21bd", + "DownLeftVectorBar;": "\u2956", + "DownRightTeeVector;": "\u295f", + "DownRightVector;": "\u21c1", + "DownRightVectorBar;": "\u2957", + "DownTee;": "\u22a4", + "DownTeeArrow;": "\u21a7", + "Downarrow;": "\u21d3", + "Dscr;": "\U0001d49f", + "Dstrok;": "\u0110", + "ENG;": "\u014a", + "ETH": "\xd0", + "ETH;": "\xd0", + "Eacute": "\xc9", + "Eacute;": "\xc9", + "Ecaron;": "\u011a", + "Ecirc": "\xca", + "Ecirc;": "\xca", + "Ecy;": "\u042d", + "Edot;": "\u0116", + "Efr;": "\U0001d508", + "Egrave": "\xc8", + "Egrave;": "\xc8", + "Element;": "\u2208", + "Emacr;": "\u0112", + "EmptySmallSquare;": "\u25fb", + "EmptyVerySmallSquare;": "\u25ab", + "Eogon;": "\u0118", + "Eopf;": "\U0001d53c", + "Epsilon;": "\u0395", + "Equal;": "\u2a75", + "EqualTilde;": "\u2242", + "Equilibrium;": "\u21cc", + "Escr;": "\u2130", + "Esim;": "\u2a73", + "Eta;": "\u0397", + "Euml": "\xcb", + "Euml;": "\xcb", + "Exists;": "\u2203", + "ExponentialE;": "\u2147", + "Fcy;": "\u0424", + "Ffr;": "\U0001d509", + "FilledSmallSquare;": "\u25fc", + "FilledVerySmallSquare;": "\u25aa", + "Fopf;": "\U0001d53d", + "ForAll;": "\u2200", + "Fouriertrf;": "\u2131", + "Fscr;": "\u2131", + "GJcy;": "\u0403", + "GT": ">", + "GT;": ">", + "Gamma;": "\u0393", + "Gammad;": "\u03dc", + "Gbreve;": "\u011e", + "Gcedil;": "\u0122", + "Gcirc;": "\u011c", + "Gcy;": "\u0413", + "Gdot;": "\u0120", + "Gfr;": "\U0001d50a", + "Gg;": "\u22d9", + "Gopf;": "\U0001d53e", + "GreaterEqual;": "\u2265", + "GreaterEqualLess;": "\u22db", + "GreaterFullEqual;": "\u2267", + "GreaterGreater;": "\u2aa2", + "GreaterLess;": "\u2277", + "GreaterSlantEqual;": "\u2a7e", + "GreaterTilde;": "\u2273", + "Gscr;": "\U0001d4a2", + "Gt;": "\u226b", + "HARDcy;": "\u042a", + "Hacek;": "\u02c7", + "Hat;": "^", + "Hcirc;": "\u0124", + "Hfr;": "\u210c", + "HilbertSpace;": "\u210b", + "Hopf;": "\u210d", + "HorizontalLine;": "\u2500", + "Hscr;": "\u210b", + "Hstrok;": "\u0126", + "HumpDownHump;": "\u224e", + "HumpEqual;": "\u224f", + "IEcy;": "\u0415", + "IJlig;": "\u0132", + "IOcy;": "\u0401", + "Iacute": "\xcd", + "Iacute;": "\xcd", + "Icirc": "\xce", + "Icirc;": "\xce", + "Icy;": "\u0418", + "Idot;": "\u0130", + "Ifr;": "\u2111", + "Igrave": "\xcc", + "Igrave;": "\xcc", + "Im;": "\u2111", + "Imacr;": "\u012a", + "ImaginaryI;": "\u2148", + "Implies;": "\u21d2", + "Int;": "\u222c", + "Integral;": "\u222b", + "Intersection;": "\u22c2", + "InvisibleComma;": "\u2063", + "InvisibleTimes;": "\u2062", + "Iogon;": "\u012e", + "Iopf;": "\U0001d540", + "Iota;": "\u0399", + "Iscr;": "\u2110", + "Itilde;": "\u0128", + "Iukcy;": "\u0406", + "Iuml": "\xcf", + "Iuml;": "\xcf", + "Jcirc;": "\u0134", + "Jcy;": "\u0419", + "Jfr;": "\U0001d50d", + "Jopf;": "\U0001d541", + "Jscr;": "\U0001d4a5", + "Jsercy;": "\u0408", + "Jukcy;": "\u0404", + "KHcy;": "\u0425", + "KJcy;": "\u040c", + "Kappa;": "\u039a", + "Kcedil;": "\u0136", + "Kcy;": "\u041a", + "Kfr;": "\U0001d50e", + "Kopf;": "\U0001d542", + "Kscr;": "\U0001d4a6", + "LJcy;": "\u0409", + "LT": "<", + "LT;": "<", + "Lacute;": "\u0139", + "Lambda;": "\u039b", + "Lang;": "\u27ea", + "Laplacetrf;": "\u2112", + "Larr;": "\u219e", + "Lcaron;": "\u013d", + "Lcedil;": "\u013b", + "Lcy;": "\u041b", + "LeftAngleBracket;": "\u27e8", + "LeftArrow;": "\u2190", + "LeftArrowBar;": "\u21e4", + "LeftArrowRightArrow;": "\u21c6", + "LeftCeiling;": "\u2308", + "LeftDoubleBracket;": "\u27e6", + "LeftDownTeeVector;": "\u2961", + "LeftDownVector;": "\u21c3", + "LeftDownVectorBar;": "\u2959", + "LeftFloor;": "\u230a", + "LeftRightArrow;": "\u2194", + "LeftRightVector;": "\u294e", + "LeftTee;": "\u22a3", + "LeftTeeArrow;": "\u21a4", + "LeftTeeVector;": "\u295a", + "LeftTriangle;": "\u22b2", + "LeftTriangleBar;": "\u29cf", + "LeftTriangleEqual;": "\u22b4", + "LeftUpDownVector;": "\u2951", + "LeftUpTeeVector;": "\u2960", + "LeftUpVector;": "\u21bf", + "LeftUpVectorBar;": "\u2958", + "LeftVector;": "\u21bc", + "LeftVectorBar;": "\u2952", + "Leftarrow;": "\u21d0", + "Leftrightarrow;": "\u21d4", + "LessEqualGreater;": "\u22da", + "LessFullEqual;": "\u2266", + "LessGreater;": "\u2276", + "LessLess;": "\u2aa1", + "LessSlantEqual;": "\u2a7d", + "LessTilde;": "\u2272", + "Lfr;": "\U0001d50f", + "Ll;": "\u22d8", + "Lleftarrow;": "\u21da", + "Lmidot;": "\u013f", + "LongLeftArrow;": "\u27f5", + "LongLeftRightArrow;": "\u27f7", + "LongRightArrow;": "\u27f6", + "Longleftarrow;": "\u27f8", + "Longleftrightarrow;": "\u27fa", + "Longrightarrow;": "\u27f9", + "Lopf;": "\U0001d543", + "LowerLeftArrow;": "\u2199", + "LowerRightArrow;": "\u2198", + "Lscr;": "\u2112", + "Lsh;": "\u21b0", + "Lstrok;": "\u0141", + "Lt;": "\u226a", + "Map;": "\u2905", + "Mcy;": "\u041c", + "MediumSpace;": "\u205f", + "Mellintrf;": "\u2133", + "Mfr;": "\U0001d510", + "MinusPlus;": "\u2213", + "Mopf;": "\U0001d544", + "Mscr;": "\u2133", + "Mu;": "\u039c", + "NJcy;": "\u040a", + "Nacute;": "\u0143", + "Ncaron;": "\u0147", + "Ncedil;": "\u0145", + "Ncy;": "\u041d", + "NegativeMediumSpace;": "\u200b", + "NegativeThickSpace;": "\u200b", + "NegativeThinSpace;": "\u200b", + "NegativeVeryThinSpace;": "\u200b", + "NestedGreaterGreater;": "\u226b", + "NestedLessLess;": "\u226a", + "NewLine;": "\n", + "Nfr;": "\U0001d511", + "NoBreak;": "\u2060", + "NonBreakingSpace;": "\xa0", + "Nopf;": "\u2115", + "Not;": "\u2aec", + "NotCongruent;": "\u2262", + "NotCupCap;": "\u226d", + "NotDoubleVerticalBar;": "\u2226", + "NotElement;": "\u2209", + "NotEqual;": "\u2260", + "NotEqualTilde;": "\u2242\u0338", + "NotExists;": "\u2204", + "NotGreater;": "\u226f", + "NotGreaterEqual;": "\u2271", + "NotGreaterFullEqual;": "\u2267\u0338", + "NotGreaterGreater;": "\u226b\u0338", + "NotGreaterLess;": "\u2279", + "NotGreaterSlantEqual;": "\u2a7e\u0338", + "NotGreaterTilde;": "\u2275", + "NotHumpDownHump;": "\u224e\u0338", + "NotHumpEqual;": "\u224f\u0338", + "NotLeftTriangle;": "\u22ea", + "NotLeftTriangleBar;": "\u29cf\u0338", + "NotLeftTriangleEqual;": "\u22ec", + "NotLess;": "\u226e", + "NotLessEqual;": "\u2270", + "NotLessGreater;": "\u2278", + "NotLessLess;": "\u226a\u0338", + "NotLessSlantEqual;": "\u2a7d\u0338", + "NotLessTilde;": "\u2274", + "NotNestedGreaterGreater;": "\u2aa2\u0338", + "NotNestedLessLess;": "\u2aa1\u0338", + "NotPrecedes;": "\u2280", + "NotPrecedesEqual;": "\u2aaf\u0338", + "NotPrecedesSlantEqual;": "\u22e0", + "NotReverseElement;": "\u220c", + "NotRightTriangle;": "\u22eb", + "NotRightTriangleBar;": "\u29d0\u0338", + "NotRightTriangleEqual;": "\u22ed", + "NotSquareSubset;": "\u228f\u0338", + "NotSquareSubsetEqual;": "\u22e2", + "NotSquareSuperset;": "\u2290\u0338", + "NotSquareSupersetEqual;": "\u22e3", + "NotSubset;": "\u2282\u20d2", + "NotSubsetEqual;": "\u2288", + "NotSucceeds;": "\u2281", + "NotSucceedsEqual;": "\u2ab0\u0338", + "NotSucceedsSlantEqual;": "\u22e1", + "NotSucceedsTilde;": "\u227f\u0338", + "NotSuperset;": "\u2283\u20d2", + "NotSupersetEqual;": "\u2289", + "NotTilde;": "\u2241", + "NotTildeEqual;": "\u2244", + "NotTildeFullEqual;": "\u2247", + "NotTildeTilde;": "\u2249", + "NotVerticalBar;": "\u2224", + "Nscr;": "\U0001d4a9", + "Ntilde": "\xd1", + "Ntilde;": "\xd1", + "Nu;": "\u039d", + "OElig;": "\u0152", + "Oacute": "\xd3", + "Oacute;": "\xd3", + "Ocirc": "\xd4", + "Ocirc;": "\xd4", + "Ocy;": "\u041e", + "Odblac;": "\u0150", + "Ofr;": "\U0001d512", + "Ograve": "\xd2", + "Ograve;": "\xd2", + "Omacr;": "\u014c", + "Omega;": "\u03a9", + "Omicron;": "\u039f", + "Oopf;": "\U0001d546", + "OpenCurlyDoubleQuote;": "\u201c", + "OpenCurlyQuote;": "\u2018", + "Or;": "\u2a54", + "Oscr;": "\U0001d4aa", + "Oslash": "\xd8", + "Oslash;": "\xd8", + "Otilde": "\xd5", + "Otilde;": "\xd5", + "Otimes;": "\u2a37", + "Ouml": "\xd6", + "Ouml;": "\xd6", + "OverBar;": "\u203e", + "OverBrace;": "\u23de", + "OverBracket;": "\u23b4", + "OverParenthesis;": "\u23dc", + "PartialD;": "\u2202", + "Pcy;": "\u041f", + "Pfr;": "\U0001d513", + "Phi;": "\u03a6", + "Pi;": "\u03a0", + "PlusMinus;": "\xb1", + "Poincareplane;": "\u210c", + "Popf;": "\u2119", + "Pr;": "\u2abb", + "Precedes;": "\u227a", + "PrecedesEqual;": "\u2aaf", + "PrecedesSlantEqual;": "\u227c", + "PrecedesTilde;": "\u227e", + "Prime;": "\u2033", + "Product;": "\u220f", + "Proportion;": "\u2237", + "Proportional;": "\u221d", + "Pscr;": "\U0001d4ab", + "Psi;": "\u03a8", + "QUOT": "\"", + "QUOT;": "\"", + "Qfr;": "\U0001d514", + "Qopf;": "\u211a", + "Qscr;": "\U0001d4ac", + "RBarr;": "\u2910", + "REG": "\xae", + "REG;": "\xae", + "Racute;": "\u0154", + "Rang;": "\u27eb", + "Rarr;": "\u21a0", + "Rarrtl;": "\u2916", + "Rcaron;": "\u0158", + "Rcedil;": "\u0156", + "Rcy;": "\u0420", + "Re;": "\u211c", + "ReverseElement;": "\u220b", + "ReverseEquilibrium;": "\u21cb", + "ReverseUpEquilibrium;": "\u296f", + "Rfr;": "\u211c", + "Rho;": "\u03a1", + "RightAngleBracket;": "\u27e9", + "RightArrow;": "\u2192", + "RightArrowBar;": "\u21e5", + "RightArrowLeftArrow;": "\u21c4", + "RightCeiling;": "\u2309", + "RightDoubleBracket;": "\u27e7", + "RightDownTeeVector;": "\u295d", + "RightDownVector;": "\u21c2", + "RightDownVectorBar;": "\u2955", + "RightFloor;": "\u230b", + "RightTee;": "\u22a2", + "RightTeeArrow;": "\u21a6", + "RightTeeVector;": "\u295b", + "RightTriangle;": "\u22b3", + "RightTriangleBar;": "\u29d0", + "RightTriangleEqual;": "\u22b5", + "RightUpDownVector;": "\u294f", + "RightUpTeeVector;": "\u295c", + "RightUpVector;": "\u21be", + "RightUpVectorBar;": "\u2954", + "RightVector;": "\u21c0", + "RightVectorBar;": "\u2953", + "Rightarrow;": "\u21d2", + "Ropf;": "\u211d", + "RoundImplies;": "\u2970", + "Rrightarrow;": "\u21db", + "Rscr;": "\u211b", + "Rsh;": "\u21b1", + "RuleDelayed;": "\u29f4", + "SHCHcy;": "\u0429", + "SHcy;": "\u0428", + "SOFTcy;": "\u042c", + "Sacute;": "\u015a", + "Sc;": "\u2abc", + "Scaron;": "\u0160", + "Scedil;": "\u015e", + "Scirc;": "\u015c", + "Scy;": "\u0421", + "Sfr;": "\U0001d516", + "ShortDownArrow;": "\u2193", + "ShortLeftArrow;": "\u2190", + "ShortRightArrow;": "\u2192", + "ShortUpArrow;": "\u2191", + "Sigma;": "\u03a3", + "SmallCircle;": "\u2218", + "Sopf;": "\U0001d54a", + "Sqrt;": "\u221a", + "Square;": "\u25a1", + "SquareIntersection;": "\u2293", + "SquareSubset;": "\u228f", + "SquareSubsetEqual;": "\u2291", + "SquareSuperset;": "\u2290", + "SquareSupersetEqual;": "\u2292", + "SquareUnion;": "\u2294", + "Sscr;": "\U0001d4ae", + "Star;": "\u22c6", + "Sub;": "\u22d0", + "Subset;": "\u22d0", + "SubsetEqual;": "\u2286", + "Succeeds;": "\u227b", + "SucceedsEqual;": "\u2ab0", + "SucceedsSlantEqual;": "\u227d", + "SucceedsTilde;": "\u227f", + "SuchThat;": "\u220b", + "Sum;": "\u2211", + "Sup;": "\u22d1", + "Superset;": "\u2283", + "SupersetEqual;": "\u2287", + "Supset;": "\u22d1", + "THORN": "\xde", + "THORN;": "\xde", + "TRADE;": "\u2122", + "TSHcy;": "\u040b", + "TScy;": "\u0426", + "Tab;": "\t", + "Tau;": "\u03a4", + "Tcaron;": "\u0164", + "Tcedil;": "\u0162", + "Tcy;": "\u0422", + "Tfr;": "\U0001d517", + "Therefore;": "\u2234", + "Theta;": "\u0398", + "ThickSpace;": "\u205f\u200a", + "ThinSpace;": "\u2009", + "Tilde;": "\u223c", + "TildeEqual;": "\u2243", + "TildeFullEqual;": "\u2245", + "TildeTilde;": "\u2248", + "Topf;": "\U0001d54b", + "TripleDot;": "\u20db", + "Tscr;": "\U0001d4af", + "Tstrok;": "\u0166", + "Uacute": "\xda", + "Uacute;": "\xda", + "Uarr;": "\u219f", + "Uarrocir;": "\u2949", + "Ubrcy;": "\u040e", + "Ubreve;": "\u016c", + "Ucirc": "\xdb", + "Ucirc;": "\xdb", + "Ucy;": "\u0423", + "Udblac;": "\u0170", + "Ufr;": "\U0001d518", + "Ugrave": "\xd9", + "Ugrave;": "\xd9", + "Umacr;": "\u016a", + "UnderBar;": "_", + "UnderBrace;": "\u23df", + "UnderBracket;": "\u23b5", + "UnderParenthesis;": "\u23dd", + "Union;": "\u22c3", + "UnionPlus;": "\u228e", + "Uogon;": "\u0172", + "Uopf;": "\U0001d54c", + "UpArrow;": "\u2191", + "UpArrowBar;": "\u2912", + "UpArrowDownArrow;": "\u21c5", + "UpDownArrow;": "\u2195", + "UpEquilibrium;": "\u296e", + "UpTee;": "\u22a5", + "UpTeeArrow;": "\u21a5", + "Uparrow;": "\u21d1", + "Updownarrow;": "\u21d5", + "UpperLeftArrow;": "\u2196", + "UpperRightArrow;": "\u2197", + "Upsi;": "\u03d2", + "Upsilon;": "\u03a5", + "Uring;": "\u016e", + "Uscr;": "\U0001d4b0", + "Utilde;": "\u0168", + "Uuml": "\xdc", + "Uuml;": "\xdc", + "VDash;": "\u22ab", + "Vbar;": "\u2aeb", + "Vcy;": "\u0412", + "Vdash;": "\u22a9", + "Vdashl;": "\u2ae6", + "Vee;": "\u22c1", + "Verbar;": "\u2016", + "Vert;": "\u2016", + "VerticalBar;": "\u2223", + "VerticalLine;": "|", + "VerticalSeparator;": "\u2758", + "VerticalTilde;": "\u2240", + "VeryThinSpace;": "\u200a", + "Vfr;": "\U0001d519", + "Vopf;": "\U0001d54d", + "Vscr;": "\U0001d4b1", + "Vvdash;": "\u22aa", + "Wcirc;": "\u0174", + "Wedge;": "\u22c0", + "Wfr;": "\U0001d51a", + "Wopf;": "\U0001d54e", + "Wscr;": "\U0001d4b2", + "Xfr;": "\U0001d51b", + "Xi;": "\u039e", + "Xopf;": "\U0001d54f", + "Xscr;": "\U0001d4b3", + "YAcy;": "\u042f", + "YIcy;": "\u0407", + "YUcy;": "\u042e", + "Yacute": "\xdd", + "Yacute;": "\xdd", + "Ycirc;": "\u0176", + "Ycy;": "\u042b", + "Yfr;": "\U0001d51c", + "Yopf;": "\U0001d550", + "Yscr;": "\U0001d4b4", + "Yuml;": "\u0178", + "ZHcy;": "\u0416", + "Zacute;": "\u0179", + "Zcaron;": "\u017d", + "Zcy;": "\u0417", + "Zdot;": "\u017b", + "ZeroWidthSpace;": "\u200b", + "Zeta;": "\u0396", + "Zfr;": "\u2128", + "Zopf;": "\u2124", + "Zscr;": "\U0001d4b5", + "aacute": "\xe1", + "aacute;": "\xe1", + "abreve;": "\u0103", + "ac;": "\u223e", + "acE;": "\u223e\u0333", + "acd;": "\u223f", + "acirc": "\xe2", + "acirc;": "\xe2", + "acute": "\xb4", + "acute;": "\xb4", + "acy;": "\u0430", + "aelig": "\xe6", + "aelig;": "\xe6", + "af;": "\u2061", + "afr;": "\U0001d51e", + "agrave": "\xe0", + "agrave;": "\xe0", + "alefsym;": "\u2135", + "aleph;": "\u2135", + "alpha;": "\u03b1", + "amacr;": "\u0101", + "amalg;": "\u2a3f", + "amp": "&", + "amp;": "&", + "and;": "\u2227", + "andand;": "\u2a55", + "andd;": "\u2a5c", + "andslope;": "\u2a58", + "andv;": "\u2a5a", + "ang;": "\u2220", + "ange;": "\u29a4", + "angle;": "\u2220", + "angmsd;": "\u2221", + "angmsdaa;": "\u29a8", + "angmsdab;": "\u29a9", + "angmsdac;": "\u29aa", + "angmsdad;": "\u29ab", + "angmsdae;": "\u29ac", + "angmsdaf;": "\u29ad", + "angmsdag;": "\u29ae", + "angmsdah;": "\u29af", + "angrt;": "\u221f", + "angrtvb;": "\u22be", + "angrtvbd;": "\u299d", + "angsph;": "\u2222", + "angst;": "\xc5", + "angzarr;": "\u237c", + "aogon;": "\u0105", + "aopf;": "\U0001d552", + "ap;": "\u2248", + "apE;": "\u2a70", + "apacir;": "\u2a6f", + "ape;": "\u224a", + "apid;": "\u224b", + "apos;": "'", + "approx;": "\u2248", + "approxeq;": "\u224a", + "aring": "\xe5", + "aring;": "\xe5", + "ascr;": "\U0001d4b6", + "ast;": "*", + "asymp;": "\u2248", + "asympeq;": "\u224d", + "atilde": "\xe3", + "atilde;": "\xe3", + "auml": "\xe4", + "auml;": "\xe4", + "awconint;": "\u2233", + "awint;": "\u2a11", + "bNot;": "\u2aed", + "backcong;": "\u224c", + "backepsilon;": "\u03f6", + "backprime;": "\u2035", + "backsim;": "\u223d", + "backsimeq;": "\u22cd", + "barvee;": "\u22bd", + "barwed;": "\u2305", + "barwedge;": "\u2305", + "bbrk;": "\u23b5", + "bbrktbrk;": "\u23b6", + "bcong;": "\u224c", + "bcy;": "\u0431", + "bdquo;": "\u201e", + "becaus;": "\u2235", + "because;": "\u2235", + "bemptyv;": "\u29b0", + "bepsi;": "\u03f6", + "bernou;": "\u212c", + "beta;": "\u03b2", + "beth;": "\u2136", + "between;": "\u226c", + "bfr;": "\U0001d51f", + "bigcap;": "\u22c2", + "bigcirc;": "\u25ef", + "bigcup;": "\u22c3", + "bigodot;": "\u2a00", + "bigoplus;": "\u2a01", + "bigotimes;": "\u2a02", + "bigsqcup;": "\u2a06", + "bigstar;": "\u2605", + "bigtriangledown;": "\u25bd", + "bigtriangleup;": "\u25b3", + "biguplus;": "\u2a04", + "bigvee;": "\u22c1", + "bigwedge;": "\u22c0", + "bkarow;": "\u290d", + "blacklozenge;": "\u29eb", + "blacksquare;": "\u25aa", + "blacktriangle;": "\u25b4", + "blacktriangledown;": "\u25be", + "blacktriangleleft;": "\u25c2", + "blacktriangleright;": "\u25b8", + "blank;": "\u2423", + "blk12;": "\u2592", + "blk14;": "\u2591", + "blk34;": "\u2593", + "block;": "\u2588", + "bne;": "=\u20e5", + "bnequiv;": "\u2261\u20e5", + "bnot;": "\u2310", + "bopf;": "\U0001d553", + "bot;": "\u22a5", + "bottom;": "\u22a5", + "bowtie;": "\u22c8", + "boxDL;": "\u2557", + "boxDR;": "\u2554", + "boxDl;": "\u2556", + "boxDr;": "\u2553", + "boxH;": "\u2550", + "boxHD;": "\u2566", + "boxHU;": "\u2569", + "boxHd;": "\u2564", + "boxHu;": "\u2567", + "boxUL;": "\u255d", + "boxUR;": "\u255a", + "boxUl;": "\u255c", + "boxUr;": "\u2559", + "boxV;": "\u2551", + "boxVH;": "\u256c", + "boxVL;": "\u2563", + "boxVR;": "\u2560", + "boxVh;": "\u256b", + "boxVl;": "\u2562", + "boxVr;": "\u255f", + "boxbox;": "\u29c9", + "boxdL;": "\u2555", + "boxdR;": "\u2552", + "boxdl;": "\u2510", + "boxdr;": "\u250c", + "boxh;": "\u2500", + "boxhD;": "\u2565", + "boxhU;": "\u2568", + "boxhd;": "\u252c", + "boxhu;": "\u2534", + "boxminus;": "\u229f", + "boxplus;": "\u229e", + "boxtimes;": "\u22a0", + "boxuL;": "\u255b", + "boxuR;": "\u2558", + "boxul;": "\u2518", + "boxur;": "\u2514", + "boxv;": "\u2502", + "boxvH;": "\u256a", + "boxvL;": "\u2561", + "boxvR;": "\u255e", + "boxvh;": "\u253c", + "boxvl;": "\u2524", + "boxvr;": "\u251c", + "bprime;": "\u2035", + "breve;": "\u02d8", + "brvbar": "\xa6", + "brvbar;": "\xa6", + "bscr;": "\U0001d4b7", + "bsemi;": "\u204f", + "bsim;": "\u223d", + "bsime;": "\u22cd", + "bsol;": "\\", + "bsolb;": "\u29c5", + "bsolhsub;": "\u27c8", + "bull;": "\u2022", + "bullet;": "\u2022", + "bump;": "\u224e", + "bumpE;": "\u2aae", + "bumpe;": "\u224f", + "bumpeq;": "\u224f", + "cacute;": "\u0107", + "cap;": "\u2229", + "capand;": "\u2a44", + "capbrcup;": "\u2a49", + "capcap;": "\u2a4b", + "capcup;": "\u2a47", + "capdot;": "\u2a40", + "caps;": "\u2229\ufe00", + "caret;": "\u2041", + "caron;": "\u02c7", + "ccaps;": "\u2a4d", + "ccaron;": "\u010d", + "ccedil": "\xe7", + "ccedil;": "\xe7", + "ccirc;": "\u0109", + "ccups;": "\u2a4c", + "ccupssm;": "\u2a50", + "cdot;": "\u010b", + "cedil": "\xb8", + "cedil;": "\xb8", + "cemptyv;": "\u29b2", + "cent": "\xa2", + "cent;": "\xa2", + "centerdot;": "\xb7", + "cfr;": "\U0001d520", + "chcy;": "\u0447", + "check;": "\u2713", + "checkmark;": "\u2713", + "chi;": "\u03c7", + "cir;": "\u25cb", + "cirE;": "\u29c3", + "circ;": "\u02c6", + "circeq;": "\u2257", + "circlearrowleft;": "\u21ba", + "circlearrowright;": "\u21bb", + "circledR;": "\xae", + "circledS;": "\u24c8", + "circledast;": "\u229b", + "circledcirc;": "\u229a", + "circleddash;": "\u229d", + "cire;": "\u2257", + "cirfnint;": "\u2a10", + "cirmid;": "\u2aef", + "cirscir;": "\u29c2", + "clubs;": "\u2663", + "clubsuit;": "\u2663", + "colon;": ":", + "colone;": "\u2254", + "coloneq;": "\u2254", + "comma;": ",", + "commat;": "@", + "comp;": "\u2201", + "compfn;": "\u2218", + "complement;": "\u2201", + "complexes;": "\u2102", + "cong;": "\u2245", + "congdot;": "\u2a6d", + "conint;": "\u222e", + "copf;": "\U0001d554", + "coprod;": "\u2210", + "copy": "\xa9", + "copy;": "\xa9", + "copysr;": "\u2117", + "crarr;": "\u21b5", + "cross;": "\u2717", + "cscr;": "\U0001d4b8", + "csub;": "\u2acf", + "csube;": "\u2ad1", + "csup;": "\u2ad0", + "csupe;": "\u2ad2", + "ctdot;": "\u22ef", + "cudarrl;": "\u2938", + "cudarrr;": "\u2935", + "cuepr;": "\u22de", + "cuesc;": "\u22df", + "cularr;": "\u21b6", + "cularrp;": "\u293d", + "cup;": "\u222a", + "cupbrcap;": "\u2a48", + "cupcap;": "\u2a46", + "cupcup;": "\u2a4a", + "cupdot;": "\u228d", + "cupor;": "\u2a45", + "cups;": "\u222a\ufe00", + "curarr;": "\u21b7", + "curarrm;": "\u293c", + "curlyeqprec;": "\u22de", + "curlyeqsucc;": "\u22df", + "curlyvee;": "\u22ce", + "curlywedge;": "\u22cf", + "curren": "\xa4", + "curren;": "\xa4", + "curvearrowleft;": "\u21b6", + "curvearrowright;": "\u21b7", + "cuvee;": "\u22ce", + "cuwed;": "\u22cf", + "cwconint;": "\u2232", + "cwint;": "\u2231", + "cylcty;": "\u232d", + "dArr;": "\u21d3", + "dHar;": "\u2965", + "dagger;": "\u2020", + "daleth;": "\u2138", + "darr;": "\u2193", + "dash;": "\u2010", + "dashv;": "\u22a3", + "dbkarow;": "\u290f", + "dblac;": "\u02dd", + "dcaron;": "\u010f", + "dcy;": "\u0434", + "dd;": "\u2146", + "ddagger;": "\u2021", + "ddarr;": "\u21ca", + "ddotseq;": "\u2a77", + "deg": "\xb0", + "deg;": "\xb0", + "delta;": "\u03b4", + "demptyv;": "\u29b1", + "dfisht;": "\u297f", + "dfr;": "\U0001d521", + "dharl;": "\u21c3", + "dharr;": "\u21c2", + "diam;": "\u22c4", + "diamond;": "\u22c4", + "diamondsuit;": "\u2666", + "diams;": "\u2666", + "die;": "\xa8", + "digamma;": "\u03dd", + "disin;": "\u22f2", + "div;": "\xf7", + "divide": "\xf7", + "divide;": "\xf7", + "divideontimes;": "\u22c7", + "divonx;": "\u22c7", + "djcy;": "\u0452", + "dlcorn;": "\u231e", + "dlcrop;": "\u230d", + "dollar;": "$", + "dopf;": "\U0001d555", + "dot;": "\u02d9", + "doteq;": "\u2250", + "doteqdot;": "\u2251", + "dotminus;": "\u2238", + "dotplus;": "\u2214", + "dotsquare;": "\u22a1", + "doublebarwedge;": "\u2306", + "downarrow;": "\u2193", + "downdownarrows;": "\u21ca", + "downharpoonleft;": "\u21c3", + "downharpoonright;": "\u21c2", + "drbkarow;": "\u2910", + "drcorn;": "\u231f", + "drcrop;": "\u230c", + "dscr;": "\U0001d4b9", + "dscy;": "\u0455", + "dsol;": "\u29f6", + "dstrok;": "\u0111", + "dtdot;": "\u22f1", + "dtri;": "\u25bf", + "dtrif;": "\u25be", + "duarr;": "\u21f5", + "duhar;": "\u296f", + "dwangle;": "\u29a6", + "dzcy;": "\u045f", + "dzigrarr;": "\u27ff", + "eDDot;": "\u2a77", + "eDot;": "\u2251", + "eacute": "\xe9", + "eacute;": "\xe9", + "easter;": "\u2a6e", + "ecaron;": "\u011b", + "ecir;": "\u2256", + "ecirc": "\xea", + "ecirc;": "\xea", + "ecolon;": "\u2255", + "ecy;": "\u044d", + "edot;": "\u0117", + "ee;": "\u2147", + "efDot;": "\u2252", + "efr;": "\U0001d522", + "eg;": "\u2a9a", + "egrave": "\xe8", + "egrave;": "\xe8", + "egs;": "\u2a96", + "egsdot;": "\u2a98", + "el;": "\u2a99", + "elinters;": "\u23e7", + "ell;": "\u2113", + "els;": "\u2a95", + "elsdot;": "\u2a97", + "emacr;": "\u0113", + "empty;": "\u2205", + "emptyset;": "\u2205", + "emptyv;": "\u2205", + "emsp13;": "\u2004", + "emsp14;": "\u2005", + "emsp;": "\u2003", + "eng;": "\u014b", + "ensp;": "\u2002", + "eogon;": "\u0119", + "eopf;": "\U0001d556", + "epar;": "\u22d5", + "eparsl;": "\u29e3", + "eplus;": "\u2a71", + "epsi;": "\u03b5", + "epsilon;": "\u03b5", + "epsiv;": "\u03f5", + "eqcirc;": "\u2256", + "eqcolon;": "\u2255", + "eqsim;": "\u2242", + "eqslantgtr;": "\u2a96", + "eqslantless;": "\u2a95", + "equals;": "=", + "equest;": "\u225f", + "equiv;": "\u2261", + "equivDD;": "\u2a78", + "eqvparsl;": "\u29e5", + "erDot;": "\u2253", + "erarr;": "\u2971", + "escr;": "\u212f", + "esdot;": "\u2250", + "esim;": "\u2242", + "eta;": "\u03b7", + "eth": "\xf0", + "eth;": "\xf0", + "euml": "\xeb", + "euml;": "\xeb", + "euro;": "\u20ac", + "excl;": "!", + "exist;": "\u2203", + "expectation;": "\u2130", + "exponentiale;": "\u2147", + "fallingdotseq;": "\u2252", + "fcy;": "\u0444", + "female;": "\u2640", + "ffilig;": "\ufb03", + "fflig;": "\ufb00", + "ffllig;": "\ufb04", + "ffr;": "\U0001d523", + "filig;": "\ufb01", + "fjlig;": "fj", + "flat;": "\u266d", + "fllig;": "\ufb02", + "fltns;": "\u25b1", + "fnof;": "\u0192", + "fopf;": "\U0001d557", + "forall;": "\u2200", + "fork;": "\u22d4", + "forkv;": "\u2ad9", + "fpartint;": "\u2a0d", + "frac12": "\xbd", + "frac12;": "\xbd", + "frac13;": "\u2153", + "frac14": "\xbc", + "frac14;": "\xbc", + "frac15;": "\u2155", + "frac16;": "\u2159", + "frac18;": "\u215b", + "frac23;": "\u2154", + "frac25;": "\u2156", + "frac34": "\xbe", + "frac34;": "\xbe", + "frac35;": "\u2157", + "frac38;": "\u215c", + "frac45;": "\u2158", + "frac56;": "\u215a", + "frac58;": "\u215d", + "frac78;": "\u215e", + "frasl;": "\u2044", + "frown;": "\u2322", + "fscr;": "\U0001d4bb", + "gE;": "\u2267", + "gEl;": "\u2a8c", + "gacute;": "\u01f5", + "gamma;": "\u03b3", + "gammad;": "\u03dd", + "gap;": "\u2a86", + "gbreve;": "\u011f", + "gcirc;": "\u011d", + "gcy;": "\u0433", + "gdot;": "\u0121", + "ge;": "\u2265", + "gel;": "\u22db", + "geq;": "\u2265", + "geqq;": "\u2267", + "geqslant;": "\u2a7e", + "ges;": "\u2a7e", + "gescc;": "\u2aa9", + "gesdot;": "\u2a80", + "gesdoto;": "\u2a82", + "gesdotol;": "\u2a84", + "gesl;": "\u22db\ufe00", + "gesles;": "\u2a94", + "gfr;": "\U0001d524", + "gg;": "\u226b", + "ggg;": "\u22d9", + "gimel;": "\u2137", + "gjcy;": "\u0453", + "gl;": "\u2277", + "glE;": "\u2a92", + "gla;": "\u2aa5", + "glj;": "\u2aa4", + "gnE;": "\u2269", + "gnap;": "\u2a8a", + "gnapprox;": "\u2a8a", + "gne;": "\u2a88", + "gneq;": "\u2a88", + "gneqq;": "\u2269", + "gnsim;": "\u22e7", + "gopf;": "\U0001d558", + "grave;": "`", + "gscr;": "\u210a", + "gsim;": "\u2273", + "gsime;": "\u2a8e", + "gsiml;": "\u2a90", + "gt": ">", + "gt;": ">", + "gtcc;": "\u2aa7", + "gtcir;": "\u2a7a", + "gtdot;": "\u22d7", + "gtlPar;": "\u2995", + "gtquest;": "\u2a7c", + "gtrapprox;": "\u2a86", + "gtrarr;": "\u2978", + "gtrdot;": "\u22d7", + "gtreqless;": "\u22db", + "gtreqqless;": "\u2a8c", + "gtrless;": "\u2277", + "gtrsim;": "\u2273", + "gvertneqq;": "\u2269\ufe00", + "gvnE;": "\u2269\ufe00", + "hArr;": "\u21d4", + "hairsp;": "\u200a", + "half;": "\xbd", + "hamilt;": "\u210b", + "hardcy;": "\u044a", + "harr;": "\u2194", + "harrcir;": "\u2948", + "harrw;": "\u21ad", + "hbar;": "\u210f", + "hcirc;": "\u0125", + "hearts;": "\u2665", + "heartsuit;": "\u2665", + "hellip;": "\u2026", + "hercon;": "\u22b9", + "hfr;": "\U0001d525", + "hksearow;": "\u2925", + "hkswarow;": "\u2926", + "hoarr;": "\u21ff", + "homtht;": "\u223b", + "hookleftarrow;": "\u21a9", + "hookrightarrow;": "\u21aa", + "hopf;": "\U0001d559", + "horbar;": "\u2015", + "hscr;": "\U0001d4bd", + "hslash;": "\u210f", + "hstrok;": "\u0127", + "hybull;": "\u2043", + "hyphen;": "\u2010", + "iacute": "\xed", + "iacute;": "\xed", + "ic;": "\u2063", + "icirc": "\xee", + "icirc;": "\xee", + "icy;": "\u0438", + "iecy;": "\u0435", + "iexcl": "\xa1", + "iexcl;": "\xa1", + "iff;": "\u21d4", + "ifr;": "\U0001d526", + "igrave": "\xec", + "igrave;": "\xec", + "ii;": "\u2148", + "iiiint;": "\u2a0c", + "iiint;": "\u222d", + "iinfin;": "\u29dc", + "iiota;": "\u2129", + "ijlig;": "\u0133", + "imacr;": "\u012b", + "image;": "\u2111", + "imagline;": "\u2110", + "imagpart;": "\u2111", + "imath;": "\u0131", + "imof;": "\u22b7", + "imped;": "\u01b5", + "in;": "\u2208", + "incare;": "\u2105", + "infin;": "\u221e", + "infintie;": "\u29dd", + "inodot;": "\u0131", + "int;": "\u222b", + "intcal;": "\u22ba", + "integers;": "\u2124", + "intercal;": "\u22ba", + "intlarhk;": "\u2a17", + "intprod;": "\u2a3c", + "iocy;": "\u0451", + "iogon;": "\u012f", + "iopf;": "\U0001d55a", + "iota;": "\u03b9", + "iprod;": "\u2a3c", + "iquest": "\xbf", + "iquest;": "\xbf", + "iscr;": "\U0001d4be", + "isin;": "\u2208", + "isinE;": "\u22f9", + "isindot;": "\u22f5", + "isins;": "\u22f4", + "isinsv;": "\u22f3", + "isinv;": "\u2208", + "it;": "\u2062", + "itilde;": "\u0129", + "iukcy;": "\u0456", + "iuml": "\xef", + "iuml;": "\xef", + "jcirc;": "\u0135", + "jcy;": "\u0439", + "jfr;": "\U0001d527", + "jmath;": "\u0237", + "jopf;": "\U0001d55b", + "jscr;": "\U0001d4bf", + "jsercy;": "\u0458", + "jukcy;": "\u0454", + "kappa;": "\u03ba", + "kappav;": "\u03f0", + "kcedil;": "\u0137", + "kcy;": "\u043a", + "kfr;": "\U0001d528", + "kgreen;": "\u0138", + "khcy;": "\u0445", + "kjcy;": "\u045c", + "kopf;": "\U0001d55c", + "kscr;": "\U0001d4c0", + "lAarr;": "\u21da", + "lArr;": "\u21d0", + "lAtail;": "\u291b", + "lBarr;": "\u290e", + "lE;": "\u2266", + "lEg;": "\u2a8b", + "lHar;": "\u2962", + "lacute;": "\u013a", + "laemptyv;": "\u29b4", + "lagran;": "\u2112", + "lambda;": "\u03bb", + "lang;": "\u27e8", + "langd;": "\u2991", + "langle;": "\u27e8", + "lap;": "\u2a85", + "laquo": "\xab", + "laquo;": "\xab", + "larr;": "\u2190", + "larrb;": "\u21e4", + "larrbfs;": "\u291f", + "larrfs;": "\u291d", + "larrhk;": "\u21a9", + "larrlp;": "\u21ab", + "larrpl;": "\u2939", + "larrsim;": "\u2973", + "larrtl;": "\u21a2", + "lat;": "\u2aab", + "latail;": "\u2919", + "late;": "\u2aad", + "lates;": "\u2aad\ufe00", + "lbarr;": "\u290c", + "lbbrk;": "\u2772", + "lbrace;": "{", + "lbrack;": "[", + "lbrke;": "\u298b", + "lbrksld;": "\u298f", + "lbrkslu;": "\u298d", + "lcaron;": "\u013e", + "lcedil;": "\u013c", + "lceil;": "\u2308", + "lcub;": "{", + "lcy;": "\u043b", + "ldca;": "\u2936", + "ldquo;": "\u201c", + "ldquor;": "\u201e", + "ldrdhar;": "\u2967", + "ldrushar;": "\u294b", + "ldsh;": "\u21b2", + "le;": "\u2264", + "leftarrow;": "\u2190", + "leftarrowtail;": "\u21a2", + "leftharpoondown;": "\u21bd", + "leftharpoonup;": "\u21bc", + "leftleftarrows;": "\u21c7", + "leftrightarrow;": "\u2194", + "leftrightarrows;": "\u21c6", + "leftrightharpoons;": "\u21cb", + "leftrightsquigarrow;": "\u21ad", + "leftthreetimes;": "\u22cb", + "leg;": "\u22da", + "leq;": "\u2264", + "leqq;": "\u2266", + "leqslant;": "\u2a7d", + "les;": "\u2a7d", + "lescc;": "\u2aa8", + "lesdot;": "\u2a7f", + "lesdoto;": "\u2a81", + "lesdotor;": "\u2a83", + "lesg;": "\u22da\ufe00", + "lesges;": "\u2a93", + "lessapprox;": "\u2a85", + "lessdot;": "\u22d6", + "lesseqgtr;": "\u22da", + "lesseqqgtr;": "\u2a8b", + "lessgtr;": "\u2276", + "lesssim;": "\u2272", + "lfisht;": "\u297c", + "lfloor;": "\u230a", + "lfr;": "\U0001d529", + "lg;": "\u2276", + "lgE;": "\u2a91", + "lhard;": "\u21bd", + "lharu;": "\u21bc", + "lharul;": "\u296a", + "lhblk;": "\u2584", + "ljcy;": "\u0459", + "ll;": "\u226a", + "llarr;": "\u21c7", + "llcorner;": "\u231e", + "llhard;": "\u296b", + "lltri;": "\u25fa", + "lmidot;": "\u0140", + "lmoust;": "\u23b0", + "lmoustache;": "\u23b0", + "lnE;": "\u2268", + "lnap;": "\u2a89", + "lnapprox;": "\u2a89", + "lne;": "\u2a87", + "lneq;": "\u2a87", + "lneqq;": "\u2268", + "lnsim;": "\u22e6", + "loang;": "\u27ec", + "loarr;": "\u21fd", + "lobrk;": "\u27e6", + "longleftarrow;": "\u27f5", + "longleftrightarrow;": "\u27f7", + "longmapsto;": "\u27fc", + "longrightarrow;": "\u27f6", + "looparrowleft;": "\u21ab", + "looparrowright;": "\u21ac", + "lopar;": "\u2985", + "lopf;": "\U0001d55d", + "loplus;": "\u2a2d", + "lotimes;": "\u2a34", + "lowast;": "\u2217", + "lowbar;": "_", + "loz;": "\u25ca", + "lozenge;": "\u25ca", + "lozf;": "\u29eb", + "lpar;": "(", + "lparlt;": "\u2993", + "lrarr;": "\u21c6", + "lrcorner;": "\u231f", + "lrhar;": "\u21cb", + "lrhard;": "\u296d", + "lrm;": "\u200e", + "lrtri;": "\u22bf", + "lsaquo;": "\u2039", + "lscr;": "\U0001d4c1", + "lsh;": "\u21b0", + "lsim;": "\u2272", + "lsime;": "\u2a8d", + "lsimg;": "\u2a8f", + "lsqb;": "[", + "lsquo;": "\u2018", + "lsquor;": "\u201a", + "lstrok;": "\u0142", + "lt": "<", + "lt;": "<", + "ltcc;": "\u2aa6", + "ltcir;": "\u2a79", + "ltdot;": "\u22d6", + "lthree;": "\u22cb", + "ltimes;": "\u22c9", + "ltlarr;": "\u2976", + "ltquest;": "\u2a7b", + "ltrPar;": "\u2996", + "ltri;": "\u25c3", + "ltrie;": "\u22b4", + "ltrif;": "\u25c2", + "lurdshar;": "\u294a", + "luruhar;": "\u2966", + "lvertneqq;": "\u2268\ufe00", + "lvnE;": "\u2268\ufe00", + "mDDot;": "\u223a", + "macr": "\xaf", + "macr;": "\xaf", + "male;": "\u2642", + "malt;": "\u2720", + "maltese;": "\u2720", + "map;": "\u21a6", + "mapsto;": "\u21a6", + "mapstodown;": "\u21a7", + "mapstoleft;": "\u21a4", + "mapstoup;": "\u21a5", + "marker;": "\u25ae", + "mcomma;": "\u2a29", + "mcy;": "\u043c", + "mdash;": "\u2014", + "measuredangle;": "\u2221", + "mfr;": "\U0001d52a", + "mho;": "\u2127", + "micro": "\xb5", + "micro;": "\xb5", + "mid;": "\u2223", + "midast;": "*", + "midcir;": "\u2af0", + "middot": "\xb7", + "middot;": "\xb7", + "minus;": "\u2212", + "minusb;": "\u229f", + "minusd;": "\u2238", + "minusdu;": "\u2a2a", + "mlcp;": "\u2adb", + "mldr;": "\u2026", + "mnplus;": "\u2213", + "models;": "\u22a7", + "mopf;": "\U0001d55e", + "mp;": "\u2213", + "mscr;": "\U0001d4c2", + "mstpos;": "\u223e", + "mu;": "\u03bc", + "multimap;": "\u22b8", + "mumap;": "\u22b8", + "nGg;": "\u22d9\u0338", + "nGt;": "\u226b\u20d2", + "nGtv;": "\u226b\u0338", + "nLeftarrow;": "\u21cd", + "nLeftrightarrow;": "\u21ce", + "nLl;": "\u22d8\u0338", + "nLt;": "\u226a\u20d2", + "nLtv;": "\u226a\u0338", + "nRightarrow;": "\u21cf", + "nVDash;": "\u22af", + "nVdash;": "\u22ae", + "nabla;": "\u2207", + "nacute;": "\u0144", + "nang;": "\u2220\u20d2", + "nap;": "\u2249", + "napE;": "\u2a70\u0338", + "napid;": "\u224b\u0338", + "napos;": "\u0149", + "napprox;": "\u2249", + "natur;": "\u266e", + "natural;": "\u266e", + "naturals;": "\u2115", + "nbsp": "\xa0", + "nbsp;": "\xa0", + "nbump;": "\u224e\u0338", + "nbumpe;": "\u224f\u0338", + "ncap;": "\u2a43", + "ncaron;": "\u0148", + "ncedil;": "\u0146", + "ncong;": "\u2247", + "ncongdot;": "\u2a6d\u0338", + "ncup;": "\u2a42", + "ncy;": "\u043d", + "ndash;": "\u2013", + "ne;": "\u2260", + "neArr;": "\u21d7", + "nearhk;": "\u2924", + "nearr;": "\u2197", + "nearrow;": "\u2197", + "nedot;": "\u2250\u0338", + "nequiv;": "\u2262", + "nesear;": "\u2928", + "nesim;": "\u2242\u0338", + "nexist;": "\u2204", + "nexists;": "\u2204", + "nfr;": "\U0001d52b", + "ngE;": "\u2267\u0338", + "nge;": "\u2271", + "ngeq;": "\u2271", + "ngeqq;": "\u2267\u0338", + "ngeqslant;": "\u2a7e\u0338", + "nges;": "\u2a7e\u0338", + "ngsim;": "\u2275", + "ngt;": "\u226f", + "ngtr;": "\u226f", + "nhArr;": "\u21ce", + "nharr;": "\u21ae", + "nhpar;": "\u2af2", + "ni;": "\u220b", + "nis;": "\u22fc", + "nisd;": "\u22fa", + "niv;": "\u220b", + "njcy;": "\u045a", + "nlArr;": "\u21cd", + "nlE;": "\u2266\u0338", + "nlarr;": "\u219a", + "nldr;": "\u2025", + "nle;": "\u2270", + "nleftarrow;": "\u219a", + "nleftrightarrow;": "\u21ae", + "nleq;": "\u2270", + "nleqq;": "\u2266\u0338", + "nleqslant;": "\u2a7d\u0338", + "nles;": "\u2a7d\u0338", + "nless;": "\u226e", + "nlsim;": "\u2274", + "nlt;": "\u226e", + "nltri;": "\u22ea", + "nltrie;": "\u22ec", + "nmid;": "\u2224", + "nopf;": "\U0001d55f", + "not": "\xac", + "not;": "\xac", + "notin;": "\u2209", + "notinE;": "\u22f9\u0338", + "notindot;": "\u22f5\u0338", + "notinva;": "\u2209", + "notinvb;": "\u22f7", + "notinvc;": "\u22f6", + "notni;": "\u220c", + "notniva;": "\u220c", + "notnivb;": "\u22fe", + "notnivc;": "\u22fd", + "npar;": "\u2226", + "nparallel;": "\u2226", + "nparsl;": "\u2afd\u20e5", + "npart;": "\u2202\u0338", + "npolint;": "\u2a14", + "npr;": "\u2280", + "nprcue;": "\u22e0", + "npre;": "\u2aaf\u0338", + "nprec;": "\u2280", + "npreceq;": "\u2aaf\u0338", + "nrArr;": "\u21cf", + "nrarr;": "\u219b", + "nrarrc;": "\u2933\u0338", + "nrarrw;": "\u219d\u0338", + "nrightarrow;": "\u219b", + "nrtri;": "\u22eb", + "nrtrie;": "\u22ed", + "nsc;": "\u2281", + "nsccue;": "\u22e1", + "nsce;": "\u2ab0\u0338", + "nscr;": "\U0001d4c3", + "nshortmid;": "\u2224", + "nshortparallel;": "\u2226", + "nsim;": "\u2241", + "nsime;": "\u2244", + "nsimeq;": "\u2244", + "nsmid;": "\u2224", + "nspar;": "\u2226", + "nsqsube;": "\u22e2", + "nsqsupe;": "\u22e3", + "nsub;": "\u2284", + "nsubE;": "\u2ac5\u0338", + "nsube;": "\u2288", + "nsubset;": "\u2282\u20d2", + "nsubseteq;": "\u2288", + "nsubseteqq;": "\u2ac5\u0338", + "nsucc;": "\u2281", + "nsucceq;": "\u2ab0\u0338", + "nsup;": "\u2285", + "nsupE;": "\u2ac6\u0338", + "nsupe;": "\u2289", + "nsupset;": "\u2283\u20d2", + "nsupseteq;": "\u2289", + "nsupseteqq;": "\u2ac6\u0338", + "ntgl;": "\u2279", + "ntilde": "\xf1", + "ntilde;": "\xf1", + "ntlg;": "\u2278", + "ntriangleleft;": "\u22ea", + "ntrianglelefteq;": "\u22ec", + "ntriangleright;": "\u22eb", + "ntrianglerighteq;": "\u22ed", + "nu;": "\u03bd", + "num;": "#", + "numero;": "\u2116", + "numsp;": "\u2007", + "nvDash;": "\u22ad", + "nvHarr;": "\u2904", + "nvap;": "\u224d\u20d2", + "nvdash;": "\u22ac", + "nvge;": "\u2265\u20d2", + "nvgt;": ">\u20d2", + "nvinfin;": "\u29de", + "nvlArr;": "\u2902", + "nvle;": "\u2264\u20d2", + "nvlt;": "<\u20d2", + "nvltrie;": "\u22b4\u20d2", + "nvrArr;": "\u2903", + "nvrtrie;": "\u22b5\u20d2", + "nvsim;": "\u223c\u20d2", + "nwArr;": "\u21d6", + "nwarhk;": "\u2923", + "nwarr;": "\u2196", + "nwarrow;": "\u2196", + "nwnear;": "\u2927", + "oS;": "\u24c8", + "oacute": "\xf3", + "oacute;": "\xf3", + "oast;": "\u229b", + "ocir;": "\u229a", + "ocirc": "\xf4", + "ocirc;": "\xf4", + "ocy;": "\u043e", + "odash;": "\u229d", + "odblac;": "\u0151", + "odiv;": "\u2a38", + "odot;": "\u2299", + "odsold;": "\u29bc", + "oelig;": "\u0153", + "ofcir;": "\u29bf", + "ofr;": "\U0001d52c", + "ogon;": "\u02db", + "ograve": "\xf2", + "ograve;": "\xf2", + "ogt;": "\u29c1", + "ohbar;": "\u29b5", + "ohm;": "\u03a9", + "oint;": "\u222e", + "olarr;": "\u21ba", + "olcir;": "\u29be", + "olcross;": "\u29bb", + "oline;": "\u203e", + "olt;": "\u29c0", + "omacr;": "\u014d", + "omega;": "\u03c9", + "omicron;": "\u03bf", + "omid;": "\u29b6", + "ominus;": "\u2296", + "oopf;": "\U0001d560", + "opar;": "\u29b7", + "operp;": "\u29b9", + "oplus;": "\u2295", + "or;": "\u2228", + "orarr;": "\u21bb", + "ord;": "\u2a5d", + "order;": "\u2134", + "orderof;": "\u2134", + "ordf": "\xaa", + "ordf;": "\xaa", + "ordm": "\xba", + "ordm;": "\xba", + "origof;": "\u22b6", + "oror;": "\u2a56", + "orslope;": "\u2a57", + "orv;": "\u2a5b", + "oscr;": "\u2134", + "oslash": "\xf8", + "oslash;": "\xf8", + "osol;": "\u2298", + "otilde": "\xf5", + "otilde;": "\xf5", + "otimes;": "\u2297", + "otimesas;": "\u2a36", + "ouml": "\xf6", + "ouml;": "\xf6", + "ovbar;": "\u233d", + "par;": "\u2225", + "para": "\xb6", + "para;": "\xb6", + "parallel;": "\u2225", + "parsim;": "\u2af3", + "parsl;": "\u2afd", + "part;": "\u2202", + "pcy;": "\u043f", + "percnt;": "%", + "period;": ".", + "permil;": "\u2030", + "perp;": "\u22a5", + "pertenk;": "\u2031", + "pfr;": "\U0001d52d", + "phi;": "\u03c6", + "phiv;": "\u03d5", + "phmmat;": "\u2133", + "phone;": "\u260e", + "pi;": "\u03c0", + "pitchfork;": "\u22d4", + "piv;": "\u03d6", + "planck;": "\u210f", + "planckh;": "\u210e", + "plankv;": "\u210f", + "plus;": "+", + "plusacir;": "\u2a23", + "plusb;": "\u229e", + "pluscir;": "\u2a22", + "plusdo;": "\u2214", + "plusdu;": "\u2a25", + "pluse;": "\u2a72", + "plusmn": "\xb1", + "plusmn;": "\xb1", + "plussim;": "\u2a26", + "plustwo;": "\u2a27", + "pm;": "\xb1", + "pointint;": "\u2a15", + "popf;": "\U0001d561", + "pound": "\xa3", + "pound;": "\xa3", + "pr;": "\u227a", + "prE;": "\u2ab3", + "prap;": "\u2ab7", + "prcue;": "\u227c", + "pre;": "\u2aaf", + "prec;": "\u227a", + "precapprox;": "\u2ab7", + "preccurlyeq;": "\u227c", + "preceq;": "\u2aaf", + "precnapprox;": "\u2ab9", + "precneqq;": "\u2ab5", + "precnsim;": "\u22e8", + "precsim;": "\u227e", + "prime;": "\u2032", + "primes;": "\u2119", + "prnE;": "\u2ab5", + "prnap;": "\u2ab9", + "prnsim;": "\u22e8", + "prod;": "\u220f", + "profalar;": "\u232e", + "profline;": "\u2312", + "profsurf;": "\u2313", + "prop;": "\u221d", + "propto;": "\u221d", + "prsim;": "\u227e", + "prurel;": "\u22b0", + "pscr;": "\U0001d4c5", + "psi;": "\u03c8", + "puncsp;": "\u2008", + "qfr;": "\U0001d52e", + "qint;": "\u2a0c", + "qopf;": "\U0001d562", + "qprime;": "\u2057", + "qscr;": "\U0001d4c6", + "quaternions;": "\u210d", + "quatint;": "\u2a16", + "quest;": "?", + "questeq;": "\u225f", + "quot": "\"", + "quot;": "\"", + "rAarr;": "\u21db", + "rArr;": "\u21d2", + "rAtail;": "\u291c", + "rBarr;": "\u290f", + "rHar;": "\u2964", + "race;": "\u223d\u0331", + "racute;": "\u0155", + "radic;": "\u221a", + "raemptyv;": "\u29b3", + "rang;": "\u27e9", + "rangd;": "\u2992", + "range;": "\u29a5", + "rangle;": "\u27e9", + "raquo": "\xbb", + "raquo;": "\xbb", + "rarr;": "\u2192", + "rarrap;": "\u2975", + "rarrb;": "\u21e5", + "rarrbfs;": "\u2920", + "rarrc;": "\u2933", + "rarrfs;": "\u291e", + "rarrhk;": "\u21aa", + "rarrlp;": "\u21ac", + "rarrpl;": "\u2945", + "rarrsim;": "\u2974", + "rarrtl;": "\u21a3", + "rarrw;": "\u219d", + "ratail;": "\u291a", + "ratio;": "\u2236", + "rationals;": "\u211a", + "rbarr;": "\u290d", + "rbbrk;": "\u2773", + "rbrace;": "}", + "rbrack;": "]", + "rbrke;": "\u298c", + "rbrksld;": "\u298e", + "rbrkslu;": "\u2990", + "rcaron;": "\u0159", + "rcedil;": "\u0157", + "rceil;": "\u2309", + "rcub;": "}", + "rcy;": "\u0440", + "rdca;": "\u2937", + "rdldhar;": "\u2969", + "rdquo;": "\u201d", + "rdquor;": "\u201d", + "rdsh;": "\u21b3", + "real;": "\u211c", + "realine;": "\u211b", + "realpart;": "\u211c", + "reals;": "\u211d", + "rect;": "\u25ad", + "reg": "\xae", + "reg;": "\xae", + "rfisht;": "\u297d", + "rfloor;": "\u230b", + "rfr;": "\U0001d52f", + "rhard;": "\u21c1", + "rharu;": "\u21c0", + "rharul;": "\u296c", + "rho;": "\u03c1", + "rhov;": "\u03f1", + "rightarrow;": "\u2192", + "rightarrowtail;": "\u21a3", + "rightharpoondown;": "\u21c1", + "rightharpoonup;": "\u21c0", + "rightleftarrows;": "\u21c4", + "rightleftharpoons;": "\u21cc", + "rightrightarrows;": "\u21c9", + "rightsquigarrow;": "\u219d", + "rightthreetimes;": "\u22cc", + "ring;": "\u02da", + "risingdotseq;": "\u2253", + "rlarr;": "\u21c4", + "rlhar;": "\u21cc", + "rlm;": "\u200f", + "rmoust;": "\u23b1", + "rmoustache;": "\u23b1", + "rnmid;": "\u2aee", + "roang;": "\u27ed", + "roarr;": "\u21fe", + "robrk;": "\u27e7", + "ropar;": "\u2986", + "ropf;": "\U0001d563", + "roplus;": "\u2a2e", + "rotimes;": "\u2a35", + "rpar;": ")", + "rpargt;": "\u2994", + "rppolint;": "\u2a12", + "rrarr;": "\u21c9", + "rsaquo;": "\u203a", + "rscr;": "\U0001d4c7", + "rsh;": "\u21b1", + "rsqb;": "]", + "rsquo;": "\u2019", + "rsquor;": "\u2019", + "rthree;": "\u22cc", + "rtimes;": "\u22ca", + "rtri;": "\u25b9", + "rtrie;": "\u22b5", + "rtrif;": "\u25b8", + "rtriltri;": "\u29ce", + "ruluhar;": "\u2968", + "rx;": "\u211e", + "sacute;": "\u015b", + "sbquo;": "\u201a", + "sc;": "\u227b", + "scE;": "\u2ab4", + "scap;": "\u2ab8", + "scaron;": "\u0161", + "sccue;": "\u227d", + "sce;": "\u2ab0", + "scedil;": "\u015f", + "scirc;": "\u015d", + "scnE;": "\u2ab6", + "scnap;": "\u2aba", + "scnsim;": "\u22e9", + "scpolint;": "\u2a13", + "scsim;": "\u227f", + "scy;": "\u0441", + "sdot;": "\u22c5", + "sdotb;": "\u22a1", + "sdote;": "\u2a66", + "seArr;": "\u21d8", + "searhk;": "\u2925", + "searr;": "\u2198", + "searrow;": "\u2198", + "sect": "\xa7", + "sect;": "\xa7", + "semi;": ";", + "seswar;": "\u2929", + "setminus;": "\u2216", + "setmn;": "\u2216", + "sext;": "\u2736", + "sfr;": "\U0001d530", + "sfrown;": "\u2322", + "sharp;": "\u266f", + "shchcy;": "\u0449", + "shcy;": "\u0448", + "shortmid;": "\u2223", + "shortparallel;": "\u2225", + "shy": "\xad", + "shy;": "\xad", + "sigma;": "\u03c3", + "sigmaf;": "\u03c2", + "sigmav;": "\u03c2", + "sim;": "\u223c", + "simdot;": "\u2a6a", + "sime;": "\u2243", + "simeq;": "\u2243", + "simg;": "\u2a9e", + "simgE;": "\u2aa0", + "siml;": "\u2a9d", + "simlE;": "\u2a9f", + "simne;": "\u2246", + "simplus;": "\u2a24", + "simrarr;": "\u2972", + "slarr;": "\u2190", + "smallsetminus;": "\u2216", + "smashp;": "\u2a33", + "smeparsl;": "\u29e4", + "smid;": "\u2223", + "smile;": "\u2323", + "smt;": "\u2aaa", + "smte;": "\u2aac", + "smtes;": "\u2aac\ufe00", + "softcy;": "\u044c", + "sol;": "/", + "solb;": "\u29c4", + "solbar;": "\u233f", + "sopf;": "\U0001d564", + "spades;": "\u2660", + "spadesuit;": "\u2660", + "spar;": "\u2225", + "sqcap;": "\u2293", + "sqcaps;": "\u2293\ufe00", + "sqcup;": "\u2294", + "sqcups;": "\u2294\ufe00", + "sqsub;": "\u228f", + "sqsube;": "\u2291", + "sqsubset;": "\u228f", + "sqsubseteq;": "\u2291", + "sqsup;": "\u2290", + "sqsupe;": "\u2292", + "sqsupset;": "\u2290", + "sqsupseteq;": "\u2292", + "squ;": "\u25a1", + "square;": "\u25a1", + "squarf;": "\u25aa", + "squf;": "\u25aa", + "srarr;": "\u2192", + "sscr;": "\U0001d4c8", + "ssetmn;": "\u2216", + "ssmile;": "\u2323", + "sstarf;": "\u22c6", + "star;": "\u2606", + "starf;": "\u2605", + "straightepsilon;": "\u03f5", + "straightphi;": "\u03d5", + "strns;": "\xaf", + "sub;": "\u2282", + "subE;": "\u2ac5", + "subdot;": "\u2abd", + "sube;": "\u2286", + "subedot;": "\u2ac3", + "submult;": "\u2ac1", + "subnE;": "\u2acb", + "subne;": "\u228a", + "subplus;": "\u2abf", + "subrarr;": "\u2979", + "subset;": "\u2282", + "subseteq;": "\u2286", + "subseteqq;": "\u2ac5", + "subsetneq;": "\u228a", + "subsetneqq;": "\u2acb", + "subsim;": "\u2ac7", + "subsub;": "\u2ad5", + "subsup;": "\u2ad3", + "succ;": "\u227b", + "succapprox;": "\u2ab8", + "succcurlyeq;": "\u227d", + "succeq;": "\u2ab0", + "succnapprox;": "\u2aba", + "succneqq;": "\u2ab6", + "succnsim;": "\u22e9", + "succsim;": "\u227f", + "sum;": "\u2211", + "sung;": "\u266a", + "sup1": "\xb9", + "sup1;": "\xb9", + "sup2": "\xb2", + "sup2;": "\xb2", + "sup3": "\xb3", + "sup3;": "\xb3", + "sup;": "\u2283", + "supE;": "\u2ac6", + "supdot;": "\u2abe", + "supdsub;": "\u2ad8", + "supe;": "\u2287", + "supedot;": "\u2ac4", + "suphsol;": "\u27c9", + "suphsub;": "\u2ad7", + "suplarr;": "\u297b", + "supmult;": "\u2ac2", + "supnE;": "\u2acc", + "supne;": "\u228b", + "supplus;": "\u2ac0", + "supset;": "\u2283", + "supseteq;": "\u2287", + "supseteqq;": "\u2ac6", + "supsetneq;": "\u228b", + "supsetneqq;": "\u2acc", + "supsim;": "\u2ac8", + "supsub;": "\u2ad4", + "supsup;": "\u2ad6", + "swArr;": "\u21d9", + "swarhk;": "\u2926", + "swarr;": "\u2199", + "swarrow;": "\u2199", + "swnwar;": "\u292a", + "szlig": "\xdf", + "szlig;": "\xdf", + "target;": "\u2316", + "tau;": "\u03c4", + "tbrk;": "\u23b4", + "tcaron;": "\u0165", + "tcedil;": "\u0163", + "tcy;": "\u0442", + "tdot;": "\u20db", + "telrec;": "\u2315", + "tfr;": "\U0001d531", + "there4;": "\u2234", + "therefore;": "\u2234", + "theta;": "\u03b8", + "thetasym;": "\u03d1", + "thetav;": "\u03d1", + "thickapprox;": "\u2248", + "thicksim;": "\u223c", + "thinsp;": "\u2009", + "thkap;": "\u2248", + "thksim;": "\u223c", + "thorn": "\xfe", + "thorn;": "\xfe", + "tilde;": "\u02dc", + "times": "\xd7", + "times;": "\xd7", + "timesb;": "\u22a0", + "timesbar;": "\u2a31", + "timesd;": "\u2a30", + "tint;": "\u222d", + "toea;": "\u2928", + "top;": "\u22a4", + "topbot;": "\u2336", + "topcir;": "\u2af1", + "topf;": "\U0001d565", + "topfork;": "\u2ada", + "tosa;": "\u2929", + "tprime;": "\u2034", + "trade;": "\u2122", + "triangle;": "\u25b5", + "triangledown;": "\u25bf", + "triangleleft;": "\u25c3", + "trianglelefteq;": "\u22b4", + "triangleq;": "\u225c", + "triangleright;": "\u25b9", + "trianglerighteq;": "\u22b5", + "tridot;": "\u25ec", + "trie;": "\u225c", + "triminus;": "\u2a3a", + "triplus;": "\u2a39", + "trisb;": "\u29cd", + "tritime;": "\u2a3b", + "trpezium;": "\u23e2", + "tscr;": "\U0001d4c9", + "tscy;": "\u0446", + "tshcy;": "\u045b", + "tstrok;": "\u0167", + "twixt;": "\u226c", + "twoheadleftarrow;": "\u219e", + "twoheadrightarrow;": "\u21a0", + "uArr;": "\u21d1", + "uHar;": "\u2963", + "uacute": "\xfa", + "uacute;": "\xfa", + "uarr;": "\u2191", + "ubrcy;": "\u045e", + "ubreve;": "\u016d", + "ucirc": "\xfb", + "ucirc;": "\xfb", + "ucy;": "\u0443", + "udarr;": "\u21c5", + "udblac;": "\u0171", + "udhar;": "\u296e", + "ufisht;": "\u297e", + "ufr;": "\U0001d532", + "ugrave": "\xf9", + "ugrave;": "\xf9", + "uharl;": "\u21bf", + "uharr;": "\u21be", + "uhblk;": "\u2580", + "ulcorn;": "\u231c", + "ulcorner;": "\u231c", + "ulcrop;": "\u230f", + "ultri;": "\u25f8", + "umacr;": "\u016b", + "uml": "\xa8", + "uml;": "\xa8", + "uogon;": "\u0173", + "uopf;": "\U0001d566", + "uparrow;": "\u2191", + "updownarrow;": "\u2195", + "upharpoonleft;": "\u21bf", + "upharpoonright;": "\u21be", + "uplus;": "\u228e", + "upsi;": "\u03c5", + "upsih;": "\u03d2", + "upsilon;": "\u03c5", + "upuparrows;": "\u21c8", + "urcorn;": "\u231d", + "urcorner;": "\u231d", + "urcrop;": "\u230e", + "uring;": "\u016f", + "urtri;": "\u25f9", + "uscr;": "\U0001d4ca", + "utdot;": "\u22f0", + "utilde;": "\u0169", + "utri;": "\u25b5", + "utrif;": "\u25b4", + "uuarr;": "\u21c8", + "uuml": "\xfc", + "uuml;": "\xfc", + "uwangle;": "\u29a7", + "vArr;": "\u21d5", + "vBar;": "\u2ae8", + "vBarv;": "\u2ae9", + "vDash;": "\u22a8", + "vangrt;": "\u299c", + "varepsilon;": "\u03f5", + "varkappa;": "\u03f0", + "varnothing;": "\u2205", + "varphi;": "\u03d5", + "varpi;": "\u03d6", + "varpropto;": "\u221d", + "varr;": "\u2195", + "varrho;": "\u03f1", + "varsigma;": "\u03c2", + "varsubsetneq;": "\u228a\ufe00", + "varsubsetneqq;": "\u2acb\ufe00", + "varsupsetneq;": "\u228b\ufe00", + "varsupsetneqq;": "\u2acc\ufe00", + "vartheta;": "\u03d1", + "vartriangleleft;": "\u22b2", + "vartriangleright;": "\u22b3", + "vcy;": "\u0432", + "vdash;": "\u22a2", + "vee;": "\u2228", + "veebar;": "\u22bb", + "veeeq;": "\u225a", + "vellip;": "\u22ee", + "verbar;": "|", + "vert;": "|", + "vfr;": "\U0001d533", + "vltri;": "\u22b2", + "vnsub;": "\u2282\u20d2", + "vnsup;": "\u2283\u20d2", + "vopf;": "\U0001d567", + "vprop;": "\u221d", + "vrtri;": "\u22b3", + "vscr;": "\U0001d4cb", + "vsubnE;": "\u2acb\ufe00", + "vsubne;": "\u228a\ufe00", + "vsupnE;": "\u2acc\ufe00", + "vsupne;": "\u228b\ufe00", + "vzigzag;": "\u299a", + "wcirc;": "\u0175", + "wedbar;": "\u2a5f", + "wedge;": "\u2227", + "wedgeq;": "\u2259", + "weierp;": "\u2118", + "wfr;": "\U0001d534", + "wopf;": "\U0001d568", + "wp;": "\u2118", + "wr;": "\u2240", + "wreath;": "\u2240", + "wscr;": "\U0001d4cc", + "xcap;": "\u22c2", + "xcirc;": "\u25ef", + "xcup;": "\u22c3", + "xdtri;": "\u25bd", + "xfr;": "\U0001d535", + "xhArr;": "\u27fa", + "xharr;": "\u27f7", + "xi;": "\u03be", + "xlArr;": "\u27f8", + "xlarr;": "\u27f5", + "xmap;": "\u27fc", + "xnis;": "\u22fb", + "xodot;": "\u2a00", + "xopf;": "\U0001d569", + "xoplus;": "\u2a01", + "xotime;": "\u2a02", + "xrArr;": "\u27f9", + "xrarr;": "\u27f6", + "xscr;": "\U0001d4cd", + "xsqcup;": "\u2a06", + "xuplus;": "\u2a04", + "xutri;": "\u25b3", + "xvee;": "\u22c1", + "xwedge;": "\u22c0", + "yacute": "\xfd", + "yacute;": "\xfd", + "yacy;": "\u044f", + "ycirc;": "\u0177", + "ycy;": "\u044b", + "yen": "\xa5", + "yen;": "\xa5", + "yfr;": "\U0001d536", + "yicy;": "\u0457", + "yopf;": "\U0001d56a", + "yscr;": "\U0001d4ce", + "yucy;": "\u044e", + "yuml": "\xff", + "yuml;": "\xff", + "zacute;": "\u017a", + "zcaron;": "\u017e", + "zcy;": "\u0437", + "zdot;": "\u017c", + "zeetrf;": "\u2128", + "zeta;": "\u03b6", + "zfr;": "\U0001d537", + "zhcy;": "\u0436", + "zigrarr;": "\u21dd", + "zopf;": "\U0001d56b", + "zscr;": "\U0001d4cf", + "zwj;": "\u200d", + "zwnj;": "\u200c", +} + +replacementCharacters = { + 0x0: "\uFFFD", + 0x0d: "\u000D", + 0x80: "\u20AC", + 0x81: "\u0081", + 0x82: "\u201A", + 0x83: "\u0192", + 0x84: "\u201E", + 0x85: "\u2026", + 0x86: "\u2020", + 0x87: "\u2021", + 0x88: "\u02C6", + 0x89: "\u2030", + 0x8A: "\u0160", + 0x8B: "\u2039", + 0x8C: "\u0152", + 0x8D: "\u008D", + 0x8E: "\u017D", + 0x8F: "\u008F", + 0x90: "\u0090", + 0x91: "\u2018", + 0x92: "\u2019", + 0x93: "\u201C", + 0x94: "\u201D", + 0x95: "\u2022", + 0x96: "\u2013", + 0x97: "\u2014", + 0x98: "\u02DC", + 0x99: "\u2122", + 0x9A: "\u0161", + 0x9B: "\u203A", + 0x9C: "\u0153", + 0x9D: "\u009D", + 0x9E: "\u017E", + 0x9F: "\u0178", +} + +tokenTypes = { + "Doctype": 0, + "Characters": 1, + "SpaceCharacters": 2, + "StartTag": 3, + "EndTag": 4, + "EmptyTag": 5, + "Comment": 6, + "ParseError": 7 +} + +tagTokenTypes = frozenset([tokenTypes["StartTag"], tokenTypes["EndTag"], + tokenTypes["EmptyTag"]]) + + +prefixes = {v: k for k, v in namespaces.items()} +prefixes["http://www.w3.org/1998/Math/MathML"] = "math" + + +class DataLossWarning(UserWarning): + """Raised when the current tree is unable to represent the input data""" + pass + + +class _ReparseException(Exception): + pass diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__init__.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/__init__.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5019e520c1533ea56dd6ae7c6aa16c78ee4eede0 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/__init__.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/alphabeticalattributes.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/alphabeticalattributes.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94d2d0370b2712a9bc8b01a8539bdc5dc6bc9960 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/alphabeticalattributes.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/base.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/base.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d9a0cf8c16acfbcb842825d959da0492a278def Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/base.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/inject_meta_charset.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/inject_meta_charset.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd14886f5be7a9e008a1d901a4edaa0619b312ee Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/inject_meta_charset.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/lint.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/lint.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efdd4ada285f976ab1e9c3cbe6af633d2bae4287 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/lint.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/optionaltags.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/optionaltags.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a8bcf7d33da3ad3c3c50461edae8097b26e9de2 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/optionaltags.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/sanitizer.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/sanitizer.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d14ad01b6d5278c6ac0b958237b88ba69bb885d2 Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/sanitizer.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/whitespace.cpython-39.pyc b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/whitespace.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bce33787673525709c9347cea1da71be698762e Binary files /dev/null and b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/__pycache__/whitespace.cpython-39.pyc differ diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/alphabeticalattributes.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/alphabeticalattributes.py new file mode 100644 index 0000000000000000000000000000000000000000..5ba926e3b09a71121d3c10b962c26137221d5a34 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/alphabeticalattributes.py @@ -0,0 +1,29 @@ +from __future__ import absolute_import, division, unicode_literals + +from . import base + +from collections import OrderedDict + + +def _attr_key(attr): + """Return an appropriate key for an attribute for sorting + + Attributes have a namespace that can be either ``None`` or a string. We + can't compare the two because they're different types, so we convert + ``None`` to an empty string first. + + """ + return (attr[0][0] or ''), attr[0][1] + + +class Filter(base.Filter): + """Alphabetizes attributes for elements""" + def __iter__(self): + for token in base.Filter.__iter__(self): + if token["type"] in ("StartTag", "EmptyTag"): + attrs = OrderedDict() + for name, value in sorted(token["data"].items(), + key=_attr_key): + attrs[name] = value + token["data"] = attrs + yield token diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/base.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/base.py new file mode 100644 index 0000000000000000000000000000000000000000..c7dbaed0fab5afb4f8947b24dd175d2239d35d6b --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/base.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import, division, unicode_literals + + +class Filter(object): + def __init__(self, source): + self.source = source + + def __iter__(self): + return iter(self.source) + + def __getattr__(self, name): + return getattr(self.source, name) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/inject_meta_charset.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/inject_meta_charset.py new file mode 100644 index 0000000000000000000000000000000000000000..aefb5c842c2f55075546065cfba3c66d137e8184 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/inject_meta_charset.py @@ -0,0 +1,73 @@ +from __future__ import absolute_import, division, unicode_literals + +from . import base + + +class Filter(base.Filter): + """Injects ```` tag into head of document""" + def __init__(self, source, encoding): + """Creates a Filter + + :arg source: the source token stream + + :arg encoding: the encoding to set + + """ + base.Filter.__init__(self, source) + self.encoding = encoding + + def __iter__(self): + state = "pre_head" + meta_found = (self.encoding is None) + pending = [] + + for token in base.Filter.__iter__(self): + type = token["type"] + if type == "StartTag": + if token["name"].lower() == "head": + state = "in_head" + + elif type == "EmptyTag": + if token["name"].lower() == "meta": + # replace charset with actual encoding + has_http_equiv_content_type = False + for (namespace, name), value in token["data"].items(): + if namespace is not None: + continue + elif name.lower() == 'charset': + token["data"][(namespace, name)] = self.encoding + meta_found = True + break + elif name == 'http-equiv' and value.lower() == 'content-type': + has_http_equiv_content_type = True + else: + if has_http_equiv_content_type and (None, "content") in token["data"]: + token["data"][(None, "content")] = 'text/html; charset=%s' % self.encoding + meta_found = True + + elif token["name"].lower() == "head" and not meta_found: + # insert meta into empty head + yield {"type": "StartTag", "name": "head", + "data": token["data"]} + yield {"type": "EmptyTag", "name": "meta", + "data": {(None, "charset"): self.encoding}} + yield {"type": "EndTag", "name": "head"} + meta_found = True + continue + + elif type == "EndTag": + if token["name"].lower() == "head" and pending: + # insert meta into head (if necessary) and flush pending queue + yield pending.pop(0) + if not meta_found: + yield {"type": "EmptyTag", "name": "meta", + "data": {(None, "charset"): self.encoding}} + while pending: + yield pending.pop(0) + meta_found = True + state = "post_head" + + if state == "in_head": + pending.append(token) + else: + yield token diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/lint.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/lint.py new file mode 100644 index 0000000000000000000000000000000000000000..acd4d7a2af1f63ccdcdf72e132df9b2d47759046 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/lint.py @@ -0,0 +1,93 @@ +from __future__ import absolute_import, division, unicode_literals + +from six import text_type + +from . import base +from ..constants import namespaces, voidElements + +from ..constants import spaceCharacters +spaceCharacters = "".join(spaceCharacters) + + +class Filter(base.Filter): + """Lints the token stream for errors + + If it finds any errors, it'll raise an ``AssertionError``. + + """ + def __init__(self, source, require_matching_tags=True): + """Creates a Filter + + :arg source: the source token stream + + :arg require_matching_tags: whether or not to require matching tags + + """ + super(Filter, self).__init__(source) + self.require_matching_tags = require_matching_tags + + def __iter__(self): + open_elements = [] + for token in base.Filter.__iter__(self): + type = token["type"] + if type in ("StartTag", "EmptyTag"): + namespace = token["namespace"] + name = token["name"] + assert namespace is None or isinstance(namespace, text_type) + assert namespace != "" + assert isinstance(name, text_type) + assert name != "" + assert isinstance(token["data"], dict) + if (not namespace or namespace == namespaces["html"]) and name in voidElements: + assert type == "EmptyTag" + else: + assert type == "StartTag" + if type == "StartTag" and self.require_matching_tags: + open_elements.append((namespace, name)) + for (namespace, name), value in token["data"].items(): + assert namespace is None or isinstance(namespace, text_type) + assert namespace != "" + assert isinstance(name, text_type) + assert name != "" + assert isinstance(value, text_type) + + elif type == "EndTag": + namespace = token["namespace"] + name = token["name"] + assert namespace is None or isinstance(namespace, text_type) + assert namespace != "" + assert isinstance(name, text_type) + assert name != "" + if (not namespace or namespace == namespaces["html"]) and name in voidElements: + assert False, "Void element reported as EndTag token: %(tag)s" % {"tag": name} + elif self.require_matching_tags: + start = open_elements.pop() + assert start == (namespace, name) + + elif type == "Comment": + data = token["data"] + assert isinstance(data, text_type) + + elif type in ("Characters", "SpaceCharacters"): + data = token["data"] + assert isinstance(data, text_type) + assert data != "" + if type == "SpaceCharacters": + assert data.strip(spaceCharacters) == "" + + elif type == "Doctype": + name = token["name"] + assert name is None or isinstance(name, text_type) + assert token["publicId"] is None or isinstance(name, text_type) + assert token["systemId"] is None or isinstance(name, text_type) + + elif type == "Entity": + assert isinstance(token["name"], text_type) + + elif type == "SerializerError": + assert isinstance(token["data"], text_type) + + else: + assert False, "Unknown token type: %(type)s" % {"type": type} + + yield token diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/optionaltags.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/optionaltags.py new file mode 100644 index 0000000000000000000000000000000000000000..4a865012c16237c3c4dd3404af7ed767b98d235a --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/optionaltags.py @@ -0,0 +1,207 @@ +from __future__ import absolute_import, division, unicode_literals + +from . import base + + +class Filter(base.Filter): + """Removes optional tags from the token stream""" + def slider(self): + previous1 = previous2 = None + for token in self.source: + if previous1 is not None: + yield previous2, previous1, token + previous2 = previous1 + previous1 = token + if previous1 is not None: + yield previous2, previous1, None + + def __iter__(self): + for previous, token, next in self.slider(): + type = token["type"] + if type == "StartTag": + if (token["data"] or + not self.is_optional_start(token["name"], previous, next)): + yield token + elif type == "EndTag": + if not self.is_optional_end(token["name"], next): + yield token + else: + yield token + + def is_optional_start(self, tagname, previous, next): + type = next and next["type"] or None + if tagname in 'html': + # An html element's start tag may be omitted if the first thing + # inside the html element is not a space character or a comment. + return type not in ("Comment", "SpaceCharacters") + elif tagname == 'head': + # A head element's start tag may be omitted if the first thing + # inside the head element is an element. + # XXX: we also omit the start tag if the head element is empty + if type in ("StartTag", "EmptyTag"): + return True + elif type == "EndTag": + return next["name"] == "head" + elif tagname == 'body': + # A body element's start tag may be omitted if the first thing + # inside the body element is not a space character or a comment, + # except if the first thing inside the body element is a script + # or style element and the node immediately preceding the body + # element is a head element whose end tag has been omitted. + if type in ("Comment", "SpaceCharacters"): + return False + elif type == "StartTag": + # XXX: we do not look at the preceding event, so we never omit + # the body element's start tag if it's followed by a script or + # a style element. + return next["name"] not in ('script', 'style') + else: + return True + elif tagname == 'colgroup': + # A colgroup element's start tag may be omitted if the first thing + # inside the colgroup element is a col element, and if the element + # is not immediately preceded by another colgroup element whose + # end tag has been omitted. + if type in ("StartTag", "EmptyTag"): + # XXX: we do not look at the preceding event, so instead we never + # omit the colgroup element's end tag when it is immediately + # followed by another colgroup element. See is_optional_end. + return next["name"] == "col" + else: + return False + elif tagname == 'tbody': + # A tbody element's start tag may be omitted if the first thing + # inside the tbody element is a tr element, and if the element is + # not immediately preceded by a tbody, thead, or tfoot element + # whose end tag has been omitted. + if type == "StartTag": + # omit the thead and tfoot elements' end tag when they are + # immediately followed by a tbody element. See is_optional_end. + if previous and previous['type'] == 'EndTag' and \ + previous['name'] in ('tbody', 'thead', 'tfoot'): + return False + return next["name"] == 'tr' + else: + return False + return False + + def is_optional_end(self, tagname, next): + type = next and next["type"] or None + if tagname in ('html', 'head', 'body'): + # An html element's end tag may be omitted if the html element + # is not immediately followed by a space character or a comment. + return type not in ("Comment", "SpaceCharacters") + elif tagname in ('li', 'optgroup', 'tr'): + # A li element's end tag may be omitted if the li element is + # immediately followed by another li element or if there is + # no more content in the parent element. + # An optgroup element's end tag may be omitted if the optgroup + # element is immediately followed by another optgroup element, + # or if there is no more content in the parent element. + # A tr element's end tag may be omitted if the tr element is + # immediately followed by another tr element, or if there is + # no more content in the parent element. + if type == "StartTag": + return next["name"] == tagname + else: + return type == "EndTag" or type is None + elif tagname in ('dt', 'dd'): + # A dt element's end tag may be omitted if the dt element is + # immediately followed by another dt element or a dd element. + # A dd element's end tag may be omitted if the dd element is + # immediately followed by another dd element or a dt element, + # or if there is no more content in the parent element. + if type == "StartTag": + return next["name"] in ('dt', 'dd') + elif tagname == 'dd': + return type == "EndTag" or type is None + else: + return False + elif tagname == 'p': + # A p element's end tag may be omitted if the p element is + # immediately followed by an address, article, aside, + # blockquote, datagrid, dialog, dir, div, dl, fieldset, + # footer, form, h1, h2, h3, h4, h5, h6, header, hr, menu, + # nav, ol, p, pre, section, table, or ul, element, or if + # there is no more content in the parent element. + if type in ("StartTag", "EmptyTag"): + return next["name"] in ('address', 'article', 'aside', + 'blockquote', 'datagrid', 'dialog', + 'dir', 'div', 'dl', 'fieldset', 'footer', + 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', + 'header', 'hr', 'menu', 'nav', 'ol', + 'p', 'pre', 'section', 'table', 'ul') + else: + return type == "EndTag" or type is None + elif tagname == 'option': + # An option element's end tag may be omitted if the option + # element is immediately followed by another option element, + # or if it is immediately followed by an optgroup + # element, or if there is no more content in the parent + # element. + if type == "StartTag": + return next["name"] in ('option', 'optgroup') + else: + return type == "EndTag" or type is None + elif tagname in ('rt', 'rp'): + # An rt element's end tag may be omitted if the rt element is + # immediately followed by an rt or rp element, or if there is + # no more content in the parent element. + # An rp element's end tag may be omitted if the rp element is + # immediately followed by an rt or rp element, or if there is + # no more content in the parent element. + if type == "StartTag": + return next["name"] in ('rt', 'rp') + else: + return type == "EndTag" or type is None + elif tagname == 'colgroup': + # A colgroup element's end tag may be omitted if the colgroup + # element is not immediately followed by a space character or + # a comment. + if type in ("Comment", "SpaceCharacters"): + return False + elif type == "StartTag": + # XXX: we also look for an immediately following colgroup + # element. See is_optional_start. + return next["name"] != 'colgroup' + else: + return True + elif tagname in ('thead', 'tbody'): + # A thead element's end tag may be omitted if the thead element + # is immediately followed by a tbody or tfoot element. + # A tbody element's end tag may be omitted if the tbody element + # is immediately followed by a tbody or tfoot element, or if + # there is no more content in the parent element. + # A tfoot element's end tag may be omitted if the tfoot element + # is immediately followed by a tbody element, or if there is no + # more content in the parent element. + # XXX: we never omit the end tag when the following element is + # a tbody. See is_optional_start. + if type == "StartTag": + return next["name"] in ['tbody', 'tfoot'] + elif tagname == 'tbody': + return type == "EndTag" or type is None + else: + return False + elif tagname == 'tfoot': + # A tfoot element's end tag may be omitted if the tfoot element + # is immediately followed by a tbody element, or if there is no + # more content in the parent element. + # XXX: we never omit the end tag when the following element is + # a tbody. See is_optional_start. + if type == "StartTag": + return next["name"] == 'tbody' + else: + return type == "EndTag" or type is None + elif tagname in ('td', 'th'): + # A td element's end tag may be omitted if the td element is + # immediately followed by a td or th element, or if there is + # no more content in the parent element. + # A th element's end tag may be omitted if the th element is + # immediately followed by a td or th element, or if there is + # no more content in the parent element. + if type == "StartTag": + return next["name"] in ('td', 'th') + else: + return type == "EndTag" or type is None + return False diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/sanitizer.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/sanitizer.py new file mode 100644 index 0000000000000000000000000000000000000000..70ef90665e5df6fb32cb449042aa9a090970640b --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/sanitizer.py @@ -0,0 +1,916 @@ +"""Deprecated from html5lib 1.1. + +See `here `_ for +information about its deprecation; `Bleach `_ +is recommended as a replacement. Please let us know in the aforementioned issue +if Bleach is unsuitable for your needs. + +""" +from __future__ import absolute_import, division, unicode_literals + +import re +import warnings +from xml.sax.saxutils import escape, unescape + +from six.moves import urllib_parse as urlparse + +from . import base +from ..constants import namespaces, prefixes + +__all__ = ["Filter"] + + +_deprecation_msg = ( + "html5lib's sanitizer is deprecated; see " + + "https://github.com/html5lib/html5lib-python/issues/443 and please let " + + "us know if Bleach is unsuitable for your needs" +) + +warnings.warn(_deprecation_msg, DeprecationWarning) + +allowed_elements = frozenset(( + (namespaces['html'], 'a'), + (namespaces['html'], 'abbr'), + (namespaces['html'], 'acronym'), + (namespaces['html'], 'address'), + (namespaces['html'], 'area'), + (namespaces['html'], 'article'), + (namespaces['html'], 'aside'), + (namespaces['html'], 'audio'), + (namespaces['html'], 'b'), + (namespaces['html'], 'big'), + (namespaces['html'], 'blockquote'), + (namespaces['html'], 'br'), + (namespaces['html'], 'button'), + (namespaces['html'], 'canvas'), + (namespaces['html'], 'caption'), + (namespaces['html'], 'center'), + (namespaces['html'], 'cite'), + (namespaces['html'], 'code'), + (namespaces['html'], 'col'), + (namespaces['html'], 'colgroup'), + (namespaces['html'], 'command'), + (namespaces['html'], 'datagrid'), + (namespaces['html'], 'datalist'), + (namespaces['html'], 'dd'), + (namespaces['html'], 'del'), + (namespaces['html'], 'details'), + (namespaces['html'], 'dfn'), + (namespaces['html'], 'dialog'), + (namespaces['html'], 'dir'), + (namespaces['html'], 'div'), + (namespaces['html'], 'dl'), + (namespaces['html'], 'dt'), + (namespaces['html'], 'em'), + (namespaces['html'], 'event-source'), + (namespaces['html'], 'fieldset'), + (namespaces['html'], 'figcaption'), + (namespaces['html'], 'figure'), + (namespaces['html'], 'footer'), + (namespaces['html'], 'font'), + (namespaces['html'], 'form'), + (namespaces['html'], 'header'), + (namespaces['html'], 'h1'), + (namespaces['html'], 'h2'), + (namespaces['html'], 'h3'), + (namespaces['html'], 'h4'), + (namespaces['html'], 'h5'), + (namespaces['html'], 'h6'), + (namespaces['html'], 'hr'), + (namespaces['html'], 'i'), + (namespaces['html'], 'img'), + (namespaces['html'], 'input'), + (namespaces['html'], 'ins'), + (namespaces['html'], 'keygen'), + (namespaces['html'], 'kbd'), + (namespaces['html'], 'label'), + (namespaces['html'], 'legend'), + (namespaces['html'], 'li'), + (namespaces['html'], 'm'), + (namespaces['html'], 'map'), + (namespaces['html'], 'menu'), + (namespaces['html'], 'meter'), + (namespaces['html'], 'multicol'), + (namespaces['html'], 'nav'), + (namespaces['html'], 'nextid'), + (namespaces['html'], 'ol'), + (namespaces['html'], 'output'), + (namespaces['html'], 'optgroup'), + (namespaces['html'], 'option'), + (namespaces['html'], 'p'), + (namespaces['html'], 'pre'), + (namespaces['html'], 'progress'), + (namespaces['html'], 'q'), + (namespaces['html'], 's'), + (namespaces['html'], 'samp'), + (namespaces['html'], 'section'), + (namespaces['html'], 'select'), + (namespaces['html'], 'small'), + (namespaces['html'], 'sound'), + (namespaces['html'], 'source'), + (namespaces['html'], 'spacer'), + (namespaces['html'], 'span'), + (namespaces['html'], 'strike'), + (namespaces['html'], 'strong'), + (namespaces['html'], 'sub'), + (namespaces['html'], 'sup'), + (namespaces['html'], 'table'), + (namespaces['html'], 'tbody'), + (namespaces['html'], 'td'), + (namespaces['html'], 'textarea'), + (namespaces['html'], 'time'), + (namespaces['html'], 'tfoot'), + (namespaces['html'], 'th'), + (namespaces['html'], 'thead'), + (namespaces['html'], 'tr'), + (namespaces['html'], 'tt'), + (namespaces['html'], 'u'), + (namespaces['html'], 'ul'), + (namespaces['html'], 'var'), + (namespaces['html'], 'video'), + (namespaces['mathml'], 'maction'), + (namespaces['mathml'], 'math'), + (namespaces['mathml'], 'merror'), + (namespaces['mathml'], 'mfrac'), + (namespaces['mathml'], 'mi'), + (namespaces['mathml'], 'mmultiscripts'), + (namespaces['mathml'], 'mn'), + (namespaces['mathml'], 'mo'), + (namespaces['mathml'], 'mover'), + (namespaces['mathml'], 'mpadded'), + (namespaces['mathml'], 'mphantom'), + (namespaces['mathml'], 'mprescripts'), + (namespaces['mathml'], 'mroot'), + (namespaces['mathml'], 'mrow'), + (namespaces['mathml'], 'mspace'), + (namespaces['mathml'], 'msqrt'), + (namespaces['mathml'], 'mstyle'), + (namespaces['mathml'], 'msub'), + (namespaces['mathml'], 'msubsup'), + (namespaces['mathml'], 'msup'), + (namespaces['mathml'], 'mtable'), + (namespaces['mathml'], 'mtd'), + (namespaces['mathml'], 'mtext'), + (namespaces['mathml'], 'mtr'), + (namespaces['mathml'], 'munder'), + (namespaces['mathml'], 'munderover'), + (namespaces['mathml'], 'none'), + (namespaces['svg'], 'a'), + (namespaces['svg'], 'animate'), + (namespaces['svg'], 'animateColor'), + (namespaces['svg'], 'animateMotion'), + (namespaces['svg'], 'animateTransform'), + (namespaces['svg'], 'clipPath'), + (namespaces['svg'], 'circle'), + (namespaces['svg'], 'defs'), + (namespaces['svg'], 'desc'), + (namespaces['svg'], 'ellipse'), + (namespaces['svg'], 'font-face'), + (namespaces['svg'], 'font-face-name'), + (namespaces['svg'], 'font-face-src'), + (namespaces['svg'], 'g'), + (namespaces['svg'], 'glyph'), + (namespaces['svg'], 'hkern'), + (namespaces['svg'], 'linearGradient'), + (namespaces['svg'], 'line'), + (namespaces['svg'], 'marker'), + (namespaces['svg'], 'metadata'), + (namespaces['svg'], 'missing-glyph'), + (namespaces['svg'], 'mpath'), + (namespaces['svg'], 'path'), + (namespaces['svg'], 'polygon'), + (namespaces['svg'], 'polyline'), + (namespaces['svg'], 'radialGradient'), + (namespaces['svg'], 'rect'), + (namespaces['svg'], 'set'), + (namespaces['svg'], 'stop'), + (namespaces['svg'], 'svg'), + (namespaces['svg'], 'switch'), + (namespaces['svg'], 'text'), + (namespaces['svg'], 'title'), + (namespaces['svg'], 'tspan'), + (namespaces['svg'], 'use'), +)) + +allowed_attributes = frozenset(( + # HTML attributes + (None, 'abbr'), + (None, 'accept'), + (None, 'accept-charset'), + (None, 'accesskey'), + (None, 'action'), + (None, 'align'), + (None, 'alt'), + (None, 'autocomplete'), + (None, 'autofocus'), + (None, 'axis'), + (None, 'background'), + (None, 'balance'), + (None, 'bgcolor'), + (None, 'bgproperties'), + (None, 'border'), + (None, 'bordercolor'), + (None, 'bordercolordark'), + (None, 'bordercolorlight'), + (None, 'bottompadding'), + (None, 'cellpadding'), + (None, 'cellspacing'), + (None, 'ch'), + (None, 'challenge'), + (None, 'char'), + (None, 'charoff'), + (None, 'choff'), + (None, 'charset'), + (None, 'checked'), + (None, 'cite'), + (None, 'class'), + (None, 'clear'), + (None, 'color'), + (None, 'cols'), + (None, 'colspan'), + (None, 'compact'), + (None, 'contenteditable'), + (None, 'controls'), + (None, 'coords'), + (None, 'data'), + (None, 'datafld'), + (None, 'datapagesize'), + (None, 'datasrc'), + (None, 'datetime'), + (None, 'default'), + (None, 'delay'), + (None, 'dir'), + (None, 'disabled'), + (None, 'draggable'), + (None, 'dynsrc'), + (None, 'enctype'), + (None, 'end'), + (None, 'face'), + (None, 'for'), + (None, 'form'), + (None, 'frame'), + (None, 'galleryimg'), + (None, 'gutter'), + (None, 'headers'), + (None, 'height'), + (None, 'hidefocus'), + (None, 'hidden'), + (None, 'high'), + (None, 'href'), + (None, 'hreflang'), + (None, 'hspace'), + (None, 'icon'), + (None, 'id'), + (None, 'inputmode'), + (None, 'ismap'), + (None, 'keytype'), + (None, 'label'), + (None, 'leftspacing'), + (None, 'lang'), + (None, 'list'), + (None, 'longdesc'), + (None, 'loop'), + (None, 'loopcount'), + (None, 'loopend'), + (None, 'loopstart'), + (None, 'low'), + (None, 'lowsrc'), + (None, 'max'), + (None, 'maxlength'), + (None, 'media'), + (None, 'method'), + (None, 'min'), + (None, 'multiple'), + (None, 'name'), + (None, 'nohref'), + (None, 'noshade'), + (None, 'nowrap'), + (None, 'open'), + (None, 'optimum'), + (None, 'pattern'), + (None, 'ping'), + (None, 'point-size'), + (None, 'poster'), + (None, 'pqg'), + (None, 'preload'), + (None, 'prompt'), + (None, 'radiogroup'), + (None, 'readonly'), + (None, 'rel'), + (None, 'repeat-max'), + (None, 'repeat-min'), + (None, 'replace'), + (None, 'required'), + (None, 'rev'), + (None, 'rightspacing'), + (None, 'rows'), + (None, 'rowspan'), + (None, 'rules'), + (None, 'scope'), + (None, 'selected'), + (None, 'shape'), + (None, 'size'), + (None, 'span'), + (None, 'src'), + (None, 'start'), + (None, 'step'), + (None, 'style'), + (None, 'summary'), + (None, 'suppress'), + (None, 'tabindex'), + (None, 'target'), + (None, 'template'), + (None, 'title'), + (None, 'toppadding'), + (None, 'type'), + (None, 'unselectable'), + (None, 'usemap'), + (None, 'urn'), + (None, 'valign'), + (None, 'value'), + (None, 'variable'), + (None, 'volume'), + (None, 'vspace'), + (None, 'vrml'), + (None, 'width'), + (None, 'wrap'), + (namespaces['xml'], 'lang'), + # MathML attributes + (None, 'actiontype'), + (None, 'align'), + (None, 'columnalign'), + (None, 'columnalign'), + (None, 'columnalign'), + (None, 'columnlines'), + (None, 'columnspacing'), + (None, 'columnspan'), + (None, 'depth'), + (None, 'display'), + (None, 'displaystyle'), + (None, 'equalcolumns'), + (None, 'equalrows'), + (None, 'fence'), + (None, 'fontstyle'), + (None, 'fontweight'), + (None, 'frame'), + (None, 'height'), + (None, 'linethickness'), + (None, 'lspace'), + (None, 'mathbackground'), + (None, 'mathcolor'), + (None, 'mathvariant'), + (None, 'mathvariant'), + (None, 'maxsize'), + (None, 'minsize'), + (None, 'other'), + (None, 'rowalign'), + (None, 'rowalign'), + (None, 'rowalign'), + (None, 'rowlines'), + (None, 'rowspacing'), + (None, 'rowspan'), + (None, 'rspace'), + (None, 'scriptlevel'), + (None, 'selection'), + (None, 'separator'), + (None, 'stretchy'), + (None, 'width'), + (None, 'width'), + (namespaces['xlink'], 'href'), + (namespaces['xlink'], 'show'), + (namespaces['xlink'], 'type'), + # SVG attributes + (None, 'accent-height'), + (None, 'accumulate'), + (None, 'additive'), + (None, 'alphabetic'), + (None, 'arabic-form'), + (None, 'ascent'), + (None, 'attributeName'), + (None, 'attributeType'), + (None, 'baseProfile'), + (None, 'bbox'), + (None, 'begin'), + (None, 'by'), + (None, 'calcMode'), + (None, 'cap-height'), + (None, 'class'), + (None, 'clip-path'), + (None, 'color'), + (None, 'color-rendering'), + (None, 'content'), + (None, 'cx'), + (None, 'cy'), + (None, 'd'), + (None, 'dx'), + (None, 'dy'), + (None, 'descent'), + (None, 'display'), + (None, 'dur'), + (None, 'end'), + (None, 'fill'), + (None, 'fill-opacity'), + (None, 'fill-rule'), + (None, 'font-family'), + (None, 'font-size'), + (None, 'font-stretch'), + (None, 'font-style'), + (None, 'font-variant'), + (None, 'font-weight'), + (None, 'from'), + (None, 'fx'), + (None, 'fy'), + (None, 'g1'), + (None, 'g2'), + (None, 'glyph-name'), + (None, 'gradientUnits'), + (None, 'hanging'), + (None, 'height'), + (None, 'horiz-adv-x'), + (None, 'horiz-origin-x'), + (None, 'id'), + (None, 'ideographic'), + (None, 'k'), + (None, 'keyPoints'), + (None, 'keySplines'), + (None, 'keyTimes'), + (None, 'lang'), + (None, 'marker-end'), + (None, 'marker-mid'), + (None, 'marker-start'), + (None, 'markerHeight'), + (None, 'markerUnits'), + (None, 'markerWidth'), + (None, 'mathematical'), + (None, 'max'), + (None, 'min'), + (None, 'name'), + (None, 'offset'), + (None, 'opacity'), + (None, 'orient'), + (None, 'origin'), + (None, 'overline-position'), + (None, 'overline-thickness'), + (None, 'panose-1'), + (None, 'path'), + (None, 'pathLength'), + (None, 'points'), + (None, 'preserveAspectRatio'), + (None, 'r'), + (None, 'refX'), + (None, 'refY'), + (None, 'repeatCount'), + (None, 'repeatDur'), + (None, 'requiredExtensions'), + (None, 'requiredFeatures'), + (None, 'restart'), + (None, 'rotate'), + (None, 'rx'), + (None, 'ry'), + (None, 'slope'), + (None, 'stemh'), + (None, 'stemv'), + (None, 'stop-color'), + (None, 'stop-opacity'), + (None, 'strikethrough-position'), + (None, 'strikethrough-thickness'), + (None, 'stroke'), + (None, 'stroke-dasharray'), + (None, 'stroke-dashoffset'), + (None, 'stroke-linecap'), + (None, 'stroke-linejoin'), + (None, 'stroke-miterlimit'), + (None, 'stroke-opacity'), + (None, 'stroke-width'), + (None, 'systemLanguage'), + (None, 'target'), + (None, 'text-anchor'), + (None, 'to'), + (None, 'transform'), + (None, 'type'), + (None, 'u1'), + (None, 'u2'), + (None, 'underline-position'), + (None, 'underline-thickness'), + (None, 'unicode'), + (None, 'unicode-range'), + (None, 'units-per-em'), + (None, 'values'), + (None, 'version'), + (None, 'viewBox'), + (None, 'visibility'), + (None, 'width'), + (None, 'widths'), + (None, 'x'), + (None, 'x-height'), + (None, 'x1'), + (None, 'x2'), + (namespaces['xlink'], 'actuate'), + (namespaces['xlink'], 'arcrole'), + (namespaces['xlink'], 'href'), + (namespaces['xlink'], 'role'), + (namespaces['xlink'], 'show'), + (namespaces['xlink'], 'title'), + (namespaces['xlink'], 'type'), + (namespaces['xml'], 'base'), + (namespaces['xml'], 'lang'), + (namespaces['xml'], 'space'), + (None, 'y'), + (None, 'y1'), + (None, 'y2'), + (None, 'zoomAndPan'), +)) + +attr_val_is_uri = frozenset(( + (None, 'href'), + (None, 'src'), + (None, 'cite'), + (None, 'action'), + (None, 'longdesc'), + (None, 'poster'), + (None, 'background'), + (None, 'datasrc'), + (None, 'dynsrc'), + (None, 'lowsrc'), + (None, 'ping'), + (namespaces['xlink'], 'href'), + (namespaces['xml'], 'base'), +)) + +svg_attr_val_allows_ref = frozenset(( + (None, 'clip-path'), + (None, 'color-profile'), + (None, 'cursor'), + (None, 'fill'), + (None, 'filter'), + (None, 'marker'), + (None, 'marker-start'), + (None, 'marker-mid'), + (None, 'marker-end'), + (None, 'mask'), + (None, 'stroke'), +)) + +svg_allow_local_href = frozenset(( + (None, 'altGlyph'), + (None, 'animate'), + (None, 'animateColor'), + (None, 'animateMotion'), + (None, 'animateTransform'), + (None, 'cursor'), + (None, 'feImage'), + (None, 'filter'), + (None, 'linearGradient'), + (None, 'pattern'), + (None, 'radialGradient'), + (None, 'textpath'), + (None, 'tref'), + (None, 'set'), + (None, 'use') +)) + +allowed_css_properties = frozenset(( + 'azimuth', + 'background-color', + 'border-bottom-color', + 'border-collapse', + 'border-color', + 'border-left-color', + 'border-right-color', + 'border-top-color', + 'clear', + 'color', + 'cursor', + 'direction', + 'display', + 'elevation', + 'float', + 'font', + 'font-family', + 'font-size', + 'font-style', + 'font-variant', + 'font-weight', + 'height', + 'letter-spacing', + 'line-height', + 'overflow', + 'pause', + 'pause-after', + 'pause-before', + 'pitch', + 'pitch-range', + 'richness', + 'speak', + 'speak-header', + 'speak-numeral', + 'speak-punctuation', + 'speech-rate', + 'stress', + 'text-align', + 'text-decoration', + 'text-indent', + 'unicode-bidi', + 'vertical-align', + 'voice-family', + 'volume', + 'white-space', + 'width', +)) + +allowed_css_keywords = frozenset(( + 'auto', + 'aqua', + 'black', + 'block', + 'blue', + 'bold', + 'both', + 'bottom', + 'brown', + 'center', + 'collapse', + 'dashed', + 'dotted', + 'fuchsia', + 'gray', + 'green', + '!important', + 'italic', + 'left', + 'lime', + 'maroon', + 'medium', + 'none', + 'navy', + 'normal', + 'nowrap', + 'olive', + 'pointer', + 'purple', + 'red', + 'right', + 'solid', + 'silver', + 'teal', + 'top', + 'transparent', + 'underline', + 'white', + 'yellow', +)) + +allowed_svg_properties = frozenset(( + 'fill', + 'fill-opacity', + 'fill-rule', + 'stroke', + 'stroke-width', + 'stroke-linecap', + 'stroke-linejoin', + 'stroke-opacity', +)) + +allowed_protocols = frozenset(( + 'ed2k', + 'ftp', + 'http', + 'https', + 'irc', + 'mailto', + 'news', + 'gopher', + 'nntp', + 'telnet', + 'webcal', + 'xmpp', + 'callto', + 'feed', + 'urn', + 'aim', + 'rsync', + 'tag', + 'ssh', + 'sftp', + 'rtsp', + 'afs', + 'data', +)) + +allowed_content_types = frozenset(( + 'image/png', + 'image/jpeg', + 'image/gif', + 'image/webp', + 'image/bmp', + 'text/plain', +)) + + +data_content_type = re.compile(r''' + ^ + # Match a content type / + (?P[-a-zA-Z0-9.]+/[-a-zA-Z0-9.]+) + # Match any character set and encoding + (?:(?:;charset=(?:[-a-zA-Z0-9]+)(?:;(?:base64))?) + |(?:;(?:base64))?(?:;charset=(?:[-a-zA-Z0-9]+))?) + # Assume the rest is data + ,.* + $ + ''', + re.VERBOSE) + + +class Filter(base.Filter): + """Sanitizes token stream of XHTML+MathML+SVG and of inline style attributes""" + def __init__(self, + source, + allowed_elements=allowed_elements, + allowed_attributes=allowed_attributes, + allowed_css_properties=allowed_css_properties, + allowed_css_keywords=allowed_css_keywords, + allowed_svg_properties=allowed_svg_properties, + allowed_protocols=allowed_protocols, + allowed_content_types=allowed_content_types, + attr_val_is_uri=attr_val_is_uri, + svg_attr_val_allows_ref=svg_attr_val_allows_ref, + svg_allow_local_href=svg_allow_local_href): + """Creates a Filter + + :arg allowed_elements: set of elements to allow--everything else will + be escaped + + :arg allowed_attributes: set of attributes to allow in + elements--everything else will be stripped + + :arg allowed_css_properties: set of CSS properties to allow--everything + else will be stripped + + :arg allowed_css_keywords: set of CSS keywords to allow--everything + else will be stripped + + :arg allowed_svg_properties: set of SVG properties to allow--everything + else will be removed + + :arg allowed_protocols: set of allowed protocols for URIs + + :arg allowed_content_types: set of allowed content types for ``data`` URIs. + + :arg attr_val_is_uri: set of attributes that have URI values--values + that have a scheme not listed in ``allowed_protocols`` are removed + + :arg svg_attr_val_allows_ref: set of SVG attributes that can have + references + + :arg svg_allow_local_href: set of SVG elements that can have local + hrefs--these are removed + + """ + super(Filter, self).__init__(source) + + warnings.warn(_deprecation_msg, DeprecationWarning) + + self.allowed_elements = allowed_elements + self.allowed_attributes = allowed_attributes + self.allowed_css_properties = allowed_css_properties + self.allowed_css_keywords = allowed_css_keywords + self.allowed_svg_properties = allowed_svg_properties + self.allowed_protocols = allowed_protocols + self.allowed_content_types = allowed_content_types + self.attr_val_is_uri = attr_val_is_uri + self.svg_attr_val_allows_ref = svg_attr_val_allows_ref + self.svg_allow_local_href = svg_allow_local_href + + def __iter__(self): + for token in base.Filter.__iter__(self): + token = self.sanitize_token(token) + if token: + yield token + + # Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and + # stripping out all attributes not in ALLOWED_ATTRIBUTES. Style attributes + # are parsed, and a restricted set, specified by ALLOWED_CSS_PROPERTIES and + # ALLOWED_CSS_KEYWORDS, are allowed through. attributes in ATTR_VAL_IS_URI + # are scanned, and only URI schemes specified in ALLOWED_PROTOCOLS are + # allowed. + # + # sanitize_html('') + # => <script> do_nasty_stuff() </script> + # sanitize_html('Click here for $100') + # => Click here for $100 + def sanitize_token(self, token): + + # accommodate filters which use token_type differently + token_type = token["type"] + if token_type in ("StartTag", "EndTag", "EmptyTag"): + name = token["name"] + namespace = token["namespace"] + if ((namespace, name) in self.allowed_elements or + (namespace is None and + (namespaces["html"], name) in self.allowed_elements)): + return self.allowed_token(token) + else: + return self.disallowed_token(token) + elif token_type == "Comment": + pass + else: + return token + + def allowed_token(self, token): + if "data" in token: + attrs = token["data"] + attr_names = set(attrs.keys()) + + # Remove forbidden attributes + for to_remove in (attr_names - self.allowed_attributes): + del token["data"][to_remove] + attr_names.remove(to_remove) + + # Remove attributes with disallowed URL values + for attr in (attr_names & self.attr_val_is_uri): + assert attr in attrs + # I don't have a clue where this regexp comes from or why it matches those + # characters, nor why we call unescape. I just know it's always been here. + # Should you be worried by this comment in a sanitizer? Yes. On the other hand, all + # this will do is remove *more* than it otherwise would. + val_unescaped = re.sub("[`\x00-\x20\x7f-\xa0\\s]+", '', + unescape(attrs[attr])).lower() + # remove replacement characters from unescaped characters + val_unescaped = val_unescaped.replace("\ufffd", "") + try: + uri = urlparse.urlparse(val_unescaped) + except ValueError: + uri = None + del attrs[attr] + if uri and uri.scheme: + if uri.scheme not in self.allowed_protocols: + del attrs[attr] + if uri.scheme == 'data': + m = data_content_type.match(uri.path) + if not m: + del attrs[attr] + elif m.group('content_type') not in self.allowed_content_types: + del attrs[attr] + + for attr in self.svg_attr_val_allows_ref: + if attr in attrs: + attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', + ' ', + unescape(attrs[attr])) + if (token["name"] in self.svg_allow_local_href and + (namespaces['xlink'], 'href') in attrs and re.search(r'^\s*[^#\s].*', + attrs[(namespaces['xlink'], 'href')])): + del attrs[(namespaces['xlink'], 'href')] + if (None, 'style') in attrs: + attrs[(None, 'style')] = self.sanitize_css(attrs[(None, 'style')]) + token["data"] = attrs + return token + + def disallowed_token(self, token): + token_type = token["type"] + if token_type == "EndTag": + token["data"] = "" % token["name"] + elif token["data"]: + assert token_type in ("StartTag", "EmptyTag") + attrs = [] + for (ns, name), v in token["data"].items(): + attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v))) + token["data"] = "<%s%s>" % (token["name"], ''.join(attrs)) + else: + token["data"] = "<%s>" % token["name"] + if token.get("selfClosing"): + token["data"] = token["data"][:-1] + "/>" + + token["type"] = "Characters" + + del token["name"] + return token + + def sanitize_css(self, style): + # disallow urls + style = re.compile(r'url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) + + # gauntlet + if not re.match(r"""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): + return '' + if not re.match(r"^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): + return '' + + clean = [] + for prop, value in re.findall(r"([-\w]+)\s*:\s*([^:;]*)", style): + if not value: + continue + if prop.lower() in self.allowed_css_properties: + clean.append(prop + ': ' + value + ';') + elif prop.split('-')[0].lower() in ['background', 'border', 'margin', + 'padding']: + for keyword in value.split(): + if keyword not in self.allowed_css_keywords and \ + not re.match(r"^(#[0-9a-fA-F]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$", keyword): # noqa + break + else: + clean.append(prop + ': ' + value + ';') + elif prop.lower() in self.allowed_svg_properties: + clean.append(prop + ': ' + value + ';') + + return ' '.join(clean) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/whitespace.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/whitespace.py new file mode 100644 index 0000000000000000000000000000000000000000..0d12584b45995d35110f75af00193fdad0fa10f4 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/filters/whitespace.py @@ -0,0 +1,38 @@ +from __future__ import absolute_import, division, unicode_literals + +import re + +from . import base +from ..constants import rcdataElements, spaceCharacters +spaceCharacters = "".join(spaceCharacters) + +SPACES_REGEX = re.compile("[%s]+" % spaceCharacters) + + +class Filter(base.Filter): + """Collapses whitespace except in pre, textarea, and script elements""" + spacePreserveElements = frozenset(["pre", "textarea"] + list(rcdataElements)) + + def __iter__(self): + preserve = 0 + for token in base.Filter.__iter__(self): + type = token["type"] + if type == "StartTag" \ + and (preserve or token["name"] in self.spacePreserveElements): + preserve += 1 + + elif type == "EndTag" and preserve: + preserve -= 1 + + elif not preserve and type == "SpaceCharacters" and token["data"]: + # Test on token["data"] above to not introduce spaces where there were not + token["data"] = " " + + elif not preserve and type == "Characters": + token["data"] = collapse_spaces(token["data"]) + + yield token + + +def collapse_spaces(text): + return SPACES_REGEX.sub(' ', text) diff --git a/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/html5parser.py b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/html5parser.py new file mode 100644 index 0000000000000000000000000000000000000000..74d829d9847ee4f8f7e5361c14104e82787e62f9 --- /dev/null +++ b/MLPY/Lib/site-packages/tensorboard/_vendor/html5lib/html5parser.py @@ -0,0 +1,2795 @@ +from __future__ import absolute_import, division, unicode_literals +from six import with_metaclass, viewkeys + +import types + +from . import _inputstream +from . import _tokenizer + +from . import treebuilders +from .treebuilders.base import Marker + +from . import _utils +from .constants import ( + spaceCharacters, asciiUpper2Lower, + specialElements, headingElements, cdataElements, rcdataElements, + tokenTypes, tagTokenTypes, + namespaces, + htmlIntegrationPointElements, mathmlTextIntegrationPointElements, + adjustForeignAttributes as adjustForeignAttributesMap, + adjustMathMLAttributes, adjustSVGAttributes, + E, + _ReparseException +) + + +def parse(doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs): + """Parse an HTML document as a string or file-like object into a tree + + :arg doc: the document to parse as a string or file-like object + + :arg treebuilder: the treebuilder to use when parsing + + :arg namespaceHTMLElements: whether or not to namespace HTML elements + + :returns: parsed tree + + Example: + + >>> from html5lib.html5parser import parse + >>> parse('

This is a doc

') + + + """ + tb = treebuilders.getTreeBuilder(treebuilder) + p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) + return p.parse(doc, **kwargs) + + +def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs): + """Parse an HTML fragment as a string or file-like object into a tree + + :arg doc: the fragment to parse as a string or file-like object + + :arg container: the container context to parse the fragment in + + :arg treebuilder: the treebuilder to use when parsing + + :arg namespaceHTMLElements: whether or not to namespace HTML elements + + :returns: parsed tree + + Example: + + >>> from html5lib.html5libparser import parseFragment + >>> parseFragment('this is a fragment') + + + """ + tb = treebuilders.getTreeBuilder(treebuilder) + p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) + return p.parseFragment(doc, container=container, **kwargs) + + +def method_decorator_metaclass(function): + class Decorated(type): + def __new__(meta, classname, bases, classDict): + for attributeName, attribute in classDict.items(): + if isinstance(attribute, types.FunctionType): + attribute = function(attribute) + + classDict[attributeName] = attribute + return type.__new__(meta, classname, bases, classDict) + return Decorated + + +class HTMLParser(object): + """HTML parser + + Generates a tree structure from a stream of (possibly malformed) HTML. + + """ + + def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False): + """ + :arg tree: a treebuilder class controlling the type of tree that will be + returned. Built in treebuilders can be accessed through + html5lib.treebuilders.getTreeBuilder(treeType) + + :arg strict: raise an exception when a parse error is encountered + + :arg namespaceHTMLElements: whether or not to namespace HTML elements + + :arg debug: whether or not to enable debug mode which logs things + + Example: + + >>> from html5lib.html5parser import HTMLParser + >>> parser = HTMLParser() # generates parser with etree builder + >>> parser = HTMLParser('lxml', strict=True) # generates parser with lxml builder which is strict + + """ + + # Raise an exception on the first error encountered + self.strict = strict + + if tree is None: + tree = treebuilders.getTreeBuilder("etree") + self.tree = tree(namespaceHTMLElements) + self.errors = [] + + self.phases = {name: cls(self, self.tree) for name, cls in + getPhases(debug).items()} + + def _parse(self, stream, innerHTML=False, container="div", scripting=False, **kwargs): + + self.innerHTMLMode = innerHTML + self.container = container + self.scripting = scripting + self.tokenizer = _tokenizer.HTMLTokenizer(stream, parser=self, **kwargs) + self.reset() + + try: + self.mainLoop() + except _ReparseException: + self.reset() + self.mainLoop() + + def reset(self): + self.tree.reset() + self.firstStartTag = False + self.errors = [] + self.log = [] # only used with debug mode + # "quirks" / "limited quirks" / "no quirks" + self.compatMode = "no quirks" + + if self.innerHTMLMode: + self.innerHTML = self.container.lower() + + if self.innerHTML in cdataElements: + self.tokenizer.state = self.tokenizer.rcdataState + elif self.innerHTML in rcdataElements: + self.tokenizer.state = self.tokenizer.rawtextState + elif self.innerHTML == 'plaintext': + self.tokenizer.state = self.tokenizer.plaintextState + else: + # state already is data state + # self.tokenizer.state = self.tokenizer.dataState + pass + self.phase = self.phases["beforeHtml"] + self.phase.insertHtmlElement() + self.resetInsertionMode() + else: + self.innerHTML = False # pylint:disable=redefined-variable-type + self.phase = self.phases["initial"] + + self.lastPhase = None + + self.beforeRCDataPhase = None + + self.framesetOK = True + + @property + def documentEncoding(self): + """Name of the character encoding that was used to decode the input stream, or + :obj:`None` if that is not determined yet + + """ + if not hasattr(self, 'tokenizer'): + return None + return self.tokenizer.stream.charEncoding[0].name + + def isHTMLIntegrationPoint(self, element): + if (element.name == "annotation-xml" and + element.namespace == namespaces["mathml"]): + return ("encoding" in element.attributes and + element.attributes["encoding"].translate( + asciiUpper2Lower) in + ("text/html", "application/xhtml+xml")) + else: + return (element.namespace, element.name) in htmlIntegrationPointElements + + def isMathMLTextIntegrationPoint(self, element): + return (element.namespace, element.name) in mathmlTextIntegrationPointElements + + def mainLoop(self): + CharactersToken = tokenTypes["Characters"] + SpaceCharactersToken = tokenTypes["SpaceCharacters"] + StartTagToken = tokenTypes["StartTag"] + EndTagToken = tokenTypes["EndTag"] + CommentToken = tokenTypes["Comment"] + DoctypeToken = tokenTypes["Doctype"] + ParseErrorToken = tokenTypes["ParseError"] + + for token in self.tokenizer: + prev_token = None + new_token = token + while new_token is not None: + prev_token = new_token + currentNode = self.tree.openElements[-1] if self.tree.openElements else None + currentNodeNamespace = currentNode.namespace if currentNode else None + currentNodeName = currentNode.name if currentNode else None + + type = new_token["type"] + + if type == ParseErrorToken: + self.parseError(new_token["data"], new_token.get("datavars", {})) + new_token = None + else: + if (len(self.tree.openElements) == 0 or + currentNodeNamespace == self.tree.defaultNamespace or + (self.isMathMLTextIntegrationPoint(currentNode) and + ((type == StartTagToken and + token["name"] not in frozenset(["mglyph", "malignmark"])) or + type in (CharactersToken, SpaceCharactersToken))) or + (currentNodeNamespace == namespaces["mathml"] and + currentNodeName == "annotation-xml" and + type == StartTagToken and + token["name"] == "svg") or + (self.isHTMLIntegrationPoint(currentNode) and + type in (StartTagToken, CharactersToken, SpaceCharactersToken))): + phase = self.phase + else: + phase = self.phases["inForeignContent"] + + if type == CharactersToken: + new_token = phase.processCharacters(new_token) + elif type == SpaceCharactersToken: + new_token = phase.processSpaceCharacters(new_token) + elif type == StartTagToken: + new_token = phase.processStartTag(new_token) + elif type == EndTagToken: + new_token = phase.processEndTag(new_token) + elif type == CommentToken: + new_token = phase.processComment(new_token) + elif type == DoctypeToken: + new_token = phase.processDoctype(new_token) + + if (type == StartTagToken and prev_token["selfClosing"] and + not prev_token["selfClosingAcknowledged"]): + self.parseError("non-void-element-with-trailing-solidus", + {"name": prev_token["name"]}) + + # When the loop finishes it's EOF + reprocess = True + phases = [] + while reprocess: + phases.append(self.phase) + reprocess = self.phase.processEOF() + if reprocess: + assert self.phase not in phases + + def parse(self, stream, *args, **kwargs): + """Parse a HTML document into a well-formed tree + + :arg stream: a file-like object or string containing the HTML to be parsed + + The optional encoding parameter must be a string that indicates + the encoding. If specified, that encoding will be used, + regardless of any BOM or later declaration (such as in a meta + element). + + :arg scripting: treat noscript elements as if JavaScript was turned on + + :returns: parsed tree + + Example: + + >>> from html5lib.html5parser import HTMLParser + >>> parser = HTMLParser() + >>> parser.parse('

This is a doc

') + + + """ + self._parse(stream, False, None, *args, **kwargs) + return self.tree.getDocument() + + def parseFragment(self, stream, *args, **kwargs): + """Parse a HTML fragment into a well-formed tree fragment + + :arg container: name of the element we're setting the innerHTML + property if set to None, default to 'div' + + :arg stream: a file-like object or string containing the HTML to be parsed + + The optional encoding parameter must be a string that indicates + the encoding. If specified, that encoding will be used, + regardless of any BOM or later declaration (such as in a meta + element) + + :arg scripting: treat noscript elements as if JavaScript was turned on + + :returns: parsed tree + + Example: + + >>> from html5lib.html5libparser import HTMLParser + >>> parser = HTMLParser() + >>> parser.parseFragment('this is a fragment') + + + """ + self._parse(stream, True, *args, **kwargs) + return self.tree.getFragment() + + def parseError(self, errorcode="XXX-undefined-error", datavars=None): + # XXX The idea is to make errorcode mandatory. + if datavars is None: + datavars = {} + self.errors.append((self.tokenizer.stream.position(), errorcode, datavars)) + if self.strict: + raise ParseError(E[errorcode] % datavars) + + def adjustMathMLAttributes(self, token): + adjust_attributes(token, adjustMathMLAttributes) + + def adjustSVGAttributes(self, token): + adjust_attributes(token, adjustSVGAttributes) + + def adjustForeignAttributes(self, token): + adjust_attributes(token, adjustForeignAttributesMap) + + def reparseTokenNormal(self, token): + # pylint:disable=unused-argument + self.parser.phase() + + def resetInsertionMode(self): + # The name of this method is mostly historical. (It's also used in the + # specification.) + last = False + newModes = { + "select": "inSelect", + "td": "inCell", + "th": "inCell", + "tr": "inRow", + "tbody": "inTableBody", + "thead": "inTableBody", + "tfoot": "inTableBody", + "caption": "inCaption", + "colgroup": "inColumnGroup", + "table": "inTable", + "head": "inBody", + "body": "inBody", + "frameset": "inFrameset", + "html": "beforeHead" + } + for node in self.tree.openElements[::-1]: + nodeName = node.name + new_phase = None + if node == self.tree.openElements[0]: + assert self.innerHTML + last = True + nodeName = self.innerHTML + # Check for conditions that should only happen in the innerHTML + # case + if nodeName in ("select", "colgroup", "head", "html"): + assert self.innerHTML + + if not last and node.namespace != self.tree.defaultNamespace: + continue + + if nodeName in newModes: + new_phase = self.phases[newModes[nodeName]] + break + elif last: + new_phase = self.phases["inBody"] + break + + self.phase = new_phase + + def parseRCDataRawtext(self, token, contentType): + # Generic RCDATA/RAWTEXT Parsing algorithm + assert contentType in ("RAWTEXT", "RCDATA") + + self.tree.insertElement(token) + + if contentType == "RAWTEXT": + self.tokenizer.state = self.tokenizer.rawtextState + else: + self.tokenizer.state = self.tokenizer.rcdataState + + self.originalPhase = self.phase + + self.phase = self.phases["text"] + + +@_utils.memoize +def getPhases(debug): + def log(function): + """Logger that records which phase processes each token""" + type_names = {value: key for key, value in tokenTypes.items()} + + def wrapped(self, *args, **kwargs): + if function.__name__.startswith("process") and len(args) > 0: + token = args[0] + info = {"type": type_names[token['type']]} + if token['type'] in tagTokenTypes: + info["name"] = token['name'] + + self.parser.log.append((self.parser.tokenizer.state.__name__, + self.parser.phase.__class__.__name__, + self.__class__.__name__, + function.__name__, + info)) + return function(self, *args, **kwargs) + else: + return function(self, *args, **kwargs) + return wrapped + + def getMetaclass(use_metaclass, metaclass_func): + if use_metaclass: + return method_decorator_metaclass(metaclass_func) + else: + return type + + # pylint:disable=unused-argument + class Phase(with_metaclass(getMetaclass(debug, log))): + """Base class for helper object that implements each phase of processing + """ + __slots__ = ("parser", "tree", "__startTagCache", "__endTagCache") + + def __init__(self, parser, tree): + self.parser = parser + self.tree = tree + self.__startTagCache = {} + self.__endTagCache = {} + + def processEOF(self): + raise NotImplementedError + + def processComment(self, token): + # For most phases the following is correct. Where it's not it will be + # overridden. + self.tree.insertComment(token, self.tree.openElements[-1]) + + def processDoctype(self, token): + self.parser.parseError("unexpected-doctype") + + def processCharacters(self, token): + self.tree.insertText(token["data"]) + + def processSpaceCharacters(self, token): + self.tree.insertText(token["data"]) + + def processStartTag(self, token): + # Note the caching is done here rather than BoundMethodDispatcher as doing it there + # requires a circular reference to the Phase, and this ends up with a significant + # (CPython 2.7, 3.8) GC cost when parsing many short inputs + name = token["name"] + # In Py2, using `in` is quicker in general than try/except KeyError + # In Py3, `in` is quicker when there are few cache hits (typically short inputs) + if name in self.__startTagCache: + func = self.__startTagCache[name] + else: + func = self.__startTagCache[name] = self.startTagHandler[name] + # bound the cache size in case we get loads of unknown tags + while len(self.__startTagCache) > len(self.startTagHandler) * 1.1: + # this makes the eviction policy random on Py < 3.7 and FIFO >= 3.7 + self.__startTagCache.pop(next(iter(self.__startTagCache))) + return func(token) + + def startTagHtml(self, token): + if not self.parser.firstStartTag and token["name"] == "html": + self.parser.parseError("non-html-root") + # XXX Need a check here to see if the first start tag token emitted is + # this token... If it's not, invoke self.parser.parseError(). + for attr, value in token["data"].items(): + if attr not in self.tree.openElements[0].attributes: + self.tree.openElements[0].attributes[attr] = value + self.parser.firstStartTag = False + + def processEndTag(self, token): + # Note the caching is done here rather than BoundMethodDispatcher as doing it there + # requires a circular reference to the Phase, and this ends up with a significant + # (CPython 2.7, 3.8) GC cost when parsing many short inputs + name = token["name"] + # In Py2, using `in` is quicker in general than try/except KeyError + # In Py3, `in` is quicker when there are few cache hits (typically short inputs) + if name in self.__endTagCache: + func = self.__endTagCache[name] + else: + func = self.__endTagCache[name] = self.endTagHandler[name] + # bound the cache size in case we get loads of unknown tags + while len(self.__endTagCache) > len(self.endTagHandler) * 1.1: + # this makes the eviction policy random on Py < 3.7 and FIFO >= 3.7 + self.__endTagCache.pop(next(iter(self.__endTagCache))) + return func(token) + + class InitialPhase(Phase): + __slots__ = tuple() + + def processSpaceCharacters(self, token): + pass + + def processComment(self, token): + self.tree.insertComment(token, self.tree.document) + + def processDoctype(self, token): + name = token["name"] + publicId = token["publicId"] + systemId = token["systemId"] + correct = token["correct"] + + if (name != "html" or publicId is not None or + systemId is not None and systemId != "about:legacy-compat"): + self.parser.parseError("unknown-doctype") + + if publicId is None: + publicId = "" + + self.tree.insertDoctype(token) + + if publicId != "": + publicId = publicId.translate(asciiUpper2Lower) + + if (not correct or token["name"] != "html" or + publicId.startswith( + ("+//silmaril//dtd html pro v0r11 19970101//", + "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", + "-//as//dtd html 3.0 aswedit + extensions//", + "-//ietf//dtd html 2.0 level 1//", + "-//ietf//dtd html 2.0 level 2//", + "-//ietf//dtd html 2.0 strict level 1//", + "-//ietf//dtd html 2.0 strict level 2//", + "-//ietf//dtd html 2.0 strict//", + "-//ietf//dtd html 2.0//", + "-//ietf//dtd html 2.1e//", + "-//ietf//dtd html 3.0//", + "-//ietf//dtd html 3.2 final//", + "-//ietf//dtd html 3.2//", + "-//ietf//dtd html 3//", + "-//ietf//dtd html level 0//", + "-//ietf//dtd html level 1//", + "-//ietf//dtd html level 2//", + "-//ietf//dtd html level 3//", + "-//ietf//dtd html strict level 0//", + "-//ietf//dtd html strict level 1//", + "-//ietf//dtd html strict level 2//", + "-//ietf//dtd html strict level 3//", + "-//ietf//dtd html strict//", + "-//ietf//dtd html//", + "-//metrius//dtd metrius presentational//", + "-//microsoft//dtd internet explorer 2.0 html strict//", + "-//microsoft//dtd internet explorer 2.0 html//", + "-//microsoft//dtd internet explorer 2.0 tables//", + "-//microsoft//dtd internet explorer 3.0 html strict//", + "-//microsoft//dtd internet explorer 3.0 html//", + "-//microsoft//dtd internet explorer 3.0 tables//", + "-//netscape comm. corp.//dtd html//", + "-//netscape comm. corp.//dtd strict html//", + "-//o'reilly and associates//dtd html 2.0//", + "-//o'reilly and associates//dtd html extended 1.0//", + "-//o'reilly and associates//dtd html extended relaxed 1.0//", + "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", + "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", + "-//spyglass//dtd html 2.0 extended//", + "-//sq//dtd html 2.0 hotmetal + extensions//", + "-//sun microsystems corp.//dtd hotjava html//", + "-//sun microsystems corp.//dtd hotjava strict html//", + "-//w3c//dtd html 3 1995-03-24//", + "-//w3c//dtd html 3.2 draft//", + "-//w3c//dtd html 3.2 final//", + "-//w3c//dtd html 3.2//", + "-//w3c//dtd html 3.2s draft//", + "-//w3c//dtd html 4.0 frameset//", + "-//w3c//dtd html 4.0 transitional//", + "-//w3c//dtd html experimental 19960712//", + "-//w3c//dtd html experimental 970421//", + "-//w3c//dtd w3 html//", + "-//w3o//dtd w3 html 3.0//", + "-//webtechs//dtd mozilla html 2.0//", + "-//webtechs//dtd mozilla html//")) or + publicId in ("-//w3o//dtd w3 html strict 3.0//en//", + "-/w3c/dtd html 4.0 transitional/en", + "html") or + publicId.startswith( + ("-//w3c//dtd html 4.01 frameset//", + "-//w3c//dtd html 4.01 transitional//")) and + systemId is None or + systemId and systemId.lower() == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"): + self.parser.compatMode = "quirks" + elif (publicId.startswith( + ("-//w3c//dtd xhtml 1.0 frameset//", + "-//w3c//dtd xhtml 1.0 transitional//")) or + publicId.startswith( + ("-//w3c//dtd html 4.01 frameset//", + "-//w3c//dtd html 4.01 transitional//")) and + systemId is not None): + self.parser.compatMode = "limited quirks" + + self.parser.phase = self.parser.phases["beforeHtml"] + + def anythingElse(self): + self.parser.compatMode = "quirks" + self.parser.phase = self.parser.phases["beforeHtml"] + + def processCharacters(self, token): + self.parser.parseError("expected-doctype-but-got-chars") + self.anythingElse() + return token + + def processStartTag(self, token): + self.parser.parseError("expected-doctype-but-got-start-tag", + {"name": token["name"]}) + self.anythingElse() + return token + + def processEndTag(self, token): + self.parser.parseError("expected-doctype-but-got-end-tag", + {"name": token["name"]}) + self.anythingElse() + return token + + def processEOF(self): + self.parser.parseError("expected-doctype-but-got-eof") + self.anythingElse() + return True + + class BeforeHtmlPhase(Phase): + __slots__ = tuple() + + # helper methods + def insertHtmlElement(self): + self.tree.insertRoot(impliedTagToken("html", "StartTag")) + self.parser.phase = self.parser.phases["beforeHead"] + + # other + def processEOF(self): + self.insertHtmlElement() + return True + + def processComment(self, token): + self.tree.insertComment(token, self.tree.document) + + def processSpaceCharacters(self, token): + pass + + def processCharacters(self, token): + self.insertHtmlElement() + return token + + def processStartTag(self, token): + if token["name"] == "html": + self.parser.firstStartTag = True + self.insertHtmlElement() + return token + + def processEndTag(self, token): + if token["name"] not in ("head", "body", "html", "br"): + self.parser.parseError("unexpected-end-tag-before-html", + {"name": token["name"]}) + else: + self.insertHtmlElement() + return token + + class BeforeHeadPhase(Phase): + __slots__ = tuple() + + def processEOF(self): + self.startTagHead(impliedTagToken("head", "StartTag")) + return True + + def processSpaceCharacters(self, token): + pass + + def processCharacters(self, token): + self.startTagHead(impliedTagToken("head", "StartTag")) + return token + + def startTagHtml(self, token): + return self.parser.phases["inBody"].processStartTag(token) + + def startTagHead(self, token): + self.tree.insertElement(token) + self.tree.headPointer = self.tree.openElements[-1] + self.parser.phase = self.parser.phases["inHead"] + + def startTagOther(self, token): + self.startTagHead(impliedTagToken("head", "StartTag")) + return token + + def endTagImplyHead(self, token): + self.startTagHead(impliedTagToken("head", "StartTag")) + return token + + def endTagOther(self, token): + self.parser.parseError("end-tag-after-implied-root", + {"name": token["name"]}) + + startTagHandler = _utils.MethodDispatcher([ + ("html", startTagHtml), + ("head", startTagHead) + ]) + startTagHandler.default = startTagOther + + endTagHandler = _utils.MethodDispatcher([ + (("head", "body", "html", "br"), endTagImplyHead) + ]) + endTagHandler.default = endTagOther + + class InHeadPhase(Phase): + __slots__ = tuple() + + # the real thing + def processEOF(self): + self.anythingElse() + return True + + def processCharacters(self, token): + self.anythingElse() + return token + + def startTagHtml(self, token): + return self.parser.phases["inBody"].processStartTag(token) + + def startTagHead(self, token): + self.parser.parseError("two-heads-are-not-better-than-one") + + def startTagBaseLinkCommand(self, token): + self.tree.insertElement(token) + self.tree.openElements.pop() + token["selfClosingAcknowledged"] = True + + def startTagMeta(self, token): + self.tree.insertElement(token) + self.tree.openElements.pop() + token["selfClosingAcknowledged"] = True + + attributes = token["data"] + if self.parser.tokenizer.stream.charEncoding[1] == "tentative": + if "charset" in attributes: + self.parser.tokenizer.stream.changeEncoding(attributes["charset"]) + elif ("content" in attributes and + "http-equiv" in attributes and + attributes["http-equiv"].lower() == "content-type"): + # Encoding it as UTF-8 here is a hack, as really we should pass + # the abstract Unicode string, and just use the + # ContentAttrParser on that, but using UTF-8 allows all chars + # to be encoded and as a ASCII-superset works. + data = _inputstream.EncodingBytes(attributes["content"].encode("utf-8")) + parser = _inputstream.ContentAttrParser(data) + codec = parser.parse() + self.parser.tokenizer.stream.changeEncoding(codec) + + def startTagTitle(self, token): + self.parser.parseRCDataRawtext(token, "RCDATA") + + def startTagNoFramesStyle(self, token): + # Need to decide whether to implement the scripting-disabled case + self.parser.parseRCDataRawtext(token, "RAWTEXT") + + def startTagNoscript(self, token): + if self.parser.scripting: + self.parser.parseRCDataRawtext(token, "RAWTEXT") + else: + self.tree.insertElement(token) + self.parser.phase = self.parser.phases["inHeadNoscript"] + + def startTagScript(self, token): + self.tree.insertElement(token) + self.parser.tokenizer.state = self.parser.tokenizer.scriptDataState + self.parser.originalPhase = self.parser.phase + self.parser.phase = self.parser.phases["text"] + + def startTagOther(self, token): + self.anythingElse() + return token + + def endTagHead(self, token): + node = self.parser.tree.openElements.pop() + assert node.name == "head", "Expected head got %s" % node.name + self.parser.phase = self.parser.phases["afterHead"] + + def endTagHtmlBodyBr(self, token): + self.anythingElse() + return token + + def endTagOther(self, token): + self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) + + def anythingElse(self): + self.endTagHead(impliedTagToken("head")) + + startTagHandler = _utils.MethodDispatcher([ + ("html", startTagHtml), + ("title", startTagTitle), + (("noframes", "style"), startTagNoFramesStyle), + ("noscript", startTagNoscript), + ("script", startTagScript), + (("base", "basefont", "bgsound", "command", "link"), + startTagBaseLinkCommand), + ("meta", startTagMeta), + ("head", startTagHead) + ]) + startTagHandler.default = startTagOther + + endTagHandler = _utils.MethodDispatcher([ + ("head", endTagHead), + (("br", "html", "body"), endTagHtmlBodyBr) + ]) + endTagHandler.default = endTagOther + + class InHeadNoscriptPhase(Phase): + __slots__ = tuple() + + def processEOF(self): + self.parser.parseError("eof-in-head-noscript") + self.anythingElse() + return True + + def processComment(self, token): + return self.parser.phases["inHead"].processComment(token) + + def processCharacters(self, token): + self.parser.parseError("char-in-head-noscript") + self.anythingElse() + return token + + def processSpaceCharacters(self, token): + return self.parser.phases["inHead"].processSpaceCharacters(token) + + def startTagHtml(self, token): + return self.parser.phases["inBody"].processStartTag(token) + + def startTagBaseLinkCommand(self, token): + return self.parser.phases["inHead"].processStartTag(token) + + def startTagHeadNoscript(self, token): + self.parser.parseError("unexpected-start-tag", {"name": token["name"]}) + + def startTagOther(self, token): + self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]}) + self.anythingElse() + return token + + def endTagNoscript(self, token): + node = self.parser.tree.openElements.pop() + assert node.name == "noscript", "Expected noscript got %s" % node.name + self.parser.phase = self.parser.phases["inHead"] + + def endTagBr(self, token): + self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]}) + self.anythingElse() + return token + + def endTagOther(self, token): + self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) + + def anythingElse(self): + # Caller must raise parse error first! + self.endTagNoscript(impliedTagToken("noscript")) + + startTagHandler = _utils.MethodDispatcher([ + ("html", startTagHtml), + (("basefont", "bgsound", "link", "meta", "noframes", "style"), startTagBaseLinkCommand), + (("head", "noscript"), startTagHeadNoscript), + ]) + startTagHandler.default = startTagOther + + endTagHandler = _utils.MethodDispatcher([ + ("noscript", endTagNoscript), + ("br", endTagBr), + ]) + endTagHandler.default = endTagOther + + class AfterHeadPhase(Phase): + __slots__ = tuple() + + def processEOF(self): + self.anythingElse() + return True + + def processCharacters(self, token): + self.anythingElse() + return token + + def startTagHtml(self, token): + return self.parser.phases["inBody"].processStartTag(token) + + def startTagBody(self, token): + self.parser.framesetOK = False + self.tree.insertElement(token) + self.parser.phase = self.parser.phases["inBody"] + + def startTagFrameset(self, token): + self.tree.insertElement(token) + self.parser.phase = self.parser.phases["inFrameset"] + + def startTagFromHead(self, token): + self.parser.parseError("unexpected-start-tag-out-of-my-head", + {"name": token["name"]}) + self.tree.openElements.append(self.tree.headPointer) + self.parser.phases["inHead"].processStartTag(token) + for node in self.tree.openElements[::-1]: + if node.name == "head": + self.tree.openElements.remove(node) + break + + def startTagHead(self, token): + self.parser.parseError("unexpected-start-tag", {"name": token["name"]}) + + def startTagOther(self, token): + self.anythingElse() + return token + + def endTagHtmlBodyBr(self, token): + self.anythingElse() + return token + + def endTagOther(self, token): + self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) + + def anythingElse(self): + self.tree.insertElement(impliedTagToken("body", "StartTag")) + self.parser.phase = self.parser.phases["inBody"] + self.parser.framesetOK = True + + startTagHandler = _utils.MethodDispatcher([ + ("html", startTagHtml), + ("body", startTagBody), + ("frameset", startTagFrameset), + (("base", "basefont", "bgsound", "link", "meta", "noframes", "script", + "style", "title"), + startTagFromHead), + ("head", startTagHead) + ]) + startTagHandler.default = startTagOther + endTagHandler = _utils.MethodDispatcher([(("body", "html", "br"), + endTagHtmlBodyBr)]) + endTagHandler.default = endTagOther + + class InBodyPhase(Phase): + # http://www.whatwg.org/specs/web-apps/current-work/#parsing-main-inbody + # the really-really-really-very crazy mode + __slots__ = ("processSpaceCharacters",) + + def __init__(self, *args, **kwargs): + super(InBodyPhase, self).__init__(*args, **kwargs) + # Set this to the default handler + self.processSpaceCharacters = self.processSpaceCharactersNonPre + + def isMatchingFormattingElement(self, node1, node2): + return (node1.name == node2.name and + node1.namespace == node2.namespace and + node1.attributes == node2.attributes) + + # helper + def addFormattingElement(self, token): + self.tree.insertElement(token) + element = self.tree.openElements[-1] + + matchingElements = [] + for node in self.tree.activeFormattingElements[::-1]: + if node is Marker: + break + elif self.isMatchingFormattingElement(node, element): + matchingElements.append(node) + + assert len(matchingElements) <= 3 + if len(matchingElements) == 3: + self.tree.activeFormattingElements.remove(matchingElements[-1]) + self.tree.activeFormattingElements.append(element) + + # the real deal + def processEOF(self): + allowed_elements = frozenset(("dd", "dt", "li", "p", "tbody", "td", + "tfoot", "th", "thead", "tr", "body", + "html")) + for node in self.tree.openElements[::-1]: + if node.name not in allowed_elements: + self.parser.parseError("expected-closing-tag-but-got-eof") + break + # Stop parsing + + def processSpaceCharactersDropNewline(self, token): + # Sometimes (start of
, , and 
+    
+`,is:"iron-autogrow-textarea",behaviors:[vi,hn],properties:{value:{observer:"_valueChanged",type:String,notify:!0},bindValue:{observer:"_bindValueChanged",type:String,notify:!0},rows:{type:Number,value:1,observer:"_updateCached"},maxRows:{type:Number,value:0,observer:"_updateCached"},autocomplete:{type:String,value:"off"},autofocus:{type:Boolean,value:!1},autocapitalize:{type:String,value:"none"},inputmode:{type:String},placeholder:{type:String},readonly:{type:String},required:{type:Boolean},minlength:{type:Number},maxlength:{type:Number},label:{type:String}},listeners:{input:"_onInput"},get textarea(){return this.$.textarea},get selectionStart(){return this.$.textarea.selectionStart},get selectionEnd(){return this.$.textarea.selectionEnd},set selectionStart(n){this.$.textarea.selectionStart=n},set selectionEnd(n){this.$.textarea.selectionEnd=n},attached:function(){var n=navigator.userAgent.match(/iP(?:[oa]d|hone)/)&&!navigator.userAgent.match(/OS 1[3456789]/);n&&(this.$.textarea.style.marginLeft="-3px")},validate:function(){var n=this.$.textarea.validity.valid;return n&&(this.required&&this.value===""?n=!1:this.hasValidator()&&(n=vi.validate.call(this,this.value))),this.invalid=!n,this.fire("iron-input-validate"),n},_bindValueChanged:function(n){this.value=n},_valueChanged:function(n){var t=this.textarea;!t||(t.value!==n&&(t.value=n||n===0?n:""),this.bindValue=n,this.$.mirror.innerHTML=this._valueForMirror(),this.fire("bind-value-changed",{value:this.bindValue}))},_onInput:function(n){var t=Ct(n).path;this.value=t?t[0].value:n.target.value},_constrain:function(n){var t;for(n=n||[""],this.maxRows>0&&n.length>this.maxRows?t=n.slice(0,this.maxRows):t=n.slice(0);this.rows>0&&t.length")+" "},_valueForMirror:function(){var n=this.textarea;if(!!n)return this.tokens=n&&n.value?n.value.replace(/&/gm,"&").replace(/"/gm,""").replace(/'/gm,"'").replace(//gm,">").split(`
+`):[""],this._constrain(this.tokens)},_updateCached:function(){this.$.mirror.innerHTML=this._constrain(this.tokens)}});At({_template:dt`
+    
+
+    
+
+      
+
+      
+
+      
+
+      
+
+    
+`,is:"paper-textarea",behaviors:[Yf,xi],properties:{_ariaLabelledBy:{observer:"_ariaLabelledByChanged",type:String},_ariaDescribedBy:{observer:"_ariaDescribedByChanged",type:String},value:{type:String},rows:{type:Number,value:1},maxRows:{type:Number,value:0}},get selectionStart(){return this.$.input.textarea.selectionStart},set selectionStart(n){this.$.input.textarea.selectionStart=n},get selectionEnd(){return this.$.input.textarea.selectionEnd},set selectionEnd(n){this.$.input.textarea.selectionEnd=n},_ariaLabelledByChanged:function(n){this._focusableElement.setAttribute("aria-labelledby",n)},_ariaDescribedByChanged:function(n){this._focusableElement.setAttribute("aria-describedby",n)},get _focusableElement(){return this.inputElement.textarea}});var q2=document.createElement("template");q2.setAttribute("style","display: none;");q2.innerHTML=`
+  
+`;document.head.appendChild(q2.content);var UH={hostAttributes:{role:"option",tabindex:"0"}},Jf=[mi,hn,UH];At({_template:dt`
+    
+    
+`,is:"paper-item",behaviors:[Jf]});At({_template:dt`
+    
+
+    
+`,is:"paper-item-body"});At({_template:dt`
+    
+    
+
+    
+ +
+ +`,is:"paper-icon-item",behaviors:[Jf]});var X2={properties:{multi:{type:Boolean,value:!1,observer:"multiChanged"},selectedValues:{type:Array,notify:!0,value:function(){return[]}},selectedItems:{type:Array,readOnly:!0,notify:!0,value:function(){return[]}}},observers:["_updateSelected(selectedValues.splices)"],select:function(n){this.multi?this._toggleSelected(n):this.selected=n},multiChanged:function(n){this._selection.multi=n,this._updateSelected()},get _shouldUpdateSelection(){return this.selected!=null||this.selectedValues!=null&&this.selectedValues.length},_updateAttrForSelected:function(){this.multi?this.selectedItems&&this.selectedItems.length>0&&(this.selectedValues=this.selectedItems.map(function(n){return this._indexToValue(this.indexOf(n))},this).filter(function(n){return n!=null},this)):fi._updateAttrForSelected.apply(this)},_updateSelected:function(){this.multi?this._selectMulti(this.selectedValues):this._selectSelected(this.selected)},_selectMulti:function(n){n=n||[];var t=(this._valuesToItems(n)||[]).filter(function(i){return i!=null});this._selection.clear(t);for(var e=0;e + :host { + display: block; + padding: 8px 0; + + background: var(--paper-listbox-background-color, var(--primary-background-color)); + color: var(--paper-listbox-color, var(--primary-text-color)); + + @apply --paper-listbox; + } + + + +`,is:"paper-listbox",behaviors:[Qf],hostAttributes:{role:"listbox"}});var J5=dt` + + + +`;J5.setAttribute("style","display: none;");document.body.appendChild(J5.content);At({_template:dt` + + + + +`,is:"paper-material",properties:{elevation:{type:Number,reflectToAttribute:!0,value:1},animated:{type:Boolean,reflectToAttribute:!0,value:!1}}});var tm={properties:{value:{type:Number,value:0,notify:!0,reflectToAttribute:!0},min:{type:Number,value:0,notify:!0},max:{type:Number,value:100,notify:!0},step:{type:Number,value:1,notify:!0},ratio:{type:Number,value:0,readOnly:!0,notify:!0}},observers:["_update(value, min, max, step)"],_calcRatio:function(n){return(this._clampValue(n)-this.min)/(this.max-this.min)},_clampValue:function(n){return Math.min(this.max,Math.max(this.min,this._calcStep(n)))},_calcStep:function(n){if(n=parseFloat(n),!this.step)return n;var t=Math.round((n-this.min)/this.step);return this.step<1?t/(1/this.step)+this.min:t*this.step+this.min},_validateValue:function(){var n=this._clampValue(this.value);return this.value=this.oldValue=isNaN(n)?this.oldValue:n,this.value!==n},_update:function(){this._validateValue(),this._setRatio(this._calcRatio(this.value)*100)}};At({_template:dt` + + +
+
+
+
+`,is:"paper-progress",behaviors:[tm],properties:{secondaryProgress:{type:Number,value:0},secondaryRatio:{type:Number,value:0,readOnly:!0},indeterminate:{type:Boolean,value:!1,observer:"_toggleIndeterminate"},disabled:{type:Boolean,value:!1,reflectToAttribute:!0,observer:"_disabledChanged"}},observers:["_progressChanged(secondaryProgress, value, min, max, indeterminate)"],hostAttributes:{role:"progressbar"},_toggleIndeterminate:function(n){this.toggleClass("indeterminate",n,this.$.primaryProgress)},_transformProgress:function(n,t){var e="scaleX("+t/100+")";n.style.transform=n.style.webkitTransform=e},_mainRatioChanged:function(n){this._transformProgress(this.$.primaryProgress,n)},_progressChanged:function(n,t,e,r,i){n=this._clampValue(n),t=this._clampValue(t);var o=this._calcRatio(n)*100,s=this._calcRatio(t)*100;this._setSecondaryRatio(o),this._transformProgress(this.$.secondaryProgress,o),this._transformProgress(this.$.primaryProgress,s),this.secondaryProgress=n,i?this.removeAttribute("aria-valuenow"):this.setAttribute("aria-valuenow",t),this.setAttribute("aria-valuemin",e),this.setAttribute("aria-valuemax",r)},_disabledChanged:function(n){this.setAttribute("aria-disabled",n?"true":"false")},_hideSecondaryProgress:function(n){return n===0}});var Q5=dt` + + +
+
+
+
+ +
`;Q5.setAttribute("strip-whitespace","");At({_template:Q5,is:"paper-radio-button",behaviors:[fl],hostAttributes:{role:"radio","aria-checked":!1,tabindex:0},properties:{ariaActiveAttribute:{type:String,value:"aria-checked"}},ready:function(){this._rippleContainer=this.$.radioContainer},attached:function(){al(this,function(){var n=this.getComputedStyleValue("--calculated-paper-radio-button-ink-size").trim();if(n==="-1px"){var t=parseFloat(this.getComputedStyleValue("--calculated-paper-radio-button-size").trim()),e=Math.floor(3*t);e%2!==t%2&&e++,this.updateStyles({"--paper-radio-button-ink-size":e+"px"})}})}});var em={hostAttributes:{role:"menubar"},keyBindings:{left:"_onLeftKey",right:"_onRightKey"},_onUpKey:function(n){this.focusedItem.click(),n.detail.keyboardEvent.preventDefault()},_onDownKey:function(n){this.focusedItem.click(),n.detail.keyboardEvent.preventDefault()},get _isRTL(){return window.getComputedStyle(this).direction==="rtl"},_onLeftKey:function(n){this._isRTL?this._focusNext():this._focusPrevious(),n.detail.keyboardEvent.preventDefault()},_onRightKey:function(n){this._isRTL?this._focusPrevious():this._focusNext(),n.detail.keyboardEvent.preventDefault()},_onKeydown:function(n){this.keyboardEventMatchesKeys(n,"up down left right esc")||this._focusWithKeyboardEvent(n)}},nm=[Qf,em];At({_template:dt` + + + +`,is:"paper-radio-group",behaviors:[nm],hostAttributes:{role:"radiogroup"},properties:{attrForSelected:{type:String,value:"name"},selectedAttribute:{type:String,value:"checked"},selectable:{type:String,value:"paper-radio-button"},allowEmptySelection:{type:Boolean,value:!1}},select:function(n){var t=this._valueToItem(n);if(!(t&&t.hasAttribute("disabled"))){if(this.selected){var e=this._valueToItem(this.selected);if(this.selected==n)if(this.allowEmptySelection)n="";else{e&&(e.checked=!0);return}e&&(e.checked=!1)}fi.select.apply(this,[n]),this.fire("paper-radio-group-changed")}},_activateFocusedItem:function(){this._itemActivate(this._valueForItem(this.focusedItem),this.focusedItem)},_onUpKey:function(n){this._focusPrevious(),n.preventDefault(),this._activateFocusedItem()},_onDownKey:function(n){this._focusNext(),n.preventDefault(),this._activateFocusedItem()},_onLeftKey:function(n){em._onLeftKey.apply(this,arguments),this._activateFocusedItem()},_onRightKey:function(n){em._onRightKey.apply(this,arguments),this._activateFocusedItem()}});var tE=dt` + + +
+
+ +
+ + + +
+
+
+
+ + +`;tE.setAttribute("strip-whitespace","");At({_template:tE,is:"paper-slider",behaviors:[Vn,xi,dl,tm],properties:{value:{type:Number,value:0},snaps:{type:Boolean,value:!1,notify:!0},pin:{type:Boolean,value:!1,notify:!0},secondaryProgress:{type:Number,value:0,notify:!0,observer:"_secondaryProgressChanged"},editable:{type:Boolean,value:!1},immediateValue:{type:Number,value:0,readOnly:!0,notify:!0},maxMarkers:{type:Number,value:0,notify:!0},expand:{type:Boolean,value:!1,readOnly:!0},ignoreBarTouch:{type:Boolean,value:!1},dragging:{type:Boolean,value:!1,readOnly:!0,notify:!0},transiting:{type:Boolean,value:!1,readOnly:!0},markers:{type:Array,readOnly:!0,value:function(){return[]}}},observers:["_updateKnob(value, min, max, snaps, step)","_valueChanged(value)","_immediateValueChanged(immediateValue)","_updateMarkers(maxMarkers, min, max, snaps)"],hostAttributes:{role:"slider",tabindex:0},keyBindings:{left:"_leftKey",right:"_rightKey","down pagedown home":"_decrementKey","up pageup end":"_incrementKey"},ready:function(){this.ignoreBarTouch&&Ns(this.$.sliderBar,"auto")},increment:function(){this.value=this._clampValue(this.value+this.step)},decrement:function(){this.value=this._clampValue(this.value-this.step)},_updateKnob:function(n,t,e,r,i){this.setAttribute("aria-valuemin",t),this.setAttribute("aria-valuemax",e),this.setAttribute("aria-valuenow",n),this._positionKnob(this._calcRatio(n)*100)},_valueChanged:function(){this.fire("value-change",{composed:!0})},_immediateValueChanged:function(){this.dragging?this.fire("immediate-value-change",{composed:!0}):this.value=this.immediateValue},_secondaryProgressChanged:function(){this.secondaryProgress=this._clampValue(this.secondaryProgress)},_expandKnob:function(){this._setExpand(!0)},_resetKnob:function(){this.cancelDebouncer("expandKnob"),this._setExpand(!1)},_positionKnob:function(n){this._setImmediateValue(this._calcStep(this._calcKnobPosition(n))),this._setRatio(this._calcRatio(this.immediateValue)*100),this.$.sliderKnob.style.left=this.ratio+"%",this.dragging&&(this._knobstartx=this.ratio*this._w/100,this.translate3d(0,0,0,this.$.sliderKnob))},_calcKnobPosition:function(n){return(this.max-this.min)*n/100+this.min},_onTrack:function(n){switch(n.stopPropagation(),n.detail.state){case"start":this._trackStart(n);break;case"track":this._trackX(n);break;case"end":this._trackEnd();break}},_trackStart:function(n){this._setTransiting(!1),this._w=this.$.sliderBar.offsetWidth,this._x=this.ratio*this._w/100,this._startx=this._x,this._knobstartx=this._startx,this._minx=-this._startx,this._maxx=this._w-this._startx,this.$.sliderKnob.classList.add("dragging"),this._setDragging(!0)},_trackX:function(n){this.dragging||this._trackStart(n);var t=this._isRTL?-1:1,e=Math.min(this._maxx,Math.max(this._minx,n.detail.dx*t));this._x=this._startx+e;var r=this._calcStep(this._calcKnobPosition(this._x/this._w*100));this._setImmediateValue(r);var i=this._calcRatio(this.immediateValue)*this._w-this._knobstartx;this.translate3d(i+"px",0,0,this.$.sliderKnob)},_trackEnd:function(){var n=this.$.sliderKnob.style;this.$.sliderKnob.classList.remove("dragging"),this._setDragging(!1),this._resetKnob(),this.value=this.immediateValue,n.transform=n.webkitTransform="",this.fire("change",{composed:!0})},_knobdown:function(n){this._expandKnob(),n.preventDefault(),this.focus()},_bartrack:function(n){this._allowBarEvent(n)&&this._onTrack(n)},_barclick:function(n){this._w=this.$.sliderBar.offsetWidth;var t=this.$.sliderBar.getBoundingClientRect(),e=(n.detail.x-t.left)/this._w*100;this._isRTL&&(e=100-e);var r=this.ratio;this._setTransiting(!0),this._positionKnob(e),r===this.ratio&&this._setTransiting(!1),this.async(function(){this.fire("change",{composed:!0})}),n.preventDefault(),this.focus()},_bardown:function(n){this._allowBarEvent(n)&&(this.debounce("expandKnob",this._expandKnob,60),this._barclick(n))},_knobTransitionEnd:function(n){n.target===this.$.sliderKnob&&this._setTransiting(!1)},_updateMarkers:function(n,t,e,r){r||this._setMarkers([]);var i=Math.round((e-t)/this.step);i>n&&(i=n),(i<0||!isFinite(i))&&(i=0),this._setMarkers(new Array(i))},_mergeClasses:function(n){return Object.keys(n).filter(function(t){return n[t]}).join(" ")},_getClassNames:function(){return this._mergeClasses({disabled:this.disabled,pin:this.pin,snaps:this.snaps,ring:this.immediateValue<=this.min,expand:this.expand,dragging:this.dragging,transiting:this.transiting,editable:this.editable})},_allowBarEvent:function(n){return!this.ignoreBarTouch||n.detail.sourceEvent instanceof MouseEvent},get _isRTL(){return this.__isRTL===void 0&&(this.__isRTL=window.getComputedStyle(this).direction==="rtl"),this.__isRTL},_leftKey:function(n){this._isRTL?this._incrementKey(n):this._decrementKey(n)},_rightKey:function(n){this._isRTL?this._decrementKey(n):this._incrementKey(n)},_incrementKey:function(n){this.disabled||(n.detail.key==="end"?this.value=this.max:this.increment(),this.fire("change"),n.preventDefault())},_decrementKey:function(n){this.disabled||(n.detail.key==="home"?this.value=this.min:this.decrement(),this.fire("change"),n.preventDefault())},_changeValue:function(n){this.value=n.target.value,this.fire("change",{composed:!0})},_inputKeyDown:function(n){n.stopPropagation()},_createRipple:function(){return this._rippleContainer=this.$.sliderKnob,Gu._createRipple.call(this)},_focusedChanged:function(n){n&&this.ensureRipple(),this.hasRipple()&&(n?this._ripple.style.display="":this._ripple.style.display="none",this._ripple.holdDown=n)}});var K2=document.createElement("template");K2.setAttribute("style","display: none;");K2.innerHTML=` + +`;document.head.appendChild(K2.content);var rm={properties:{active:{type:Boolean,value:!1,reflectToAttribute:!0,observer:"__activeChanged"},alt:{type:String,value:"loading",observer:"__altChanged"},__coolingDown:{type:Boolean,value:!1}},__computeContainerClasses:function(n,t){return[n||t?"active":"",t?"cooldown":""].join(" ")},__activeChanged:function(n,t){this.__setAriaHidden(!n),this.__coolingDown=!n&&t},__altChanged:function(n){n==="loading"?this.alt=this.getAttribute("aria-label")||n:(this.__setAriaHidden(n===""),this.setAttribute("aria-label",n))},__setAriaHidden:function(n){var t="aria-hidden";n?this.setAttribute(t,"true"):this.removeAttribute(t)},__reset:function(){this.active=!1,this.__coolingDown=!1}};var eE=dt` + + +
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+`;eE.setAttribute("strip-whitespace","");At({_template:eE,is:"paper-spinner",behaviors:[rm]});var nE=dt` + + +
+
+
+
+
+
+
+
+
+
+`;nE.setAttribute("strip-whitespace","");At({_template:nE,is:"paper-spinner-lite",behaviors:[rm]});var WH=dt` + + + + +`;document.head.appendChild(WH.content);At({_template:dt` + + +
+ +
+`,is:"paper-tab",behaviors:[hn,mi,qr],properties:{link:{type:Boolean,value:!1,reflectToAttribute:!0}},hostAttributes:{role:"tab"},listeners:{down:"_updateNoink",tap:"_onTap"},attached:function(){this._updateNoink()},get _parentNoink(){var n=Ct(this).parentNode;return!!n&&!!n.noink},_updateNoink:function(){this.noink=!!this.noink||!!this._parentNoink},_onTap:function(n){if(this.link){var t=this.queryEffectiveChildren("a");if(!t||n.target===t)return;t.click()}}});At({_template:dt` + + + + +
+
+
+ +
+
+ + +`,is:"paper-tabs",behaviors:[di,nm],properties:{noink:{type:Boolean,value:!1,observer:"_noinkChanged"},noBar:{type:Boolean,value:!1},noSlide:{type:Boolean,value:!1},scrollable:{type:Boolean,value:!1},fitContainer:{type:Boolean,value:!1},disableDrag:{type:Boolean,value:!1},hideScrollButtons:{type:Boolean,value:!1},alignBottom:{type:Boolean,value:!1},selectable:{type:String,value:"paper-tab"},autoselect:{type:Boolean,value:!1},autoselectDelay:{type:Number,value:0},_step:{type:Number,value:10},_holdDelay:{type:Number,value:1},_leftHidden:{type:Boolean,value:!1},_rightHidden:{type:Boolean,value:!1},_previousTab:{type:Object}},hostAttributes:{role:"tablist"},listeners:{"iron-resize":"_onTabSizingChanged","iron-items-changed":"_onTabSizingChanged","iron-select":"_onIronSelect","iron-deselect":"_onIronDeselect"},keyBindings:{"left:keyup right:keyup":"_onArrowKeyup"},created:function(){this._holdJob=null,this._pendingActivationItem=void 0,this._pendingActivationTimeout=void 0,this._bindDelayedActivationHandler=this._delayedActivationHandler.bind(this),this.addEventListener("blur",this._onBlurCapture.bind(this),!0)},ready:function(){this.setScrollDirection("y",this.$.tabsContainer)},detached:function(){this._cancelPendingActivation()},_noinkChanged:function(n){var t=Ct(this).querySelectorAll("paper-tab");t.forEach(n?this._setNoinkAttribute:this._removeNoinkAttribute)},_setNoinkAttribute:function(n){n.setAttribute("noink","")},_removeNoinkAttribute:function(n){n.removeAttribute("noink")},_computeScrollButtonClass:function(n,t,e){return!t||e?"hidden":n?"not-visible":""},_computeTabsContentClass:function(n,t){return n?"scrollable"+(t?" fit-container":""):" fit-container"},_computeSelectionBarClass:function(n,t){return n?"hidden":t?"align-bottom":""},_onTabSizingChanged:function(){this.debounce("_onTabSizingChanged",function(){this._scroll(),this._tabChanged(this.selectedItem)},10)},_onIronSelect:function(n){this._tabChanged(n.detail.item,this._previousTab),this._previousTab=n.detail.item,this.cancelDebouncer("tab-changed")},_onIronDeselect:function(n){this.debounce("tab-changed",function(){this._tabChanged(null,this._previousTab),this._previousTab=null},1)},_activateHandler:function(){this._cancelPendingActivation(),Ds._activateHandler.apply(this,arguments)},_scheduleActivation:function(n,t){this._pendingActivationItem=n,this._pendingActivationTimeout=this.async(this._bindDelayedActivationHandler,t)},_delayedActivationHandler:function(){var n=this._pendingActivationItem;this._pendingActivationItem=void 0,this._pendingActivationTimeout=void 0,n.fire(this.activateEvent,null,{bubbles:!0,cancelable:!0})},_cancelPendingActivation:function(){this._pendingActivationTimeout!==void 0&&(this.cancelAsync(this._pendingActivationTimeout),this._pendingActivationItem=void 0,this._pendingActivationTimeout=void 0)},_onArrowKeyup:function(n){this.autoselect&&this._scheduleActivation(this.focusedItem,this.autoselectDelay)},_onBlurCapture:function(n){n.target===this._pendingActivationItem&&this._cancelPendingActivation()},get _tabContainerScrollSize(){return Math.max(0,this.$.tabsContainer.scrollWidth-this.$.tabsContainer.offsetWidth)},_scroll:function(n,t){if(!!this.scrollable){var e=t&&-t.ddx||0;this._affectScroll(e)}},_down:function(n){this.async(function(){this._defaultFocusAsync&&(this.cancelAsync(this._defaultFocusAsync),this._defaultFocusAsync=null)},1)},_affectScroll:function(n){this.$.tabsContainer.scrollLeft+=n;var t=this.$.tabsContainer.scrollLeft;this._leftHidden=t===0,this._rightHidden=t===this._tabContainerScrollSize},_onLeftScrollButtonDown:function(){this._scrollToLeft(),this._holdJob=setInterval(this._scrollToLeft.bind(this),this._holdDelay)},_onRightScrollButtonDown:function(){this._scrollToRight(),this._holdJob=setInterval(this._scrollToRight.bind(this),this._holdDelay)},_onScrollButtonUp:function(){clearInterval(this._holdJob),this._holdJob=null},_scrollToLeft:function(){this._affectScroll(-this._step)},_scrollToRight:function(){this._affectScroll(this._step)},_tabChanged:function(n,t){if(!n){this.$.selectionBar.classList.remove("expand"),this.$.selectionBar.classList.remove("contract"),this._positionBar(0,0);return}var e=this.$.tabsContent.getBoundingClientRect(),r=e.width,i=n.getBoundingClientRect(),o=i.left-e.left;if(this._pos={width:this._calcPercent(i.width,r),left:this._calcPercent(o,r)},this.noSlide||t==null){this.$.selectionBar.classList.remove("expand"),this.$.selectionBar.classList.remove("contract"),this._positionBar(this._pos.width,this._pos.left);return}var s=t.getBoundingClientRect(),a=this.items.indexOf(t),l=this.items.indexOf(n),c=5;this.$.selectionBar.classList.add("expand");var u=a0&&(this.$.tabsContainer.scrollLeft+=e))},_calcPercent:function(n,t){return 100*n/t},_positionBar:function(n,t){n=n||0,t=t||0,this._width=n,this._left=t,this.transform("translateX("+t+"%) scaleX("+n/100+")",this.$.selectionBar)},_onBarTransitionEnd:function(n){var t=this.$.selectionBar.classList;t.contains("expand")?(t.remove("expand"),t.add("contract"),this._positionBar(this._pos.width,this._pos.left)):t.contains("contract")&&t.remove("contract")}});var vl=null;At({_template:dt` + + + {{text}} + +`,is:"paper-toast",behaviors:[gl],properties:{fitInto:{type:Object,value:window,observer:"_onFitIntoChanged"},horizontalAlign:{type:String,value:"left"},verticalAlign:{type:String,value:"bottom"},duration:{type:Number,value:3e3},text:{type:String,value:""},noCancelOnOutsideClick:{type:Boolean,value:!0},noAutoFocus:{type:Boolean,value:!0}},listeners:{transitionend:"__onTransitionEnd"},get visible(){return ko._warn("`visible` is deprecated, use `opened` instead"),this.opened},get _canAutoClose(){return this.duration>0&&this.duration!==1/0},created:function(){this._autoClose=null,Ar.requestAvailability()},show:function(n){typeof n=="string"&&(n={text:n});for(var t in n)t.indexOf("_")===0?ko._warn('The property "'+t+'" is private and was not set.'):t in this?this[t]=n[t]:ko._warn('The property "'+t+'" is not valid.');this.open()},hide:function(){this.close()},__onTransitionEnd:function(n){n&&n.target===this&&n.propertyName==="opacity"&&(this.opened?this._finishRenderOpened():this._finishRenderClosed())},_openedChanged:function(){this._autoClose!==null&&(this.cancelAsync(this._autoClose),this._autoClose=null),this.opened?(vl&&vl!==this&&vl.close(),vl=this,this.fire("iron-announce",{text:this.text}),this._canAutoClose&&(this._autoClose=this.async(this.close,this.duration))):vl===this&&(vl=null),Ro._openedChanged.apply(this,arguments)},_renderOpened:function(){this.classList.add("paper-toast-open")},_renderClosed:function(){this.classList.remove("paper-toast-open")},_onFitIntoChanged:function(n){this.positionTarget=n}});var rE=dt` + + + +
+
+
+
+ +
+ + `;rE.setAttribute("strip-whitespace","");At({_template:rE,is:"paper-toggle-button",behaviors:[fl],hostAttributes:{role:"button","aria-pressed":"false",tabindex:0},properties:{},listeners:{track:"_ontrack"},attached:function(){al(this,function(){Ns(this,"pan-y")})},_ontrack:function(n){var t=n.detail;t.state==="start"?this._trackStart(t):t.state==="track"?this._trackMove(t):t.state==="end"&&this._trackEnd(t)},_trackStart:function(n){this._width=this.$.toggleBar.offsetWidth/2,this._trackChecked=this.checked,this.$.toggleButton.classList.add("dragging")},_trackMove:function(n){var t=n.dx;this._x=Math.min(this._width,Math.max(0,this._trackChecked?this._width+t:t)),this.translate3d(this._x+"px",0,0,this.$.toggleButton),this._userActivate(this._x>this._width/2)},_trackEnd:function(n){this.$.toggleButton.classList.remove("dragging"),this.transform("",this.$.toggleButton)},_createRipple:function(){this._rippleContainer=this.$.toggleButton;var n=qr._createRipple();return n.id="ink",n.setAttribute("recenters",""),n.classList.add("circle","toggle-ink"),n}});At({_template:dt` + + +
+ +
+ +
+ +
+ +
+ +
+`,is:"paper-toolbar",hostAttributes:{role:"toolbar"},properties:{bottomJustify:{type:String,value:""},justify:{type:String,value:""},middleJustify:{type:String,value:""}},ready:function(){console.warn(this.is,"is deprecated. Please use app-layout instead!")},attached:function(){this._observer=this._observe(this),this._updateAriaLabelledBy()},detached:function(){this._observer&&this._observer.disconnect()},_observe:function(n){var t=new MutationObserver(function(){this._updateAriaLabelledBy()}.bind(this));return t.observe(n,{childList:!0,subtree:!0}),t},_updateAriaLabelledBy:function(){jr();for(var n=[],t=Array.prototype.slice.call(Ct(this.root).querySelectorAll("slot")).concat(Array.prototype.slice.call(Ct(this.root).querySelectorAll("content"))),e,r=0;e=t[r];r++)for(var i=Ct(e).getDistributedNodes(),o,s=0;o=i[s];s++)if(o.classList&&o.classList.contains("title"))if(o.id)n.push(o.id);else{var a="paper-toolbar-label-"+Math.floor(Math.random()*1e4);o.id=a,n.push(a)}n.length>0&&this.setAttribute("aria-labelledby",n.join(" "))},_computeBarExtraClasses:function(n){return n?n+(n==="justified"?"":"-justified"):""}});At({_template:dt` + + + +`,is:"paper-tooltip",hostAttributes:{role:"tooltip",tabindex:-1},properties:{for:{type:String,observer:"_findTarget"},manualMode:{type:Boolean,value:!1,observer:"_manualModeChanged"},position:{type:String,value:"bottom"},fitToVisibleBounds:{type:Boolean,value:!1},offset:{type:Number,value:14},marginTop:{type:Number,value:14},animationDelay:{type:Number,value:500,observer:"_delayChange"},animationEntry:{type:String,value:""},animationExit:{type:String,value:""},animationConfig:{type:Object,value:function(){return{entry:[{name:"fade-in-animation",node:this,timing:{delay:0}}],exit:[{name:"fade-out-animation",node:this}]}}},_showing:{type:Boolean,value:!1}},listeners:{webkitAnimationEnd:"_onAnimationEnd"},get target(){var n=Ct(this).parentNode,t=Ct(this).getOwnerRoot(),e;return this.for?e=Ct(t).querySelector("#"+this.for):e=n.nodeType==Node.DOCUMENT_FRAGMENT_NODE?t.host:n,e},attached:function(){this._findTarget()},detached:function(){this.manualMode||this._removeListeners()},playAnimation:function(n){n==="entry"?this.show():n==="exit"&&this.hide()},cancelAnimation:function(){this.$.tooltip.classList.add("cancel-animation")},show:function(){if(!this._showing){if(Ct(this).textContent.trim()===""){for(var n=!0,t=Ct(this).getEffectiveChildNodes(),e=0;ewindow.innerWidth?(this.style.right="0px",this.style.left="auto"):(this.style.left=Math.max(0,l)+"px",this.style.right="auto"),t.top+c+r.height>window.innerHeight?(this.style.bottom=t.height-a+n+"px",this.style.top="auto"):(this.style.top=Math.max(-t.top,c)+"px",this.style.bottom="auto")):(this.style.left=l+"px",this.style.top=c+"px")}},_addListeners:function(){this._target&&(this.listen(this._target,"mouseenter","show"),this.listen(this._target,"focus","show"),this.listen(this._target,"mouseleave","hide"),this.listen(this._target,"blur","hide"),this.listen(this._target,"tap","hide")),this.listen(this.$.tooltip,"animationend","_onAnimationEnd"),this.listen(this,"mouseenter","hide")},_findTarget:function(){this.manualMode||this._removeListeners(),this._target=this.target,this.manualMode||this._addListeners()},_delayChange:function(n){n!==500&&this.updateStyles({"--paper-tooltip-delay-in":n+"ms"})},_manualModeChanged:function(){this.manualMode?this._removeListeners():this._addListeners()},_cancelAnimation:function(){this.$.tooltip.classList.remove(this._getAnimationType("entry")),this.$.tooltip.classList.remove(this._getAnimationType("exit")),this.$.tooltip.classList.remove("cancel-animation"),this.$.tooltip.classList.add("hidden")},_onAnimationFinish:function(){this._showing&&(this.$.tooltip.classList.remove(this._getAnimationType("entry")),this.$.tooltip.classList.remove("cancel-animation"),this.$.tooltip.classList.add(this._getAnimationType("exit")))},_onAnimationEnd:function(){this._animationPlaying=!1,this._showing||(this.$.tooltip.classList.remove(this._getAnimationType("exit")),this.$.tooltip.classList.add("hidden"))},_getAnimationType:function(n){if(n==="entry"&&this.animationEntry!=="")return this.animationEntry;if(n==="exit"&&this.animationExit!=="")return this.animationExit;if(this.animationConfig[n]&&typeof this.animationConfig[n][0].name=="string"){if(this.animationConfig[n][0].timing&&this.animationConfig[n][0].timing.delay&&this.animationConfig[n][0].timing.delay!==0){var t=this.animationConfig[n][0].timing.delay;n==="entry"?this.updateStyles({"--paper-tooltip-delay-in":t+"ms"}):n==="exit"&&this.updateStyles({"--paper-tooltip-delay-out":t+"ms"})}return this.animationConfig[n][0].name}},_removeListeners:function(){this._target&&(this.unlisten(this._target,"mouseenter","show"),this.unlisten(this._target,"focus","show"),this.unlisten(this._target,"mouseleave","hide"),this.unlisten(this._target,"blur","hide"),this.unlisten(this._target,"tap","hide")),this.unlisten(this.$.tooltip,"animationend","_onAnimationEnd"),this.unlisten(this,"mouseenter","hide")}});var im=class{constructor(t,e){if(typeof ga=="undefined"||ga==null){this.eventLogging=!1,this.pageViewLogging=!1;return}this.eventLogging=e,this.pageViewLogging=t}logPageView(t){this.pageViewLogging&&ga("send",{hitType:"pageview",page:`/v/${t}`})}logProjectionChanged(t){this.eventLogging&&ga("send",{hitType:"event",eventCategory:"Projection",eventAction:"click",eventLabel:t})}logWebGLDisabled(){this.eventLogging&&ga("send",{hitType:"event",eventCategory:"Error",eventAction:"PageLoad",eventLabel:"WebGL_disabled"})}};var WO=Jd(vT(),1);var eh=Jd(yT(),1),bT;window.numeric=(bT=window.numeric)!=null?bT:eh.default;var mm=class{constructor(t){if(t.length<1)throw new Error("There should be at least 1 data point");this.dim=t[0].length,this.masks=new Array(Math.pow(2,this.dim));for(let s=0;st.box.center[i]&&(r|=this.masks[i]);t.children[r]==null?this.makeChild(t,r,e):this.insert(t.children[r],e)}makeChild(t,e,r){let i=t.box.center,o=t.box.halfDim/2,s=new Array(this.dim);for(let a=0;a1)return MT(n);let i=Math.sqrt(-2*Math.log(r)/r);return wT=e*i,fb=!0,t*i}function oU(n,t,e){return t+MT(n)*e}function ET(n){return new Float64Array(n)}function sU(n,t,e){let r=n*t,i=ET(r);for(let o=0;o1e-7&&(g-=b*Math.log(b))}if(g>i?(h=d,p===1/0?d=d*2:d=(d+p)/2):(p=d,h===-1/0?d=d/2:d=(d+h)/2),m++,m>=f||Math.abs(g-i)0?1:n<0?-1:0}function lU(n,t,e,r){n[0]+=t*(e[0]-r[0]),n[1]+=t*(e[1]-r[1])}function cU(n,t,e,r){n[0]+=t*(e[0]-r[0]),n[1]+=t*(e[1]-r[1]),n[2]+=t*(e[2]-r[2])}var gm=class{constructor(t){if(this.iter=0,t=t||{dim:2},this.perplexity=t.perplexity||30,this.setEpsilon(t.epsilon||10),this.rng=t.rng||Math.random,this.dim=t.dim,t.dim===2)this.dist2=rU,this.computeForce=lU;else if(t.dim===3)this.dist2=iU,this.computeForce=cU;else throw new Error("Only 2D and 3D is supported")}initDataDist(t){let e=t.length;this.nearest=t,this.P=aU(t,this.perplexity,1e-4),this.N=e,this.initSolution()}initSolution(){this.Y||(this.Y=sU(this.N,this.dim,this.rng)),this.gains=ST(this.N,this.dim,1),this.ystep=ST(this.N,this.dim,0),this.iter=0}getDim(){return this.dim}getRng(){return this.rng}getSolution(){return this.Y}setSolution(t){this.Y=t}perturb(){let t=this.N,e=0,r=this.dim===3?[0,0,0]:[0,0];for(let o=0;oe&&(e=s)}let i=Math.pow(e,.5);for(let o=0;othis.labelCounts[i]=0),t.forEach(i=>this.labelCounts[i]+=1)),e!=null&&(this.unlabeledClass=e)}setSuperviseFactor(t){t!=null&&(this.superviseFactor=t)}costGrad(t){let e=this.N,r=this.P,i=this.iter<100?4:1,o=this.superviseFactor/100,s=this.unlabeledClass,a=this.labels,l=this.labelCounts,c=o!=null&&o>0&&a!=null&&l!=null,u=c&&s!=null&&s!==""?l[s]:0,h=new Array(e);for(let S=0;S{let E=1;if(S.children==null)return S.numCells=E,S.yCell=S.point,{numCells:E,yCell:S.yCell};let M=S.point.slice();for(let P=0;PP/E),{numCells:E,yCell:M}};f(d),p.visit((S,E,M)=>(S.rCell=M[0]-E[0],!1));let m=[],x=0,g=0,v=new Array(e);for(let S=0;S{let N=this.dist2(E,I.yCell);if(I.children==null||N>0&&I.rCell/Math.sqrt(N)0;)r=Math.random()*t|0,t--,e=n[t],n[t]=n[r],n[r]=e}function uU(n,t){if(n.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${n.length}Second array length was ${t.length}`);let e=n.length,r,i,o=0;for(;e>0;)o=Math.random()*e|0,e--,r=n[e],i=t[e],n[e]=n[o],t[e]=t[o],n[o]=r,t[o]=i}function wl(n,t,e){return Math.max(n,Math.min(t,e))}function hU(n){return n%2===0?n:n+1}function pU(n){let t=0;for(let e=0;ee+` Shapes ${n} and ${t} must match`)}function mU(n){Ut(n!=null,()=>"The input to the tensor constructor must be a non-null value.")}function No(n,t=[],e=!1){if(t==null&&(t=[]),Array.isArray(n)||lr(n)&&!e)for(let r=0;r0,e){return new Promise((r,i)=>{let o=0,s=()=>{if(n()){r();return}o++;let a=t(o);if(e!=null&&o>=e){i();return}setTimeout(s,a)};s()})}function _U(n,t){let e=1,r=-1;for(let o=0;o=0)e*=n[o];else if(n[o]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${o}`);r=o}else if(n[o]<0)throw Error(`Shapes can not be < 0. Found ${n[o]} at dim ${o}`);if(r===-1){if(t>0&&t!==e)throw Error(`Size(${t}) must match the product of shape ${n}`);return n}if(e===0)throw Error(`Cannot infer the missing size in [${n}] when there are 0 elements`);if(t%e!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${e}`);let i=n.slice();return i[r]=t/e,i}function IT(n,t){let e=t.length;return n=n==null?t.map((r,i)=>i):[].concat(n),Ut(n.every(r=>r>=-e&&r`All values in axis param must be in range [-${e}, ${e}) but got axis ${n}`),Ut(n.every(r=>AT(r)),()=>`All values in axis param must be integers but got axis ${n}`),n.map(r=>r<0?e+r:r)}function wU(n,t){let e=[],r=[],i=t!=null&&Array.isArray(t)&&t.length===0,o=t==null||i?null:IT(t,n).sort(),s=0;for(let a=0;aa)&&n[a]===1&&(e.push(n[a]),r.push(a)),o[s]<=a&&s++}n[a]!==1&&(e.push(n[a]),r.push(a))}return{newShape:e,keptDims:r}}function SU(n,t){let e=null;if(n==null||n==="float32")e=new Float32Array(t);else if(n==="int32")e=new Int32Array(t);else if(n==="bool")e=new Uint8Array(t);else throw new Error(`Unknown data type ${n}`);return e}function gb(n,t){let e=null;if(n==null||n==="float32")e=new Float32Array(t);else if(n==="int32")e=new Int32Array(t);else if(n==="bool")e=new Uint8Array(t);else if(n==="string")e=new Array(t);else throw new Error(`Unknown data type ${n}`);return e}function xb(n,t){for(let e=0;et+=e.length),t}function Cl(n){return typeof n=="string"||n instanceof String}function kT(n){return typeof n=="boolean"}function RT(n){return typeof n=="number"}function Ml(n){return Array.isArray(n)?Ml(n[0]):n instanceof Float32Array?"float32":n instanceof Int32Array||n instanceof Uint8Array?"int32":RT(n)?"float32":Cl(n)?"string":kT(n)?"bool":"float32"}function vm(n){return!!(n&&n.constructor&&n.call&&n.apply)}function El(n,t){for(let e=t;e=0;--r)e[r]=e[r+1]*n[r+1];return e}function PT(n,t,e,r=!1){let i=new Array;if(t.length===1){let o=t[0]*(r?2:1);for(let s=0;sl*c)*(r?2:1);for(let l=0;li*o)*(e?2:1);if(r===0)return[];if(r!==t.length)throw new Error(`[${n}] does not match the input size ${t.length}${e?" for a complex tensor":""}.`);return PT(0,n,t,e)}function bb(n,t){let e=Tl(n,t);for(let r=0;rr*i,1);if(t==null||t==="float32")return Hs(n,new Float32Array(e));if(t==="int32")return Hs(n,new Int32Array(e));if(t==="bool")return Hs(n,new Uint8Array(e));throw new Error(`Unknown data type ${t}`)}function nh(n){n.forEach(t=>{Ut(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${n}].`)})}function EU(n,t,e){if(t===0)return 0;if(t===1)return n[0];let r=n[n.length-1];for(let i=0;i{let[i,o]=r.split(":");this.urlFlags[i]=RU(i,o)})}};function IU(n){let t={};return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...r)=>(kU(t,r[0],r[1]),r.join("="))),t}function kU(n,t,e){n[decodeURIComponent(t)]=decodeURIComponent(e||"")}function RU(n,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${n}.`)}function ot(){return _b}var _b=null;function LT(n){_b=n}var wb;function Sb(){if(wb==null){let n;if(typeof window!="undefined")n=window;else if(typeof global!="undefined")n=global;else if(typeof process!="undefined")n=process;else if(typeof self!="undefined")n=self;else throw new Error("Could not find a global object");wb=n}return wb}function PU(){let n=Sb();return n._tfGlobals==null&&(n._tfGlobals=new Map),n._tfGlobals}function oh(n,t){let e=PU();if(e.has(n))return e.get(n);{let r=t();return e.set(n,r),e.get(n)}}var ym="Abs",sh="Acos",ah="Acosh",Us="Add",bm="AddN",_m="All",wm="Any",Sm="ArgMax",Cm="ArgMin",lh="Asin",ch="Asinh",uh="Atan",hh="Atanh",ph="Atan2",Mm="AvgPool",Em="AvgPoolGrad",Tm="AvgPool3D",Am="AvgPool3DGrad",Al="BatchMatMul",Im="BatchToSpaceND",km="Bincount";var Lo="Cast",dh="Ceil",fh="ClipByValue",Il="Complex",Rm="ComplexAbs",Pm="Concat",Nm="Conv2D",Lm="Conv2DBackpropFilter",Dm="Conv2DBackpropInput",zm="Conv3D",Fm="Conv3DBackpropFilterV2",Om="Conv3DBackpropInputV2",mh="Cos",gh="Cosh",Bm="Cumsum",Vm="CropAndResize",Hm="DenseBincount",$m="DepthToSpace",Um="DepthwiseConv2dNative",Wm="DepthwiseConv2dNativeBackpropFilter",Gm="DepthwiseConv2dNativeBackpropInput",jm="Diag",qm="Dilation2D",Cb="Dilation2DBackpropInput",Mb="Dilation2DBackpropFilter",xh="RealDiv",Xm="Einsum",Ws="Elu",Km="EluGrad",vh="Erf",yh="Equal",bh="Exp",Ym="ExpandDims",_h="Expm1",Zm="FFT",Jm="Fill",Qm="FlipLeftRight",wh="Floor",Sh="FloorDiv",tg="FusedBatchNorm",eg="GatherV2",ng="GatherNd",Ch="Greater",Mh="GreaterEqual",Do="Identity",rg="IFFT",ig="Imag",Eh="IsFinite",Th="IsInf",Ah="IsNan",kl="LeakyRelu",Ih="Less",kh="LessEqual",og="LinSpace",Rh="Log",Ph="Log1p",Nh="LogicalAnd",Lh="LogicalNot",Dh="LogicalOr";var sg="LRN",ag="LRNGrad",lg="Max",zh="Maximum",cg="MaxPool",ug="MaxPoolGrad",hg="MaxPool3D",pg="MaxPool3DGrad",dg="MaxPoolWithArgmax",fg="Mean",mg="Min",Fh="Minimum",gg="MirrorPad",Oh="Mod",xg="Multinomial",Gs="Multiply",vg="Neg",Bh="NotEqual",yg="NonMaxSuppressionV3",bg="NonMaxSuppressionV4",_g="NonMaxSuppressionV5",wg="OnesLike",Sg="OneHot",Cg="Pack",Rl="PadV2";var Vh="Pow",Pl="Prelu",Mg="Prod",Eg="Range",Tg="Real",Hh="Reciprocal",js="Relu",Nl="Reshape",Ag="ResizeNearestNeighbor",Ig="ResizeNearestNeighborGrad",kg="ResizeBilinear",Rg="ResizeBilinearGrad",qs="Relu6",Pg="Reverse",$h="Round",Uh="Rsqrt",Ng="ScatterNd",Lg="Select",Wh="Selu",Dg="Slice",Gh="Sin",jh="Sinh",qh="Sign",Xh="Sigmoid",Kh="Softplus",Yh="Sqrt",Ll="Sum",zg="SpaceToBatchND",Dl="SplitV",Fg="Softmax",Zh="SquaredDifference",Og="Square",Xs="Sub",Bg="SparseToDense",Vg="StridedSlice",Jh="Tan",Qh="Tanh",Hg="Tile",$g="TopK",Ug="Transform",zl="Transpose",Wg="Unique",Gg="Unpack",jg="UnsortedSegmentSum",qg="ZerosLike",Ks="Step",DT="FromPixels",Xg="RotateWithOffset",Kg="_FusedMatMul",Yg="FusedConv2D",Zg="FusedDepthwiseConv2D";var Jg=oh("kernelRegistry",()=>new Map),NU=oh("gradRegistry",()=>new Map);function Eb(n,t){let e=zT(n,t);return Jg.get(e)}function Tb(n){return NU.get(n)}function Ab(n){let t=Jg.entries(),e=[];for(;;){let{done:r,value:i}=t.next();if(r)break;let[o,s]=i,[a]=o.split("_");a===n&&e.push(s)}return e}function Qg(n){let{kernelName:t,backendName:e}=n,r=zT(t,e);Jg.has(r)&&console.warn(`The kernel '${t}' for backend '${e}' is already registered`),Jg.set(r,n)}function zT(n,t){return`${t}_${n}`}var R={};So(R,{arraysEqual:()=>Sl,assert:()=>Ut,assertNonNegativeIntegerDimensions:()=>nh,assertNonNull:()=>mU,assertShapesMatch:()=>mb,bytesFromStringArray:()=>yb,bytesPerElement:()=>xm,checkConversionForErrors:()=>xb,clamp:()=>wl,computeStrides:()=>_i,createScalarValue:()=>LU,createShuffledIndices:()=>yU,decodeString:()=>Bl,distSquared:()=>fU,encodeString:()=>Ol,fetch:()=>zU,flatten:()=>No,getArrayFromDType:()=>gb,getTypedArrayFromDType:()=>SU,hasEncodingLoss:()=>CU,indexToLoc:()=>TU,inferDtype:()=>Ml,inferFromImplicitShape:()=>_U,isBoolean:()=>kT,isFunction:()=>vm,isInt:()=>AT,isNumber:()=>RT,isPromise:()=>rh,isScalarShape:()=>gU,isString:()=>Cl,isTypedArray:()=>lr,isValidDtype:()=>vb,locToIndex:()=>EU,makeOnesTypedArray:()=>bb,makeZerosNestedTypedArray:()=>MU,makeZerosTypedArray:()=>Tl,nearestDivisor:()=>El,nearestLargerEven:()=>hU,now:()=>Ys,parseAxisParam:()=>IT,randUniform:()=>dU,repeatedTry:()=>bU,rightPad:()=>$s,shuffle:()=>TT,shuffleCombo:()=>uU,sizeFromShape:()=>xn,sizeToSquarishShape:()=>vU,squeezeShape:()=>wU,sum:()=>pU,tanh:()=>xU,toNestedArray:()=>Hs,toTypedArray:()=>Fl});function LU(n,t){return t==="string"?Ol(n):Fl([n],t)}function DU(n,t){return n instanceof Float32Array&&t==="float32"||n instanceof Int32Array&&t==="int32"||n instanceof Uint8Array&&t==="bool"}function Fl(n,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=No(n)),ot().getBool("DEBUG")&&xb(n,t),DU(n,t))return n;if(t==null||t==="float32"||t==="complex64")return new Float32Array(n);if(t==="int32")return new Int32Array(n);if(t==="bool"){let e=new Uint8Array(n.length);for(let r=0;r{i=r()},s,a=Ys();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(o);else{o();for(let c of i)c.dataSync();s=Promise.resolve({kernelMs:Ys()-a})}if(ot().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let c=0;c{FU(h,u.dtype,t)})}return{kernelName:t,outputs:i,inputs:e,timeMs:s.then(c=>c.kernelMs),extraInfo:s.then(c=>c.getExtraProfileInfo!=null?c.getExtraProfileInfo():"")}}logKernelProfile(t){let{kernelName:e,outputs:r,timeMs:i,inputs:o,extraInfo:s}=t;r.forEach(a=>{Promise.all([a.data(),i,s]).then(l=>{this.logger.logKernelProfile(e,a,l[0],l[1],o,l[2])})})}};function FU(n,t,e){if(t!=="float32")return!1;for(let r=0;r0?m:""} `}}console.log(`%c${l} %c${a} %c${c}D ${h} %c${u} %c${p} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function FT(n,t,e){let r={},i={};for(let l=0;lr[m.id]=!0),d=!0,i[c.id]=!0;break}if(d)break}}let o={};o[e.id]=!0;let s={};for(let l=n.length-1;l>=0;l--){let c=n[l],u=c.inputs;for(let h=0;h=0;i--){let o=t[i],s=[];if(o.outputs.forEach(l=>{let c=n[l.id];c!=null?s.push(c):s.push(null)}),o.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${o.kernelName}.`);let a=o.gradient(s);for(let l in o.inputs){if(!(l in a))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(a)}.`);let c=e(()=>a[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);let u=o.inputs[l];if(!Sl(c.shape,u.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(n[u.id]==null)n[u.id]=c;else{let h=n[u.id];n[u.id]=r(h,c),h.dispose()}}}}var BT=20,tp=3,kb=7;function VT(n,t,e,r){let i=_i(t),o=OU(n,t,e,i),s=t.length,a=e1(n,t,e,i,o),l=["Tensor"];return r&&(l.push(` dtype: ${e}`),l.push(` rank: ${s}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(a.map(c=>" "+c).join(` +`)),l.join(` +`)}function OU(n,t,e,r){let i=xn(t),o=r[r.length-1],s=new Array(o).fill(0),a=t.length,l=e==="complex64"?np(n):n;if(a>1)for(let c=0;cBT){let x=tp*s,g=Array.from(n.slice(0,x)),v=Array.from(n.slice((a-tp)*s,a*s));return e==="complex64"&&(g=np(g),v=np(v)),["["+g.map((b,y)=>ep(b,i[y],e)).join(", ")+", ..., "+v.map((b,y)=>ep(b,i[a-tp+y],e)).join(", ")+"]"]}let m=e==="complex64"?np(n):Array.from(n);return["["+m.map((x,g)=>ep(x,i[g],e)).join(", ")+"]"]}let c=t.slice(1),u=r.slice(1),h=r[0]*s,p=[];if(a>BT){for(let m=0;m`Length of values '${i}' does not match the size inferred by the shape '${this.size}'.`)}if(e==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=r||gb(e,this.size),this.strides=_i(t)}set(t,...e){e.length===0&&(e=[0]),Ut(e.length===this.rank,()=>`The number of provided coordinates (${e.length}) must match the rank (${this.rank})`);let r=this.locToIndex(e);this.values[r]=t}get(...t){t.length===0&&(t=[0]);let e=0;for(let i of t){if(i<0||i>=this.shape[e]){let o=`Requested out of range element at ${t}. Buffer shape=${this.shape}`;throw new Error(o)}e++}let r=t[t.length-1];for(let i=0;iBl(r))}catch(r){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return t})}dataSync(){this.throwIfDisposed();let t=wi().readSync(this.dataId);if(this.dtype==="string")try{return t.map(e=>Bl(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t}bytes(){return Jt(this,null,function*(){this.throwIfDisposed();let t=yield wi().read(this.dataId);return this.dtype==="string"?t:new Uint8Array(t.buffer)})}dispose(){this.isDisposed||(wi().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(t=!1){return Vl.print(this,t)}clone(){return this.throwIfDisposed(),Vl.clone(this)}toString(t=!1){let e=this.dataSync();return VT(e,this.shape,this.dtype,t)}cast(t){return this.throwIfDisposed(),Vl.cast(this,t)}variable(t=!0,e,r){return this.throwIfDisposed(),wi().makeVariable(this,t,e,r)}};Object.defineProperty(An,Symbol.hasInstance,{value:n=>!!n&&n.data!=null&&n.dataSync!=null&&n.throwIfDisposed!=null});function VU(){return oh("Tensor",()=>An)}VU();var Zs=class extends An{constructor(t,e,r,i){super(t.shape,t.dtype,t.dataId,i),this.trainable=e,this.name=r}assign(t){if(t.dtype!==this.dtype)throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);if(!Sl(t.shape,this.shape))throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);wi().disposeTensor(this),this.dataId=t.dataId,wi().incRef(this,null)}dispose(){wi().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Zs,Symbol.hasInstance,{value:n=>n instanceof An&&n.assign!=null&&n.assign instanceof Function});var Rb;(function(n){n.R0="R0",n.R1="R1",n.R2="R2",n.R3="R3",n.R4="R4",n.R5="R5",n.R6="R6"})(Rb||(Rb={}));var Pb;(function(n){n.float32="float32",n.int32="int32",n.bool="int32",n.complex64="complex64"})(Pb||(Pb={}));var Nb;(function(n){n.float32="float32",n.int32="int32",n.bool="bool",n.complex64="complex64"})(Nb||(Nb={}));var Lb;(function(n){n.float32="float32",n.int32="float32",n.bool="float32",n.complex64="complex64"})(Lb||(Lb={}));var Db;(function(n){n.float32="complex64",n.int32="complex64",n.bool="complex64",n.complex64="complex64"})(Db||(Db={}));var HU={float32:Lb,int32:Pb,bool:Nb,complex64:Db};function on(n,t){if(n==="string"||t==="string"){if(n==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${n} with ${t}`)}return HU[n][t]}function Js(n){return on(n,"int32")}function Hl(n,t){if(n.dtype===t.dtype)return[n,t];let e=on(n.dtype,t.dtype);return[n.cast(e),t.cast(e)]}function GT(n){let t=[];return jT(n,t,new Set),t}function jT(n,t,e){if(n==null)return;if(n instanceof An){t.push(n);return}if(!$U(n))return;let r=n;for(let i in r){let o=r[i];e.has(o)||(e.add(o),jT(o,t,e))}}function $U(n){return Array.isArray(n)||typeof n=="object"}function zb(n){return n.kernelName!=null}var n1=class{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(t=>t.name)))}}}dispose(){for(let t in this.registeredVariables)this.registeredVariables[t].dispose()}},zo=class{constructor(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new n1}ready(){return Jt(this,null,function*(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let t=this.getSortedBackends();for(let e=0;e{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(t){Ab(t).forEach(r=>{r.disposeFunc!=null&&r.disposeFunc(this.registry[t])})}initializeBackend(t){let e=this.registryFactory[t];if(e==null)throw new Error(`Cannot initialize backend ${t}, no registration found.`);try{let r=e.factory();if(r&&!(r instanceof Qi)&&typeof r.then=="function"){let i=++this.pendingBackendInitId,o=r.then(s=>i(ithis.registryFactory[e].priority-this.registryFactory[t].priority)}initializeBackendsAndReturnBest(){let t=this.getSortedBackends();for(let e=0;ethis.startScope(r),()=>this.endScope(i),()=>(i=e(),i instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),i))}scopedRun(t,e,r){t();try{let i=r();return e(),i}catch(i){throw e(),i}}nextTensorId(){return zo.nextTensorId++}nextVariableId(){return zo.nextVariableId++}clone(t){let e=Kt.runKernel(Do,{x:t}),r={x:t},i=s=>({x:()=>{let a="float32",l={x:s},c={dtype:a};return Kt.runKernel(Lo,l,c)}}),o=[];return this.addTapeNode(this.state.activeScope.name,r,[e],i,o,{}),e}runKernel(t,e,r){if(!(Eb(t,this.backendName)!=null))throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:t,inputs:e,attrs:r})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(t,e,r){let i=this.backend.numDataIds(),o=0;r.forEach(l=>{o+=l.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=i-e-o-s;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${t}'`)}runKernelFunc(t){let e,r=[],i=this.isTapeOn(),o=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let a;this.backendName==null&&this.backend;let l,c=zb(t)?t.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(zb(t)){let{kernelName:f,inputs:m,attrs:x}=t;this.backendName==null&&this.backend;let g=Eb(f,this.backendName);Ut(g!=null,()=>`Cannot find registered kernel '${f}' for backend '${this.backendName}'`),a=()=>{let v=this.backend.numDataIds();l=g.kernelFunc({inputs:m,attrs:x,backend:this.backend});let b=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(f,v,b);let y=b.map(_=>{if(_.rank!=null)return _;let{dataId:S,shape:E,dtype:M}=_;return this.makeTensorFromDataId(S,E,M)});if(i){let _=this.getTensorsForGradient(f,m,y);r=this.saveTensorsForBackwardMode(_)}return y}}else{let{forwardFunc:f}=t,m=x=>{!i||(r=x.map(g=>this.keep(this.clone(g))))};a=()=>{let x=this.backend.numDataIds();l=this.tidy(()=>f(this.backend,m));let g=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,x,g),g}}let{inputs:u,attrs:h}=t,p=zb(t)?null:t.backwardsFunc,d;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?e=a():(d=this.profiler.profileKernel(c,u,()=>a()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),e=d.outputs)}),i&&this.addTapeNode(c,u,e,p,r,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:c,bytesAdded:this.state.numBytes-o,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(f=>u[f]!=null?u[f].shape:null),outputShapes:e.map(f=>f.shape),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(l)?e:e[0]}saveTensorsForBackwardMode(t){return t.map(r=>this.keep(this.clone(r)))}getTensorsForGradient(t,e,r){let i=Tb(t);if(i!=null){let o=i.inputsToSave||[],s=i.outputsToSave||[],a;i.saveAllInputs?(Ut(Array.isArray(e),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(e).map(c=>e[c])):a=o.map(c=>e[c]);let l=r.filter((c,u)=>s[u]);return a.concat(l)}return[]}makeTensor(t,e,r,i){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");r=r||"float32",i=i||this.backend;let o=t;r==="string"&&Cl(t[0])&&(o=t.map(l=>Ol(l)));let s=i.write(o,e,r),a=new An(e,r,s,this.nextTensorId());if(this.trackTensor(a,i),r==="string"){let l=this.state.tensorInfo.get(s),c=yb(o);this.state.numBytes+=c-l.bytes,l.bytes=c}return a}makeTensorFromDataId(t,e,r,i){r=r||"float32";let o=new An(e,r,t,this.nextTensorId());return this.trackTensor(o,i),o}makeVariable(t,e=!0,r,i){r=r||this.nextVariableId().toString(),i!=null&&i!==t.dtype&&(t=t.cast(i));let o=new Zs(t,e,r,this.nextTensorId());if(this.state.registeredVariables[o.name]!=null)throw new Error(`Variable with name ${o.name} was already registered`);return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o}trackTensor(t,e){this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++;let r=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(r=t.size*xm(t.dtype)),this.state.numBytes+=r,this.state.tensorInfo.has(t.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r})),t instanceof Zs||this.track(t)}incRef(t,e){this.trackTensor(t,e),this.backend.incRef(t.dataId)}removeDataId(t,e){this.state.tensorInfo.has(t)&&this.state.tensorInfo.get(t).backend===e&&(this.state.tensorInfo.delete(t),this.state.numDataBuffers--)}disposeTensor(t){if(!this.state.tensorInfo.has(t.dataId))return;let e=this.state.tensorInfo.get(t.dataId);if(this.state.numTensors--,t.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=e.bytes),t.dtype!=="complex64"&&t.dtype!=="string"){let r=t.size*xm(t.dtype);this.state.numBytes-=r}e.backend.disposeData(t.dataId)&&this.removeDataId(t.dataId,e.backend)}disposeVariables(){for(let t in this.state.registeredVariables){let e=this.state.registeredVariables[t];this.disposeVariable(e)}}disposeVariable(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]}memory(){let t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t}profile(t){return Jt(this,null,function*(){this.state.profiling=!0;let e=this.state.numBytes,r=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=yield t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(i=>i.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-r;for(let i of this.state.activeProfile.kernels)i.kernelTimeMs=yield i.kernelTimeMs,i.extraInfo=yield i.extraInfo;return this.state.activeProfile})}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(t,e,r,i,o,s){let a={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:r,saved:o},l=Tb(t);l!=null&&(i=l.gradFunc),i!=null&&(a.gradient=c=>(c=c.map((u,h)=>{if(u==null){let p=r[h],d=Tl(p.size,p.dtype);return this.makeTensor(d,p.shape,p.dtype)}return u}),i(c.length>1?c:c[0],o,s))),this.state.activeTape.push(a)}keep(t){return t.kept=!0,t}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(t){let e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e}endScope(t){let e=GT(t),r=new Set(e.map(o=>o.id));for(let o=0;o{!o.kept&&o.scopeId===i.id&&this.track(o)})}gradients(t,e,r,i=!1){if(Ut(e.length>0,()=>"gradients() received an empty list of xs."),r!=null&&r.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${r.dtype}'`);let o=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",t));Ut(o instanceof An,()=>"The result y returned by f() must be a tensor.");let s=FT(this.state.activeTape,e,o);if(!i&&s.length===0&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let a={};a[o.id]=r==null?UU(o.shape):r,OT(a,s,c=>this.tidy(c),WU);let l=e.map(c=>a[c.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(c=>{for(let u of c.saved)u.dispose()}),this.state.activeTape=null),{value:o,grads:l}})}customGrad(t){return Ut(vm(t),()=>"The f passed in customGrad(f) must be a function."),(...e)=>{Ut(e.every(a=>a instanceof An),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let r,i={};e.forEach((a,l)=>{i[l]=a});let o=(a,l)=>(r=t(...e,l),Ut(r.value instanceof An,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),Ut(vm(r.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),r.value),s=(a,l)=>{let c=r.gradFunc(a,l),u=Array.isArray(c)?c:[c];Ut(u.length===e.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),Ut(u.every(p=>p instanceof An),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let h={};return u.forEach((p,d)=>{h[d]=()=>p}),h};return this.runKernelFunc({forwardFunc:o,backwardsFunc:s,inputs:i})}}readSync(t){return this.state.tensorInfo.get(t).backend.readSync(t)}read(t){return this.state.tensorInfo.get(t).backend.read(t)}time(t){return Jt(this,null,function*(){let e=Ys(),r=yield this.backend.time(t);return r.wallMs=Ys()-e,r})}track(t){return this.state.activeScope!=null&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new n1;for(let t in this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};zo.nextTensorId=0;zo.nextVariableId=0;function UU(n){let t=bb(xn(n),"float32");return Kt.makeTensor(t,n,"float32")}function Fb(){let n=Sb();if(n._tfengine==null){let t=new ih(n);n._tfengine=new zo(t)}return LT(n._tfengine.ENV),$T(()=>n._tfengine),n._tfengine}var Kt=Fb();function WU(n,t){let e={a:n,b:t};return Kt.runKernel(Us,e)}var Fo={};So(Fo,{isBrowser:()=>Ob,isMobile:()=>jU});function GU(){return typeof navigator!="undefined"&&navigator!=null}function jU(n){if(n||GU()){if(n||(n=navigator),n.product==="ReactNative")return!0;let t=n.userAgent||n.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function Ob(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Kr=ot();Kr.registerFlag("DEBUG",()=>!1,n=>{n&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Kr.registerFlag("IS_BROWSER",()=>Ob());Kr.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Kr.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Kr.registerFlag("PROD",()=>!1);Kr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Kr.getBool("DEBUG"));Kr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Kr.registerFlag("IS_TEST",()=>!1);Kr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Kr.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Bb(n,t){let e=n;if(lr(n))return t==="string"?[]:[n.length];if(!Array.isArray(n))return[];let r=[];for(;Array.isArray(e)||lr(e)&&t!=="string";)r.push(e.length),e=e[0];return Array.isArray(n)&&ot().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&XT(n,r,[]),r}function XT(n,t,e){if(e=e||[],!Array.isArray(n)&&!lr(n)){Ut(t.length===0,()=>`Element arr[${e.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}Ut(t.length>0,()=>`Element arr[${e.join("][")}] should be a primitive, but is an array of ${n.length} elements`),Ut(n.length===t[0],()=>`Element arr[${e.join("][")}] should have ${t[0]} elements, but has ${n.length} elements`);let r=t.slice(1);for(let i=0;i=0&&(i=r),qT(r,i,t,e),n==null||!lr(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){let l=n==null?"null":n.constructor.name;throw new Error(`Argument '${t}' passed to '${e}' must be a Tensor or TensorLike, but got '${l}'`)}let o=Bb(n,i);!lr(n)&&!Array.isArray(n)&&(n=[n]);let a=i!=="string"?Fl(n,i):No(n,[],!0);return Kt.makeTensor(a,o,i)}var qU="__op";function xe(n){let t=Object.keys(n);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let e=t[0],r=n[e];e.endsWith("_")&&(e=e.substring(0,e.length-1)),e=e+qU;let i=(...o)=>{Kt.startScope(e);try{let s=r(...o);return rh(s)&&console.error("Cannot return a Promise inside of tidy."),Kt.endScope(s),s}catch(s){throw Kt.endScope(null),s}};return Object.defineProperty(i,"name",{value:e,configurable:!0}),i}function XU(n,t){let e=pe(n,"real","complex"),r=pe(t,"imag","complex");mb(e.shape,r.shape,`real and imag shapes, ${e.shape} and ${r.shape}, must match in call to tf.complex().`);let i={real:e,imag:r};return Kt.runKernel(Il,i)}var KT=xe({complex_:XU});function r1(n,t,e,r){if(r==null&&(r=Ml(n)),r==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!lr(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){nh(t);let i=xn(t),o=xn(e);Ut(i===o,()=>`Based on the provided shape, [${t}], the tensor should have ${i} values but has ${o}`);for(let s=0;s`Error creating a new Tensor. Inferred shape (${e}) does not match the provided shape (${t}). `)}}return!lr(n)&&!Array.isArray(n)&&(n=[n]),t=t||e,n=r!=="string"?Fl(n,r):No(n,[],!0),Kt.makeTensor(n,t,r)}function Vb(n,t,e){let r=Bb(n,e);return r1(n,t,r,e)}var Hb=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function YT(n){return Hb?Buffer.byteLength(n):new Blob([n]).size}function ZT(n){if(Hb)return Buffer.from(n).toString("base64");let t=new Uint8Array(n),e="";for(let r=0,i=t.length;r{t+=i.byteLength});let e=new Uint8Array(t),r=0;return n.forEach(i=>{e.set(new Uint8Array(i),r),r+=i.byteLength}),e.buffer}function to(n){if(n.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:n.modelTopology==null?0:YT(JSON.stringify(n.modelTopology)),weightSpecsBytes:n.weightSpecs==null?0:YT(JSON.stringify(n.weightSpecs)),weightDataBytes:n.weightData==null?0:n.weightData.byteLength}}var Fe=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Fe.instance==null&&(Fe.instance=new Fe),Fe.instance}static registerSaveRouter(t){Fe.getInstance().saveRouters.push(t)}static registerLoadRouter(t){Fe.getInstance().loadRouters.push(t)}static getSaveHandlers(t){return Fe.getHandlers(t,"save")}static getLoadHandlers(t,e){return Fe.getHandlers(t,"load",e)}static getHandlers(t,e,r){let i=[];return(e==="load"?Fe.getInstance().loadRouters:Fe.getInstance().saveRouters).forEach(s=>{let a=s(t,r);a!==null&&i.push(a)}),i}};var $b="tensorflowjs",Ub=1,Qs="models_store",Oo="model_info_store";function QT(){if(!ot().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let n=typeof window=="undefined"?self:window,t=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Wb(n){let t=n.result;t.createObjectStore(Qs,{keyPath:"modelPath"}),t.createObjectStore(Oo,{keyPath:"modelPath"})}var Si=class{constructor(t){if(this.indexedDB=QT(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}save(t){return Jt(this,null,function*(){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,t)})}load(){return Jt(this,null,function*(){return this.databaseAction(this.modelPath)})}databaseAction(t,e){return new Promise((r,i)=>{let o=this.indexedDB.open($b,Ub);o.onupgradeneeded=()=>Wb(o),o.onsuccess=()=>{let s=o.result;if(e==null){let a=s.transaction(Qs,"readonly"),c=a.objectStore(Qs).get(this.modelPath);c.onsuccess=()=>{if(c.result==null)return s.close(),i(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));r(c.result.modelArtifacts)},c.onerror=u=>(s.close(),i(c.error)),a.oncomplete=()=>s.close()}else{let a=to(e),l=s.transaction(Oo,"readwrite"),c=l.objectStore(Oo),u=c.put({modelPath:this.modelPath,modelArtifactsInfo:a}),h;u.onsuccess=()=>{h=s.transaction(Qs,"readwrite");let d=h.objectStore(Qs).put({modelPath:this.modelPath,modelArtifacts:e,modelArtifactsInfo:a});d.onsuccess=()=>r({modelArtifactsInfo:a}),d.onerror=f=>{c=l.objectStore(Oo);let m=c.delete(this.modelPath);m.onsuccess=()=>(s.close(),i(d.error)),m.onerror=x=>(s.close(),i(d.error))}},u.onerror=p=>(s.close(),i(u.error)),l.oncomplete=()=>{h==null?s.close():h.oncomplete=()=>s.close()}}},o.onerror=s=>i(o.error)})}};Si.URL_SCHEME="indexeddb://";var tA=n=>ot().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(Si.URL_SCHEME)?YU(n.slice(Si.URL_SCHEME.length)):null;Fe.registerSaveRouter(tA);Fe.registerLoadRouter(tA);function YU(n){return new Si(n)}function ZU(n){return n.startsWith(Si.URL_SCHEME)?n.slice(Si.URL_SCHEME.length):n}var o1=class{constructor(){this.indexedDB=QT()}listModels(){return Jt(this,null,function*(){return new Promise((t,e)=>{let r=this.indexedDB.open($b,Ub);r.onupgradeneeded=()=>Wb(r),r.onsuccess=()=>{let i=r.result,o=i.transaction(Oo,"readonly"),a=o.objectStore(Oo).getAll();a.onsuccess=()=>{let l={};for(let c of a.result)l[c.modelPath]=c.modelArtifactsInfo;t(l)},a.onerror=l=>(i.close(),e(a.error)),o.oncomplete=()=>i.close()},r.onerror=i=>e(r.error)})})}removeModel(t){return Jt(this,null,function*(){return t=ZU(t),new Promise((e,r)=>{let i=this.indexedDB.open($b,Ub);i.onupgradeneeded=()=>Wb(i),i.onsuccess=()=>{let o=i.result,s=o.transaction(Oo,"readwrite"),a=s.objectStore(Oo),l=a.get(t),c;l.onsuccess=()=>{if(l.result==null)return o.close(),r(new Error(`Cannot find model with path '${t}' in IndexedDB.`));{let u=a.delete(t),h=()=>{c=o.transaction(Qs,"readwrite");let d=c.objectStore(Qs).delete(t);d.onsuccess=()=>e(l.result.modelArtifactsInfo),d.onerror=f=>r(l.error)};u.onsuccess=h,u.onerror=p=>(h(),o.close(),r(l.error))}},l.onerror=u=>(o.close(),r(l.error)),s.oncomplete=()=>{c==null?o.close():c.oncomplete=()=>o.close()}},i.onerror=o=>r(i.error)})})}};var eo="/",$l="tensorflowjs_models",eA="info",JU="model_topology",QU="weight_specs",tW="weight_data",eW="model_metadata";function nA(n){return{info:[$l,n,eA].join(eo),topology:[$l,n,JU].join(eo),weightSpecs:[$l,n,QU].join(eo),weightData:[$l,n,tW].join(eo),modelMetadata:[$l,n,eW].join(eo)}}function nW(n){let t=n.split(eo);if(t.length<3)throw new Error(`Invalid key format: ${n}`);return t.slice(1,t.length-1).join(eo)}function rW(n){return n.startsWith(Ci.URL_SCHEME)?n.slice(Ci.URL_SCHEME.length):n}var Ci=class{constructor(t){if(!ot().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,t==null||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=nA(this.modelPath)}save(t){return Jt(this,null,function*(){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let e=JSON.stringify(t.modelTopology),r=JSON.stringify(t.weightSpecs),i=to(t);try{this.LS.setItem(this.keys.info,JSON.stringify(i)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,ZT(t.weightData));let o={format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy};return t.signature!=null&&(o.signature=t.signature),t.userDefinedMetadata!=null&&(o.userDefinedMetadata=t.userDefinedMetadata),t.modelInitializer!=null&&(o.modelInitializer=t.modelInitializer),this.LS.setItem(this.keys.modelMetadata,JSON.stringify(o)),{modelArtifactsInfo:i}}catch(o){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${i.modelTopologyBytes}, weightSpecsBytes=${i.weightSpecsBytes}, weightDataBytes=${i.weightDataBytes}.`)}}})}load(){return Jt(this,null,function*(){let t=JSON.parse(this.LS.getItem(this.keys.info));if(t==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(t.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let e={},r=JSON.parse(this.LS.getItem(this.keys.topology));if(r==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);e.modelTopology=r;let i=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(i==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);e.weightSpecs=i;let o=this.LS.getItem(this.keys.modelMetadata);if(o!=null){let a=JSON.parse(o);e.format=a.format,e.generatedBy=a.generatedBy,e.convertedBy=a.convertedBy,a.signature!=null&&(e.signature=a.signature),a.userDefinedMetadata!=null&&(e.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(e.modelInitializer=a.modelInitializer)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return e.weightData=JT(s),e})}};Ci.URL_SCHEME="localstorage://";var rA=n=>ot().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(Ci.URL_SCHEME)?iW(n.slice(Ci.URL_SCHEME.length)):null;Fe.registerSaveRouter(rA);Fe.registerLoadRouter(rA);function iW(n){return new Ci(n)}var s1=class{constructor(){Ut(ot().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),Ut(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}listModels(){return Jt(this,null,function*(){let t={},e=$l+eo,r=eo+eA;for(let i=0;i"scheme must not be undefined or null."),t.endsWith(iA)&&(t=t.slice(0,t.indexOf(iA))),Ut(t.length>0,()=>"scheme must not be an empty string.");let r=Yr.getInstance();Ut(r.managers[t]==null,()=>`A model store manager is already registered for scheme '${t}'.`),r.managers[t]=e}static getManager(t){let e=this.getInstance().managers[t];if(e==null)throw new Error(`Cannot find model manager for scheme '${t}'`);return e}static getSchemes(){return Object.keys(this.getInstance().managers)}};var Gb=class{fetch(t,e){return fetch(t,e)}now(){return performance.now()}encode(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${e}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)}decode(t,e){return new TextDecoder(e).decode(t)}};if(ot().get("IS_BROWSER")){ot().setPlatform("browser",new Gb);try{Yr.registerManager(Ci.URL_SCHEME,new s1)}catch(n){}try{Yr.registerManager(Si.URL_SCHEME,new o1)}catch(n){}}var oW={importFetch:()=>oA()},jb;var qb=class{constructor(){this.util=sA(),this.textEncoder=new this.util.TextEncoder}fetch(t,e){return ot().global.fetch!=null?ot().global.fetch(t,e):(jb==null&&(jb=oW.importFetch()),jb(t,e))}now(){let t=process.hrtime();return t[0]*1e3+t[1]/1e6}encode(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${e}`);return this.textEncoder.encode(t)}decode(t,e){return t.length===0?"":new this.util.TextDecoder(e).decode(t)}};ot().get("IS_NODE")&&ot().setPlatform("node",new qb);function Xt(n,t="float32",e){return t=t||"float32",nh(n),new Ce(n,t,e)}function sW(n,t){let e=pe(n,"x","cast");if(!vb(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&e.dtype!=="string"||t!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");let r={x:e},i={dtype:t};return Kt.runKernel(Lo,r,i)}var a1=xe({cast_:sW});function aW(n){let e={x:pe(n,"x","clone","string_or_numeric")};return Kt.runKernel(Do,e)}var aA=xe({clone_:aW});function lA(n,t=!1){console.log(n.toString(t))}Fb();var lW={buffer:Xt,cast:a1,clone:aA,print:lA};UT(lW);var cW="model",uW=".json",hW=".weights.bin";function cA(n){return new Promise(t=>setTimeout(t)).then(n)}var no=class{constructor(t){if(!ot().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(no.URL_SCHEME)&&(t=t.slice(no.URL_SCHEME.length)),(t==null||t.length===0)&&(t=cW),this.modelTopologyFileName=t+uW,this.weightDataFileName=t+hW}save(t){return Jt(this,null,function*(){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"}));if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let r=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],i={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:r};t.signature!=null&&(i.signature=t.signature),t.userDefinedMetadata!=null&&(i.userDefinedMetadata=t.userDefinedMetadata),t.modelInitializer!=null&&(i.modelInitializer=t.modelInitializer);let o=window.URL.createObjectURL(new Blob([JSON.stringify(i)],{type:"application/json"})),s=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(s.download=this.modelTopologyFileName,s.href=o,yield cA(()=>s.dispatchEvent(new MouseEvent("click"))),t.weightData!=null){let a=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;a.download=this.weightDataFileName,a.href=e,yield cA(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:to(t)}}})}};no.URL_SCHEME="downloads://";var pW=n=>ot().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(no.URL_SCHEME)?dW(n.slice(no.URL_SCHEME.length)):null;Fe.registerSaveRouter(pW);function dW(n="model"){return new no(n)}function Xb(n,t,e,r){s(n),e=e==null?0:e,r=r==null?1:r,a(e,r);let i=0,o=l=>(l.then(c=>{let u=e+ ++i/n.length*(r-e);return t(u),c}),l);function s(l){Ut(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function a(l,c){Ut(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),Ut(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),Ut(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(n.map(o))}function uA(n,t){return Jt(this,null,function*(){t==null&&(t={});let e=t.fetchFunc==null?ot().platform.fetch:t.fetchFunc,r=n.map(h=>e(h,t.requestInit,{isBinary:!0})),i=0,o=.5,a=(t.onProgress==null?yield Promise.all(r):yield Xb(r,t.onProgress,i,o)).map(h=>h.arrayBuffer()),l=.5,c=1;return t.onProgress==null?yield Promise.all(a):yield Xb(a,t.onProgress,l,c)})}var mW="application/octet-stream",gW="application/json",rp=class{constructor(t,e){if(this.DEFAULT_METHOD="POST",e==null&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,this.weightUrlConverter=e.weightUrlConverter,e.fetchFunc!=null?(Ut(typeof e.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=e.fetchFunc):this.fetch=ot().platform.fetch,Ut(t!=null&&t.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(t)&&Ut(t.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${t.length}).`),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}save(t){return Jt(this,null,function*(){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);e.body=new FormData;let r=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],i={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:r};t.signature!=null&&(i.signature=t.signature),t.userDefinedMetadata!=null&&(i.userDefinedMetadata=t.userDefinedMetadata),t.modelInitializer!=null&&(i.modelInitializer=t.modelInitializer),e.body.append("model.json",new Blob([JSON.stringify(i)],{type:gW}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:mW}),"model.weights.bin");let o=yield this.fetch(this.path,e);if(o.ok)return{modelArtifactsInfo:to(t),responses:[o]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${o.status}.`)})}load(){return Jt(this,null,function*(){let t=yield this.fetch(this.path,this.requestInit);if(!t.ok)throw new Error(`Request to ${this.path} failed with status code ${t.status}. Please verify this URL points to the model JSON of the model to load.`);let e;try{e=yield t.json()}catch(f){let m=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?m+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":m+=" Please make sure the server is serving valid JSON for this request.",new Error(m)}let r=e.modelTopology,i=e.weightsManifest,o=e.generatedBy,s=e.convertedBy,a=e.format,l=e.signature,c=e.userDefinedMetadata;if(r==null&&i==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let u,h;i!=null&&([u,h]=yield this.loadWeights(i));let p={modelTopology:r,weightSpecs:u,weightData:h,generatedBy:o,convertedBy:s,format:a};l!=null&&(p.signature=l),c!=null&&(p.userDefinedMetadata=c);let d=e.modelInitializer;return d&&(p.modelInitializer=d),p})}loadWeights(t){return Jt(this,null,function*(){let e=Array.isArray(this.path)?this.path[1]:this.path,[r,i]=xW(e),o=this.weightPathPrefix||r,s=[];for(let u of t)s.push(...u.weights);let a=[],l=[];for(let u of t)for(let h of u.paths)this.weightUrlConverter!=null?l.push(this.weightUrlConverter(h)):a.push(o+h+i);this.weightUrlConverter&&a.push(...yield Promise.all(l));let c=yield uA(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,i1(c)]})}};rp.URL_SCHEME_REGEX=/^https?:\/\//;function xW(n){let t=n.lastIndexOf("/"),e=n.lastIndexOf("?"),r=n.substring(0,t),i=e>t?n.substring(e):"";return[r+"/",i]}function Kb(n){return n.match(rp.URL_SCHEME_REGEX)!=null}var hA=(n,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let e=!0;if(Array.isArray(n)?e=n.every(r=>Kb(r)):e=Kb(n),e)return pA(n,t)}return null};Fe.registerSaveRouter(hA);Fe.registerLoadRouter(hA);function pA(n,t){return new rp(n,t)}function yW(n,t,e=!1,r=!1){let i=pe(n,"a","matMul"),o=pe(t,"b","matMul");[i,o]=Hl(i,o);let s={a:i,b:o},a={transposeA:e,transposeB:r};return Kt.runKernel(Al,s,a)}var Yb=xe({matMul_:yW});function bW(n,t){let e=pe(n,"x","transpose");if(t==null&&(t=e.shape.map((o,s)=>s).reverse()),Ut(e.rank===t.length,()=>`Error in transpose: rank of input ${e.rank} must match length of perm ${t}.`),t.forEach(o=>{Ut(o>=0&&o`All entries in 'perm' must be between 0 and ${e.rank-1} but got ${t}`)}),e.rank<=1)return e.clone();let r={x:e},i={perm:t};return Kt.runKernel(zl,r,i)}var dA=xe({transpose_:bW});function _W(n,t){let e=n.shape.length,r=t.shape.length;if(e<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>e)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${e}`);if(xn(n.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${n.shape}.`);let i=t.shape,o=i[i.length-1],s=1;for(let h=0;hh/c),1].slice(0,o);return[l,s,c,u]}function fA(n,t,e){let r=t.rank>1?t.shape[t.rank-1]:1,i=t.rank>1?t.rank-1:1,o=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${e.shape}, indices.shape: ${t.shape}, shape: ${n}, sliceDim: ${r}, and batchDim: ${i}.`;if(e.rank1?t.shape[r-1]:1,o=e.length,s=1;for(let h=i;hCW,computeFlatOffset:()=>EW,computeOutShape:()=>mA,getNormalizedAxes:()=>yA,isSliceContinous:()=>MW,maskToAxes:()=>l1,parseSliceParams:()=>TW,sliceInfo:()=>AW,startForAxis:()=>SA,startIndicesWithElidedDims:()=>bA,stopForAxis:()=>CA,stopIndicesWithElidedDims:()=>_A,stridesForAxis:()=>wA,stridesWithElidedDims:()=>gA});function CW(n,t,e){let r=n.shape.length;Ut(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),Ut(r===e.length,()=>`Error in slice${r}D: Length of size ${e} must match the rank of the array (${r}).`);for(let i=0;i`Error in slice${r}D: begin[${i}] + size[${i}] (${t[i]+e[i]}) would overflow input.shape[${i}] (${n.shape[i]})`)}function l1(n){let t=[],e=0;for(;n>0;)n&1&&t.push(e),n/=2,e++;return t}function mA(n,t,e){let r=[];for(let i=0;i0){let d=t[0],f=e+1;u=bA(s,d,f,r,n),h=_A(a,d,f,i,n),p=gA(o,d,f,n)}else for(let d=0;d-1)o[a]=0;else{let l=xA(t,e,a),c=r[l];n&1<-1)o[a]=Number.MAX_SAFE_INTEGER;else{let l=xA(t,e,a),c=r[l];n&1<0?s=Number.MIN_SAFE_INTEGER:s=Number.MAX_SAFE_INTEGER);let l=r[i];return s<0&&(s+=l),s=wl(0,s,l-1),s}function CA(n,t,e,r,i,o){let s=t[i],a=e[i]||1;(n&1<0?s=Number.MAX_SAFE_INTEGER:s=Number.MIN_SAFE_INTEGER);let l=r[i];return s<0&&(s+=l),a>0?s=wl(0,s,l):s=wl(-1,s,l-1),s}function MW(n,t,e){let r=e.length;for(let i=0;i1){r=i;break}for(let i=r+1;i0||e[i]!==n[i])return!1;return!0}function EW(n,t){let e=n.length>0?n[n.length-1]:1;for(let r=0;r{Ut(s!==-1,()=>"slice() does not support negative begin indexing.")});let o;return e==null?o=new Array(i).fill(-1):typeof e=="number"?o=[e,...new Array(i-1).fill(-1)]:e.lengths>=0?s:(Ut(s===-1,()=>`Negative size values should be exactly -1 but got ${s} for the slice() size at index ${a}.`),n.shape[a]-r[a])),[r,o]}function AW(n,t,e,r,i,o,s,a,l){let c=t.slice(),u=e.slice(),h=r;r==null&&(h=new Array(c.length));let p=l1(s);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(s!==0&&a!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(s!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let d=n.length-c.length,f=l1(a),m=n.slice();f.forEach(E=>{c[E]=0,u[E]=1,m.splice(E,0,1)});let{begin:x,end:g,strides:v}=yA(m,p,d,c,u,h,i,o,s);c=x,u=g,h=v;let b=l1(l);b.forEach(E=>{u[E]=c[E]+1,h[E]=1});let y=mA(c,u,h),_=y.filter((E,M)=>b.indexOf(M)===-1);return{nonStrided:h.every(E=>E===1),$begin:c,$end:u,$strides:h,size:y,newShape:m,outShape:_}}function IW(n){ot().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}WT(IW);function ro(){return Kt}function MA(n,t){return Kt.tidy(n,t)}function EA(){return Kt.ready()}function TA(){return Kt.backendName}function c1(n,t,e=1){return Kt.registerBackend(n,t,e)}function kW(n,t){let e=pe(n,"a","mul"),r=pe(t,"b","mul");[e,r]=Hl(e,r);let i={a:e,b:r};return Kt.runKernel(Gs,i)}var AA=xe({mul_:kW});function RW(n,t,e,r,i="NHWC",o){let s=n[3],a=[...t,s],l=kA(i);return Qb(n,a,e,o,r,null,null,l)}function PW(n,t,e,r,i,o,s="channelsLast"){let[a,l]=u1(t),c;if(s==="channelsLast")c=[a,l,n[3],n[3]];else if(s==="channelsFirst")c=[a,l,n[1],n[1]];else throw new Error(`Unknown dataFormat ${s}`);return Qb(n,c,e,r,i,o,!1,s)}function NW(n,t,e,r,i,o,s="NDHWC"){let[a,l,c]=Zb(t),u,h;if(s==="NDHWC")h="channelsLast",u=[a,l,c,n[4],n[4]];else if(s==="NCDHW")h="channelsFirst",u=[a,l,c,n[1],n[1]];else throw new Error(`Unknown dataFormat ${s}`);return IA(n,u,e,r,i,!1,h,o)}function Qb(n,t,e,r,i,o,s=!1,a="channelsLast"){let[l,c,u,h]=[-1,-1,-1,-1];if(a==="channelsLast")[l,c,u,h]=n;else if(a==="channelsFirst")[l,h,c,u]=n;else throw new Error(`Unknown dataFormat ${a}`);let[p,d,,f]=t,[m,x]=u1(e),[g,v]=u1(r),b=Ul(p,g),y=Ul(d,v),{padInfo:_,outHeight:S,outWidth:E}=zW(i,c,u,m,x,b,y,o,a),M=s?f*h:f,P;return a==="channelsFirst"?P=[l,M,S,E]:a==="channelsLast"&&(P=[l,S,E,M]),{batchSize:l,dataFormat:a,inHeight:c,inWidth:u,inChannels:h,outHeight:S,outWidth:E,outChannels:M,padInfo:_,strideHeight:m,strideWidth:x,filterHeight:p,filterWidth:d,effectiveFilterHeight:b,effectiveFilterWidth:y,dilationHeight:g,dilationWidth:v,inShape:n,outShape:P,filterShape:t}}function IA(n,t,e,r,i,o=!1,s="channelsLast",a){let[l,c,u,h,p]=[-1,-1,-1,-1,-1];if(s==="channelsLast")[l,c,u,h,p]=n;else if(s==="channelsFirst")[l,p,c,u,h]=n;else throw new Error(`Unknown dataFormat ${s}`);let[d,f,m,,x]=t,[g,v,b]=Zb(e),[y,_,S]=Zb(r),E=Ul(d,y),M=Ul(f,_),P=Ul(m,S),{padInfo:D,outDepth:w,outHeight:I,outWidth:N}=FW(i,c,u,h,g,v,b,E,M,P,a),L=o?x*p:x,O;return s==="channelsFirst"?O=[l,L,w,I,N]:s==="channelsLast"&&(O=[l,w,I,N,L]),{batchSize:l,dataFormat:s,inDepth:c,inHeight:u,inWidth:h,inChannels:p,outDepth:w,outHeight:I,outWidth:N,outChannels:L,padInfo:D,strideDepth:g,strideHeight:v,strideWidth:b,filterDepth:d,filterHeight:f,filterWidth:m,effectiveFilterDepth:E,effectiveFilterHeight:M,effectiveFilterWidth:P,dilationDepth:y,dilationHeight:_,dilationWidth:S,inShape:n,outShape:O,filterShape:t}}function LW(n,t,e,r,i){r==null&&(r=t_(n,t,e));let o=n[0],s=n[1],a=ta((o-t+2*r)/e+1,i),l=ta((s-t+2*r)/e+1,i);return[a,l]}function DW(n,t,e,r,i,o){i==null&&(i=t_(n,t,r));let s=n[0],a=n[1],l=n[2],c=ta((s-t+2*i)/r+1,o),u=ta((a-t+2*i)/r+1,o),h=ta((l-t+2*i)/r+1,o);return[c,u,h,e]}function t_(n,t,e,r=1){let i=Ul(t,r);return Math.floor((n[0]*(e-1)-e+i)/2)}function u1(n){return typeof n=="number"?[n,n,n]:n.length===2?[n[0],n[1],1]:n}function Zb(n){return typeof n=="number"?[n,n,n]:n}function Ul(n,t){return t<=1?n:n+(n-1)*(t-1)}function zW(n,t,e,r,i,o,s,a,l){let c,u,h;if(typeof n=="number"){c={top:n,bottom:n,left:n,right:n,type:n===0?"VALID":"NUMBER"};let d=LW([t,e],o,r,n,a);u=d[0],h=d[1]}else if(n==="same"){u=Math.ceil(t/r),h=Math.ceil(e/i);let p=Math.max(0,(u-1)*r+o-t),d=Math.max(0,(h-1)*i+s-e),f=Math.floor(p/2),m=p-f,x=Math.floor(d/2),g=d-x;c={top:f,bottom:m,left:x,right:g,type:"SAME"}}else if(n==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-o+1)/r),h=Math.ceil((e-s+1)/i);else if(typeof n=="object"){let p=l==="channelsLast"?n[1][0]:n[2][0],d=l==="channelsLast"?n[1][1]:n[2][1],f=l==="channelsLast"?n[2][0]:n[3][0],m=l==="channelsLast"?n[2][1]:n[3][1];c={top:p,bottom:d,left:f,right:m,type:p===0&&d===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=ta((t-o+p+d)/r+1,a),h=ta((e-s+f+m)/i+1,a)}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:c,outHeight:u,outWidth:h}}function FW(n,t,e,r,i,o,s,a,l,c,u){let h,p,d,f;if(typeof n=="number"){h={top:n,bottom:n,left:n,right:n,front:n,back:n,type:n===0?"VALID":"NUMBER"};let x=DW([t,e,r,1],a,1,i,n,u);p=x[0],d=x[1],f=x[2]}else if(n==="same"){p=Math.ceil(t/i),d=Math.ceil(e/o),f=Math.ceil(r/s);let m=(p-1)*i+a-t,x=(d-1)*o+l-e,g=(f-1)*s+c-r,v=Math.floor(m/2),b=m-v,y=Math.floor(x/2),_=x-y,S=Math.floor(g/2),E=g-S;h={top:y,bottom:_,left:S,right:E,front:v,back:b,type:"SAME"}}else if(n==="valid")h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-a+1)/i),d=Math.ceil((e-l+1)/o),f=Math.ceil((r-c+1)/s);else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:h,outDepth:p,outHeight:d,outWidth:f}}function ta(n,t){if(!t)return Math.trunc(n);switch(t){case"round":return Math.round(n);case"ceil":return Math.ceil(n);case"floor":return Math.floor(n);default:throw new Error(`Unknown roundingMode ${t}`)}}function Jb(n){let[t,e,r]=u1(n);return t===1&&e===1&&r===1}function OW(n,t){return Jb(n)||Jb(t)}function kA(n){if(n==="NHWC")return"channelsLast";if(n==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${n}`)}function BW(n,t){let r={x:pe(n,"x","reshape","string_or_numeric")},i={shape:t};return Kt.runKernel(Nl,r,i)}var RA=xe({reshape_:BW});function VW(n,t){let e=n.length,r=[];for(let i=0;i1&&s===1&&r.unshift(o)}return r}function e_(n,t){let e=[];for(let r=0;r1)&&e.unshift(o)}return e}function HW(n,t){let e=[],r=Math.max(n.length,t.length);for(let i=0;in[o]);return[e,i]}function XW(n,t){let e=t.map(r=>1);return DA(n,e,t)}function KW(n,t,e){Ut(r_(t,e),()=>`${n} supports only inner-most axes for now. Got axes ${t} and rank-${e} input.`)}function YW(n,t){if(r_(n,t))return null;let e=[];for(let r=0;re.push(r)),e}function ZW(n){return n.map((t,e)=>[e,t]).sort((t,e)=>t[1]-e[1]).map(t=>t[0])}function JW(n,t){let e=[];for(let r=t-n;r0&&(e=LA(e,r)),RA(e,n.shape)}function dG(n,t,e,r){if(t==="linear")return n;if(t==="relu")return QA(n);if(t==="elu")return PA(n);if(t==="relu6")return tI(n);if(t==="prelu")return zA(n,e);if(t==="leakyrelu")return NA(n,r);throw new Error(`Unknown fused activation ${t}.`)}var fG=(n,t)=>!(n>0)||t==="linear";function rI(n,t,e){let r=mG(n,t,e),i=r<0?-(r+1):r;n.splice(i,0,t)}function mG(n,t,e){return xG(n,t,e||gG)}function gG(n,t){return n>t?1:n>>1);let a=e(t,n[o]);a>0?r=o+1:(i=o,s=!a)}return s?r:-r-1}function oI(n,t,e,r,i){return d_(n,t,e,r,i,0)}function sI(n,t,e,r,i,o){return d_(n,t,e,r,i,0,!1,o,!0)}function aI(n,t,e,r,i,o){return d_(n,t,e,r,i,o,!0)}function d_(n,t,e,r,i,o,s=!1,a=!1,l=!1){let c=[];for(let x=0;xi&&c.push({score:t[x],boxIndex:x,suppressBeginIndex:0});c.sort(iI);let u=o>0?-.5/o:0,h=[],p=[];for(;h.length0;){let x=c.pop(),{score:g,boxIndex:v,suppressBeginIndex:b}=x;if(g=b;--_){let S=vG(n,v,h[_]);if(S>=r){y=!0;break}if(x.score=x.score*yG(r,u,S),x.score<=i)break}x.suppressBeginIndex=h.length,y||(x.score===g?(h.push(v),p.push(x.score)):x.score>i&&rI(c,x,iI))}let d=h.length,f=e-d;a&&f>0&&(h.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:h};return s&&(m.selectedScores=p),l&&(m.validOutputs=d),m}function vG(n,t,e){let r=n.subarray(t*4,t*4+4),i=n.subarray(e*4,e*4+4),o=Math.min(r[0],r[2]),s=Math.min(r[1],r[3]),a=Math.max(r[0],r[2]),l=Math.max(r[1],r[3]),c=Math.min(i[0],i[2]),u=Math.min(i[1],i[3]),h=Math.max(i[0],i[2]),p=Math.max(i[1],i[3]),d=(a-o)*(l-s),f=(h-c)*(p-u);if(d<=0||f<=0)return 0;let m=Math.max(o,c),x=Math.max(s,u),g=Math.min(a,h),v=Math.min(l,p),b=Math.max(g-m,0)*Math.max(v-x,0);return b/(d+f-b)}function yG(n,t,e){let r=Math.exp(t*e*e);return e<=n?r:0}function iI(n,t){return n.score-t.score||n.score===t.score&&t.boxIndex-n.boxIndex}var F={};So(F,{ERF_A1:()=>PG,ERF_A2:()=>NG,ERF_A3:()=>LG,ERF_A4:()=>DG,ERF_A5:()=>zG,ERF_P:()=>RG,PARALLELIZE_THRESHOLD:()=>p1,SELU_SCALE:()=>kG,SELU_SCALEALPHA:()=>IG,applyActivation:()=>dG,assertAndGetBroadcastShape:()=>HW,assertAxesAreInnerMostDims:()=>KW,assertParamsConsistent:()=>bG,assignToTypedArray:()=>WG,axesAreInnerMostDims:()=>r_,calculateShapes:()=>SW,checkEinsumDimSizes:()=>YG,combineLocations:()=>DA,complexWithEvenIndex:()=>HG,complexWithOddIndex:()=>$G,computeConv2DInfo:()=>Qb,computeConv3DInfo:()=>IA,computeDefaultPad:()=>t_,computeDilation2DInfo:()=>RW,computeOptimalWindowSize:()=>wG,computeOutAndReduceShapes:()=>qW,computeOutShape:()=>_G,computePool2DInfo:()=>PW,computePool3DInfo:()=>NW,convertConv2DDataFormat:()=>kA,decodeEinsumEquation:()=>XG,eitherStridesOrDilationsAreOne:()=>OW,expandShapeToKeepDim:()=>XW,exponent:()=>jG,exponents:()=>GG,fromStringArrayToUint8:()=>oj,fromUint8ToStringArray:()=>ij,getAxesPermutation:()=>YW,getBroadcastDims:()=>VW,getComplexWithIndex:()=>UG,getEinsumComputePath:()=>ZG,getEinsumPermutation:()=>KG,getFusedBiasGradient:()=>pG,getFusedDyActivation:()=>hG,getImageCenter:()=>SG,getInnerMostAxes:()=>JW,getPermuted:()=>MG,getReductionAxes:()=>e_,getReshaped:()=>CG,getReshapedPermuted:()=>EG,getSliceBeginCoords:()=>TG,getSliceSize:()=>AG,getUndoAxesPermutation:()=>ZW,isIdentityPermutation:()=>JG,log:()=>OG,mergeRealAndImagArrays:()=>BG,prepareAndValidate:()=>_W,prepareSplitSize:()=>tj,segment_util:()=>m_,shouldFuse:()=>fG,slice_util:()=>In,splitRealAndImagArrays:()=>VG,tupleValuesAreOne:()=>Jb,upcastType:()=>on,validateInput:()=>wW,validateUpdateShape:()=>fA,warn:()=>FG});function bG(n,t){let e=n[0].length;n.forEach((i,o)=>{Ut(i.length===e,()=>`Error in concat${e}D: rank of tensors[${o}] must be the same as the rank of the rest (${e})`)}),Ut(t>=0&&t`Error in concat${e}D: axis must be between 0 and ${e-1}.`);let r=n[0];n.forEach((i,o)=>{for(let s=0;s`Error in concat${e}D: Shape of tensors[${o}] (${i}) does not match the shape of the rest (${r}) along the non-concatenated axis ${o}.`)})}function _G(n,t){let e=n[0].slice();for(let r=1;r=t*2+1||s%2===1?o.push(s):i.push(s);r.push(...i),r.push(0),r.push(...o)}return r}function EG(n,t,e,r=!0){let i=[];r?i.push(n[0]/e):i.push(n[0]*e);for(let o=1;o/g,lI=",",cI="...";function XG(n,t){n=n.replace(/\s/g,"");let e=(n.length-n.replace(qG,"").length)/f_.length;if(e<1)throw new Error("Equations without an arrow are not supported.");if(e>1)throw new Error(`Equation must contain exactly one arrow ("${f_}").`);let[r,i]=n.split(f_);Ut(r.indexOf(cI)===-1,()=>`The ellipsis notation ("${cI}") is not supported yet.`);let o=r.split(lI),s=o.length;if(t!==s)throw new Error(`Expected ${s} input tensors, received ${t}`);if(s>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let a=[];for(let p=0;pf.indexOf(d)!==-1))throw new Error(`Output subscripts contain the label ${d} not present in the input subscripts.`);a.indexOf(d)===-1&&a.push(d)}for(let p=0;pi!==-1),{permutationIndices:e,expandDims:r}}function YG(n,t,e){let r=new Array(n);for(let i=0;i`Expected dimension ${r[t[i][s]]} at axis ${s} of input shaped ${JSON.stringify(o)}, but got dimension ${o[s]}`)}}function ZG(n,t){let e=n,r=[],i=0;n.length===0&&e.push(-1),i=n.length+1;for(let s=0;st===e)}function QG(n,t){let e=[];for(let r=0;r"Number of splits must evenly divide the axis."),r=new Array(t).fill(n.shape[e]/t);else{let i=t.reduce((s,a)=>(a===-1&&(s+=1),s),0);Ut(i<=1,()=>"There should be only one negative value in split array.");let o=t.indexOf(-1);if(o!==-1){let s=t.reduce((a,l)=>l>0?a+l:a);t[o]=n.shape[e]-s}Ut(n.shape[e]===t.reduce((s,a)=>s+a),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}var m_={};So(m_,{collectGatherOpShapeInfo:()=>rj,computeOutShape:()=>nj,segOpComputeOptimalWindowSize:()=>ej});function ej(n,t){let e=!1,r;for(n<=p1?(r=n,e=!0):r=El(n,Math.floor(Math.sqrt(n)));!e;)r>t||r===n?e=!0:r=El(n,r+1);return r}function nj(n,t,e){let r=[],i=n.length;for(let o=0;oi))throw new Error(`Expect batchDims in the range of [-${i}, ${i}], but got ${r}`);if(r<0&&(r+=i),r>o)throw new Error(`batchDims (${r}) must be less than rank(x) ( + ${o}).`);if(eBl(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function oj(n){return n.map(t=>Ol(t))}var kn={};So(kn,{nonMaxSuppressionV3Impl:()=>oI,nonMaxSuppressionV4Impl:()=>sI,nonMaxSuppressionV5Impl:()=>aI,whereImpl:()=>nI});function ut(n,t){Array.isArray(n)||(n=[n]),n.forEach(e=>{e!=null&&R.assert(e.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var aj=kn.whereImpl,na=class extends Qi{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Vs(this,ro())}nextDataId(){return na.nextDataId++}write(t,e,r){this.firstUse&&(this.firstUse=!1,ot().get("IS_NODE")&&F.warn(` +============================ +Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details. +============================`));let i={id:this.nextDataId()};return this.data.set(i,{values:t,dtype:r,refCount:1}),i}makeTensorInfo(t,e,r){let i;if(e==="string"&&r!=null&&r.length>0&&R.isString(r[0])){let o=r.map(s=>R.encodeString(s));i=this.write(o,t,e)}else i=this.write(r,t,e);return{dataId:i,shape:t,dtype:e}}refCount(t){return this.data.has(t)?this.data.get(t).refCount:0}incRef(t){let e=this.data.get(t);e.refCount++}decRef(t){if(this.data.has(t)){let e=this.data.get(t);e.refCount--}}move(t,e,r,i,o){this.data.set(t,{values:e,dtype:i,refCount:o})}numDataIds(){return this.data.numDataIds()}read(t){return Jt(this,null,function*(){return this.readSync(t)})}readSync(t){let{dtype:e,complexTensorInfos:r}=this.data.get(t);if(e==="complex64"){let i=this.readSync(r.real.dataId),o=this.readSync(r.imag.dataId);return F.mergeRealAndImagArrays(i,o)}return this.data.get(t).values}bufferSync(t){let e=this.readSync(t.dataId),r=e;if(t.dtype==="string")try{r=e.map(i=>R.decodeString(i))}catch(i){throw new Error("Failed to decode encoded string bytes into utf-8")}return Xt(t.shape,t.dtype,r)}makeOutput(t,e,r){let i=this.write(t,e,r);return ro().makeTensorFromDataId(i,e,r,this)}disposeData(t,e=!1){if(this.data.has(t)){if(this.data.get(t).refCount--,!e&&this.data.get(t).refCount>0)return!1;let{complexTensorInfos:r}=this.data.get(t);r!=null&&(this.disposeData(r.real.dataId,!0),this.disposeData(r.imag.dataId,!0)),this.data.delete(t)}return!0}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}time(t){return Jt(this,null,function*(){let e=R.now();return t(),{kernelMs:R.now()-e}})}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(t){ut([t],"where");let e=this.readSync(t.dataId);return aj(t.shape,e)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};na.nextDataId=0;var D_={};So(D_,{addImpl:()=>x_,bincountImpl:()=>jl,bincountReduceImpl:()=>d1,ceilImpl:()=>v_,concatImpl:()=>f1,expImpl:()=>y_,expm1Impl:()=>__,floorImpl:()=>w_,gatherV2Impl:()=>m1,greaterImpl:()=>S_,lessImpl:()=>C_,linSpaceImpl:()=>g1,logImpl:()=>M_,maxImpl:()=>x1,maximumImpl:()=>E_,minimumImpl:()=>T_,multiplyImpl:()=>op,negImpl:()=>A_,notEqualImpl:()=>I_,prodImpl:()=>k_,rangeImpl:()=>v1,rsqrtImpl:()=>R_,simpleAbsImpl:()=>g_,sliceImpl:()=>P_,squaredDifferenceImpl:()=>N_,stridedSliceImpl:()=>y1,subImpl:()=>L_,tileImpl:()=>b1,topKImpl:()=>_1,transposeImpl:()=>ql,uniqueImpl:()=>w1});function g_(n){let t=new Float32Array(n.length);for(let e=0;e{let{x:t}=n.inputs,e=n.backend;ut(t,"abs");let r=new Float32Array(R.sizeFromShape(t.shape)),i=e.data.get(t.dataId).values;return r=g_(i),e.makeOutput(r,t.shape,"float32")},uI={kernelName:ym,backendName:"cpu",kernelFunc:lj};function le(n){return(t,e,r,i,o)=>{let s=F.assertAndGetBroadcastShape(t,e),a=s.length,l=R.computeStrides(s),c=R.sizeFromShape(s),u=R.getTypedArrayFromDType(o,c),h=t.length,p=e.length,d=R.computeStrides(t),f=R.computeStrides(e),m=F.getBroadcastDims(t,s),x=F.getBroadcastDims(e,s);if(m.length+x.length===0)for(let g=0;gb[E]=0);let y=R.locToIndex(b,h,d),_=v.slice(-p);x.forEach(E=>_[E]=0);let S=R.locToIndex(_,p,f);u[g]=n(r[y],i[S])}return[u,s]}}function sn(n){let{inputs:t,backend:e}=n,{real:r,imag:i}=t,o=e.data.get(r.dataId).values,s=e.data.get(i.dataId).values,a=e.makeTensorInfo(r.shape,"complex64"),l=e.data.get(a.dataId);return l.complexTensorInfos={real:e.makeTensorInfo(r.shape,"float32",o),imag:e.makeTensorInfo(i.shape,"float32",s)},a}var hI={kernelName:Il,backendName:"cpu",kernelFunc:sn};function Wl(n,t,e="float32"){if(e==="complex64"){let i=Wl(n,t,"float32"),o=Wl(n,t,"float32");return sn({inputs:{real:i,imag:o},backend:n})}let r=R.makeZerosTypedArray(R.sizeFromShape(t),e);return n.makeTensorInfo(t,e,r)}function Rn(n){let{inputs:t,backend:e}=n,{x:r}=t;return e.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var pI={kernelName:Do,backendName:"cpu",kernelFunc:Rn};function Pr(n){let{inputs:t,backend:e}=n,{input:r}=t,i=e.data.get(r.dataId).complexTensorInfos.real,o=e.data.get(i.dataId).values;return e.makeTensorInfo(i.shape,i.dtype,o)}var dI={kernelName:Tg,backendName:"cpu",kernelFunc:Pr};function Nr(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{dtype:o}=r;if(o==="complex64"){if(i.dtype==="complex64")return Rn({inputs:{x:i},backend:e});let s=Wl(e,i.shape,i.dtype),a=Nr({inputs:{x:i},backend:e,attrs:{dtype:"float32"}}),l=sn({inputs:{real:a,imag:s},backend:e});return e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(a),l}if(i.dtype==="complex64"){let s=Pr({inputs:{input:i},backend:e}),a=Nr({inputs:{x:s},backend:e,attrs:{dtype:o}});return e.disposeIntermediateTensorInfo(s),a}if(!R.hasEncodingLoss(i.dtype,o)){let s=Rn({inputs:{x:i},backend:e});return{dataId:s.dataId,shape:s.shape,dtype:o}}if(o==="int32"){let s=e.data.get(i.dataId).values,a=Int32Array.from(s);return e.makeTensorInfo(i.shape,"int32",a)}if(o==="bool"){let s=e.data.get(i.dataId).values,a=R.toTypedArray([0],i.dtype),[l,c]=le((u,h)=>u!==h?1:0)(i.shape,[],s,a,"bool");return e.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}var fI={kernelName:Lo,backendName:"cpu",kernelFunc:Nr};function fe(n,t,e,r){return e==null?({inputs:i,backend:o})=>{let{a:s,b:a}=i,l=o;ut([s,a],n);let c=l.data.get(s.dataId).values,u=l.data.get(a.dataId).values,h=r||s.dtype,[p,d]=t(s.shape,a.shape,c,u,h);return l.makeTensorInfo(d,h,p)}:({inputs:i,backend:o})=>{let{a:s,b:a}=i,l=o;if(s.dtype==="complex64"||a.dtype==="complex64"){let c=Nr({inputs:{x:s},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(c.dataId),h=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,d=l.data.get(h.dataId).values,f=l.data.get(p.dataId).values,m=Nr({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),x=l.data.get(m.dataId),g=x.complexTensorInfos.real,v=x.complexTensorInfos.imag,b=l.data.get(g.dataId).values,y=l.data.get(v.dataId).values,[_,S,E]=e(s.shape,a.shape,d,f,b,y),M=l.makeTensorInfo(E,"float32",_),P=l.makeTensorInfo(E,"float32",S),D=sn({inputs:{real:M,imag:P},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(M),l.disposeIntermediateTensorInfo(P),D}else{let c=l.data.get(s.dataId).values,u=l.data.get(a.dataId).values,h=r||s.dtype,[p,d]=t(s.shape,a.shape,c,u,h);return l.makeTensorInfo(d,h,p)}}}function Gl(n){return(t,e,r,i,o,s)=>{let a=F.assertAndGetBroadcastShape(t,e),l=R.sizeFromShape(a),c=a.length,u=R.computeStrides(a),h=R.getTypedArrayFromDType("float32",l),p=R.getTypedArrayFromDType("float32",l),d=F.getBroadcastDims(t,a),f=F.getBroadcastDims(e,a),m=F.mergeRealAndImagArrays(r,i),x=F.mergeRealAndImagArrays(o,s),g=t.length,v=R.computeStrides(t),b=e.length,y=R.computeStrides(e);if(d.length+f.length===0)for(let _=0;_E[I]=0);let M=R.locToIndex(E,g,v),P=S.slice(-b);f.forEach(I=>P[I]=0);let D=R.locToIndex(P,b,y),w=n(m[M*2],m[M*2+1],x[D*2],x[D*2+1]);h[_]=w.real,p[_]=w.imag}return[h,p,a]}}var x_=le((n,t)=>n+t),cj=Gl((n,t,e,r)=>({real:n+e,imag:t+r})),io=fe(Us,x_,cj),mI={kernelName:Us,backendName:"cpu",kernelFunc:io};function jl(n,t,e,r,i){let o=R.sizeFromShape(r),s=R.makeZerosTypedArray(i,e);for(let a=0;a=i||(o>0?s[l]+=t[a]:s[l]+=1)}return s}function d1(n,t,e,r=!1){let i=n.shape[0],o=n.shape[1],s=Xt([i,e],t.dtype);for(let a=0;a=e||(r?s.set(1,a,c):t.size>0?s.set(s.get(a,c)+t.get(a,l),a,c):s.set(s.get(a,c)+1,a,c))}return s}function Lr(n){return(t,e,r)=>{let i=R.getTypedArrayFromDType(e,t.length);for(let o=0;o{let{x:s}=r;if(ut(s,n),s.dtype==="string"||e==="string")throw new Error("unaryKernelFunc does not support string input/output");let a=o,l=a.data.get(s.dataId).values,c=R.sizeFromShape(s.shape),u=e||s.dtype,h=R.getArrayFromDType(u,c);for(let p=0;p{let{x:s}=r;if(ut(s,n),s.dtype==="string"||e==="string")throw new Error("unaryKernelFunc does not support string input/output");let a=o,l=a.data.get(s.dataId).values,c=e||s.dtype,u=t(l,c,i);return a.makeTensorInfo(s.shape,c,u)}}var v_=Lr(n=>Math.ceil(n)),uj=Dr(dh,v_),gI={kernelName:dh,backendName:"cpu",kernelFunc:uj};function f1(n,t,e,r){let i=R.getArrayFromDType(e,R.sizeFromShape(t));if(r&&e!=="string"){let o=0;n.forEach(s=>{let a=R.sizeFromShape(s.shape);i.set(s.vals,o),o+=a})}else{let o=0;n.forEach(s=>{let a=e==="string"?F.fromUint8ToStringArray(s.vals):s.vals,l=0;for(let c=0;cMath.exp(n)),b_=Dr(bh,y_),xI={kernelName:bh,backendName:"cpu",kernelFunc:b_};var __=Lr(n=>Math.expm1(n)),hj=Dr(_h,__),vI={kernelName:_h,backendName:"cpu",kernelFunc:hj};var w_=Lr(n=>Math.floor(n)),pj=Dr(wh,w_),yI={kernelName:wh,backendName:"cpu",kernelFunc:pj};function m1(n,t,e){let r=Xt(e,n.dtype);for(let i=0;in>t?1:0),dj=fe(Ch,S_,null,"bool"),bI={kernelName:Ch,backendName:"cpu",kernelFunc:dj};var C_=le((n,t)=>nMath.log(n)),mj=Dr(Rh,M_),wI={kernelName:Rh,backendName:"cpu",kernelFunc:mj};function x1(n,t,e,r){let i=R.getTypedArrayFromDType(r,R.sizeFromShape(e));for(let o=0;oa&&(a=c)}i[o]=a}return i}var E_=le((n,t)=>Math.max(n,t)),gj=fe(zh,E_),SI={kernelName:zh,backendName:"cpu",kernelFunc:gj};var T_=le((n,t)=>Math.min(n,t)),xj=fe(Fh,T_),CI={kernelName:Fh,backendName:"cpu",kernelFunc:xj};var op=le((n,t)=>n*t),vj=Gl((n,t,e,r)=>({real:n*e-t*r,imag:n*r+t*e})),ra=fe(Gs,op,vj),MI={kernelName:Gs,backendName:"cpu",kernelFunc:ra};function A_(n,t,e){let r=R.createScalarValue(-1,e);return op([],t,r,n,e)}function yj(n){let{inputs:t,backend:e}=n,{x:r}=t;ut(r,"neg");let i=e.data.get(r.dataId).values,[o,s]=A_(i,r.shape,r.dtype);return e.makeTensorInfo(s,r.dtype,o)}var EI={kernelName:vg,backendName:"cpu",kernelFunc:yj};var I_=le((n,t)=>n!==t?1:0),bj=fe(Bh,I_,null,"bool"),TI={kernelName:Bh,backendName:"cpu",kernelFunc:bj};function ql(n,t,e,r,i){let o=t.length,s=R.sizeFromShape(t),a=R.computeStrides(t),l=R.computeStrides(i),c=R.getTypedArrayFromDType(e,R.sizeFromShape(i));for(let u=0;ue.disposeIntermediateTensorInfo(v)),e.makeTensorInfo(g,x,f)}var II={kernelName:Mg,backendName:"cpu",kernelFunc:_j};function v1(n,t,e,r){let i=n===t,o=n1;if(i||o||s)return R.makeZerosTypedArray(0,r);let a=Math.abs(Math.ceil((t-n)/e)),l=R.makeZerosTypedArray(a,r);t1/Math.sqrt(n)),wj=Dr(Uh,R_),kI={kernelName:Uh,backendName:"cpu",kernelFunc:wj};function P_(n,t,e,r,i){let o=In.isSliceContinous(r,t,e),s=R.sizeFromShape(e),a=R.computeStrides(r);if(o){let h=In.computeFlatOffset(t,a);return i==="string"?n.slice(h,h+s):n.subarray(h,h+s)}let l=i==="string"?F.fromUint8ToStringArray(n):n,c=Xt(r,i,l),u=Xt(e,i);for(let h=0;hf+t[m]);u.set(c.get(...d),...p)}return i==="string"?F.fromStringArrayToUint8(u.values):u.values}function zr(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{begin:o,size:s}=r;ut(i,"slice");let[a,l]=In.parseSliceParams(i,o,s);In.assertParamsValid(i,a,l);let c=e.data.get(i.dataId).values,u=P_(c,a,l,i.shape,i.dtype);return e.makeTensorInfo(l,i.dtype,u)}var RI={kernelName:Dg,backendName:"cpu",kernelFunc:zr};var N_=le((n,t)=>{let e=n-t;return e*e}),Sj=fe(Zh,N_),PI={kernelName:Zh,backendName:"cpu",kernelFunc:Sj};function y1(n,t,e,r){let i=Xt(n,t.dtype);for(let o=0;on-t),Cj=Gl((n,t,e,r)=>({real:n-e,imag:t-r})),sp=fe(Xs,L_,Cj),NI={kernelName:Xs,backendName:"cpu",kernelFunc:sp};function b1(n,t){let e=new Array(n.rank);for(let i=0;ib.value-v.value);let m=h*r,x=l.subarray(m,m+r),g=c.subarray(m,m+r);for(let v=0;v{for(let x=0;xnew na,1);var z_=qt(Ws,n=>n>=0?n:Math.exp(n)-1),LI={kernelName:Ws,backendName:"cpu",kernelFunc:z_};function F_(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{alpha:o}=r;ut([i],"leakyRelu");let s=R.sizeFromShape(i.shape),a=e.data.get(i.dataId).values,l=R.getTypedArrayFromDType("float32",s);for(let c=0;cn<0?t*n:n);function O_(n){let{inputs:t,backend:e}=n,{x:r,alpha:i}=t;ut([r,i],"prelu");let o=e.data.get(r.dataId).values,s=e.data.get(i.dataId).values,[a,l]=Mj(r.shape,i.shape,o,s,r.dtype);return e.makeTensorInfo(l,r.dtype,a)}var zI={kernelName:Pl,backendName:"cpu",kernelFunc:O_};var B_=qt(js,n=>Math.max(0,n)),FI={kernelName:js,backendName:"cpu",kernelFunc:B_};var V_=qt(qs,n=>Math.min(Math.max(0,n),6)),OI={kernelName:qs,backendName:"cpu",kernelFunc:V_};function Xl(n,t,e,r,i){if(e==="linear")return Rn({inputs:{x:t},backend:n});if(e==="relu")return B_({inputs:{x:t},backend:n});if(e==="elu")return z_({inputs:{x:t},backend:n});if(e==="relu6")return V_({inputs:{x:t},backend:n});if(e==="prelu")return O_({inputs:{x:t,alpha:r},backend:n});if(e==="leakyrelu")return F_({inputs:{x:t},backend:n,attrs:{alpha:i}});throw new Error(`Activation ${e} has not been implemented for the CPU backend.`)}function ce(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{shape:o}=r,s=R.sizeFromShape(i.shape),a=R.inferFromImplicitShape(o,s),l=R.sizeFromShape(a);R.assert(s===l,()=>`The new shape (${a}) has ${l} elements and the old shape (${i.shape}) has ${s} elements. The new shape and old shape must have the same number of elements.`),e.incRef(i.dataId);let c=e.data.get(i.dataId);if(c.complexTensorInfos!=null){let u=c.complexTensorInfos.real,h=c.complexTensorInfos.imag;u.shape=a,h.shape=a}return{dataId:i.dataId,shape:a,dtype:i.dtype}}var BI={kernelName:Nl,backendName:"cpu",kernelFunc:ce};function H_(n){let{inputs:t,backend:e,attrs:r}=n,{a:i,b:o}=t,{transposeA:s,transposeB:a}=r;ut([i,o],"matMul");let l=i.shape.length,c=o.shape.length,u=s?i.shape[l-2]:i.shape[l-1],h=a?o.shape[c-1]:o.shape[c-2],p=s?i.shape[l-1]:i.shape[l-2],d=a?o.shape[c-2]:o.shape[c-1],f=i.shape.slice(0,-2),m=o.shape.slice(0,-2),x=R.sizeFromShape(f),g=R.sizeFromShape(m),v=x===g||x===1||g===1;R.assert(l>=2&&c>=2&&v,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${m}).`);let y=(x>g?i.shape.slice(0,-2):o.shape.slice(0,-2)).concat([p,d]);R.assert(u===h,()=>`Error in matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${i.shape} and ${o.shape} and transposeA=${s} and transposeB=${a} must match.`);let _=s?[x,u,p]:[x,p,u],S=a?[g,d,h]:[g,h,d],E=ce({inputs:{x:i},backend:e,attrs:{shape:_}}),M=ce({inputs:{x:o},backend:e,attrs:{shape:S}}),P=s?E.shape[1]:E.shape[2],D=s?E.shape[2]:E.shape[1],w=a?M.shape[1]:M.shape[2],I=Math.max(x,g),N=e.data.get(E.dataId).values,L=e.data.get(M.dataId).values,O=R.computeStrides(E.shape),z=R.computeStrides(M.shape),[V,$,X]=s?[O[0],1,O[1]]:[O[0],O[1],1],[W,K,Z]=a?[1,z[1],z[0]]:[z[1],1,z[0]],Y=D*w,tt=Xt([I,D,w],E.dtype),q=tt.values,et=e.blockSize;for(let rt=0;rtMath.acos(n)),$I={kernelName:sh,backendName:"cpu",kernelFunc:Tj};var Aj=qt(ah,n=>Math.acosh(n)),UI={kernelName:ah,backendName:"cpu",kernelFunc:Aj};function Ij(n){let{inputs:t,backend:e}=n,r=t;ut(t,"addN");let i=r.map(a=>e.data.get(a.dataId).values),o=Xt(r[0].shape,r[0].dtype),s=o.values;for(let a=0;av&&(v=_,b=y)}d[x]=b}return c.forEach(x=>e.disposeIntermediateTensorInfo(x)),e.makeTensorInfo(u,"int32",d)}var qI={kernelName:Sm,backendName:"cpu",kernelFunc:Pj};function Nj(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o}=r;ut(i,"argMin");let s=R.parseAxisParam(o,i.shape),a=F.getAxesPermutation(s,i.shape.length),l=i,c=[];a!=null&&(l=Ve({inputs:{x:i},backend:e,attrs:{perm:a}}),c.push(l),s=F.getInnerMostAxes(s.length,l.shape.length)),s=[s[0]],F.assertAxesAreInnerMostDims("argMin",s,l.shape.length);let[u,h]=F.computeOutAndReduceShapes(l.shape,s),p=R.sizeFromShape(u),d=R.makeZerosTypedArray(p,"int32"),f=R.sizeFromShape(h),m=e.data.get(l.dataId).values;for(let x=0;xe.disposeIntermediateTensorInfo(x)),e.makeTensorInfo(u,"int32",d)}var XI={kernelName:Cm,backendName:"cpu",kernelFunc:Nj};var Lj=qt(lh,n=>Math.asin(n)),KI={kernelName:lh,backendName:"cpu",kernelFunc:Lj};var Dj=qt(ch,n=>Math.asinh(n)),YI={kernelName:ch,backendName:"cpu",kernelFunc:Dj};var zj=qt(uh,n=>Math.atan(n)),ZI={kernelName:uh,backendName:"cpu",kernelFunc:zj};var Fj=le((n,t)=>Math.atan2(n,t)),Oj=fe(ph,Fj),JI={kernelName:ph,backendName:"cpu",kernelFunc:Oj};var Bj=qt(hh,n=>Math.atanh(n)),QI={kernelName:hh,backendName:"cpu",kernelFunc:Bj};function Kl(n,t,e,r,i,o){let s=i.strideHeight,a=i.strideWidth,l=i.dilationHeight,c=i.dilationWidth,u=i.effectiveFilterHeight,h=i.effectiveFilterWidth,p=i.padInfo.top,d=i.padInfo.left,f=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Xt(i.outShape,e),x=m.values,g=i.outShape[1]*i.outShape[2]*i.outShape[3],v=i.outShape[2]*i.outShape[3],b=i.outShape[3];for(let y=0;yV?V=q:o==="avg"&&($+=q,X++)}if(isNaN(V))break}let W=I+N*b+E;x[W]=o==="avg"?$/X:V}}}return m}function S1(n,t,e,r,i=!1,o=!1){let s=Xt(r.outShape,"int32"),a=r.strideHeight,l=r.strideWidth,c=r.dilationHeight,u=r.dilationWidth,h=r.effectiveFilterHeight,p=r.effectiveFilterWidth,d=r.padInfo.top,f=r.padInfo.left,m=Xt(t,e,n);for(let x=0;xD&&(D=z,i?w=o?((x*r.inHeight+I)*r.inWidth+L)*r.inChannels+g:(I*r.inWidth+L)*r.inChannels+g:w=N*p+O)}}s.set(w,x,v,S,g)}}return s}function C1(n,t,e,r,i,o){let s=i.strideDepth,a=i.strideHeight,l=i.strideWidth,c=i.dilationDepth,u=i.dilationHeight,h=i.dilationWidth,p=i.effectiveFilterDepth,d=i.effectiveFilterHeight,f=i.effectiveFilterWidth,m=i.padInfo.front,x=i.padInfo.top,g=i.padInfo.left,v=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,b=Xt(i.outShape,e),y=b.values,_=i.outShape[1]*i.outShape[2]*i.outShape[3]*i.outShape[4],S=i.outShape[2]*i.outShape[3]*i.outShape[4],E=i.outShape[3]*i.outShape[4],M=i.outShape[4];for(let P=0;Pat?at=Lt:o==="avg"&&(nt+=Lt,wt++),isNaN(at))break}if(isNaN(at))break}if(isNaN(at))break}let vt=rt+I;y[vt]=o==="avg"?nt/wt:at}}}}return b}function tk(n,t){let e=Xt(t.outShape,"int32"),r=t.strideDepth,i=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,a=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,u=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.front,d=t.padInfo.top,f=t.padInfo.left;for(let m=0;m=N&&(N=K,L=z*u*h+$*u+W)}}}e.set(L,m,g,_,P,x)}}}return e}function Vj(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t;ut(i,"avgPool");let{filterSize:o,strides:s,pad:a,dimRoundingMode:l}=r,c=1;R.assert(F.eitherStridesOrDilationsAreOne(s,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${c}'`);let u=F.computePool2DInfo(i.shape,o,s,c,a,l),h;if(u.filterWidth===1&&u.filterHeight===1&&R.arraysEqual(u.inShape,u.outShape))h=Rn({inputs:{x:i},backend:e});else{let p=e.data.get(i.dataId).values,d=R.computeStrides(i.shape),f=Kl(p,i.shape,i.dtype,d,u,"avg");h=e.makeTensorInfo(u.outShape,i.dtype,f.values)}return h}var ek={kernelName:Mm,backendName:"cpu",kernelFunc:Vj};function Hj(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{filterSize:o,strides:s,pad:a,dimRoundingMode:l,dataFormat:c}=r;ut(i,"avgPool3d");let u=F.computePool3DInfo(i.shape,o,s,1,a,l,c),h=e.data.get(i.dataId).values,p=C1(h,i.shape,i.dtype,R.computeStrides(i.shape),u,"avg");return e.makeTensorInfo(p.shape,"float32",p.values)}var nk={kernelName:Tm,backendName:"cpu",kernelFunc:Hj};function $j(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,input:o}=t,{filterSize:s,strides:a,pad:l,dimRoundingMode:c}=r;ut([i,o],"avgPool3DGrad");let u=F.computePool3DInfo(o.shape,s,a,1,l,c),h=u.strideDepth,p=u.strideHeight,d=u.strideWidth,f=u.filterDepth,m=u.filterHeight,x=u.filterWidth,g=u.dilationDepth,v=u.dilationHeight,b=u.dilationWidth,y=u.effectiveFilterDepth,_=u.effectiveFilterHeight,S=u.effectiveFilterWidth,E=y-1-u.padInfo.front,M=S-1-u.padInfo.left,P=_-1-u.padInfo.top,D=Xt(o.shape,"float32"),w=1/(f*m*x),I=e.bufferSync(i);for(let N=0;N=u.outDepth||Math.floor(Y)!==Y))for(let tt=0;tt<_;tt+=v){let q=(X+tt)/p;if(!(q<0||q>=u.outHeight||Math.floor(q)!==q))for(let et=0;et=u.outWidth||Math.floor(rt)!==rt)continue;K+=I.get(N,Y,q,rt,L)}}}D.set(K*w,N,O,z,V,L)}return e.makeTensorInfo(D.shape,D.dtype,D.values)}var rk={kernelName:Am,backendName:"cpu",kernelFunc:$j};function Uj(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,input:o}=t,s=o;ut([i,o],"avgPoolGrad");let{filterSize:a,strides:l,pad:c}=r,u=F.computePool2DInfo(s.shape,a,l,1,c),h=u.strideHeight,p=u.strideWidth,d=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,x=u.dilationWidth,g=u.effectiveFilterHeight,v=u.effectiveFilterWidth,b=v-1-u.padInfo.left,y=g-1-u.padInfo.top,_=Xt(s.shape,"float32"),S=1/(d*f),E=e.data.get(i.dataId).values,M=Xt(i.shape,"float32",E);for(let P=0;P=u.outHeight||Math.floor(V)!==V))for(let $=0;$=u.outWidth||Math.floor(X)!==X)continue;O+=M.get(P,V,X,D)}}_.set(O*S,P,w,I,D)}return e.makeTensorInfo(_.shape,_.dtype,_.values)}var ik={kernelName:Em,backendName:"cpu",kernelFunc:Uj};function Wj(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,scale:o,offset:s,mean:a,variance:l}=t;R.assert(a.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),R.assert(s==null||a.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),R.assert(o==null||a.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ut([i,a,l,o,s],"batchNorm");let{varianceEpsilon:c}=r;c==null&&(c=.001);let u=e.data.get(i.dataId).values,h=e.data.get(a.dataId).values,p=e.data.get(l.dataId).values,d=o?e.data.get(o.dataId).values:new Float32Array([1]),f=s?e.data.get(s.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),x=f.length,g=d.length,v=p.length,b=h.length,y=0,_=0,S=0,E=0;for(let M=0;M=x&&(y=0),_>=b&&(_=0),S>=g&&(S=0),E>=v&&(E=0);return e.makeTensorInfo(i.shape,i.dtype,m)}var ok={kernelName:tg,backendName:"cpu",kernelFunc:Wj};function Gj(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{blockShape:o,crops:s}=r;ut([i],"batchToSpaceND");let a=o.reduce((g,v)=>g*v),l=F.getReshaped(i.shape,o,a),c=F.getPermuted(l.length,o.length),u=F.getReshapedPermuted(i.shape,o,a),h=F.getSliceBeginCoords(s,o.length),p=F.getSliceSize(u,s,o.length),d=ce({inputs:{x:i},backend:e,attrs:{shape:l}}),f=Ve({inputs:{x:d},backend:e,attrs:{perm:c}}),m=ce({inputs:{x:f},backend:e,attrs:{shape:u}}),x=zr({inputs:{x:m},backend:e,attrs:{begin:h,size:p}});return e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),x}var sk={kernelName:Im,backendName:"cpu",kernelFunc:Gj};function jj(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,weights:o}=t,{size:s}=r,a=e.data.get(i.dataId).values,l=e.data.get(o.dataId).values,c=jl(a,l,o.dtype,o.shape,s);return e.makeTensorInfo([s],o.dtype,c)}var ak={kernelName:km,backendName:"cpu",kernelFunc:jj};var qj=qt(fh,(n,t)=>{let e=t;return n>e.clipValueMax?e.clipValueMax:n{let{x:t}=n.inputs,e=n.backend,r=new Float32Array(R.sizeFromShape(t.shape)),i=e.data.get(t.dataId),o=i.complexTensorInfos.real,s=i.complexTensorInfos.imag,a=e.data.get(o.dataId).values,l=e.data.get(s.dataId).values;for(let c=0;cm.shape),o);if(R.sizeFromShape(s)===0)return e.makeTensorInfo(s,t[0].dtype,[]);let a=t.filter(m=>R.sizeFromShape(m.shape)>0);if(a.length===1)return Rn({inputs:{x:a[0]},backend:e});let l=a.map(m=>m.shape);if(F.assertParamsConsistent(l,o),a[0].dtype==="complex64"){let m=a.map(y=>Pr({inputs:{input:y},backend:e})),x=a.map(y=>Mi({inputs:{input:y},backend:e})),g=Bo({inputs:m,backend:e,attrs:{axis:o}}),v=Bo({inputs:x,backend:e,attrs:{axis:o}}),b=sn({inputs:{real:g,imag:v},backend:e});return m.forEach(y=>e.disposeIntermediateTensorInfo(y)),x.forEach(y=>e.disposeIntermediateTensorInfo(y)),e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(v),b}let c=a.map(m=>{let x=R.sizeFromShape(m.shape.slice(o));return ce({inputs:{x:m},backend:e,attrs:{shape:[-1,x]}})}),u=c.map(m=>({vals:e.data.get(m.dataId).values,shape:m.shape}));s=F.computeOutShape(c.map(m=>m.shape),1);let h=c[0].shape[0]===1,p=f1(u,s,t[0].dtype,h),d=F.computeOutShape(a.map(m=>m.shape),o),f=e.makeTensorInfo(d,t[0].dtype,p);return c.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}var hk={kernelName:Pm,backendName:"cpu",kernelFunc:Bo};function $_(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,filter:o}=t,{strides:s,pad:a,dataFormat:l,dilations:c,dimRoundingMode:u}=r;ut([i,o],"conv2d");let h=F.convertConv2DDataFormat(l),p=F.computeConv2DInfo(i.shape,o.shape,s,c,a,u,!1,h),d=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,x=p.dilationWidth,g=p.padInfo.left,v=p.padInfo.top,b=p.dataFormat==="channelsLast",y=new Ce(p.outShape,i.dtype),_=R.computeStrides(i.shape),S=R.computeStrides(o.shape),E=_[0],M=b?_[1]:_[2],P=b?_[2]:1,D=b?1:_[1],w=y.strides[0],I=b?y.strides[1]:y.strides[2],N=b?y.strides[2]:1,L=b?1:y.strides[1],O=e.data.get(i.dataId).values,z=e.data.get(o.dataId).values,V=y.values;for(let $=0;$=p.inHeight)continue;let et=tt*S[0],rt=X+q*M;for(let at=0;at=p.inWidth)continue;let yt=et+vt*S[1],ct=rt+it*P,bt=yt;for(let gt=0;gt=c.inDepth)continue;let $=z*P[0],X=w+V*M[1];for(let W=0;W=c.inHeight)continue;let q=$+Y*P[1],et=X+tt*M[2];for(let rt=0;rt=c.inWidth)continue;let it=q+wt*P[2],yt=et+vt*c.inChannels,ct=it;for(let bt=0;btMath.cos(n)),vk={kernelName:mh,backendName:"cpu",kernelFunc:tq};var eq=qt(gh,n=>Math.cosh(n)),yk={kernelName:gh,backendName:"cpu",kernelFunc:eq};function nq(n){let{inputs:t,backend:e,attrs:r}=n,{image:i,boxes:o,boxInd:s}=t,{cropSize:a,method:l,extrapolationValue:c}=r,[u,h,p,d]=i.shape,f=o.shape[0],[m,x]=a,g=Xt([f,m,x,d],"float32"),v=e.data.get(o.dataId).values,b=e.data.get(s.dataId).values,y=e.data.get(i.dataId).values,_=R.computeStrides(i.shape),S=R.computeStrides(g.shape);for(let E=0;E=u)continue;let L=m>1?(w-P)*(h-1)/(m-1):0,O=x>1?(I-D)*(p-1)/(x-1):0;for(let z=0;z1?P*(h-1)+z*L:.5*(P+w)*(h-1);if(V<0||V>h-1){for(let $=0;$1?D*(p-1)+K*O:.5*(D+I)*(p-1);if(Z<0||Z>p-1){for(let et=0;et1?D*(p-1)+$*O:.5*(D+I)*(p-1);if(X<0||X>p-1){for(let Z=0;Zg+f-v-1:(g,v)=>g+v;for(let g=0;g`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${s}`),R.assert(o>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${o}`);let a=i.shape[0],l=i.shape[1],c=i.shape[2],u=i.shape[3],h=l*o,p=c*o,d=u/(o*o),f=e.data.get(i.dataId).values,m=new Float32Array(a*h*p*d),x=0;for(let g=0;g`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${p}'`);let d=F.computeConv2DInfo(i.shape,o.shape,s,p,a,c,!0),{filterHeight:f,filterWidth:m,dilationHeight:x,dilationWidth:g,padInfo:v}=d,b=v.left,y=v.top,_=d.outChannels/d.inChannels,S=new Ce(d.outShape,i.dtype),E=e.data.get(i.dataId).values,M=e.data.get(o.dataId).values,P=S.values;for(let D=0;D=d.inHeight)continue;let $=z*h[0],X=w+V*u[1];for(let W=0;W=d.inWidth)continue;let q=$+Y*h[1],et=X+tt*d.inChannels,rt=K,at=q;for(let nt=0;nt{let{x:r,filter:i}=n,{strides:o,pad:s,dilations:a}=e,l=t,c=l.data.get(r.dataId).values,u=r.shape.length,h=l.data.get(i.dataId).values,p=i.shape.length,{batchSize:d,inHeight:f,inWidth:m,inChannels:x,outHeight:g,outWidth:v,padInfo:b,strideHeight:y,strideWidth:_,filterHeight:S,filterWidth:E,dilationHeight:M,dilationWidth:P,outShape:D}=F.computeDilation2DInfo(r.shape,i.shape,o,s,"NHWC",a),w=R.sizeFromShape(D),I=D.length,N=R.getArrayFromDType(r.dtype,w);for(let O=0;O=0&&tt=0&&etK&&(K=nt)}}}let Z=R.locToIndex([O,z,$,W],I,R.computeStrides(D));N[Z]=K}}}return{dataId:l.write(R.toTypedArray(N,r.dtype),D,r.dtype),shape:D,dtype:r.dtype}}};var Ik={kernelName:Mb,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{let{x:r,filter:i,dy:o}=n,{strides:s,pad:a,dilations:l}=e,c=t,u=R.toNestedArray(r.shape,c.data.get(r.dataId).values),h=R.toNestedArray(i.shape,c.data.get(i.dataId).values),{batchSize:p,inHeight:d,inWidth:f,inChannels:m,outHeight:x,outWidth:g,padInfo:v,strideHeight:b,strideWidth:y,filterHeight:_,filterWidth:S,dilationHeight:E,dilationWidth:M,outShape:P}=F.computeDilation2DInfo(r.shape,i.shape,s,a,"NHWC",l);R.assert(o.rank===P.length,()=>`Error in ${Mb}, dy must have the same rank as output ${P.length}, but got ${o.rank}`);let D=R.toNestedArray(P,c.data.get(o.dataId).values),w=R.makeZerosNestedTypedArray(i.shape,i.dtype);for(let N=0;N=0&&Y=0&&qX&&(X=et,W=Z,K=tt)}}}w[W][K][$]+=D[N][L][z][$]}}}return{dataId:c.write(R.toTypedArray(w,r.dtype),i.shape,i.dtype),shape:i.shape,dtype:i.dtype}}};var kk={kernelName:Cb,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{let{x:r,filter:i,dy:o}=n,{strides:s,pad:a,dilations:l}=e,c=t,u=R.toNestedArray(r.shape,c.data.get(r.dataId).values),h=R.toNestedArray(i.shape,c.data.get(i.dataId).values),{batchSize:p,inHeight:d,inWidth:f,inChannels:m,outHeight:x,outWidth:g,padInfo:v,strideHeight:b,strideWidth:y,filterHeight:_,filterWidth:S,dilationHeight:E,dilationWidth:M,outShape:P}=F.computeDilation2DInfo(r.shape,i.shape,s,a,"NHWC",l);R.assert(o.rank===P.length,()=>`Error in ${Cb}, dy must have the same rank as output ${P.length}, but got ${o.rank}`);let D=R.toNestedArray(P,c.data.get(o.dataId).values),w=R.makeZerosNestedTypedArray(r.shape,r.dtype);for(let N=0;N=0&&Y=0&&qX&&(X=et,W=Y,K=q)}}}w[N][W][K][$]+=D[N][L][z][$]}}}return{dataId:c.write(R.toTypedArray(w,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};function oo(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o,keepDims:s}=r;ut(i,"sum");let a;i.dtype==="bool"?a=Nr({inputs:{x:i},backend:e,attrs:{dtype:"int32"}}):a=Rn({inputs:{x:i},backend:e});let l=a.shape.length,c=R.parseAxisParam(o,a.shape),u=F.getAxesPermutation(c,l),h=c,p=a;u!=null&&(p=Ve({inputs:{x:a},backend:e,attrs:{perm:u}}),h=F.getInnerMostAxes(h.length,l)),F.assertAxesAreInnerMostDims("sum",h,p.shape.length);let[d,f]=F.computeOutAndReduceShapes(p.shape,h),m=F.upcastType(p.dtype,"int32"),x=Wl(e,d,m),g=R.sizeFromShape(f),v=e.data.get(x.dataId).values,b=e.data.get(p.dataId).values;for(let y=0;y=0&&(p=oo({inputs:{x:p},backend:e,attrs:{axis:c[m]-(s.length-d),keepDims:!1}}),f.push(p)),d--)}for(let m of f)m!==p&&e.disposeIntermediateTensorInfo(m);return p}var Pk={kernelName:Xm,backendName:"cpu",kernelFunc:cq};function uq(n){let{inputs:t,backend:e}=n,{dy:r,y:i}=t;ut([r,i],"eluGrad");let o=new Float32Array(R.sizeFromShape(i.shape)),s=e.data.get(i.dataId).values,a=e.data.get(r.dataId).values;for(let l=0;l=1?o[l]=a[l]:o[l]=a[l]*(c+1)}return e.makeTensorInfo(i.shape,"float32",o)}var Nk={kernelName:Km,backendName:"cpu",kernelFunc:uq};var hq=le((n,t)=>n===t?1:0),W_=fe(yh,hq,null,"bool"),Lk={kernelName:yh,backendName:"cpu",kernelFunc:W_};var pq=F.ERF_P,dq=F.ERF_A1,fq=F.ERF_A2,mq=F.ERF_A3,gq=F.ERF_A4,xq=F.ERF_A5,vq=qt(vh,n=>{let t=Math.sign(n),e=Math.abs(n),r=1/(1+pq*e);return t*(1-((((xq*r+gq)*r+mq)*r+fq)*r+dq)*r*Math.exp(-e*e))}),Dk={kernelName:vh,backendName:"cpu",kernelFunc:vq};function Yl(n){let{inputs:t,backend:e,attrs:r}=n,{input:i}=t,{dim:o}=r,s=i.shape.length,a=i.shape.slice(),l=o;return o<0&&(R.assert(-(s+1)<=o,()=>`Axis must be in the interval [${-(s+1)}, ${s}]`),l=s+o+1),a.splice(l,0,1),ce({inputs:{x:i},backend:e,attrs:{shape:a}})}var zk={kernelName:Ym,backendName:"cpu",kernelFunc:Yl};var yq=le((n,t)=>n/t),ap=fe(xh,yq),lp={kernelName:xh,backendName:"cpu",kernelFunc:ap};function M1(n,t,e){let r=n.shape,i=r[0],o=r[1],s=e.data.get(n.dataId),a=s.complexTensorInfos.real,l=s.complexTensorInfos.imag,c=[i,o],u=R.sizeFromShape(c),h=R.getTypedArrayFromDType("float32",u),p=R.getTypedArrayFromDType("float32",u);for(let x=0;x{let{image:r}=n,i=e,o=R.getTypedArrayFromDType(r.dtype,R.sizeFromShape(r.shape)),[s,a,l,c]=r.shape,u=i.data.get(r.dataId).values;for(let p=0;p=0&&_Math.floor(n/t)),Eq=fe(Sh,Mq,null,"int32"),Vk={kernelName:Sh,backendName:"cpu",kernelFunc:Eq};function Tq(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,filter:o,bias:s,preluActivationWeights:a}=t,{strides:l,pad:c,dataFormat:u,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r,m=$_({inputs:{x:i,filter:o},backend:e,attrs:{strides:l,pad:c,dataFormat:u,dilations:h,dimRoundingMode:p}});if(s){let x=m;m=io({inputs:{a:m,b:s},backend:e}),e.disposeIntermediateTensorInfo(x)}if(d){let x=m;m=Xl(e,m,d,a,f),e.disposeIntermediateTensorInfo(x)}return m}var Hk={kernelName:Yg,backendName:"cpu",kernelFunc:Tq};function Aq(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,filter:o,bias:s,preluActivationWeights:a}=t,{strides:l,pad:c,dataFormat:u,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r,m=U_({inputs:{x:i,filter:o},backend:e,attrs:{strides:l,pad:c,dataFormat:u,dilations:h,dimRoundingMode:p}});if(s){let x=m;m=io({inputs:{a:m,b:s},backend:e}),e.disposeIntermediateTensorInfo(x)}if(d){let x=m;m=Xl(e,m,d,a,f),e.disposeIntermediateTensorInfo(x)}return m}var $k={kernelName:Zg,backendName:"cpu",kernelFunc:Aq};function Iq(n){let{inputs:t,backend:e}=n,{params:r,indices:i}=t,o=R.sizeFromShape(r.shape),s=i.shape,a=s[s.length-1],[l,c,u,h]=F.prepareAndValidate(r,i);if(c===0)return e.makeTensorInfo(l,r.dtype,[]);let p=Xt([c,u],r.dtype),d=e.data.get(i.dataId).values,f=e.data.get(r.dataId).values;for(let m=0;m=o/u)throw new Error(`Invalid indices: ${x} does not index into ${r.shape}`);for(let v=0;vn>=t?1:0),Pq=fe(Mh,Rq,null,"bool"),Gk={kernelName:Mh,backendName:"cpu",kernelFunc:Pq};function Nq(n){let{inputs:t,backend:e}=n,{input:r}=t,i=R.sizeFromShape(r.shape),o=r.shape[r.shape.length-1],s=i/o,a=ce({inputs:{x:r},backend:e,attrs:{shape:[s,o]}}),l=M1(a,!0,e),c=ce({inputs:{x:l},backend:e,attrs:{shape:r.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(l),c}var jk={kernelName:rg,backendName:"cpu",kernelFunc:Nq};var Lq=qt(Eh,n=>Number.isFinite(n)?1:0,"bool"),qk={kernelName:Eh,backendName:"cpu",kernelFunc:Lq};var Dq=qt(Th,n=>Math.abs(n)===1/0?1:0,"bool"),Xk={kernelName:Th,backendName:"cpu",kernelFunc:Dq};var zq=qt(Ah,n=>Number.isNaN(n)?1:0,"bool"),Kk={kernelName:Ah,backendName:"cpu",kernelFunc:zq};var Fq=le((n,t)=>n<=t?1:0),Oq=fe(kh,Fq,null,"bool"),Yk={kernelName:kh,backendName:"cpu",kernelFunc:Oq};function Bq(n){let{backend:t,attrs:e}=n,{start:r,stop:i,num:o}=e,s=g1(r,i,o);return t.makeTensorInfo([s.length],"float32",s)}var Zk={kernelName:og,backendName:"cpu",kernelFunc:Bq};var Vq=qt(Ph,n=>Math.log1p(n)),Jk={kernelName:Ph,backendName:"cpu",kernelFunc:Vq};var Hq=le((n,t)=>n&&t),$q=fe(Nh,Hq,null,"bool"),Qk={kernelName:Nh,backendName:"cpu",kernelFunc:$q};var Uq=qt(Lh,n=>n?0:1,"bool"),tR={kernelName:Lh,backendName:"cpu",kernelFunc:Uq};var Wq=le((n,t)=>n||t),Gq=fe(Dh,Wq,null,"bool"),eR={kernelName:Dh,backendName:"cpu",kernelFunc:Gq};function jq(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{depthRadius:o,bias:s,alpha:a,beta:l}=r;ut(i,"LRN");let c=i.shape[3],u=c-1,h=e.data.get(i.dataId).values,p=R.sizeFromShape(i.shape),d=new Float32Array(p);function f(m){let x=m%c,g=m-x+Math.max(0,x-o),v=m-x+Math.min(x+o,u),b=0;for(;g<=v;g++){let y=h[g];b+=y*y}return b}for(let m=0;m`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${c}'`);let u=F.computePool2DInfo(i.shape,o,s,c,a,l),h;if(u.filterWidth===1&&u.filterHeight===1&&R.arraysEqual(u.inShape,u.outShape))h=Rn({inputs:{x:i},backend:e});else{let p=e.data.get(i.dataId).values,d=R.computeStrides(i.shape),f=Kl(p,i.shape,i.dtype,d,u,"max");h=e.makeTensorInfo(u.outShape,i.dtype,f.values)}return h}var oR={kernelName:cg,backendName:"cpu",kernelFunc:Xq};function Kq(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{filterSize:o,strides:s,pad:a,dimRoundingMode:l,dataFormat:c}=r;ut(i,"maxPool3d");let u=F.computePool3DInfo(i.shape,o,s,1,a,l,c),h=e.data.get(i.dataId).values,p=C1(h,i.shape,i.dtype,R.computeStrides(i.shape),u,"max");return e.makeTensorInfo(p.shape,"float32",p.values)}var sR={kernelName:hg,backendName:"cpu",kernelFunc:Kq};function Yq(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,input:o}=t,{filterSize:s,strides:a,pad:l,dimRoundingMode:c}=r;ut([i,o],"maxPool3DGrad");let u=F.computePool3DInfo(o.shape,s,a,1,l,c),h=e.bufferSync(o),p=tk(h,u),d=u.strideDepth,f=u.strideHeight,m=u.strideWidth,x=u.dilationDepth,g=u.dilationHeight,v=u.dilationWidth,b=u.effectiveFilterDepth,y=u.effectiveFilterHeight,_=u.effectiveFilterWidth,S=b-1-u.padInfo.front,E=_-1-u.padInfo.left,M=y-1-u.padInfo.top,P=Xt(o.shape,"float32"),D=e.bufferSync(i);for(let w=0;w=u.outDepth||Math.floor(K)!==K))for(let Z=0;Z=u.outHeight||Math.floor(Y)!==Y))for(let tt=0;tt<_;tt+=v){let q=($+tt)/m;if(q<0||q>=u.outWidth||Math.floor(q)!==q)continue;let et=b*y*_-1-p.get(w,K,Y,q,I),rt=W*y*_+Z*_+tt,at=et===rt?1:0;if(at===0)continue;X+=D.get(w,K,Y,q,I)*at}}}P.set(X,w,N,L,O,I)}return e.makeTensorInfo(P.shape,P.dtype,P.values)}var aR={kernelName:pg,backendName:"cpu",kernelFunc:Yq};function Zq(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,input:o,output:s}=t,a=o;ut([o,s],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:h}=r,p=F.computePool2DInfo(a.shape,l,c,1,u,h),d=e.data.get(a.dataId).values,f=Xt(p.outShape,a.dtype,S1(d,a.shape,a.dtype,p).values),m=p.strideHeight,x=p.strideWidth,g=p.dilationHeight,v=p.dilationWidth,b=p.effectiveFilterHeight,y=p.effectiveFilterWidth,_=y-1-p.padInfo.left,S=b-1-p.padInfo.top,E=Xt(a.shape,"float32"),M=e.data.get(i.dataId).values,P=Xt(i.shape,"float32",M);for(let D=0;D=p.outHeight||Math.floor($)!==$))for(let X=0;X=p.outWidth||Math.floor(W)!==W)continue;let K=b*y-1-f.get(D,$,W,w),Z=V*y+X,Y=K===Z?1:0;if(Y===0)continue;z+=P.get(D,$,W,w)*Y}}E.set(z,D,I,N,w)}return e.makeTensorInfo(E.shape,E.dtype,E.values)}var lR={kernelName:ug,backendName:"cpu",kernelFunc:Zq};function cR(n,t,e,r,i){let o=R.computeStrides(t),s=Kl(n,t,e,o,i,"max"),a=S1(n,t,e,i,!0,r);return[s.values,a.values]}var uR={kernelName:dg,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{x:r}=n,{filterSize:i,strides:o,pad:s,includeBatchInIndex:a}=t,l=e;ut(r,"MaxPoolWithArgmax");let c=l.data.get(r.dataId).values,u=F.computePool2DInfo(r.shape,i,o,[1,1],s),[h,p]=cR(c,r.shape,r.dtype,a,u),d=l.write(h,u.outShape,r.dtype),f=l.write(p,u.outShape,r.dtype);return[{dataId:d,shape:u.outShape,dtype:r.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};function Jq(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o,keepDims:s}=r,a=R.parseAxisParam(o,i.shape),c=F.computeOutAndReduceShapes(i.shape,a)[1],u=R.sizeFromShape(c),h=[],p=e.makeTensorInfo([],"float32",new Float32Array([u]));h.push(p);let d=Nr({inputs:{x:i},backend:e,attrs:{dtype:"float32"}});h.push(d);let f=ap({inputs:{a:d,b:p},backend:e});h.push(f);let m=oo({inputs:{x:f},backend:e,attrs:{axis:o,keepDims:s}});return h.forEach(x=>e.disposeIntermediateTensorInfo(x)),m}var hR={kernelName:fg,backendName:"cpu",kernelFunc:Jq};function Qq(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o,keepDims:s}=r;ut(i,"min");let a=R.parseAxisParam(o,i.shape),l=a,c=F.getAxesPermutation(l,i.shape.length),u=i;c!=null&&(u=Ve({inputs:{x:i},backend:e,attrs:{perm:c}}),l=F.getInnerMostAxes(l.length,i.shape.length)),F.assertAxesAreInnerMostDims("min",l,u.shape.length);let[h,p]=F.computeOutAndReduceShapes(u.shape,l),d=R.sizeFromShape(p),f=R.makeZerosTypedArray(R.sizeFromShape(h),u.dtype),m=e.data.get(u.dataId).values;for(let g=0;gb[0]+i.shape[y]+b[1]),l=o.map(b=>b[0]),c=o.map((b,y)=>b[0]+i.shape[y]),u=s==="reflect"?0:1,h=e.data.get(i.dataId).values,p=i.shape.length,d=R.computeStrides(i.shape),f=R.sizeFromShape(a),m=a.length,x=R.computeStrides(a),g=R.getTypedArrayFromDType(i.dtype,f);for(let b=0;b=c[S]&&(y[S]=(c[S]-1)*2-y[S]+u);y=y.map((S,E)=>S-l[E]);let _=R.locToIndex(y,p,d);g[b]=h[_]}return{dataId:e.write(g,a,i.dtype),shape:a,dtype:i.dtype}}var dR={kernelName:gg,backendName:"cpu",kernelFunc:tX};var eX=le((n,t)=>{let e=n%t;return n<0&&t<0||n>=0&&t>=0?e:(e+t)%t}),nX=fe(Oh,eX),fR={kernelName:Oh,backendName:"cpu",kernelFunc:nX};var gR=Jd(JA());function q_(n){let{inputs:t,backend:e,attrs:r}=n,{logits:i}=t,{dim:o}=r,s=i.shape.length,a=o;if(a===-1&&(a=s-1),a!==s-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${s} and dim was ${a}`);let l=R.parseAxisParam([a],i.shape),c=j_({inputs:{x:i},backend:e,attrs:{reductionIndices:l,keepDims:!1}}),u=F.expandShapeToKeepDim(c.shape,l),h=ce({inputs:{x:c},backend:e,attrs:{shape:u}}),p=sp({inputs:{a:i,b:h},backend:e}),d=b_({inputs:{x:p},backend:e}),f=oo({inputs:{x:d},backend:e,attrs:{axis:l,keepDims:!1}}),m=ce({inputs:{x:f},backend:e,attrs:{shape:u}}),x=ap({inputs:{a:d,b:m},backend:e});return e.disposeIntermediateTensorInfo(c),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),x}var mR={kernelName:Fg,backendName:"cpu",kernelFunc:q_};function rX(n){let{inputs:t,backend:e,attrs:r}=n,{logits:i}=t,{numSamples:o,seed:s,normalized:a}=r;ut(i,"multinomial");let l=a?i:q_({inputs:{logits:i},backend:e,attrs:{dim:-1}}),c=l.shape[0],u=l.shape[1],h=e.data.get(l.dataId).values,p=[c,o],d=R.makeZerosTypedArray(R.sizeFromShape(p),"int32");for(let f=0;f=0&&u[h]{R.assertShapesMatch(o,u.shape,"All tensors passed to stack must have matching shapes"),R.assert(s===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],l=t.map(u=>{let h=Yl({inputs:{input:u},backend:e,attrs:{dim:i}});return a.push(h),h}),c=Bo({inputs:l,backend:e,attrs:{axis:i}});return a.forEach(u=>e.disposeIntermediateTensorInfo(u)),c}var MR={kernelName:Cg,backendName:"cpu",kernelFunc:X_};function hX(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{paddings:o,constantValue:s}=r;ut(i,"pad");let a=o.map((v,b)=>v[0]+i.shape[b]+v[1]),l=o.map(v=>v[0]),c=e.data.get(i.dataId).values,u=R.sizeFromShape(i.shape),h=i.shape.length,p=R.computeStrides(i.shape),d=R.sizeFromShape(a),f=a.length,m=R.computeStrides(a),x=R.getTypedArrayFromDType(i.dtype,d);s!==0&&x.fill(s);for(let v=0;vS+l[E]),_=R.locToIndex(y,f,m);x[_]=c[v]}return{dataId:e.write(x,a,i.dtype),shape:a,dtype:i.dtype}}var E1={kernelName:Rl,backendName:"cpu",kernelFunc:hX};var pX=le((n,t)=>Math.pow(n,t)),dX=fe(Vh,pX),ER={kernelName:Vh,backendName:"cpu",kernelFunc:dX};function fX(n){let{backend:t,attrs:e}=n,{start:r,stop:i,dtype:o,step:s}=e,a=v1(r,i,s,o);return t.makeTensorInfo([a.length],o,a)}var TR={kernelName:Eg,backendName:"cpu",kernelFunc:fX};var mX=qt(Hh,n=>1/n),AR={kernelName:Hh,backendName:"cpu",kernelFunc:mX};function gX(n){let{inputs:t,backend:e,attrs:r}=n,{images:i}=t,{alignCorners:o,halfPixelCenters:s,size:a}=r;ut(i,"resizeBilinear");let l=R.computeStrides(i.shape),[c,u]=a,[h,p,d,f]=i.shape,m=e.data.get(i.dataId).values,x=new Float32Array(R.sizeFromShape([h,c,u,f])),g=[o&&c>1?p-1:p,o&&u>1?d-1:d],v=[o&&c>1?c-1:c,o&&u>1?u-1:u],b=0,y=g[0]/v[0],_=g[1]/v[1];for(let S=0;S1?c-1:c,s&&d>1?u-1:u],x=[s&&p>1?p-1:p,s&&d>1?d-1:d],g=m[0]/x[0],v=m[1]/x[1],b=e.data.get(o.dataId).values,y=0;for(let _=0;_1?p-1:p,o&&u>1?d-1:d],v=[o&&c>1?c-1:c,o&&u>1?u-1:u],b=g[0]/v[0],y=g[1]/v[1],_=0;for(let S=0;S1?u-1:u,s&&f>1?h-1:h],v=[s&&d>1?d-1:d,s&&f>1?f-1:f],b=g[0]/v[0],y=g[1]/v[1],_=1/b,S=1/y,E=Math.ceil(_)*2+2,M=Math.ceil(S)*2+2;for(let P=0;P=d)continue;let Y=D+Z*l[1],tt=Z*b,q=Math.min(u-1,s?Math.round(tt):Math.floor(tt));if(w===q)for(let et=0;et=f)continue;let at=Y+rt*l[2],nt=rt*y,wt=Math.min(h-1,s?Math.round(nt):Math.floor(nt));O===wt&&(W+=x[at+X])}}m[z+X]=W}}}}return e.makeTensorInfo(i.shape,i.dtype,m)}var PR={kernelName:Ig,backendName:"cpu",kernelFunc:yX};function bX(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{dims:o}=r;ut(i,"reverse");let s=i.shape.length,a=R.parseAxisParam(o,i.shape);if(s===0)return Rn({inputs:{x:i},backend:e});let l=new Ce(i.shape,i.dtype),c=e.bufferSync(i);for(let u=0;up[d]=i.shape[d]-1-p[d]),l.set(c.get(...p),...h)}return e.makeTensorInfo(l.shape,l.dtype,l.values)}var NR={kernelName:Pg,backendName:"cpu",kernelFunc:bX};var LR={kernelName:Xg,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{image:r}=n,{radians:i,fillValue:o,center:s}=t,a=e,l=R.getTypedArrayFromDType(r.dtype,R.sizeFromShape(r.shape)),[c,u,h,p]=r.shape,[d,f]=F.getImageCenter(s,u,h),m=255,x=Math.sin(i),g=Math.cos(i),v=a.data.get(r.dataId).values;for(let y=0;y=0&&L=0&&O{let t=Math.floor(n);return n-t<.5?Math.floor(n):n-t>.5?Math.ceil(n):t%2===0?t:t+1}),DR={kernelName:$h,backendName:"cpu",kernelFunc:_X};function T1(n,t,e,r,i,o,s,a,l,c){let u=[r/i,i],h=n.values,p=t.values;if(r===0)return Xt(e,t.dtype);let d=Xt(u,t.dtype);d.values.fill(l);for(let f=0;f=r/i)throw new Error(`Invalid indices: ${m} does not index into ${e}`);for(let g=0;g1||i.shape.length===1?1:R.sizeFromShape(i.shape.slice(1));for(let f=0;fn>=0?MX*n:CX*(Math.exp(n)-1)),OR={kernelName:Wh,backendName:"cpu",kernelFunc:EX};var TX=qt(Xh,n=>1/(1+Math.exp(-n))),BR={kernelName:Xh,backendName:"cpu",kernelFunc:TX};var AX=qt(qh,n=>n<0?-1:n>0?1:0),VR={kernelName:qh,backendName:"cpu",kernelFunc:AX};var IX=qt(Gh,n=>Math.sin(n)),HR={kernelName:Gh,backendName:"cpu",kernelFunc:IX};var kX=qt(jh,n=>Math.sinh(n)),$R={kernelName:jh,backendName:"cpu",kernelFunc:kX};var RX=11920928955078125e-23,UR=Math.log(RX)+2,PX=qt(Kh,n=>{let t=n>-UR,e=n{let p=[...u];p[a]=h;let d=zr({inputs:{x:i},backend:e,attrs:{begin:c,size:p}});return c[a]+=h,d})}var qR={kernelName:Dl,backendName:"cpu",kernelFunc:DX};var zX=qt(Yh,n=>Math.sqrt(n)),XR={kernelName:Yh,backendName:"cpu",kernelFunc:zX};var KR={kernelName:Og,backendName:"cpu",kernelFunc:({inputs:n,backend:t})=>{let{x:e}=n,r=t;ut(e,"square");let i=r.data.get(e.dataId).values,o=new Float32Array(i.length);for(let a=0;a{let e=t;return isNaN(n)?NaN:n>0?1:e.alpha}),YR={kernelName:Ks,backendName:"cpu",kernelFunc:FX};function OX(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{begin:o,end:s,strides:a,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:h,shrinkAxisMask:p}=r;ut(i,"stridedSlice");let{nonStrided:d,$begin:f,$strides:m,size:x,newShape:g,outShape:v}=In.sliceInfo(i.shape,o,s,a,l,c,u,h,p),b=ce({inputs:{x:i},backend:e,attrs:{shape:g}}),y;if(d){let S=zr({inputs:{x:b},backend:e,attrs:{begin:f,size:x}});y=ce({inputs:{x:S},backend:e,attrs:{shape:v}}),e.disposeIntermediateTensorInfo(S)}else if(v.some(S=>S===0))y=e.makeTensorInfo(v,i.dtype,[]);else{let S=e.bufferSync(b),E=y1(v,S,m,f);y=e.makeTensorInfo(E.shape,E.dtype,E.values)}let _=ce({inputs:{x:y},backend:e,attrs:{shape:v}});return e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(y),_}var ZR={kernelName:Vg,backendName:"cpu",kernelFunc:OX};var BX=qt(Jh,n=>Math.tan(n)),JR={kernelName:Jh,backendName:"cpu",kernelFunc:BX};var VX=qt(Qh,n=>Math.tanh(n)),QR={kernelName:Qh,backendName:"cpu",kernelFunc:VX};function HX(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{reps:o}=r;ut(i,"tile");let s=b1(e.bufferSync(i),o);return e.makeTensorInfo(s.shape,s.dtype,s.values)}var tP={kernelName:Hg,backendName:"cpu",kernelFunc:HX};function $X(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{k:o,sorted:s}=r;ut(i,"topk");let a=e.data.get(i.dataId).values,[l,c]=_1(a,i.shape,i.dtype,o,s);return[e.makeTensorInfo(l.shape,l.dtype,l.values),e.makeTensorInfo(c.shape,c.dtype,c.values)]}var eP={kernelName:$g,backendName:"cpu",kernelFunc:$X};function UX(n){let{inputs:t,attrs:e,backend:r}=n,{image:i,transforms:o}=t,{interpolation:s,fillMode:a,fillValue:l,outputShape:c}=e,[u,h,p,d]=i.shape,[f,m]=c!=null?c:[h,p],x=[u,f,m,d],g=R.computeStrides(i.shape),v=g[0],b=g[1],y=g[2],_=R.getTypedArrayFromDType(i.dtype,R.sizeFromShape(x));_.fill(l);let S=r.data.get(i.dataId).values,E=r.data.get(o.dataId).values;for(let P=0;Pt-1)if(t<=1)e=0;else{let r=2*t;e-=r*Math.trunc(e/r),e>=t&&(e=r-e-1)}return R.clamp(0,e,t-1)}function GX(n,t){let e=n;if(e<0)if(t<=1)e=0;else{let r=t-1;e+=t*(Math.trunc(-e/r)+1)}else if(e>t-1)if(t<=1)e=0;else{let r=t-1;e-=t*Math.trunc(e/r)}return R.clamp(0,e,t-1)}function jX(n,t){return n}function qX(n,t){return R.clamp(0,n,t-1)}function hp(n,t,e,r,i,o,s,a,l,c,u){let h=s*r+a*i+l*o+c;return 0<=a&&ae.disposeIntermediateTensorInfo(f)),d}var sP={kernelName:jg,backendName:"cpu",kernelFunc:JX};var QX=[HI,uI,$I,UI,mI,WI,GI,jI,qI,XI,KI,YI,ZI,JI,QI,ek,nk,rk,ik,VI,ok,sk,ak,fI,gI,lk,hI,ck,hk,dk,fk,pk,gk,xk,mk,vk,yk,bk,_k,wk,Sk,Ck,Mk,Ek,Tk,Ak,kk,Ik,lp,Pk,LI,Nk,Lk,Dk,xI,zk,vI,Fk,Ok,Bk,yI,Vk,Hk,$k,Uk,Wk,bI,Gk,pI,jk,uk,qk,Xk,Kk,DI,_I,Yk,Zk,wI,Jk,Qk,tR,eR,nR,rR,SI,oR,sR,aR,lR,uR,iR,hR,pR,CI,dR,fR,xR,MI,EI,vR,yR,bR,TI,_R,CR,MR,E1,ER,zI,II,TR,dI,AR,FI,OI,BI,IR,kR,RR,PR,NR,LR,DR,kI,zR,FR,OR,BR,VR,HR,$R,RI,mR,WR,GR,jR,qR,XR,KR,PI,YR,ZR,NI,Rk,JR,QR,tP,eP,AI,rP,iP,oP,sP,wR];for(let n of QX)Qg(n);var ia={},K_={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function aP(n,t){ia[n]=t}function gr(n){if(!(n in ia)){let e=eK(n);if(e!==null)ia[n]=e;else return console.log("Could not get context for WebGL version",n),null}let t=ia[n];return t.isContextLost()?(delete ia[n],gr(n)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),ia[n])}function tK(n){if(typeof OffscreenCanvas!="undefined"&&n===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function eK(n){if(n!==1&&n!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=tK(n);return t.addEventListener("webglcontextlost",e=>{e.preventDefault(),delete ia[n]},!1),n===1?t.getContext("webgl",K_)||t.getContext("experimental-webgl",K_):t.getContext("webgl2",K_)}var Vo;(function(n){n[n.DENSE=0]="DENSE",n[n.SHARED_BATCH=1]="SHARED_BATCH"})(Vo||(Vo={}));var Pn;(function(n){n[n.RENDER=0]="RENDER",n[n.UPLOAD=1]="UPLOAD",n[n.PIXELS=2]="PIXELS",n[n.DOWNLOAD=3]="DOWNLOAD"})(Pn||(Pn={}));var vn;(function(n){n[n.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",n[n.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",n[n.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",n[n.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",n[n.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(vn||(vn={}));function oa(n,t){return[t,n]}function lP(n,t){return n*t}function Ho(n){let t=R.sizeFromShape(n),e=Math.ceil(t/4);return R.sizeToSquarishShape(e)}function Ei(n,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(n/2))]}function cP(n,t){let[e,r]=Ei(n,t);return e*r*4}function pp(n,t){let e=n,r,i,o,s,a,l,c,u,h,p;return ot().getNumber("WEBGL_VERSION")===2?(r=e.R32F,i=e.R16F,o=e.RGBA16F,s=e.RGBA32F,a=e.RED,c=4,u=1,h=e.HALF_FLOAT,p=e.FLOAT):(r=n.RGBA,i=n.RGBA,o=n.RGBA,s=e.RGBA,a=n.RGBA,c=4,u=4,h=t!=null?t.HALF_FLOAT_OES:null,p=n.FLOAT),l=n.RGBA,{internalFormatFloat:r,internalFormatHalfFloat:i,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:s,textureFormatFloat:a,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:u,textureTypeHalfFloat:h,textureTypeFloat:p}}function Gt(n,t){let e=t();return ot().getBool("DEBUG")&&nK(n),e}function nK(n){let t=n.getError();if(t!==n.NO_ERROR)throw new Error("WebGL Error: "+oK(n,t))}var rK=596e-10,iK=65504;function uP(n){return!!(ot().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||n===0||rKn.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function hP(n,t){let e=so(n,()=>n.createShader(n.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Gt(n,()=>n.shaderSource(e,t)),Gt(n,()=>n.compileShader(e)),n.getShaderParameter(e,n.COMPILE_STATUS)===!1)throw console.log(n.getShaderInfoLog(e)),new Error("Failed to compile vertex shader.");return e}function pP(n,t){let e=so(n,()=>n.createShader(n.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Gt(n,()=>n.shaderSource(e,t)),Gt(n,()=>n.compileShader(e)),n.getShaderParameter(e,n.COMPILE_STATUS)===!1)throw aK(t,n.getShaderInfoLog(e)),new Error("Failed to compile fragment shader.");return e}var sK=/ERROR: [0-9]+:([0-9]+):/g;function aK(n,t){let e=sK.exec(t);if(e==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(n);return}let r=+e[1],i=n.split(` +`),o=i.length.toString().length+2,s=i.map((h,p)=>R.rightPad((p+1).toString(),o)+h),a=0;for(let h=0;hn.createProgram(),"Unable to create WebGLProgram.")}function fP(n,t){if(Gt(n,()=>n.linkProgram(t)),n.getProgramParameter(t,n.LINK_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function I1(n,t){if(Gt(n,()=>n.validateProgram(t)),n.getProgramParameter(t,n.VALIDATE_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function mP(n,t){let e=so(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return Gt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),Gt(n,()=>n.bufferData(n.ARRAY_BUFFER,t,n.STATIC_DRAW)),e}function gP(n,t){let e=so(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return Gt(n,()=>n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e)),Gt(n,()=>n.bufferData(n.ELEMENT_ARRAY_BUFFER,t,n.STATIC_DRAW)),e}function xP(n){return so(n,()=>n.createTexture(),"Unable to create WebGLTexture.")}function vP(n,t){let e=ot().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||t<=0){let r=`[${n}x${t}]`;throw new Error("Requested texture size "+r+" is invalid.")}if(n>e||t>e){let r=`[${n}x${t}]`,i=`[${e}x${e}]`;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+i+".")}}function yP(n){return so(n,()=>n.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function tw(n,t,e,r,i,o,s){let a=n.getAttribLocation(t,e);return a===-1?!1:(Gt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,r)),Gt(n,()=>n.vertexAttribPointer(a,i,n.FLOAT,!1,o,s)),Gt(n,()=>n.enableVertexAttribArray(a)),!0)}function lK(n,t,e){uK(n,e),Gt(n,()=>n.activeTexture(n.TEXTURE0+e)),Gt(n,()=>n.bindTexture(n.TEXTURE_2D,t))}function bP(n,t,e){return so(n,()=>n.getUniformLocation(t,e),'uniform "'+e+'" not present in program.')}function _P(n,t,e){return n.getUniformLocation(t,e)}function wP(n,t,e,r){Gt(n,()=>lK(n,t,r)),Gt(n,()=>n.uniform1i(e,r))}function k1(n,t,e){Gt(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,e)),Gt(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0))}function ew(n,t){Gt(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,t)),Gt(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0))}function fp(n){let t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+cK(n,t))}function cK(n,t){switch(t){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function so(n,t,e){let r=Gt(n,()=>t());if(r==null)throw new Error(e);return r}function uK(n,t){let e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+n.TEXTURE0;if(re){let i=`[gl.TEXTURE0, gl.TEXTURE${e}]`;throw new Error(`textureUnit must be in ${i}.`)}}function $o(n,t=2){return R.sizeFromShape(n.slice(0,n.length-t))}function Uo(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function R1(n){let t=[1,1,1];return n.length===0||n.length===1&&n[0]===1||(t=[$o(n),...Uo(n)]),t}function SP(n,t=!1){let e=ot().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(e=e*2,n=n.map((i,o)=>o>=n.length-2?R.nearestLargerEven(n[o]):n[o]),n.length===1&&(n=[2,n[0]])),n.length!==2&&(n=R.squeezeShape(n).newShape);let r=R.sizeFromShape(n);if(n.length<=1&&r<=e)return[1,r];if(n.length===2&&n[0]<=e&&n[1]<=e)return n;if(n.length===3&&n[0]*n[1]<=e&&n[2]<=e)return[n[0]*n[1],n[2]];if(n.length===3&&n[0]<=e&&n[1]*n[2]<=e)return[n[0],n[1]*n[2]];if(n.length===4&&n[0]*n[1]*n[2]<=e&&n[3]<=e)return[n[0]*n[1]*n[2],n[3]];if(n.length===4&&n[0]<=e&&n[1]*n[2]*n[3]<=e)return[n[0],n[1]*n[2]*n[3]];if(t){let i=$o(n),o=2,s=2;return n.length&&([o,s]=Uo(n)),r=i*(o/2)*(s/2),R.sizeToSquarishShape(r).map(a=>a*2)}return R.sizeToSquarishShape(r)}function A1(n){return n%2===0}function sa(n,t){if(n=n.slice(-2),t=t.slice(-2),R.arraysEqual(n,t)||!n.length||!t.length||n[0]===0||n[1]===0||t[0]===0||t[1]===0)return!0;if(n.length!==t.length){let e=n.slice(-1)[0],r=t.slice(-1)[0];if(e===r||A1(e)&&A1(r)&&(n[0]===1||t[0]===1))return!0}return n[1]===t[1]&&A1(n[0])&&A1(t[0])}var Z_,J_;function CP(n){if(Z_==null){let t=gr(n);Z_=t.getParameter(t.MAX_TEXTURE_SIZE)}return Z_}function MP(n){if(J_==null){let t=gr(n);J_=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,J_)}function EP(n){if(n===0)return 0;let t,e=gr(n);return xr(e,"EXT_disjoint_timer_query_webgl2")&&n===2?t=2:xr(e,"EXT_disjoint_timer_query")?t=1:t=0,t}function xr(n,t){return n.getExtension(t)!=null}function nw(n){try{if(gr(n)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function TP(n){if(n===0)return!1;let t=gr(n);if(n===1){if(!xr(t,"OES_texture_float"))return!1}else if(!xr(t,"EXT_color_buffer_float"))return!1;return Q_(t)}function AP(n){if(n===0)return!1;let t=gr(n);if(n===1){if(!xr(t,"OES_texture_float")||!xr(t,"WEBGL_color_buffer_float"))return!1}else{if(xr(t,"EXT_color_buffer_float"))return Q_(t);let r="EXT_color_buffer_half_float";if(xr(t,r)){let i=t.getExtension(r);return hK(t,i)}return!1}return Q_(t)}function Q_(n){let t=pp(n),e=n.createTexture();n.bindTexture(n.TEXTURE_2D,e);let r=1,i=1;n.texImage2D(n.TEXTURE_2D,0,t.internalFormatFloat,r,i,0,t.textureFormatFloat,t.textureTypeFloat,null);let o=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,o),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0);let s=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(e),n.deleteFramebuffer(o),s}function hK(n,t){let e=pp(n,t),r=n.createTexture();n.bindTexture(n.TEXTURE_2D,r);let i=1,o=1;n.texImage2D(n.TEXTURE_2D,0,e.internalFormatHalfFloat,i,o,0,e.textureFormatFloat,e.textureTypeHalfFloat,null);let s=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,s),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,r,0);let a=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(r),n.deleteFramebuffer(s),a}function IP(n){return n!==2?!1:gr(n).fenceSync!=null}function Ti(n,t){Array.isArray(n)||(n=[n]),n.forEach(e=>{e!=null&&R.assert(e.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var te=ot();te.registerFlag("HAS_WEBGL",()=>te.getNumber("WEBGL_VERSION")>0);te.registerFlag("WEBGL_VERSION",()=>nw(2)?2:nw(1)?1:0);te.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);te.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>te.get("WEBGL_VERSION")===2);te.registerFlag("WEBGL_CPU_FORWARD",()=>!0);te.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);te.registerFlag("WEBGL_PACK",()=>te.getBool("HAS_WEBGL"));te.registerFlag("WEBGL_PACK_NORMALIZATION",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_PACK_CLIP",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!0);te.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_PACK_REDUCE",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_LAZILY_UNPACK",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_CONV_IM2COL",()=>te.getBool("WEBGL_PACK"));te.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>CP(te.getNumber("WEBGL_VERSION")));te.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>MP(te.getNumber("WEBGL_VERSION")));te.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let n=te.getNumber("WEBGL_VERSION");return n===0?0:EP(n)});te.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>te.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Fo.isMobile());te.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>TP(te.getNumber("WEBGL_VERSION")));te.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>te.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:te.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));te.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>AP(te.getNumber("WEBGL_VERSION")));te.registerFlag("WEBGL_FENCE_API_ENABLED",()=>IP(te.getNumber("WEBGL_VERSION")));te.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>te.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);te.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,n=>{if(n<0&&n!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${n}.`)});te.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Fo.isMobile()&&te.getBool("IS_CHROME")?1:-1,n=>{if(n<0&&n!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${n}.`)});function Le(){let n,t,e,r,i,o,s,a,l,c;return ot().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",t="in",e="out",r="in",i="texture",o="outputColor",s="out vec4 outputColor;",a=` + bool isnan_custom(float val) { + return (val > 0.0 || val < 0.0) ? false : val != 0.0; + } + + bvec4 isnan_custom(vec4 val) { + return bvec4(isnan_custom(val.x), + isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w)); + } + + #define isnan(value) isnan_custom(value) + `,l="",c=` + #define round(value) newRound(value) + int newRound(float value) { + return int(floor(value + 0.5)); + } + + ivec4 newRound(vec4 value) { + return ivec4(floor(value + vec4(0.5))); + } + `):(n="",t="attribute",e="varying",r="varying",i="texture2D",o="gl_FragColor",s="",a=` + #define isnan(value) isnan_custom(value) + bool isnan_custom(float val) { + return (val > 0. || val < 1. || val == 0.) ? false : true; + } + bvec4 isnan_custom(vec4 val) { + return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w)); + } + `,l=` + uniform float INFINITY; + + bool isinf(float val) { + return abs(val) == INFINITY; + } + bvec4 isinf(vec4 val) { + return equal(abs(val), vec4(INFINITY)); + } + `,c=` + int round(float value) { + return int(floor(value + 0.5)); + } + + ivec4 round(vec4 value) { + return ivec4(floor(value + vec4(0.5))); + } + `),{version:n,attribute:t,varyingVs:e,varyingFs:r,texture2D:i,output:o,defineOutput:s,defineSpecialNaN:a,defineSpecialInf:l,defineRound:c}}function Zr(n,t,e="index"){let r=R.computeStrides(t);return r.map((i,o)=>{let s=`int ${n[o]} = ${e} / ${i}`,a=o===r.length-1?`int ${n[o+1]} = ${e} - ${n[o]} * ${i}`:`index -= ${n[o]} * ${i}`;return`${s}; ${a};`}).join("")}function Zl(n){let t=R.computeStrides(n).map(e=>e.toString());return` + int getFlatIndex(ivec3 coords) { + return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z; + } +`}var N1=` + const float FLOAT_MAX = 1.70141184e38; + const float FLOAT_MIN = 1.17549435e-38; + + lowp vec4 encode_float(highp float v) { + if (isnan(v)) { + return vec4(255, 255, 255, 255); + } + + highp float av = abs(v); + + if(av < FLOAT_MIN) { + return vec4(0.0, 0.0, 0.0, 0.0); + } else if(v > FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; + } else if(v < -FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; + } + + highp vec4 c = vec4(0,0,0,0); + + highp float e = floor(log2(av)); + highp float m = exp2(fract(log2(av))) - 1.0; + + c[2] = floor(128.0 * m); + m -= c[2] / 128.0; + c[1] = floor(32768.0 * m); + m -= c[1] / 32768.0; + c[0] = floor(8388608.0 * m); + + highp float ebias = e + 127.0; + c[3] = floor(ebias / 2.0); + ebias -= c[3] * 2.0; + c[2] += floor(ebias) * 128.0; + + c[3] += 128.0 * step(0.0, -v); + + return c / 255.0; + } +`;var L1=class{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Vo.DENSE;let e=Ho(t),r=Le();this.outputShape=t,this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + ${Zr(["r","c","d"],t)} + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${e[0]}, ${e[1]})); + int index = 4 * (resTexRC.x * ${e[1]} + resTexRC.y); + + vec4 result = vec4(0.); + + for (int i=0; i<4; i++) { + int flatIndex = index + i; + ivec3 rc = outCoordsFromFlatIndex(flatIndex); + result[i] = getA(rc.x, rc.y, rc.z); + } + + ${r.output} = result; + } + `}};var D1=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Vo.DENSE;let e=Ho(t),r=Le();this.outputShape=t,this.userCode=` + ivec3 outCoordsFromFlatIndex(int index) { + ${Zr(["r","c","d"],t)} + return ivec3(r, c, d); + } + + void main() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${e[0]}, ${e[1]})); + int index = 4 * (resTexRC.x * ${e[1]} + resTexRC.y); + + vec4 result = vec4(0.); + + for (int i=0; i<4; i++) { + int flatIndex = index + i; + ivec3 rc = outCoordsFromFlatIndex(flatIndex); + result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z)); + } + + ${r.output} = result; + } + `}};var z1=class{constructor(t){this.variableNames=["A"],this.outTexUsage=Pn.DOWNLOAD;let e=Le();this.outputShape=t,this.userCode=` + ${N1} + + void main() { + float x = getAAtOutCoords(); + ${e.output} = encode_float(x); + } + `}};var F1=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Pn.DOWNLOAD;let e=Le();this.outputShape=t,this.userCode=` + ${N1} + + void main() { + ivec3 coords = getOutputCoords(); + float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); + ${e.output} = encode_float(x); + } + `}};var O1=class{constructor(t,e,r=!1){this.variableNames=["A"];let i=Le(),[o,s]=e;this.outputShape=t;let a="result";r&&(a="floor(result * 255. + 0.5)"),this.userCode=` + ${Zl(t)} + + void main() { + ivec3 coords = getOutputCoords(); + + int flatIndex = getFlatIndex(coords); + int offset = imod(flatIndex, 4); + + flatIndex = idiv(flatIndex, 4, 1.); + + int r = flatIndex / ${s}; + int c = imod(flatIndex, ${s}); + vec2 uv = (vec2(c, r) + halfCR) / vec2(${s}.0, ${o}.0); + vec4 values = ${i.texture2D}(A, uv); + + float result; + + if(offset == 0) { + result = values[0]; + } else if(offset == 1) { + result = values[1]; + } else if(offset == 2) { + result = values[2]; + } else { + result = values[3]; + } + + ${i.output} = vec4(${a}, 0., 0., 0.); + } + `}};var B1=class{constructor(t,e,r=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let i=Le(),[o,s]=e;this.outputShape=t;let a="",l="result";r&&(l="floor(result * 255. + 0.5)");for(let c=0;c<=1;c++)for(let u=0;u<=1;u++){let h=c*2+u;a+=` + localCoords = coords; + if(localCoords[2] + ${u} < ${t[2]}) { + localCoords[2] += ${u}; + if(localCoords[1] + ${c} < ${t[1]}) { + localCoords[1] += ${c}; + + flatIndex = getFlatIndex(localCoords); + offset = imod(flatIndex, 4); + + flatIndex = idiv(flatIndex, 4, 1.); + + r = flatIndex / ${s}; + c = imod(flatIndex, ${s}); + uv = (vec2(c, r) + halfCR) / vec2(${s}.0, ${o}.0); + values = ${i.texture2D}(A, uv); + + if(offset == 0) { + result[${h}] = values[0]; + } else if(offset == 1) { + result[${h}] = values[1]; + } else if(offset == 2) { + result[${h}] = values[2]; + } else { + result[${h}] = values[3]; + } + } + } + `}this.userCode=` + ${Zl(t)} + + void main() { + ivec3 coords = getOutputCoords(); + + vec4 result = vec4(0.); + int flatIndex, r, c, offset; + ivec3 localCoords; + vec2 uv; + vec4 values; + + ${a} + + ${i.output} = ${l}; + } + `}};function kP(n){let t=Le(),e=`${t.version} + precision highp float; + ${t.attribute} vec3 clipSpacePos; + ${t.attribute} vec2 uv; + ${t.varyingVs} vec2 resultUV; + + void main() { + gl_Position = vec4(clipSpacePos, 1); + resultUV = uv; + }`;return hP(n,e)}function RP(n){let t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return mP(n,t)}function PP(n){let t=new Uint16Array([0,1,2,2,1,3]);return gP(n,t)}function mp(n,t,e,r,i,o){vP(t,e);let s=xP(n),a=n.TEXTURE_2D;return Gt(n,()=>n.bindTexture(a,s)),Gt(n,()=>n.texParameteri(a,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)),Gt(n,()=>n.texParameteri(a,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),Gt(n,()=>n.texParameteri(a,n.TEXTURE_MIN_FILTER,n.NEAREST)),Gt(n,()=>n.texParameteri(a,n.TEXTURE_MAG_FILTER,n.NEAREST)),Gt(n,()=>n.texImage2D(a,0,r,t,e,0,i,o,null)),Gt(n,()=>n.bindTexture(n.TEXTURE_2D,null)),s}function rw(n){return n.internalFormatFloat}function NP(n,t,e,r){let[i,o]=oa(t,e);return mp(n,i,o,rw(r),r.textureFormatFloat,n.FLOAT)}function iw(n){return n.internalFormatHalfFloat}function LP(n,t,e,r){let[i,o]=oa(t,e);return mp(n,i,o,iw(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function ow(n){return n.downloadTextureFormat}function DP(n,t,e,r){let[i,o]=oa(t,e);return mp(n,i,o,ow(r),n.RGBA,n.UNSIGNED_BYTE)}function sw(n){return n.internalFormatPackedFloat}function zP(n,t,e,r){let[i,o]=Ei(t,e);return mp(n,i,o,sw(r),n.RGBA,n.FLOAT)}function aw(n){return n.internalFormatPackedHalfFloat}function FP(n,t,e,r){let[i,o]=Ei(t,e);return mp(n,i,o,aw(r),n.RGBA,r.textureTypeHalfFloat)}function OP(n,t,e){return Gt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),tw(n,t,"clipSpacePos",e,3,20,0)&&tw(n,t,"uv",e,2,20,12)}function BP(n,t,e,r,i,o){Gt(n,()=>n.bindTexture(n.TEXTURE_2D,t));let s,a,l;i instanceof Uint8Array?(s=new Uint8Array(e*r*4),a=n.UNSIGNED_BYTE,l=n.RGBA):(s=new Float32Array(e*r*4),a=n.FLOAT,l=o.internalFormatPackedFloat),s.set(i),Gt(n,()=>n.texImage2D(n.TEXTURE_2D,0,l,e,r,0,n.RGBA,a,s)),Gt(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function VP(n,t,e){Gt(n,()=>n.bindTexture(n.TEXTURE_2D,t)),e.data instanceof Uint8Array?Gt(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)):Gt(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)),Gt(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function HP(n,t,e,r){let i=n.createBuffer();Gt(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,i));let a=4*4*t*e;return Gt(n,()=>n.bufferData(n.PIXEL_PACK_BUFFER,a,n.STREAM_READ)),Gt(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)),Gt(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,null)),i}function $P(n,t,e){let r=n,i=new Float32Array(e);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function UP(n,t,e,r){let[i,o]=oa(t,e),s=4,a=new Uint8Array(lP(t*e,s));return Gt(n,()=>n.readPixels(0,0,i,o,r.downloadTextureFormat,n.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function WP(n,t,e,r,i,o,s,a){let l=n,c=new Float32Array(cP(o,s));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function GP(n,t,e){let r=new Float32Array(t*e*4);return Gt(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,r)),r}var V1=class{constructor(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let e=ot().getNumber("WEBGL_VERSION");t!=null?(this.gl=t,aP(e,t)):this.gl=gr(e);let r="WEBGL_color_buffer_float",i="EXT_color_buffer_half_float";if(ot().getNumber("WEBGL_VERSION")===1){let o="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=dp(this.gl,o),xr(this.gl,s))this.textureHalfFloatExtension=dp(this.gl,s);else if(ot().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(r),xr(this.gl,i))this.colorBufferHalfFloatExtension=dp(this.gl,i);else if(ot().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(r="EXT_color_buffer_float",xr(this.gl,r))this.colorBufferFloatExtension=this.gl.getExtension(r);else if(xr(this.gl,i))this.colorBufferHalfFloatExtension=this.gl.getExtension(i);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=RP(this.gl),this.indexBuffer=PP(this.gl),this.framebuffer=yP(this.gl),this.textureConfig=pp(this.gl,this.textureHalfFloatExtension)}get debug(){return ot().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let t=this.gl;Gt(t,()=>t.finish()),Gt(t,()=>t.bindFramebuffer(t.FRAMEBUFFER,null)),Gt(t,()=>t.deleteFramebuffer(this.framebuffer)),Gt(t,()=>t.bindBuffer(t.ARRAY_BUFFER,null)),Gt(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),Gt(t,()=>t.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(t,e){return this.throwIfDisposed(),NP(this.gl,t,e,this.textureConfig)}createFloat16MatrixTexture(t,e){return this.throwIfDisposed(),LP(this.gl,t,e,this.textureConfig)}createUnsignedBytesMatrixTexture(t,e){return this.throwIfDisposed(),DP(this.gl,t,e,this.textureConfig)}uploadPixelDataToTexture(t,e){this.throwIfDisposed(),VP(this.gl,t,e)}uploadDenseMatrixToTexture(t,e,r,i){this.throwIfDisposed(),BP(this.gl,t,e,r,i,this.textureConfig)}createFloat16PackedMatrixTexture(t,e){return this.throwIfDisposed(),FP(this.gl,t,e,this.textureConfig)}createPackedMatrixTexture(t,e){return this.throwIfDisposed(),zP(this.gl,t,e,this.textureConfig)}deleteMatrixTexture(t){this.throwIfDisposed(),this.outputTexture===t&&(ew(this.gl,this.framebuffer),this.outputTexture=null),Gt(this.gl,()=>this.gl.deleteTexture(t))}downloadByteEncodedFloatMatrixFromOutputTexture(t,e,r){return this.downloadMatrixDriver(t,()=>UP(this.gl,e,r,this.textureConfig))}downloadPackedMatrixFromBuffer(t,e,r,i,o,s){return WP(this.gl,t,e,r,i,o,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(t,e){return $P(this.gl,t,e)}createBufferFromTexture(t,e,r){this.bindTextureToFrameBuffer(t);let i=HP(this.gl,e,r,this.textureConfig);return this.unbindTextureToFrameBuffer(),i}createAndWaitForFence(){let t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e,r;if(ot().getBool("WEBGL_FENCE_API_ENABLED")){let i=t,o=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),r=()=>{let s=i.clientWaitSync(o,0,0);return s===i.ALREADY_SIGNALED||s===i.CONDITION_SATISFIED},e=o}else ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),r=()=>this.isQueryAvailable(e,ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):r=()=>!0;return{query:e,isFencePassed:r}}downloadMatrixFromPackedTexture(t,e,r){return this.downloadMatrixDriver(t,()=>GP(this.gl,e,r))}createProgram(t){this.throwIfDisposed();let e=this.gl,r=pP(e,t),i=kP(e),o=dP(e);return Gt(e,()=>e.attachShader(o,i)),Gt(e,()=>e.attachShader(o,r)),fP(e,o),this.debug&&I1(e,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=OP(e,this.program,this.vertexBuffer)),o}deleteProgram(t){this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&Gt(this.gl,()=>this.gl.deleteProgram(t))}setProgram(t){this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&I1(this.gl,this.program),Gt(this.gl,()=>this.gl.useProgram(t))}getUniformLocation(t,e,r=!0){return this.throwIfDisposed(),r?bP(this.gl,t,e):_P(this.gl,t,e)}getAttributeLocation(t,e){return this.throwIfDisposed(),Gt(this.gl,()=>this.gl.getAttribLocation(t,e))}getUniformLocationNoThrow(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)}setInputMatrixTexture(t,e,r){this.throwIfDisposed(),this.throwIfNoProgram(),wP(this.gl,t,e,r)}setOutputMatrixTexture(t,e,r){this.setOutputMatrixTextureDriver(t,r,e)}setOutputPackedMatrixTexture(t,e,r){this.throwIfDisposed();let[i,o]=Ei(e,r);this.setOutputMatrixTextureDriver(t,i,o)}setOutputMatrixWriteRegion(t,e,r,i){this.setOutputMatrixWriteRegionDriver(r,t,i,e)}setOutputPackedMatrixWriteRegion(t,e,r,i){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&I1(this.gl,this.program),fp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let t=this.gl;this.debug&&this.debugValidate(),Gt(t,()=>t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Gt(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=dp(this.gl,ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let r=this.gl,i=this.getQueryTimerExtensionWebGL2(),o=r.createQuery();return r.beginQuery(i.TIME_ELAPSED_EXT,o),o}let t=this.getQueryTimerExtensionWebGL1(),e=t.createQueryEXT();return t.beginQueryEXT(t.TIME_ELAPSED_EXT,e),e}endQuery(){if(ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let e=this.gl,r=this.getQueryTimerExtensionWebGL2();e.endQuery(r.TIME_ELAPSED_EXT);return}let t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}waitForQueryAndGetTime(t){return Jt(this,null,function*(){return yield R.repeatedTry(()=>this.disposed||this.isQueryAvailable(t,ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(t,ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})}getQueryTime(t,e){if(e===0)return null;if(e===2){let r=this.gl;return r.getQueryParameter(t,r.QUERY_RESULT)/1e6}else{let r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(t,e){if(e===0)return!0;if(e===2){let r=this.gl,i=this.getQueryTimerExtensionWebGL2(),o=r.getQueryParameter(t,r.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(i.GPU_DISJOINT_EXT)),o&&!this.disjoint}else{let r=this.getQueryTimerExtensionWebGL1(),i=r.getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}}pollFence(t){return new Promise(e=>{this.addItemToPoll(()=>t.isFencePassed(),()=>e())})}pollItems(){let t=dK(this.itemsToPoll.map(e=>e.isDoneFn));for(let e=0;e<=t;++e){let{resolveFn:r}=this.itemsToPoll[e];r()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}addItemToPoll(t,e){this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),!(this.itemsToPoll.length>1)&&R.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(t){this.throwIfDisposed(),k1(this.gl,t,this.framebuffer),this.debug&&fp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(k1(this.gl,this.outputTexture,this.framebuffer),this.debug&&fp(this.gl)):ew(this.gl,this.framebuffer)}downloadMatrixDriver(t,e){this.bindTextureToFrameBuffer(t);let r=e();return this.unbindTextureToFrameBuffer(),r}setOutputMatrixTextureDriver(t,e,r){this.throwIfDisposed();let i=this.gl;k1(i,t,this.framebuffer),this.debug&&fp(i),this.outputTexture=t,Gt(i,()=>i.viewport(0,0,e,r)),Gt(i,()=>i.scissor(0,0,e,r))}setOutputMatrixWriteRegionDriver(t,e,r,i){this.throwIfDisposed(),Gt(this.gl,()=>this.gl.scissor(t,e,r,i))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function dK(n){let t=0;for(;t{let m=R.sizeFromShape(f.shapeInfo.logicalShape);f.shapeInfo.isUniform?i.push(`uniform float ${f.name}${m>1?`[${m}]`:""};`):(i.push(`uniform sampler2D ${f.name};`),i.push(`uniform int offset${f.name};`))});let o=i.join(` +`),s=n.map(f=>fK(f,t,r)).join(` +`),a=t.texShape,l=Le(),c=xK(l),u,h,p=bK(l);return t.isPacked?(u=mK(t.logicalShape,a),h=yK(l)):(u=gK(t.logicalShape,a),h=vK(l)),r&&(p+=CK),[p,c,h,o,u,s,e].join(` +`)}function Ql(n){let t=n.shapeInfo.logicalShape;switch(t.length){case 0:return zK(n);case 1:return OK(n);case 2:return VK(n);case 3:return $K(n);case 4:return WK(n);case 5:return GK(n);case 6:return jK(n);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function XP(n){switch(n.shapeInfo.logicalShape.length){case 0:return DK(n);case 1:return FK(n);case 2:return BK(n);case 3:return HK(n);default:return UK(n)}}function fK(n,t,e=!1){let r="";e?r+=XP(n):r+=Ql(n);let i=n.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(e?r+=qK(n,t):r+=XK(n,t)),r}function mK(n,t){switch(n.length){case 0:return KP();case 1:return MK(n,t);case 2:return NK(n,t);case 3:return TK(n,t);default:return IK(n,t)}}function gK(n,t){switch(n.length){case 0:return KP();case 1:return EK(n,t);case 2:return LK(n,t);case 3:return AK(n,t);case 4:return kK(n,t);case 5:return RK(n,t);case 6:return PK(n,t);default:throw new Error(`${n.length}-D output sampling is not yet supported`)}}function xK(n){return` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return ${n.texture2D}(textureSampler, uv).r; + } + `}function vK(n){return` + void setOutput(float val) { + ${n.output} = vec4(val, 0, 0, 0); + } + `}function yK(n){return` + void setOutput(vec4 val) { + ${n.output} = val; + } + `}function bK(n){return`${n.version} + precision highp float; + precision highp int; + precision highp sampler2D; + ${n.varyingFs} vec2 resultUV; + ${n.defineOutput} + const vec2 halfCR = vec2(0.5, 0.5); + + struct ivec5 + { + int x; + int y; + int z; + int w; + int u; + }; + + struct ivec6 + { + int x; + int y; + int z; + int w; + int u; + int v; + }; + + uniform float NAN; + ${n.defineSpecialNaN} + ${n.defineSpecialInf} + ${n.defineRound} + + int imod(int x, int y) { + return x - y * (x / y); + } + + int idiv(int a, int b, float sign) { + int res = a / b; + int mod = imod(a, b); + if (sign < 0. && mod != 0) { + res -= 1; + } + return res; + } + + //Based on the work of Dave Hoskins + //https://www.shadertoy.com/view/4djSRW + #define HASHSCALE1 443.8975 + float random(float seed){ + vec2 p = resultUV * seed; + vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1); + p3 += dot(p3, p3.yzx + 19.19); + return fract((p3.x + p3.y) * p3.z); + } + + ${_K} + ${wK} + ${SK} + `}var _K=` +vec2 uvFromFlat(int texNumR, int texNumC, int index) { + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { + int texelIndex = index / 2; + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,wK=` +vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR, + int texNumC, int row, int col) { + int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,SK=` +vec2 packedUVfrom3D(int texNumR, int texNumC, + int texelsInBatch, int texelsInLogicalRow, int b, + int row, int col) { + int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); +} +`,CK=` + float getChannel(vec4 frag, vec2 innerDims) { + vec2 modCoord = mod(innerDims, 2.); + return modCoord.x == 0. ? + (modCoord.y == 0. ? frag.r : frag.g) : + (modCoord.y == 0. ? frag.b : frag.a); + } + float getChannel(vec4 frag, int dim) { + float modCoord = mod(float(dim), 2.); + return modCoord == 0. ? frag.r : frag.g; + } +`;function KP(){return` + int getOutputCoords() { + return 0; + } + `}function MK(n,t){let e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return e[0]===1?` + int getOutputCoords() { + return 2 * int(resultUV.x * ${e[1]}.0); + } + `:e[1]===1?` + int getOutputCoords() { + return 2 * int(resultUV.y * ${e[0]}.0); + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${e[0]}, ${e[1]})); + return 2 * (resTexRC.x * ${e[1]} + resTexRC.y); + } + `}function EK(n,t){return t[0]===1?` + int getOutputCoords() { + return int(resultUV.x * ${t[1]}.0); + } + `:t[1]===1?` + int getOutputCoords() { + return int(resultUV.y * ${t[0]}.0); + } + `:` + int getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${t[0]}, ${t[1]})); + return resTexRC.x * ${t[1]} + resTexRC.y; + } + `}function TK(n,t){let e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[2]/2),i=r*Math.ceil(n[1]/2);return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.x * ${e[1]} + resTexRC.y; + + int b = index / ${i}; + index -= b * ${i}; + + int r = 2 * (index / ${r}); + int c = imod(index, ${r}) * 2; + + return ivec3(b, r, c); + } + `}function AK(n,t){let e=Zr(["r","c","d"],n);return` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(resultUV.yx * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.x * ${t[1]} + resTexRC.y; + ${e} + return ivec3(r, c, d); + } + `}function IK(n,t){let e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[n.length-1]/2),i=r*Math.ceil(n[n.length-2]/2),o=i,s="",a="b, r, c";for(let l=2;l=1?u="coords = 0;":u=a.map(v=>`coords.${h[v+c]} = 0;`).join(` +`);let p="";s<2&&o>0?p="coords":p=n.shapeInfo.logicalShape.map((v,b)=>`coords.${h[b+c]}`).join(", ");let d="return outputValue;",m=R.sizeFromShape(n.shapeInfo.logicalShape)===1,g=R.sizeFromShape(t.logicalShape)===1;if(o===1&&!m&&!g)d=` + return vec4(outputValue.xy, outputValue.xy); + `;else if(m&&!g)s===1?d=` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:d=` + return vec4(outputValue.x); + `;else if(a.length){let v=o-2,b=o-1;a.indexOf(v)>-1&&a.indexOf(b)>-1?d="return vec4(outputValue.x);":a.indexOf(v)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(b)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}return` + vec4 ${i}() { + ${l} coords = getOutputCoords(); + ${u} + vec4 outputValue = get${r}(${p}); + ${d} + } + `}function XK(n,t){let e=n.name,r=e.charAt(0).toUpperCase()+e.slice(1),i="get"+r+"AtOutCoords",o=t.texShape,s=n.shapeInfo.texShape,a=n.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!n.shapeInfo.isUniform&&a===l&&n.shapeInfo.flatOffset==null&&R.arraysEqual(s,o))return` + float ${i}() { + return sampleTexture(${e}, resultUV); + } + `;let c=ne(l),u=jP(n.shapeInfo.logicalShape,t.logicalShape),h=l-a,p,d=["x","y","z","w","u","v"];a===0?p="":l<2&&u.length>=1?p="coords = 0;":p=u.map(m=>`coords.${d[m+h]} = 0;`).join(` +`);let f="";return l<2&&a>0?f="coords":f=n.shapeInfo.logicalShape.map((m,x)=>`coords.${d[x+h]}`).join(", "),` + float ${i}() { + ${c} coords = getOutputCoords(); + ${p} + return get${r}(${f}); + } + `}function ne(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error(`GPU for rank ${n} is not yet supported`)}function ec(n,t){let e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function nc(n,t){return t.map(e=>n[e]).join(", ")}function ZP(n,t,e,r){let i=t.userCode,o=e.map((d,f)=>{let m={logicalShape:d.shape,texShape:d.isUniform?null:d.texData.texShape,isUniform:d.isUniform,isPacked:d.isUniform?!1:d.texData.isPacked,flatOffset:null};return d.texData!=null&&d.texData.slice!=null&&d.texData.slice.flatOffset>0&&(m.flatOffset=d.texData.slice.flatOffset),{name:t.variableNames[f],shapeInfo:m}}),s=o.map(d=>d.shapeInfo),a={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},l=qP(o,a,i,t.packedInputs),c=n.createProgram(l),u=null,h=n.getUniformLocation(c,"NAN",!1);ot().getNumber("WEBGL_VERSION")===1&&(u=n.getUniformLocation(c,"INFINITY",!1));let p={};for(let d=0;d{let i=e.logicalShape,o=t[r],s=o.shape;if(!R.arraysEqual(i,s))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${i} and ${s} must match`);if(e.isUniform&&o.isUniform)return;let a=e.texShape,l=o.isUniform?null:o.texData.texShape;if(!R.arraysEqual(a,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${l} must match`)})}function JP(n,t,e,r,i){YP(t.inShapeInfos,e),YP([t.outShapeInfo],[r]);let o=r.texData.texture,s=r.texData.texShape;r.texData.isPacked?n.setOutputPackedMatrixTexture(o,s[0],s[1]):n.setOutputMatrixTexture(o,s[0],s[1]),n.setProgram(t.webGLProgram),ot().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&n.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&n.gl.uniform1f(t.nanLoc,NaN),e.forEach((a,l)=>{let c=t.program.variableNames[l],u=t.uniformLocations[c],h=t.uniformLocations[`offset${c}`];if(u!=null){if(a.isUniform){if(R.sizeFromShape(a.shape)<2)n.gl.uniform1f(u,a.uniformValues[0]);else{let p=a.uniformValues;p instanceof Float32Array||(p=new Float32Array(p)),n.gl.uniform1fv(u,p)}return}a.texData.slice!=null&&h!=null&&n.gl.uniform1i(h,a.texData.slice.flatOffset),n.setInputMatrixTexture(a.texData.texture,u,l)}}),i!=null&&i(n,t.webGLProgram),n.executeProgram()}function QP(n,t,e){let r="";t.concat(e).forEach(s=>{let a=s.texData!=null&&s.texData.slice!=null&&s.texData.slice.flatOffset>0,l=s.isUniform?"uniform":s.texData.texShape;r+=`${s.shape}_${l}_${a}`});let i=n.userCode,o=n.constructor.name;return o+="_"+r+"_"+i,o}var{addImpl:t6,bincountImpl:H1,bincountReduceImpl:e6,ceilImpl:n6,concatImpl:r6,expImpl:i6,expm1Impl:o6,floorImpl:s6,gatherV2Impl:a6,greaterImpl:l6,lessImpl:c6,linSpaceImpl:u6,logImpl:h6,maxImpl:p6,maximumImpl:d6,minimumImpl:f6,multiplyImpl:m6,negImpl:g6,prodImpl:x6,rangeImpl:v6,rsqrtImpl:y6,simpleAbsImpl:$1,sliceImpl:b6,stridedSliceImpl:_6,subImpl:w6,tileImpl:S6,topKImpl:C6,transposeImpl:la,uniqueImpl:M6}=D_;function lw(n,t){return["x","y","z","w","u","v"].slice(0,t).map(e=>`${n}.${e}`)}function Oe(n,t){return t===1?[n]:lw(n,t)}function E6(n,t){if(n===1)return"rc";let e="";for(let r=0;r ${t[0]}`;let r="";for(let i=n-2;i= ${t[i]}`,i= ${t}; + bool rEdge = rp1 >= ${e}; + `}function tY(n,t){let e=n.length,r=ZK(e,t);return e===1?`getA(rc), + rc + 1 >= ${n[0]} ? 0. : getA(rc + 1), + 0, 0`:`getA(${r[0]}), + cEdge ? 0. : getA(${r[1]}), + rEdge ? 0. : getA(${r[2]}), + rEdge || cEdge ? 0. : getA(${r[3]})`}var rc=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;let r="";for(let i=0;i<4;i++){let o="thisRC = rc;";i%2===1&&(o+="thisRC.z += 1;"),i>1&&(o+="thisRC.y += 1;"),r+=` + ${o} + ${i>0?"if(thisRC.y < rows && thisRC.z < cols){":""} + int flatIndex = getFlatIndex(thisRC); + + ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex); + vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z)); + + result[${i}] = + getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); + ${i>0?"}":""} + `}this.userCode=` + ${eY(e)} + ${Zl(t)} + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.); + + ivec3 thisRC; + int rows = ${t[1]}; + int cols = ${t[2]}; + + ${r} + + setOutput(result); + } + `}};function eY(n){return` + ivec3 inputCoordsFromReshapedOutCoords(int index) { + ${Zr(["r","c","d"],n)} + return ivec3(r, c, d); + } + `}var W1=class{constructor(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(t,e,r){let i=A6(e,r),o=I6(t,i,r);o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]);let s=T6(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,r);if(this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let l=this.freeTextures[o].shift();return this.usedTextures[o].push(l),l}let a;return i===vn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===vn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===vn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===vn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===vn.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[o].push(a),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),a}releaseTexture(t,e,r,i){if(this.freeTextures==null)return;let o=A6(r,i),s=I6(e,o,i);s in this.freeTextures||(this.freeTextures[s]=[]);let a=T6(e,o,this.gpgpu.gl,this.gpgpu.textureConfig,i),l=ot().get("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(t),this._numBytesAllocated-=a):(this.freeTextures[s].push(t),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;let c=this.usedTextures[s],u=c.indexOf(t);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${t})`);let e=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*e)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let t in this.freeTextures)this.freeTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e)});for(let t in this.usedTextures)this.usedTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function nY(n,t){let e=n;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===n.RGBA)return 16;if(t===e.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function T6(n,t,e,r,i){let o=rY(t,r),s;if(i){let[l,c]=Ei(n[0],n[1]);s=l*c}else{let[l,c]=oa(n[0],n[1]);s=l*c}let a=nY(e,o);return s*a}function rY(n,t){switch(n){case vn.PACKED_2X2_FLOAT32:return sw(t);case vn.PACKED_2X2_FLOAT16:return aw(t);case vn.UNPACKED_FLOAT32:return rw(t);case vn.UNPACKED_FLOAT16:return iw(t);case vn.PACKED_4X1_UNSIGNED_BYTE:return ow(t);default:throw new Error(`Unknown physical texture type ${n}`)}}function iY(n){return ot().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?vn.PACKED_2X2_FLOAT32:vn.UNPACKED_FLOAT32:n?vn.PACKED_2X2_FLOAT16:vn.UNPACKED_FLOAT16}function A6(n,t){if(n===Pn.UPLOAD)return vn.PACKED_2X2_FLOAT32;if(n===Pn.RENDER||n==null)return iY(t);if(n===Pn.DOWNLOAD||n===Pn.PIXELS)return vn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${n}`)}function I6(n,t,e){return`${n[0]}_${n[1]}_${t}_${e}`}var jn=class{constructor(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode=` + float unaryOperation(float x) { + ${e} + } + + void main() { + float x = getAAtOutCoords(); + float y = unaryOperation(x); + + setOutput(y); + } + `}},pn="if (isnan(x)) return x;",k6="return x;",cw="return abs(x);";var R6="return (x >= 0.0) ? x : (exp(x) - 1.0);",P6=pn+` + return (x < 0.0) ? 0.0 : x; +`,N6=pn+` + return (x < 0.0) ? 0.0 : min(6.0, x); +`,gp="return x;";var D6="return x;",z6=` + vec4 result; + + result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); + result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); + result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); + result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); + + return result; +`,F6=` + vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,O6=` + vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,Fr=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=` + vec4 unaryOperation(vec4 x) { + ${e} + } + + void main() { + vec4 x = getAAtOutCoords(); + vec4 y = unaryOperation(x); + + setOutput(y); + } + `}};var G1=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;let e=t.length,r=Oe("rc",e),i=ne(e),o=E6(e,r),s=r.slice(-2),a=e<=1?"rc":`vec2(${s.join(",")})`;this.userCode=` + void main() { + ${i} rc = getOutputCoords(); + vec4 packedInput = getA(${o}); + + setOutput(getChannel(packedInput, ${a})); + } + `}};var sY=kn.whereImpl,aY=1e-7,lY=1e-4,j1={};function cY(n){return n in j1||(j1[n]={}),j1[n]}var uY=128,hY=600;function pY(){return ot().global.screen==null?1024:ot().global.screen.height*ot().global.screen.width*window.devicePixelRatio*hY/1024/1024}var ca=class extends Qi{constructor(t){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!ot().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(t==null){let e=gr(ot().getNumber("WEBGL_VERSION"));this.binaryCache=cY(ot().getNumber("WEBGL_VERSION")),this.gpgpu=new V1(e),this.canvas=e.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=t,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=t.gl.canvas;this.textureManager=new W1(this.gpgpu),this.numMBBeforeWarning=pY(),this.texData=new Vs(this,ro())}nextDataId(){return ca.nextDataId++}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(t,e,r){if((ot().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||ot().getBool("DEBUG"))&&this.checkNumericalProblems(t),r==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let i={id:this.nextDataId()};return this.texData.set(i,{shape:e,dtype:r,values:t,usage:Pn.UPLOAD,refCount:1}),i}refCount(t){return this.texData.has(t)?this.texData.get(t).refCount:0}incRef(t){let e=this.texData.get(t);e.refCount++}decRef(t){if(this.texData.has(t)){let e=this.texData.get(t);e.refCount--}}move(t,e,r,i,o){if(ot().getBool("DEBUG")&&this.checkNumericalProblems(e),i==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:r,dtype:i,values:e,usage:Pn.UPLOAD,refCount:o})}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}readSync(t){let e=this.texData.get(t),{values:r,dtype:i,complexTensorInfos:o,slice:s,shape:a,isPacked:l}=e;if(s!=null){let p;l?p=new Fr(a,gp):p=new jn(a,gp);let d=this.runWebGLProgram(p,[{dataId:t,shape:a,dtype:i}],i),f=this.readSync(d.dataId);return this.disposeIntermediateTensorInfo(d),f}if(r!=null)return this.convertAndCacheOnCPU(t);if(i==="string")return r;let c=this.activeTimers!=null,u;c&&(u=R.now());let h;if(i==="complex64"){let p=this.readSync(o.real.dataId),d=this.readSync(o.imag.dataId);h=F.mergeRealAndImagArrays(p,d)}else h=this.getValuesFromTexture(t);return c&&(this.downloadWaitMs+=R.now()-u),this.convertAndCacheOnCPU(t,h)}read(t){return Jt(this,null,function*(){if(this.pendingRead.has(t)){let f=this.pendingRead.get(t);return new Promise(m=>f.push(m))}let e=this.texData.get(t),{values:r,shape:i,slice:o,dtype:s,complexTensorInfos:a,isPacked:l}=e;if(o!=null){let f;l?f=new Fr(i,gp):f=new jn(i,gp);let m=this.runWebGLProgram(f,[{dataId:t,shape:i,dtype:s}],s),x=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),x}if(r!=null)return this.convertAndCacheOnCPU(t);if(!ot().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&ot().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c=null,u;if(s!=="complex64"&&ot().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(t);let f=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(f.texture,...Ho(i))}this.pendingRead.set(t,[]),s!=="complex64"&&(yield this.gpgpu.createAndWaitForFence());let h;if(s==="complex64"){let f=yield Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),m=f[0],x=f[1];h=F.mergeRealAndImagArrays(m,x)}else if(c==null)h=this.getValuesFromTexture(t);else{let f=R.sizeFromShape(i);h=this.gpgpu.downloadFloat32MatrixFromBuffer(c,f)}u!=null&&this.disposeIntermediateTensorInfo(u);let p=this.convertAndCacheOnCPU(t,h),d=this.pendingRead.get(t);return this.pendingRead.delete(t),d.forEach(f=>f(p)),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)&&ro().removeDataId(t,this),this.pendingDeletes--),p})}bufferSync(t){let e=this.readSync(t.dataId),r=e;if(t.dtype==="string")try{r=e.map(i=>R.decodeString(i))}catch(i){throw new Error("Failed to decode encoded string bytes into utf-8")}return Xt(t.shape,t.dtype,r)}checkNumericalProblems(t){if(t!=null)for(let e=0;e0}time(t){return Jt(this,null,function*(){let e=this.activeTimers,r=[],i=!1;this.programTimersStack==null?(this.programTimersStack=r,i=!0):this.activeTimers.push(r),this.activeTimers=r,t();let o=R.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),s=R.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=e,i&&(this.programTimersStack=null);let a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let l=yield Promise.all(o);a.kernelMs=R.sum(l),a.getExtraProfileInfo=()=>l.map((c,u)=>({name:s[u],ms:c})).map(c=>`${c.name}: ${c.ms}`).join(", ")}else a.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,a})}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:R.now(),endMs:null}}endTimer(t){return ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=R.now(),t)}getQueryTime(t){return Jt(this,null,function*(){if(ot().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(t);let e=t;return e.endMs-e.startMs})}disposeData(t,e=!1){if(this.pendingDisposal.has(t))return!1;if(!this.texData.has(t))return!0;if(e?this.texData.get(t).refCount=0:this.texData.get(t).refCount--,!e&&this.texData.get(t).refCount>0)return!1;if(this.pendingRead.has(t))return this.pendingDisposal.add(t),this.pendingDeletes++,!1;this.releaseGPUData(t);let{complexTensorInfos:r}=this.texData.get(t);return r!=null&&(this.disposeData(r.real.dataId,e),this.disposeData(r.imag.dataId,e)),this.texData.delete(t),!0}releaseGPUData(t){let{texture:e,dtype:r,texShape:i,usage:o,isPacked:s,slice:a}=this.texData.get(t),l=a&&a.origDataId||t,c=this.dataRefCount.get(l);c>1?this.dataRefCount.set(l,c-1):(this.dataRefCount.delete(l),e!=null&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(e,i,o,s)));let u=this.texData.get(t);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(t){return this.uploadToGPU(t),this.texData.get(t).texture}getDataInfo(t){return this.texData.get(t)}shouldExecuteOnCPU(t,e=uY){return ot().getBool("WEBGL_CPU_FORWARD")&&t.every(r=>this.texData.get(r.dataId).texture==null&&R.sizeFromShape(r.shape)0&&R.isString(r[0])){let o=r.map(s=>R.encodeString(s));i=this.write(o,t,e)}else i=this.write(r,t,e);return this.texData.get(i).usage=null,{dataId:i,shape:t,dtype:e}}makeOutput(t,e,r){let{dataId:i}=this.makeTensorInfo(t,e,r);return ro().makeTensorFromDataId(i,t,e,this)}unpackTensor(t){let e=new G1(t.shape);return this.runWebGLProgram(e,[t],t.dtype)}packTensor(t){let e=new U1(t.shape),r=!0;return this.runWebGLProgram(e,[t],t.dtype,null,r)}packedReshape(t,e){let r=[$o(t.shape),...Uo(t.shape)],i={dtype:t.dtype,shape:r,dataId:t.dataId},o=[$o(e),...Uo(e)],s=new rc(o,r),a=!0,l=this.runWebGLProgram(s,[i],t.dtype,null,a);return{dataId:l.dataId,shape:e,dtype:l.dtype}}decode(t){let e=this.texData.get(t),{isPacked:r,shape:i,dtype:o}=e,s=R1(i),a;r?a=new D1(s):a=new L1(s);let l=!0,c=this.runWebGLProgram(a,[{shape:s,dtype:o,dataId:t}],o,null,l);return{dtype:o,shape:i,dataId:c.dataId}}runWebGLProgram(t,e,r,i,o=!1){let s=this.makeTensorInfo(t.outputShape,r),a=this.texData.get(s.dataId);if(t.packedOutput&&(a.isPacked=!0),t.outPackingScheme===Vo.DENSE){let x=Ho(t.outputShape);a.texShape=x.map(g=>g*2)}if(t.outTexUsage!=null&&(a.usage=t.outTexUsage),R.sizeFromShape(s.shape)===0)return a.values=R.getTypedArrayFromDType(s.dtype,0),s;let l=[],c=e.map(x=>{if(x.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let g=this.texData.get(x.dataId);if(g.texture==null){if(!t.packedInputs&&R.sizeFromShape(x.shape)<=ot().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:x.shape,texData:null,isUniform:!0,uniformValues:g.values};t.packedInputs&&(g.isPacked=!0,g.shape=x.shape)}else if(!!g.isPacked!=!!t.packedInputs)x=g.isPacked?this.unpackTensor(x):this.packTensor(x),l.push(x),g=this.texData.get(x.dataId);else if(g.isPacked&&!sa(g.shape,x.shape)){let v=x,b=x.shape;x.shape=g.shape,x=this.packedReshape(x,b),l.push(x),g=this.texData.get(x.dataId),v.shape=b}return this.uploadToGPU(x.dataId),{shape:x.shape,texData:g,isUniform:!1}});this.uploadToGPU(s.dataId);let u={shape:s.shape,texData:a,isUniform:!1},h=QP(t,c,u),p=this.getAndSaveBinary(h,()=>ZP(this.gpgpu,t,c,u)),d=this.activeTimers!=null,f;d&&(f=this.startTimer()),JP(this.gpgpu,p,c,u,i),l.forEach(x=>this.disposeIntermediateTensorInfo(x)),d&&(f=this.endTimer(f),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(f)}));let m=ot().get("WEBGL_FLUSH_THRESHOLD");if(m>0){let x=R.now();x-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=x)}if(!ot().getBool("WEBGL_LAZILY_UNPACK")&&a.isPacked&&o===!1){let x=this.unpackTensor(s);return this.disposeIntermediateTensorInfo(s),x}return s}compileAndRun(t,e,r,i,o=!1){return r=r||e[0].dtype,this.runWebGLProgram(t,e,r,i,o)}getAndSaveBinary(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(ot().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=MA(()=>{if(!ot().get("WEBGL_RENDER_FLOAT32_ENABLED")){let t=ot().getBool("DEBUG");ot().set("DEBUG",!1);let e=this.abs(h_(1e-8)).dataSync()[0];if(ot().set("DEBUG",t),e>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?aY:lY}uploadToGPU(t){let e=this.texData.get(t),{shape:r,dtype:i,values:o,texture:s,usage:a,isPacked:l}=e;if(s!=null)return;let c=this.activeTimers!=null,u;c&&(u=R.now());let h=e.texShape;if(h==null&&(h=SP(r,l),e.texShape=h),o!=null){let p=R1(r),d,f=h[1],m=h[0],x=o instanceof Uint8Array;l?([f,m]=Ei(h[0],h[1]),d=new B1(p,[m,f],x)):d=new O1(p,[m,f],x);let g=this.makeTensorInfo([m,f],i);x?this.texData.get(g.dataId).usage=Pn.PIXELS:this.texData.get(g.dataId).usage=Pn.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),f,m,o);let v=!0,b=this.runWebGLProgram(d,[g],i,null,v),y=this.texData.get(b.dataId);e.texture=y.texture,e.texShape=y.texShape,e.isPacked=y.isPacked,e.usage=y.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(b.dataId),e.values=null,c&&(this.uploadWaitMs+=R.now()-u)}else{let p=this.acquireTexture(h,a,i,l);e.texture=p}}convertAndCacheOnCPU(t,e){let r=this.texData.get(t),{dtype:i}=r;return this.releaseGPUData(t),e!=null&&(r.values=dY(e,i)),r.values}acquireTexture(t,e,r,i){if(this.numBytesInGPU+=this.computeBytes(t,r),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${o} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(t,e,i)}computeBytes(t,e){return t[0]*t[1]*R.bytesPerElement(e)}};ca.nextDataId=0;function dY(n,t){if(t==="float32"||t==="complex64")return n;if(t==="int32"||t==="bool"){let e=t==="int32"?new Int32Array(n.length):new Uint8Array(n.length);for(let r=0;rnew ca,2);var q1=` + if (isnan(a)) return a; + if (isnan(b)) return b; +`;var vr=class{constructor(t,e,r){this.variableNames=["A","B"],this.outputShape=F.assertAndGetBroadcastShape(e,r),this.userCode=` + float binaryOperation(float a, float b) { + ${t} + } + + void main() { + float a = getAAtOutCoords(); + float b = getBAtOutCoords(); + setOutput(binaryOperation(a, b)); + } + `}};var Wo=` + result.r = isNaN.r > 0. ? NAN : result.r; + result.g = isNaN.g > 0. ? NAN : result.g; + result.b = isNaN.b > 0. ? NAN : result.b; + result.a = isNaN.a > 0. ? NAN : result.a; +`;var Or=class{constructor(t,e,r,i=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=F.assertAndGetBroadcastShape(e,r);let o=this.outputShape.length,s="";if(i)if(o===0||R.sizeFromShape(this.outputShape)===1)s=` + result.y = 0.; + result.z = 0.; + result.w = 0.; + `;else if(s=` + ${ne(o)} coords = getOutputCoords(); + `,o===1)s+=` + result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y; + result.z = 0.; + result.w = 0.; + `;else{let l=Oe("coords",o);s+=` + bool nextRowOutOfBounds = + (${l[o-2]} + 1) >= ${this.outputShape[o-2]}; + bool nextColOutOfBounds = + (${l[o-1]} + 1) >= ${this.outputShape[o-1]}; + result.y = nextColOutOfBounds ? 0. : result.y; + result.z = nextRowOutOfBounds ? 0. : result.z; + result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; + `}this.userCode=` + vec4 binaryOperation(vec4 a, vec4 b) { + ${t} + } + + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + + vec4 result = binaryOperation(a, b); + ${s} + + setOutput(result); + } + `}};function Be(n){let{inputs:t,backend:e}=n,{x:r}=t;return e.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var B6={kernelName:Do,backendName:"webgl",kernelFunc:Be};function tr(n){let{inputs:t,backend:e}=n,{real:r,imag:i}=t,o=e.makeTensorInfo(r.shape,"complex64"),s=e.texData.get(o.dataId),a=Be({inputs:{x:r},backend:e}),l=Be({inputs:{x:i},backend:e});return s.complexTensorInfos={real:a,imag:l},o}var V6={kernelName:Il,backendName:"webgl",kernelFunc:tr};var uw="return (a < 0.) ? b * a : a;",hw=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`;function fY(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{alpha:o}=r,s=e.makeTensorInfo([],"float32",R.createScalarValue(o,"float32")),a=ot().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Or(hw,i.shape,s.shape):new vr(uw,i.shape,s.shape),l=e.runWebGLProgram(a,[i,s],i.dtype);return e.disposeIntermediateTensorInfo(s),l}var H6={kernelName:kl,backendName:"webgl",kernelFunc:fY};var pw="return (a < 0.) ? b * a : a;",dw=` + vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); + return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); +`;function mY(n){let{inputs:t,backend:e}=n,{x:r,alpha:i}=t,o=ot().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Or(dw,r.shape,i.shape):new vr(pw,r.shape,i.shape);return e.runWebGLProgram(o,[r,i],r.dtype)}var $6={kernelName:Pl,backendName:"webgl",kernelFunc:mY};var X1="if (isnan(x)) return x;",U6=` + if (isnan(a)) return a; + if (isnan(b)) return b; +`,W6=` + result.r = isNaN.r > 0. ? NAN : result.r; + result.g = isNaN.g > 0. ? NAN : result.g; + result.b = isNaN.b > 0. ? NAN : result.b; + result.a = isNaN.a > 0. ? NAN : result.a; +`;function Ot({opSnippet:n,packedOpSnippet:t,cpuKernelImpl:e,dtype:r}){return({inputs:i,backend:o})=>{let{x:s}=i,a=o,l=r||s.dtype;if(a.shouldExecuteOnCPU([s])&&e!=null){let h=a.texData.get(s.dataId),p=e(h.values,l);return a.makeTensorInfo(s.shape,l,p)}let c=ot().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return c?u=new Fr(s.shape,t):u=new jn(s.shape,n),a.runWebGLProgram(u,[s],l)}}function me({opSnippet:n,packedOpSnippet:t,checkOutOfBounds:e=!1,supportsComplex:r=!1,cpuKernelImpl:i,dtype:o}){return({inputs:s,backend:a})=>{let{a:l,b:c}=s,u=a;if(r&&l.dtype==="complex64"){let f=u.texData.get(l.dataId),m=u.texData.get(c.dataId),[x,g]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(b=>{let[y,_]=b,S={dataId:y.dataId,dtype:y.dtype,shape:l.shape},E={dataId:_.dataId,dtype:_.dtype,shape:c.shape},M=new vr(n,l.shape,c.shape);return u.runWebGLProgram(M,[S,E],on(y.dtype,_.dtype))}),v=tr({inputs:{real:x,imag:g},backend:u});return u.disposeIntermediateTensorInfo(x),u.disposeIntermediateTensorInfo(g),v}let h=o||on(l.dtype,c.dtype);if(u.shouldExecuteOnCPU([l,c])&&i!=null){let f=u.texData.get(l.dataId),m=u.texData.get(c.dataId),[x,g]=i(l.shape,c.shape,f.values,m.values,h),v=u.makeTensorInfo(g,h),b=u.texData.get(v.dataId);return b.values=x,v}let p=ot().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,d;return p?d=new Or(t,l.shape,c.shape,e):d=new vr(n,l.shape,c.shape),u.runWebGLProgram(d,[l,c],h)}}function Go(n,t=!1){if(n==="linear")return t?D6:k6;if(n==="relu")return t?F6:P6;if(n==="elu")return t?z6:R6;if(n==="relu6")return t?O6:N6;if(n==="prelu")return t?dw:pw;if(n==="leakyrelu")return t?hw:uw;throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`)}var ic=class{constructor(t,e,r,i=!1,o=!1,s=!1,a=null,l=!1,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;let u=i?t[1]:t[2],h=Math.ceil(u/2),p=i?"i * 2, rc.y":"rc.y, i * 2",d=o?"rc.z, i * 2":"i * 2, rc.z",f=i?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=o?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],x="",g="";a&&(l?x=`vec4 activation(vec4 a) { + vec4 b = getPreluActivationWeightsAtOutCoords(); + ${a} + }`:c?x=`vec4 activation(vec4 a) { + vec4 b = getLeakyreluAlphaAtOutCoords(); + ${a} + }`:x=`vec4 activation(vec4 x) { + ${a} + }`,g="result = activation(result);");let v=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let b="rc.x",y="rc.x";t[0]`The new shape (${l}) has ${c} elements and the old shape (${i.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);let u=s.texData.get(i.dataId);return u.isPacked&&!sa(i.shape,l)&&!(u.texture!==null&&sa(u.shape,l))?q6(i,l,s):(s.incRef(i.dataId),{dataId:i.dataId,shape:l,dtype:i.dtype})}var X6={kernelName:Nl,backendName:"webgl",kernelFunc:Tt};var yp=class{constructor(t,e){this.variableNames=["x"];let{windowSize:r,batchSize:i,inSize:o,outSize:s}=t;this.outputShape=[i,s];let a=Math.floor(r/4)*4,l=r%4,c="sumValue += dot(values, ones);";if(e!=null){let h=1/e;c=`sumValue += dot(values * ${R.isInt(h)?h.toPrecision(2):h}, ones);`}let u="";o%r>0&&(u=` + if (inIdx < 0 || inIdx >= ${o}) { + return 0.0; + } + `),this.userCode=` + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + ${u} + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${r}; + + float sumValue = 0.0; + + for (int i = 0; i < ${a}; i += 4) { + int inIdx = inOffset + i; + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + ${c} + } + + int inIdx = inOffset + ${a}; + if (${l===1}) { + vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0); + + ${c} + } else if (${l===2}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), 0.0, 0.0); + + ${c} + } else if (${l===3}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), 0.0); + + ${c} + } + setOutput(sumValue); + } + `}};var K1=class{constructor(t,e){this.variableNames=["x"];let{windowSize:r,batchSize:i,inSize:o,outSize:s}=t;this.outputShape=[i,s];let a="0.0",l="";e==="prod"?a="1.0":e==="min"?(a="1.0 / 1e-20",l="min"):e==="max"&&(a="-1.0 / 1e-20",l="max");let c=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="sum"?c="sumValue":e==="prod"?c="prodValue":e==="all"?c="allValue":e==="any"&&(c="anyValue");let u=Math.floor(r/4)*4,h=r%4,p=` + if (${e==="sum"}) { + sumValue += dot(values, ones); + } else if (${e==="prod"}) { + vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]); + prodValue *= tmp[0] * tmp[1]; + } else { + minMaxValue = ${l}(values, minMaxValue); + } + `,d="vec4";e==="all"?(a="1.0",p=` + bool reducedAllValue = all(values); + float floatedReducedAllValue = float(reducedAllValue); + allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); + `,d="bvec4"):e==="any"&&(a="0.0",p=` + bool reducedAnyValue = any(values); + float floatedReducedAnyValue = float(reducedAnyValue); + anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); + `,d="bvec4");let f="";o%r>0&&(f=` + if (inIdx < 0 || inIdx >= ${o}) { + return initializationValue; + } + `),this.userCode=` + const float initializationValue = ${a}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float getValue(int batch, int inIdx) { + ${f} + return getX(batch, inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${r}; + + vec4 minMaxValue = vec4(${a}); + float prodValue = 1.0; + float sumValue = 0.0; + float allValue = 1.0; + float anyValue = 0.0; + + for (int i = 0; i < ${u}; i += 4) { + int inIdx = inOffset + i; + ${d} values = ${d}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + ${p} + } + + int inIdx = inOffset + ${u}; + if (${h===1}) { + ${d} values = ${d}( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + ${p} + } else if (${h===2}) { + ${d} values = ${d}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + ${p} + } else if (${h===3}) { + ${d} values = ${d}( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + ${p} + } + setOutput(${c}); + } + `}};function xY(n){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let e=t.length?t[t.length-1].outSize:n[1],r=F.computeOptimalWindowSize(e);t.push({inSize:e,windowSize:r,outSize:Math.ceil(e/r)})}return t}function cr(n,t,e,r){let i=xY(n.shape),o=n;for(let s=0;s6)throw Error(`Transpose for rank ${t} is not yet supported`);let e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let i=0;i6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let i=ne(this.rank),o=lw("rc",this.rank),s=new Array(this.rank);for(let u=0;u=2&&u>=2&&b,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${x}).`);let _=(g>v?n.shape.slice(0,-2):t.shape.slice(0,-2)).concat([d,f]);R.assert(h===p,()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${n.shape} and ${t.shape} and transposeA=${e} and transposeB=${r} must match.`);let S=e?[g,h,d]:[g,d,h],E=r?[v,f,p]:[v,p,f],M=Tt({inputs:{x:n},backend:i,attrs:{shape:S}}),P=Tt({inputs:{x:t},backend:i,attrs:{shape:E}}),D=[M,P],w=Math.max(g,v),I=e?M.shape[1]:M.shape[2],N=o!=null,L=s!=null,O=l==="leakyrelu",z=l!=null?Go(l,!0):null,V=N||L||O||z!=null,$;if((d===1||f===1)&&I>mw&&V===!1){let W=M,K=P;e&&(W=Pe({inputs:{x:M},backend:i,attrs:{perm:[0,2,1]}}),D.push(W)),r&&(K=Pe({inputs:{x:P},backend:i,attrs:{perm:[0,2,1]}}),D.push(K));let Z=f!==1,Y=f===1,tt=W;Z&&(tt=Tt({inputs:{x:W},backend:i,attrs:{shape:[w,I,1]}}),D.push(tt));let q=f===1?2:1,et=K;Y&&(et=Tt({inputs:{x:K},backend:i,attrs:{shape:[w,1,I]}}),D.push(et));let rt=vp({inputs:{a:tt,b:et},backend:i});$=ua({inputs:{x:rt},backend:i,attrs:{axis:q,keepDims:!0}}),D.push(rt)}else{let W=on(n.dtype,t.dtype),K=new ic(S,E,[w,d,f],e,r,N,z,L,O),Z=[M,P];if(o!=null&&Z.push(o),L&&Z.push(s),O){let Y=i.makeTensorInfo([],"float32",R.createScalarValue(a,"float32"));Z.push(Y),D.push(Y)}$=i.runWebGLProgram(K,Z,W)}let X=Tt({inputs:{x:$},backend:i,attrs:{shape:_}});D.push($);for(let W of D)i.disposeIntermediateTensorInfo(W);return X}function yY(n){let{inputs:t,backend:e,attrs:r}=n,{a:i,b:o,bias:s,preluActivationWeights:a}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:h}=r;return ha({a:i,b:o,transposeA:l,transposeB:c,backend:e,bias:s,preluActivationWeights:a,leakyreluAlpha:h,activation:u})}var J6={kernelName:Kg,backendName:"webgl",kernelFunc:yY};var Q6="return abs(x);";function bY(n){let{inputs:t,backend:e}=n,{x:r}=t;if(e.shouldExecuteOnCPU([r])&&r.dtype!=="complex64"){let o=e.texData.get(r.dataId),s=$1(o.values);return e.makeTensorInfo(r.shape,r.dtype,s)}let i;return ot().getBool("WEBGL_PACK_UNARY_OPERATIONS")?i=new Fr(r.shape,Q6):i=new jn(r.shape,Q6),e.runWebGLProgram(i,[r],r.dtype)}var tN={kernelName:ym,backendName:"webgl",kernelFunc:bY};var _Y=pn+` + if (abs(x) > 1.) { + return NAN; + } + return acos(x); +`,wY=Ot({opSnippet:_Y}),eN={kernelName:sh,backendName:"webgl",kernelFunc:wY};var SY=pn+` + if (x < 1.0) return NAN; +return log(x + sqrt(x * x - 1.0));`,CY=Ot({opSnippet:SY}),nN={kernelName:ah,backendName:"webgl",kernelFunc:CY};var rN="return a + b;",MY=me({opSnippet:rN,packedOpSnippet:rN,supportsComplex:!0,cpuKernelImpl:t6}),iN={kernelName:Us,backendName:"webgl",kernelFunc:MY};var J1=class{constructor(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map((o,s)=>`T${s}`);let r=[];this.variableNames.forEach(o=>{r.push(`float v${o} = get${o}AtOutCoords();`)});let i=this.variableNames.map(o=>`v${o}`).join(" + ");this.userCode=` + void main() { + ${r.join(` + `)} + + float result = ${i}; + setOutput(result); + } + `}};var Q1=class{constructor(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((o,s)=>`T${s}`);let r=[];this.variableNames.forEach(o=>{r.push(`vec4 v${o} = get${o}AtOutCoords();`)});let i=this.variableNames.map(o=>`v${o}`).join(" + ");this.userCode=` + void main() { + ${r.join(` + `)} + + vec4 result = ${i}; + setOutput(result); + } + `}};function t0(n){let{inputs:t,backend:e}=n,r=t;if(r.length===1)return Be({inputs:{x:r[0]},backend:e});if(r.length>ot().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(r.length/2),c=t0({inputs:r.slice(0,l),backend:e}),u=t0({inputs:r.slice(l),backend:e});return t0({inputs:[c,u],backend:e})}let i=r.map(l=>l.dtype).reduce((l,c)=>on(l,c)),o=r.map(l=>l.shape),a=ot().getBool("WEBGL_PACK")?new Q1(r[0].shape,o):new J1(r[0].shape,o);return e.runWebGLProgram(a,r,i)}var oN={kernelName:bm,backendName:"webgl",kernelFunc:t0};function EY(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o,keepDims:s}=r,a=i.shape.length,l=R.parseAxisParam(o,i.shape),c=l,u=F.getAxesPermutation(c,a),h=i;u!=null&&(h=Pe({inputs:{x:i},backend:e,attrs:{perm:u}}),c=F.getInnerMostAxes(c.length,a)),F.assertAxesAreInnerMostDims("all",c,a);let[p,d]=F.computeOutAndReduceShapes(h.shape,c),f=R.sizeFromShape(d),m=Tt({inputs:{x:h},backend:e,attrs:{shape:[-1,f]}}),x=cr(m,m.dtype,"all",e),g;if(s){let v=F.expandShapeToKeepDim(p,l);g=Tt({inputs:{x},backend:e,attrs:{shape:v}})}else g=Tt({inputs:{x},backend:e,attrs:{shape:p}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(x),u!=null&&e.disposeIntermediateTensorInfo(h),g}var sN={kernelName:_m,backendName:"webgl",kernelFunc:EY};function TY(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o,keepDims:s}=r,a=i.shape.length,l=R.parseAxisParam(o,i.shape),c=l,u=F.getAxesPermutation(c,a),h=i;u!=null&&(h=Pe({inputs:{x:i},backend:e,attrs:{perm:u}}),c=F.getInnerMostAxes(c.length,a)),F.assertAxesAreInnerMostDims("any",c,a);let[p,d]=F.computeOutAndReduceShapes(h.shape,c),f=R.sizeFromShape(d),m=Tt({inputs:{x:h},backend:e,attrs:{shape:[-1,f]}}),x=cr(m,m.dtype,"any",e),g;if(s){let v=F.expandShapeToKeepDim(p,l);g=Tt({inputs:{x},backend:e,attrs:{shape:v}})}else g=Tt({inputs:{x},backend:e,attrs:{shape:p}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(x),u!=null&&e.disposeIntermediateTensorInfo(h),g}var aN={kernelName:wm,backendName:"webgl",kernelFunc:TY};var e0=class{constructor(t,e,r){this.variableNames=["A"];let{windowSize:i,batchSize:o,outSize:s}=t;r||this.variableNames.push("bestIndicesA"),this.outputShape=[o,s];let a=e==="max"?">":"<",l=r?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = outIdx * ${i}; + + int bestIndex = inOffset; + float bestValue = getA(batch, bestIndex); + + for (int i = 0; i < ${i}; i++) { + int inIdx = ${l}; + float candidate = getA(batch, inIdx); + if (candidate ${a} bestValue) { + bestValue = candidate; + bestIndex = inIdx; + } + } + setOutput(float(bestIndex)); + } + `}};var n0=class{constructor(t,e,r,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,R.assert(t.length>2,()=>`Packed arg${r.charAt(0).toUpperCase()+r.slice(1)} supports only inputs with rank above 2.`);let o=t[t.length-1],s=Math.ceil(o/e);this.outputShape=t.slice(0,-1),s>1&&this.outputShape.push(s),i||this.variableNames.push("bestIndicesA");let a=this.outputShape,l=a.length,c=ne(l),u=Oe("coords",l),h,p;if(s===1){p=l+1;let M=ne(p);h=` + ${M} sourceLocR = ${M}(${u.join()}, 0); + ++${u[l-1]}; + ${M} sourceLocG = ${M}(${u.join()}, 0); + ++${u[l-2]}; + ${M} sourceLocA = ${M}(${u.join()}, 0); + --${u[l-1]}; + ${M} sourceLocB = ${M}(${u.join()}, 0); + --${u[l-2]};`}else p=l,h=` + ${c} sourceLocR = coords; + ++${u[l-1]}; + ${c} sourceLocG = coords; + ++${u[l-2]}; + ${c} sourceLocA = coords; + --${u[l-1]}; + ${c} sourceLocB = coords; + --${u[l-2]};`;let d=["x","y","z","w","u","v"].slice(0,p),f="."+d[p-1],m=d.map(M=>"int "+M),x=Oe("sourceLocR",p-1).concat("inIdx.r"),g=Oe("sourceLocG",p-1).concat("inIdx.g"),v=Oe("sourceLocB",p-1).concat("inIdx.b"),b=Oe("sourceLocA",p-1).concat("inIdx.a"),y=r==="max"?"greaterThan":"lessThan",_=i?"":` + inIdx = round(vec4(getBestIndicesAChannel(${x.join()}), + getBestIndicesAChannel(${g.join()}), + getBestIndicesAChannel(${v.join()}), + getBestIndicesAChannel(${b.join()})));`,S=`vec4( + getAChannel(${x.join()}), + hasNextCol ? getAChannel(${g.join()}) : 0., + hasNextRow ? getAChannel(${v.join()}) : 0., + hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,E=i?"":` + float getBestIndicesAChannel(${m.join()}) { + return getChannel(getBestIndicesA(${d.join()}), + vec2(${d.slice(-2).join()})); + }`;this.userCode=` + float getAChannel(${m.join()}) { + return getChannel(getA(${d.join()}), + vec2(${d.slice(-2).join()})); + } + ${E} + void main() { + ${c} coords = getOutputCoords(); + bool hasNextCol = ${u[l-1]} < ${a[l-1]-1}; + bool hasNextRow = ${u[l-2]} < ${a[l-2]-1}; + ${h} + ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f}, + sourceLocB${f}, sourceLocA${f}) * ${e}; + ivec4 inIdx = srcIdx; + vec4 bestIndex = vec4(inIdx); + vec4 bestValue = ${S}; + + for (int i = 0; i < ${e}; i++) { + inIdx = srcIdx; + ${_} + vec4 candidate = ${S}; + bvec4 nan = isnan(candidate); + bvec4 replace = bvec4( + vec4(${y}(candidate, bestValue)) * (vec4(1.0) - vec4(nan))); + + bestValue = vec4(replace.x ? candidate.x : bestValue.x, + replace.y ? candidate.y : bestValue.y, + replace.z ? candidate.z : bestValue.z, + replace.w ? candidate.w : bestValue.w); + bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace)); + srcIdx++; + } + setOutput(bestIndex); + } + `}};function lN(n,t,e,r=null){let i=t.shape[0],o=t.shape[1];r!=null&&(i=r.shape[0],o=r.shape[1]);let s=F.computeOptimalWindowSize(o),a={windowSize:s,inSize:o,batchSize:i,outSize:Math.ceil(o/s)},l=new e0(a,e,r==null),c=[t];r!=null&&c.push(r);let u=n.runWebGLProgram(l,c,"int32");if(u.shape[1]===1)return u;let h=lN(n,t,e,u);return n.disposeIntermediateTensorInfo(u),h}function cN(n,t,e,r=null){let i=r!=null?r.shape:t.shape,o=i[i.length-1],s=F.computeOptimalWindowSize(o),a=new n0(i,s,e,r==null),l=r==null?[t]:[t,r],c=n.runWebGLProgram(a,l,"int32");if(c.shape.length===t.shape.length){let u=cN(n,t,e,c);return n.disposeIntermediateTensorInfo(c),u}return c}function r0(n,t,e,r){let i=[e];if(F.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),i,t.shape.length),!ot().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let o=[],[s,a]=F.computeOutAndReduceShapes(t.shape,i),l=R.sizeFromShape(a),c=Tt({inputs:{x:t},backend:n,attrs:{shape:[-1,l]}});o.push(c);let u=lN(n,c,r);o.push(u);let h=Tt({inputs:{x:u},backend:n,attrs:{shape:s}});return o.forEach(p=>n.disposeIntermediateTensorInfo(p)),h}return cN(n,t,r)}function AY(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o}=r,s=R.parseAxisParam(o,i.shape),a=F.getAxesPermutation(s,i.shape.length),l=i,c=[];a!=null&&(l=Pe({inputs:{x:i},backend:e,attrs:{perm:a}}),c.push(l),s=F.getInnerMostAxes(s.length,l.shape.length)),F.assertAxesAreInnerMostDims("argMax",[s[0]],l.shape.length);let u=r0(e,l,s[0],"max");return c.forEach(h=>e.disposeIntermediateTensorInfo(h)),u}var uN={kernelName:Sm,backendName:"webgl",kernelFunc:AY};function IY(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o}=r,s=R.parseAxisParam(o,i.shape),a=F.getAxesPermutation(s,i.shape.length),l=i,c=[];a!=null&&(l=Pe({inputs:{x:i},backend:e,attrs:{perm:a}}),c.push(l),s=F.getInnerMostAxes(s.length,l.shape.length)),F.assertAxesAreInnerMostDims("argMin",[s[0]],l.shape.length);let u=r0(e,l,s[0],"min");return c.forEach(h=>e.disposeIntermediateTensorInfo(h)),u}var hN={kernelName:Cm,backendName:"webgl",kernelFunc:IY};var kY=pn+` + if (abs(x) > 1.) { + return NAN; + } + return asin(x); +`,RY=Ot({opSnippet:kY}),pN={kernelName:lh,backendName:"webgl",kernelFunc:RY};var PY=pn+"return log(x + sqrt(x * x + 1.0));",NY=Ot({opSnippet:PY}),dN={kernelName:ch,backendName:"webgl",kernelFunc:NY};var LY=pn+` + return atan(x); +`,DY=Ot({opSnippet:LY}),fN={kernelName:uh,backendName:"webgl",kernelFunc:DY};var zY=U6+` + return atan(a, b); +`,FY=` + vec4 result = atan(a, b); + vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); + `+W6+` + return result; +`,OY=me({opSnippet:zY,packedOpSnippet:FY}),mN={kernelName:ph,backendName:"webgl",kernelFunc:OY};var BY=pn+` + if ((x < -1.0) || (x > 1.0)) return NAN; +return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,VY=Ot({opSnippet:BY}),gN={kernelName:hh,backendName:"webgl",kernelFunc:VY};var Jr=class{constructor(t,e,r,i=!1,o=!1){if(this.variableNames=["x"],e==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let s=t.filterWidth,a=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,u=t.dilationWidth,h=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=t.padInfo.top,f=t.padInfo.left;this.outputShape=t.outShape;let m=e==="avg",x=`((batch * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + d`,g=`(xR * ${t.inWidth} + xC) * ${t.inChannels} + d`,v="0.0";if(m||(v="-1.0 / 1e-20"),r){let M=">=";this.userCode=` + const ivec2 strides = ivec2(${a}, ${l}); + const ivec2 pads = ivec2(${d}, ${f}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d = coords[3]; + + ivec2 xRCCorner = coords.yz * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // max/min x(?, ?, d) to get y(yR, yC, d). + // ? = to be determined + float minMaxValue = 0.0; + float minMaxValueFound = 0.0; + int minMaxPosition = 0; + float avgValue = 0.0; + + for (int wR = 0; wR < ${h}; + wR += ${c}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${p}; + wC += ${u}) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + float value = getX(batch, xR, xC, d); + + // If a min / max value has already been found, use it. If not, + // use the current value. + float currMinMaxValue = mix( + value, minMaxValue, minMaxValueFound); + if (value ${M} currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = ${i?o?x:g:`wR * ${p} + wC`}; + } + } + } + setOutput(float(minMaxPosition)); + } + `;return}let b="max",y=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(y="avgValue / count");let _=Math.floor(s/4)*4,S=s%4,E=` + if (${m}) { + avgValue += dot(values, ones); + } else { + minMaxValue = ${b}(values, minMaxValue); + } + `;this.userCode=` + const ivec2 strides = ivec2(${a}, ${l}); + const ivec2 pads = ivec2(${d}, ${f}); + const float initializationValue = ${v}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float count = 0.0; + + float getValue(int batch, int xR, int xC, int d) { + if (xC < 0 || xC >= ${t.inWidth}) { + return initializationValue; + } + count += 1.0; + return getX(batch, xR, xC, d); + } + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d = coords[3]; + + ivec2 xRCCorner = coords.yz * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // max/min x(?, ?, d) to get y(yR, yC, d). + // ? = to be determined + vec4 minMaxValue = vec4(${v}); + float avgValue = 0.0; + count = 0.0; + + for (int wR = 0; wR < ${h}; + wR += ${c}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${_}; wC += 4) { + int xC = xCCorner + wC * ${u}; + + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + getValue(batch, xR, xC + 2 * ${u}, d), + getValue(batch, xR, xC + 3 * ${u}, d) + ); + + ${E} + } + + int xC = xCCorner + ${_}; + if (${S===1}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + initializationValue, + initializationValue, + initializationValue + ); + + ${E} + } else if (${S===2}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + initializationValue, + initializationValue + ); + + ${E} + } else if (${S===3}) { + vec4 values = vec4( + getValue(batch, xR, xC, d), + getValue(batch, xR, xC + ${u}, d), + getValue(batch, xR, xC + 2 * ${u}, d), + initializationValue + ); + + ${E} + } + } + setOutput(${y}); + } + `}},qo=class{constructor(t,e,r,i=!1,o=!1){if(this.variableNames=["x"],e==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let s=t.filterWidth,a=t.strideDepth,l=t.strideHeight,c=t.strideWidth,u=t.dilationDepth,h=t.dilationHeight,p=t.dilationWidth,d=t.effectiveFilterDepth,f=t.effectiveFilterHeight,m=t.effectiveFilterWidth,x=t.padInfo.front,g=t.padInfo.top,v=t.padInfo.left;this.outputShape=t.outShape;let b=e==="avg",y="0.0";if(b||(y="-1.0 / 1e-20"),r){let D=">=";this.userCode=` + const ivec3 strides = + ivec3(${a}, ${l}, ${c}); + const ivec3 pads = ivec3(${x}, ${g}, ${v}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xDCorner = xCorner.x; + int xRCorner = xCorner.y; + int xCCorner = xCorner.z; + + // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch). + // ? = to be determined + float minMaxValue = 0.0; + float minMaxValueFound = 0.0; + int minMaxPosition = 0; + + for (int wD = 0; wD < ${d}; + wD += ${u}) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= ${t.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${f}; + wR += ${h}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${m}; + wC += ${p}) { + int xC = xCCorner + wC; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + float value = getX(batch, xD, xR, xC, ch); + + // If a min / max value has already been found, use it. If not, + // use the current value. + float currMinMaxValue = mix( + value, minMaxValue, minMaxValueFound); + if (value ${D} currMinMaxValue) { + minMaxValue = value; + minMaxValueFound = 1.0; + minMaxPosition = ${i?o?`(((batch * ${t.inDepth} + xD) * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`((xD * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`wD * ${f} * ${m} + + wR * ${m} + wC`}; + } + } + } + } + setOutput(float(minMaxPosition)); + } + `;return}let _="max",S=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(S="avgValue / count");let E=Math.floor(s/4)*4,M=s%4,P=` + if (${b}) { + avgValue += dot(values, ones); + } else { + minMaxValue = ${_}(values, minMaxValue); + } + `;this.userCode=` + const ivec3 strides = + ivec3(${a}, ${l}, ${c}); + const ivec3 pads = ivec3(${x}, ${g}, ${v}); + const float initializationValue = ${y}; + const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); + + float count = 0.0; + + float getValue(int batch, int xD, int xR, int xC, int ch) { + if (xC < 0 || xC >= ${t.inWidth}) { + return initializationValue; + } + count += 1.0; + return getX(batch, xD, xR, xC, ch); + } + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xDCorner = xCorner.x; + int xRCorner = xCorner.y; + int xCCorner = xCorner.z; + + // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch). + // ? = to be determined + vec4 minMaxValue = vec4(${y}); + float avgValue = 0.0; + count = 0.0; + + for (int wD = 0; wD < ${d}; + wD += ${u}) { + int xD = xDCorner + wD; + + if (xD < 0 || xD >= ${t.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${f}; + wR += ${h}) { + int xR = xRCorner + wR; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${E}; wC += 4) { + int xC = xCCorner + wC * ${p}; + + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${p}, ch), + getValue(batch, xD, xR, xC + 2 * ${p}, ch), + getValue(batch, xD, xR, xC + 3 * ${p}, ch) + ); + + ${P} + } + + int xC = xCCorner + ${E}; + if (${M===1}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + initializationValue, + initializationValue, + initializationValue + ); + + ${P} + } else if (${M===2}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${p}, ch), + initializationValue, + initializationValue + ); + + ${P} + } else if (${M===3}) { + vec4 values = vec4( + getValue(batch, xD, xR, xC, ch), + getValue(batch, xD, xR, xC + ${p}, ch), + getValue(batch, xD, xR, xC + 2 * ${p}, ch), + initializationValue + ); + + ${P} + } + } + setOutput(${S}); + } + } + `}};function HY(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t;Ti(i,"avgPool");let{filterSize:o,strides:s,pad:a,dimRoundingMode:l}=r,c=1;R.assert(F.eitherStridesOrDilationsAreOne(s,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${c}'`);let u=F.computePool2DInfo(i.shape,o,s,c,a,l);if(u.filterWidth===1&&u.filterHeight===1&&R.arraysEqual(u.inShape,u.outShape))return Be({inputs:{x:i},backend:e});let h=new Jr(u,"avg",!1);return e.runWebGLProgram(h,[i],"float32")}var xN={kernelName:Mm,backendName:"webgl",kernelFunc:HY};function $Y(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{filterSize:o,strides:s,pad:a,dimRoundingMode:l,dataFormat:c}=r,u=[1,1,1],h=F.computePool3DInfo(i.shape,o,s,u,a,l,c),p=new qo(h,"avg",!1);return e.runWebGLProgram(p,[i],"float32")}var vN={kernelName:Tm,backendName:"webgl",kernelFunc:$Y};var i0=class{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;let e=t.filterHeight,r=t.filterWidth,i=t.strideHeight,o=t.strideWidth,s=t.dilationHeight,a=t.dilationWidth,l=t.effectiveFilterHeight,c=t.effectiveFilterWidth,u=l-1-t.padInfo.top,h=c-1-t.padInfo.left,p=1/(e*r);this.userCode=` + const ivec2 pads = ivec2(${u}, ${h}); + const float avgMultiplier = float(${p}); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + + ivec2 dyRCCorner = coords.yz - pads; + int dyRCorner = dyRCCorner.x; + int dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${l}; + wR += ${s}) { + float dyR = float(dyRCorner + wR) / ${i}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${c}; + wC+= ${a}) { + float dyC = float(dyCCorner + wC) / ${o}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + + dotProd += dyValue * avgMultiplier; + } + } + setOutput(dotProd); + } + `}},o0=class{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;let e=t.filterDepth,r=t.filterHeight,i=t.filterWidth,o=t.strideDepth,s=t.strideHeight,a=t.strideWidth,l=t.dilationDepth,c=t.dilationHeight,u=t.dilationWidth,h=t.effectiveFilterDepth,p=t.effectiveFilterHeight,d=t.effectiveFilterWidth,f=h-1-t.padInfo.front,m=p-1-t.padInfo.top,x=d-1-t.padInfo.left,g=1/(e*r*i);this.userCode=` + const ivec3 pads = ivec3(${f}, ${m}, ${x}); + const float avgMultiplier = float(${g}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyDCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int wD = 0; wD < ${h}; + wD += ${l}) { + float dyD = float(dyDCorner + wD) / ${o}.0; + + if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < ${p}; + wR += ${c}) { + float dyR = float(dyRCorner + wR) / ${s}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${d}; + wC += ${u}) { + float dyC = float(dyCCorner + wC) / ${a}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + + dotProd += dyValue * avgMultiplier; + } + } + } + setOutput(dotProd); + } + `}};function UY(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,input:o}=t,s=o,{filterSize:a,strides:l,pad:c,dimRoundingMode:u}=r,h=[1,1,1],p=F.computePool3DInfo(s.shape,a,l,h,c,u),d=new o0(p);return e.runWebGLProgram(d,[i],s.dtype)}var yN={kernelName:Am,backendName:"webgl",kernelFunc:UY};function WY(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,input:o}=t,s=o;Ti([i,o],"avgPoolGrad");let{filterSize:a,strides:l,pad:c}=r,u=F.computePool2DInfo(s.shape,a,l,1,c),h=new i0(u);return e.runWebGLProgram(h,[i],s.dtype)}var bN={kernelName:Em,backendName:"webgl",kernelFunc:WY};function GY(n){let{inputs:t,backend:e,attrs:r}=n,{a:i,b:o}=t,{transposeA:s,transposeB:a}=r;return ha({a:i,b:o,transposeA:s,transposeB:a,backend:e})}var _N={kernelName:Al,backendName:"webgl",kernelFunc:GY};var s0=class{constructor(t,e,r,i,o,s){this.outputShape=[],this.variableNames=["x","mean","variance"],F.assertAndGetBroadcastShape(t,e),F.assertAndGetBroadcastShape(t,r);let a="0.0";i!=null&&(F.assertAndGetBroadcastShape(t,i),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let l="1.0";o!=null&&(F.assertAndGetBroadcastShape(t,o),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=` + void main() { + float x = getXAtOutCoords(); + float mean = getMeanAtOutCoords(); + float variance = getVarianceAtOutCoords(); + float offset = ${a}; + float scale = ${l}; + float inv = scale * inversesqrt(variance + float(${s})); + setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); + } + `}};var a0=class{constructor(t,e,r,i,o,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],F.assertAndGetBroadcastShape(t,e),F.assertAndGetBroadcastShape(t,r);let a="vec4(0.0)";i!=null&&(F.assertAndGetBroadcastShape(t,i),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let l="vec4(1.0)";o!=null&&(F.assertAndGetBroadcastShape(t,o),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=` + void main() { + vec4 offset = ${a}; + vec4 scale = ${l}; + + vec4 x = getXAtOutCoords(); + vec4 mean = getMeanAtOutCoords(); + vec4 variance = getVarianceAtOutCoords(); + + vec4 inv = scale * inversesqrt(variance + vec4(${s})); + + setOutput((x - mean) * inv + offset); + } + `}};var jY=({inputs:n,backend:t,attrs:e})=>{let{x:r,mean:i,variance:o,offset:s,scale:a}=n;R.assert(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),R.assert(s==null||i.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),R.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=e;l==null&&(l=.001);let c=[r,i,o],u=null;s!=null&&(u=s.shape,c.push(s));let h=null;a!=null&&(h=a.shape,c.push(a));let p=ot().getBool("WEBGL_PACK_NORMALIZATION")?new a0(r.shape,i.shape,o.shape,u,h,l):new s0(r.shape,i.shape,o.shape,u,h,l);return t.runWebGLProgram(p,c,c[0].dtype)},wN={kernelName:tg,backendName:"webgl",kernelFunc:jY};var l0=class{constructor(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;let e=ne(this.rank),r=`uniform int start[${this.rank}];`,i=qY(this.rank),o,s=t.map((a,l)=>`sourceLoc.${gw[l]} = start[${l}] + coords.${gw[l]};`);o=` + ${e} sourceLoc; + ${e} coords = getOutputCoords(); + ${s.join(` +`)} + `,this.userCode=` + ${r} + void main() { + ${o} + setOutput(getSource(${i})); + } + `}getCustomSetupFunc(t){if(t.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${t.length})`);return(e,r)=>{this.startLoc==null&&(this.startLoc=e.getUniformLocationNoThrow(r,"start"),this.startLoc==null)||e.gl.uniform1iv(this.startLoc,t)}}},gw=["x","y","z","w","u","v"];function qY(n){if(n===1)return"sourceLoc";if(n<=6)return gw.slice(0,n).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}var c0=class{constructor(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;let e=ne(this.rank),r=Oe("coords",this.rank),i=Oe("sourceLoc",this.rank),o=this.rank===1?"sourceLoc":`vec2(${i.slice(-2).join()})`,s=`getChannel(getSource(${i.join()}), ${o})`,a=` + result.x = ${s}; + if (++${r[this.rank-1]} < ${t[this.rank-1]}) { + ++${i[this.rank-1]}; + result.y = ${s}; + --${i[this.rank-1]}; + } + `,l=this.rank===1?"":` + --${r[this.rank-1]}; + if (++${r[this.rank-2]} < ${t[this.rank-2]}) { + ++${i[this.rank-2]}; + result.z = ${s}; + if (++${r[this.rank-1]} < ${t[this.rank-1]}) { + ++${i[this.rank-1]}; + result.w = ${s}; + } + } + `,c=this.rank<=4?`sourceLoc = coords + + ${e}(${t.map((u,h)=>`start[${h}]`).join()});`:t.map((u,h)=>`${i[h]} = ${r[h]} + start[${h}];`).join(` +`);this.userCode=` + uniform int start[${this.rank}]; + void main() { + ${e} coords = getOutputCoords(); + ${e} sourceLoc; + ${c} + vec4 result = vec4(0.); + ${a} + ${l} + setOutput(result); + } + `}getCustomSetupFunc(t){if(t.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${t.length})`);return(e,r)=>{this.startLoc==null&&(this.startLoc=e.getUniformLocationNoThrow(r,"start"),this.startLoc==null)||e.gl.uniform1iv(this.startLoc,t)}}};function XY(n,t,e,r){let i=r.texData.get(n.dataId),o=r.makeTensorInfo(e,n.dtype),s=r.texData.get(o.dataId);Object.assign(s,i),s.refCount=1,s.shape=e,s.dtype=n.dtype;let a=In.computeFlatOffset(t,R.computeStrides(n.shape));i.slice&&(a+=i.slice.flatOffset),s.slice={flatOffset:a,origDataId:i.slice&&i.slice.origDataId||n.dataId};let l=r.dataRefCount.get(s.slice.origDataId)||1;return r.dataRefCount.set(s.slice.origDataId,l+1),o}function ao(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{begin:o,size:s}=r,[a,l]=In.parseSliceParams(i,o,s);if(In.assertParamsValid(i,a,l),R.sizeFromShape(l)===0)return e.makeTensorInfo(l,i.dtype,[]);if(e.shouldExecuteOnCPU([i])||i.dtype==="string"){let h=e.texData.get(i.dataId),p=b6(h.values,a,l,i.shape,i.dtype);return e.makeTensorInfo(l,i.dtype,p)}let{isPacked:c}=e.texData.get(i.dataId),u=In.isSliceContinous(i.shape,a,l);if(c||!u){let h=ot().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new c0(l):new l0(l),p=h.getCustomSetupFunc(a);return e.runWebGLProgram(h,[i],i.dtype,p)}return e.uploadToGPU(i.dataId),XY(i,a,l,e)}var SN={kernelName:Dg,backendName:"webgl",kernelFunc:ao};var KY=n=>{let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{blockShape:o,crops:s}=r;R.assert(i.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let a=o.reduce((v,b)=>v*b),l=F.getReshaped(i.shape,o,a),c=F.getPermuted(l.length,o.length),u=F.getReshapedPermuted(i.shape,o,a),h=F.getSliceBeginCoords(s,o.length),p=F.getSliceSize(u,s,o.length),d=[],f=Tt({inputs:{x:i},backend:e,attrs:{shape:l}}),m=Pe({inputs:{x:f},backend:e,attrs:{perm:c}}),x=Tt({inputs:{x:m},backend:e,attrs:{shape:u}}),g=ao({inputs:{x},backend:e,attrs:{begin:h,size:p}});return d.push(f),d.push(m),d.push(x),d.forEach(v=>e.disposeIntermediateTensorInfo(v)),g},CN={kernelName:Im,backendName:"webgl",kernelFunc:KY};function YY(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,weights:o}=t,{size:s}=r,a=e.readSync(i.dataId),l=e.readSync(o.dataId),c=H1(a,l,o.dtype,o.shape,s);return e.makeTensorInfo([s],o.dtype,c)}var MN={kernelName:km,backendName:"webgl",kernelFunc:YY};var ZY="return float(a != b);",xw=me({opSnippet:ZY,dtype:"bool"}),EN={kernelName:Bh,backendName:"webgl",kernelFunc:xw};function lo(n){let{inputs:t,backend:e}=n,{input:r}=t,i=e.texData.get(r.dataId);return Be({inputs:{x:i.complexTensorInfos.real},backend:e})}var TN={kernelName:Tg,backendName:"webgl",kernelFunc:lo};var JY="return float(int(x));";function AN(n,t){let e=new jn(n.shape,JY),r=t.runWebGLProgram(e,[n],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function vw(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{dtype:o}=r;if(o==="complex64"){if(i.dtype==="complex64")return Be({inputs:{x:i},backend:e});let s=ip(i.shape),a=vw({inputs:{x:i},backend:e,attrs:{dtype:"float32"}}),l=tr({inputs:{real:a,imag:s},backend:e});return s.dispose(),e.disposeIntermediateTensorInfo(a),l}if(i.dtype==="complex64"){let s=lo({inputs:{input:i},backend:e}),a=vw({inputs:{x:s},backend:e,attrs:{dtype:o}});return e.disposeIntermediateTensorInfo(s),a}if(!R.hasEncodingLoss(i.dtype,o)){let s=Be({inputs:{x:i},backend:e});return{dataId:s.dataId,shape:s.shape,dtype:o}}if(o==="int32")return AN(i,e);if(o==="bool"){let s=e.makeTensorInfo([],"bool",R.getTypedArrayFromDType("bool",1)),l=xw({inputs:{a:i,b:s},backend:e});return e.disposeIntermediateTensorInfo(s),l}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}var IN={kernelName:Lo,backendName:"webgl",kernelFunc:vw};var kN="return ceil(x);",QY=Ot({opSnippet:kN,packedOpSnippet:kN,cpuKernelImpl:n6}),RN={kernelName:dh,backendName:"webgl",kernelFunc:QY};var u0=class{constructor(t){this.variableNames=["A"],this.outputShape=t,this.userCode=` + uniform float minVal; + uniform float maxVal; + + void main() { + float value = getAAtOutCoords(); + if (isnan(value)) { + setOutput(value); + return; + } + + setOutput(clamp(value, minVal, maxVal)); + } + `}getCustomSetupFunc(t,e){return(r,i)=>{this.minLoc==null&&(this.minLoc=r.getUniformLocationNoThrow(i,"minVal"),this.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(this.minLoc,t),r.gl.uniform1f(this.maxLoc,e)}}};var h0=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=` + uniform float minVal; + uniform float maxVal; + + void main() { + vec4 value = getAAtOutCoords(); + + if (any(isnan(value))) { + setOutput(value); + return; + } + + setOutput(clamp(value, vec4(minVal), vec4(maxVal))); + } + `}getCustomSetupFunc(t,e){return(r,i)=>{this.minLoc==null&&(this.minLoc=r.getUniformLocationNoThrow(i,"minVal"),this.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(this.minLoc,t),r.gl.uniform1f(this.maxLoc,e)}}};function tZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{clipValueMin:o,clipValueMax:s}=r,a;ot().getBool("WEBGL_PACK_CLIP")?a=new h0(i.shape):a=new u0(i.shape);let l=a.getCustomSetupFunc(o,s);return e.runWebGLProgram(a,[i],i.dtype,l)}var PN={kernelName:fh,backendName:"webgl",kernelFunc:tZ};var p0=class{constructor(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=` + void main() { + float re = abs(getRealAtOutCoords()); + float im = abs(getImagAtOutCoords()); + float mx = max(re, im); + + // sadly the length function in glsl is not underflow-safe + // (at least not on Intel GPUs). So the safe solution is + // to ensure underflow-safety in all cases. + setOutput( + mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx)) + ); + } + `}};function NN(n,t){return{dataId:t.dataId,dtype:t.dtype,shape:n.shape}}function eZ(n){let{inputs:t,backend:e}=n,{x:r}=t,i=e.texData.get(r.dataId),o=new p0(r.shape),s=[NN(r,i.complexTensorInfos.real),NN(r,i.complexTensorInfos.imag)];return e.runWebGLProgram(o,s,s[0].dtype)}var LN={kernelName:Rm,backendName:"webgl",kernelFunc:eZ};var d0=class{constructor(t){this.outputShape=[],this.outputShape=F.computeOutShape(t,1),this.variableNames=t.map((s,a)=>`T${a}`);let e=new Array(t.length-1);e[0]=t[0][1];for(let s=1;s`T${x}`);let l=new Array(t.length-1);l[0]=t[0][e];for(let m=1;m= ${l[m-1]}) { + return getChannel( + getT${m}(${f0(a,c,x)}), + vec2(${f0(u,c,x)})); + }`}let d=l.length,f=l[l.length-1];p+=` + return getChannel( + getT${d}(${f0(a,c,f)}), + vec2(${f0(u,c,f)}));`,this.userCode=` + float getValue(${a.map(m=>"int "+m)}) { + ${p} + } + + void main() { + ${o} coords = getOutputCoords(); + vec4 result = vec4(getValue(${s}), 0., 0., 0.); + + ${s[i-1]} = ${s[i-1]} + 1; + if (${s[i-1]} < ${r[i-1]}) { + result.g = getValue(${s}); + } + + ${s[i-2]} = ${s[i-2]} + 1; + if (${s[i-2]} < ${r[i-2]}) { + result.a = getValue(${s}); + } + + ${s[i-1]} = ${s[i-1]} - 1; + if (${s[i-2]} < ${r[i-2]} && + ${s[i-1]} < ${r[i-1]}) { + result.b = getValue(${s}); + } + setOutput(result); + } + `}};function f0(n,t,e){let r=n.indexOf(t);return n.map((o,s)=>s===r?`${o} - ${e}`:o).join()}function pa(n){let{inputs:t,backend:e}=n,{input:r}=t,i=e.texData.get(r.dataId);return Be({inputs:{x:i.complexTensorInfos.imag},backend:e})}var DN={kernelName:ig,backendName:"webgl",kernelFunc:pa};function da(n,t,e){let r=n[0].dtype;if(r==="complex64"){let c=n.map(f=>lo({inputs:{input:f},backend:e})),u=n.map(f=>pa({inputs:{input:f},backend:e})),h=da(c,t,e),p=da(u,t,e),d=tr({inputs:{real:h,imag:p},backend:e});return c.forEach(f=>e.disposeIntermediateTensorInfo(f)),u.forEach(f=>e.disposeIntermediateTensorInfo(f)),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),d}if(r==="string"){let{tensors2D:c,outShape:u}=zN(n,t,e),h=c.map(x=>({vals:e.readSync(x.dataId),shape:x.shape})),p=c[0].shape[0]===1,d=r6(h,u,r,p),f=F.computeOutShape(n.map(x=>x.shape),t),m=e.makeTensorInfo(f,r,d);return c.forEach(x=>e.disposeIntermediateTensorInfo(x)),m}if(n.length>ot().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(n.length/2),u=da(n.slice(0,c),t,e),h=da(n.slice(c),t,e),p=da([u,h],t,e);return e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(h),p}if(ot().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&n[0].shape.length>1){let c=new m0(n.map(u=>u.shape),t);return e.runWebGLProgram(c,n,r)}let{tensors2D:i,outShape:o}=zN(n,t,e),s=new d0(i.map(c=>c.shape)),a=e.runWebGLProgram(s,i,r);i.forEach(c=>e.disposeIntermediateTensorInfo(c));let l=Tt({inputs:{x:a},attrs:{shape:o},backend:e});return e.disposeIntermediateTensorInfo(a),l}function zN(n,t,e){let r=F.computeOutShape(n.map(o=>o.shape),t);return{tensors2D:n.map(o=>Tt({inputs:{x:o},attrs:{shape:[-1,R.sizeFromShape(o.shape.slice(t))]},backend:e})),outShape:r}}function yw(n){let{inputs:t,backend:e,attrs:r}=n,{axis:i}=r,o=R.parseAxisParam(i,t[0].shape)[0],s=F.computeOutShape(t.map(c=>c.shape),o);if(R.sizeFromShape(s)===0)return e.makeTensorInfo(s,t[0].dtype,[]);let a=t.filter(c=>R.sizeFromShape(c.shape)>0);if(a.length===1)return Be({inputs:{x:a[0]},backend:e});let l=a.map(c=>c.shape);return F.assertParamsConsistent(l,o),da(a,o,e)}var FN={kernelName:Pm,backendName:"webgl",kernelFunc:yw};var oc=class{constructor(t,e=!1,r=null,i=!1,o=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;let s=t.padInfo.top,a=t.padInfo.left,l=t.strideHeight,c=t.strideWidth,u=t.dilationHeight,h=t.dilationWidth,p=t.filterHeight,d=t.filterWidth,f=Math.floor(t.inChannels/4)*4,m=t.inChannels%4,x=t.dataFormat==="channelsLast",g=x?1:2,v=x?2:3,b=x?3:1,y="",_="";r&&(i?y=`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + ${r} + }`:o?y=`float activation(float a) { + float b = getLeakyreluAlphaAtOutCoords(); + ${r} + }`:y=` + float activation(float x) { + ${r} + } + `,_="result = activation(result);");let S=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),o&&this.variableNames.push("leakyreluAlpha"),this.userCode=` + ${y} + + const ivec2 strides = ivec2(${l}, ${c}); + const ivec2 pads = ivec2(${s}, ${a}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d2 = coords[${b}]; + + ivec2 xRCCorner = + ivec2(coords[${g}], coords[${v}]) * strides - pads; + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${p}; wR++) { + int xR = xRCorner + wR * ${u}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${d}; wC++) { + int xC = xCCorner + wC * ${h}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + for (int d1 = 0; d1 < ${f}; d1 += 4) { + vec4 wValues = vec4( + getW(wR, wC, d1, d2), + getW(wR, wC, d1 + 1, d2), + getW(wR, wC, d1 + 2, d2), + getW(wR, wC, d1 + 3, d2) + ); + + if (${x}) { + vec4 xValues = vec4( + getX(batch, xR, xC, d1), + getX(batch, xR, xC, d1 + 1), + getX(batch, xR, xC, d1 + 2), + getX(batch, xR, xC, d1 + 3) + ); + dotProd += dot(xValues, wValues); + } else { + vec4 xValues = vec4( + getX(batch, d1, xR, xC), + getX(batch, d1 + 1, xR, xC), + getX(batch, d1 + 2, xR, xC), + getX(batch, d1 + 3, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + } + + if (${m===1}) { + + if (${x}) { + dotProd += + getX(batch, xR, xC, ${f}) * + getW(wR, wC, ${f}, d2); + } else { + dotProd += + getX(batch, ${f}, xR, xC) * + getW(wR, wC, ${f}, d2); + } + + } else if (${m===2}) { + vec2 wValues = vec2( + getW(wR, wC, ${f}, d2), + getW(wR, wC, ${f} + 1, d2) + ); + + if (${x}) { + vec2 xValues = vec2( + getX(batch, xR, xC, ${f}), + getX(batch, xR, xC, ${f} + 1) + ); + dotProd += dot(xValues, wValues); + } else { + vec2 xValues = vec2( + getX(batch, ${f}, xR, xC), + getX(batch, ${f} + 1, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + + } else if (${m===3}) { + vec3 wValues = vec3( + getW(wR, wC, ${f}, d2), + getW(wR, wC, ${f} + 1, d2), + getW(wR, wC, ${f} + 2, d2) + ); + + if (${x}) { + vec3 xValues = vec3( + getX(batch, xR, xC, ${f}), + getX(batch, xR, xC, ${f} + 1), + getX(batch, xR, xC, ${f} + 2) + ); + dotProd += dot(xValues, wValues); + } else { + vec3 xValues = vec3( + getX(batch, ${f}, xR, xC), + getX(batch, ${f} + 1, xR, xC), + getX(batch, ${f} + 2, xR, xC) + ); + dotProd += dot(xValues, wValues); + } + + } + } + } + + float result = dotProd; + ${S} + ${_} + setOutput(result); + } + `}},g0=class{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;let e=t.padInfo.front,r=t.padInfo.top,i=t.padInfo.left,o=t.strideDepth,s=t.strideHeight,a=t.strideWidth,l=t.dilationDepth,c=t.dilationHeight,u=t.dilationWidth,h=t.filterDepth,p=t.filterHeight,d=t.filterWidth,f=Math.floor(t.inChannels/4)*4,m=t.inChannels%4;this.userCode=` + const ivec3 strides = ivec3(${o}, ${s}, ${a}); + const ivec3 pads = ivec3(${e}, ${r}, ${i}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int d2 = coords.u; + + ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; + int xFCorner = xFRCCorner.x; + int xRCorner = xFRCCorner.y; + int xCCorner = xFRCCorner.z; + + // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get + // y(yF, yR, yC, d2). ? = to be determined. : = across all + // values in that axis. + float dotProd = 0.0; + for (int wF = 0; wF < ${h}; wF++) { + int xF = xFCorner + wF * ${l}; + + if (xF < 0 || xF >= ${t.inDepth}) { + continue; + } + + for (int wR = 0; wR < ${p}; wR++) { + int xR = xRCorner + wR * ${c}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int wC = 0; wC < ${d}; wC++) { + int xC = xCCorner + wC * ${u}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + for (int d1 = 0; d1 < ${f}; d1 += 4) { + vec4 xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3) + ); + vec4 wValues = vec4( + getW(wF, wR, wC, d1, d2), + getW(wF, wR, wC, d1 + 1, d2), + getW(wF, wR, wC, d1 + 2, d2), + getW(wF, wR, wC, d1 + 3, d2) + ); + + dotProd += dot(xValues, wValues); + } + + if (${m===1}) { + dotProd += + getX(batch, xF, xR, xC, ${f}) * + getW(wF, wR, wC, ${f}, d2); + } else if (${m===2}) { + vec2 xValues = vec2( + getX(batch, xF, xR, xC, ${f}), + getX(batch, xF, xR, xC, ${f} + 1) + ); + vec2 wValues = vec2( + getW(wF, wR, wC, ${f}, d2), + getW(wF, wR, wC, ${f} + 1, d2) + ); + dotProd += dot(xValues, wValues); + } else if (${m===3}) { + vec3 xValues = vec3( + getX(batch, xF, xR, xC, ${f}), + getX(batch, xF, xR, xC, ${f} + 1), + getX(batch, xF, xR, xC, ${f} + 2) + ); + vec3 wValues = vec3( + getW(wF, wR, wC, ${f}, d2), + getW(wF, wR, wC, ${f} + 1, d2), + getW(wF, wR, wC, ${f} + 2, d2) + ); + dotProd += dot(xValues, wValues); + } + } + } + } + setOutput(dotProd); + } + `}};var x0=class{constructor(t,e,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;let{filterWidth:i,inChannels:o,strideWidth:s,strideHeight:a,padInfo:l,outWidth:c,dilationWidth:u,dilationHeight:h,dataFormat:p}=r,{left:d,top:f}=l,m=o*i,x=Le(),g=p==="channelsLast",v=g?0:1,b=g?1:2,y="";for(let _=0;_<=1;_++)for(let S=0;S<=1;S++)y+=` + blockIndex = rc.y + ${S}; + pos = rc.x + ${_}; + + if(blockIndex < ${t[1]} && pos < ${t[0]}) { + offsetY = int(blockIndex / (${c})) * ${a} - ${f}; + d0 = offsetY + ${h} * (pos / ${m}); + + if(d0 < ${e[v]} && d0 >= 0) { + + offsetX = int(mod(float(blockIndex), ${c}.) * ${s}. - ${d}.); + d1 = offsetX + ${u} * (int(mod(float(pos), ${m}.) / ${o}.)); + + if(d1 < ${e[b]} && d1 >= 0) { + + ch = int(mod(float(pos), ${o}.)); + + if (${g}) { + innerDims = vec2(d1, ch); + result[${_*2+S}] = getChannel( + getA(d0, int(innerDims.x), + int(innerDims.y)), innerDims); + } else { + innerDims = vec2(d0, d1); + result[${_*2+S}] = getChannel( + getA(ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + } + `;this.userCode=` + void main() { + ivec2 rc = getOutputCoords(); + + vec4 result = vec4(0); + + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + + ${y} + + ${x.output} = result; + } + `}};function v0({x:n,filter:t,convInfo:e,backend:r,bias:i=null,preluActivationWeights:o=null,leakyreluAlpha:s=0,activation:a=null}){let l=n.shape,c=r.texData.get(n.dataId),u=e.inChannels,h=l[0]*l[1]*l[2],p=e.outChannels,d=e.dataFormat==="channelsLast",f=!1,m=!1,x,g=[],v=(h===1||p===1)&&u>mw,b=l[2]%2!==0&&!!c.isPacked;if(v||!ot().getBool("WEBGL_LAZILY_UNPACK")||!ot().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!b){let y=d?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],_=Tt({inputs:{x:n},backend:r,attrs:{shape:[1,y,e.inChannels]}}),S=Tt({inputs:{x:t},backend:r,attrs:{shape:[1,e.inChannels,e.outChannels]}}),E=ha({a:_,b:S,transposeA:f,transposeB:m,backend:r,bias:i,activation:a,preluActivationWeights:o,leakyreluAlpha:s});x=Tt({inputs:{x:E},backend:r,attrs:{shape:e.outShape}}),g.push(_),g.push(S),g.push(E)}else{let y=d?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),_={dataId:n.dataId,shape:[1,y,e.inChannels],dtype:n.dtype},S=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,R.assert(sa(c.shape,_.shape),()=>`packed reshape ${c.shape} to ${_.shape} isn't free`);let E=Tt({inputs:{x:t},backend:r,attrs:{shape:[1,e.inChannels,e.outChannels]}});g.push(E);let M=ha({a:_,b:E,backend:r,transposeA:f,transposeB:m,bias:i,activation:a,preluActivationWeights:o,leakyreluAlpha:s}),P=r.texData.get(M.dataId);R.assert(P.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=S,P.shape=e.outShape,x=Be({inputs:{x:M},backend:r}),x.shape=e.outShape,g.push(M)}for(let y of g)r.disposeIntermediateTensorInfo(y);return x}function y0({x:n,filter:t,convInfo:e,backend:r,bias:i=null,preluActivationWeights:o=null,leakyreluAlpha:s=0,activation:a=null}){let{filterWidth:l,filterHeight:c,inChannels:u,outWidth:h,outHeight:p,dataFormat:d}=e,f=d==="channelsLast",m=l*c*u,x=p*h,g=[m,x],v=!0,b=!1,y=[],_=Tt({inputs:{x:n},backend:r,attrs:{shape:n.shape.slice(1)}}),S=Tt({inputs:{x:t},backend:r,attrs:{shape:[1,m,R.sizeFromShape(t.shape)/m]}});y.push(_),y.push(S);let E=new x0(g,_.shape,e),M=r.runWebGLProgram(E,[_],"float32"),P=Tt({inputs:{x:M},backend:r,attrs:{shape:[1,g[0],g[1]]}});y.push(M),y.push(P);let D=i!=null,w=o!=null,I=a==="leakyrelu",N=a?Go(a,!0):null,L=new ic(P.shape,S.shape,[1,x,e.outChannels],v,b,D,N,w,I),O=[P,S];if(i&&O.push(i),w&&O.push(o),I){let X=r.makeTensorInfo([],"float32",R.createScalarValue(s,"float32"));O.push(X),y.push(X)}let z=r.runWebGLProgram(L,O,"float32"),V=f?[1,p,h,e.outChannels]:[1,e.outChannels,p,h],$=Tt({inputs:{x:z},backend:r,attrs:{shape:V}});y.push(z);for(let X of y)r.disposeIntermediateTensorInfo(X);return $}function nZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,filter:o}=t,{strides:s,pad:a,dataFormat:l,dilations:c,dimRoundingMode:u}=r,h=F.convertConv2DDataFormat(l),p=F.computeConv2DInfo(i.shape,o.shape,s,c,a,u,!1,h),d;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))d=v0({x:i,filter:o,convInfo:p,backend:e});else if(ot().getBool("WEBGL_CONV_IM2COL")&&i.shape[0]===1)d=y0({x:i,filter:o,convInfo:p,backend:e});else{let m=new oc(p);d=e.runWebGLProgram(m,[i,o],"float32")}let f=Tt({inputs:{x:d},backend:e,attrs:{shape:p.outShape}});return e.disposeIntermediateTensorInfo(d),f}var ON={kernelName:Nm,backendName:"webgl",kernelFunc:nZ};var b0=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideHeight,r=t.strideWidth,i=t.padInfo.top,o=t.padInfo.left,s=t.dataFormat==="channelsLast";this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int wR = coords.x; + int wC = coords.y; + int d1 = coords.z; + int d2 = coords.w; + + // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int b = 0; b < ${t.batchSize}; b++) { + for (int yR = 0; yR < ${t.outHeight}; yR++) { + int xR = wR + yR * ${e} - ${i}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${t.outWidth}; yC++) { + int xC = wC + yC * ${r} - ${o}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + if (${s}) { + float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue); + } else { + float dyValue = getDy(b, d2, yR, yC); + float xValue = getX(b, d1, xR, xC); + dotProd += (xValue * dyValue); + } + + } + } + } + setOutput(dotProd); + } + `}},_0=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterHeight,r=t.filterWidth,i=t.strideHeight,o=t.strideWidth,s=t.dataFormat==="channelsLast",a=e-1-t.padInfo.top,l=r-1-t.padInfo.left,c=s?1:2,u=s?2:3,h=s?3:1;this.userCode=` + const ivec2 pads = ivec2(${a}, ${l}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[${h}]; + + ivec2 dyCorner = ivec2(coords[${c}], coords[${u}]) - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${e}; wR++) { + float dyR = float(dyRCorner + wR) / ${i}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${e} - 1 - wR; + + for (int wC = 0; wC < ${r}; wC++) { + float dyC = float(dyCCorner + wC) / ${o}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${r} - 1 - wC; + + for (int d2 = 0; d2 < ${t.outChannels}; d2++) { + + if (${s}) { + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } else { + float xValue = getDy(batch, d2, idyR, idyC); + float wValue = getW(wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + + } + } + } + setOutput(dotProd); + } + `}},w0=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideDepth,r=t.strideHeight,i=t.strideWidth,o=t.padInfo.front,s=t.padInfo.top,a=t.padInfo.left;this.userCode=` + void main() { + ivec5 coords = getOutputCoords(); + int wF = coords.x; + int wR = coords.y; + int wC = coords.z; + int d1 = coords.w; + int d2 = coords.u; + + float dotProd = 0.0; + + for (int b = 0; b < ${t.batchSize}; b++) { + for (int yF = 0; yF < ${t.outDepth}; yF++) { + int xF = wF + yF * ${e} - ${o}; + + if (xF < 0 || xF >= ${t.inDepth}) { + continue; + } + + for (int yR = 0; yR < ${t.outHeight}; yR++) { + int xR = wR + yR * ${r} - ${s}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${t.outWidth}; yC++) { + int xC = wC + yC * ${i} - ${a}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + float dyValue = getDy(b, yF, yR, yC, d2); + float xValue = getX(b, xF, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + } + setOutput(dotProd); + } + `}},S0=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterDepth,r=t.filterHeight,i=t.filterWidth,o=t.strideDepth,s=t.strideHeight,a=t.strideWidth,l=e-1-t.padInfo.front,c=r-1-t.padInfo.top,u=i-1-t.padInfo.left;this.userCode=` + const ivec3 pads = ivec3(${l}, ${c}, ${u}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int d1 = coords.u; + + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyFCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + float dotProd = 0.0; + for (int wF = 0; wF < ${e}; wF++) { + float dyF = float(dyFCorner + wF) / ${o}.0; + + if (dyF < 0.0 || dyF >= ${t.outDepth}.0 || fract(dyF) > 0.0) { + continue; + } + int idyF = int(dyF); + + int wFPerm = ${e} - 1 - wF; + + for (int wR = 0; wR < ${r}; wR++) { + float dyR = float(dyRCorner + wR) / ${s}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${r} - 1 - wR; + + for (int wC = 0; wC < ${i}; wC++) { + float dyC = float(dyCCorner + wC) / ${a}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${i} - 1 - wC; + + for (int d2 = 0; d2 < ${t.outChannels}; d2++) { + float xValue = getDy(batch, idyF, idyR, idyC, d2); + float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); + dotProd += xValue * wValue; + } + } + } + } + setOutput(dotProd); + } + `}};function rZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,dy:o}=t,{strides:s,pad:a,dataFormat:l,dimRoundingMode:c,filterShape:u}=r,h=F.convertConv2DDataFormat(l),p=F.computeConv2DInfo(i.shape,u,s,1,a,c,!1,h),d=new b0(p);return e.runWebGLProgram(d,[i,o],"float32")}var BN={kernelName:Lm,backendName:"webgl",kernelFunc:rZ};function iZ(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,filter:o}=t,{inputShape:s,strides:a,pad:l,dataFormat:c,dimRoundingMode:u}=r,h=F.convertConv2DDataFormat(c),p=F.computeConv2DInfo(s,o.shape,a,1,l,u,!1,h),d=new _0(p);return e.runWebGLProgram(d,[i,o],"float32")}var VN={kernelName:Dm,backendName:"webgl",kernelFunc:iZ};function oZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,filter:o}=t,{strides:s,pad:a,dilations:l}=r,c=F.computeConv3DInfo(i.shape,o.shape,s,l,a),u=new g0(c);return e.runWebGLProgram(u,[i,o],"float32")}var HN={kernelName:zm,backendName:"webgl",kernelFunc:oZ};function sZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,dy:o}=t,{strides:s,pad:a,filterShape:l}=r,c=F.computeConv3DInfo(i.shape,l,s,1,a),u=new w0(c);return e.runWebGLProgram(u,[i,o],"float32")}var $N={kernelName:Fm,backendName:"webgl",kernelFunc:sZ};function aZ(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,filter:o}=t,{pad:s,strides:a,inputShape:l}=r,c=F.computeConv3DInfo(l,o.shape,a,1,s),u=new S0(c);return e.runWebGLProgram(u,[i,o],"float32")}var UN={kernelName:Om,backendName:"webgl",kernelFunc:aZ};var lZ=X1+` + return cos(x); +`,cZ=Ot({opSnippet:lZ}),WN={kernelName:mh,backendName:"webgl",kernelFunc:cZ};var uZ=` + float e2x = exp(-x); + return (e2x + 1.0 / e2x) / 2.0; +`,hZ=Ot({opSnippet:uZ}),GN={kernelName:gh,backendName:"webgl",kernelFunc:hZ};var C0=class{constructor(t,e,r,i,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,a,l,c]=t,[u]=e,[h,p]=r;this.outputShape=[u,h,p,c];let d=i==="bilinear"?1:0,[f,m]=[`${a-1}.0`,`${l-1}.0`],[x,g,v]=h>1?[`${(a-1)/(h-1)}`,"(y2-y1) * height_ratio",`y1*${f} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${f}`],[b,y,_]=p>1?[`${(l-1)/(p-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=` + const float height_ratio = float(${x}); + const float width_ratio = float(${b}); + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int y = coords[1]; + int x = coords[2]; + int d = coords[3]; + + // get box vals + float y1 = getBoxes(b,0); + float x1 = getBoxes(b,1); + float y2 = getBoxes(b,2); + float x2 = getBoxes(b,3); + + // get image in batch index + int bInd = round(getBoxInd(b)); + if(bInd < 0 || bInd >= ${s}) { + return; + } + + float height_scale = ${g}; + float width_scale = ${y}; + + float in_y = ${v}; + if( in_y < 0.0 || in_y > ${f} ) { + setOutput(float(${o})); + return; + } + float in_x = ${_}; + if( in_x < 0.0 || in_x > ${m} ) { + setOutput(float(${o})); + return; + } + + vec2 sourceFracIndexCR = vec2(in_x,in_y); + if(${d} == 1) { + // Compute the four integer indices. + ivec2 sourceFloorCR = ivec2(sourceFracIndexCR); + ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR)); + + float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d); + float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d); + float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d); + float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d); + + vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR); + + float top = topLeft + (topRight - topLeft) * fracCR.x; + float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; + float newValue = top + (bottom - top) * fracCR.y; + setOutput(newValue); + } else { + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestCR = ivec2(floor( + sourceFracIndexCR + vec2(0.5,0.5))); + float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d); + setOutput(newValue); + } + } + `}};var pZ=n=>{let{inputs:t,backend:e,attrs:r}=n,{image:i,boxes:o,boxInd:s}=t,{cropSize:a,method:l,extrapolationValue:c}=r,u=new C0(i.shape,o.shape,a,l,c);return e.runWebGLProgram(u,[i,o,s],"float32")},jN={kernelName:Vm,backendName:"webgl",kernelFunc:pZ};var bp=class{constructor(t,e,r){this.variableNames=["x"],this.outputShape=t;let i=t.length,o=e?"0.0":`getX(${qN(i,"coords")})`,s=t[t.length-1],a="",l="";e?(a=r?`end != ${s-1}`:"end != 0",l=r?"end + 1":"end - 1"):(a=r?`end + pow2 < ${s}`:"end >= pow2",l=r?"end + pow2":"end - pow2"),this.userCode=` + uniform float index; + void main() { + ${ne(i)} coords = getOutputCoords(); + int end = ${XN(i,"coords")}; + float val = ${o}; + int pow2 = int(pow(2.0, index)); + if (${a}) { + int idx = ${l}; + ${XN(i,"coords")} = idx; + val += getX(${qN(i,"coords")}); + } + setOutput(val); + } + `}getCustomSetupFunc(t){return(e,r)=>{this.index==null&&(this.index=e.getUniformLocation(r,"index")),e.gl.uniform1f(this.index,t)}}};function qN(n,t){if(n===1)return`${t}`;if(n===2)return`${t}.x, ${t}.y`;if(n===3)return`${t}.x, ${t}.y, ${t}.z`;if(n===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${n} is not yet supported`)}function XN(n,t){if(n===1)return`${t}`;if(n===2)return`${t}.y`;if(n===3)return`${t}.z`;if(n===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${n} is not yet supported`)}function dZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o,exclusive:s,reverse:a}=r,l=i.shape.length,c=F.getAxesPermutation([o],l),u=i;c!=null&&(u=Pe({inputs:{x:i},backend:e,attrs:{perm:c}}));let h=F.getInnerMostAxes(1,l)[0];if(h!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${i.shape.length-1} but got axis=${o}`);let p=u.shape[h],d=Be({inputs:{x:u},backend:e});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new bp(u.shape,!1,a),x=m.getCustomSetupFunc(f),g=d;d=e.runWebGLProgram(m,[d],d.dtype,x),e.disposeIntermediateTensorInfo(g)}if(s){let f=new bp(u.shape,s,a),m=d;d=e.runWebGLProgram(f,[d],d.dtype),e.disposeIntermediateTensorInfo(m)}if(c!=null){let f=F.getUndoAxesPermutation(c),m=Pe({inputs:{x:d},backend:e,attrs:{perm:f}});return e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(u),m}return d}var KN={kernelName:Bm,backendName:"webgl",kernelFunc:dZ};function fZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,weights:o}=t,{size:s,binaryOutput:a}=r;if(i.shape.length===1){let l=e.readSync(i.dataId),c=e.readSync(o.dataId),u=H1(l,c,o.dtype,o.shape,s);return e.makeTensorInfo([s],o.dtype,u)}else if(i.shape.length===2){let l=e.bufferSync(i),c=e.bufferSync(o),u=e6(l,c,s,a);return e.makeTensorInfo(u.shape,o.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${i.shape.length}.`)}var YN={kernelName:Hm,backendName:"webgl",kernelFunc:fZ};var M0=class{constructor(t,e,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=r,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int h = ${this.getHeightCoordString()}; + int w = ${this.getWidthCoordString()}; + int d = ${this.getDepthCoordString()}; + + int in_h = h / ${e}; + int offset_h = imod(h, ${e}); + int in_w = w / ${e}; + int offset_w = imod(w, ${e}); + int offset_d = (offset_h * ${e} + offset_w) * + ${this.getOutputDepthSize()}; + int in_d = d + offset_d; + + float result = ${this.getInputSamplingString()}; + setOutput(result); + } + `}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function mZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{blockSize:o,dataFormat:s}=r;R.assert(o>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${o}`);let a=i.shape[0],l=s==="NHWC"?i.shape[1]:i.shape[2],c=s==="NHWC"?i.shape[2]:i.shape[3],u=s==="NHWC"?i.shape[3]:i.shape[1],h=l*o,p=c*o,d=u/(o*o),f=s==="NHWC"?[a,h,p,d]:[a,d,h,p],m=new M0(f,o,s);return e.runWebGLProgram(m,[i],i.dtype)}var ZN={kernelName:$m,backendName:"webgl",kernelFunc:mZ};var sc=class{constructor(t,e=!1,r=null,i=!1,o=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;let s=t.inHeight,a=t.inWidth,l=t.padInfo.top,c=t.padInfo.left,u=t.strideHeight,h=t.strideWidth,p=t.dilationHeight,d=t.dilationWidth,f=t.filterHeight,m=t.filterWidth,x=t.outChannels/t.inChannels,g="",v="";r&&(i?g=`float activation(float a) { + float b = getPreluActivationWeightsAtOutCoords(); + ${r} + }`:o?g=`float activation(float a) { + float b = getLeakyreluAlphaAtOutCoords(); + ${r} + }`:g=` + float activation(float x) { + ${r} + } + `,v="result = activation(result);");let b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),o&&this.variableNames.push("leakyreluAlpha"),this.userCode=` + ${g} + + const ivec2 strides = ivec2(${u}, ${h}); + const ivec2 pads = ivec2(${l}, ${c}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + ivec2 xRCCorner = coords.yz * strides - pads; + int d2 = coords.w; + int d1 = d2 / ${x}; + int q = d2 - d1 * ${x}; + + int xRCorner = xRCCorner.x; + int xCCorner = xRCCorner.y; + + // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations. + for (int wR = 0; wR < ${f}; wR++) { + int xR = xRCorner + wR * ${p}; + + if (xR < 0 || xR >= ${s}) { + continue; + } + + for (int wC = 0; wC < ${m}; wC++) { + int xC = xCCorner + wC * ${d}; + + if (xC < 0 || xC >= ${a}) { + continue; + } + + float xVal = getX(batch, xR, xC, d1); + float wVal = getW(wR, wC, d1, q); + dotProd += xVal * wVal; + } + } + + float result = dotProd; + ${b} + ${v} + setOutput(result); + } + `}};var ac=class{constructor(t,e=!1,r=null,i=!1,o=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;let s=t.outChannels/t.inChannels,a=t.inHeight,l=t.inWidth,c=t.padInfo.top,u=t.padInfo.left,h=t.strideHeight,p=t.strideWidth,d=t.dilationHeight,f=t.dilationWidth,m=t.filterHeight,x=t.filterWidth,g=x,v=` + int xR; int xC; int xCOffset; + vec4 wTexel; vec4 previous; vec4 final;`;for(let S=0;S=0 && xR < ${a}) { + `;for(let E=0;E= 0 && xCOffset < ${l}) { + xTexelC${M} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= ${l}) { + xTexelC${M}.zw = vec2(0.0); + } + } + `,f===1&&M>0?v+=` + xC${M} = vec4(xTexelC${M-2}.zw, xTexelC${M}.xy); + `:v+=` + xCOffset = xC + 1 - 2; + + if (xCOffset >= 0 && xCOffset < ${l}) { + previous = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= ${l}) { + previous.zw = vec2(0.0); + } + + xC${M} = vec4(previous.zw, xTexelC${M}.xy); + } else { + xC${M} = vec4(0.0, 0.0, xTexelC${M}.xy); + } + `):v+=` + if (xC >= 0 && xC < ${l}) { + xTexelC${M} = getX(batch, xR, xC, d1); + if (xC + 1 >= ${l}) { + xTexelC${M}.zw = vec2(0.0); + } + } + + xC${M} = xTexelC${M}; + `,M+1= 0 && xCOffset < ${l}) { + xTexelC${M+2} = getX(batch, xR, xCOffset, d1); + + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= ${l}) { + xTexelC${M+2}.zw = vec2(0.0); + } + } + `,f>1&&(v+=` + xCOffset -= 2; + if (xCOffset >= 0 && xCOffset < ${l}) { + xTexelC${M} = getX(batch, xR, xCOffset, d1); + } + `),v+=` + xC${M+1} = vec4(xTexelC${M}.zw, xTexelC${M+2}.xy); + `):P===1?v+=` + xC${M+1} = xTexelC${M}; + `:v+=` + xCOffset = xC + ${P}; + + if (xCOffset >= 0 && xCOffset < ${l}) { + xTexelC${M+2} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= ${l}) { + xTexelC${M+2}.zw = vec2(0.0); + } + } + + xC${M+1} = xTexelC${M+2}; + `}}else M= 0 && xCOffset < ${l}) { + xTexelC${M} = getX(batch, xR, xCOffset, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xCOffset + 1 >= ${l}) { + xTexelC${M}.zw = vec2(0.0); + } + } + + if(xC + 1 >= 0 && xC + 1 < ${l}) { + xTexelC${M+2} = getX(batch, xR, xC + 1, d1); + // Need to manually clear unused channels in case + // we're reading from recycled texture. + if (xC + 2 >= ${l}) { + xTexelC${M+2}.zw = vec2(0.0); + } + } + + xC${M} = vec4(xTexelC${M}.zw, xTexelC${M+2}.zw); + `,M+1= 0 && xCOffset < ${l}) { + final = getX(batch, xR, xCOffset, d1); + } + xC${M+1} = vec4(xTexelC${M+2}.xy, final.xy); + `)):(v+=` + if(xC >= 0 && xC < ${l}) { + xTexelC${M} = getX(batch, xR, xC, d1); + if (xC + 1 >= ${l}) { + xTexelC${M}.zw = vec2(0.0); + } + } + + xCOffset = xC + ${p}; + if(xCOffset >= 0 && xCOffset < ${l}) { + xTexelC${M+2} = getX(batch, xR, xCOffset, d1); + if (xCOffset + 1 >= ${l}) { + xTexelC${M+2}.zw = vec2(0.); + } + } + + xC${M} = vec4( + xTexelC${M}.xy, xTexelC${M+2}.xy); + `,M+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let h=F.computeConv2DInfo(i.shape,o.shape,s,u,a,c,!0),p;return ot().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels===1?p=new ac(h):p=new sc(h),e.runWebGLProgram(p,[i,o],"float32")}var JN={kernelName:Um,backendName:"webgl",kernelFunc:gZ};var E0=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideHeight,r=t.strideWidth,i=t.padInfo.top,o=t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int wR = coords.x; + int wC = coords.y; + int d1 = coords.z; + int dm = coords.w; + int d2 = d1 * ${s} + dm; + + float dotProd = 0.0; + + // TO DO: Vec4 over the batch size + for (int b = 0; b < ${t.batchSize}; b++) { + for (int yR = 0; yR < ${t.outHeight}; yR++) { + int xR = wR + yR * ${e} - ${i}; + + if (xR < 0 || xR >= ${t.inHeight}) { + continue; + } + + for (int yC = 0; yC < ${t.outWidth}; yC++) { + int xC = wC + yC * ${r} - ${o}; + + if (xC < 0 || xC >= ${t.inWidth}) { + continue; + } + + float dyValue = getDy(b, yR, yC, d2); + float xValue = getX(b, xR, xC, d1); + dotProd += (xValue * dyValue); + } + } + } + setOutput(dotProd); + } + `}},T0=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterHeight,r=t.filterWidth,i=t.strideHeight,o=t.strideWidth,s=e-1-t.padInfo.top,a=r-1-t.padInfo.left,l=t.outChannels/t.inChannels;this.userCode=` + const ivec2 pads = ivec2(${s}, ${a}); + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords[0]; + int d1 = coords[3]; + ivec2 dyCorner = coords.yz - pads; + int dyRCorner = dyCorner.x; + int dyCCorner = dyCorner.y; + + float dotProd = 0.0; + + for (int wR = 0; wR < ${e}; wR++) { + float dyR = float(dyRCorner + wR) / ${i}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + int wRPerm = ${e} - 1 - wR; + + for (int wC = 0; wC < ${r}; wC++) { + float dyC = float(dyCCorner + wC) / ${o}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + int wCPerm = ${r} - 1 - wC; + + // TO DO: Vec4 over the channelMul + for (int dm = 0; dm < ${l}; dm++) { + int d2 = d1 * ${l} + dm; + float xValue = getDy(batch, idyR, idyC, d2); + float wValue = getW(wRPerm, wCPerm, d1, dm); + dotProd += xValue * wValue; + } + } + } + setOutput(dotProd); + } + `}};function xZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,dy:o}=t,{strides:s,dilations:a,pad:l,dimRoundingMode:c,filterShape:u}=r,h=F.computeConv2DInfo(i.shape,u,s,a,l,c,!0),p=new E0(h);return e.runWebGLProgram(p,[i,o],"float32")}var QN={kernelName:Wm,backendName:"webgl",kernelFunc:xZ};function vZ(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,filter:o}=t,{strides:s,dilations:a,pad:l,dimRoundingMode:c,inputShape:u}=r,h=F.computeConv2DInfo(u,o.shape,s,a,l,c,!0),p=new T0(h);return e.runWebGLProgram(p,[i,o],"float32")}var t9={kernelName:Gm,backendName:"webgl",kernelFunc:vZ};var A0=class{constructor(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; + setOutput(val); + } + `}};function yZ(n){let{inputs:t,backend:e}=n,{x:r}=t,i=[...r.shape,...r.shape],o=R.sizeFromShape(r.shape),s=Tt({inputs:{x:r},backend:e,attrs:{shape:[o]}}),a=new A0(o),l=e.runWebGLProgram(a,[s],s.dtype),c=Tt({inputs:{x:l},backend:e,attrs:{shape:i}});return e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(l),c}var e9={kernelName:jm,backendName:"webgl",kernelFunc:yZ};var I0=class{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;let{inHeight:e,inWidth:r,padInfo:i,strideHeight:o,strideWidth:s,filterHeight:a,filterWidth:l,dilationHeight:c,dilationWidth:u}=t,{top:h,left:p}=i;this.userCode=` + const ivec2 strides = ivec2(${o}, ${s}); + const ivec2 pads = ivec2(${h}, ${p}); + const float neg_infinity = -3.4e38; + + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int d1 = coords.w; + ivec2 outTopLeftCorner = + coords.yz * strides - pads; + int hBeg = outTopLeftCorner.x; + int wBeg = outTopLeftCorner.y; + + float curVal = neg_infinity; + for (int h = 0; h < ${a}; h++) { + int hIn = hBeg + h * ${c}; + + if (hIn >= 0 && hIn < ${e}) { + for (int w = 0; w < ${l}; w++) { + int wIn = wBeg + w * ${u}; + + if (wIn >= 0 && wIn < ${r}) { + float xVal = getX(batch, hIn, wIn, d1); + float wVal = getW(h, w, d1); + + float val = xVal + wVal; + if (val > curVal) { + curVal = val; + } + } + } + } + } + + float result = curVal; + setOutput(result); + } + `}};function bZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,filter:o}=t,{strides:s,pad:a,dilations:l}=r,c=F.computeDilation2DInfo(i.shape,o.shape,s,a,"NHWC",l),u,h=new I0(c);u=e.runWebGLProgram(h,[i,o],"float32");let p=Tt({inputs:{x:u},backend:e,attrs:{shape:c.outShape}});return e.disposeIntermediateTensorInfo(u),p}var n9={kernelName:qm,backendName:"webgl",kernelFunc:bZ};function _Z(n){let{inputs:t,backend:e,attrs:r}=n,{equation:i}=r,o=t,{allDims:s,summedDims:a,idDims:l}=F.decodeEinsumEquation(i,o.length);F.checkEinsumDimSizes(s.length,l,o);let{path:c,steps:u}=F.getEinsumComputePath(a,l),h=u.length,p=null,d=s.length,f=[];for(let m=0;m=0&&(p=ua({inputs:{x:p},backend:e,attrs:{axis:c[m]-(s.length-d),keepDims:!1}}),f.push(p)),d--)}for(let m of f)m!==p&&e.disposeIntermediateTensorInfo(m);return p}var r9={kernelName:Xm,backendName:"webgl",kernelFunc:_Z};var wZ="return (x >= 0.0) ? x : (exp(x) - 1.0);",SZ=` + vec4 result; + + result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); + result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); + result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); + result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); + + return result; +`,CZ=Ot({opSnippet:wZ,packedOpSnippet:SZ}),i9={kernelName:Ws,backendName:"webgl",kernelFunc:CZ};var MZ="return (b >= 1.0) ? a : a * (b + 1.0);",EZ=` + vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); + return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); +`,TZ=n=>{let{inputs:t,backend:e}=n,{dy:r,y:i}=t,o=ot().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Or(EZ,r.shape,i.shape):new vr(MZ,r.shape,i.shape);return e.runWebGLProgram(o,[r,i],r.dtype)},o9={kernelName:Km,backendName:"webgl",kernelFunc:TZ};var AZ=` + return vec4(equal(a, b)); +`,IZ="return float(a == b);",kZ=me({opSnippet:IZ,packedOpSnippet:AZ,dtype:"bool"}),s9={kernelName:yh,backendName:"webgl",kernelFunc:kZ};var RZ=` + // Error function is calculated approximately with elementary function. + // See "Handbook of Mathematical Functions with Formulas, + // Graphs, and Mathematical Tables", Abramowitz and Stegun. + float p = ${F.ERF_P}; + float a1 = ${F.ERF_A1}; + float a2 = ${F.ERF_A2}; + float a3 = ${F.ERF_A3}; + float a4 = ${F.ERF_A4}; + float a5 = ${F.ERF_A5}; + + float sign = sign(x); + x = abs(x); + float t = 1.0 / (1.0 + p * x); + return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x)); +`,PZ=Ot({opSnippet:RZ}),a9={kernelName:vh,backendName:"webgl",kernelFunc:PZ};var l9="return exp(x);",bw=Ot({opSnippet:l9,packedOpSnippet:l9,cpuKernelImpl:i6}),c9={kernelName:bh,backendName:"webgl",kernelFunc:bw};function k0(n){let{inputs:t,attrs:e,backend:r}=n,{dim:i}=e,{input:o}=t,s=o.shape.length,a=o.shape.slice(),l=i;return i<0&&(R.assert(-(s+1)<=i,()=>`Axis must be in the interval [${-(s+1)}, ${s}]`),l=s+i+1),a.splice(l,0,1),Tt({inputs:{x:o},backend:r,attrs:{shape:a}})}var u9={kernelName:Ym,backendName:"webgl",kernelFunc:k0};var h9="return exp(x) - 1.0;",NZ=Ot({opSnippet:h9,packedOpSnippet:h9,cpuKernelImpl:o6}),p9={kernelName:_h,backendName:"webgl",kernelFunc:NZ};var _p=class{constructor(t,e,r){this.variableNames=["real","imag"];let i=e[1];this.outputShape=e;let o=r?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=r?`${i}.0`:"1.0",a;if(t==="real")a="return real * expR - imag * expI;";else if(t==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${t}.`);this.userCode=` + const float exponentMultiplier = ${o}; + + float unaryOpComplex(float real, float expR, float imag, float expI) { + ${a} + } + + float mulMatDFT(int batch, int index) { + float indexRatio = float(index) / float(${i}); + float exponentMultiplierTimesIndexRatio = + exponentMultiplier * indexRatio; + + float result = 0.0; + + for (int i = 0; i < ${i}; i++) { + // x = (-2|2 * PI / N) * index * i; + float x = exponentMultiplierTimesIndexRatio * float(i); + float expR = cos(x); + float expI = sin(x); + float real = getReal(batch, i); + float imag = getImag(batch, i); + + result += + unaryOpComplex(real, expR, imag, expI) / ${s}; + } + + return result; + } + + void main() { + ivec2 coords = getOutputCoords(); + setOutput(mulMatDFT(coords[0], coords[1])); + } + `}};function R0(n,t,e){let r=e.texData.get(n.dataId),i=R.sizeFromShape(n.shape),o=n.shape[n.shape.length-1],s=i/o,a=Tt({inputs:{x:n},backend:e,attrs:{shape:[s,o]}}),l=a.shape,c=new _p("real",l,t),u=new _p("imag",l,t),h=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:l},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:l}],p=e.runWebGLProgram(c,h,"float32"),d=e.runWebGLProgram(u,h,"float32"),f=tr({inputs:{real:p,imag:d},backend:e});e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(d);let m=Tt({inputs:{x:f},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(f),m}function LZ(n){let{inputs:t,backend:e}=n,{input:r}=t;return R0(r,!1,e)}var d9={kernelName:Zm,backendName:"webgl",kernelFunc:LZ};var P0=class{constructor(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=` + uniform float value; + void main() { + // Input can be obtained from uniform value. + setOutput(value); + } + `}getCustomSetupFunc(t){return(e,r)=>{this.valueLoc==null&&(this.valueLoc=e.getUniformLocationNoThrow(r,"value")),e.gl.uniform1f(this.valueLoc,t)}}};function wp(n){let{backend:t,attrs:e}=n,{shape:r,value:i}=e,{dtype:o}=e;if(o=o||R.inferDtype(i),o==="string"){let s=R.getArrayFromDType(o,R.sizeFromShape(r));return s.fill(i),t.makeTensorInfo(r,o,s)}else{let s=new P0(r,i),a=s.getCustomSetupFunc(i);return t.runWebGLProgram(s,[],o,a)}}var f9={kernelName:Jm,backendName:"webgl",kernelFunc:wp};var N0=class{constructor(t){this.variableNames=["Image"],this.outputShape=[];let e=t[2];this.outputShape=t,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int x = coords[2]; + + int coordX = ${e} - x; + float outputValue; + if(coordX >= 0 && coordX < ${e}) { + outputValue = getImage(coords[0], coords[1], coordX, coords[3]); + } else { + outputValue = getImage(coords[0], coords[1], coords[2], coords[3]); + } + setOutput(outputValue); + } + `}};var m9={kernelName:Qm,backendName:"webgl",kernelFunc:({inputs:n,backend:t})=>{let{image:e}=n,r=t,i=new N0(e.shape);return r.runWebGLProgram(i,[e],e.dtype)}};var g9="return floor(x);",DZ=Ot({opSnippet:g9,packedOpSnippet:g9,cpuKernelImpl:s6}),x9={kernelName:wh,backendName:"webgl",kernelFunc:DZ};var zZ=` + float s = sign(a) * sign(b); + int ia = round(a); + int ib = round(b); + if (ib != 0) { + // Windows (D3D) wants guaranteed non-zero int division at compile-time. + return float(idiv(ia, ib, s)); + } else { + return NAN; + } +`,FZ=` + ivec4 ia = round(a); + ivec4 ib = round(b); + bvec4 cond = notEqual(ib, ivec4(0)); + ivec4 result = ivec4(0); + vec4 s = sign(a) * sign(b); + + // Windows (D3D) wants guaranteed non-zero int division at compile-time. + if (cond[0]) { + result[0] = idiv(ia[0], ib[0], s[0]); + } + if (cond[1]) { + result[1] = idiv(ia[1], ib[1], s[1]); + } + if (cond[2]) { + result[2] = idiv(ia[2], ib[2], s[2]); + } + if (cond[3]) { + result[3] = idiv(ia[3], ib[3], s[3]); + } + return vec4(result); +`,OZ=me({opSnippet:zZ,packedOpSnippet:FZ,dtype:"int32"}),v9={kernelName:Sh,backendName:"webgl",kernelFunc:OZ};var L0=class{constructor(t){this.variableNames=["A"];let e=Le(),[r,i]=t;this.outputShape=t,this.userCode=` + void main() { + ivec3 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + int depth = coords[2]; + vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${i}.0, ${r}.0); + + vec4 values = ${e.texture2D}(A, uv); + float value; + if (depth == 0) { + value = values.r; + } else if (depth == 1) { + value = values.g; + } else if (depth == 2) { + value = values.b; + } else if (depth == 3) { + value = values.a; + } + + setOutput(floor(value * 255.0 + 0.5)); + } + `}};var D0=class{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let e=Le(),[r,i]=t;this.outputShape=t,this.userCode=` + void main() { + ivec3 coords = getOutputCoords(); + int texR = coords[0]; + int texC = coords[1]; + int depth = coords[2]; + + vec4 result = vec4(0.); + + for(int row=0; row<=1; row++) { + for(int col=0; col<=1; col++) { + texC = coords[1] + row; + depth = coords[2] + col; + + vec2 uv = (vec2(texC, texR) + halfCR) / + vec2(${i}.0, ${r}.0); + vec4 values = ${e.texture2D}(A, uv); + float value; + if (depth == 0) { + value = values.r; + } else if (depth == 1) { + value = values.g; + } else if (depth == 2) { + value = values.b; + } else if (depth == 3) { + value = values.a; + } + + result[row * 2 + col] = floor(value * 255.0 + 0.5); + } + } + + ${e.output} = result; + } + `}};var y9={kernelName:DT,backendName:"webgl",kernelFunc:BZ},lc;function BZ(n){let{inputs:t,backend:e,attrs:r}=n,{pixels:i}=t,{numChannels:o}=r,s=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,a=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,[l,c]=s?[i.videoWidth,i.videoHeight]:[i.width,i.height],u=[c,l],h=[c,l,o];(a||s)&&(lc==null&&(lc=document.createElement("canvas").getContext("2d")),lc.canvas.width=l,lc.canvas.height=c,lc.drawImage(i,0,0,l,c),i=lc.canvas);let p=e.makeTensorInfo(u,"int32");e.texData.get(p.dataId).usage=Pn.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(p.dataId),i);let d=ot().getBool("WEBGL_PACK")?new D0(h):new L0(h),f=e.runWebGLProgram(d,[p],"int32");return e.disposeData(p.dataId),f}function VZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,filter:o,bias:s,preluActivationWeights:a}=t,{strides:l,pad:c,dataFormat:u,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=r,m=F.convertConv2DDataFormat(u),x=F.computeConv2DInfo(i.shape,o.shape,l,h,c,p,!1,m),g,v=[];if(x.filterHeight===1&&x.filterWidth===1&&x.dilationHeight===1&&x.dilationWidth===1&&x.strideHeight===1&&x.strideWidth===1&&(x.padInfo.type==="SAME"||x.padInfo.type==="VALID"))g=v0({x:i,filter:o,convInfo:x,backend:e,bias:s,activation:d,preluActivationWeights:a,leakyreluAlpha:f});else if(ot().getBool("WEBGL_CONV_IM2COL")&&i.shape[0]===1)g=y0({x:i,filter:o,convInfo:x,backend:e,bias:s,activation:d,preluActivationWeights:a,leakyreluAlpha:f});else{let y=s!=null,_=a!=null,S=d==="leakyrelu",E=d?Go(d,!1):null,M=new oc(x,y,E,_,S),P=[i,o];if(s&&P.push(s),a&&P.push(a),S){let D=e.makeTensorInfo([],"float32",R.createScalarValue(f,"float32"));P.push(D),v.push(D)}g=e.runWebGLProgram(M,P,"float32")}let b=Tt({inputs:{x:g},backend:e,attrs:{shape:x.outShape}});return v.push(g),v.forEach(y=>e.disposeIntermediateTensorInfo(y)),b}var b9={kernelName:Yg,backendName:"webgl",kernelFunc:VZ};function HZ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,filter:o,bias:s,preluActivationWeights:a}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:h,activation:p,leakyreluAlpha:d}=r,f=[],m=u;m==null&&(m=[1,1]),R.assert(F.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let x=F.computeConv2DInfo(i.shape,o.shape,l,m,c,h,!0),g=ot().getBool("WEBGL_PACK_DEPTHWISECONV")&&x.strideWidth<=2&&x.outChannels/x.inChannels===1,v=p?Go(p,g):null,b=[i,o],y=s!=null,_=a!=null,S=p==="leakyrelu";if(y&&b.push(s),_&&b.push(a),S){let P=e.makeTensorInfo([],"float32",R.createScalarValue(d,"float32"));b.push(P),f.push(P)}let E;g?E=new ac(x,y,v,_,S):E=new sc(x,y,v,_,S);let M=e.runWebGLProgram(E,b,"float32");return f.forEach(P=>e.disposeIntermediateTensorInfo(P)),M}var _9={kernelName:Zg,backendName:"webgl",kernelFunc:HZ};var z0=class{constructor(t,e,r){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=r;let i=ne(e.length),o=ne(r.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode=` + ${i} strides = ${i}(${this.strides}); + void main() { + ${o} coords = getOutputCoords(); + int flattenIndex = 0; + for (int j = 0; j < ${this.sliceDim}; j++) { + int index = round(getIndices(coords[0], j)); + flattenIndex += index * ${s}; + } + setOutput(getX(flattenIndex, coords[1])); + } + `}};function $Z(n){let{inputs:t,backend:e}=n,{params:r,indices:i}=t,o=i.shape,s=o[o.length-1],[a,l,c,u]=F.prepareAndValidate(r,i),h=Tt({inputs:{x:i},backend:e,attrs:{shape:[l,s]}}),p=Tt({inputs:{x:r},backend:e,attrs:{shape:[R.sizeFromShape(r.shape)/c,c]}}),d=new z0(s,u,[l,c]),f=e.runWebGLProgram(d,[p,h],p.dtype),m=Tt({inputs:{x:f},backend:e,attrs:{shape:a}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),m}var w9={kernelName:ng,backendName:"webgl",kernelFunc:$Z};var F0=class{constructor(t,e){this.variableNames=["A","indices"],this.outputShape=e,this.rank=e.length;let r=ne(this.rank),i=UZ(t,2);this.userCode=` + void main() { + ${r} resRC = getOutputCoords(); + setOutput(getA(${i})); + } + `}};function UZ(n,t){let e=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let i=0;ie.disposeIntermediateTensorInfo(_)),e.makeTensorInfo(c.outputShape,y.dtype,y.values)}let m=new F0(p.shape,f),x=e.runWebGLProgram(m,[p,d],p.dtype);h.push(x);let g=Tt({inputs:{x},backend:e,attrs:{shape:c.outputShape}});return h.forEach(v=>e.disposeIntermediateTensorInfo(v)),g}var S9={kernelName:eg,backendName:"webgl",kernelFunc:WZ};var GZ="return float(a > b);",jZ=` + return vec4(greaterThan(a, b)); +`,qZ=me({opSnippet:GZ,packedOpSnippet:jZ,cpuKernelImpl:l6,dtype:"bool"}),C9={kernelName:Ch,backendName:"webgl",kernelFunc:qZ};var XZ="return float(a >= b);",KZ=` + return vec4(greaterThanEqual(a, b)); +`,YZ=me({opSnippet:XZ,packedOpSnippet:KZ,dtype:"bool"}),M9={kernelName:Mh,backendName:"webgl",kernelFunc:YZ};function ZZ(n){let{inputs:t,backend:e}=n,{input:r}=t;return R0(r,!0,e)}var E9={kernelName:rg,backendName:"webgl",kernelFunc:ZZ};var JZ="return float(!isnan(x) && !isinf(x));",QZ=Ot({opSnippet:JZ,dtype:"bool"}),T9={kernelName:Eh,backendName:"webgl",kernelFunc:QZ};var tJ="return float(isinf(x));",eJ=Ot({opSnippet:tJ,dtype:"bool"}),A9={kernelName:Th,backendName:"webgl",kernelFunc:eJ};var nJ="return float(isnan(x));",rJ=Ot({opSnippet:nJ,dtype:"bool"}),I9={kernelName:Ah,backendName:"webgl",kernelFunc:rJ};var iJ="return float(a < b);",oJ=` + return vec4(lessThan(a, b)); +`,sJ=me({opSnippet:iJ,packedOpSnippet:oJ,cpuKernelImpl:c6,dtype:"bool"}),k9={kernelName:Ih,backendName:"webgl",kernelFunc:sJ};var aJ="return float(a <= b);",lJ=` + return vec4(lessThanEqual(a, b)); +`,cJ=me({opSnippet:aJ,packedOpSnippet:lJ,dtype:"bool"}),R9={kernelName:kh,backendName:"webgl",kernelFunc:cJ};function uJ(n){let{backend:t,attrs:e}=n,{start:r,stop:i,num:o}=e,s=u6(r,i,o);return t.makeTensorInfo([s.length],"float32",s)}var P9={kernelName:og,backendName:"webgl",kernelFunc:uJ};var hJ=`if (x < 0.0) return NAN; + return log(x);`,pJ=` + vec4 result = log(x); + vec4 isNaN = vec4(lessThan(x, vec4(0.0))); + result.r = isNaN.r == 1.0 ? NAN : result.r; + result.g = isNaN.g == 1.0 ? NAN : result.g; + result.b = isNaN.b == 1.0 ? NAN : result.b; + result.a = isNaN.a == 1.0 ? NAN : result.a; + + return result; +`,dJ=Ot({opSnippet:hJ,packedOpSnippet:pJ,cpuKernelImpl:h6}),N9={kernelName:Rh,backendName:"webgl",kernelFunc:dJ};var fJ="return log(1.0 + x);",mJ=Ot({opSnippet:fJ}),L9={kernelName:Ph,backendName:"webgl",kernelFunc:mJ};var gJ="return float(a >= 1.0 && b >= 1.0);",xJ=` + return vec4( + vec4(greaterThanEqual(a, vec4(1.0))) * + vec4(greaterThanEqual(b, vec4(1.0)))); +`,vJ=me({opSnippet:gJ,packedOpSnippet:xJ,dtype:"bool"}),D9={kernelName:Nh,backendName:"webgl",kernelFunc:vJ};var yJ="return float(!(x >= 1.0));",bJ=Ot({opSnippet:yJ}),z9={kernelName:Lh,backendName:"webgl",kernelFunc:bJ};var _J="return float(a >= 1.0 || b >= 1.0);",wJ=` + return min( + vec4(greaterThanEqual(a, vec4(1.0))) + + vec4(greaterThanEqual(b, vec4(1.0))), + vec4(1.0)); +`,SJ=me({opSnippet:_J,packedOpSnippet:wJ,dtype:"bool"}),F9={kernelName:Dh,backendName:"webgl",kernelFunc:SJ};var O0=class{constructor(t,e,r,i,o){this.variableNames=["x"],this.outputShape=[];let s=e,a=t[3]-1;this.outputShape=t;let l,c=`float(${r}) + float(${i}) * sum`;o===.5?l=`inversesqrt(${c})`:o===1?l=`1.0/(${c})`:l=`exp(log(${c}) * float(-${o}));`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int r = coords[1]; + int c = coords[2]; + int d = coords[3]; + float x = getX(b, r, c, d); + float sum = 0.0; + for (int j = -${s}; j <= ${s}; j++) { + int idx = d + j; + if (idx >= 0 && idx <= ${a}) { + float z = getX(b, r, c, idx); + sum += z * z; + } + } + float val = x * ${l}; + setOutput(val); + } + `}};var B0=class{constructor(t,e,r,i,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=e,a=t[3]-1;this.outputShape=t;let l,c=`float(${r}) + float(${i}) * sum`;o===.5?l=`inversesqrt(${c})`:o===1?l=`1.0/(${c})`:l=`exp(log(${c}) * float(-${o}));`,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords.x; + int r = coords.y; + int c = coords.z; + int d = coords.w; + + bool hasNextCol = d < ${this.outputShape[3]}; + bool hasNextRow = c < ${this.outputShape[2]}; + + vec4 sum = vec4(0.); + vec4 xFragAtOutputCoords = getX(b, r, c, d); + + vec4 xAtOutputCoords = vec4( + getChannel(xFragAtOutputCoords, vec2(c, d)), + hasNextCol ? + getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0, + hasNextRow ? + getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0, + (hasNextRow && hasNextCol) ? + getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0 + ); + + int firstChannel = d - ${s}; + vec2 cache = vec2(0.); + if(firstChannel >= 0){ + vec4 firstChannelFrag = getX(b, r, c, firstChannel); + cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel)); + if(hasNextRow){ + cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel)); + } + } + + ivec2 depth = ivec2(d, d + 1); + for (int j = - ${s}; j <= ${s}; j++) { + ivec2 idx = depth + j; + bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); + bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a})); + + bool depthInRange = aboveLowerBound.x && belowUpperBound.x; + bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y; + + if(depthInRange || depthPlusOneInRange){ + vec4 z = vec4(0.); + vec4 xFragAtCurrentDepth; + z.xz = cache.xy; + if(depthPlusOneInRange && hasNextCol){ + xFragAtCurrentDepth = idx.y != d ? + getX(b, r, c, idx.y) : xFragAtOutputCoords; + z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y)); + if(hasNextRow){ + z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y)); + } + } + cache.xy = z.yw; + sum += z * z; + } + } + vec4 result = xAtOutputCoords * ${l}; + setOutput(result); + } + `}};var CJ=n=>{let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{depthRadius:o,bias:s,alpha:a,beta:l}=r,c=ot().getBool("WEBGL_PACK_NORMALIZATION")?new B0(i.shape,o,s,a,l):new O0(i.shape,o,s,a,l);return e.runWebGLProgram(c,[i],i.dtype)},O9={kernelName:sg,backendName:"webgl",kernelFunc:CJ};var V0=class{constructor(t,e,r,i,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=r,this.alpha=i,this.beta=o,this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int r = coords[1]; + int c = coords[2]; + + float result = 0.0; + for (int d = 0; d < ${this.depth}; ++d) { + int depthBegin = int(max(0.0, float(d - ${e}))); + int depthEnd = int(min(float(${this.depth}), + float(d + ${e} + 1))); + + const int MIN_DEPTH_BEGIN = 0; + const int MAX_DEPTH_END = ${this.depth}; + + float norm = 0.0; + for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) { + if (k < depthBegin){ + continue; + } + else if (k >= depthBegin && k < depthEnd) { + norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k); + } + else { + break; + } + } + + norm = float(${i}) * norm + float(${r}); + + for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){ + if (k < depthBegin){ + continue; + } + else if (k >= depthBegin && k < depthEnd){ + float dyi = -2.0 * float(${i}) + * float(${o}) + * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d) + / norm; + if (k == d) { + dyi += pow(norm, -1.0 * ${o}); + } + if (k == coords[3]) { + dyi *= getDy(b, r, c, d); + result += dyi; + } + } + else { + break; + } + } + } + setOutput(result); + } + `}};var MJ=n=>{let{inputs:t,backend:e,attrs:r}=n,{x:i,y:o,dy:s}=t,{depthRadius:a,bias:l,alpha:c,beta:u}=r,h=new V0(i.shape,a,l,c,u);return e.runWebGLProgram(h,[i,o,s],i.dtype)},B9={kernelName:ag,backendName:"webgl",kernelFunc:MJ};function V9(n,t,e,r){let i=R.sizeFromShape(t),s=R.sizeFromShape(n.shape)/i,a=Tt({inputs:{x:n},attrs:{shape:[s,i]},backend:r}),l=cr(a,n.dtype,"max",r),c=Tt({inputs:{x:l},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(l),c}function _w(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{reductionIndices:o,keepDims:s}=r,a=i.shape.length,l=R.parseAxisParam(o,i.shape),c=l,u=F.getAxesPermutation(c,a),h=u!=null,p=e.shouldExecuteOnCPU([i]),d=i;if(h){if(p){let b=e.texData.get(d.dataId).values,y=new Array(a);for(let E=0;E`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${c}'`);let u=F.computePool2DInfo(i.shape,o,s,c,a,l);if(u.filterWidth===1&&u.filterHeight===1&&R.arraysEqual(u.inShape,u.outShape))return Be({inputs:{x:i},backend:e});let h=new Jr(u,"max",!1);return e.runWebGLProgram(h,[i],i.dtype)}var U9={kernelName:cg,backendName:"webgl",kernelFunc:IJ};function kJ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{filterSize:o,strides:s,pad:a,dataFormat:l,dimRoundingMode:c}=r,u=[1,1,1],h=F.computePool3DInfo(i.shape,o,s,u,a,c,l),p=new qo(h,"max",!1);return e.runWebGLProgram(p,[i],i.dtype)}var W9={kernelName:hg,backendName:"webgl",kernelFunc:kJ};var H0=class{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;let e=t.strideHeight,r=t.strideWidth,i=t.dilationHeight,o=t.effectiveFilterHeight,s=t.effectiveFilterWidth,a=o-1-t.padInfo.top,l=s-1-t.padInfo.left,c=o*s-1;this.userCode=` + const ivec2 pads = ivec2(${a}, ${l}); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + + ivec2 dyRCCorner = coords.yz - pads; + int dyRCorner = dyRCCorner.x; + int dyCCorner = dyRCCorner.y; + + // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + for (int wR = 0; wR < ${o}; + wR += ${i}) { + float dyR = float(dyRCorner + wR) / ${e}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${s}; wC++) { + float dyC = float(dyCCorner + wC) / ${r}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(b, idyR, idyC, d); + int maxPosValue = ${c} - int(getMaxPos(b, idyR, idyC, d)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = wR * ${s} + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + setOutput(dotProd); + } + `}},$0=class{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;let e=t.strideDepth,r=t.strideHeight,i=t.strideWidth,o=t.dilationDepth,s=t.dilationHeight,a=t.dilationWidth,l=t.effectiveFilterDepth,c=t.effectiveFilterHeight,u=t.effectiveFilterWidth,h=l-1-t.padInfo.front,p=c-1-t.padInfo.top,d=u-1-t.padInfo.left,f=l*c*u-1;this.userCode=` + const ivec3 pads = ivec3(${h}, ${p}, ${d}); + + void main() { + ivec5 coords = getOutputCoords(); + int batch = coords.x; + int ch = coords.u; + + ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; + int dyDCorner = dyCorner.x; + int dyRCorner = dyCorner.y; + int dyCCorner = dyCorner.z; + + // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get + // dx(xD, xR, xC, ch). + // ? = to be determined. : = across all values in that axis. + float dotProd = 0.0; + + for (int wD = 0; wD < ${l}; + wD += ${o}) { + float dyD = float(dyDCorner + wD) / ${e}.0; + + if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) { + continue; + } + int idyD = int(dyD); + + for (int wR = 0; wR < ${c}; + wR += ${s}) { + float dyR = float(dyRCorner + wR) / ${r}.0; + + if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || + fract(dyR) > 0.0) { + continue; + } + int idyR = int(dyR); + + for (int wC = 0; wC < ${u}; + wC += ${a}) { + float dyC = float(dyCCorner + wC) / ${i}.0; + + if (dyC < 0.0 || dyC >= ${t.outWidth}.0 || + fract(dyC) > 0.0) { + continue; + } + int idyC = int(dyC); + + float dyValue = getDy(batch, idyD, idyR, idyC, ch); + int maxPosValue = ${f} - + int(getMaxPos(batch, idyD, idyR, idyC, ch)); + + // Get the current value, check it against the value from the + // position matrix. + int curPosValue = + wD * ${c} * ${u} + + wR * ${u} + wC; + float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); + + dotProd += dyValue * mask; + } + } + } + setOutput(dotProd); + } + `}};function RJ(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,input:o}=t,s=o,{filterSize:a,strides:l,pad:c,dimRoundingMode:u}=r,h=[1,1,1],p=F.computePool3DInfo(s.shape,a,l,h,c,u),d=new qo(p,"max",!0),f=e.runWebGLProgram(d,[s],s.dtype),m=new $0(p),x=e.runWebGLProgram(m,[i,f],s.dtype);return e.disposeIntermediateTensorInfo(f),x}var G9={kernelName:pg,backendName:"webgl",kernelFunc:RJ};function PJ(n){let{inputs:t,backend:e,attrs:r}=n,{dy:i,input:o,output:s}=t,a=o;Ti([o,s],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:h}=r,p=F.computePool2DInfo(a.shape,l,c,1,u,h),d=!0,f=new Jr(p,"max",d),m=e.runWebGLProgram(f,[a],a.dtype),x=new H0(p),g=e.runWebGLProgram(x,[i,m],a.dtype);return e.disposeIntermediateTensorInfo(m),g}var j9={kernelName:ug,backendName:"webgl",kernelFunc:PJ};function q9(n,t,e,r){let i=new Jr(e,"max",!1),o=r.runWebGLProgram(i,[n],"float32");i=new Jr(e,"max",!0,!0,t);let s=r.runWebGLProgram(i,[n],"float32");return[o,s]}var X9={kernelName:dg,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{x:r}=n,{filterSize:i,strides:o,pad:s,includeBatchInIndex:a}=t,l=e;R.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let c=[1,1];R.assert(F.eitherStridesOrDilationsAreOne(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=F.computePool2DInfo(r.shape,i,o,c,s),[h,p]=q9(r,a,u,l);return[h,p]}};function K9(n,t,e,r){let i=R.sizeFromShape(t),s=R.sizeFromShape(n.shape)/i,a=Tt({inputs:{x:n},attrs:{shape:[s,i]},backend:r}),l=cr(a,"float32","mean",r),c=Tt({inputs:{x:l},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(l),c}var Y9={kernelName:fg,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{x:r}=n,{keepDims:i,axis:o}=t,s=e,a=r.shape.length,l=R.parseAxisParam(o,r.shape),c=l,u=F.getAxesPermutation(c,a),h=u!=null,p=s.shouldExecuteOnCPU([r]),d=[],f=r;if(h){if(p){let y=s.texData.get(f.dataId).values,_=new Array(a);for(let M=0;M<_.length;M++)_[M]=r.shape[u[M]];let S=la(y,r.shape,r.dtype,u,_);f=s.makeTensorInfo(_,r.dtype);let E=s.texData.get(f.dataId);E.values=S}else f=jo(r,u,s);d.push(f),c=F.getInnerMostAxes(c.length,a)}F.assertAxesAreInnerMostDims("sum",c,a);let[m,x]=F.computeOutAndReduceShapes(f.shape,c),g=m;i&&(g=F.expandShapeToKeepDim(m,l));let v=K9(f,x,g,s);for(let b of d)s.disposeIntermediateTensorInfo(b);return v}};function NJ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o,keepDims:s}=r,a=i.shape.length,l=R.parseAxisParam(o,i.shape),c=l,u=F.getAxesPermutation(c,a),h=i;u!=null&&(h=Pe({inputs:{x:i},backend:e,attrs:{perm:u}}),c=F.getInnerMostAxes(c.length,i.shape.length)),F.assertAxesAreInnerMostDims("min",c,a);let[p,d]=F.computeOutAndReduceShapes(h.shape,c),f=R.sizeFromShape(d),m=Tt({inputs:{x:h},backend:e,attrs:{shape:[-1,f]}}),x=cr(m,m.dtype,"min",e),g;if(s){let v=F.expandShapeToKeepDim(p,l);g=Tt({inputs:{x},backend:e,attrs:{shape:v}})}else g=Tt({inputs:{x},backend:e,attrs:{shape:p}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(x),u!=null&&e.disposeIntermediateTensorInfo(h),g}var Z9={kernelName:mg,backendName:"webgl",kernelFunc:NJ};var LJ=q1+` + return min(a, b); +`,DJ=` + vec4 result = vec4(min(a, b)); + vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); + `+Wo+` + return result; +`,zJ=me({opSnippet:LJ,packedOpSnippet:DJ,cpuKernelImpl:f6}),J9={kernelName:Fh,backendName:"webgl",kernelFunc:zJ};var U0=class{constructor(t,e,r){this.variableNames=["x"],this.outputShape=e.map((u,h)=>u[0]+t[h]+u[1]);let i=t.length,o=ne(i),s=e.map(u=>u[0]).join(","),a=e.map((u,h)=>u[0]+t[h]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,i),c=r==="reflect"?0:1;if(i===1){this.userCode=` + int start = ${s}; + int end = ${a}; + + void main() { + int outC = getOutputCoords(); + if (outC < start) { + outC = start * 2 - outC - ${c}; + } else if(outC >= end) { + outC = (end - 1) * 2 - outC + ${c}; + } + setOutput(getX(outC - start)); + } + `;return}this.userCode=` + ${o} start = ${o}(${s}); + ${o} end = ${o}(${a}); + + void main() { + ${o} outC = getOutputCoords(); + for (int i = 0; i < ${i}; i++) { + if (outC[i] < start[i]) { + outC[i] = start[i] * 2 - outC[i] - ${c}; + } else if(outC[i] >= end[i]) { + outC[i] = (end[i] - 1) * 2 - outC[i] + ${c}; + } + } + ${o} coords = outC - start; + setOutput(getX(${l})); + } + `}};var W0=class{constructor(t,e,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((f,m)=>f[0]+t[m]+f[1]);let i=t.length,o=ne(i),s=e.map(f=>f[0]).join(","),a=e.map((f,m)=>f[0]+t[m]).join(","),l=Oe("rc",i),c=Oe("source",i),u=`${l[i-1]} < ${this.outputShape[i-1]}`,h=i===1?"source":`vec2(${c.slice(-2).join()})`,p=r==="reflect"?0:1,d="";if(i===1){let f=` + ${o} source = rc; + if (source < start) { + source = start * 2 - source - ${p}; + } else if (source >= end) { + source = (end - 1) * 2 - source + ${p}; + } + source -= start; + `;d=` + ${o} rc = outputLoc; + ${f} + result[0] = getChannel(getX(${c.join()}), ${h}); + ${l[i-1]} += 1; + if(${u}) { + ${f} + result[1] = getChannel(getX(${c.join()}), ${h}); + } + `}else{let f=` + ${o} source = rc; + ${o} lt = ${o}(lessThan(source, start)); + ${o} gte = ${o}(greaterThanEqual(source, end)); + ${o} orig = 1 - (lt + gte); + source = orig * source + + lt * (start * 2 - source - ${p}) + + gte * ((end - 1) * 2 - source + ${p}); + source -= start; + `;d=` + ${o} rc = outputLoc; + ${f} + result[0] = getChannel(getX(${c.join()}), ${h}); + ${l[i-1]} += 1; + if(${u}) { + ${f} + result[1] = getChannel(getX(${c.join()}), ${h}); + } + rc = outputLoc; + ${l[i-2]} += 1; + if(${l[i-2]} < ${this.outputShape[i-2]}) { + ${f} + result[2] = getChannel(getX(${c.join()}), ${h}); + ${l[i-1]} += 1; + if(${u}) { + ${f} + result[3] = getChannel(getX(${c.join()}), ${h}); + } + } + `}this.userCode=` + const ${o} start = ${o}(${s}); + const ${o} end = ${o}(${a}); + + void main() { + ${o} outputLoc = getOutputCoords(); + vec4 result = vec4(0.); + ${d} + setOutput(result); + } + `}};var FJ=({inputs:n,backend:t,attrs:e})=>{let{x:r}=n,{paddings:i,mode:o}=e,s=ot().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new W0(r.shape,i,o):new U0(r.shape,i,o);return t.runWebGLProgram(s,[r],r.dtype)},Q9={kernelName:gg,backendName:"webgl",kernelFunc:FJ};var OJ=`if (b == 0.0) return NAN; + return mod(a, b);`,BJ=` + vec4 result = mod(a, b); + vec4 isNaN = vec4(equal(b, vec4(0.0))); + `+Wo+` + return result; +`,VJ=me({opSnippet:OJ,packedOpSnippet:BJ}),tL={kernelName:Oh,backendName:"webgl",kernelFunc:VJ};var G0=class{constructor(t,e,r){this.variableNames=["probs"],this.outputShape=[t,r],this.userCode=` + uniform float seed; + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + + float r = random(seed); + float cdf = 0.0; + + for (int i = 0; i < ${e-1}; i++) { + cdf += getProbs(batch, i); + + if (r < cdf) { + setOutput(float(i)); + return; + } + } + + // If no other event happened, last event happened. + setOutput(float(${e-1})); + } + `}getCustomSetupFunc(t){return(e,r)=>{this.seedLoc==null&&(this.seedLoc=e.getUniformLocation(r,"seed")),e.gl.uniform1f(this.seedLoc,t)}}};var HJ=` +if (a == b) { + return 1.0; +}; +return a / b;`,$J=` + // vec4 one = vec4(equal(a, b)); + // return one + (vec4(1.0) - one) * a / b; + vec4 result = a / b; + if(a.x == b.x) { + result.x = 1.; + } + if(a.y == b.y) { + result.y = 1.; + } + if(a.z == b.z) { + result.z = 1.; + } + if(a.w == b.w) { + result.w = 1.; + } + + return result; +`,ww=me({opSnippet:HJ,packedOpSnippet:$J,checkOutOfBounds:!0}),eL={kernelName:xh,backendName:"webgl",kernelFunc:ww};var nL="return a - b;",Sw=me({opSnippet:nL,packedOpSnippet:nL,supportsComplex:!0,cpuKernelImpl:w6}),rL={kernelName:Xs,backendName:"webgl",kernelFunc:Sw};function Cw(n){let{inputs:t,backend:e,attrs:r}=n,{logits:i}=t,{dim:o}=r,s=R.parseAxisParam([o],i.shape),a=_w({inputs:{x:i},backend:e,attrs:{reductionIndices:s,keepDims:!1}}),l=F.expandShapeToKeepDim(a.shape,s),c=Tt({inputs:{x:a},backend:e,attrs:{shape:l}}),u=Sw({inputs:{a:i,b:c},backend:e}),h=bw({inputs:{x:u},backend:e}),p=ua({inputs:{x:h},backend:e,attrs:{axis:s,keepDims:!1}}),d=Tt({inputs:{x:p},backend:e,attrs:{shape:l}}),f=ww({inputs:{a:h,b:d},backend:e});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(c),e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(d),f}var iL={kernelName:Fg,backendName:"webgl",kernelFunc:Cw};function UJ(n){let{inputs:t,backend:e,attrs:r}=n,{logits:i}=t,{numSamples:o,seed:s,normalized:a}=r,l=a?i:Cw({inputs:{logits:i},backend:e,attrs:{dim:i.shape.length-1}}),c=l.shape[0],u=l.shape[1],h=new G0(c,u,o),p=h.getCustomSetupFunc(s),d=e.runWebGLProgram(h,[l],"int32",p);return a||e.disposeIntermediateTensorInfo(l),d}var oL={kernelName:xg,backendName:"webgl",kernelFunc:UJ};var sL="return -x;";function WJ(n){let{inputs:t,backend:e}=n,{x:r}=t;if(e.shouldExecuteOnCPU([r])){let o=e.texData.get(r.dataId),[s,a]=g6(o.values,r.shape,r.dtype);return e.makeTensorInfo(a,r.dtype,s)}let i;return ot().getBool("WEBGL_PACK_UNARY_OPERATIONS")?i=new Fr(r.shape,sL):i=new jn(r.shape,sL),e.runWebGLProgram(i,[r],r.dtype)}var aL={kernelName:vg,backendName:"webgl",kernelFunc:WJ};var GJ=kn.nonMaxSuppressionV3Impl;function jJ(n){F.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:r}=n,{boxes:i,scores:o}=t,{maxOutputSize:s,iouThreshold:a,scoreThreshold:l}=r,c=e.readSync(i.dataId),u=e.readSync(o.dataId),{selectedIndices:h}=GJ(c,u,s,a,l);return e.makeTensorInfo([h.length],"int32",new Int32Array(h))}var lL={kernelName:yg,backendName:"webgl",kernelFunc:jJ};var qJ=kn.nonMaxSuppressionV4Impl;function XJ(n){F.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:r}=n,{boxes:i,scores:o}=t,{maxOutputSize:s,iouThreshold:a,scoreThreshold:l,padToMaxOutputSize:c}=r,u=e.readSync(i.dataId),h=e.readSync(o.dataId),{selectedIndices:p,validOutputs:d}=qJ(u,h,s,a,l,c);return[e.makeTensorInfo([p.length],"int32",new Int32Array(p)),e.makeTensorInfo([],"int32",new Int32Array([d]))]}var cL={kernelName:bg,backendName:"webgl",kernelFunc:XJ};var KJ=kn.nonMaxSuppressionV5Impl;function YJ(n){F.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:r}=n,{boxes:i,scores:o}=t,{maxOutputSize:s,iouThreshold:a,scoreThreshold:l,softNmsSigma:c}=r,u=e.readSync(i.dataId),h=e.readSync(o.dataId),p=s,d=a,f=l,m=c,{selectedIndices:x,selectedScores:g}=KJ(u,h,p,d,f,m);return[e.makeTensorInfo([x.length],"int32",new Int32Array(x)),e.makeTensorInfo([g.length],"float32",new Float32Array(g))]}var uL={kernelName:_g,backendName:"webgl",kernelFunc:YJ};var j0=class{constructor(t,e,r,i){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=` + void main() { + ivec2 coords = getOutputCoords(); + int index = round(getIndices(coords.x)); + setOutput(mix(float(${i}), float(${r}), + float(index == coords.y))); + } + `}};var ZJ=n=>{let{inputs:t,backend:e,attrs:r}=n,{indices:i}=t,{depth:o,onValue:s,offValue:a}=r,l=R.sizeFromShape(i.shape),c=new j0(l,o,s,a),u=Tt({inputs:{x:i},backend:e,attrs:{shape:[l]}}),h=e.runWebGLProgram(c,[u],i.dtype);e.disposeIntermediateTensorInfo(u);let p=[...i.shape,o],d=Tt({inputs:{x:h},backend:e,attrs:{shape:p}});return e.disposeIntermediateTensorInfo(h),d},hL={kernelName:Sg,backendName:"webgl",kernelFunc:ZJ};function Sp(n){let{inputs:t,backend:e}=n,{x:r}=t;if(r.dtype==="complex64"){let i=lo({inputs:{input:r},backend:e}),o=Sp({inputs:{x:i},backend:e}),s=pa({inputs:{input:r},backend:e}),a=Sp({inputs:{x:s},backend:e}),l=tr({inputs:{real:o,imag:a},backend:e});return e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(a),l}else return wp({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:e})}var pL={kernelName:qg,backendName:"webgl",kernelFunc:Sp};function dL(n){let{inputs:t,backend:e}=n,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(r.dtype==="complex64"){let i=lo({inputs:{input:r},backend:e}),o=dL({inputs:{x:i},backend:e}),s=pa({inputs:{input:r},backend:e}),a=Sp({inputs:{x:s},backend:e}),l=tr({inputs:{real:o,imag:a},backend:e});return e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(a),l}else return wp({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:e})}var fL={kernelName:wg,backendName:"webgl",kernelFunc:dL};function JJ(n){let{inputs:t,backend:e,attrs:r}=n,{axis:i}=r;if(t.length===1)return k0({inputs:{input:t[0]},backend:e,attrs:{dim:i}});let o=t[0].shape,s=t[0].dtype;t.forEach(u=>{R.assertShapesMatch(o,u.shape,"All tensors passed to stack must have matching shapes"),R.assert(s===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],l=t.map(u=>{let h=k0({inputs:{input:u},backend:e,attrs:{dim:i}});return a.push(h),h}),c=yw({inputs:l,backend:e,attrs:{axis:i}});return a.forEach(u=>e.disposeIntermediateTensorInfo(u)),c}var mL={kernelName:Cg,backendName:"webgl",kernelFunc:JJ};var q0=class{constructor(t,e,r){this.variableNames=["x"],this.outputShape=e.map((c,u)=>c[0]+t[u]+c[1]);let i=t.length,o=ne(i),s=e.map(c=>c[0]).join(","),a=e.map((c,u)=>c[0]+t[u]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,i);if(i===1){this.userCode=` + int start = ${s}; + int end = ${a}; + uniform float value; + + void main() { + int outC = getOutputCoords(); + if (outC < start || outC >= end) { + setOutput(value); + } else { + setOutput(getX(outC - start)); + } + } + `;return}this.userCode=` + ${o} start = ${o}(${s}); + ${o} end = ${o}(${a}); + uniform float value; + + void main() { + ${o} outC = getOutputCoords(); + if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { + setOutput(value); + } else { + ${o} coords = outC - start; + setOutput(getX(${l})); + } + } + `}getCustomSetupFunc(t){return(e,r)=>{this.valueLoc==null&&(this.valueLoc=e.getUniformLocationNoThrow(r,"value")),e.gl.uniform1f(this.valueLoc,t)}}};var X0=class{constructor(t,e,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((m,x)=>m[0]+t[x]+m[1]);let i=t.length,o=ne(i),s=e.map(m=>m[0]).join(","),a=e.map((m,x)=>m[0]+t[x]).join(","),l=Oe("rc",i),c=Oe("source",i),u=`${l[i-1]} < ${this.outputShape[i-1]}`,h=i===1?"source":`vec2(${c.slice(-2).join()})`,p=[`${o} rc = outputLoc;`,`${l[i-1]} += 1; + if(${u}) { + `,i===1?"":`} + rc = outputLoc; + ${l[i-2]} += 1; + if(${l[i-2]} < ${this.outputShape[i-2]}) {`,i===1?"":` ${l[i-1]} += 1; + if(${u}) {`],d=i===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="";for(let m=0,x=i===1?2:4;m{this.valueLoc==null&&(this.valueLoc=e.getUniformLocationNoThrow(r,"value")),e.gl.uniform1f(this.valueLoc,t)}}};var Mw=n=>{let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{paddings:o,constantValue:s}=r,a=ot().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new X0(i.shape,o,s):new q0(i.shape,o,s),l=a.getCustomSetupFunc(s);return e.runWebGLProgram(a,[i],i.dtype,l)},gL={kernelName:Rl,backendName:"webgl",kernelFunc:Mw};var QJ=` + if(a < 0.0 && floor(b) < b){ + return NAN; + } + if (b == 0.0) { + return 1.0; + } + return (round(mod(b, 2.0)) != 1) ? + pow(abs(a), b) : sign(a) * pow(abs(a), b); +`,tQ=` + // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise. + vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1))); + vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); + vec4 result = multiplier * pow(abs(a), b); + + // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS + bvec4 isExpZero = equal(b, vec4(0.0)); + result.r = isExpZero.r ? 1.0 : result.r; + result.g = isExpZero.g ? 1.0 : result.g; + result.b = isExpZero.b ? 1.0 : result.b; + result.a = isExpZero.a ? 1.0 : result.a; + + vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b)); + `+Wo+` + return result; +`,eQ=me({opSnippet:QJ,packedOpSnippet:tQ}),xL={kernelName:Vh,backendName:"webgl",kernelFunc:eQ};function nQ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{axis:o,keepDims:s}=r,a=i.shape.length,l=[],c=R.parseAxisParam(o,i.shape),u=c,h=F.getAxesPermutation(u,a),p=i;h!=null&&(p=Pe({inputs:{x:i},backend:e,attrs:{perm:h}}),u=F.getInnerMostAxes(u.length,a),l.push(p)),F.assertAxesAreInnerMostDims("prod",u,a);let d;if(e.shouldExecuteOnCPU([p])){let f=e.texData.get(p.dataId).values,{outVals:m,outShape:x,outDtype:g}=x6(p.shape,p.dtype,f,u);d=e.makeTensorInfo(x,g,m)}else{let[f,m]=F.computeOutAndReduceShapes(p.shape,u),x=R.sizeFromShape(m),g=Tt({inputs:{x:p},backend:e,attrs:{shape:[-1,x]}}),v=Js(i.dtype),b=cr(g,v,"prod",e);d=Tt({inputs:{x:b},backend:e,attrs:{shape:f}}),l.push(g),l.push(b)}if(s){l.push(d);let f=F.expandShapeToKeepDim(d.shape,c);d=Tt({inputs:{x:d},backend:e,attrs:{shape:f}})}return l.forEach(f=>e.disposeIntermediateTensorInfo(f)),d}var vL={kernelName:Mg,backendName:"webgl",kernelFunc:nQ};var Ew=n=>{let{backend:t,attrs:e}=n,{start:r,stop:i,step:o,dtype:s}=e,a=v6(r,i,o,s);return t.makeTensorInfo([a.length],s,a)},yL={kernelName:Eg,backendName:"webgl",kernelFunc:Ew};var rQ="return 1.0 / x;",iQ=Ot({opSnippet:rQ}),bL={kernelName:Hh,backendName:"webgl",kernelFunc:iQ};var oQ=pn+` + return (x < 0.0) ? 0.0 : x; +`,sQ=` + vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,aQ=Ot({opSnippet:oQ,packedOpSnippet:sQ}),_L={kernelName:js,backendName:"webgl",kernelFunc:aQ};var lQ=pn+` + return (x < 0.0) ? 0.0 : min(6.0, x); +`,cQ=` + vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); + bvec4 isNaN = isnan(x); + + result.r = isNaN.r ? x.r : result.r; + result.g = isNaN.g ? x.g : result.g; + result.b = isNaN.b ? x.b : result.b; + result.a = isNaN.a ? x.a : result.a; + + return result; +`,uQ=Ot({opSnippet:lQ,packedOpSnippet:cQ}),wL={kernelName:qs,backendName:"webgl",kernelFunc:uQ};var K0=class{constructor(t,e,r,i,o){this.variableNames=["A"],this.outputShape=[];let[s,a,l,c]=t;this.outputShape=[s,e,r,c];let u=[i&&e>1?a-1:a,i&&r>1?l-1:l],h=[i&&e>1?e-1:e,i&&r>1?r-1:r],p;o?p="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + ${u[0]/h[0]}, + ${u[1]/h[1]}); + const vec2 inputShapeRC = vec2(${a}.0, ${l}.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = ${p}; + + // Compute the four integer indices. + ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0))); + ivec2 sourceCeilRC = ivec2( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d); + float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d); + float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d); + float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d); + + vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC); + + float top = topLeft + (topRight - topLeft) * fracRC.y; + float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; + float newValue = top + (bottom - top) * fracRC.x; + + setOutput(newValue); + } + `}};var Y0=class{constructor(t,e,r,i,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,a,l,c]=t;this.outputShape=[s,e,r,c];let u=[i&&e>1?a-1:a,i&&r>1?l-1:l],h=[i&&e>1?e-1:e,i&&r>1?r-1:r],p;o?p="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec3 effectiveInputOverOutputRatioRC = vec3( + ${u[0]/h[0]}, + ${u[1]/h[1]}, + ${u[1]/h[1]}); + const vec3 inputShapeRC = vec3(${a}.0, ${l}.0, + ${l}.0); + + float getAValue(int b, int r, int c, int d) { + return getChannel(getA(b, r, c, d), vec2(c, d)); + } + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + // Calculate values for next column in yRC.z. + ivec3 yRC = coords.yzz + ivec3(0, 0, 1); + + // Fractional source index. + vec3 sourceFracIndexRC = ${p}; + + // Compute the four integer indices. + ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0))); + ivec3 sourceCeilRC = ivec3( + min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); + + // Should we calculate next column and row elements in 2x2 packed cell. + bool hasNextCol = d < ${c-1}; + bool hasNextRow = coords.z < ${r-1}; + + // In parallel, construct four corners for all four components in + // packed 2x2 cell. + vec4 topLeft = vec4( + getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d), + hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0); + + vec4 bottomLeft = vec4( + getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d), + hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0); + + vec4 topRight = vec4( + getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d), + hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0); + + vec4 bottomRight = vec4( + getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d), + hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1) + : 0.0, + hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d) + : 0.0, + (hasNextRow && hasNextCol) ? + getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0); + + vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC); + + vec4 top = mix(topLeft, topRight, fracRC.yyzz); + vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz); + vec4 newValue = mix(top, bottom, fracRC.x); + + setOutput(newValue); + } + `}};function hQ(n){let{inputs:t,backend:e,attrs:r}=n,{images:i}=t,{alignCorners:o,halfPixelCenters:s,size:a}=r,[l,c]=a,u=ot().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Y0(i.shape,l,c,o,s):new K0(i.shape,l,c,o,s);return e.runWebGLProgram(u,[i],"float32")}var SL={kernelName:kg,backendName:"webgl",kernelFunc:hQ};var Z0=class{constructor(t,e,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;let[,i,o]=e,[,s,a]=t,l=[r&&s>1?i-1:i,r&&a>1?o-1:o],c=[r&&s>1?s-1:s,r&&a>1?a-1:a],u=l[0]/c[0],h=l[1]/c[1],p=1/u,d=1/h,f=Math.ceil(p)*2+2,m=Math.ceil(d)*2+2;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + int r = coords[1]; + int c = coords[2]; + + float accumulator = 0.0; + + const float heightScale = float(${u}); + const float widthScale = float(${h}); + + const float invHeightScale = float(${p}); + const float invWidthScale = float(${d}); + + const int winHeight = int(${f}); + const int winWidth = int(${m}); + + // Compute bounds for where in dy we will look + float startRLerp = floor(float(r) * invHeightScale); + int startDyR = int(startRLerp - float(winHeight / 2)); + + float startCLerp = floor(float(c) * invWidthScale); + int startDyC = int(startCLerp - float(winWidth / 2)); + + // Loop over dy + for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { + int dyR = dyROffset + startDyR; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= ${s}) { + continue; + } + + for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { + int dyC = dyCOffset + startDyC; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= ${a}) { + continue; + } + + float dxR = float(dyR) * heightScale; + int topDxRIndex = int(floor(dxR)); + int bottomDxRIndex = int(min(ceil(dxR), ${i-1}.0)); + float dxRLerp = dxR - float(topDxRIndex); + float inverseDxRLerp = 1.0 - dxRLerp; + + float dxC = float(dyC) * widthScale; + int leftDxCIndex = int(floor(dxC)); + int rightDxCIndex = int(min(ceil(dxC), ${o-1}.0)); + float dxCLerp = dxC - float(leftDxCIndex); + float inverseDxCLerp = 1.0 - dxCLerp; + + if (r == topDxRIndex && c == leftDxCIndex) { + // topLeft + accumulator += + getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp; + } + + if (r == topDxRIndex && c == rightDxCIndex) { + // topRight + accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp; + } + + if (r == bottomDxRIndex && c == leftDxCIndex) { + // bottomLeft + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp; + } + + if (r == bottomDxRIndex && c == rightDxCIndex) { + // bottomRight + accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp; + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `}};function pQ(n){let{inputs:t,backend:e,attrs:r}=n,{images:i,dy:o}=t,{alignCorners:s}=r,a=new Z0(o.shape,i.shape,s);return e.runWebGLProgram(a,[o],o.dtype)}var CL={kernelName:Rg,backendName:"webgl",kernelFunc:pQ};var J0=class{constructor(t,e,r,i,o){this.variableNames=["A"],this.outputShape=[];let[s,a,l,c]=t;this.outputShape=[s,e,r,c];let u=[i&&e>1?a-1:a,i&&r>1?l-1:l],h=[i&&e>1?e-1:e,i&&r>1?r-1:r],p=i?"0.5":"0.0",d;o?d="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` + const vec2 effectiveInputOverOutputRatioRC = vec2( + ${u[0]/h[0]}, + ${u[1]/h[1]}); + const vec2 inputShapeRC = vec2(${a}.0, ${l}.0); + + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + ivec2 yRC = coords.yz; + + // Fractional source index. + vec2 sourceFracIndexRC = ${d}; + + // Compute the coordinators of nearest neighbor point. + ivec2 sourceNearestRC = ivec2( + min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p}))); + float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); + + setOutput(newValue); + } + `}};function dQ(n){let{inputs:t,backend:e,attrs:r}=n,{images:i}=t,{alignCorners:o,halfPixelCenters:s,size:a}=r,[l,c]=a,u=new J0(i.shape,l,c,o,s);return e.runWebGLProgram(u,[i],i.dtype)}var ML={kernelName:Ag,backendName:"webgl",kernelFunc:dQ};var Q0=class{constructor(t,e,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;let[,i,o]=e,[,s,a]=t,l=[r&&s>1?i-1:i,r&&a>1?o-1:o],c=[r&&s>1?s-1:s,r&&a>1?a-1:a],u=l[0]/c[0],h=l[1]/c[1],p=1/u,d=1/h,f=Math.ceil(p)*2+2,m=Math.ceil(d)*2+2;this.userCode=` + void main() { + ivec4 coords = getOutputCoords(); + int b = coords[0]; + int d = coords[3]; + int r = coords[1]; + int c = coords[2]; + + float accumulator = 0.0; + + const float heightScale = float(${u}); + const float widthScale = float(${h}); + + const float invHeightScale = float(${p}); + const float invWidthScale = float(${d}); + + const int winHeight = int(${f}); + const int winWidth = int(${m}); + + // Compute bounds for where in dy we will look + float startRLerp = floor(float(r) * invHeightScale); + int startDyR = int(floor(startRLerp - float(winHeight / 2))); + + float startCLerp = floor(float(c) * invWidthScale); + int startDyC = int(floor(startCLerp - float(winWidth / 2))); + + // Loop over dy + for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { + int dyR = dyROffset + startDyR; + + // Guard against the window exceeding the bounds of dy + if (dyR < 0 || dyR >= ${s}) { + continue; + } + + for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { + int dyC = dyCOffset + startDyC; + + // Guard against the window exceeding the bounds of dy + if (dyC < 0 || dyC >= ${a}) { + continue; + } + + float sourceFracRow = + float(${l[0]}) * + (float(dyR) / float(${c[0]})); + + float sourceFracCol = + float(${l[1]}) * + (float(dyC) / float(${c[1]})); + + int sourceNearestRow = int(min( + float(int(${i}) - 1), + ${r} ? float(round(sourceFracRow)) : + float(floor(sourceFracRow)))); + + int sourceNearestCol = int(min( + float(int(${o}) - 1), + ${r} ? float(round(sourceFracCol)) : + float(floor(sourceFracCol)))); + + if (r == sourceNearestRow && c == sourceNearestCol) { + accumulator += getDy(b, dyR, dyC, d); + } + } + } + // End loop over dy + + setOutput(accumulator); + } + `}};function fQ(n){let{inputs:t,backend:e,attrs:r}=n,{images:i,dy:o}=t,{alignCorners:s}=r,a=new Q0(o.shape,i.shape,s);return e.runWebGLProgram(a,[o],o.dtype)}var EL={kernelName:Ig,backendName:"webgl",kernelFunc:fQ};var tx=class{constructor(t,e){this.variableNames=["x"];let r=t.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);if(this.outputShape=t,r===1){this.userCode=` + void main() { + int coord = getOutputCoords(); + setOutput(getX(${t[0]} - coord - 1)); + } + `;return}let i=a=>e.indexOf(a)!==-1&&t[a]!==1?`${t[a]} - coords[${a}] - 1`:`coords[${a}]`,o=t.map((a,l)=>i(l)).join(","),s=ne(r);this.userCode=` + void main() { + ${s} coords = getOutputCoords(); + setOutput(getX(${o})); + } + `}};var ex=class{constructor(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let r=t.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);this.outputShape=t;let i=Oe("rc",r),o=`${i[r-1]} + 1 < ${this.outputShape[r-1]}`,s=`${i[r-2]} + 1 < ${this.outputShape[r-2]}`,a=ne(r);r===1?this.userCode=` + void main(){ + int rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = getChannel(getX(${t[0]} - rc - 1), + ${t[0]} - rc - 1); + if(${o}){ + result.g = getChannel(getX(${t[0]} - (rc + 1) - 1), + ${t[0]} - (rc + 1) - 1); + } + setOutput(result); + } + `:this.userCode=` + void main() { + ${a} rc = getOutputCoords(); + vec4 result = vec4(0.); + result.r = ${l(i.slice())}; + if(${o}){ + result.g = ${c(i.slice())}; + } + if(${s}) { + result.b = ${u(i.slice())}; + if(${o}) { + result.a = ${h(i.slice())}; + } + } + setOutput(result); + } + `;function l(f){return p(f)}function c(f){return f[r-1]="("+f[r-1]+" + 1)",p(f)}function u(f){return f[r-2]="("+f[r-2]+" + 1)",p(f)}function h(f){return f[r-1]="("+f[r-1]+" + 1)",f[r-2]="("+f[r-2]+" + 1)",p(f)}function p(f){let m=t.map((v,b)=>d(b,f)),x=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${x}), vec2(${g}))`}function d(f,m){return e.indexOf(f)!==-1&&t[f]!==1?`${t[f]} - ${m[f]} - 1`:`${m[f]}`}}};function mQ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{dims:o}=r,s=i.shape.length,a=R.parseAxisParam(o,i.shape);if(s===0)return Be({inputs:{x:i},backend:e});let l=ot().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ex(i.shape,a):new tx(i.shape,a);return e.runWebGLProgram(l,[i],i.dtype)}var TL={kernelName:Pg,backendName:"webgl",kernelFunc:mQ};var nx=class{constructor(t,e){this.variableNames=["Image"],this.outputShape=[];let r=t[1],i=t[2];this.outputShape=t;let o="";typeof e=="number"?o=`float outputValue = ${e.toFixed(2)};`:o=` + vec3 fill = vec3(${e.join(",")}); + float outputValue = fill[coords[3]];`,this.userCode=` + uniform vec4 params; + void main() { + ivec4 coords = getOutputCoords(); + int x = coords[2]; + int y = coords[1]; + float coordXFloat = (float(x) - params[0]) * params[3] - + (float(y) - params[1]) * params[2]; + float coordYFloat = (float(x) - params[0]) * params[2] + + (float(y) - params[1]) * params[3]; + int coordX = int(round(coordXFloat + params[0])); + int coordY = int(round(coordYFloat + params[1])); + ${o} + if(coordX >= 0 && coordX < ${i} && coordY >= 0 && coordY < ${r}) { + outputValue = getImage(coords[0], coordY, coordX, coords[3]); + } + setOutput(outputValue); + } + `}getCustomSetupFunc(t,e,r,i){return(o,s)=>{this.paramsLoc==null&&(this.paramsLoc=o.getUniformLocationNoThrow(s,"params")),o.gl.uniform4f(this.paramsLoc,t,e,r,i)}}};var AL={kernelName:Xg,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{image:r}=n,{radians:i,fillValue:o,center:s}=t,a=e,l=new nx(r.shape,o),[c,u]=F.getImageCenter(s,r.shape[1],r.shape[2]),h=l.getCustomSetupFunc(c,u,Math.sin(i),Math.cos(i));return a.runWebGLProgram(l,[r],r.dtype,h)}};var gQ=` + // OpenGL ES does not support round function. + // The algorithm is based on banker's rounding. + float base = floor(x); + if ((x - base) < 0.5) { + return floor(x); + } else if ((x - base) > 0.5) { + return ceil(x); + } else { + if (mod(base, 2.0) == 0.0) { + return base; + } else { + return base + 1.0; + } + } +`,xQ=Ot({opSnippet:gQ}),IL={kernelName:$h,backendName:"webgl",kernelFunc:xQ};var vQ="return inversesqrt(x);",yQ=Ot({opSnippet:vQ,cpuKernelImpl:y6}),kL={kernelName:Uh,backendName:"webgl",kernelFunc:yQ};var cc=class{constructor(t,e,r,i,o,s,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let l=ne(o.length),c=ne(s.length),u="";r===1?u="i":r===2&&(u="i, j");let h=`getIndices(${u})`,p="";i===1?p="i":i===2&&(p="i, coords[1]");let d=`getUpdates(${p})`,f=e>1?"strides[j]":"strides";this.userCode=` + ${l} strides = ${l}(${o}); + + void main() { + ${c} coords = getOutputCoords(); + float sum = 0.0; + bool found = false; + for (int i = 0; i < ${t}; i++) { + int flattenedIndex = 0; + for (int j = 0; j < ${e}; j++) { + int index = round(${h}); + flattenedIndex += index * ${f}; + } + if (flattenedIndex == coords[0]) { + sum += ${d}; + found = true; + } + } + setOutput(mix(getDefaultValue(), sum, float(found))); + } + `}};function bQ(n){let{inputs:t,backend:e,attrs:r}=n,{indices:i,updates:o}=t,{shape:s}=r,{sliceRank:a,numUpdates:l,sliceSize:c,strides:u,outputSize:h}=F.calculateShapes(o,i,s),p=[h/c,c];if(h===0)return e.makeTensorInfo(s,i.dtype);let d=Tt({inputs:{x:i},backend:e,attrs:{shape:[l,a]}}),f=Tt({inputs:{x:o},backend:e,attrs:{shape:[l,c]}}),m=e.makeTensorInfo([],"float32",new Float32Array([0])),x=new cc(l,a,d.shape.length,f.shape.length,u,p),g=e.runWebGLProgram(x,[f,d,m],f.dtype),v=Tt({inputs:{x:g},backend:e,attrs:{shape:s}});return e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(m),v}var RL={kernelName:Ng,backendName:"webgl",kernelFunc:bQ};var rx=class{constructor(t,e,r){this.variableNames=["c","a","b"],this.outputShape=e;let i,o;if(r>4)throw Error(`Where for rank ${r} is not yet supported`);if(r===1)o="resRC",i="resRC";else{let a=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],c=[];for(let u=0;u= 1.0) { + setOutput(getA(${o})); + } else { + setOutput(getB(${o})); + } + } + `}};function _Q(n){let{inputs:t,backend:e}=n,{condition:r,t:i,e:o}=t,s=new rx(r.shape.length,i.shape,i.shape.length);return e.runWebGLProgram(s,[r,i,o],on(i.dtype,o.dtype))}var PL={kernelName:Lg,backendName:"webgl",kernelFunc:_Q};var wQ=` + // Stable and Attracting Fixed Point (0, 1) for Normalized Weights. + // see: https://arxiv.org/abs/1706.02515 + float scaleAlpha = ${F.SELU_SCALEALPHA}; + float scale = ${F.SELU_SCALE}; + return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); +`,SQ=Ot({opSnippet:wQ}),NL={kernelName:Wh,backendName:"webgl",kernelFunc:SQ};var CQ="return 1.0 / (1.0 + exp(-1.0 * x));",MQ=Ot({opSnippet:CQ}),LL={kernelName:Xh,backendName:"webgl",kernelFunc:MQ};var EQ=` + if (isnan(x)) { return 0.0; } + return sign(x); +`,TQ=Ot({opSnippet:EQ}),DL={kernelName:qh,backendName:"webgl",kernelFunc:TQ};var AQ=X1+` + return sin(x); +`,IQ=Ot({opSnippet:AQ}),zL={kernelName:Gh,backendName:"webgl",kernelFunc:IQ};var kQ=` + float e2x = exp(x); + return (e2x - 1.0 / e2x) / 2.0; +`,RQ=Ot({opSnippet:kQ}),FL={kernelName:jh,backendName:"webgl",kernelFunc:RQ};var PQ=` + float epsilon = 1.1920928955078125e-7; + float threshold = log(epsilon) + 2.0; + + bool too_large = x > -threshold; + bool too_small = x < threshold; + + float result; + float exp_x = exp(x); + + if (too_large){ + result = x; + } + else if (too_small){ + result = exp_x; + } + else{ + result = log(exp_x + 1.0); + } + return result; +`,NQ=Ot({opSnippet:PQ}),OL={kernelName:Kh,backendName:"webgl",kernelFunc:NQ};var LQ=n=>{let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{blockShape:o,paddings:s}=r;R.assert(i.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let a=o.reduce((g,v)=>g*v),l=[[0,0]];l.push(...s);for(let g=1+o.length;ge.disposeIntermediateTensorInfo(g)),x},BL={kernelName:zg,backendName:"webgl",kernelFunc:LQ};function DQ(n){let{inputs:t,backend:e,attrs:r}=n,{sparseIndices:i,sparseValues:o,defaultValue:s}=t,{outputShape:a}=r,{sliceRank:l,numUpdates:c,strides:u,outputSize:h}=F.calculateShapes(o,i,a),p=!1,d=new cc(c,l,i.shape.length,o.shape.length,u,[h,1],p),f=e.runWebGLProgram(d,[o,i,s],o.dtype),m=Tt({inputs:{x:f},backend:e,attrs:{shape:a}});return e.disposeIntermediateTensorInfo(f),m}var VL={kernelName:Bg,backendName:"webgl",kernelFunc:DQ};function zQ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{numOrSizeSplits:o,axis:s}=r,a=R.parseAxisParam(s,i.shape)[0],l=F.prepareSplitSize(i,o,a),c=i.shape.length,u=new Array(c).fill(0),h=i.shape.slice();return l.map(p=>{let d=[...h];d[a]=p;let f=ao({inputs:{x:i},backend:e,attrs:{begin:u,size:d}});return u[a]+=p,f})}var HL={kernelName:Dl,backendName:"webgl",kernelFunc:zQ};var FQ="return sqrt(x);",OQ=Ot({opSnippet:FQ}),$L={kernelName:Yh,backendName:"webgl",kernelFunc:OQ};var BQ="return x * x;",VQ=Ot({opSnippet:BQ}),UL={kernelName:Og,backendName:"webgl",kernelFunc:VQ};var WL="return (a - b) * (a - b);",HQ=me({opSnippet:WL,packedOpSnippet:WL}),GL={kernelName:Zh,backendName:"webgl",kernelFunc:HQ};function $Q({inputs:n,attrs:t,backend:e}){let{x:r}=n,i=pn+` + return x > 0.0 ? 1.0 : float(${t.alpha}); + `,o=new jn(r.shape,i);return e.runWebGLProgram(o,[r],r.dtype)}var jL={kernelName:Ks,backendName:"webgl",kernelFunc:$Q};var ix=class{constructor(t,e,r){this.variableNames=["x"],this.outputShape=r;let i=r.length,o=ne(r.length),s=ne(r.length),a="";if(i===1)a="coords * strides + begin";else{let l=0;a=r.map((c,u)=>(l++,r.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${l-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=` + ${o} begin = ${o}(${t}); + ${o} strides = ${o}(${e}); + + void main() { + ${s} coords = getOutputCoords(); + setOutput(getX(${a})); + } + `}};function UQ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{begin:o,end:s,strides:a,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:h,shrinkAxisMask:p}=r,{nonStrided:d,$begin:f,$strides:m,size:x,newShape:g,outShape:v}=In.sliceInfo(i.shape,o,s,a,l,c,u,h,p),b=Tt({inputs:{x:i},backend:e,attrs:{shape:g}}),y;if(d){let S=ao({inputs:{x:b},backend:e,attrs:{begin:f,size:x}});y=Tt({inputs:{x:S},backend:e,attrs:{shape:v}}),e.disposeIntermediateTensorInfo(S)}else if(v.some(S=>S===0))y=e.makeTensorInfo(v,i.dtype,[]);else if(e.shouldExecuteOnCPU([b])){let M=e.texData.get(b.dataId).values,P=Xt(b.shape,b.dtype,M),D=_6(v,P,m,f);y=e.makeTensorInfo(v,b.dtype,D.values)}else{let E=new ix(f,m,v);y=e.runWebGLProgram(E,[b],b.dtype)}let _=Tt({inputs:{x:y},backend:e,attrs:{shape:v}});return e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(y),_}var qL={kernelName:Vg,backendName:"webgl",kernelFunc:UQ};var WQ="return tan(x);",GQ=Ot({opSnippet:WQ}),XL={kernelName:Jh,backendName:"webgl",kernelFunc:GQ};var jQ=` + float e2x = exp(-2.0 * abs(x)); + return sign(x) * (1.0 - e2x) / (1.0 + e2x); +`,qQ=Ot({opSnippet:jQ}),KL={kernelName:Qh,backendName:"webgl",kernelFunc:qQ};var ox=class{constructor(t,e){this.variableNames=["A"];let r=new Array(t.length);for(let s=0;s5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${n[0]})`;let e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let i=0;iR.decodeString(p)),u=Xt(i.shape,i.dtype,c),h=S6(u,o);return e.makeTensorInfo(h.shape,h.dtype,h.values)}let s=new ox(i.shape,o);return e.runWebGLProgram(s,[i],i.dtype)}var YL={kernelName:Hg,backendName:"webgl",kernelFunc:Tw};function KQ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i}=t,{k:o,sorted:s}=r,a=e.readSync(i.dataId),[l,c]=C6(a,i.shape,i.dtype,o,s);return[e.makeTensorInfo(l.shape,l.dtype,l.values),e.makeTensorInfo(c.shape,c.dtype,c.values)]}var ZL={kernelName:$g,backendName:"webgl",kernelFunc:KQ};var sx=class{constructor(t,e,r,i,o,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let a=r==="nearest"?1:2,l;switch(i){case"constant":l=1;break;case"reflect":l=2;break;case"wrap":l=3;break;case"nearest":l=4;break;default:l=1;break}this.userCode=` + float mapCoord(float outCoord, float len) { + float inCoord = outCoord; + if(${l} == 2) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz2 = 2.0 * len; + if (inCoord < sz2) { + inCoord = sz2 * float(int(float(-inCoord / sz2))) + + inCoord; + } + inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0; + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz2 = 2.0 * len; + inCoord -= sz2 * float(int(float(inCoord / sz2))); + if (inCoord >= len) { + inCoord = sz2 - inCoord - 1.0; + } + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (${l} == 3) { + if (inCoord < 0.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz = len - 1.0; + inCoord += len * (float(int(float(-inCoord / sz))) + 1.0); + } + } else if (inCoord > len - 1.0) { + if (len <= 1.0) { + inCoord = 0.0; + } else { + float sz = len - 1.0; + inCoord -= len * float(int(float(inCoord / sz))); + } + } + return clamp(inCoord, 0.0, len - 1.0); + } else if (${l} == 4) { + return clamp(outCoord, 0.0, len - 1.0); + } else { + return outCoord; + } + } + + float readWithFillValue(int batch, int coordY, int coordX, + int channel) { + float outputValue; + if (0 <= coordY && coordY < ${t} && 0 <= coordX && coordX < ${e}) { + outputValue = getImage(batch, coordY, coordX, channel); + } else { + outputValue = float(${o}); + } + return outputValue; + } + + void main() { + ivec4 coords = getOutputCoords(); + float outputValue; + int batch = coords[0]; + int x = coords[2]; + int y = coords[1]; + int channel = coords[3]; + float xf = float(x); + float yf = float(y); + float a1 = getTransforms(batch, 0); + float a2 = getTransforms(batch, 1); + float a3 = getTransforms(batch, 2); + float b1 = getTransforms(batch, 3); + float b2 = getTransforms(batch, 4); + float b3 = getTransforms(batch, 5); + float c1 = getTransforms(batch, 6); + float c2 = getTransforms(batch, 7); + float projection = c1 * xf + c2 * yf + 1.0; + if (projection == 0.0) { + outputValue = float(${o}); + } else { + float inX = (a1 * xf + a2 * yf + a3) / projection; + float inY = (b1 * xf + b2 * yf + b3) / projection; + float mapX = mapCoord(inX, float(${e})); + float mapY = mapCoord(inY, float(${t})); + + if (${a} == 1) { + int coordY = int(round(mapY)); + int coordX = int(round(mapX)); + outputValue = readWithFillValue(batch, coordY, coordX, + channel); + } else { + float yFloor = floor(mapY); + float xFloor = floor(mapX); + float yCeil = yFloor + 1.0; + float xCeil = xFloor + 1.0; + float valueYFloor = (xCeil - mapX) * + readWithFillValue(batch, int(yFloor), int(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, int(yFloor), int(xCeil), channel); + float valueYCeil = (xCeil - mapX) * + readWithFillValue(batch, int(yCeil), int(xFloor), channel) + + (mapX - xFloor) * + readWithFillValue(batch, int(yCeil), int(xCeil), channel); + outputValue = (yCeil - mapY) * valueYFloor + + (mapY - yFloor) * valueYCeil; + } + } + setOutput(outputValue); + } + `}};function YQ(n){let{inputs:t,backend:e,attrs:r}=n,{image:i,transforms:o}=t,{interpolation:s,fillMode:a,fillValue:l,outputShape:c}=r,[u,h,p,d]=i.shape,[f,m]=c!=null?c:[h,p],x=[u,f,m,d],g=new sx(h,p,s,a,l,x);return e.runWebGLProgram(g,[i,o],"float32")}var JL={kernelName:Ug,backendName:"webgl",kernelFunc:YQ};function ZQ(n){let{inputs:t,attrs:e,backend:r}=n,{axis:i}=e,{x:o}=t;Ti(o,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let s=r.readSync(o.dataId),{outputValues:a,outputShape:l,indices:c}=M6(s,i,o.shape,o.dtype);return[r.makeTensorInfo(l,o.dtype,a),r.makeTensorInfo([c.length],"int32",c)]}var QL={kernelName:Wg,backendName:"webgl",kernelFunc:ZQ};function JQ(n){let{inputs:t,backend:e,attrs:r}=n,{value:i}=t,{axis:o}=r;o<0&&(o+=i.shape.length);let s=i,a=s.shape.length,l=i.shape[o],c=new Array(a-1),u=0;for(let m=0;me.disposeIntermediateTensorInfo(m)),f}var tD={kernelName:Gg,backendName:"webgl",kernelFunc:JQ};var ax=class{constructor(t,e){this.variableNames=["x","segmentIds"];let r=t.windowSize,i=t.batchSize,o=t.inSize,s=t.numSegments,a=s*Math.ceil(o/r);this.outputShape=[i,a];let l="0.0",c="sumValue",u=Math.floor(r/4)*4,h=r%4,p=` + sumValue += dot(values, segFilter); + `,d="";o%r>0&&(d=` + if (inIdx < 0 || inIdx >= ${o}) { + return initializationValue; + } + `);let f="";o%r>0&&(f=` + if (inIdx < 0 || inIdx >= ${o}) { + return -1.0; + } + `),this.userCode=` + const float initializationValue = ${l}; + + float getValue(int batch, int inIdx) { + ${d} + return getX(batch, inIdx); + } + + float getSegmentIdAtIndex(int inIdx) { + ${f} + return getSegmentIds(inIdx); + } + + void main() { + ivec2 coords = getOutputCoords(); + int batch = coords[0]; + int outIdx = coords[1]; + int inOffset = int(floor(float(outIdx) / float( + ${s})) * float(${r})); + int currentSeg = int(mod(float(outIdx), float(${s}))); + + float sumValue = 0.0; + + for (int i = 0; i < ${u}; i += 4) { + int inIdx = inOffset + i; + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + getValue(batch, inIdx + 3) + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0 + ); + + ${p} + } + + int inIdx = inOffset + ${u}; + if (${h===1}) { + vec4 values = vec4( + getValue(batch, inIdx), + initializationValue, + initializationValue, + initializationValue + ); + + int inIdxSeg = int(getSegmentIdAtIndex(inIdx)); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + 0, + 0, + 0 + ); + + ${p} + } else if (${h===2}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + initializationValue, + initializationValue + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + 0, + 0 + ); + + ${p} + } else if (${h===3}) { + vec4 values = vec4( + getValue(batch, inIdx), + getValue(batch, inIdx + 1), + getValue(batch, inIdx + 2), + initializationValue + ); + + vec4 segFilter = vec4( + int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, + int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, + 0 + ); + + ${p} + } + setOutput(${c}); + } + `}};function QQ(n){let{inputs:t,backend:e,attrs:r}=n,{x:i,segmentIds:o}=t,{numSegments:s}=r,a=i.shape.length,l=[],c=0,u=F.getAxesPermutation([c],a),h=i;u!=null&&(h=Pe({inputs:{x:i},backend:e,attrs:{perm:u}}),l.push(h),c=F.getInnerMostAxes(1,a)[0]);let p=F.segment_util.computeOutShape(h.shape,c,s),d=R.sizeFromShape([h.shape[c]]),f=Tt({inputs:{x:h},backend:e,attrs:{shape:[-1,d]}});l.push(f);let m=Js(i.dtype),x=(y,_,S,E,M)=>{let P=y.shape[0],D=y.shape[1],w=F.segment_util.segOpComputeOptimalWindowSize(D,M),I={windowSize:w,inSize:D,batchSize:P,numSegments:M},N=new ax(I,_),L=e.compileAndRun(N,[y,S],E);if(l.push(L),L.shape[1]===M)return L;let O=Ew({backend:e,attrs:{start:0,stop:M,step:1,dtype:"float32"}}),z=Tw({inputs:{x:O},backend:e,attrs:{reps:[D/w]}});return l.push(O),l.push(z),x(L,_,z,E,M)},g=x(f,"unsortedSegmentSum",o,m,s),v=Tt({inputs:{x:g},backend:e,attrs:{shape:p}}),b=v;if(u!=null){l.push(v);let y=F.getUndoAxesPermutation(u);b=Pe({inputs:{x:b},backend:e,attrs:{perm:y}})}return l.forEach(y=>e.disposeIntermediateTensorInfo(y)),b}var eD={kernelName:jg,backendName:"webgl",kernelFunc:QQ};var ttt=[O9,B9,J6,tN,eN,nN,iN,oN,sN,aN,uN,hN,pN,dN,mN,fN,gN,vN,xN,yN,bN,_N,wN,CN,MN,IN,RN,PN,LN,V6,FN,BN,VN,ON,$N,UN,HN,WN,GN,jN,KN,YN,ZN,QN,t9,JN,e9,n9,r9,i9,o9,s9,a9,c9,u9,p9,d9,f9,m9,x9,v9,y9,b9,_9,w9,S9,C9,M9,B6,E9,DN,T9,A9,I9,H6,k9,R9,P9,L9,N9,D9,z9,F9,H9,W9,U9,G9,j9,X9,$9,Y9,Z9,J9,Q9,tL,oL,j6,aL,lL,cL,uL,EN,hL,fL,mL,gL,xL,$6,vL,yL,TN,eL,bL,wL,_L,X6,SL,CL,ML,EL,TL,AL,IL,kL,RL,PL,NL,LL,DL,zL,FL,SN,iL,OL,BL,VL,HL,$L,UL,GL,jL,qL,rL,Y6,XL,KL,YL,ZL,JL,Z6,QL,tD,eD,pL];for(let n of ttt)Qg(n);var Aw=class{constructor(){this.arr=[]}push(t,e){this.arr.push({key:t,value:e}),this.bubbleUp(this.arr.length-1)}pop(){if(this.arr.length===0)throw new Error("pop() called on empty binary heap");let t=this.arr[0],e=this.arr.length-1;return this.arr[0]=this.arr[e],this.arr.pop(),e>0&&this.bubbleDown(0),t}peek(){return this.arr[0]}popPush(t,e){if(this.arr.length===0)throw new Error("pop() called on empty binary heap");let r=this.arr[0];return this.arr[0]={key:t,value:e},this.arr.length>0&&this.bubbleDown(0),r}size(){return this.arr.length}items(){return this.arr}swap(t,e){let r=this.arr[t];this.arr[t]=this.arr[e],this.arr[e]=r}bubbleDown(t){let e=(t<<1)+1,r=e+1,i=t;e>1;this.arr[t].keyr.key-e.key),t.map(e=>e.value)}getSize(){return this.maxHeap.size()}getLargestKey(){return this.maxHeap.size()===0?null:-this.maxHeap.peek().key}};var hc=null,ett=0,lx=0;function rD(n){hc=n}function ve(n,t=null,e=null,r=!1){var c;if(hc==null)return console.warn("Can't show modal message before the dom is initialized"),"";t==null&&(t=(ett++).toString());let i=(c=hc.shadowRoot)==null?void 0:c.querySelector("#notification-dialog");i.querySelector(".close-button").style.display=r?null:"none";let o=i.querySelector(".progress");o.style.display=r?"none":null,o.active=r?null:!0,i.querySelector("#notification-title").textContent=e;let s=i.querySelector("#notify-msgs");if(r)s.textContent="";else{let u=s.querySelectorAll(".error");for(let h=0;h>8&255]+Hn[n>>16&255]+Hn[n>>24&255]+"-"+Hn[t&255]+Hn[t>>8&255]+"-"+Hn[t>>16&15|64]+Hn[t>>24&255]+"-"+Hn[e&63|128]+Hn[e>>8&255]+"-"+Hn[e>>16&255]+Hn[e>>24&255]+Hn[r&255]+Hn[r>>8&255]+Hn[r>>16&255]+Hn[r>>24&255]).toUpperCase()}function er(n,t,e){return Math.max(t,Math.min(e,n))}function tet(n,t){return(n%t+t)%t}function zw(n,t,e){return(1-e)*n+e*t}function LD(n){return(n&n-1)===0&&n!==0}function eet(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}var Mt=class{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t,e){return e!==void 0?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t,e){return e!==void 0?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){let e=this.x,r=this.y,i=t.elements;return this.x=i[0]*e+i[3]*r+i[6],this.y=i[1]*e+i[4]*r+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){let r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(t,Math.min(e,r)))}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=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,r=this.y-t.y;return e*e+r*r}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,r){return this.x=t.x+(e.x-t.x)*r,this.y=t.y+(e.y-t.y)*r,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e,r){return r!==void 0&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){let r=Math.cos(e),i=Math.sin(e),o=this.x-t.x,s=this.y-t.y;return this.x=o*r-s*i+t.x,this.y=o*i+s*r+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};Mt.prototype.isVector2=!0;var _n=class{constructor(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}set(t,e,r,i,o,s,a,l,c){let u=this.elements;return u[0]=t,u[1]=i,u[2]=a,u[3]=e,u[4]=o,u[5]=l,u[6]=r,u[7]=s,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){let e=this.elements,r=t.elements;return e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=r[3],e[4]=r[4],e[5]=r[5],e[6]=r[6],e[7]=r[7],e[8]=r[8],this}extractBasis(t,e,r){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(t){let e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){let r=t.elements,i=e.elements,o=this.elements,s=r[0],a=r[3],l=r[6],c=r[1],u=r[4],h=r[7],p=r[2],d=r[5],f=r[8],m=i[0],x=i[3],g=i[6],v=i[1],b=i[4],y=i[7],_=i[2],S=i[5],E=i[8];return o[0]=s*m+a*v+l*_,o[3]=s*x+a*b+l*S,o[6]=s*g+a*y+l*E,o[1]=c*m+u*v+h*_,o[4]=c*x+u*b+h*S,o[7]=c*g+u*y+h*E,o[2]=p*m+d*v+f*_,o[5]=p*x+d*b+f*S,o[8]=p*g+d*y+f*E,this}multiplyScalar(t){let e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){let t=this.elements,e=t[0],r=t[1],i=t[2],o=t[3],s=t[4],a=t[5],l=t[6],c=t[7],u=t[8];return e*s*u-e*a*c-r*o*u+r*a*l+i*o*c-i*s*l}invert(){let t=this.elements,e=t[0],r=t[1],i=t[2],o=t[3],s=t[4],a=t[5],l=t[6],c=t[7],u=t[8],h=u*s-a*c,p=a*l-u*o,d=c*o-s*l,f=e*h+r*p+i*d;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/f;return t[0]=h*m,t[1]=(i*c-u*r)*m,t[2]=(a*r-i*s)*m,t[3]=p*m,t[4]=(u*e-i*l)*m,t[5]=(i*o-a*e)*m,t[6]=d*m,t[7]=(r*l-c*e)*m,t[8]=(s*e-r*o)*m,this}transpose(){let t,e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){let e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,r,i,o,s,a){let l=Math.cos(o),c=Math.sin(o);return this.set(r*l,r*c,-r*(l*s+c*a)+s+t,-i*c,i*l,-i*(-c*s+l*a)+a+e,0,0,1),this}scale(t,e){let r=this.elements;return r[0]*=t,r[3]*=t,r[6]*=t,r[1]*=e,r[4]*=e,r[7]*=e,this}rotate(t){let e=Math.cos(t),r=Math.sin(t),i=this.elements,o=i[0],s=i[3],a=i[6],l=i[1],c=i[4],u=i[7];return i[0]=e*o+r*l,i[3]=e*s+r*c,i[6]=e*a+r*u,i[1]=-r*o+e*l,i[4]=-r*s+e*c,i[7]=-r*a+e*u,this}translate(t,e){let r=this.elements;return r[0]+=t*r[2],r[3]+=t*r[5],r[6]+=t*r[8],r[1]+=e*r[2],r[4]+=e*r[5],r[7]+=e*r[8],this}equals(t){let e=this.elements,r=t.elements;for(let i=0;i<9;i++)if(e[i]!==r[i])return!1;return!0}fromArray(t,e=0){for(let r=0;r<9;r++)this.elements[r]=t[r+e];return this}toArray(t=[],e=0){let r=this.elements;return t[e]=r[0],t[e+1]=r[1],t[e+2]=r[2],t[e+3]=r[3],t[e+4]=r[4],t[e+5]=r[5],t[e+6]=r[6],t[e+7]=r[7],t[e+8]=r[8],t}clone(){return new this.constructor().fromArray(this.elements)}};_n.prototype.isMatrix3=!0;function Gz(n){for(let t=n.length-1;t>=0;--t)if(n[t]>65535)return!0;return!1}function Hp(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}var jz={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},Qr={h:0,s:0,l:0},cx={h:0,s:0,l:0};function Fw(n,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?n+(t-n)*6*e:e<1/2?t:e<2/3?n+(t-n)*6*(2/3-e):n}function Oc(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function Ow(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}var Pt=class{constructor(t,e,r){return e===void 0&&r===void 0?this.set(t):this.setRGB(t,e,r)}set(t){return t&&t.isColor?this.copy(t):typeof t=="number"?this.setHex(t):typeof t=="string"&&this.setStyle(t),this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,this}setRGB(t,e,r){return this.r=t,this.g=e,this.b=r,this}setHSL(t,e,r){if(t=tet(t,1),e=er(e,0,1),r=er(r,0,1),e===0)this.r=this.g=this.b=r;else{let i=r<=.5?r*(1+e):r+e-r*e,o=2*r-i;this.r=Fw(o,i,t+1/3),this.g=Fw(o,i,t),this.b=Fw(o,i,t-1/3)}return this}setStyle(t){function e(i){i!==void 0&&parseFloat(i)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let r;if(r=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(t)){let i,o=r[1],s=r[2];switch(o){case"rgb":case"rgba":if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s))return this.r=Math.min(255,parseInt(i[1],10))/255,this.g=Math.min(255,parseInt(i[2],10))/255,this.b=Math.min(255,parseInt(i[3],10))/255,e(i[4]),this;if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s))return this.r=Math.min(100,parseInt(i[1],10))/100,this.g=Math.min(100,parseInt(i[2],10))/100,this.b=Math.min(100,parseInt(i[3],10))/100,e(i[4]),this;break;case"hsl":case"hsla":if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s)){let a=parseFloat(i[1])/360,l=parseInt(i[2],10)/100,c=parseInt(i[3],10)/100;return e(i[4]),this.setHSL(a,l,c)}break}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(t)){let i=r[1],o=i.length;if(o===3)return this.r=parseInt(i.charAt(0)+i.charAt(0),16)/255,this.g=parseInt(i.charAt(1)+i.charAt(1),16)/255,this.b=parseInt(i.charAt(2)+i.charAt(2),16)/255,this;if(o===6)return this.r=parseInt(i.charAt(0)+i.charAt(1),16)/255,this.g=parseInt(i.charAt(2)+i.charAt(3),16)/255,this.b=parseInt(i.charAt(4)+i.charAt(5),16)/255,this}return t&&t.length>0?this.setColorName(t):this}setColorName(t){let e=jz[t.toLowerCase()];return e!==void 0?this.setHex(e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Oc(t.r),this.g=Oc(t.g),this.b=Oc(t.b),this}copyLinearToSRGB(t){return this.r=Ow(t.r),this.g=Ow(t.g),this.b=Ow(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(){return this.r*255<<16^this.g*255<<8^this.b*255<<0}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}getHSL(t){let e=this.r,r=this.g,i=this.b,o=Math.max(e,r,i),s=Math.min(e,r,i),a,l,c=(s+o)/2;if(s===o)a=0,l=0;else{let u=o-s;switch(l=c<=.5?u/(o+s):u/(2-o-s),o){case e:a=(r-i)/u+(r2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if(typeof HTMLImageElement!="undefined"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&t instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&t instanceof ImageBitmap){let e=Hp("canvas");e.width=t.width,e.height=t.height;let r=e.getContext("2d");r.drawImage(t,0,0,t.width,t.height);let i=r.getImageData(0,0,t.width,t.height),o=i.data;for(let s=0;s1)switch(this.wrapS){case xS:t.x=t.x-Math.floor(t.x);break;case _r:t.x=t.x<0?0:1;break;case vS:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case xS:t.y=t.y-Math.floor(t.y);break;case _r:t.y=t.y<0?0:1;break;case vS:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&this.version++}};Qe.DEFAULT_IMAGE=void 0;Qe.DEFAULT_MAPPING=Uz;Qe.prototype.isTexture=!0;function Bw(n){return typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&n instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&n instanceof ImageBitmap?go.getDataURL(n):n.data?{data:Array.prototype.slice.call(n.data),width:n.width,height:n.height,type:n.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}var Re=class{constructor(t=0,e=0,r=0,i=1){this.x=t,this.y=e,this.z=r,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,r,i){return this.x=t,this.y=e,this.z=r,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t,e){return e!==void 0?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this)}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t,e){return e!==void 0?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this)}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){let e=this.x,r=this.y,i=this.z,o=this.w,s=t.elements;return this.x=s[0]*e+s[4]*r+s[8]*i+s[12]*o,this.y=s[1]*e+s[5]*r+s[9]*i+s[13]*o,this.z=s[2]*e+s[6]*r+s[10]*i+s[14]*o,this.w=s[3]*e+s[7]*r+s[11]*i+s[15]*o,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);let e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,r,i,o,l=t.elements,c=l[0],u=l[4],h=l[8],p=l[1],d=l[5],f=l[9],m=l[2],x=l[6],g=l[10];if(Math.abs(u-p)<.01&&Math.abs(h-m)<.01&&Math.abs(f-x)<.01){if(Math.abs(u+p)<.1&&Math.abs(h+m)<.1&&Math.abs(f+x)<.1&&Math.abs(c+d+g-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;let b=(c+1)/2,y=(d+1)/2,_=(g+1)/2,S=(u+p)/4,E=(h+m)/4,M=(f+x)/4;return b>y&&b>_?b<.01?(r=0,i=.707106781,o=.707106781):(r=Math.sqrt(b),i=S/r,o=E/r):y>_?y<.01?(r=.707106781,i=0,o=.707106781):(i=Math.sqrt(y),r=S/i,o=M/i):_<.01?(r=.707106781,i=.707106781,o=0):(o=Math.sqrt(_),r=E/o,i=M/o),this.set(r,i,o,e),this}let v=Math.sqrt((x-f)*(x-f)+(h-m)*(h-m)+(p-u)*(p-u));return Math.abs(v)<.001&&(v=1),this.x=(x-f)/v,this.y=(h-m)/v,this.z=(p-u)/v,this.w=Math.acos((c+d+g-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){let r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(t,Math.min(e,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this.w=this.w<0?Math.ceil(this.w):Math.floor(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,r){return this.x=t.x+(e.x-t.x)*r,this.y=t.y+(e.y-t.y)*r,this.z=t.z+(e.z-t.z)*r,this.w=t.w+(e.w-t.w)*r,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e,r){return r!==void 0&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};Re.prototype.isVector4=!0;var Xn=class extends ii{constructor(t,e,r={}){super(),this.width=t,this.height=e,this.depth=1,this.scissor=new Re(0,0,t,e),this.scissorTest=!1,this.viewport=new Re(0,0,t,e),this.texture=new Qe(void 0,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.encoding),this.texture.isRenderTargetTexture=!0,this.texture.image={width:t,height:e,depth:1},this.texture.generateMipmaps=r.generateMipmaps!==void 0?r.generateMipmaps:!1,this.texture.internalFormat=r.internalFormat!==void 0?r.internalFormat:null,this.texture.minFilter=r.minFilter!==void 0?r.minFilter:dn,this.depthBuffer=r.depthBuffer!==void 0?r.depthBuffer:!0,this.stencilBuffer=r.stencilBuffer!==void 0?r.stencilBuffer:!1,this.depthTexture=r.depthTexture!==void 0?r.depthTexture:null}setTexture(t){t.image={width:this.width,height:this.height,depth:this.depth},this.texture=t}setSize(t,e,r=1){(this.width!==t||this.height!==e||this.depth!==r)&&(this.width=t,this.height=e,this.depth=r,this.texture.image.width=t,this.texture.image.height=e,this.texture.image.depth=r,this.dispose()),this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){return this.width=t.width,this.height=t.height,this.depth=t.depth,this.viewport.copy(t.viewport),this.texture=t.texture.clone(),this.texture.image=Object.assign({},t.texture.image),this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.depthTexture=t.depthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}};Xn.prototype.isWebGLRenderTarget=!0;var _S=class extends Xn{constructor(t,e,r){super(t,e);let i=this.texture;this.texture=[];for(let o=0;o=0?1:-1,b=1-g*g;if(b>Number.EPSILON){let _=Math.sqrt(b),S=Math.atan2(_,g*v);x=Math.sin(x*S)/_,a=Math.sin(a*S)/_}let y=a*v;if(l=l*x+p*y,c=c*x+d*y,u=u*x+f*y,h=h*x+m*y,x===1-a){let _=1/Math.sqrt(l*l+c*c+u*u+h*h);l*=_,c*=_,u*=_,h*=_}}t[e]=l,t[e+1]=c,t[e+2]=u,t[e+3]=h}static multiplyQuaternionsFlat(t,e,r,i,o,s){let a=r[i],l=r[i+1],c=r[i+2],u=r[i+3],h=o[s],p=o[s+1],d=o[s+2],f=o[s+3];return t[e]=a*f+u*h+l*d-c*p,t[e+1]=l*f+u*p+c*h-a*d,t[e+2]=c*f+u*d+a*p-l*h,t[e+3]=u*f-a*h-l*p-c*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,r,i){return this._x=t,this._y=e,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e){if(!(t&&t.isEuler))throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");let r=t._x,i=t._y,o=t._z,s=t._order,a=Math.cos,l=Math.sin,c=a(r/2),u=a(i/2),h=a(o/2),p=l(r/2),d=l(i/2),f=l(o/2);switch(s){case"XYZ":this._x=p*u*h+c*d*f,this._y=c*d*h-p*u*f,this._z=c*u*f+p*d*h,this._w=c*u*h-p*d*f;break;case"YXZ":this._x=p*u*h+c*d*f,this._y=c*d*h-p*u*f,this._z=c*u*f-p*d*h,this._w=c*u*h+p*d*f;break;case"ZXY":this._x=p*u*h-c*d*f,this._y=c*d*h+p*u*f,this._z=c*u*f+p*d*h,this._w=c*u*h-p*d*f;break;case"ZYX":this._x=p*u*h-c*d*f,this._y=c*d*h+p*u*f,this._z=c*u*f-p*d*h,this._w=c*u*h+p*d*f;break;case"YZX":this._x=p*u*h+c*d*f,this._y=c*d*h+p*u*f,this._z=c*u*f-p*d*h,this._w=c*u*h-p*d*f;break;case"XZY":this._x=p*u*h-c*d*f,this._y=c*d*h-p*u*f,this._z=c*u*f+p*d*h,this._w=c*u*h+p*d*f;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return e!==!1&&this._onChangeCallback(),this}setFromAxisAngle(t,e){let r=e/2,i=Math.sin(r);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(t){let e=t.elements,r=e[0],i=e[4],o=e[8],s=e[1],a=e[5],l=e[9],c=e[2],u=e[6],h=e[10],p=r+a+h;if(p>0){let d=.5/Math.sqrt(p+1);this._w=.25/d,this._x=(u-l)*d,this._y=(o-c)*d,this._z=(s-i)*d}else if(r>a&&r>h){let d=2*Math.sqrt(1+r-a-h);this._w=(u-l)/d,this._x=.25*d,this._y=(i+s)/d,this._z=(o+c)/d}else if(a>h){let d=2*Math.sqrt(1+a-r-h);this._w=(o-c)/d,this._x=(i+s)/d,this._y=.25*d,this._z=(l+u)/d}else{let d=2*Math.sqrt(1+h-r-a);this._w=(s-i)/d,this._x=(o+c)/d,this._y=(l+u)/d,this._z=.25*d}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let r=t.dot(e)+1;return rMath.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=r):(this._x=0,this._y=-t.z,this._z=t.y,this._w=r)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=r),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(er(this.dot(t),-1,1)))}rotateTowards(t,e){let r=this.angleTo(t);if(r===0)return this;let i=Math.min(1,e/r);return this.slerp(t,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(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t,e){return e!==void 0?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){let r=t._x,i=t._y,o=t._z,s=t._w,a=e._x,l=e._y,c=e._z,u=e._w;return this._x=r*u+s*a+i*c-o*l,this._y=i*u+s*l+o*a-r*c,this._z=o*u+s*c+r*l-i*a,this._w=s*u-r*a-i*l-o*c,this._onChangeCallback(),this}slerp(t,e){if(e===0)return this;if(e===1)return this.copy(t);let r=this._x,i=this._y,o=this._z,s=this._w,a=s*t._w+r*t._x+i*t._y+o*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=r,this._y=i,this._z=o,this;let l=1-a*a;if(l<=Number.EPSILON){let d=1-e;return this._w=d*s+e*this._w,this._x=d*r+e*this._x,this._y=d*i+e*this._y,this._z=d*o+e*this._z,this.normalize(),this._onChangeCallback(),this}let c=Math.sqrt(l),u=Math.atan2(c,a),h=Math.sin((1-e)*u)/c,p=Math.sin(e*u)/c;return this._w=s*h+this._w*p,this._x=r*h+this._x*p,this._y=i*h+this._y*p,this._z=o*h+this._z*p,this._onChangeCallback(),this}slerpQuaternions(t,e,r){return this.copy(t).slerp(e,r)}random(){let t=Math.random(),e=Math.sqrt(1-t),r=Math.sqrt(t),i=2*Math.PI*Math.random(),o=2*Math.PI*Math.random();return this.set(e*Math.cos(i),r*Math.sin(o),r*Math.cos(o),e*Math.sin(i))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}};wn.prototype.isQuaternion=!0;var j=class{constructor(t=0,e=0,r=0){this.x=t,this.y=e,this.z=r}set(t,e,r){return r===void 0&&(r=this.z),this.x=t,this.y=e,this.z=r,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t,e){return e!==void 0?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t,e){return e!==void 0?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t,e){return e!==void 0?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return t&&t.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(DD.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(DD.setFromAxisAngle(t,e))}applyMatrix3(t){let e=this.x,r=this.y,i=this.z,o=t.elements;return this.x=o[0]*e+o[3]*r+o[6]*i,this.y=o[1]*e+o[4]*r+o[7]*i,this.z=o[2]*e+o[5]*r+o[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){let e=this.x,r=this.y,i=this.z,o=t.elements,s=1/(o[3]*e+o[7]*r+o[11]*i+o[15]);return this.x=(o[0]*e+o[4]*r+o[8]*i+o[12])*s,this.y=(o[1]*e+o[5]*r+o[9]*i+o[13])*s,this.z=(o[2]*e+o[6]*r+o[10]*i+o[14])*s,this}applyQuaternion(t){let e=this.x,r=this.y,i=this.z,o=t.x,s=t.y,a=t.z,l=t.w,c=l*e+s*i-a*r,u=l*r+a*e-o*i,h=l*i+o*r-s*e,p=-o*e-s*r-a*i;return this.x=c*l+p*-o+u*-a-h*-s,this.y=u*l+p*-s+h*-o-c*-a,this.z=h*l+p*-a+c*-s-u*-o,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){let e=this.x,r=this.y,i=this.z,o=t.elements;return this.x=o[0]*e+o[4]*r+o[8]*i,this.y=o[1]*e+o[5]*r+o[9]*i,this.z=o[2]*e+o[6]*r+o[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){let r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(t,Math.min(e,r)))}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=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,r){return this.x=t.x+(e.x-t.x)*r,this.y=t.y+(e.y-t.y)*r,this.z=t.z+(e.z-t.z)*r,this}cross(t,e){return e!==void 0?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e)):this.crossVectors(this,t)}crossVectors(t,e){let r=t.x,i=t.y,o=t.z,s=e.x,a=e.y,l=e.z;return this.x=i*l-o*a,this.y=o*s-r*l,this.z=r*a-i*s,this}projectOnVector(t){let e=t.lengthSq();if(e===0)return this.set(0,0,0);let r=t.dot(this)/e;return this.copy(t).multiplyScalar(r)}projectOnPlane(t){return Vw.copy(this).projectOnVector(t),this.sub(Vw)}reflect(t){return this.sub(Vw.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let r=this.dot(t)/e;return Math.acos(er(r,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,r=this.y-t.y,i=this.z-t.z;return e*e+r*r+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,r){let i=Math.sin(e)*t;return this.x=i*Math.sin(r),this.y=Math.cos(e)*t,this.z=i*Math.cos(r),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,r){return this.x=t*Math.sin(e),this.y=r,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){let e=this.setFromMatrixColumn(t,0).length(),r=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=r,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e,r){return r!==void 0&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let t=(Math.random()-.5)*2,e=Math.random()*Math.PI*2,r=Math.sqrt(1-V3(t,2));return this.x=r*Math.cos(e),this.y=r*Math.sin(e),this.z=t,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};j.prototype.isVector3=!0;var Vw=new j,DD=new wn,wr=class{constructor(t=new j(1/0,1/0,1/0),e=new j(-1/0,-1/0,-1/0)){this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){let e=1/0,r=1/0,i=1/0,o=-1/0,s=-1/0,a=-1/0;for(let l=0,c=t.length;lo&&(o=u),h>s&&(s=h),p>a&&(a=p)}return this.min.set(e,r,i),this.max.set(o,s,a),this}setFromBufferAttribute(t){let e=1/0,r=1/0,i=1/0,o=-1/0,s=-1/0,a=-1/0;for(let l=0,c=t.count;lo&&(o=u),h>s&&(s=h),p>a&&(a=p)}return this.min.set(e,r,i),this.max.set(o,s,a),this}setFromPoints(t){this.makeEmpty();for(let e=0,r=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)}intersectsSphere(t){return this.clampPoint(t.center,fa),fa.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,r;return t.normal.x>0?(e=t.normal.x*this.min.x,r=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,r=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,r+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,r+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,r+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,r+=t.normal.z*this.min.z),e<=-t.constant&&r>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Cp),ux.subVectors(this.max,Cp),fc.subVectors(t.a,Cp),mc.subVectors(t.b,Cp),gc.subVectors(t.c,Cp),Ko.subVectors(mc,fc),Yo.subVectors(gc,mc),ma.subVectors(fc,gc);let e=[0,-Ko.z,Ko.y,0,-Yo.z,Yo.y,0,-ma.z,ma.y,Ko.z,0,-Ko.x,Yo.z,0,-Yo.x,ma.z,0,-ma.x,-Ko.y,Ko.x,0,-Yo.y,Yo.x,0,-ma.y,ma.x,0];return!$w(e,fc,mc,gc,ux)||(e=[1,0,0,0,1,0,0,0,1],!$w(e,fc,mc,gc,ux))?!1:(hx.crossVectors(Ko,Yo),e=[hx.x,hx.y,hx.z],$w(e,fc,mc,gc,ux))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return fa.copy(t).clamp(this.min,this.max).sub(t).length()}getBoundingSphere(t){return this.getCenter(t.center),t.radius=this.getSize(fa).length()*.5,t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(co[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),co[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),co[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),co[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),co[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),co[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),co[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),co[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(co),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}};wr.prototype.isBox3=!0;var co=[new j,new j,new j,new j,new j,new j,new j,new j],fa=new j,Hw=new wr,fc=new j,mc=new j,gc=new j,Ko=new j,Yo=new j,ma=new j,Cp=new j,ux=new j,hx=new j,xa=new j;function $w(n,t,e,r,i){for(let o=0,s=n.length-3;o<=s;o+=3){xa.fromArray(n,o);let a=i.x*Math.abs(xa.x)+i.y*Math.abs(xa.y)+i.z*Math.abs(xa.z),l=t.dot(xa),c=e.dot(xa),u=r.dot(xa);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>a)return!1}return!0}var ret=new wr,zD=new j,px=new j,Uw=new j,us=class{constructor(t=new j,e=-1){this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){let r=this.center;e!==void 0?r.copy(e):ret.setFromPoints(t).getCenter(r);let i=0;for(let o=0,s=t.length;othis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){Uw.subVectors(t,this.center);let e=Uw.lengthSq();if(e>this.radius*this.radius){let r=Math.sqrt(e),i=(r-this.radius)*.5;this.center.add(Uw.multiplyScalar(i/r)),this.radius+=i}return this}union(t){return this.center.equals(t.center)===!0?px.set(0,0,1).multiplyScalar(t.radius):px.subVectors(t.center,this.center).normalize().multiplyScalar(t.radius),this.expandByPoint(zD.copy(t.center).add(px)),this.expandByPoint(zD.copy(t.center).sub(px)),this}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}},uo=new j,Ww=new j,dx=new j,Zo=new j,Gw=new j,fx=new j,jw=new j,hs=class{constructor(t=new j,e=new j(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.direction).multiplyScalar(t).add(this.origin)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,uo)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);let r=e.dot(this.direction);return r<0?e.copy(this.origin):e.copy(this.direction).multiplyScalar(r).add(this.origin)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){let e=uo.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(uo.copy(this.direction).multiplyScalar(e).add(this.origin),uo.distanceToSquared(t))}distanceSqToSegment(t,e,r,i){Ww.copy(t).add(e).multiplyScalar(.5),dx.copy(e).sub(t).normalize(),Zo.copy(this.origin).sub(Ww);let o=t.distanceTo(e)*.5,s=-this.direction.dot(dx),a=Zo.dot(this.direction),l=-Zo.dot(dx),c=Zo.lengthSq(),u=Math.abs(1-s*s),h,p,d,f;if(u>0)if(h=s*l-a,p=s*a-l,f=o*u,h>=0)if(p>=-f)if(p<=f){let m=1/u;h*=m,p*=m,d=h*(h+s*p+2*a)+p*(s*h+p+2*l)+c}else p=o,h=Math.max(0,-(s*p+a)),d=-h*h+p*(p+2*l)+c;else p=-o,h=Math.max(0,-(s*p+a)),d=-h*h+p*(p+2*l)+c;else p<=-f?(h=Math.max(0,-(-s*o+a)),p=h>0?-o:Math.min(Math.max(-o,-l),o),d=-h*h+p*(p+2*l)+c):p<=f?(h=0,p=Math.min(Math.max(-o,-l),o),d=p*(p+2*l)+c):(h=Math.max(0,-(s*o+a)),p=h>0?o:Math.min(Math.max(-o,-l),o),d=-h*h+p*(p+2*l)+c);else p=s>0?-o:o,h=Math.max(0,-(s*p+a)),d=-h*h+p*(p+2*l)+c;return r&&r.copy(this.direction).multiplyScalar(h).add(this.origin),i&&i.copy(dx).multiplyScalar(p).add(Ww),d}intersectSphere(t,e){uo.subVectors(t.center,this.origin);let r=uo.dot(this.direction),i=uo.dot(uo)-r*r,o=t.radius*t.radius;if(i>o)return null;let s=Math.sqrt(o-i),a=r-s,l=r+s;return a<0&&l<0?null:a<0?this.at(l,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){let e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;let r=-(this.origin.dot(t.normal)+t.constant)/e;return r>=0?r:null}intersectPlane(t,e){let r=this.distanceToPlane(t);return r===null?null:this.at(r,e)}intersectsPlane(t){let e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let r,i,o,s,a,l,c=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,p=this.origin;return c>=0?(r=(t.min.x-p.x)*c,i=(t.max.x-p.x)*c):(r=(t.max.x-p.x)*c,i=(t.min.x-p.x)*c),u>=0?(o=(t.min.y-p.y)*u,s=(t.max.y-p.y)*u):(o=(t.max.y-p.y)*u,s=(t.min.y-p.y)*u),r>s||o>i||((o>r||r!==r)&&(r=o),(s=0?(a=(t.min.z-p.z)*h,l=(t.max.z-p.z)*h):(a=(t.max.z-p.z)*h,l=(t.min.z-p.z)*h),r>l||a>i)||((a>r||r!==r)&&(r=a),(l=0?r:i,e)}intersectsBox(t){return this.intersectBox(t,uo)!==null}intersectTriangle(t,e,r,i,o){Gw.subVectors(e,t),fx.subVectors(r,t),jw.crossVectors(Gw,fx);let s=this.direction.dot(jw),a;if(s>0){if(i)return null;a=1}else if(s<0)a=-1,s=-s;else return null;Zo.subVectors(this.origin,t);let l=a*this.direction.dot(fx.crossVectors(Zo,fx));if(l<0)return null;let c=a*this.direction.dot(Gw.cross(Zo));if(c<0||l+c>s)return null;let u=-a*Zo.dot(jw);return u<0?null:this.at(u/s,o)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Qt=class{constructor(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}set(t,e,r,i,o,s,a,l,c,u,h,p,d,f,m,x){let g=this.elements;return g[0]=t,g[4]=e,g[8]=r,g[12]=i,g[1]=o,g[5]=s,g[9]=a,g[13]=l,g[2]=c,g[6]=u,g[10]=h,g[14]=p,g[3]=d,g[7]=f,g[11]=m,g[15]=x,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Qt().fromArray(this.elements)}copy(t){let e=this.elements,r=t.elements;return e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=r[3],e[4]=r[4],e[5]=r[5],e[6]=r[6],e[7]=r[7],e[8]=r[8],e[9]=r[9],e[10]=r[10],e[11]=r[11],e[12]=r[12],e[13]=r[13],e[14]=r[14],e[15]=r[15],this}copyPosition(t){let e=this.elements,r=t.elements;return e[12]=r[12],e[13]=r[13],e[14]=r[14],this}setFromMatrix3(t){let e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,r){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(t,e,r){return this.set(t.x,e.x,r.x,0,t.y,e.y,r.y,0,t.z,e.z,r.z,0,0,0,0,1),this}extractRotation(t){let e=this.elements,r=t.elements,i=1/xc.setFromMatrixColumn(t,0).length(),o=1/xc.setFromMatrixColumn(t,1).length(),s=1/xc.setFromMatrixColumn(t,2).length();return e[0]=r[0]*i,e[1]=r[1]*i,e[2]=r[2]*i,e[3]=0,e[4]=r[4]*o,e[5]=r[5]*o,e[6]=r[6]*o,e[7]=0,e[8]=r[8]*s,e[9]=r[9]*s,e[10]=r[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){t&&t.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");let e=this.elements,r=t.x,i=t.y,o=t.z,s=Math.cos(r),a=Math.sin(r),l=Math.cos(i),c=Math.sin(i),u=Math.cos(o),h=Math.sin(o);if(t.order==="XYZ"){let p=s*u,d=s*h,f=a*u,m=a*h;e[0]=l*u,e[4]=-l*h,e[8]=c,e[1]=d+f*c,e[5]=p-m*c,e[9]=-a*l,e[2]=m-p*c,e[6]=f+d*c,e[10]=s*l}else if(t.order==="YXZ"){let p=l*u,d=l*h,f=c*u,m=c*h;e[0]=p+m*a,e[4]=f*a-d,e[8]=s*c,e[1]=s*h,e[5]=s*u,e[9]=-a,e[2]=d*a-f,e[6]=m+p*a,e[10]=s*l}else if(t.order==="ZXY"){let p=l*u,d=l*h,f=c*u,m=c*h;e[0]=p-m*a,e[4]=-s*h,e[8]=f+d*a,e[1]=d+f*a,e[5]=s*u,e[9]=m-p*a,e[2]=-s*c,e[6]=a,e[10]=s*l}else if(t.order==="ZYX"){let p=s*u,d=s*h,f=a*u,m=a*h;e[0]=l*u,e[4]=f*c-d,e[8]=p*c+m,e[1]=l*h,e[5]=m*c+p,e[9]=d*c-f,e[2]=-c,e[6]=a*l,e[10]=s*l}else if(t.order==="YZX"){let p=s*l,d=s*c,f=a*l,m=a*c;e[0]=l*u,e[4]=m-p*h,e[8]=f*h+d,e[1]=h,e[5]=s*u,e[9]=-a*u,e[2]=-c*u,e[6]=d*h+f,e[10]=p-m*h}else if(t.order==="XZY"){let p=s*l,d=s*c,f=a*l,m=a*c;e[0]=l*u,e[4]=-h,e[8]=c*u,e[1]=p*h+m,e[5]=s*u,e[9]=d*h-f,e[2]=f*h-d,e[6]=a*u,e[10]=m*h+p}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(iet,t,oet)}lookAt(t,e,r){let i=this.elements;return yr.subVectors(t,e),yr.lengthSq()===0&&(yr.z=1),yr.normalize(),Jo.crossVectors(r,yr),Jo.lengthSq()===0&&(Math.abs(r.z)===1?yr.x+=1e-4:yr.z+=1e-4,yr.normalize(),Jo.crossVectors(r,yr)),Jo.normalize(),mx.crossVectors(yr,Jo),i[0]=Jo.x,i[4]=mx.x,i[8]=yr.x,i[1]=Jo.y,i[5]=mx.y,i[9]=yr.y,i[2]=Jo.z,i[6]=mx.z,i[10]=yr.z,this}multiply(t,e){return e!==void 0?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){let r=t.elements,i=e.elements,o=this.elements,s=r[0],a=r[4],l=r[8],c=r[12],u=r[1],h=r[5],p=r[9],d=r[13],f=r[2],m=r[6],x=r[10],g=r[14],v=r[3],b=r[7],y=r[11],_=r[15],S=i[0],E=i[4],M=i[8],P=i[12],D=i[1],w=i[5],I=i[9],N=i[13],L=i[2],O=i[6],z=i[10],V=i[14],$=i[3],X=i[7],W=i[11],K=i[15];return o[0]=s*S+a*D+l*L+c*$,o[4]=s*E+a*w+l*O+c*X,o[8]=s*M+a*I+l*z+c*W,o[12]=s*P+a*N+l*V+c*K,o[1]=u*S+h*D+p*L+d*$,o[5]=u*E+h*w+p*O+d*X,o[9]=u*M+h*I+p*z+d*W,o[13]=u*P+h*N+p*V+d*K,o[2]=f*S+m*D+x*L+g*$,o[6]=f*E+m*w+x*O+g*X,o[10]=f*M+m*I+x*z+g*W,o[14]=f*P+m*N+x*V+g*K,o[3]=v*S+b*D+y*L+_*$,o[7]=v*E+b*w+y*O+_*X,o[11]=v*M+b*I+y*z+_*W,o[15]=v*P+b*N+y*V+_*K,this}multiplyScalar(t){let e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){let t=this.elements,e=t[0],r=t[4],i=t[8],o=t[12],s=t[1],a=t[5],l=t[9],c=t[13],u=t[2],h=t[6],p=t[10],d=t[14],f=t[3],m=t[7],x=t[11],g=t[15];return f*(+o*l*h-i*c*h-o*a*p+r*c*p+i*a*d-r*l*d)+m*(+e*l*d-e*c*p+o*s*p-i*s*d+i*c*u-o*l*u)+x*(+e*c*h-e*a*d-o*s*h+r*s*d+o*a*u-r*c*u)+g*(-i*a*u-e*l*h+e*a*p+i*s*h-r*s*p+r*l*u)}transpose(){let t=this.elements,e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,r){let i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=r),this}invert(){let t=this.elements,e=t[0],r=t[1],i=t[2],o=t[3],s=t[4],a=t[5],l=t[6],c=t[7],u=t[8],h=t[9],p=t[10],d=t[11],f=t[12],m=t[13],x=t[14],g=t[15],v=h*x*c-m*p*c+m*l*d-a*x*d-h*l*g+a*p*g,b=f*p*c-u*x*c-f*l*d+s*x*d+u*l*g-s*p*g,y=u*m*c-f*h*c+f*a*d-s*m*d-u*a*g+s*h*g,_=f*h*l-u*m*l-f*a*p+s*m*p+u*a*x-s*h*x,S=e*v+r*b+i*y+o*_;if(S===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let E=1/S;return t[0]=v*E,t[1]=(m*p*o-h*x*o-m*i*d+r*x*d+h*i*g-r*p*g)*E,t[2]=(a*x*o-m*l*o+m*i*c-r*x*c-a*i*g+r*l*g)*E,t[3]=(h*l*o-a*p*o-h*i*c+r*p*c+a*i*d-r*l*d)*E,t[4]=b*E,t[5]=(u*x*o-f*p*o+f*i*d-e*x*d-u*i*g+e*p*g)*E,t[6]=(f*l*o-s*x*o-f*i*c+e*x*c+s*i*g-e*l*g)*E,t[7]=(s*p*o-u*l*o+u*i*c-e*p*c-s*i*d+e*l*d)*E,t[8]=y*E,t[9]=(f*h*o-u*m*o-f*r*d+e*m*d+u*r*g-e*h*g)*E,t[10]=(s*m*o-f*a*o+f*r*c-e*m*c-s*r*g+e*a*g)*E,t[11]=(u*a*o-s*h*o-u*r*c+e*h*c+s*r*d-e*a*d)*E,t[12]=_*E,t[13]=(u*m*i-f*h*i+f*r*p-e*m*p-u*r*x+e*h*x)*E,t[14]=(f*a*i-s*m*i-f*r*l+e*m*l+s*r*x-e*a*x)*E,t[15]=(s*h*i-u*a*i+u*r*l-e*h*l-s*r*p+e*a*p)*E,this}scale(t){let e=this.elements,r=t.x,i=t.y,o=t.z;return e[0]*=r,e[4]*=i,e[8]*=o,e[1]*=r,e[5]*=i,e[9]*=o,e[2]*=r,e[6]*=i,e[10]*=o,e[3]*=r,e[7]*=i,e[11]*=o,this}getMaxScaleOnAxis(){let t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],r=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,r,i))}makeTranslation(t,e,r){return this.set(1,0,0,t,0,1,0,e,0,0,1,r,0,0,0,1),this}makeRotationX(t){let e=Math.cos(t),r=Math.sin(t);return this.set(1,0,0,0,0,e,-r,0,0,r,e,0,0,0,0,1),this}makeRotationY(t){let e=Math.cos(t),r=Math.sin(t);return this.set(e,0,r,0,0,1,0,0,-r,0,e,0,0,0,0,1),this}makeRotationZ(t){let e=Math.cos(t),r=Math.sin(t);return this.set(e,-r,0,0,r,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){let r=Math.cos(e),i=Math.sin(e),o=1-r,s=t.x,a=t.y,l=t.z,c=o*s,u=o*a;return this.set(c*s+r,c*a-i*l,c*l+i*a,0,c*a+i*l,u*a+r,u*l-i*s,0,c*l-i*a,u*l+i*s,o*l*l+r,0,0,0,0,1),this}makeScale(t,e,r){return this.set(t,0,0,0,0,e,0,0,0,0,r,0,0,0,0,1),this}makeShear(t,e,r,i,o,s){return this.set(1,r,o,0,t,1,s,0,e,i,1,0,0,0,0,1),this}compose(t,e,r){let i=this.elements,o=e._x,s=e._y,a=e._z,l=e._w,c=o+o,u=s+s,h=a+a,p=o*c,d=o*u,f=o*h,m=s*u,x=s*h,g=a*h,v=l*c,b=l*u,y=l*h,_=r.x,S=r.y,E=r.z;return i[0]=(1-(m+g))*_,i[1]=(d+y)*_,i[2]=(f-b)*_,i[3]=0,i[4]=(d-y)*S,i[5]=(1-(p+g))*S,i[6]=(x+v)*S,i[7]=0,i[8]=(f+b)*E,i[9]=(x-v)*E,i[10]=(1-(p+m))*E,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,r){let i=this.elements,o=xc.set(i[0],i[1],i[2]).length(),s=xc.set(i[4],i[5],i[6]).length(),a=xc.set(i[8],i[9],i[10]).length();this.determinant()<0&&(o=-o),t.x=i[12],t.y=i[13],t.z=i[14],ti.copy(this);let c=1/o,u=1/s,h=1/a;return ti.elements[0]*=c,ti.elements[1]*=c,ti.elements[2]*=c,ti.elements[4]*=u,ti.elements[5]*=u,ti.elements[6]*=u,ti.elements[8]*=h,ti.elements[9]*=h,ti.elements[10]*=h,e.setFromRotationMatrix(ti),r.x=o,r.y=s,r.z=a,this}makePerspective(t,e,r,i,o,s){s===void 0&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");let a=this.elements,l=2*o/(e-t),c=2*o/(r-i),u=(e+t)/(e-t),h=(r+i)/(r-i),p=-(s+o)/(s-o),d=-2*s*o/(s-o);return a[0]=l,a[4]=0,a[8]=u,a[12]=0,a[1]=0,a[5]=c,a[9]=h,a[13]=0,a[2]=0,a[6]=0,a[10]=p,a[14]=d,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,r,i,o,s){let a=this.elements,l=1/(e-t),c=1/(r-i),u=1/(s-o),h=(e+t)*l,p=(r+i)*c,d=(s+o)*u;return a[0]=2*l,a[4]=0,a[8]=0,a[12]=-h,a[1]=0,a[5]=2*c,a[9]=0,a[13]=-p,a[2]=0,a[6]=0,a[10]=-2*u,a[14]=-d,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){let e=this.elements,r=t.elements;for(let i=0;i<16;i++)if(e[i]!==r[i])return!1;return!0}fromArray(t,e=0){for(let r=0;r<16;r++)this.elements[r]=t[r+e];return this}toArray(t=[],e=0){let r=this.elements;return t[e]=r[0],t[e+1]=r[1],t[e+2]=r[2],t[e+3]=r[3],t[e+4]=r[4],t[e+5]=r[5],t[e+6]=r[6],t[e+7]=r[7],t[e+8]=r[8],t[e+9]=r[9],t[e+10]=r[10],t[e+11]=r[11],t[e+12]=r[12],t[e+13]=r[13],t[e+14]=r[14],t[e+15]=r[15],t}};Qt.prototype.isMatrix4=!0;var xc=new j,ti=new Qt,iet=new j(0,0,0),oet=new j(1,1,1),Jo=new j,mx=new j,yr=new j,FD=new Qt,OD=new wn,ps=class{constructor(t=0,e=0,r=0,i=ps.DefaultOrder){this._x=t,this._y=e,this._z=r,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,r,i=this._order){return this._x=t,this._y=e,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,r=!0){let i=t.elements,o=i[0],s=i[4],a=i[8],l=i[1],c=i[5],u=i[9],h=i[2],p=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin(er(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-s,o)):(this._x=Math.atan2(p,c),this._z=0);break;case"YXZ":this._x=Math.asin(-er(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-h,o),this._z=0);break;case"ZXY":this._x=Math.asin(er(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,c)):(this._y=0,this._z=Math.atan2(l,o));break;case"ZYX":this._y=Math.asin(-er(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(p,d),this._z=Math.atan2(l,o)):(this._x=0,this._z=Math.atan2(-s,c));break;case"YZX":this._z=Math.asin(er(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-h,o)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-er(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(p,c),this._y=Math.atan2(a,o)):(this._x=Math.atan2(-u,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,r===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,r){return FD.makeRotationFromQuaternion(t),this.setFromRotationMatrix(FD,e,r)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return OD.setFromEuler(this),this.setFromQuaternion(OD,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}toVector3(t){return t?t.set(this._x,this._y,this._z):new j(this._x,this._y,this._z)}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}};ps.prototype.isEuler=!0;ps.DefaultOrder="XYZ";ps.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];var qx=class{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let e=0;e1){for(let r=0;r0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(r.geometries=a),l.length>0&&(r.materials=l),c.length>0&&(r.textures=c),u.length>0&&(r.images=u),h.length>0&&(r.shapes=h),p.length>0&&(r.skeletons=p),d.length>0&&(r.animations=d)}return r.object=i,r;function s(a){let l=[];for(let c in a){let u=a[c];delete u.metadata,l.push(u)}return l}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let r=0;r0?i.multiplyScalar(1/Math.sqrt(o)):i.set(0,0,0)}static getBarycoord(t,e,r,i,o){ei.subVectors(i,e),po.subVectors(r,e),qw.subVectors(t,e);let s=ei.dot(ei),a=ei.dot(po),l=ei.dot(qw),c=po.dot(po),u=po.dot(qw),h=s*c-a*a;if(h===0)return o.set(-2,-1,-1);let p=1/h,d=(c*l-a*u)*p,f=(s*u-a*l)*p;return o.set(1-d-f,f,d)}static containsPoint(t,e,r,i){return this.getBarycoord(t,e,r,i,fo),fo.x>=0&&fo.y>=0&&fo.x+fo.y<=1}static getUV(t,e,r,i,o,s,a,l){return this.getBarycoord(t,e,r,i,fo),l.set(0,0),l.addScaledVector(o,fo.x),l.addScaledVector(s,fo.y),l.addScaledVector(a,fo.z),l}static isFrontFacing(t,e,r,i){return ei.subVectors(r,e),po.subVectors(t,e),ei.cross(po).dot(i)<0}set(t,e,r){return this.a.copy(t),this.b.copy(e),this.c.copy(r),this}setFromPointsAndIndices(t,e,r,i){return this.a.copy(t[e]),this.b.copy(t[r]),this.c.copy(t[i]),this}setFromAttributeAndIndices(t,e,r,i){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,r),this.c.fromBufferAttribute(t,i),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return ei.subVectors(this.c,this.b),po.subVectors(this.a,this.b),ei.cross(po).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Ze.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Ze.getBarycoord(t,this.a,this.b,this.c,e)}getUV(t,e,r,i,o){return Ze.getUV(t,this.a,this.b,this.c,e,r,i,o)}containsPoint(t){return Ze.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Ze.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){let r=this.a,i=this.b,o=this.c,s,a;yc.subVectors(i,r),bc.subVectors(o,r),Xw.subVectors(t,r);let l=yc.dot(Xw),c=bc.dot(Xw);if(l<=0&&c<=0)return e.copy(r);Kw.subVectors(t,i);let u=yc.dot(Kw),h=bc.dot(Kw);if(u>=0&&h<=u)return e.copy(i);let p=l*h-u*c;if(p<=0&&l>=0&&u<=0)return s=l/(l-u),e.copy(r).addScaledVector(yc,s);Yw.subVectors(t,o);let d=yc.dot(Yw),f=bc.dot(Yw);if(f>=0&&d<=f)return e.copy(o);let m=d*c-l*f;if(m<=0&&c>=0&&f<=0)return a=c/(c-f),e.copy(r).addScaledVector(bc,a);let x=u*f-d*h;if(x<=0&&h-u>=0&&d-f>=0)return WD.subVectors(o,i),a=(h-u)/(h-u+(d-f)),e.copy(i).addScaledVector(WD,a);let g=1/(x+m+p);return s=m*g,a=p*g,e.copy(r).addScaledVector(yc,s).addScaledVector(bc,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}},het=0,Dn=class extends ii{constructor(){super(),Object.defineProperty(this,"id",{value:het++}),this.uuid=ri(),this.name="",this.type="Material",this.fog=!0,this.blending=is,this.side=Op,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.blendSrc=Hz,this.blendDst=$z,this.blendEquation=Pc,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=fS,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Qtt,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Lw,this.stencilZFail=Lw,this.stencilZPass=Lw,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.alphaWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(let e in t){let r=t[e];if(r===void 0){console.warn("THREE.Material: '"+e+"' parameter is undefined.");continue}if(e==="shading"){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=r===Vz;continue}let i=this[e];if(i===void 0){console.warn("THREE."+this.type+": '"+e+"' is not a property of this material.");continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[e]=r}}toJSON(t){let e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});let r={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(t).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(t).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(t).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(t).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(t).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==is&&(r.blending=this.blending),this.side!==Op&&(r.side=this.side),this.vertexColors&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=this.transparent),r.depthFunc=this.depthFunc,r.depthTest=this.depthTest,r.depthWrite=this.depthWrite,r.colorWrite=this.colorWrite,r.alphaWrite=this.alphaWrite,r.stencilWrite=this.stencilWrite,r.stencilWriteMask=this.stencilWriteMask,r.stencilFunc=this.stencilFunc,r.stencilRef=this.stencilRef,r.stencilFuncMask=this.stencilFuncMask,r.stencilFail=this.stencilFail,r.stencilZFail=this.stencilZFail,r.stencilZPass=this.stencilZPass,this.rotation&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaToCoverage===!0&&(r.alphaToCoverage=this.alphaToCoverage),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(r.wireframe=this.wireframe),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=this.flatShading),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),JSON.stringify(this.userData)!=="{}"&&(r.userData=this.userData);function i(o){let s=[];for(let a in o){let l=o[a];delete l.metadata,s.push(l)}return s}if(e){let o=i(t.textures),s=i(t.images);o.length>0&&(r.textures=o),s.length>0&&(r.images=s)}return r}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.fog=t.fog,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;let e=t.clippingPlanes,r=null;if(e!==null){let i=e.length;r=new Array(i);for(let o=0;o!==i;++o)r[o]=e[o].clone()}return this.clippingPlanes=r,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.alphaWrite=t.alphaWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}};Dn.prototype.isMaterial=!0;var Up=class extends Dn{constructor(t){super(),this.type="MeshBasicMaterial",this.color=new Pt(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.combine=yv,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this}};Up.prototype.isMeshBasicMaterial=!0;var De=new j,xx=new Mt,se=class{constructor(t,e,r){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=r===!0,this.usage=Vp,this.updateRange={offset:0,count:-1},this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this}copyAt(t,e,r){t*=this.itemSize,r*=e.itemSize;for(let i=0,o=this.itemSize;i0&&(t.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(t[c]=l[c]);return t}t.data={attributes:{}};let e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});let r=this.attributes;for(let l in r){let c=r[l];t.data.attributes[l]=c.toJSON(t.data)}let i={},o=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],u=[];for(let h=0,p=c.length;h0&&(i[l]=u,o=!0)}o&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);let s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));let a=this.boundingSphere;return a!==null&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let e={};this.name=t.name;let r=t.index;r!==null&&this.setIndex(r.clone(e));let i=t.attributes;for(let c in i){let u=i[c];this.setAttribute(c,u.clone(e))}let o=t.morphAttributes;for(let c in o){let u=[],h=o[c];for(let p=0,d=h.length;p0){let i=e[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let o=0,s=i.length;o0&&console.error("THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}}raycast(t,e){let r=this.geometry,i=this.material,o=this.matrixWorld;if(i===void 0||(r.boundingSphere===null&&r.computeBoundingSphere(),Jw.copy(r.boundingSphere),Jw.applyMatrix4(o),t.ray.intersectsSphere(Jw)===!1)||(GD.copy(o).invert(),wc.copy(t.ray).applyMatrix4(GD),r.boundingBox!==null&&wc.intersectsBox(r.boundingBox)===!1))return;let s;if(r.isBufferGeometry){let a=r.index,l=r.attributes.position,c=r.morphAttributes.position,u=r.morphTargetsRelative,h=r.attributes.uv,p=r.attributes.uv2,d=r.groups,f=r.drawRange;if(a!==null)if(Array.isArray(i))for(let m=0,x=d.length;me.far?null:{distance:c,point:Cx.clone(),object:n}}function Mx(n,t,e,r,i,o,s,a,l,c,u,h){Qo.fromBufferAttribute(i,c),ts.fromBufferAttribute(i,u),es.fromBufferAttribute(i,h);let p=n.morphTargetInfluences;if(o&&p){vx.set(0,0,0),yx.set(0,0,0),bx.set(0,0,0);for(let f=0,m=o.length;f0?1:-1,u.push(X.x,X.y,X.z),h.push(Z/E),h.push(1-W/M),V+=1}}for(let W=0;W0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader;let r={};for(let i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(e.extensions=r),e}};ur.prototype.isShaderMaterial=!0;var Wp=class extends Te{constructor(){super(),this.type="Camera",this.matrixWorldInverse=new Qt,this.projectionMatrix=new Qt,this.projectionMatrixInverse=new Qt}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this}getWorldDirection(t){this.updateWorldMatrix(!0,!1);let e=this.matrixWorld.elements;return t.set(-e[8],-e[9],-e[10]).normalize()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}};Wp.prototype.isCamera=!0;var ln=class extends Wp{constructor(t=50,e=1,r=.1,i=2e3){super(),this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=t.view===null?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){let e=.5*this.getFilmHeight()/t;this.fov=bS*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){let t=Math.tan(Dw*.5*this.fov);return .5*this.getFilmHeight()/t}getEffectiveFOV(){return bS*2*Math.atan(Math.tan(Dw*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(t,e,r,i,o,s){this.aspect=t/e,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=r,this.view.offsetY=i,this.view.width=o,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let t=this.near,e=t*Math.tan(Dw*.5*this.fov)/this.zoom,r=2*e,i=this.aspect*r,o=-.5*i,s=this.view;if(this.view!==null&&this.view.enabled){let l=s.fullWidth,c=s.fullHeight;o+=s.offsetX*i/l,e-=s.offsetY*r/c,i*=s.width/l,r*=s.height/c}let a=this.filmOffset;a!==0&&(o+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(o,o+i,e,e-r,t,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){let e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,this.view!==null&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}};ln.prototype.isPerspectiveCamera=!0;var Sc=90,Cc=1,Gp=class extends Te{constructor(t,e,r){if(super(),this.type="CubeCamera",r.isWebGLCubeRenderTarget!==!0){console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");return}this.renderTarget=r;let i=new ln(Sc,Cc,t,e);i.layers=this.layers,i.up.set(0,-1,0),i.lookAt(new j(1,0,0)),this.add(i);let o=new ln(Sc,Cc,t,e);o.layers=this.layers,o.up.set(0,-1,0),o.lookAt(new j(-1,0,0)),this.add(o);let s=new ln(Sc,Cc,t,e);s.layers=this.layers,s.up.set(0,0,1),s.lookAt(new j(0,1,0)),this.add(s);let a=new ln(Sc,Cc,t,e);a.layers=this.layers,a.up.set(0,0,-1),a.lookAt(new j(0,-1,0)),this.add(a);let l=new ln(Sc,Cc,t,e);l.layers=this.layers,l.up.set(0,-1,0),l.lookAt(new j(0,0,1)),this.add(l);let c=new ln(Sc,Cc,t,e);c.layers=this.layers,c.up.set(0,-1,0),c.lookAt(new j(0,0,-1)),this.add(c)}update(t,e){this.parent===null&&this.updateMatrixWorld();let r=this.renderTarget,[i,o,s,a,l,c]=this.children,u=t.xr.enabled,h=t.getRenderTarget();t.xr.enabled=!1;let p=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,t.setRenderTarget(r,0),t.render(e,i),t.setRenderTarget(r,1),t.render(e,o),t.setRenderTarget(r,2),t.render(e,s),t.setRenderTarget(r,3),t.render(e,a),t.setRenderTarget(r,4),t.render(e,l),r.texture.generateMipmaps=p,t.setRenderTarget(r,5),t.render(e,c),t.setRenderTarget(h),t.xr.enabled=u,r.texture.needsPMREMUpdate=!0}},Uc=class extends Qe{constructor(t,e,r,i,o,s,a,l,c,u){t=t!==void 0?t:[],e=e!==void 0?e:pd,super(t,e,r,i,o,s,a,l,c,u),this.flipY=!1}get images(){return this.image}set images(t){this.image=t}};Uc.prototype.isCubeTexture=!0;var Yx=class extends Xn{constructor(t,e,r){Number.isInteger(e)&&(console.warn("THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )"),e=r),super(t,t,e),e=e||{},this.texture=new Uc(void 0,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.encoding),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=e.generateMipmaps!==void 0?e.generateMipmaps:!1,this.texture.minFilter=e.minFilter!==void 0?e.minFilter:dn}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.format=nr,this.texture.encoding=e.encoding,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;let r={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},i=new wa(5,5,5),o=new ur({name:"CubemapFromEquirect",uniforms:$c(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:yn,blending:rs});o.uniforms.tEquirect.value=e;let s=new Ln(i,o),a=e.minFilter;return e.minFilter===_v&&(e.minFilter=dn),new Gp(1,10,this).update(t,s),e.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(t,e,r,i){let o=t.getRenderTarget();for(let s=0;s<6;s++)t.setRenderTarget(this,s),t.clear(e,r,i);t.setRenderTarget(o)}};Yx.prototype.isWebGLCubeRenderTarget=!0;var rS=new j,xet=new j,vet=new _n,ni=class{constructor(t=new j(1,0,0),e=0){this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,r,i){return this.normal.set(t,e,r),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,r){let i=rS.subVectors(r,e).cross(xet.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){let t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(this.normal).multiplyScalar(-this.distanceToPoint(t)).add(t)}intersectLine(t,e){let r=t.delta(rS),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;let o=-(t.start.dot(this.normal)+this.constant)/i;return o<0||o>1?null:e.copy(r).multiplyScalar(o).add(t.start)}intersectsLine(t){let e=this.distanceToPoint(t.start),r=this.distanceToPoint(t.end);return e<0&&r>0||r<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){let r=e||vet.getNormalMatrix(t),i=this.coplanarPoint(rS).applyMatrix4(t),o=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(o),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}};ni.prototype.isPlane=!0;var Mc=new us,Ex=new j,Wc=class{constructor(t=new ni,e=new ni,r=new ni,i=new ni,o=new ni,s=new ni){this.planes=[t,e,r,i,o,s]}set(t,e,r,i,o,s){let a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(r),a[3].copy(i),a[4].copy(o),a[5].copy(s),this}copy(t){let e=this.planes;for(let r=0;r<6;r++)e[r].copy(t.planes[r]);return this}setFromProjectionMatrix(t){let e=this.planes,r=t.elements,i=r[0],o=r[1],s=r[2],a=r[3],l=r[4],c=r[5],u=r[6],h=r[7],p=r[8],d=r[9],f=r[10],m=r[11],x=r[12],g=r[13],v=r[14],b=r[15];return e[0].setComponents(a-i,h-l,m-p,b-x).normalize(),e[1].setComponents(a+i,h+l,m+p,b+x).normalize(),e[2].setComponents(a+o,h+c,m+d,b+g).normalize(),e[3].setComponents(a-o,h-c,m-d,b-g).normalize(),e[4].setComponents(a-s,h-u,m-f,b-v).normalize(),e[5].setComponents(a+s,h+u,m+f,b+v).normalize(),this}intersectsObject(t){let e=t.geometry;return e.boundingSphere===null&&e.computeBoundingSphere(),Mc.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),this.intersectsSphere(Mc)}intersectsSprite(t){return Mc.center.set(0,0,0),Mc.radius=.7071067811865476,Mc.applyMatrix4(t.matrixWorld),this.intersectsSphere(Mc)}intersectsSphere(t){let e=this.planes,r=t.center,i=-t.radius;for(let o=0;o<6;o++)if(e[o].distanceToPoint(r)0?t.max.x:t.min.x,Ex.y=i.normal.y>0?t.max.y:t.min.y,Ex.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(Ex)<0)return!1}return!0}containsPoint(t){let e=this.planes;for(let r=0;r<6;r++)if(e[r].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}};function qz(){let n=null,t=!1,e=null,r=null;function i(o,s){e(o,s),r=n.requestAnimationFrame(i)}return{start:function(){t!==!0&&e!==null&&(r=n.requestAnimationFrame(i),t=!0)},stop:function(){n.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(o){e=o},setContext:function(o){n=o}}}function yet(n,t){let e=t.isWebGL2,r=new WeakMap;function i(c,u){let h=c.array,p=c.usage,d=n.createBuffer();n.bindBuffer(u,d),n.bufferData(u,h,p),c.onUploadCallback();let f=5126;return h instanceof Float32Array?f=5126:h instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):h instanceof Uint16Array?c.isFloat16BufferAttribute?e?f=5131:console.warn("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2."):f=5123:h instanceof Int16Array?f=5122:h instanceof Uint32Array?f=5125:h instanceof Int32Array?f=5124:h instanceof Int8Array?f=5120:(h instanceof Uint8Array||h instanceof Uint8ClampedArray)&&(f=5121),{buffer:d,type:f,bytesPerElement:h.BYTES_PER_ELEMENT,version:c.version}}function o(c,u,h){let p=u.array,d=u.updateRange;n.bindBuffer(h,c),d.count===-1?n.bufferSubData(h,0,p):(e?n.bufferSubData(h,d.offset*p.BYTES_PER_ELEMENT,p,d.offset,d.count):n.bufferSubData(h,d.offset*p.BYTES_PER_ELEMENT,p.subarray(d.offset,d.offset+d.count)),d.count=-1)}function s(c){return c.isInterleavedBufferAttribute&&(c=c.data),r.get(c)}function a(c){c.isInterleavedBufferAttribute&&(c=c.data);let u=r.get(c);u&&(n.deleteBuffer(u.buffer),r.delete(c))}function l(c,u){if(c.isGLBufferAttribute){let p=r.get(c);(!p||p.version 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +float G_BlinnPhong_Implicit( ) { + return 0.25; +} +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); +} +vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( specularColor, 1.0, dotVH ); + float G = G_BlinnPhong_Implicit( ); + float D = D_BlinnPhong( shininess, dotNH ); + return F * ( G * D ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif`,ket=`#ifdef USE_BUMPMAP + uniform sampler2D bumpMap; + uniform float bumpScale; + vec2 dHdxy_fwd() { + vec2 dSTdx = dFdx( vUv ); + vec2 dSTdy = dFdy( vUv ); + float Hll = bumpScale * texture2D( bumpMap, vUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll; + return vec2( dBx, dBy ); + } + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { + vec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) ); + vec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) ); + vec3 vN = surf_norm; + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + float fDet = dot( vSigmaX, R1 ) * faceDirection; + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + } +#endif`,Ret=`#if NUM_CLIPPING_PLANES > 0 + vec4 plane; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif +#endif`,Pet=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,Net=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,Let=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,Det=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,zet=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,Fet=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) + varying vec3 vColor; +#endif`,Oet=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif`,Bet=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +struct GeometricContext { + vec3 position; + vec3 normal; + vec3 viewDir; +#ifdef USE_CLEARCOAT + vec3 clearcoatNormal; +#endif +}; +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +float linearToRelativeLuminance( const in vec3 color ) { + vec3 weights = vec3( 0.2126, 0.7152, 0.0722 ); + return dot( weights, color.rgb ); +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +}`,Vet=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_maxMipLevel 8.0 + #define cubeUV_minMipLevel 4.0 + #define cubeUV_maxTileSize 256.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + float texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize ); + vec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ) + 0.5; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + if ( mipInt < cubeUV_maxMipLevel ) { + uv.y += 2.0 * cubeUV_maxTileSize; + } + uv.y += filterInt * 2.0 * cubeUV_minTileSize; + uv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize ); + uv *= texelSize; + return texture2D( envMap, uv ).rgb; + } + #define r0 1.0 + #define v0 0.339 + #define m0 - 2.0 + #define r1 0.8 + #define v1 0.276 + #define m1 - 1.0 + #define r4 0.4 + #define v4 0.046 + #define m4 2.0 + #define r5 0.305 + #define v5 0.016 + #define m5 3.0 + #define r6 0.21 + #define v6 0.0038 + #define m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= r1 ) { + mip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0; + } else if ( roughness >= r4 ) { + mip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1; + } else if ( roughness >= r5 ) { + mip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4; + } else if ( roughness >= r6 ) { + mip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,Het=`vec3 transformedNormal = objectNormal; +#ifdef USE_INSTANCING + mat3 m = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) ); + transformedNormal = m * transformedNormal; +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + vec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,$et=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,Uet=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias ); +#endif`,Wet=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vUv ); + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,Get=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,jet="gl_FragColor = linearToOutputTexel( gl_FragColor );",qet=`vec4 LinearToLinear( in vec4 value ) { + return value; +} +vec4 LinearTosRGB( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,Xet=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,Ket=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,Yet=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,Zet=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,Jet=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,Qet=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,tnt=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,ent=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,nnt=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,rnt=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + return ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 ); + #endif +}`,int=`#ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vUv2 ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + #ifndef PHYSICALLY_CORRECT_LIGHTS + lightMapIrradiance *= PI; + #endif + reflectedLight.indirectDiffuse += lightMapIrradiance; +#endif`,ont=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,snt=`vec3 diffuse = vec3( 1.0 ); +GeometricContext geometry; +geometry.position = mvPosition.xyz; +geometry.normal = normalize( transformedNormal ); +geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz ); +GeometricContext backGeometry; +backGeometry.position = geometry.position; +backGeometry.normal = -geometry.normal; +backGeometry.viewDir = geometry.viewDir; +vLightFront = vec3( 0.0 ); +vIndirectFront = vec3( 0.0 ); +#ifdef DOUBLE_SIDED + vLightBack = vec3( 0.0 ); + vIndirectBack = vec3( 0.0 ); +#endif +IncidentLight directLight; +float dotNL; +vec3 directLightColor_Diffuse; +vIndirectFront += getAmbientLightIrradiance( ambientLightColor ); +vIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal ); +#ifdef DOUBLE_SIDED + vIndirectBack += getAmbientLightIrradiance( ambientLightColor ); + vIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal ); +#endif +#if NUM_POINT_LIGHTS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + getPointLightInfo( pointLights[ i ], geometry, directLight ); + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + #ifdef DOUBLE_SIDED + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + #endif + } + #pragma unroll_loop_end +#endif +#if NUM_SPOT_LIGHTS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + getSpotLightInfo( spotLights[ i ], geometry, directLight ); + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + #ifdef DOUBLE_SIDED + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + #endif + } + #pragma unroll_loop_end +#endif +#if NUM_DIR_LIGHTS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + getDirectionalLightInfo( directionalLights[ i ], geometry, directLight ); + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + #ifdef DOUBLE_SIDED + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + #endif + } + #pragma unroll_loop_end +#endif +#if NUM_HEMI_LIGHTS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + vIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); + #ifdef DOUBLE_SIDED + vIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal ); + #endif + } + #pragma unroll_loop_end +#endif`,ant=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +uniform vec3 lightProbe[ 9 ]; +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + #if defined ( PHYSICALLY_CORRECT_LIGHTS ) + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; + #else + if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) { + return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent ); + } + return 1.0; + #endif +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometry.position; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometry.position; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,lnt=`#if defined( USE_ENVMAP ) + #ifdef ENVMAP_MODE_REFRACTION + uniform float refractionRatio; + #endif + vec3 getIBLIrradiance( const in vec3 normal ) { + #if defined( ENVMAP_TYPE_CUBE_UV ) + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #if defined( ENVMAP_TYPE_CUBE_UV ) + vec3 reflectVec; + #ifdef ENVMAP_MODE_REFLECTION + reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + #else + reflectVec = refract( - viewDir, normal, refractionRatio ); + #endif + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } +#endif`,cnt=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,unt=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon +#define Material_LightProbeLOD( material ) (0)`,hnt=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,pnt=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong +#define Material_LightProbeLOD( material ) (0)`,dnt=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + #ifdef SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULARINTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a; + #endif + #ifdef USE_SPECULARCOLORMAP + specularColorFactor *= texture2D( specularColorMap, vUv ).rgb; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEENCOLORMAP + material.sheenColor *= texture2D( sheenColorMap, vUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEENROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a; + #endif +#endif`,fnt=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif +}; +vec3 clearcoatSpecular = vec3( 0.0 ); +vec3 sheenSpecular = vec3( 0.0 ); +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + vec3 FssEss = specularColor * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometry.normal; + vec3 viewDir = geometry.viewDir; + vec3 position = geometry.position; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + computeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + vec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,mnt=` +GeometricContext geometry; +geometry.position = - vViewPosition; +geometry.normal = normal; +geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +#ifdef USE_CLEARCOAT + geometry.clearcoatNormal = clearcoatNormal; +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometry, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometry, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometry, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometry, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, geometry, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometry, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,gnt=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vUv2 ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + #ifndef PHYSICALLY_CORRECT_LIGHTS + lightMapIrradiance *= PI; + #endif + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometry.normal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + radiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness ); + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,xnt=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight ); +#endif`,vnt=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) + gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,ynt=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,bnt=`#ifdef USE_LOGDEPTHBUF + #ifdef USE_LOGDEPTHBUF_EXT + varying float vFragDepth; + varying float vIsPerspective; + #else + uniform float logDepthBufFC; + #endif +#endif`,_nt=`#ifdef USE_LOGDEPTHBUF + #ifdef USE_LOGDEPTHBUF_EXT + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); + #else + if ( isPerspectiveMatrix( projectionMatrix ) ) { + gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0; + gl_Position.z *= gl_Position.w; + } + #endif +#endif`,wnt=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,Snt=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,Cnt=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,Mnt=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,Ent=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vUv ); + metalnessFactor *= texelMetalness.b; +#endif`,Tnt=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,Ant=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + #ifdef MORPHTARGETS_TEXTURE + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ]; + } + #else + objectNormal += morphNormal0 * morphTargetInfluences[ 0 ]; + objectNormal += morphNormal1 * morphTargetInfluences[ 1 ]; + objectNormal += morphNormal2 * morphTargetInfluences[ 2 ]; + objectNormal += morphNormal3 * morphTargetInfluences[ 3 ]; + #endif +#endif`,Int=`#ifdef USE_MORPHTARGETS + uniform float morphTargetBaseInfluence; + #ifdef MORPHTARGETS_TEXTURE + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + uniform sampler2DArray morphTargetsTexture; + uniform vec2 morphTargetsTextureSize; + vec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) { + float texelIndex = float( vertexIndex * stride + offset ); + float y = floor( texelIndex / morphTargetsTextureSize.x ); + float x = texelIndex - y * morphTargetsTextureSize.x; + vec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex ); + return texture( morphTargetsTexture, morphUV ).xyz; + } + #else + #ifndef USE_MORPHNORMALS + uniform float morphTargetInfluences[ 8 ]; + #else + uniform float morphTargetInfluences[ 4 ]; + #endif + #endif +#endif`,knt=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + #ifdef MORPHTARGETS_TEXTURE + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #ifndef USE_MORPHNORMALS + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ]; + #else + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ]; + #endif + } + #else + transformed += morphTarget0 * morphTargetInfluences[ 0 ]; + transformed += morphTarget1 * morphTargetInfluences[ 1 ]; + transformed += morphTarget2 * morphTargetInfluences[ 2 ]; + transformed += morphTarget3 * morphTargetInfluences[ 3 ]; + #ifndef USE_MORPHNORMALS + transformed += morphTarget4 * morphTargetInfluences[ 4 ]; + transformed += morphTarget5 * morphTargetInfluences[ 5 ]; + transformed += morphTarget6 * morphTargetInfluences[ 6 ]; + transformed += morphTarget7 * morphTargetInfluences[ 7 ]; + #endif + #endif +#endif`,Rnt=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) ); + vec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + #ifdef USE_TANGENT + vec3 tangent = normalize( vTangent ); + vec3 bitangent = normalize( vBitangent ); + #ifdef DOUBLE_SIDED + tangent = tangent * faceDirection; + bitangent = bitangent * faceDirection; + #endif + #if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP ) + mat3 vTBN = mat3( tangent, bitangent, normal ); + #endif + #endif +#endif +vec3 geometryNormal = normal;`,Pnt=`#ifdef OBJECTSPACE_NORMALMAP + normal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( TANGENTSPACE_NORMALMAP ) + vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + #ifdef USE_TANGENT + normal = normalize( vTBN * mapN ); + #else + normal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection ); + #endif +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,Nnt=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Lnt=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Dnt=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,znt=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef OBJECTSPACE_NORMALMAP + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) ) + vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) { + vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) ); + vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) ); + vec2 st0 = dFdx( vUv.st ); + vec2 st1 = dFdy( vUv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det ); + return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z ); + } +#endif`,Fnt=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = geometryNormal; +#endif`,Ont=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + #ifdef USE_TANGENT + clearcoatNormal = normalize( vTBN * clearcoatMapN ); + #else + clearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection ); + #endif +#endif`,Bnt=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif`,Vnt=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= transmissionAlpha + 0.1; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Hnt=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.; +const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. ); +const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. ); +const float ShiftRight8 = 1. / 256.; +vec4 packDepthToRGBA( const in float v ) { + vec4 r = vec4( fract( v * PackFactors ), v ); + r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale; +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors ); +} +vec4 pack2HalfToRGBA( vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) { + return linearClipZ * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * invClipZ - far ); +}`,$nt=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,Unt=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,Wnt=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,Gnt=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,jnt=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vUv ); + roughnessFactor *= texelRoughness.g; +#endif`,qnt=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,Xnt=`#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 ); + bool inFrustum = all( inFrustumVec ); + bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 ); + bool frustumTest = all( frustumTestVec ); + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return shadow; + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + vec3 lightToPosition = shadowCoord.xyz; + float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + return ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } +#endif`,Knt=`#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ]; + varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,Ynt=`#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 ); + vSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif`,Znt=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,Jnt=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,Qnt=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + #ifdef BONE_TEXTURE + uniform highp sampler2D boneTexture; + uniform int boneTextureSize; + mat4 getBoneMatrix( const in float i ) { + float j = i * 4.0; + float x = mod( j, float( boneTextureSize ) ); + float y = floor( j / float( boneTextureSize ) ); + float dx = 1.0 / float( boneTextureSize ); + float dy = 1.0 / float( boneTextureSize ); + y = dy * ( y + 0.5 ); + vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) ); + vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) ); + vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) ); + vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) ); + mat4 bone = mat4( v1, v2, v3, v4 ); + return bone; + } + #else + uniform mat4 boneMatrices[ MAX_BONES ]; + mat4 getBoneMatrix( const in float i ) { + mat4 bone = boneMatrices[ int(i) ]; + return bone; + } + #endif +#endif`,trt=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,ert=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,nrt=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,rrt=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,irt=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,ort=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return toneMappingExposure * color; +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 OptimizedCineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,srt=`#ifdef USE_TRANSMISSION + float transmissionAlpha = 1.0; + float transmissionFactor = transmission; + float thicknessFactor = thickness; + #ifdef USE_TRANSMISSIONMAP + transmissionFactor *= texture2D( transmissionMap, vUv ).r; + #endif + #ifdef USE_THICKNESSMAP + thicknessFactor *= texture2D( thicknessMap, vUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmission = getIBLVolumeRefraction( + n, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor, + attenuationColor, attenuationDistance ); + totalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor ); + transmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor ); +#endif`,art=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + #ifdef TEXTURE_LOD_EXT + return texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod ); + #else + return texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod ); + #endif + } + vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( attenuationDistance == 0.0 ) { + return radiance; + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance * radiance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance ); + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a ); + } +#endif`,lrt=`#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) ) + varying vec2 vUv; +#endif`,crt=`#ifdef USE_UV + #ifdef UVS_VERTEX_ONLY + vec2 vUv; + #else + varying vec2 vUv; + #endif + uniform mat3 uvTransform; +#endif`,urt=`#ifdef USE_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; +#endif`,hrt=`#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + varying vec2 vUv2; +#endif`,prt=`#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + attribute vec2 uv2; + varying vec2 vUv2; + uniform mat3 uv2Transform; +#endif`,drt=`#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy; +#endif`,frt=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`,mrt=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,grt=`uniform sampler2D t2D; +varying vec2 vUv; +void main() { + gl_FragColor = texture2D( t2D, vUv ); + #include + #include +}`,xrt=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,vrt=`#include +uniform float opacity; +varying vec3 vWorldDirection; +#include +void main() { + vec3 vReflect = vWorldDirection; + #include + gl_FragColor = envColor; + gl_FragColor.a *= opacity; + #include + #include +}`,yrt=`#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,brt=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + vec4 diffuseColor = vec4( 1.0 ); + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #endif +}`,_rt=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,wrt=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main () { + #include + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,Srt=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,Crt=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,Mrt=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include +}`,Ert=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +void main() { + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Trt=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Art=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel= texture2D( lightMap, vUv2 ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,Irt=`#define LAMBERT +varying vec3 vLightFront; +varying vec3 vIndirectFront; +#ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,krt=`uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +varying vec3 vLightFront; +varying vec3 vIndirectFront; +#ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #ifdef DOUBLE_SIDED + reflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack; + #else + reflectedLight.indirectDiffuse += vIndirectFront; + #endif + #include + reflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb ); + #ifdef DOUBLE_SIDED + reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; + #else + reflectedLight.directDiffuse = vLightFront; + #endif + reflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask(); + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Rrt=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,Prt=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,Nrt=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP ) + vViewPosition = - mvPosition.xyz; +#endif +}`,Lrt=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), opacity ); +}`,Drt=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,zrt=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Frt=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,Ort=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULARINTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif + #ifdef USE_SPECULARCOLORMAP + uniform sampler2D specularColorMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEENCOLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEENROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,Brt=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,Vrt=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,Hrt=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,$rt=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec3 outgoingLight = vec3( 0.0 ); + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Urt=`#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Wrt=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +void main() { + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,Grt=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); + vec2 scale; + scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) ); + scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,jrt=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec3 outgoingLight = vec3( 0.0 ); + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,ue={alphamap_fragment:bet,alphamap_pars_fragment:_et,alphatest_fragment:wet,alphatest_pars_fragment:Cet,aomap_fragment:Met,aomap_pars_fragment:Eet,begin_vertex:Tet,beginnormal_vertex:Aet,bsdfs:Iet,bumpmap_pars_fragment:ket,clipping_planes_fragment:Ret,clipping_planes_pars_fragment:Pet,clipping_planes_pars_vertex:Net,clipping_planes_vertex:Let,color_fragment:Det,color_pars_fragment:zet,color_pars_vertex:Fet,color_vertex:Oet,common:Bet,cube_uv_reflection_fragment:Vet,defaultnormal_vertex:Het,displacementmap_pars_vertex:$et,displacementmap_vertex:Uet,emissivemap_fragment:Wet,emissivemap_pars_fragment:Get,encodings_fragment:jet,encodings_pars_fragment:qet,envmap_fragment:Xet,envmap_common_pars_fragment:Ket,envmap_pars_fragment:Yet,envmap_pars_vertex:Zet,envmap_physical_pars_fragment:lnt,envmap_vertex:Jet,fog_vertex:Qet,fog_pars_vertex:tnt,fog_fragment:ent,fog_pars_fragment:nnt,gradientmap_pars_fragment:rnt,lightmap_fragment:int,lightmap_pars_fragment:ont,lights_lambert_vertex:snt,lights_pars_begin:ant,lights_toon_fragment:cnt,lights_toon_pars_fragment:unt,lights_phong_fragment:hnt,lights_phong_pars_fragment:pnt,lights_physical_fragment:dnt,lights_physical_pars_fragment:fnt,lights_fragment_begin:mnt,lights_fragment_maps:gnt,lights_fragment_end:xnt,logdepthbuf_fragment:vnt,logdepthbuf_pars_fragment:ynt,logdepthbuf_pars_vertex:bnt,logdepthbuf_vertex:_nt,map_fragment:wnt,map_pars_fragment:Snt,map_particle_fragment:Cnt,map_particle_pars_fragment:Mnt,metalnessmap_fragment:Ent,metalnessmap_pars_fragment:Tnt,morphnormal_vertex:Ant,morphtarget_pars_vertex:Int,morphtarget_vertex:knt,normal_fragment_begin:Rnt,normal_fragment_maps:Pnt,normal_pars_fragment:Nnt,normal_pars_vertex:Lnt,normal_vertex:Dnt,normalmap_pars_fragment:znt,clearcoat_normal_fragment_begin:Fnt,clearcoat_normal_fragment_maps:Ont,clearcoat_pars_fragment:Bnt,output_fragment:Vnt,packing:Hnt,premultiplied_alpha_fragment:$nt,project_vertex:Unt,dithering_fragment:Wnt,dithering_pars_fragment:Gnt,roughnessmap_fragment:jnt,roughnessmap_pars_fragment:qnt,shadowmap_pars_fragment:Xnt,shadowmap_pars_vertex:Knt,shadowmap_vertex:Ynt,shadowmask_pars_fragment:Znt,skinbase_vertex:Jnt,skinning_pars_vertex:Qnt,skinning_vertex:trt,skinnormal_vertex:ert,specularmap_fragment:nrt,specularmap_pars_fragment:rrt,tonemapping_fragment:irt,tonemapping_pars_fragment:ort,transmission_fragment:srt,transmission_pars_fragment:art,uv_pars_fragment:lrt,uv_pars_vertex:crt,uv_vertex:urt,uv2_pars_fragment:hrt,uv2_pars_vertex:prt,uv2_vertex:drt,worldpos_vertex:frt,background_vert:mrt,background_frag:grt,cube_vert:xrt,cube_frag:vrt,depth_vert:yrt,depth_frag:brt,distanceRGBA_vert:_rt,distanceRGBA_frag:wrt,equirect_vert:Srt,equirect_frag:Crt,linedashed_vert:Mrt,linedashed_frag:Ert,meshbasic_vert:Trt,meshbasic_frag:Art,meshlambert_vert:Irt,meshlambert_frag:krt,meshmatcap_vert:Rrt,meshmatcap_frag:Prt,meshnormal_vert:Nrt,meshnormal_frag:Lrt,meshphong_vert:Drt,meshphong_frag:zrt,meshphysical_vert:Frt,meshphysical_frag:Ort,meshtoon_vert:Brt,meshtoon_frag:Vrt,points_vert:Hrt,points_frag:$rt,shadow_vert:Urt,shadow_frag:Wrt,sprite_vert:Grt,sprite_frag:jrt},Nt={common:{diffuse:{value:new Pt(16777215)},opacity:{value:1},map:{value:null},uvTransform:{value:new _n},uv2Transform:{value:new _n},alphaMap:{value:null},alphaTest:{value:0}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new Mt(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Pt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Pt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new _n}},sprite:{diffuse:{value:new Pt(16777215)},opacity:{value:1},center:{value:new Mt(.5,.5)},rotation:{value:0},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new _n}}},Ii={basic:{uniforms:qn([Nt.common,Nt.specularmap,Nt.envmap,Nt.aomap,Nt.lightmap,Nt.fog]),vertexShader:ue.meshbasic_vert,fragmentShader:ue.meshbasic_frag},lambert:{uniforms:qn([Nt.common,Nt.specularmap,Nt.envmap,Nt.aomap,Nt.lightmap,Nt.emissivemap,Nt.fog,Nt.lights,{emissive:{value:new Pt(0)}}]),vertexShader:ue.meshlambert_vert,fragmentShader:ue.meshlambert_frag},phong:{uniforms:qn([Nt.common,Nt.specularmap,Nt.envmap,Nt.aomap,Nt.lightmap,Nt.emissivemap,Nt.bumpmap,Nt.normalmap,Nt.displacementmap,Nt.fog,Nt.lights,{emissive:{value:new Pt(0)},specular:{value:new Pt(1118481)},shininess:{value:30}}]),vertexShader:ue.meshphong_vert,fragmentShader:ue.meshphong_frag},standard:{uniforms:qn([Nt.common,Nt.envmap,Nt.aomap,Nt.lightmap,Nt.emissivemap,Nt.bumpmap,Nt.normalmap,Nt.displacementmap,Nt.roughnessmap,Nt.metalnessmap,Nt.fog,Nt.lights,{emissive:{value:new Pt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ue.meshphysical_vert,fragmentShader:ue.meshphysical_frag},toon:{uniforms:qn([Nt.common,Nt.aomap,Nt.lightmap,Nt.emissivemap,Nt.bumpmap,Nt.normalmap,Nt.displacementmap,Nt.gradientmap,Nt.fog,Nt.lights,{emissive:{value:new Pt(0)}}]),vertexShader:ue.meshtoon_vert,fragmentShader:ue.meshtoon_frag},matcap:{uniforms:qn([Nt.common,Nt.bumpmap,Nt.normalmap,Nt.displacementmap,Nt.fog,{matcap:{value:null}}]),vertexShader:ue.meshmatcap_vert,fragmentShader:ue.meshmatcap_frag},points:{uniforms:qn([Nt.points,Nt.fog]),vertexShader:ue.points_vert,fragmentShader:ue.points_frag},dashed:{uniforms:qn([Nt.common,Nt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ue.linedashed_vert,fragmentShader:ue.linedashed_frag},depth:{uniforms:qn([Nt.common,Nt.displacementmap]),vertexShader:ue.depth_vert,fragmentShader:ue.depth_frag},normal:{uniforms:qn([Nt.common,Nt.bumpmap,Nt.normalmap,Nt.displacementmap,{opacity:{value:1}}]),vertexShader:ue.meshnormal_vert,fragmentShader:ue.meshnormal_frag},sprite:{uniforms:qn([Nt.sprite,Nt.fog]),vertexShader:ue.sprite_vert,fragmentShader:ue.sprite_frag},background:{uniforms:{uvTransform:{value:new _n},t2D:{value:null}},vertexShader:ue.background_vert,fragmentShader:ue.background_frag},cube:{uniforms:qn([Nt.envmap,{opacity:{value:1}}]),vertexShader:ue.cube_vert,fragmentShader:ue.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ue.equirect_vert,fragmentShader:ue.equirect_frag},distanceRGBA:{uniforms:qn([Nt.common,Nt.displacementmap,{referencePosition:{value:new j},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ue.distanceRGBA_vert,fragmentShader:ue.distanceRGBA_frag},shadow:{uniforms:qn([Nt.lights,Nt.fog,{color:{value:new Pt(0)},opacity:{value:1}}]),vertexShader:ue.shadow_vert,fragmentShader:ue.shadow_frag}};Ii.physical={uniforms:qn([Ii.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatNormalScale:{value:new Mt(1,1)},clearcoatNormalMap:{value:null},sheen:{value:0},sheenColor:{value:new Pt(0)},sheenColorMap:{value:null},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},transmission:{value:0},transmissionMap:{value:null},transmissionSamplerSize:{value:new Mt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:0},attenuationColor:{value:new Pt(0)},specularIntensity:{value:1},specularIntensityMap:{value:null},specularColor:{value:new Pt(1,1,1)},specularColorMap:{value:null}}]),vertexShader:ue.meshphysical_vert,fragmentShader:ue.meshphysical_frag};function qrt(n,t,e,r,i,o){let s=new Pt(0),a=i===!0?0:1,l,c,u=null,h=0,p=null;function d(m,x){let g=!1,v=x.isScene===!0?x.background:null;v&&v.isTexture&&(v=t.get(v));let b=n.xr,y=b.getSession&&b.getSession();y&&y.environmentBlendMode==="additive"&&(v=null),v===null?f(s,a):v&&v.isColor&&(f(v,1),g=!0),(n.autoClear||g)&&n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil),v&&(v.isCubeTexture||v.mapping===bv)?(c===void 0&&(c=new Ln(new wa(1,1,1),new ur({name:"BackgroundCubeMaterial",uniforms:$c(Ii.cube.uniforms),vertexShader:Ii.cube.vertexShader,fragmentShader:Ii.cube.fragmentShader,side:yn,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(_,S,E){this.matrixWorld.copyPosition(E.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),c.material.uniforms.envMap.value=v,c.material.uniforms.flipEnvMap.value=v.isCubeTexture&&v.isRenderTargetTexture===!1?-1:1,(u!==v||h!==v.version||p!==n.toneMapping)&&(c.material.needsUpdate=!0,u=v,h=v.version,p=n.toneMapping),m.unshift(c,c.geometry,c.material,0,0,null)):v&&v.isTexture&&(l===void 0&&(l=new Ln(new jp(2,2),new ur({name:"BackgroundMaterial",uniforms:$c(Ii.background.uniforms),vertexShader:Ii.background.vertexShader,fragmentShader:Ii.background.fragmentShader,side:Op,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=v,v.matrixAutoUpdate===!0&&v.updateMatrix(),l.material.uniforms.uvTransform.value.copy(v.matrix),(u!==v||h!==v.version||p!==n.toneMapping)&&(l.material.needsUpdate=!0,u=v,h=v.version,p=n.toneMapping),m.unshift(l,l.geometry,l.material,0,0,null))}function f(m,x){e.buffers.color.setClear(m.r,m.g,m.b,x,o)}return{getClearColor:function(){return s},setClearColor:function(m,x=1){s.set(m),a=x,f(s,a)},getClearAlpha:function(){return a},setClearAlpha:function(m){a=m,f(s,a)},render:d}}function Xrt(n,t,e,r){let i=n.getParameter(34921),o=r.isWebGL2?null:t.get("OES_vertex_array_object"),s=r.isWebGL2||o!==null,a={},l=m(null),c=l;function u(N,L,O,z,V){let $=!1;if(s){let X=f(z,O,L);c!==X&&(c=X,p(c.object)),$=x(z,V),$&&g(z,V)}else{let X=L.wireframe===!0;(c.geometry!==z.id||c.program!==O.id||c.wireframe!==X)&&(c.geometry=z.id,c.program=O.id,c.wireframe=X,$=!0)}N.isInstancedMesh===!0&&($=!0),V!==null&&e.update(V,34963),$&&(E(N,L,O,z),V!==null&&n.bindBuffer(34963,e.get(V).buffer))}function h(){return r.isWebGL2?n.createVertexArray():o.createVertexArrayOES()}function p(N){return r.isWebGL2?n.bindVertexArray(N):o.bindVertexArrayOES(N)}function d(N){return r.isWebGL2?n.deleteVertexArray(N):o.deleteVertexArrayOES(N)}function f(N,L,O){let z=O.wireframe===!0,V=a[N.id];V===void 0&&(V={},a[N.id]=V);let $=V[L.id];$===void 0&&($={},V[L.id]=$);let X=$[z];return X===void 0&&(X=m(h()),$[z]=X),X}function m(N){let L=[],O=[],z=[];for(let V=0;V=0){let Z=V[W];if(Z===void 0&&(W==="instanceMatrix"&&N.instanceMatrix&&(Z=N.instanceMatrix),W==="instanceColor"&&N.instanceColor&&(Z=N.instanceColor)),Z!==void 0){let Y=Z.normalized,tt=Z.itemSize,q=e.get(Z);if(q===void 0)continue;let et=q.buffer,rt=q.type,at=q.bytesPerElement;if(Z.isInterleavedBufferAttribute){let nt=Z.data,wt=nt.stride,vt=Z.offset;if(nt&&nt.isInstancedInterleavedBuffer){for(let it=0;it0&&n.getShaderPrecisionFormat(35632,36338).precision>0)return"highp";E="mediump"}return E==="mediump"&&n.getShaderPrecisionFormat(35633,36337).precision>0&&n.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}let s=typeof WebGL2RenderingContext!="undefined"&&n instanceof WebGL2RenderingContext||typeof WebGL2ComputeRenderingContext!="undefined"&&n instanceof WebGL2ComputeRenderingContext,a=e.precision!==void 0?e.precision:"highp",l=o(a);l!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",l,"instead."),a=l);let c=s||t.has("WEBGL_draw_buffers"),u=e.logarithmicDepthBuffer===!0,h=n.getParameter(34930),p=n.getParameter(35660),d=n.getParameter(3379),f=n.getParameter(34076),m=n.getParameter(34921),x=n.getParameter(36347),g=n.getParameter(36348),v=n.getParameter(36349),b=p>0,y=s||t.has("OES_texture_float"),_=b&&y,S=s?n.getParameter(36183):0;return{isWebGL2:s,drawBuffers:c,getMaxAnisotropy:i,getMaxPrecision:o,precision:a,logarithmicDepthBuffer:u,maxTextures:h,maxVertexTextures:p,maxTextureSize:d,maxCubemapSize:f,maxAttributes:m,maxVertexUniforms:x,maxVaryings:g,maxFragmentUniforms:v,vertexTextures:b,floatFragmentTextures:y,floatVertexTextures:_,maxSamples:S}}function Zrt(n){let t=this,e=null,r=0,i=!1,o=!1,s=new ni,a=new _n,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,p,d){let f=h.length!==0||p||r!==0||i;return i=p,e=u(h,d,0),r=h.length,f},this.beginShadows=function(){o=!0,u(null)},this.endShadows=function(){o=!1,c()},this.setState=function(h,p,d){let f=h.clippingPlanes,m=h.clipIntersection,x=h.clipShadows,g=n.get(h);if(!i||f===null||f.length===0||o&&!x)o?u(null):c();else{let v=o?0:r,b=v*4,y=g.clippingState||null;l.value=y,y=u(f,p,b,d);for(let _=0;_!==b;++_)y[_]=e[_];g.clippingState=y,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==e&&(l.value=e,l.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(h,p,d,f){let m=h!==null?h.length:0,x=null;if(m!==0){if(x=l.value,f!==!0||x===null){let g=d+m*4,v=p.matrixWorldInverse;a.getNormalMatrix(v),(x===null||x.length0){let c=new Yx(l.height/2);return c.fromEquirectangularTexture(n,s),t.set(s,c),s.addEventListener("dispose",i),e(c.texture,s.mapping)}else return null}}return s}function i(s){let a=s.target;a.removeEventListener("dispose",i);let l=t.get(a);l!==void 0&&(t.delete(a),l.dispose())}function o(){t=new WeakMap}return{get:r,dispose:o}}var Sa=class extends Wp{constructor(t=-1,e=1,r=1,i=-1,o=.1,s=2e3){super(),this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=r,this.bottom=i,this.near=o,this.far=s,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=t.view===null?null:Object.assign({},t.view),this}setViewOffset(t,e,r,i,o,s){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=r,this.view.offsetY=i,this.view.width=o,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2,o=r-t,s=r+t,a=i+e,l=i-e;if(this.view!==null&&this.view.enabled){let c=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;o+=c*this.view.offsetX,s=o+c*this.view.width,a-=u*this.view.offsetY,l=a-u*this.view.height}this.projectionMatrix.makeOrthographic(o,s,a,l,this.near,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){let e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,this.view!==null&&(e.object.view=Object.assign({},this.view)),e}};Sa.prototype.isOrthographicCamera=!0;var Gc=class extends ur{constructor(t){super(t),this.type="RawShaderMaterial"}};Gc.prototype.isRawShaderMaterial=!0;var Bc=4,as=8,Ai=Math.pow(2,as),Xz=[.125,.215,.35,.446,.526,.582],Kz=as-Bc+1+Xz.length,Ec=20,iS=new Sa,{_lodPlanes:Tp,_sizeLods:jD,_sigmas:Tx}=Qrt(),qD=new Pt,oS=null,va=(1+Math.sqrt(5))/2,Tc=1/va,XD=[new j(1,1,1),new j(-1,1,1),new j(1,1,-1),new j(-1,1,-1),new j(0,va,Tc),new j(0,va,-Tc),new j(Tc,0,va),new j(-Tc,0,va),new j(va,Tc,0),new j(-va,Tc,0)],Zx=class{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._blurMaterial=tit(Ec),this._equirectShader=null,this._cubemapShader=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,r=.1,i=100){oS=this._renderer.getRenderTarget();let o=this._allocateTargets();return this._sceneToCubeUV(t,r,i,o),e>0&&this._blur(o,0,0,e),this._applyPMREM(o),this._cleanup(o),o}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapShader===null&&(this._cubemapShader=ZD(),this._compileMaterial(this._cubemapShader))}compileEquirectangularShader(){this._equirectShader===null&&(this._equirectShader=YD(),this._compileMaterial(this._equirectShader))}dispose(){this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose(),this._cubemapShader!==null&&this._cubemapShader.dispose(),this._equirectShader!==null&&this._equirectShader.dispose();for(let t=0;t2?Ai:0,Ai,Ai),u.setRenderTarget(i),m&&u.render(f,a),u.render(t,a)}f.geometry.dispose(),f.material.dispose(),u.toneMapping=p,u.autoClear=h,t.background=x}_textureToCubeUV(t,e){let r=this._renderer,i=t.mapping===pd||t.mapping===dd;i?(this._cubemapShader===null&&(this._cubemapShader=ZD()),this._cubemapShader.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectShader===null&&(this._equirectShader=YD());let o=i?this._cubemapShader:this._equirectShader,s=new Ln(Tp[0],o),a=o.uniforms;a.envMap.value=t,i||a.texelSize.value.set(1/t.image.width,1/t.image.height),Ax(e,0,0,3*Ai,2*Ai),r.setRenderTarget(e),r.render(s,iS)}_applyPMREM(t){let e=this._renderer,r=e.autoClear;e.autoClear=!1;for(let i=1;iEc&&console.warn(`sigmaRadians, ${o}, is too large and will clip, as it requested ${x} samples when the maximum is set to ${Ec}`);let g=[],v=0;for(let S=0;Sas-Bc?i-as+Bc:0);Ax(e,y,_,3*b,2*b),l.setRenderTarget(e),l.render(h,iS)}};function Qrt(){let n=[],t=[],e=[],r=as;for(let i=0;ias-Bc?s=Xz[i-as+Bc-1]:i===0&&(s=0),e.push(s);let a=1/(o-1),l=-a/2,c=1+a/2,u=[l,l,c,l,c,c,l,l,c,c,l,c],h=6,p=6,d=3,f=2,m=1,x=new Float32Array(d*p*h),g=new Float32Array(f*p*h),v=new Float32Array(m*p*h);for(let y=0;y2?0:-1,E=[_,S,0,_+2/3,S,0,_+2/3,S+1,0,_,S,0,_+2/3,S+1,0,_,S+1,0];x.set(E,d*p*y),g.set(u,f*p*y);let M=[y,y,y,y,y,y];v.set(M,m*p*y)}let b=new _e;b.setAttribute("position",new se(x,d)),b.setAttribute("uv",new se(g,f)),b.setAttribute("faceIndex",new se(v,m)),n.push(b),r>Bc&&r--}return{_lodPlanes:n,_sizeLods:t,_sigmas:e}}function KD(n){let t=new Xn(3*Ai,3*Ai,n);return t.texture.mapping=bv,t.texture.name="PMREM.cubeUv",t.scissorTest=!0,t}function Ax(n,t,e,r,i){n.viewport.set(t,e,r,i),n.scissor.set(t,e,r,i)}function tit(n){let t=new Float32Array(n),e=new j(0,1,0);return new Gc({name:"SphericalGaussianBlur",defines:{n},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:t},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:e}},vertexShader:IC(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:rs,depthTest:!1,depthWrite:!1})}function YD(){let n=new Mt(1,1);return new Gc({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null},texelSize:{value:n}},vertexShader:IC(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform vec2 texelSize; + + #include + + void main() { + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + vec2 f = fract( uv / texelSize - 0.5 ); + uv -= f * texelSize; + vec3 tl = texture2D ( envMap, uv ).rgb; + uv.x += texelSize.x; + vec3 tr = texture2D ( envMap, uv ).rgb; + uv.y += texelSize.y; + vec3 br = texture2D ( envMap, uv ).rgb; + uv.x -= texelSize.x; + vec3 bl = texture2D ( envMap, uv ).rgb; + + vec3 tm = mix( tl, tr, f.x ); + vec3 bm = mix( bl, br, f.x ); + gl_FragColor.rgb = mix( tm, bm, f.y ); + + } + `,blending:rs,depthTest:!1,depthWrite:!1})}function ZD(){return new Gc({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:IC(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:rs,depthTest:!1,depthWrite:!1})}function IC(){return` + + precision mediump float; + precision mediump int; + + attribute vec3 position; + attribute vec2 uv; + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function eit(n){let t=new WeakMap,e=null;function r(a){if(a&&a.isTexture){let l=a.mapping,c=l===mS||l===gS,u=l===pd||l===dd;if(c||u)if(a.isRenderTargetTexture&&a.needsPMREMUpdate===!0){a.needsPMREMUpdate=!1;let h=t.get(a);return e===null&&(e=new Zx(n)),h=c?e.fromEquirectangular(a,h):e.fromCubemap(a,h),t.set(a,h),h.texture}else{if(t.has(a))return t.get(a).texture;{let h=a.image;if(c&&h&&h.height>0||u&&h&&i(h)){e===null&&(e=new Zx(n));let p=c?e.fromEquirectangular(a):e.fromCubemap(a);return t.set(a,p),a.addEventListener("dispose",o),p.texture}else return null}}}return a}function i(a){let l=0,c=6;for(let u=0;ut.maxTextureSize&&(M=Math.ceil(E/t.maxTextureSize),E=t.maxTextureSize);let P=new Float32Array(E*M*4*f),D=new qp(P,E,M,f);D.format=nr,D.type=ya,D.needsUpdate=!0;let w=S*4;for(let N=0;N0)return n;let i=t*e,o=QD[i];if(o===void 0&&(o=new Float32Array(i),QD[i]=o),t!==0){r.toArray(o,0);for(let s=1,a=0;s!==t;++s)a+=e,n[s].toArray(o,a)}return o}function rr(n,t){if(n.length!==t.length)return!1;for(let e=0,r=n.length;e/gm;function SS(n){return n.replace(sot,aot)}function aot(n,t){let e=ue[t];if(e===void 0)throw new Error("Can not resolve #include <"+t+">");return SS(e)}var lot=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,cot=/#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 cz(n){return n.replace(cot,nF).replace(lot,uot)}function uot(n,t,e,r){return console.warn("WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead."),nF(n,t,e,r)}function nF(n,t,e,r){let i="";for(let o=parseInt(t);o0&&(m+=` +`),x=[p,d].filter(Lp).join(` +`),x.length>0&&(x+=` +`)):(m=[uz(e),"#define SHADER_NAME "+e.shaderName,d,e.instancing?"#define USE_INSTANCING":"",e.instancingColor?"#define USE_INSTANCING_COLOR":"",e.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define MAX_BONES "+e.maxBones,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+u:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMap&&e.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",e.normalMap&&e.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.displacementMap&&e.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",e.specularColorMap?"#define USE_SPECULARCOLORMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.sheenColorMap?"#define USE_SHEENCOLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",e.vertexTangents?"#define USE_TANGENT":"",e.vertexColors?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUvs?"#define USE_UV":"",e.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",e.flatShading?"#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.useVertexTexture?"#define BONE_TEXTURE":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&e.flatShading===!1?"#define USE_MORPHNORMALS":"",e.morphTargets&&e.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",e.morphTargets&&e.isWebGL2?"#define MORPHTARGETS_COUNT "+e.morphTargetsCount:"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",e.logarithmicDepthBuffer&&e.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(Lp).join(` +`),x=[p,uz(e),"#define SHADER_NAME "+e.shaderName,d,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.matcap?"#define USE_MATCAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+c:"",e.envMap?"#define "+u:"",e.envMap?"#define "+h:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMap&&e.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",e.normalMap&&e.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",e.clearcoat?"#define USE_CLEARCOAT":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",e.specularColorMap?"#define USE_SPECULARCOLORMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaTest?"#define USE_ALPHATEST":"",e.sheen?"#define USE_SHEEN":"",e.sheenColorMap?"#define USE_SHEENCOLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",e.vertexTangents?"#define USE_TANGENT":"",e.vertexColors||e.instancingColor?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUvs?"#define USE_UV":"",e.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",e.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",e.logarithmicDepthBuffer&&e.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"",(e.extensionShaderTextureLOD||e.envMap)&&e.rendererExtensionShaderTextureLod?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",e.toneMapping!==os?"#define TONE_MAPPING":"",e.toneMapping!==os?ue.tonemapping_pars_fragment:"",e.toneMapping!==os?not("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.alphaWrite?"":"#define OPAQUE",ue.encodings_pars_fragment,eot("linearToOutputTexel",e.outputEncoding),e.depthPacking?"#define DEPTH_PACKING "+e.depthPacking:"",` +`].filter(Lp).join(` +`)),s=SS(s),s=az(s,e),s=lz(s,e),a=SS(a),a=az(a,e),a=lz(a,e),s=cz(s),a=cz(a),e.isWebGL2&&e.isRawShaderMaterial!==!0&&(g=`#version 300 es +`,m=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+m,x=["#define varying in",e.glslVersion===ND?"":"layout(location = 0) out highp vec4 pc_fragColor;",e.glslVersion===ND?"":"#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(` +`)+` +`+x);let v=g+m+s,b=g+x+a,y=oz(i,35633,v),_=oz(i,35632,b);if(i.attachShader(f,y),i.attachShader(f,_),e.index0AttributeName!==void 0?i.bindAttribLocation(f,0,e.index0AttributeName):e.morphTargets===!0&&i.bindAttribLocation(f,0,"position"),i.linkProgram(f),n.debug.checkShaderErrors){let M=i.getProgramInfoLog(f).trim(),P=i.getShaderInfoLog(y).trim(),D=i.getShaderInfoLog(_).trim(),w=!0,I=!0;if(i.getProgramParameter(f,35714)===!1){w=!1;let N=sz(i,y,"vertex"),L=sz(i,_,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(f,35715)+` + +Program Info Log: `+M+` +`+N+` +`+L)}else M!==""?console.warn("THREE.WebGLProgram: Program Info Log:",M):(P===""||D==="")&&(I=!1);I&&(this.diagnostics={runnable:w,programLog:M,vertexShader:{log:P,prefix:m},fragmentShader:{log:D,prefix:x}})}i.deleteShader(y),i.deleteShader(_);let S;this.getUniforms=function(){return S===void 0&&(S=new ls(i,f)),S};let E;return this.getAttributes=function(){return E===void 0&&(E=oot(i,f)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(f),this.program=void 0},this.name=e.shaderName,this.id=Jit++,this.cacheKey=t,this.usedTimes=1,this.program=f,this.vertexShader=y,this.fragmentShader=_,this}var got=0,CS=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){let e=t.vertexShader,r=t.fragmentShader,i=this._getShaderStage(e),o=this._getShaderStage(r),s=this._getShaderCacheForMaterial(t);return s.has(i)===!1&&(s.add(i),i.usedTimes++),s.has(o)===!1&&(s.add(o),o.usedTimes++),this}remove(t){let e=this.materialCache.get(t);for(let r of e)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){let e=this.materialCache;return e.has(t)===!1&&e.set(t,new Set),e.get(t)}_getShaderStage(t){let e=this.shaderCache;if(e.has(t)===!1){let r=new MS;e.set(t,r)}return e.get(t)}},MS=class{constructor(){this.id=got++,this.usedTimes=0}};function xot(n,t,e,r,i,o,s){let a=new qx,l=new CS,c=[],u=i.isWebGL2,h=i.logarithmicDepthBuffer,p=i.floatVertexTextures,d=i.maxVertexUniforms,f=i.vertexTextures,m=i.precision,x={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(w){let N=w.skeleton.bones;if(p)return 1024;{let O=Math.floor((d-20)/4),z=Math.min(O,N.length);return z0,rt=w.clearcoat>0;return{isWebGL2:u,shaderID:X,shaderName:w.type,vertexShader:K,fragmentShader:Z,defines:w.defines,customVertexShaderID:Y,customFragmentShaderID:tt,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:m,instancing:O.isInstancedMesh===!0,instancingColor:O.isInstancedMesh===!0&&O.instanceColor!==null,supportsVertexTextures:f,outputEncoding:q===null?n.outputEncoding:q.isXRRenderTarget===!0?q.texture.encoding:cs,map:!!w.map,matcap:!!w.matcap,envMap:!!$,envMapMode:$&&$.mapping,envMapCubeUV:!!$&&($.mapping===bv||$.mapping===TC),lightMap:!!w.lightMap,aoMap:!!w.aoMap,emissiveMap:!!w.emissiveMap,bumpMap:!!w.bumpMap,normalMap:!!w.normalMap,objectSpaceNormalMap:w.normalMapType===Jtt,tangentSpaceNormalMap:w.normalMapType===Jc,decodeVideoTexture:!!w.map&&w.map.isVideoTexture===!0&&w.map.encoding===He,clearcoat:rt,clearcoatMap:rt&&!!w.clearcoatMap,clearcoatRoughnessMap:rt&&!!w.clearcoatRoughnessMap,clearcoatNormalMap:rt&&!!w.clearcoatNormalMap,displacementMap:!!w.displacementMap,roughnessMap:!!w.roughnessMap,metalnessMap:!!w.metalnessMap,specularMap:!!w.specularMap,specularIntensityMap:!!w.specularIntensityMap,specularColorMap:!!w.specularColorMap,alphaMap:!!w.alphaMap,alphaTest:et,alphaWrite:w.alphaWrite||w.transparent,gradientMap:!!w.gradientMap,sheen:w.sheen>0,sheenColorMap:!!w.sheenColorMap,sheenRoughnessMap:!!w.sheenRoughnessMap,transmission:w.transmission>0,transmissionMap:!!w.transmissionMap,thicknessMap:!!w.thicknessMap,combine:w.combine,vertexTangents:!!w.normalMap&&!!O.geometry&&!!O.geometry.attributes.tangent,vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!O.geometry&&!!O.geometry.attributes.color&&O.geometry.attributes.color.itemSize===4,vertexUvs:!!w.map||!!w.bumpMap||!!w.normalMap||!!w.specularMap||!!w.alphaMap||!!w.emissiveMap||!!w.roughnessMap||!!w.metalnessMap||!!w.clearcoatMap||!!w.clearcoatRoughnessMap||!!w.clearcoatNormalMap||!!w.displacementMap||!!w.transmissionMap||!!w.thicknessMap||!!w.specularIntensityMap||!!w.specularColorMap||!!w.sheenColorMap||!!w.sheenRoughnessMap,uvsVertexOnly:!(!!w.map||!!w.bumpMap||!!w.normalMap||!!w.specularMap||!!w.alphaMap||!!w.emissiveMap||!!w.roughnessMap||!!w.metalnessMap||!!w.clearcoatNormalMap||w.transmission>0||!!w.transmissionMap||!!w.thicknessMap||!!w.specularIntensityMap||!!w.specularColorMap||w.sheen>0||!!w.sheenColorMap||!!w.sheenRoughnessMap)&&!!w.displacementMap,fog:!!z,useFog:w.fog,fogExp2:z&&z.isFogExp2,flatShading:!!w.flatShading,sizeAttenuation:w.sizeAttenuation,logarithmicDepthBuffer:h,skinning:O.isSkinnedMesh===!0&&W>0,maxBones:W,useVertexTexture:p,morphTargets:!!O.geometry&&!!O.geometry.morphAttributes.position,morphNormals:!!O.geometry&&!!O.geometry.morphAttributes.normal,morphTargetsCount:!!O.geometry&&!!O.geometry.morphAttributes.position?O.geometry.morphAttributes.position.length:0,numDirLights:I.directional.length,numPointLights:I.point.length,numSpotLights:I.spot.length,numRectAreaLights:I.rectArea.length,numHemiLights:I.hemi.length,numDirLightShadows:I.directionalShadowMap.length,numPointLightShadows:I.pointShadowMap.length,numSpotLightShadows:I.spotShadowMap.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:w.dithering,shadowMapEnabled:n.shadowMap.enabled&&N.length>0,shadowMapType:n.shadowMap.type,toneMapping:w.toneMapped?n.toneMapping:os,physicallyCorrectLights:n.physicallyCorrectLights,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===Vc,flipSided:w.side===yn,depthPacking:w.depthPacking!==void 0?w.depthPacking:!1,index0AttributeName:w.index0AttributeName,extensionDerivatives:w.extensions&&w.extensions.derivatives,extensionFragDepth:w.extensions&&w.extensions.fragDepth,extensionDrawBuffers:w.extensions&&w.extensions.drawBuffers,extensionShaderTextureLOD:w.extensions&&w.extensions.shaderTextureLOD,rendererExtensionFragDepth:u||r.has("EXT_frag_depth"),rendererExtensionDrawBuffers:u||r.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:u||r.has("EXT_shader_texture_lod"),customProgramCacheKey:w.customProgramCacheKey()}}function b(w){let I=[];if(w.shaderID?I.push(w.shaderID):(I.push(w.customVertexShaderID),I.push(w.customFragmentShaderID)),w.defines!==void 0)for(let N in w.defines)I.push(N),I.push(w.defines[N]);return w.isRawShaderMaterial===!1&&(y(I,w),_(I,w),I.push(n.outputEncoding)),I.push(w.customProgramCacheKey),I.join()}function y(w,I){w.push(I.precision),w.push(I.outputEncoding),w.push(I.envMapMode),w.push(I.combine),w.push(I.vertexUvs),w.push(I.fogExp2),w.push(I.sizeAttenuation),w.push(I.maxBones),w.push(I.morphTargetsCount),w.push(I.numDirLights),w.push(I.numPointLights),w.push(I.numSpotLights),w.push(I.numHemiLights),w.push(I.numRectAreaLights),w.push(I.numDirLightShadows),w.push(I.numPointLightShadows),w.push(I.numSpotLightShadows),w.push(I.shadowMapType),w.push(I.toneMapping),w.push(I.numClippingPlanes),w.push(I.numClipIntersection),w.push(I.alphaWrite)}function _(w,I){a.disableAll(),I.isWebGL2&&a.enable(0),I.supportsVertexTextures&&a.enable(1),I.instancing&&a.enable(2),I.instancingColor&&a.enable(3),I.map&&a.enable(4),I.matcap&&a.enable(5),I.envMap&&a.enable(6),I.envMapCubeUV&&a.enable(7),I.lightMap&&a.enable(8),I.aoMap&&a.enable(9),I.emissiveMap&&a.enable(10),I.bumpMap&&a.enable(11),I.normalMap&&a.enable(12),I.objectSpaceNormalMap&&a.enable(13),I.tangentSpaceNormalMap&&a.enable(14),I.clearcoat&&a.enable(15),I.clearcoatMap&&a.enable(16),I.clearcoatRoughnessMap&&a.enable(17),I.clearcoatNormalMap&&a.enable(18),I.displacementMap&&a.enable(19),I.specularMap&&a.enable(20),I.roughnessMap&&a.enable(21),I.metalnessMap&&a.enable(22),I.gradientMap&&a.enable(23),I.alphaMap&&a.enable(24),I.alphaTest&&a.enable(25),I.vertexColors&&a.enable(26),I.vertexAlphas&&a.enable(27),I.vertexUvs&&a.enable(28),I.vertexTangents&&a.enable(29),I.uvsVertexOnly&&a.enable(30),I.fog&&a.enable(31),w.push(a.mask),a.disableAll(),I.useFog&&a.enable(0),I.flatShading&&a.enable(1),I.logarithmicDepthBuffer&&a.enable(2),I.skinning&&a.enable(3),I.useVertexTexture&&a.enable(4),I.morphTargets&&a.enable(5),I.morphNormals&&a.enable(6),I.premultipliedAlpha&&a.enable(7),I.shadowMapEnabled&&a.enable(8),I.physicallyCorrectLights&&a.enable(9),I.doubleSided&&a.enable(10),I.flipSided&&a.enable(11),I.depthPacking&&a.enable(12),I.dithering&&a.enable(13),I.specularIntensityMap&&a.enable(14),I.specularColorMap&&a.enable(15),I.transmission&&a.enable(16),I.transmissionMap&&a.enable(17),I.thicknessMap&&a.enable(18),I.sheen&&a.enable(19),I.sheenColorMap&&a.enable(20),I.sheenRoughnessMap&&a.enable(21),I.decodeVideoTexture&&a.enable(22),w.push(a.mask)}function S(w){let I=x[w.type],N;if(I){let L=Ii[I];N=fet.clone(L.uniforms)}else N=w.uniforms;return N}function E(w,I){let N;for(let L=0,O=c.length;L0?r.push(g):d.transparent===!0?i.push(g):e.push(g)}function l(h,p,d,f,m,x){let g=s(h,p,d,f,m,x);d.transmission>0?r.unshift(g):d.transparent===!0?i.unshift(g):e.unshift(g)}function c(h,p){e.length>1&&e.sort(h||yot),r.length>1&&r.sort(p||hz),i.length>1&&i.sort(p||hz)}function u(){for(let h=t,p=n.length;h=n.get(r).length?(o=new pz,n.get(r).push(o)):o=n.get(r)[i],o}function e(){n=new WeakMap}return{get:t,dispose:e}}function _ot(){let n={};return{get:function(t){if(n[t.id]!==void 0)return n[t.id];let e;switch(t.type){case"DirectionalLight":e={direction:new j,color:new Pt};break;case"SpotLight":e={position:new j,direction:new j,color:new Pt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":e={position:new j,color:new Pt,distance:0,decay:0};break;case"HemisphereLight":e={direction:new j,skyColor:new Pt,groundColor:new Pt};break;case"RectAreaLight":e={color:new Pt,position:new j,halfWidth:new j,halfHeight:new j};break}return n[t.id]=e,e}}}function wot(){let n={};return{get:function(t){if(n[t.id]!==void 0)return n[t.id];let e;switch(t.type){case"DirectionalLight":e={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Mt};break;case"SpotLight":e={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Mt};break;case"PointLight":e={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Mt,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[t.id]=e,e}}}var Sot=0;function Cot(n,t){return(t.castShadow?1:0)-(n.castShadow?1:0)}function Mot(n,t){let e=new _ot,r=wot(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadow:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};for(let u=0;u<9;u++)i.probe.push(new j);let o=new j,s=new Qt,a=new Qt;function l(u,h){let p=0,d=0,f=0;for(let P=0;P<9;P++)i.probe[P].set(0,0,0);let m=0,x=0,g=0,v=0,b=0,y=0,_=0,S=0;u.sort(Cot);let E=h!==!0?Math.PI:1;for(let P=0,D=u.length;P0&&(t.isWebGL2||n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Nt.LTC_FLOAT_1,i.rectAreaLTC2=Nt.LTC_FLOAT_2):n.has("OES_texture_half_float_linear")===!0?(i.rectAreaLTC1=Nt.LTC_HALF_1,i.rectAreaLTC2=Nt.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),i.ambient[0]=p,i.ambient[1]=d,i.ambient[2]=f;let M=i.hash;(M.directionalLength!==m||M.pointLength!==x||M.spotLength!==g||M.rectAreaLength!==v||M.hemiLength!==b||M.numDirectionalShadows!==y||M.numPointShadows!==_||M.numSpotShadows!==S)&&(i.directional.length=m,i.spot.length=g,i.rectArea.length=v,i.point.length=x,i.hemi.length=b,i.directionalShadow.length=y,i.directionalShadowMap.length=y,i.pointShadow.length=_,i.pointShadowMap.length=_,i.spotShadow.length=S,i.spotShadowMap.length=S,i.directionalShadowMatrix.length=y,i.pointShadowMatrix.length=_,i.spotShadowMatrix.length=S,M.directionalLength=m,M.pointLength=x,M.spotLength=g,M.rectAreaLength=v,M.hemiLength=b,M.numDirectionalShadows=y,M.numPointShadows=_,M.numSpotShadows=S,i.version=Sot++)}function c(u,h){let p=0,d=0,f=0,m=0,x=0,g=h.matrixWorldInverse;for(let v=0,b=u.length;v=e.get(o).length?(a=new dz(n,t),e.get(o).push(a)):a=e.get(o)[s],a}function i(){e=new WeakMap}return{get:r,dispose:i}}var Qx=class extends Dn{constructor(t){super(),this.type="MeshDepthMaterial",this.depthPacking=Ytt,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}};Qx.prototype.isMeshDepthMaterial=!0;var tv=class extends Dn{constructor(t){super(),this.type="MeshDistanceMaterial",this.referencePosition=new j,this.nearDistance=1,this.farDistance=1e3,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.fog=!1,this.setValues(t)}copy(t){return super.copy(t),this.referencePosition.copy(t.referencePosition),this.nearDistance=t.nearDistance,this.farDistance=t.farDistance,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}};tv.prototype.isMeshDistanceMaterial=!0;var Tot=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,Aot=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function rF(n,t,e){let r=new Wc,i=new Mt,o=new Mt,s=new Re,a=new Qx({depthPacking:Ztt}),l=new tv,c={},u=e.maxTextureSize,h={0:yn,1:Op,2:Vc},p=new ur({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Mt},radius:{value:4}},vertexShader:Tot,fragmentShader:Aot}),d=p.clone();d.defines.HORIZONTAL_PASS=1;let f=new _e;f.setAttribute("position",new se(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let m=new Ln(f,p),x=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Bz,this.render=function(y,_,S){if(x.enabled===!1||x.autoUpdate===!1&&x.needsUpdate===!1||y.length===0)return;let E=n.getRenderTarget(),M=n.getActiveCubeFace(),P=n.getActiveMipmapLevel(),D=n.state;D.setBlending(rs),D.buffers.color.setClear(1,1,1,1),D.buffers.depth.setTest(!0),D.setScissorTest(!1);for(let w=0,I=y.length;wu||i.y>u)&&(i.x>u&&(o.x=Math.floor(u/O.x),i.x=o.x*O.x,L.mapSize.x=o.x),i.y>u&&(o.y=Math.floor(u/O.y),i.y=o.y*O.y,L.mapSize.y=o.y)),L.map===null&&!L.isPointLightShadow&&this.type===Np){let V={minFilter:dn,magFilter:dn,format:nr};L.map=new Xn(i.x,i.y,V),L.map.texture.name=N.name+".shadowMap",L.mapPass=new Xn(i.x,i.y,V),L.camera.updateProjectionMatrix()}if(L.map===null){let V={minFilter:bn,magFilter:bn,format:nr};L.map=new Xn(i.x,i.y,V),L.map.texture.name=N.name+".shadowMap",L.camera.updateProjectionMatrix()}n.setRenderTarget(L.map),n.clear();let z=L.getViewportCount();for(let V=0;V0){let N=w.uuid,L=S.uuid,O=c[N];O===void 0&&(O={},c[N]=O);let z=O[L];z===void 0&&(z=w.clone(),O[L]=z),w=z}return w.visible=S.visible,w.wireframe=S.wireframe,D===Np?w.side=S.shadowSide!==null?S.shadowSide:S.side:w.side=S.shadowSide!==null?S.shadowSide:h[S.side],w.alphaMap=S.alphaMap,w.alphaTest=S.alphaTest,w.clipShadows=S.clipShadows,w.clippingPlanes=S.clippingPlanes,w.clipIntersection=S.clipIntersection,w.displacementMap=S.displacementMap,w.displacementScale=S.displacementScale,w.displacementBias=S.displacementBias,w.wireframeLinewidth=S.wireframeLinewidth,w.linewidth=S.linewidth,E.isPointLight===!0&&w.isMeshDistanceMaterial===!0&&(w.referencePosition.setFromMatrixPosition(E.matrixWorld),w.nearDistance=M,w.farDistance=P),w}function b(y,_,S,E,M){if(y.visible===!1)return;if(y.layers.test(_.layers)&&(y.isMesh||y.isLine||y.isPoints)&&(y.castShadow||y.receiveShadow&&M===Np)&&(!y.frustumCulled||r.intersectsObject(y))){y.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,y.matrixWorld);let w=t.update(y),I=y.material;if(Array.isArray(I)){let N=w.groups;for(let L=0,O=N.length;L=1):z.indexOf("OpenGL ES")!==-1&&(O=parseFloat(/^OpenGL ES (\d)/.exec(z)[1]),L=O>=2);let V=null,$={},X=n.getParameter(3088),W=n.getParameter(2978),K=new Re().fromArray(X),Z=new Re().fromArray(W);function Y(Q,Vt,zt){let ee=new Uint8Array(4),xt=n.createTexture();n.bindTexture(Q,xt),n.texParameteri(Q,10241,9728),n.texParameteri(Q,10240,9728);for(let jt=0;jtkt||G.height>kt)&&(Bt=kt/Math.max(G.width,G.height)),Bt<1||H===!0)if(typeof HTMLImageElement!="undefined"&&G instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&G instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&G instanceof ImageBitmap){let ft=H?eet:Math.floor,Ht=ft(Bt*G.width),J=ft(Bt*G.height);m===void 0&&(m=g(Ht,J));let mt=ht?g(Ht,J):m;return mt.width=Ht,mt.height=J,mt.getContext("2d").drawImage(G,0,0,Ht,J),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+G.width+"x"+G.height+") to ("+Ht+"x"+J+")."),mt}else return"data"in G&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+G.width+"x"+G.height+")."),G;return G}function b(G){return LD(G.width)&&LD(G.height)}function y(G){return a?!1:G.wrapS!==_r||G.wrapT!==_r||G.minFilter!==bn&&G.minFilter!==dn}function _(G,H){return G.generateMipmaps&&H&&G.minFilter!==bn&&G.minFilter!==dn}function S(G){n.generateMipmap(G)}function E(G,H,ht,kt,Bt=!1){if(a===!1)return H;if(G!==null){if(n[G]!==void 0)return n[G];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+G+"'")}let ft=H;return H===6403&&(ht===5126&&(ft=33326),ht===5131&&(ft=33325),ht===5121&&(ft=33321)),H===33319&&(ht===5126&&(ft=33328),ht===5131&&(ft=33327),ht===5121&&(ft=33323)),H===6408&&(ht===5126&&(ft=34836),ht===5131&&(ft=34842),ht===5121&&(ft=kt===He&&Bt===!1?35907:32856),ht===32819&&(ft=32854),ht===32820&&(ft=32855)),(ft===33325||ft===33326||ft===33327||ft===33328||ft===34842||ft===34836)&&t.get("EXT_color_buffer_float"),ft}function M(G,H,ht){return _(G,ht)===!0||G.isFramebufferTexture&&G.minFilter!==bn&&G.minFilter!==dn?Math.log2(Math.max(H.width,H.height))+1:G.mipmaps!==void 0&&G.mipmaps.length>0?G.mipmaps.length:G.isCompressedTexture&&Array.isArray(G.image)?H.mipmaps.length:1}function P(G){return G===bn||G===uD||G===hD?9728:9729}function D(G){let H=G.target;H.removeEventListener("dispose",D),I(H),H.isVideoTexture&&f.delete(H),s.memory.textures--}function w(G){let H=G.target;H.removeEventListener("dispose",w),N(H)}function I(G){let H=r.get(G);H.__webglInit!==void 0&&(n.deleteTexture(H.__webglTexture),r.remove(G))}function N(G){let H=G.texture,ht=r.get(G),kt=r.get(H);if(!!G){if(kt.__webglTexture!==void 0&&(n.deleteTexture(kt.__webglTexture),s.memory.textures--),G.depthTexture&&G.depthTexture.dispose(),G.isWebGLCubeRenderTarget)for(let Bt=0;Bt<6;Bt++)n.deleteFramebuffer(ht.__webglFramebuffer[Bt]),ht.__webglDepthbuffer&&n.deleteRenderbuffer(ht.__webglDepthbuffer[Bt]);else n.deleteFramebuffer(ht.__webglFramebuffer),ht.__webglDepthbuffer&&n.deleteRenderbuffer(ht.__webglDepthbuffer),ht.__webglMultisampledFramebuffer&&n.deleteFramebuffer(ht.__webglMultisampledFramebuffer),ht.__webglColorRenderbuffer&&n.deleteRenderbuffer(ht.__webglColorRenderbuffer),ht.__webglDepthRenderbuffer&&n.deleteRenderbuffer(ht.__webglDepthRenderbuffer);if(G.isWebGLMultipleRenderTargets)for(let Bt=0,ft=H.length;Bt=l&&console.warn("THREE.WebGLTextures: Trying to use "+G+" texture units while this GPU supports only "+l),L+=1,G}function V(G,H){let ht=r.get(G);if(G.isVideoTexture&>(G),G.version>0&&ht.__version!==G.version){let kt=G.image;if(kt===void 0)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined");else if(kt.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{q(ht,G,H);return}}e.activeTexture(33984+H),e.bindTexture(3553,ht.__webglTexture)}function $(G,H){let ht=r.get(G);if(G.version>0&&ht.__version!==G.version){q(ht,G,H);return}e.activeTexture(33984+H),e.bindTexture(35866,ht.__webglTexture)}function X(G,H){let ht=r.get(G);if(G.version>0&&ht.__version!==G.version){q(ht,G,H);return}e.activeTexture(33984+H),e.bindTexture(32879,ht.__webglTexture)}function W(G,H){let ht=r.get(G);if(G.version>0&&ht.__version!==G.version){et(ht,G,H);return}e.activeTexture(33984+H),e.bindTexture(34067,ht.__webglTexture)}let K={[xS]:10497,[_r]:33071,[vS]:33648},Z={[bn]:9728,[uD]:9984,[hD]:9986,[dn]:9729,[Rtt]:9985,[_v]:9987};function Y(G,H,ht){if(ht?(n.texParameteri(G,10242,K[H.wrapS]),n.texParameteri(G,10243,K[H.wrapT]),(G===32879||G===35866)&&n.texParameteri(G,32882,K[H.wrapR]),n.texParameteri(G,10240,Z[H.magFilter]),n.texParameteri(G,10241,Z[H.minFilter])):(n.texParameteri(G,10242,33071),n.texParameteri(G,10243,33071),(G===32879||G===35866)&&n.texParameteri(G,32882,33071),(H.wrapS!==_r||H.wrapT!==_r)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),n.texParameteri(G,10240,P(H.magFilter)),n.texParameteri(G,10241,P(H.minFilter)),H.minFilter!==bn&&H.minFilter!==dn&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),t.has("EXT_texture_filter_anisotropic")===!0){let kt=t.get("EXT_texture_filter_anisotropic");if(H.type===ya&&t.has("OES_texture_float_linear")===!1||a===!1&&H.type===zc&&t.has("OES_texture_half_float_linear")===!1)return;(H.anisotropy>1||r.get(H).__currentAnisotropy)&&(n.texParameterf(G,kt.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(H.anisotropy,i.getMaxAnisotropy())),r.get(H).__currentAnisotropy=H.anisotropy)}}function tt(G,H){G.__webglInit===void 0&&(G.__webglInit=!0,H.addEventListener("dispose",D),G.__webglTexture=n.createTexture(),s.memory.textures++)}function q(G,H,ht){let kt=3553;H.isDataTexture2DArray&&(kt=35866),H.isDataTexture3D&&(kt=32879),tt(G,H),e.activeTexture(33984+ht),e.bindTexture(kt,G.__webglTexture),n.pixelStorei(37440,H.flipY),n.pixelStorei(37441,H.premultiplyAlpha),n.pixelStorei(3317,H.unpackAlignment),n.pixelStorei(37443,0);let Bt=y(H)&&b(H.image)===!1,ft=v(H.image,Bt,!1,u);ft=Rt(H,ft);let Ht=b(ft)||a,J=o.convert(H.format,H.encoding),mt=o.convert(H.type),It=E(H.internalFormat,J,mt,H.encoding,H.isVideoTexture);Y(kt,H,Ht);let Wt,Q=H.mipmaps,Vt=a&&H.isVideoTexture!==!0,zt=G.__version===void 0,ee=M(H,ft,Ht);if(H.isDepthTexture)It=6402,a?H.type===ya?It=36012:H.type===$x?It=33190:H.type===Fc?It=35056:It=33189:H.type===ya&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),H.format===_a&&It===6402&&H.type!==Bp&&H.type!==$x&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),H.type=Bp,mt=o.convert(H.type)),H.format===Hc&&It===6402&&(It=34041,H.type!==Fc&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),H.type=Fc,mt=o.convert(H.type))),Vt&&zt?e.texStorage2D(3553,1,It,ft.width,ft.height):e.texImage2D(3553,0,It,ft.width,ft.height,0,J,mt,null);else if(H.isDataTexture)if(Q.length>0&&Ht){Vt&&zt&&e.texStorage2D(3553,ee,It,Q[0].width,Q[0].height);for(let xt=0,jt=Q.length;xt0&&Ht){Vt&&zt&&e.texStorage2D(3553,ee,It,Q[0].width,Q[0].height);for(let xt=0,jt=Q.length;xt0&&zt++,e.texStorage2D(34067,zt,Wt,ft[0].width,ft[0].height));for(let xt=0;xt<6;xt++)if(Bt){Q?e.texSubImage2D(34069+xt,0,0,0,ft[xt].width,ft[xt].height,mt,It,ft[xt].data):e.texImage2D(34069+xt,0,Wt,ft[xt].width,ft[xt].height,0,mt,It,ft[xt].data);for(let jt=0;jtd+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!c.inputState.pinching&&p<=d-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else l!==null&&t.gripSpace&&(o=e.getPose(t.gripSpace,r),o!==null&&(l.matrix.fromArray(o.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),o.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(o.linearVelocity)):l.hasLinearVelocity=!1,o.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(o.angularVelocity)):l.hasAngularVelocity=!1));return a!==null&&(a.visible=i!==null),l!==null&&(l.visible=o!==null),c!==null&&(c.visible=s!==null),this}},Xp=class extends Qe{constructor(t,e,r,i,o,s,a,l,c,u){if(u=u!==void 0?u:_a,u!==_a&&u!==Hc)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");r===void 0&&u===_a&&(r=Bp),r===void 0&&u===Hc&&(r=Fc),super(null,i,o,s,a,l,u,r,c),this.image={width:t,height:e},this.magFilter=a!==void 0?a:bn,this.minFilter=l!==void 0?l:bn,this.flipY=!1,this.generateMipmaps=!1}};Xp.prototype.isDepthTexture=!0;var ES=class extends ii{constructor(t,e){super();let r=this,i=null,o=1,s=null,a="local-floor",l=t.extensions.has("WEBGL_multisampled_render_to_texture"),c=null,u=null,h=null,p=null,d=!1,f=null,m=e.getContextAttributes(),x=null,g=null,v=[],b=new Map,y=new ln;y.layers.enable(1),y.viewport=new Re;let _=new ln;_.layers.enable(2),_.viewport=new Re;let S=[y,_],E=new ev;E.layers.enable(1),E.layers.enable(2);let M=null,P=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(W){let K=v[W];return K===void 0&&(K=new Dp,v[W]=K),K.getTargetRaySpace()},this.getControllerGrip=function(W){let K=v[W];return K===void 0&&(K=new Dp,v[W]=K),K.getGripSpace()},this.getHand=function(W){let K=v[W];return K===void 0&&(K=new Dp,v[W]=K),K.getHandSpace()};function D(W){let K=b.get(W.inputSource);K&&K.dispatchEvent({type:W.type,data:W.inputSource})}function w(){b.forEach(function(W,K){W.disconnect(K)}),b.clear(),M=null,P=null,t.setRenderTarget(x),p=null,h=null,u=null,i=null,g=null,X.stop(),r.isPresenting=!1,r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(W){o=W,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(W){a=W,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return s},this.getBaseLayer=function(){return h!==null?h:p},this.getBinding=function(){return u},this.getFrame=function(){return f},this.getSession=function(){return i},this.setSession=function(W){return Jt(this,null,function*(){if(i=W,i!==null){if(x=t.getRenderTarget(),i.addEventListener("select",D),i.addEventListener("selectstart",D),i.addEventListener("selectend",D),i.addEventListener("squeeze",D),i.addEventListener("squeezestart",D),i.addEventListener("squeezeend",D),i.addEventListener("end",w),i.addEventListener("inputsourceschange",I),m.xrCompatible!==!0&&(yield e.makeXRCompatible()),i.renderState.layers===void 0||t.capabilities.isWebGL2===!1){let K={antialias:i.renderState.layers===void 0?m.antialias:!0,alpha:m.alpha,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:o};p=new XRWebGLLayer(i,e,K),i.updateRenderState({baseLayer:p}),g=new Xn(p.framebufferWidth,p.framebufferHeight,{format:nr,type:ss,encoding:t.outputEncoding})}else{d=m.antialias;let K=null,Z=null,Y=null;m.depth&&(Y=m.stencil?35056:33190,K=m.stencil?Hc:_a,Z=m.stencil?Fc:Bp);let tt={colorFormat:t.outputEncoding===He?35907:32856,depthFormat:Y,scaleFactor:o};u=new XRWebGLBinding(i,e),h=u.createProjectionLayer(tt),i.updateRenderState({layers:[h]}),d?g=new $p(h.textureWidth,h.textureHeight,{format:nr,type:ss,depthTexture:new Xp(h.textureWidth,h.textureHeight,Z,void 0,void 0,void 0,void 0,void 0,void 0,K),stencilBuffer:m.stencil,ignoreDepth:h.ignoreDepthValues,useRenderToTexture:l,encoding:t.outputEncoding}):g=new Xn(h.textureWidth,h.textureHeight,{format:nr,type:ss,depthTexture:new Xp(h.textureWidth,h.textureHeight,Z,void 0,void 0,void 0,void 0,void 0,void 0,K),stencilBuffer:m.stencil,ignoreDepth:h.ignoreDepthValues,encoding:t.outputEncoding})}g.isXRRenderTarget=!0,this.setFoveation(1),s=yield i.requestReferenceSpace(a),X.setContext(i),X.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}})};function I(W){let K=i.inputSources;for(let Z=0;Z0&&(g.alphaTest.value=v.alphaTest);let b=n.get(v).envMap;b&&(g.envMap.value=b,g.flipEnvMap.value=b.isCubeTexture&&b.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=v.reflectivity,g.ior.value=v.ior,g.refractionRatio.value=v.refractionRatio),v.lightMap&&(g.lightMap.value=v.lightMap,g.lightMapIntensity.value=v.lightMapIntensity),v.aoMap&&(g.aoMap.value=v.aoMap,g.aoMapIntensity.value=v.aoMapIntensity);let y;v.map?y=v.map:v.specularMap?y=v.specularMap:v.displacementMap?y=v.displacementMap:v.normalMap?y=v.normalMap:v.bumpMap?y=v.bumpMap:v.roughnessMap?y=v.roughnessMap:v.metalnessMap?y=v.metalnessMap:v.alphaMap?y=v.alphaMap:v.emissiveMap?y=v.emissiveMap:v.clearcoatMap?y=v.clearcoatMap:v.clearcoatNormalMap?y=v.clearcoatNormalMap:v.clearcoatRoughnessMap?y=v.clearcoatRoughnessMap:v.specularIntensityMap?y=v.specularIntensityMap:v.specularColorMap?y=v.specularColorMap:v.transmissionMap?y=v.transmissionMap:v.thicknessMap?y=v.thicknessMap:v.sheenColorMap?y=v.sheenColorMap:v.sheenRoughnessMap&&(y=v.sheenRoughnessMap),y!==void 0&&(y.isWebGLRenderTarget&&(y=y.texture),y.matrixAutoUpdate===!0&&y.updateMatrix(),g.uvTransform.value.copy(y.matrix));let _;v.aoMap?_=v.aoMap:v.lightMap&&(_=v.lightMap),_!==void 0&&(_.isWebGLRenderTarget&&(_=_.texture),_.matrixAutoUpdate===!0&&_.updateMatrix(),g.uv2Transform.value.copy(_.matrix))}function i(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity}function o(g,v){g.dashSize.value=v.dashSize,g.totalSize.value=v.dashSize+v.gapSize,g.scale.value=v.scale}function s(g,v,b,y){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.size.value=v.size*b,g.scale.value=y*.5,v.map&&(g.map.value=v.map),v.alphaMap&&(g.alphaMap.value=v.alphaMap),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest);let _;v.map?_=v.map:v.alphaMap&&(_=v.alphaMap),_!==void 0&&(_.matrixAutoUpdate===!0&&_.updateMatrix(),g.uvTransform.value.copy(_.matrix))}function a(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.rotation.value=v.rotation,v.map&&(g.map.value=v.map),v.alphaMap&&(g.alphaMap.value=v.alphaMap),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest);let b;v.map?b=v.map:v.alphaMap&&(b=v.alphaMap),b!==void 0&&(b.matrixAutoUpdate===!0&&b.updateMatrix(),g.uvTransform.value.copy(b.matrix))}function l(g,v){v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap)}function c(g,v){g.specular.value.copy(v.specular),g.shininess.value=Math.max(v.shininess,1e-4),v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap),v.bumpMap&&(g.bumpMap.value=v.bumpMap,g.bumpScale.value=v.bumpScale,v.side===yn&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,g.normalScale.value.copy(v.normalScale),v.side===yn&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias)}function u(g,v){v.gradientMap&&(g.gradientMap.value=v.gradientMap),v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap),v.bumpMap&&(g.bumpMap.value=v.bumpMap,g.bumpScale.value=v.bumpScale,v.side===yn&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,g.normalScale.value.copy(v.normalScale),v.side===yn&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias)}function h(g,v){g.roughness.value=v.roughness,g.metalness.value=v.metalness,v.roughnessMap&&(g.roughnessMap.value=v.roughnessMap),v.metalnessMap&&(g.metalnessMap.value=v.metalnessMap),v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap),v.bumpMap&&(g.bumpMap.value=v.bumpMap,g.bumpScale.value=v.bumpScale,v.side===yn&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,g.normalScale.value.copy(v.normalScale),v.side===yn&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias),n.get(v).envMap&&(g.envMapIntensity.value=v.envMapIntensity)}function p(g,v,b){h(g,v),g.ior.value=v.ior,v.sheen>0&&(g.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),g.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(g.sheenColorMap.value=v.sheenColorMap),v.sheenRoughnessMap&&(g.sheenRoughnessMap.value=v.sheenRoughnessMap)),v.clearcoat>0&&(g.clearcoat.value=v.clearcoat,g.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(g.clearcoatMap.value=v.clearcoatMap),v.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap),v.clearcoatNormalMap&&(g.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),g.clearcoatNormalMap.value=v.clearcoatNormalMap,v.side===yn&&g.clearcoatNormalScale.value.negate())),v.transmission>0&&(g.transmission.value=v.transmission,g.transmissionSamplerMap.value=b.texture,g.transmissionSamplerSize.value.set(b.width,b.height),v.transmissionMap&&(g.transmissionMap.value=v.transmissionMap),g.thickness.value=v.thickness,v.thicknessMap&&(g.thicknessMap.value=v.thicknessMap),g.attenuationDistance.value=v.attenuationDistance,g.attenuationColor.value.copy(v.attenuationColor)),g.specularIntensity.value=v.specularIntensity,g.specularColor.value.copy(v.specularColor),v.specularIntensityMap&&(g.specularIntensityMap.value=v.specularIntensityMap),v.specularColorMap&&(g.specularColorMap.value=v.specularColorMap)}function d(g,v){v.matcap&&(g.matcap.value=v.matcap),v.bumpMap&&(g.bumpMap.value=v.bumpMap,g.bumpScale.value=v.bumpScale,v.side===yn&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,g.normalScale.value.copy(v.normalScale),v.side===yn&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias)}function f(g,v){v.displacementMap&&(g.displacementMap.value=v.displacementMap,g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias)}function m(g,v){v.displacementMap&&(g.displacementMap.value=v.displacementMap,g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias),g.referencePosition.value.copy(v.referencePosition),g.nearDistance.value=v.nearDistance,g.farDistance.value=v.farDistance}function x(g,v){v.bumpMap&&(g.bumpMap.value=v.bumpMap,g.bumpScale.value=v.bumpScale,v.side===yn&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,g.normalScale.value.copy(v.normalScale),v.side===yn&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias)}return{refreshFogUniforms:t,refreshMaterialUniforms:e}}function Lot(){let n=Hp("canvas");return n.style.display="block",n}function Ie(n={}){let t=n.canvas!==void 0?n.canvas:Lot(),e=n.context!==void 0?n.context:null,r=n.alpha!==void 0?n.alpha:!1,i=n.depth!==void 0?n.depth:!0,o=n.stencil!==void 0?n.stencil:!0,s=n.antialias!==void 0?n.antialias:!1,a=n.premultipliedAlpha!==void 0?n.premultipliedAlpha:!0,l=n.preserveDrawingBuffer!==void 0?n.preserveDrawingBuffer:!1,c=n.powerPreference!==void 0?n.powerPreference:"default",u=n.failIfMajorPerformanceCaveat!==void 0?n.failIfMajorPerformanceCaveat:!1,h=null,p=null,d=[],f=[];this.domElement=t,this.debug={checkShaderErrors:!0},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.outputEncoding=cs,this.physicallyCorrectLights=!1,this.toneMapping=os,this.toneMappingExposure=1;let m=this,x=!1,g=0,v=0,b=null,y=-1,_=null,S=new Re,E=new Re,M=null,P=t.width,D=t.height,w=1,I=null,N=null,L=new Re(0,0,P,D),O=new Re(0,0,P,D),z=!1,V=new Wc,$=!1,X=!1,W=null,K=new Qt,Z=new j,Y={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function tt(){return b===null?w:1}let q=e;function et(U,st){for(let pt=0;pt0?p=f[f.length-1]:p=null,d.pop(),d.length>0?h=d[d.length-1]:h=null};function je(U,st,pt,lt){if(U.visible===!1)return;if(U.layers.test(st.layers)){if(U.isGroup)pt=U.renderOrder;else if(U.isLOD)U.autoUpdate===!0&&U.update(st);else if(U.isLight)p.pushLight(U),U.castShadow&&p.pushShadow(U);else if(U.isSprite){if(!U.frustumCulled||V.intersectsSprite(U)){lt&&Z.setFromMatrixPosition(U.matrixWorld).applyMatrix4(K);let oe=Rt.update(U),de=U.material;de.visible&&h.push(U,oe,de,pt,Z.z,null)}}else if((U.isMesh||U.isLine||U.isPoints)&&(U.isSkinnedMesh&&U.skeleton.frame!==wt.render.frame&&(U.skeleton.update(),U.skeleton.frame=wt.render.frame),!U.frustumCulled||V.intersectsObject(U))){lt&&Z.setFromMatrixPosition(U.matrixWorld).applyMatrix4(K);let oe=Rt.update(U),de=U.material;if(Array.isArray(de)){let he=oe.groups;for(let ke=0,be=he.length;ke0&&Ui(St,st,pt),lt&&nt.viewport(S.copy(lt)),St.length>0&&Yd(St,st,pt),ie.length>0&&Yd(ie,st,pt),oe.length>0&&Yd(oe,st,pt)}function Ui(U,st,pt){if(W===null){let oe=s===!0&&at.isWebGL2===!0?$p:Xn;W=new oe(1024,1024,{generateMipmaps:!0,type:Ht.convert(zc)!==null?zc:ss,minFilter:_v,magFilter:bn,wrapS:_r,wrapT:_r,useRenderToTexture:rt.has("WEBGL_multisampled_render_to_texture")})}let lt=m.getRenderTarget();m.setRenderTarget(W),m.clear();let St=m.toneMapping;m.toneMapping=os,Yd(U,st,pt),m.toneMapping=St,it.updateMultisampleRenderTarget(W),it.updateRenderTargetMipmap(W),m.setRenderTarget(lt)}function Yd(U,st,pt){let lt=st.isScene===!0?st.overrideMaterial:null;for(let St=0,ie=U.length;St=0&&st<=U.width-lt&&pt>=0&&pt<=U.height-St&&q.readPixels(st,pt,lt,St,Ht.convert(ke),Ht.convert(be),ie):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{let he=b!==null?vt.get(b).__webglFramebuffer:null;nt.bindFramebuffer(36160,he)}}},this.copyFramebufferToTexture=function(U,st,pt=0){if(st.isFramebufferTexture!==!0){console.error("THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.");return}let lt=Math.pow(2,-pt),St=Math.floor(st.image.width*lt),ie=Math.floor(st.image.height*lt);it.setTexture2D(st,0),q.copyTexSubImage2D(3553,pt,0,0,U.x,U.y,St,ie),nt.unbindTexture()},this.copyTextureToTexture=function(U,st,pt,lt=0){let St=st.image.width,ie=st.image.height,oe=Ht.convert(pt.format),de=Ht.convert(pt.type);it.setTexture2D(pt,0),q.pixelStorei(37440,pt.flipY),q.pixelStorei(37441,pt.premultiplyAlpha),q.pixelStorei(3317,pt.unpackAlignment),st.isDataTexture?q.texSubImage2D(3553,lt,U.x,U.y,St,ie,oe,de,st.image.data):st.isCompressedTexture?q.compressedTexSubImage2D(3553,lt,U.x,U.y,st.mipmaps[0].width,st.mipmaps[0].height,oe,st.mipmaps[0].data):q.texSubImage2D(3553,lt,U.x,U.y,oe,de,st.image),lt===0&&pt.generateMipmaps&&q.generateMipmap(3553),nt.unbindTexture()},this.copyTextureToTexture3D=function(U,st,pt,lt,St=0){if(m.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}let ie=U.max.x-U.min.x+1,oe=U.max.y-U.min.y+1,de=U.max.z-U.min.z+1,he=Ht.convert(lt.format),ke=Ht.convert(lt.type),be;if(lt.isDataTexture3D)it.setTexture3D(lt,0),be=32879;else if(lt.isDataTexture2DArray)it.setTexture2DArray(lt,0),be=35866;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}q.pixelStorei(37440,lt.flipY),q.pixelStorei(37441,lt.premultiplyAlpha),q.pixelStorei(3317,lt.unpackAlignment);let we=q.getParameter(3314),qe=q.getParameter(32878),Es=q.getParameter(3316),Xa=q.getParameter(3315),Me=q.getParameter(32877),ci=pt.isCompressedTexture?pt.mipmaps[0]:pt.image;q.pixelStorei(3314,ci.width),q.pixelStorei(32878,ci.height),q.pixelStorei(3316,U.min.x),q.pixelStorei(3315,U.min.y),q.pixelStorei(32877,U.min.z),pt.isDataTexture||pt.isDataTexture3D?q.texSubImage3D(be,St,st.x,st.y,st.z,ie,oe,de,he,ke,ci.data):pt.isCompressedTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),q.compressedTexSubImage3D(be,St,st.x,st.y,st.z,ie,oe,de,he,ci.data)):q.texSubImage3D(be,St,st.x,st.y,st.z,ie,oe,de,he,ke,ci),q.pixelStorei(3314,we),q.pixelStorei(32878,qe),q.pixelStorei(3316,Es),q.pixelStorei(3315,Xa),q.pixelStorei(32877,Me),St===0&<.generateMipmaps&&q.generateMipmap(be),nt.unbindTexture()},this.initTexture=function(U){it.setTexture2D(U,0),nt.unbindTexture()},this.resetState=function(){g=0,v=0,b=null,nt.reset(),J.reset()},typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}Ie.prototype.isWebGLRenderer=!0;var TS=class extends Ie{};TS.prototype.isWebGL1Renderer=!0;var Kp=class{constructor(t,e=25e-5){this.name="",this.color=new Pt(t),this.density=e}clone(){return new Kp(this.color,this.density)}toJSON(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}}};Kp.prototype.isFogExp2=!0;var Ca=class{constructor(t,e=1,r=1e3){this.name="",this.color=new Pt(t),this.near=e,this.far=r}clone(){return new Ca(this.color,this.near,this.far)}toJSON(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}};Ca.prototype.isFog=!0;var jc=class extends Te{constructor(){super(),this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0,typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),t.background!==null&&(this.background=t.background.clone()),t.environment!==null&&(this.environment=t.environment.clone()),t.fog!==null&&(this.fog=t.fog.clone()),t.overrideMaterial!==null&&(this.overrideMaterial=t.overrideMaterial.clone()),this.autoUpdate=t.autoUpdate,this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){let e=super.toJSON(t);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),e}};jc.prototype.isScene=!0;var Ma=class{constructor(t,e){this.array=t,this.stride=e,this.count=t!==void 0?t.length/e:0,this.usage=Vp,this.updateRange={offset:0,count:-1},this.version=0,this.uuid=ri()}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,r){t*=this.stride,r*=e.stride;for(let i=0,o=this.stride;it.far||e.push({distance:l,point:Ap.clone(),uv:Ze.getUV(Ap,Ix,kp,kx,fz,aS,mz,new Mt),face:null,object:this})}copy(t){return super.copy(t),t.center!==void 0&&this.center.copy(t.center),this.material=t.material,this}};AS.prototype.isSprite=!0;function Rx(n,t,e,r,i,o){Rc.subVectors(n,e).addScalar(.5).multiply(r),i!==void 0?(Ip.x=o*Rc.x-i*Rc.y,Ip.y=i*Rc.x+o*Rc.y):Ip.copy(Rc),n.copy(t),n.x+=Ip.x,n.y+=Ip.y,n.applyMatrix4(iF)}var gz=new j,xz=new Re,vz=new Re,Dot=new j,yz=new Qt,rv=class extends Ln{constructor(t,e){super(t,e),this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new Qt,this.bindMatrixInverse=new Qt}copy(t){return super.copy(t),this.bindMode=t.bindMode,this.bindMatrix.copy(t.bindMatrix),this.bindMatrixInverse.copy(t.bindMatrixInverse),this.skeleton=t.skeleton,this}bind(t,e){this.skeleton=t,e===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.copy(e).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let t=new Re,e=this.geometry.attributes.skinWeight;for(let r=0,i=e.count;rl)continue;p.applyMatrix4(this.matrixWorld);let M=t.ray.origin.distanceTo(p);Mt.far||e.push({distance:M,point:h.clone().applyMatrix4(this.matrixWorld),index:b,face:null,faceIndex:null,object:this})}}else{let g=Math.max(0,s.start),v=Math.min(x.count,s.start+s.count);for(let b=g,y=v-1;bl)continue;p.applyMatrix4(this.matrixWorld);let S=t.ray.origin.distanceTo(p);St.far||e.push({distance:S,point:h.clone().applyMatrix4(this.matrixWorld),index:b,face:null,faceIndex:null,object:this})}}}else r.isGeometry&&console.error("THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}updateMorphTargets(){let t=this.geometry;if(t.isBufferGeometry){let e=t.morphAttributes,r=Object.keys(e);if(r.length>0){let i=e[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let o=0,s=i.length;o0&&console.error("THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}}};Zp.prototype.isLine=!0;var Mz=new j,Ez=new j,ds=class extends Zp{constructor(t,e){super(t,e),this.type="LineSegments"}computeLineDistances(){let t=this.geometry;if(t.isBufferGeometry)if(t.index===null){let e=t.attributes.position,r=[];for(let i=0,o=e.count;i0){let i=e[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let o=0,s=i.length;o0&&console.error("THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}}};Jp.prototype.isPoints=!0;function Az(n,t,e,r,i,o,s){let a=NS.distanceSqToPoint(n);if(ai.far)return;o.push({distance:c,distanceToRay:Math.sqrt(a),point:l,index:t,face:null,object:s})}}var LS=class extends Qe{constructor(t,e,r,i,o,s,a,l,c){super(t,e,r,i,o,s,a,l,c),this.minFilter=s!==void 0?s:dn,this.magFilter=o!==void 0?o:dn,this.generateMipmaps=!1;let u=this;function h(){u.needsUpdate=!0,t.requestVideoFrameCallback(h)}"requestVideoFrameCallback"in t&&t.requestVideoFrameCallback(h)}clone(){return new this.constructor(this.image).copy(this)}update(){let t=this.image;"requestVideoFrameCallback"in t===!1&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}};LS.prototype.isVideoTexture=!0;var DS=class extends Qe{constructor(t,e,r){super({width:t,height:e}),this.format=r,this.magFilter=bn,this.minFilter=bn,this.generateMipmaps=!1,this.needsUpdate=!0}};DS.prototype.isFramebufferTexture=!0;var zS=class extends Qe{constructor(t,e,r,i,o,s,a,l,c,u,h,p){super(null,s,a,l,c,u,i,o,h,p),this.image={width:e,height:r},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}};zS.prototype.isCompressedTexture=!0;var FS=class extends Qe{constructor(t,e,r,i,o,s,a,l,c){super(t,e,r,i,o,s,a,l,c),this.needsUpdate=!0}};FS.prototype.isCanvasTexture=!0;var nne=new j,rne=new j,ine=new j,one=new Ze;var hr=class{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){let r=this.getUtoTmapping(t);return this.getPoint(r,e)}getPoints(t=5){let e=[];for(let r=0;r<=t;r++)e.push(this.getPoint(r/t));return e}getSpacedPoints(t=5){let e=[];for(let r=0;r<=t;r++)e.push(this.getPointAt(r/t));return e}getLength(){let t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;let e=[],r,i=this.getPoint(0),o=0;e.push(0);for(let s=1;s<=t;s++)r=this.getPoint(s/t),o+=r.distanceTo(i),e.push(o),i=r;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){let r=this.getLengths(),i=0,o=r.length,s;e?s=e:s=t*r[o-1];let a=0,l=o-1,c;for(;a<=l;)if(i=Math.floor(a+(l-a)/2),c=r[i]-s,c<0)a=i+1;else if(c>0)l=i-1;else{l=i;break}if(i=l,r[i]===s)return i/(o-1);let u=r[i],p=r[i+1]-u,d=(s-u)/p;return(i+d)/(o-1)}getTangent(t,e){let i=t-1e-4,o=t+1e-4;i<0&&(i=0),o>1&&(o=1);let s=this.getPoint(i),a=this.getPoint(o),l=e||(s.isVector2?new Mt:new j);return l.copy(a).sub(s).normalize(),l}getTangentAt(t,e){let r=this.getUtoTmapping(t);return this.getTangent(r,e)}computeFrenetFrames(t,e){let r=new j,i=[],o=[],s=[],a=new j,l=new Qt;for(let d=0;d<=t;d++){let f=d/t;i[d]=this.getTangentAt(f,new j)}o[0]=new j,s[0]=new j;let c=Number.MAX_VALUE,u=Math.abs(i[0].x),h=Math.abs(i[0].y),p=Math.abs(i[0].z);u<=c&&(c=u,r.set(1,0,0)),h<=c&&(c=h,r.set(0,1,0)),p<=c&&r.set(0,0,1),a.crossVectors(i[0],r).normalize(),o[0].crossVectors(i[0],a),s[0].crossVectors(i[0],o[0]);for(let d=1;d<=t;d++){if(o[d]=o[d-1].clone(),s[d]=s[d-1].clone(),a.crossVectors(i[d-1],i[d]),a.length()>Number.EPSILON){a.normalize();let f=Math.acos(er(i[d-1].dot(i[d]),-1,1));o[d].applyMatrix4(l.makeRotationAxis(a,f))}s[d].crossVectors(i[d],o[d])}if(e===!0){let d=Math.acos(er(o[0].dot(o[t]),-1,1));d/=t,i[0].dot(a.crossVectors(o[0],o[t]))>0&&(d=-d);for(let f=1;f<=t;f++)o[f].applyMatrix4(l.makeRotationAxis(i[f],d*f)),s[f].crossVectors(i[f],o[f])}return{tangents:i,normals:o,binormals:s}}clone(){return new this.constructor().copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){let t={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}},qc=class extends hr{constructor(t=0,e=0,r=1,i=1,o=0,s=Math.PI*2,a=!1,l=0){super(),this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=r,this.yRadius=i,this.aStartAngle=o,this.aEndAngle=s,this.aClockwise=a,this.aRotation=l}getPoint(t,e){let r=e||new Mt,i=Math.PI*2,o=this.aEndAngle-this.aStartAngle,s=Math.abs(o)i;)o-=i;o0?0:(Math.floor(Math.abs(a)/o)+1)*o:l===0&&a===o-1&&(a=o-2,l=1);let c,u;this.closed||a>0?c=i[(a-1)%o]:(zx.subVectors(i[0],i[1]).add(i[0]),c=zx);let h=i[a%o],p=i[(a+1)%o];if(this.closed||a+2i.length-2?i.length-1:s+1],h=i[s>i.length-3?i.length-1:s+2];return r.set(Iz(a,l.x,c.x,u.x,h.x),Iz(a,l.y,c.y,u.y,h.y)),r}copy(t){super.copy(t),this.points=[];for(let e=0,r=t.points.length;e=r){let s=i[o]-r,a=this.curves[o],l=a.getLength(),c=l===0?0:1-s/l;return a.getPointAt(c,e)}o++}return null}getLength(){let t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let t=[],e=0;for(let r=0,i=this.curves.length;r1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,r=t.curves.length;e0){let h=c.getPoint(0);h.equals(this.currentPoint)||this.lineTo(h.x,h.y)}this.curves.push(c);let u=c.getPoint(1);return this.currentPoint.copy(u),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){let t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}},Ta=class extends nd{constructor(t){super(t),this.uuid=ri(),this.type="Shape",this.holes=[]}getPointsHoles(t){let e=[];for(let r=0,i=this.holes.length;r80*e){a=c=n[0],l=u=n[1];for(let f=e;fc&&(c=h),p>u&&(u=p);d=Math.max(c-a,u-l),d=d!==0?1/d:0}return rd(o,s,e,a,l,d),s}};function sF(n,t,e,r,i){let o,s;if(i===ost(n,t,e,r)>0)for(o=t;o=t;o-=r)s=kz(o,n[o],n[o+1],s);return s&&Sv(s,s.next)&&(od(s),s=s.next),s}function fs(n,t){if(!n)return n;t||(t=n);let e=n,r;do if(r=!1,!e.steiner&&(Sv(e,e.next)||Ge(e.prev,e,e.next)===0)){if(od(e),e=t=e.prev,e===e.next)break;r=!0}else e=e.next;while(r||e!==t);return t}function rd(n,t,e,r,i,o,s){if(!n)return;!s&&o&&Qot(n,r,i,o);let a=n,l,c;for(;n.prev!==n.next;){if(l=n.prev,c=n.next,o?Got(n,r,i,o):Wot(n)){t.push(l.i/e),t.push(n.i/e),t.push(c.i/e),od(n),n=c.next,a=c.next;continue}if(n=c,n===a){s?s===1?(n=jot(fs(n),t,e),rd(n,t,e,r,i,o,2)):s===2&&qot(n,t,e,r,i,o):rd(fs(n),t,e,r,i,o,1);break}}}function Wot(n){let t=n.prev,e=n,r=n.next;if(Ge(t,e,r)>=0)return!1;let i=n.next.next;for(;i!==n.prev;){if(Dc(t.x,t.y,e.x,e.y,r.x,r.y,i.x,i.y)&&Ge(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function Got(n,t,e,r){let i=n.prev,o=n,s=n.next;if(Ge(i,o,s)>=0)return!1;let a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,u=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,h=VS(a,l,t,e,r),p=VS(c,u,t,e,r),d=n.prevZ,f=n.nextZ;for(;d&&d.z>=h&&f&&f.z<=p;){if(d!==n.prev&&d!==n.next&&Dc(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&Ge(d.prev,d,d.next)>=0||(d=d.prevZ,f!==n.prev&&f!==n.next&&Dc(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&Ge(f.prev,f,f.next)>=0))return!1;f=f.nextZ}for(;d&&d.z>=h;){if(d!==n.prev&&d!==n.next&&Dc(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&Ge(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;f&&f.z<=p;){if(f!==n.prev&&f!==n.next&&Dc(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&Ge(f.prev,f,f.next)>=0)return!1;f=f.nextZ}return!0}function jot(n,t,e){let r=n;do{let i=r.prev,o=r.next.next;!Sv(i,o)&&aF(i,r,r.next,o)&&id(i,o)&&id(o,i)&&(t.push(i.i/e),t.push(r.i/e),t.push(o.i/e),od(r),od(r.next),r=n=o),r=r.next}while(r!==n);return fs(r)}function qot(n,t,e,r,i,o){let s=n;do{let a=s.next.next;for(;a!==s.prev;){if(s.i!==a.i&&nst(s,a)){let l=lF(s,a);s=fs(s,s.next),l=fs(l,l.next),rd(s,t,e,r,i,o),rd(l,t,e,r,i,o);return}a=a.next}s=s.next}while(s!==n)}function Xot(n,t,e,r){let i=[],o,s,a,l,c;for(o=0,s=t.length;o=e.next.y&&e.next.y!==e.y){let p=e.x+(i-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(p<=r&&p>o){if(o=p,p===r){if(i===e.y)return e;if(i===e.next.y)return e.next}s=e.x=e.x&&e.x>=l&&r!==e.x&&Dc(is.x||e.x===s.x&&Jot(s,e)))&&(s=e,u=h)),e=e.next;while(e!==a);return s}function Jot(n,t){return Ge(n.prev,n,t.prev)<0&&Ge(t.next,n,n.next)<0}function Qot(n,t,e,r){let i=n;do i.z===null&&(i.z=VS(i.x,i.y,t,e,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==n);i.prevZ.nextZ=null,i.prevZ=null,tst(i)}function tst(n){let t,e,r,i,o,s,a,l,c=1;do{for(e=n,n=null,o=null,s=0;e;){for(s++,r=e,a=0,t=0;t0||l>0&&r;)a!==0&&(l===0||!r||e.z<=r.z)?(i=e,e=e.nextZ,a--):(i=r,r=r.nextZ,l--),o?o.nextZ=i:n=i,i.prevZ=o,o=i;e=r}o.nextZ=null,c*=2}while(s>1);return n}function VS(n,t,e,r,i){return n=32767*(n-e)*i,t=32767*(t-r)*i,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,n|t<<1}function est(n){let t=n,e=n;do(t.x=0&&(n-s)*(r-a)-(e-s)*(t-a)>=0&&(e-s)*(o-a)-(i-s)*(r-a)>=0}function nst(n,t){return n.next.i!==t.i&&n.prev.i!==t.i&&!rst(n,t)&&(id(n,t)&&id(t,n)&&ist(n,t)&&(Ge(n.prev,n,t.prev)||Ge(n,t.prev,t))||Sv(n,t)&&Ge(n.prev,n,n.next)>0&&Ge(t.prev,t,t.next)>0)}function Ge(n,t,e){return(t.y-n.y)*(e.x-t.x)-(t.x-n.x)*(e.y-t.y)}function Sv(n,t){return n.x===t.x&&n.y===t.y}function aF(n,t,e,r){let i=Ox(Ge(n,t,e)),o=Ox(Ge(n,t,r)),s=Ox(Ge(e,r,n)),a=Ox(Ge(e,r,t));return!!(i!==o&&s!==a||i===0&&Fx(n,e,t)||o===0&&Fx(n,r,t)||s===0&&Fx(e,n,r)||a===0&&Fx(e,t,r))}function Fx(n,t,e){return t.x<=Math.max(n.x,e.x)&&t.x>=Math.min(n.x,e.x)&&t.y<=Math.max(n.y,e.y)&&t.y>=Math.min(n.y,e.y)}function Ox(n){return n>0?1:n<0?-1:0}function rst(n,t){let e=n;do{if(e.i!==n.i&&e.next.i!==n.i&&e.i!==t.i&&e.next.i!==t.i&&aF(e,e.next,n,t))return!0;e=e.next}while(e!==n);return!1}function id(n,t){return Ge(n.prev,n,n.next)<0?Ge(n,t,n.next)>=0&&Ge(n,n.prev,t)>=0:Ge(n,t,n.prev)<0||Ge(n,n.next,t)<0}function ist(n,t){let e=n,r=!1,i=(n.x+t.x)/2,o=(n.y+t.y)/2;do e.y>o!=e.next.y>o&&e.next.y!==e.y&&i<(e.next.x-e.x)*(o-e.y)/(e.next.y-e.y)+e.x&&(r=!r),e=e.next;while(e!==n);return r}function lF(n,t){let e=new HS(n.i,n.x,n.y),r=new HS(t.i,t.x,t.y),i=n.next,o=t.prev;return n.next=t,t.prev=n,e.next=i,i.prev=e,r.next=e,e.prev=r,o.next=r,r.prev=o,r}function kz(n,t,e,r){let i=new HS(n,t,e);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function od(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function HS(n,t,e){this.i=n,this.x=t,this.y=e,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function ost(n,t,e,r){let i=0;for(let o=t,s=e-r;o2&&n[t-1].equals(n[0])&&n.pop()}function Pz(n,t){for(let e=0;eNumber.EPSILON){let ht=Math.sqrt(G),kt=Math.sqrt(Zt*Zt+re*re),Bt=yt.x-Yt/ht,ft=yt.y+Lt/ht,Ht=ct.x-re/kt,J=ct.y+Zt/kt,mt=((Ht-Bt)*re-(J-ft)*Zt)/(Lt*re-Yt*Zt);bt=Bt+Lt*mt-it.x,gt=ft+Yt*mt-it.y;let It=bt*bt+gt*gt;if(It<=2)return new Mt(bt,gt);Rt=Math.sqrt(It/2)}else{let ht=!1;Lt>Number.EPSILON?Zt>Number.EPSILON&&(ht=!0):Lt<-Number.EPSILON?Zt<-Number.EPSILON&&(ht=!0):Math.sign(Yt)===Math.sign(re)&&(ht=!0),ht?(bt=-Yt,gt=Lt,Rt=Math.sqrt(G)):(bt=Lt,gt=Yt,Rt=Math.sqrt(G/2))}return new Mt(bt/Rt,gt/Rt)}let X=[];for(let it=0,yt=L.length,ct=yt-1,bt=it+1;it=0;it--){let yt=it/x,ct=d*Math.cos(yt*Math.PI/2),bt=f*Math.sin(yt*Math.PI/2)+m;for(let gt=0,Rt=L.length;gt=0;){let bt=ct,gt=ct-1;gt<0&&(gt=it.length-1);for(let Rt=0,Lt=u+x*2;Rt0!=t>0&&this.version++,this._sheen=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.ior=t.ior,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}};US.prototype.isMeshPhysicalMaterial=!0;var WS=class extends Dn{constructor(t){super(),this.type="MeshPhongMaterial",this.color=new Pt(16777215),this.specular=new Pt(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Jc,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=yv,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this}};WS.prototype.isMeshPhongMaterial=!0;var GS=class extends Dn{constructor(t){super(),this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Pt(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Jc,this.normalScale=new Mt(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.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this}};GS.prototype.isMeshToonMaterial=!0;var jS=class extends Dn{constructor(t){super(),this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Jc,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}};jS.prototype.isMeshNormalMaterial=!0;var qS=class extends Dn{constructor(t){super(),this.type="MeshLambertMaterial",this.color=new Pt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=yv,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this}};qS.prototype.isMeshLambertMaterial=!0;var XS=class extends Dn{constructor(t){super(),this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Pt(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Jc,this.normalScale=new Mt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.flatShading=t.flatShading,this}};XS.prototype.isMeshMatcapMaterial=!0;var KS=class extends Ri{constructor(t){super(),this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}};KS.prototype.isLineDashedMaterial=!0;var $e={arraySlice:function(n,t,e){return $e.isTypedArray(n)?new n.constructor(n.subarray(t,e!==void 0?e:n.length)):n.slice(t,e)},convertArray:function(n,t,e){return!n||!e&&n.constructor===t?n:typeof t.BYTES_PER_ELEMENT=="number"?new t(n):Array.prototype.slice.call(n)},isTypedArray:function(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)},getKeyframeOrder:function(n){function t(i,o){return n[i]-n[o]}let e=n.length,r=new Array(e);for(let i=0;i!==e;++i)r[i]=i;return r.sort(t),r},sortedArray:function(n,t,e){let r=n.length,i=new n.constructor(r);for(let o=0,s=0;s!==r;++o){let a=e[o]*t;for(let l=0;l!==t;++l)i[s++]=n[a+l]}return i},flattenJSON:function(n,t,e,r){let i=1,o=n[0];for(;o!==void 0&&o[r]===void 0;)o=n[i++];if(o===void 0)return;let s=o[r];if(s!==void 0)if(Array.isArray(s))do s=o[r],s!==void 0&&(t.push(o.time),e.push.apply(e,s)),o=n[i++];while(o!==void 0);else if(s.toArray!==void 0)do s=o[r],s!==void 0&&(t.push(o.time),s.toArray(e,e.length)),o=n[i++];while(o!==void 0);else do s=o[r],s!==void 0&&(t.push(o.time),e.push(s)),o=n[i++];while(o!==void 0)},subclip:function(n,t,e,r,i=30){let o=n.clone();o.name=t;let s=[];for(let l=0;l=r)){h.push(c.times[d]);for(let m=0;mo.tracks[l].times[0]&&(a=o.tracks[l].times[0]);for(let l=0;l=a.times[f]){let g=f*h+u,v=g+h-u;m=$e.arraySlice(a.values,g,v)}else{let g=a.createInterpolant(),v=u,b=h-u;g.evaluate(o),m=$e.arraySlice(g.resultBuffer,v,b)}l==="quaternion"&&new wn().fromArray(m).normalize().conjugate().toArray(m);let x=c.times.length;for(let g=0;g=o)){let a=e[1];t=o)break e}s=r,r=0;break n}break t}for(;r>>1;te;)--s;if(++s,o!==0||s!==i){o>=s&&(s=Math.max(s,1),o=s-1);let a=this.getValueSize();this.times=$e.arraySlice(r,o,s),this.values=$e.arraySlice(this.values,o*a,s*a)}return this}validate(){let t=!0,e=this.getValueSize();e-Math.floor(e)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);let r=this.times,i=this.values,o=r.length;o===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let s=null;for(let a=0;a!==o;a++){let l=r[a];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,a,l),t=!1;break}if(s!==null&&s>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,a,l,s),t=!1;break}s=l}if(i!==void 0&&$e.isTypedArray(i))for(let a=0,l=i.length;a!==l;++a){let c=i[a];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,a,c),t=!1;break}}return t}optimize(){let t=$e.arraySlice(this.times),e=$e.arraySlice(this.values),r=this.getValueSize(),i=this.getInterpolation()===Nw,o=t.length-1,s=1;for(let a=1;a0){t[s]=t[o];for(let a=o*r,l=s*r,c=0;c!==r;++c)e[l+c]=e[a+c];++s}return s!==t.length?(this.times=$e.arraySlice(t,0,s),this.values=$e.arraySlice(e,0,s*r)):(this.times=t,this.values=e),this}clone(){let t=$e.arraySlice(this.times,0),e=$e.arraySlice(this.values,0),r=this.constructor,i=new r(this.name,t,e);return i.createInterpolant=this.createInterpolant,i}};Vr.prototype.TimeBufferType=Float32Array;Vr.prototype.ValueBufferType=Float32Array;Vr.prototype.DefaultInterpolation=Wx;var gs=class extends Vr{};gs.prototype.ValueTypeName="bool";gs.prototype.ValueBufferType=Array;gs.prototype.DefaultInterpolation=Ux;gs.prototype.InterpolantFactoryMethodLinear=void 0;gs.prototype.InterpolantFactoryMethodSmooth=void 0;var hv=class extends Vr{};hv.prototype.ValueTypeName="color";var Kc=class extends Vr{};Kc.prototype.ValueTypeName="number";var JS=class extends Pi{constructor(t,e,r,i){super(t,e,r,i)}interpolate_(t,e,r,i){let o=this.resultBuffer,s=this.sampleValues,a=this.valueSize,l=(r-e)/(i-e),c=t*a;for(let u=c+a;c!==u;c+=4)wn.slerpFlat(o,0,s,c-a,s,c,l);return o}},Aa=class extends Vr{InterpolantFactoryMethodLinear(t){return new JS(this.times,this.values,this.getValueSize(),t)}};Aa.prototype.ValueTypeName="quaternion";Aa.prototype.DefaultInterpolation=Wx;Aa.prototype.InterpolantFactoryMethodSmooth=void 0;var xs=class extends Vr{};xs.prototype.ValueTypeName="string";xs.prototype.ValueBufferType=Array;xs.prototype.DefaultInterpolation=Ux;xs.prototype.InterpolantFactoryMethodLinear=void 0;xs.prototype.InterpolantFactoryMethodSmooth=void 0;var Yc=class extends Vr{};Yc.prototype.ValueTypeName="vector";var pv=class{constructor(t,e=-1,r,i=AC){this.name=t,this.tracks=r,this.duration=e,this.blendMode=i,this.uuid=ri(),this.duration<0&&this.resetDuration()}static parse(t){let e=[],r=t.tracks,i=1/(t.fps||1);for(let s=0,a=r.length;s!==a;++s)e.push(ust(r[s]).scale(i));let o=new this(t.name,t.duration,e,t.blendMode);return o.uuid=t.uuid,o}static toJSON(t){let e=[],r=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let o=0,s=r.length;o!==s;++o)e.push(Vr.toJSON(r[o]));return i}static CreateFromMorphTargetSequence(t,e,r,i){let o=e.length,s=[];for(let a=0;a1){let h=u[1],p=i[h];p||(i[h]=p=[]),p.push(c)}}let s=[];for(let a in i)s.push(this.CreateFromMorphTargetSequence(a,i[a],e,r));return s}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;let r=function(h,p,d,f,m){if(d.length!==0){let x=[],g=[];$e.flattenJSON(d,x,g,f),x.length!==0&&m.push(new h(p,x,g))}},i=[],o=t.name||"default",s=t.fps||30,a=t.blendMode,l=t.length||-1,c=t.hierarchy||[];for(let h=0;h{e&&e(o),this.manager.itemEnd(t)},0),o;if(mo[t]!==void 0){mo[t].push({onLoad:e,onProgress:r,onError:i});return}mo[t]=[],mo[t].push({onLoad:e,onProgress:r,onError:i});let s=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,l=this.responseType;fetch(s).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream=="undefined"||c.body.getReader===void 0)return c;let u=mo[t],h=c.body.getReader(),p=c.headers.get("Content-Length"),d=p?parseInt(p):0,f=d!==0,m=0,x=new ReadableStream({start(g){v();function v(){h.read().then(({done:b,value:y})=>{if(b)g.close();else{m+=y.byteLength;let _=new ProgressEvent("progress",{lengthComputable:f,loaded:m,total:d});for(let S=0,E=u.length;S{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(u=>new DOMParser().parseFromString(u,a));case"json":return c.json();default:if(a===void 0)return c.text();{let h=/charset="?([^;"\s]*)"?/i.exec(a),p=h&&h[1]?h[1].toLowerCase():void 0,d=new TextDecoder(p);return c.arrayBuffer().then(f=>d.decode(f))}}}).then(c=>{Zc.add(t,c);let u=mo[t];delete mo[t];for(let h=0,p=u.length;h{let u=mo[t];if(u===void 0)throw this.manager.itemError(t),c;delete mo[t];for(let h=0,p=u.length;h{this.manager.itemEnd(t)}),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}};var dv=class extends Ni{constructor(t){super(t)}load(t,e,r,i){this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);let o=this,s=Zc.get(t);if(s!==void 0)return o.manager.itemStart(t),setTimeout(function(){e&&e(s),o.manager.itemEnd(t)},0),s;let a=Hp("img");function l(){u(),Zc.add(t,this),e&&e(this),o.manager.itemEnd(t)}function c(h){u(),i&&i(h),o.manager.itemError(t),o.manager.itemEnd(t)}function u(){a.removeEventListener("load",l,!1),a.removeEventListener("error",c,!1)}return a.addEventListener("load",l,!1),a.addEventListener("error",c,!1),t.substr(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),o.manager.itemStart(t),a.src=t,a}},eC=class extends Ni{constructor(t){super(t)}load(t,e,r,i){let o=new Uc,s=new dv(this.manager);s.setCrossOrigin(this.crossOrigin),s.setPath(this.path);let a=0;function l(c){s.load(t[c],function(u){o.images[c]=u,a++,a===6&&(o.needsUpdate=!0,e&&e(o))},void 0,i)}for(let c=0;c0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t0&&this._mixBufferRegionAdditive(r,i,this._addIndex*e,1,e);for(let l=e,c=e+e;l!==c;++l)if(r[l]!==r[l+e]){a.setValue(r,i);break}}saveOriginalState(){let t=this.binding,e=this.buffer,r=this.valueSize,i=r*this._origIndex;t.getValue(e,i);for(let o=r,s=i;o!==s;++o)e[o]=e[i+o%r];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let t=this.valueSize*3;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){let t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let r=t;r=.5)for(let s=0;s!==o;++s)t[e+s]=t[r+s]}_slerp(t,e,r,i){wn.slerpFlat(t,e,t,e,t,r,i)}_slerpAdditive(t,e,r,i,o){let s=this._workIndex*o;wn.multiplyQuaternionsFlat(t,s,t,e,t,r),wn.slerpFlat(t,e,t,e,t,s,i)}_lerp(t,e,r,i,o){let s=1-i;for(let a=0;a!==o;++a){let l=e+a;t[l]=t[l]*s+t[r+a]*i}}_lerpAdditive(t,e,r,i,o){for(let s=0;s!==o;++s){let a=e+s;t[a]=t[a]+t[r+s]*i}}},RC="\\[\\]\\.:\\/",dst=new RegExp("["+RC+"]","g"),PC="[^"+RC+"]",fst="[^"+RC.replace("\\.","")+"]",mst=/((?:WC+[\/:])*)/.source.replace("WC",PC),gst=/(WCOD+)?/.source.replace("WCOD",fst),xst=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",PC),vst=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",PC),yst=new RegExp("^"+mst+gst+xst+vst+"$"),bst=["material","materials","bones"],xC=class{constructor(t,e,r){let i=r||ye.parseTrackName(e);this._targetGroup=t,this._bindings=t.subscribe_(e,i)}getValue(t,e){this.bind();let r=this._targetGroup.nCachedObjects_,i=this._bindings[r];i!==void 0&&i.getValue(t,e)}setValue(t,e){let r=this._bindings;for(let i=this._targetGroup.nCachedObjects_,o=r.length;i!==o;++i)r[i].setValue(t,e)}bind(){let t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,r=t.length;e!==r;++e)t[e].bind()}unbind(){let t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,r=t.length;e!==r;++e)t[e].unbind()}},ye=class{constructor(t,e,r){this.path=e,this.parsedPath=r||ye.parseTrackName(e),this.node=ye.findNode(t,this.parsedPath.nodeName)||t,this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,r){return t&&t.isAnimationObjectGroup?new ye.Composite(t,e,r):new ye(t,e,r)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(dst,"")}static parseTrackName(t){let e=yst.exec(t);if(!e)throw new Error("PropertyBinding: Cannot parse trackName: "+t);let r={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},i=r.nodeName&&r.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let o=r.nodeName.substring(i+1);bst.indexOf(o)!==-1&&(r.nodeName=r.nodeName.substring(0,i),r.objectName=o)}if(r.propertyName===null||r.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return r}static findNode(t,e){if(!e||e===""||e==="."||e===-1||e===t.name||e===t.uuid)return t;if(t.skeleton){let r=t.skeleton.getBoneByName(e);if(r!==void 0)return r}if(t.children){let r=function(o){for(let s=0;s=o){let h=o++,p=t[h];e[p.uuid]=u,t[u]=p,e[c]=h,t[h]=l;for(let d=0,f=i;d!==f;++d){let m=r[d],x=m[h],g=m[u];m[u]=x,m[h]=g}}}this.nCachedObjects_=o}uncache(){let t=this._objects,e=this._indicesByUUID,r=this._bindings,i=r.length,o=this.nCachedObjects_,s=t.length;for(let a=0,l=arguments.length;a!==l;++a){let c=arguments[a],u=c.uuid,h=e[u];if(h!==void 0)if(delete e[u],h0&&(e[d.uuid]=h),t[h]=d,t.pop();for(let f=0,m=i;f!==m;++f){let x=r[f];x[h]=x[p],x.pop()}}}this.nCachedObjects_=o}subscribe_(t,e){let r=this._bindingsIndicesByPath,i=r[t],o=this._bindings;if(i!==void 0)return o[i];let s=this._paths,a=this._parsedPaths,l=this._objects,c=l.length,u=this.nCachedObjects_,h=new Array(c);i=o.length,r[t]=i,s.push(t),a.push(e),o.push(h);for(let p=u,d=l.length;p!==d;++p){let f=l[p];h[p]=new ye(f,t,e)}return h}unsubscribe_(t){let e=this._bindingsIndicesByPath,r=e[t];if(r!==void 0){let i=this._paths,o=this._parsedPaths,s=this._bindings,a=s.length-1,l=s[a],c=t[a];e[c]=r,s[r]=l,s.pop(),o[r]=o[a],o.pop(),i[r]=i[a],i.pop()}}};vC.prototype.isAnimationObjectGroup=!0;var yC=class{constructor(t,e,r=null,i=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=r,this.blendMode=i;let o=e.tracks,s=o.length,a=new Array(s),l={endingStart:Nc,endingEnd:Nc};for(let c=0;c!==s;++c){let u=o[c].createInterpolant(null);a[c]=u,u.settings=l}this._interpolantSettings=l,this._interpolants=a,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=qtt,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(t){return this._startTime=t,this}setLoop(t,e){return this.loop=t,this.repetitions=e,this}setEffectiveWeight(t){return this.weight=t,this._effectiveWeight=this.enabled?t:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(t){return this._scheduleFading(t,0,1)}fadeOut(t){return this._scheduleFading(t,1,0)}crossFadeFrom(t,e,r){if(t.fadeOut(e),this.fadeIn(e),r){let i=this._clip.duration,o=t._clip.duration,s=o/i,a=i/o;t.warp(1,s,e),this.warp(a,1,e)}return this}crossFadeTo(t,e,r){return t.crossFadeFrom(this,e,r)}stopFading(){let t=this._weightInterpolant;return t!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}setEffectiveTimeScale(t){return this.timeScale=t,this._effectiveTimeScale=this.paused?0:t,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(t){return this.timeScale=this._clip.duration/t,this.stopWarping()}syncWith(t){return this.time=t.time,this.timeScale=t.timeScale,this.stopWarping()}halt(t){return this.warp(this._effectiveTimeScale,0,t)}warp(t,e,r){let i=this._mixer,o=i.time,s=this.timeScale,a=this._timeScaleInterpolant;a===null&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);let l=a.parameterPositions,c=a.sampleValues;return l[0]=o,l[1]=o+r,c[0]=t/s,c[1]=e/s,this}stopWarping(){let t=this._timeScaleInterpolant;return t!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(t,e,r,i){if(!this.enabled){this._updateWeight(t);return}let o=this._startTime;if(o!==null){let l=(t-o)*r;if(l<0||r===0)return;this._startTime=null,e=r*l}e*=this._updateTimeScale(t);let s=this._updateTime(e),a=this._updateWeight(t);if(a>0){let l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case Wz:for(let u=0,h=l.length;u!==h;++u)l[u].evaluate(s),c[u].accumulateAdditive(a);break;case AC:default:for(let u=0,h=l.length;u!==h;++u)l[u].evaluate(s),c[u].accumulate(i,a)}}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;let r=this._weightInterpolant;if(r!==null){let i=r.evaluate(t)[0];e*=i,t>r.parameterPositions[1]&&(this.stopFading(),i===0&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;let r=this._timeScaleInterpolant;r!==null&&(e*=r.evaluate(t)[0],t>r.parameterPositions[1]&&(this.stopWarping(),e===0?this.paused=!0:this.timeScale=e))}return this._effectiveTimeScale=e,e}_updateTime(t){let e=this._clip.duration,r=this.loop,i=this.time+t,o=this._loopCount,s=r===Xtt;if(t===0)return o===-1?i:s&&(o&1)===1?e-i:i;if(r===jtt){o===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(i>=e)i=e;else if(i<0)i=0;else{this.time=i;break t}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(o===-1&&(t>=0?(o=0,this._setEndings(!0,this.repetitions===0,s)):this._setEndings(this.repetitions===0,!0,s)),i>=e||i<0){let a=Math.floor(i/e);i-=e*a,o+=Math.abs(a);let l=this.repetitions-o;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=t>0?e:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(l===1){let c=t<0;this._setEndings(c,!c,s)}else this._setEndings(!1,!1,s);this._loopCount=o,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:a})}}else this.time=i;if(s&&(o&1)===1)return e-i}return i}_setEndings(t,e,r){let i=this._interpolantSettings;r?(i.endingStart=Lc,i.endingEnd=Lc):(t?i.endingStart=this.zeroSlopeAtStart?Lc:Nc:i.endingStart=Gx,e?i.endingEnd=this.zeroSlopeAtEnd?Lc:Nc:i.endingEnd=Gx)}_scheduleFading(t,e,r){let i=this._mixer,o=i.time,s=this._weightInterpolant;s===null&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);let a=s.parameterPositions,l=s.sampleValues;return a[0]=o,l[0]=e,a[1]=o+t,l[1]=r,this}},bC=class extends ii{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(t,e){let r=t._localRoot||this._root,i=t._clip.tracks,o=i.length,s=t._propertyBindings,a=t._interpolants,l=r.uuid,c=this._bindingsByRootAndName,u=c[l];u===void 0&&(u={},c[l]=u);for(let h=0;h!==o;++h){let p=i[h],d=p.name,f=u[d];if(f!==void 0)++f.referenceCount,s[h]=f;else{if(f=s[h],f!==void 0){f._cacheIndex===null&&(++f.referenceCount,this._addInactiveBinding(f,l,d));continue}let m=e&&e._propertyBindings[h].binding.parsedPath;f=new gC(ye.create(r,d,m),p.ValueTypeName,p.getValueSize()),++f.referenceCount,this._addInactiveBinding(f,l,d),s[h]=f}a[h].resultBuffer=f.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(t._cacheIndex===null){let r=(t._localRoot||this._root).uuid,i=t._clip.uuid,o=this._actionsByClip[i];this._bindAction(t,o&&o.knownActions[0]),this._addInactiveAction(t,i,r)}let e=t._propertyBindings;for(let r=0,i=e.length;r!==i;++r){let o=e[r];o.useCount++===0&&(this._lendBinding(o),o.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){let e=t._propertyBindings;for(let r=0,i=e.length;r!==i;++r){let o=e[r];--o.useCount===0&&(o.restoreOriginalState(),this._takeBackBinding(o))}this._takeBackAction(t)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}}_isActiveAction(t){let e=t._cacheIndex;return e!==null&&e=0;--r)t[r].stop();return this}update(t){t*=this.timeScale;let e=this._actions,r=this._nActiveActions,i=this.time+=t,o=Math.sign(t),s=this._accuIndex^=1;for(let c=0;c!==r;++c)e[c]._update(i,t,o,s);let a=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)a[c].apply(s);return this}setTime(t){this.time=0;for(let e=0;ethis.max.x||t.ythis.max.y)}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return!(t.max.xthis.max.x||t.max.ythis.max.y)}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return Fz.copy(t).clamp(this.min,this.max).sub(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}};Ia.prototype.isBox2=!0;var Oz=new j,Vx=new j,SC=class{constructor(t=new j,e=new j){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){Oz.subVectors(t,this.start),Vx.subVectors(this.end,this.start);let r=Vx.dot(Vx),o=Vx.dot(Oz)/r;return e&&(o=er(o,0,1)),o}closestPointToPoint(t,e,r){let i=this.closestPointToPointParameter(t,e);return this.delta(r).multiplyScalar(i).add(this.start)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return new this.constructor().copy(this)}};var ns=new j,Hx=new Qt,dS=new Qt,CC=class extends ds{constructor(t){let e=cF(t),r=new _e,i=[],o=[],s=new Pt(0,0,1),a=new Pt(0,1,0);for(let c=0;ci?p:i,r=pi.test(o.metadata[e].toString())}else n=n.toLowerCase(),r=i=>i.metadata[e].toString().toLowerCase().indexOf(n)>=0;return r}function Di(n,t,e=null,r=wst){let i=e==null;return e=ve(n,e),new Promise((o,s)=>{setTimeout(()=>{try{let a=t();i&&ve(null,e),o(a)}catch(a){We(a.message),s(a)}return!0},r)})}function mF(n){if(!n)return{};let t=n.indexOf("?")!==-1?n.split("?")[1]:n;t.indexOf("#")&&(t=t.split("#")[0]);let e=t.split("&"),r={};for(let i=0;i=0)return!0;return!1}function LC(n,t){return(n||t)&&!(n&&t)}function Cv(){return Jt(this,null,function*(){try{let n=document.createElement("canvas"),t=n.getContext("webgl")||n.getContext("experimental-webgl");return yield EA(),t!=null&&TA()==="webgl"}catch(n){return!1}})}function zi(n,t){return nt?1:n>=t?0:NaN}function Mv(n){return n.length===1&&(n=Sst(n)),{left:function(t,e,r,i){for(r==null&&(r=0),i==null&&(i=t.length);r>>1;n(t[o],e)<0?r=o+1:i=o}return r},right:function(t,e,r,i){for(r==null&&(r=0),i==null&&(i=t.length);r>>1;n(t[o],e)>0?i=o:r=o+1}return r}}}function Sst(n){return function(t,e){return zi(n(t),e)}}var gF=Mv(zi),xF=gF.right,Cst=gF.left,vs=xF;function Na(n,t){var e=n.length,r=-1,i,o,s;if(t==null){for(;++r=i)for(o=s=i;++ri&&(o=i),s=i)for(o=s=i;++ri&&(o=i),s0)return[n];if((r=t0)for(n=Math.ceil(n/a),t=Math.floor(t/a),s=new Array(o=Math.ceil(t-n+1));++i=0?(o>=DC?10:o>=zC?5:o>=FC?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(o>=DC?10:o>=zC?5:o>=FC?2:1)}function La(n,t,e){var r=Math.abs(t-n)/Math.max(0,e),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),o=r/i;return o>=DC?i*=10:o>=zC?i*=5:o>=FC&&(i*=2),t=0&&(r=e.slice(i+1),e=e.slice(0,i)),e&&!t.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:r}})}Av.prototype=_F.prototype={constructor:Av,on:function(n,t){var e=this._,r=Lst(n+"",e),i,o=-1,s=r.length;if(arguments.length<2){for(;++o0)for(var e=new Array(i),r=0,i,o;r=0&&(t=n.slice(0,e))!=="xmlns"&&(n=n.slice(e+1)),VC.hasOwnProperty(t)?{space:VC[t],local:n}:n}function zst(n){return function(){var t=this.ownerDocument,e=this.namespaceURI;return e===Iv&&t.documentElement.namespaceURI===Iv?t.createElement(n):t.createElementNS(e,n)}}function Fst(n){return function(){return this.ownerDocument.createElementNS(n.space,n.local)}}function kv(n){var t=xo(n);return(t.local?Fst:zst)(t)}function Ost(){}function Da(n){return n==null?Ost:function(){return this.querySelector(n)}}function wF(n){typeof n!="function"&&(n=Da(n));for(var t=this._groups,e=t.length,r=new Array(e),i=0;i=b&&(b=v+1);!(_=x[b])&&++b=0;)(s=r[i])&&(o&&s.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(s,o),o=s);return this}function NF(n){n||(n=$st);function t(h,p){return h&&p?n(h.__data__,p.__data__):!h-!p}for(var e=this._groups,r=e.length,i=new Array(r),o=0;ot?1:n>=t?0:NaN}function LF(){var n=arguments[0];return arguments[0]=this,n.apply(null,arguments),this}function DF(){var n=new Array(this.size()),t=-1;return this.each(function(){n[++t]=this}),n}function zF(){for(var n=this._groups,t=0,e=n.length;t1?this.each((t==null?Kst:typeof t=="function"?Zst:Yst)(n,t,e==null?"":e)):ys(this.node(),n)}function ys(n,t){return n.style.getPropertyValue(t)||Pv(n).getComputedStyle(n,null).getPropertyValue(t)}function Jst(n){return function(){delete this[n]}}function Qst(n,t){return function(){this[n]=t}}function tat(n,t){return function(){var e=t.apply(this,arguments);e==null?delete this[n]:this[n]=e}}function $F(n,t){return arguments.length>1?this.each((t==null?Jst:typeof t=="function"?tat:Qst)(n,t)):this.node()[n]}function UF(n){return n.trim().split(/^|\s+/)}function HC(n){return n.classList||new WF(n)}function WF(n){this._node=n,this._names=UF(n.getAttribute("class")||"")}WF.prototype={add:function(n){var t=this._names.indexOf(n);t<0&&(this._names.push(n),this._node.setAttribute("class",this._names.join(" ")))},remove:function(n){var t=this._names.indexOf(n);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(n){return this._names.indexOf(n)>=0}};function GF(n,t){for(var e=HC(n),r=-1,i=t.length;++r=0&&(e=t.slice(r+1),t=t.slice(0,r)),{type:t,name:e}})}function vat(n){return function(){var t=this.__on;if(!!t){for(var e=0,r=-1,i=t.length,o;e>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):e===8?Lv(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):e===4?Lv(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Cat.exec(n))?new Cr(t[1],t[2],t[3],1):(t=Mat.exec(n))?new Cr(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Eat.exec(n))?Lv(t[1],t[2],t[3],t[4]):(t=Tat.exec(n))?Lv(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Aat.exec(n))?g8(t[1],t[2]/100,t[3]/100,1):(t=Iat.exec(n))?g8(t[1],t[2]/100,t[3]/100,t[4]):u8.hasOwnProperty(n)?d8(u8[n]):n==="transparent"?new Cr(NaN,NaN,NaN,0):null}function d8(n){return new Cr(n>>16&255,n>>8&255,n&255,1)}function Lv(n,t,e,r){return r<=0&&(n=t=e=NaN),new Cr(n,t,e,r)}function Rat(n){return n instanceof _d||(n=oi(n)),n?(n=n.rgb(),new Cr(n.r,n.g,n.b,n.opacity)):new Cr}function iu(n,t,e,r){return arguments.length===1?Rat(n):new Cr(n,t,e,r==null?1:r)}function Cr(n,t,e,r){this.r=+n,this.g=+t,this.b=+e,this.opacity=+r}Nv(Cr,iu,UC(_d,{brighter:function(n){return n=n==null?Dv:Math.pow(Dv,n),new Cr(this.r*n,this.g*n,this.b*n,this.opacity)},darker:function(n){return n=n==null?yd:Math.pow(yd,n),new Cr(this.r*n,this.g*n,this.b*n,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:f8,formatHex:f8,formatRgb:m8,toString:m8}));function f8(){return"#"+WC(this.r)+WC(this.g)+WC(this.b)}function m8(){var n=this.opacity;return n=isNaN(n)?1:Math.max(0,Math.min(1,n)),(n===1?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(n===1?")":", "+n+")")}function WC(n){return n=Math.max(0,Math.min(255,Math.round(n)||0)),(n<16?"0":"")+n.toString(16)}function g8(n,t,e,r){return r<=0?n=t=e=NaN:e<=0||e>=1?n=t=NaN:t<=0&&(n=NaN),new Fi(n,t,e,r)}function x8(n){if(n instanceof Fi)return new Fi(n.h,n.s,n.l,n.opacity);if(n instanceof _d||(n=oi(n)),!n)return new Fi;if(n instanceof Fi)return n;n=n.rgb();var t=n.r/255,e=n.g/255,r=n.b/255,i=Math.min(t,e,r),o=Math.max(t,e,r),s=NaN,a=o-i,l=(o+i)/2;return a?(t===o?s=(e-r)/a+(e0&&l<1?0:s,new Fi(s,a,l,n.opacity)}function zv(n,t,e,r){return arguments.length===1?x8(n):new Fi(n,t,e,r==null?1:r)}function Fi(n,t,e,r){this.h=+n,this.s=+t,this.l=+e,this.opacity=+r}Nv(Fi,zv,UC(_d,{brighter:function(n){return n=n==null?Dv:Math.pow(Dv,n),new Fi(this.h,this.s,this.l*n,this.opacity)},darker:function(n){return n=n==null?yd:Math.pow(yd,n),new Fi(this.h,this.s,this.l*n,this.opacity)},rgb:function(){var n=this.h%360+(this.h<0)*360,t=isNaN(n)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*t,i=2*e-r;return new Cr(GC(n>=240?n-240:n+120,i,r),GC(n,i,r),GC(n<120?n+240:n-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var n=this.opacity;return n=isNaN(n)?1:Math.max(0,Math.min(1,n)),(n===1?"hsl(":"hsla(")+(this.h||0)+", "+(this.s||0)*100+"%, "+(this.l||0)*100+"%"+(n===1?")":", "+n+")")}}));function GC(n,t,e){return(n<60?t+(e-t)*n/60:n<180?e:n<240?t+(e-t)*(240-n)/60:t)*255}function jC(n,t,e,r,i){var o=n*n,s=o*n;return((1-3*n+3*o-s)*t+(4-6*o+3*s)*e+(1+3*n+3*o-3*s)*r+s*i)/6}function v8(n){var t=n.length-1;return function(e){var r=e<=0?e=0:e>=1?(e=1,t-1):Math.floor(e*t),i=n[r],o=n[r+1],s=r>0?n[r-1]:2*i-o,a=re&&(o=t.slice(e,o),a[s]?a[s]+=o:a[++s]=o),(r=r[0])===(i=i[0])?a[s]?a[s]+=i:a[++s]=i:(a[++s]=null,l.push({i:s,x:$n(r,i)})),e=qC.lastIndex;return e180?u+=360:u-c>180&&(c+=360),p.push({i:h.push(i(h)+"rotate(",null,r)-2,x:$n(c,u)})):u&&h.push(i(h)+"rotate("+u+r)}function a(c,u,h,p){c!==u?p.push({i:h.push(i(h)+"skewX(",null,r)-2,x:$n(c,u)}):u&&h.push(i(h)+"skewX("+u+r)}function l(c,u,h,p,d,f){if(c!==h||u!==p){var m=d.push(i(d)+"scale(",null,",",null,")");f.push({i:m-4,x:$n(c,h)},{i:m-2,x:$n(u,p)})}else(h!==1||p!==1)&&d.push(i(d)+"scale("+h+","+p+")")}return function(c,u){var h=[],p=[];return c=n(c),u=n(u),o(c.translateX,c.translateY,u.translateX,u.translateY,h,p),s(c.rotate,u.rotate,h,p),a(c.skewX,u.skewX,h,p),l(c.scaleX,c.scaleY,u.scaleX,u.scaleY,h,p),c=u=null,function(d){for(var f=-1,m=p.length,x;++f=0&&n._call.call(null,t),n=n._next;--ou}function P8(){Oa=(Hv=Ad.now())+$v,ou=Ed=0;try{D8()}finally{ou=0,Vat(),Oa=0}}function Bat(){var n=Ad.now(),t=n-Hv;t>N8&&($v-=t,Hv=n)}function Vat(){for(var n,t=Vv,e,r=1/0;t;)t._call?(r>t._time&&(r=t._time),n=t,t=t._next):(e=t._next,t._next=null,t=n?n._next=e:Vv=e);Td=n,t3(r)}function t3(n){if(!ou){Ed&&(Ed=clearTimeout(Ed));var t=n-Oa;t>24?(n<1/0&&(Ed=setTimeout(P8,n-Ad.now()-$v)),Md&&(Md=clearInterval(Md))):(Md||(Hv=Ad.now(),Md=setInterval(Bat,N8)),ou=1,L8(P8))}}function Wv(n,t,e){var r=new Id;return t=t==null?0:+t,r.restart(function(i){r.stop(),n(i+t)},t,e),r}var Hat=BC("start","end","cancel","interrupt"),$at=[],F8=0,e3=1,jv=2,Gv=3,z8=4,qv=5,kd=6;function bs(n,t,e,r,i,o){var s=n.__transition;if(!s)n.__transition={};else if(e in s)return;Uat(n,e,{name:t,index:r,group:i,on:Hat,tween:$at,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:F8})}function Rd(n,t){var e=Cn(n,t);if(e.state>F8)throw new Error("too late; already scheduled");return e}function ir(n,t){var e=Cn(n,t);if(e.state>Gv)throw new Error("too late; already running");return e}function Cn(n,t){var e=n.__transition;if(!e||!(e=e[t]))throw new Error("transition not found");return e}function Uat(n,t,e){var r=n.__transition,i;r[t]=e,e.timer=Uv(o,0,e.time);function o(c){e.state=e3,e.timer.restart(s,e.delay,e.time),e.delay<=c&&s(c-e.delay)}function s(c){var u,h,p,d;if(e.state!==e3)return l();for(u in r)if(d=r[u],d.name===e.name){if(d.state===Gv)return Wv(s);d.state===z8?(d.state=kd,d.timer.stop(),d.on.call("interrupt",n,n.__data__,d.index,d.group),delete r[u]):+ujv&&r.state=0&&(t=t.slice(0,e)),!t||t==="start"})}function llt(n,t,e){var r,i,o=alt(t)?Rd:ir;return function(){var s=o(this,n),a=s.on;a!==r&&(i=(r=a).copy()).on(t,e),s.on=i}}function q8(n,t){var e=this._id;return arguments.length<2?Cn(this.node(),e).on.on(n):this.each(llt(e,n,t))}function clt(n){return function(){var t=this.parentNode;for(var e in this.__transition)if(+e!==n)return;t&&t.removeChild(this)}}function X8(){return this.on("end.remove",clt(this._id))}function K8(n){var t=this._name,e=this._id;typeof n!="function"&&(n=Da(n));for(var r=this._groups,i=r.length,o=new Array(i),s=0;s=1e21?n.toLocaleString("en").replace(/,/g,""):n.toString(10)}function Va(n,t){if((e=(n=t?n.toExponential(t-1):n.toExponential()).indexOf("e"))<0)return null;var e,r=n.slice(0,e);return[r.length>1?r[0]+r.slice(2):r,+n.slice(e+1)]}function Bi(n){return n=Va(Math.abs(n)),n?n[1]:NaN}function pO(n,t){return function(e,r){for(var i=e.length,o=[],s=0,a=n[0],l=0;i>0&&a>0&&(l+a+1>r&&(a=Math.max(1,r-l)),o.push(e.substring(i-=a,i+a)),!((l+=a+1)>r));)a=n[s=(s+1)%n.length];return o.reverse().join(t)}}function dO(n){return function(t){return t.replace(/[0-9]/g,function(e){return n[+e]})}}var Rlt=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function _s(n){if(!(t=Rlt.exec(n)))throw new Error("invalid format: "+n);var t;return new Qv({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}_s.prototype=Qv.prototype;function Qv(n){this.fill=n.fill===void 0?" ":n.fill+"",this.align=n.align===void 0?">":n.align+"",this.sign=n.sign===void 0?"-":n.sign+"",this.symbol=n.symbol===void 0?"":n.symbol+"",this.zero=!!n.zero,this.width=n.width===void 0?void 0:+n.width,this.comma=!!n.comma,this.precision=n.precision===void 0?void 0:+n.precision,this.trim=!!n.trim,this.type=n.type===void 0?"":n.type+""}Qv.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function fO(n){t:for(var t=n.length,e=1,r=-1,i;e0&&(r=0);break}return r>0?n.slice(0,r)+n.slice(i+1):n}var o3;function mO(n,t){var e=Va(n,t);if(!e)return n+"";var r=e[0],i=e[1],o=i-(o3=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,s=r.length;return o===s?r:o>s?r+new Array(o-s+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+Va(n,Math.max(0,t+o-1))[0]}function s3(n,t){var e=Va(n,t);if(!e)return n+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}var a3={"%":function(n,t){return(n*100).toFixed(t)},b:function(n){return Math.round(n).toString(2)},c:function(n){return n+""},d:hO,e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},g:function(n,t){return n.toPrecision(t)},o:function(n){return Math.round(n).toString(8)},p:function(n,t){return s3(n*100,t)},r:s3,s:mO,X:function(n){return Math.round(n).toString(16).toUpperCase()},x:function(n){return Math.round(n).toString(16)}};function l3(n){return n}var gO=Array.prototype.map,xO=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function vO(n){var t=n.grouping===void 0||n.thousands===void 0?l3:pO(gO.call(n.grouping,Number),n.thousands+""),e=n.currency===void 0?"":n.currency[0]+"",r=n.currency===void 0?"":n.currency[1]+"",i=n.decimal===void 0?".":n.decimal+"",o=n.numerals===void 0?l3:dO(gO.call(n.numerals,String)),s=n.percent===void 0?"%":n.percent+"",a=n.minus===void 0?"-":n.minus+"",l=n.nan===void 0?"NaN":n.nan+"";function c(h){h=_s(h);var p=h.fill,d=h.align,f=h.sign,m=h.symbol,x=h.zero,g=h.width,v=h.comma,b=h.precision,y=h.trim,_=h.type;_==="n"?(v=!0,_="g"):a3[_]||(b===void 0&&(b=12),y=!0,_="g"),(x||p==="0"&&d==="=")&&(x=!0,p="0",d="=");var S=m==="$"?e:m==="#"&&/[boxX]/.test(_)?"0"+_.toLowerCase():"",E=m==="$"?r:/[%p]/.test(_)?s:"",M=a3[_],P=/[defgprs%]/.test(_);b=b===void 0?6:/[gprs]/.test(_)?Math.max(1,Math.min(21,b)):Math.max(0,Math.min(20,b));function D(w){var I=S,N=E,L,O,z;if(_==="c")N=M(w)+N,w="";else{w=+w;var V=w<0||1/w<0;if(w=isNaN(w)?l:M(Math.abs(w),b),y&&(w=fO(w)),V&&+w==0&&f!=="+"&&(V=!1),I=(V?f==="("?f:a:f==="-"||f==="("?"":f)+I,N=(_==="s"?xO[8+o3/3]:"")+N+(V&&f==="("?")":""),P){for(L=-1,O=w.length;++Lz||z>57){N=(z===46?i+w.slice(L+1):w.slice(L))+N,w=w.slice(0,L);break}}}v&&!x&&(w=t(w,1/0));var $=I.length+w.length+N.length,X=$>1)+I+w+N+X.slice($);break;default:w=X+I+w+N;break}return o(w)}return D.toString=function(){return h+""},D}function u(h,p){var d=c((h=_s(h),h.type="f",h)),f=Math.max(-8,Math.min(8,Math.floor(Bi(p)/3)))*3,m=Math.pow(10,-f),x=xO[8+f/3];return function(g){return d(m*g)+x}}return{format:c,formatPrefix:u}}var ty,ey,ny;c3({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"});function c3(n){return ty=vO(n),ey=ty.format,ny=ty.formatPrefix,ty}function u3(n){return Math.max(0,-Bi(Math.abs(n)))}function h3(n,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Bi(t)/3)))*3-Bi(Math.abs(n)))}function p3(n,t){return n=Math.abs(n),t=Math.abs(t)-n,Math.max(0,Bi(t)-Bi(n))+1}function $r(){return Math.random()}var Plt=function n(t){function e(r,i){return r=r==null?0:+r,i=i==null?1:+i,arguments.length===1?(i=r,r=0):i-=r,function(){return t()*i+r}}return e.source=n,e}($r);var Ld=function n(t){function e(r,i){var o,s;return r=r==null?0:+r,i=i==null?1:+i,function(){var a;if(o!=null)a=o,o=null;else do o=t()*2-1,a=t()*2-1,s=o*o+a*a;while(!s||s>1);return r+i*a*Math.sqrt(-2*Math.log(s)/s)}}return e.source=n,e}($r);var Nlt=function n(t){function e(){var r=Ld.source(t).apply(this,arguments);return function(){return Math.exp(r())}}return e.source=n,e}($r);var d3=function n(t){function e(r){return function(){for(var i=0,o=0;oe&&(r=t,t=e,e=r),function(i){return Math.max(t,Math.min(e,i))}}function zlt(n,t,e){var r=n[0],i=n[1],o=t[0],s=t[1];return i2?Flt:zlt,l=c=null,h}function h(p){return isNaN(p=+p)?o:(l||(l=a(n.map(r),t,e)))(r(s(p)))}return h.invert=function(p){return s(i((c||(c=a(t,n.map(r),$n)))(p)))},h.domain=function(p){return arguments.length?(n=ry.call(p,m3),s===Zn||(s=wO(n)),u()):n.slice()},h.range=function(p){return arguments.length?(t=ws.call(p),u()):t.slice()},h.rangeRound=function(p){return t=ws.call(p),e=KC,u()},h.clamp=function(p){return arguments.length?(s=p?wO(n):Zn,h):s!==Zn},h.interpolate=function(p){return arguments.length?(e=p,u()):e},h.unknown=function(p){return arguments.length?(o=p,h):o},function(p,d){return r=p,i=d,u()}}function iy(n,t){return Dd()(n,t)}function x3(n,t,e,r){var i=La(n,t,e),o;switch(r=_s(r==null?",f":r),r.type){case"s":{var s=Math.max(Math.abs(n),Math.abs(t));return r.precision==null&&!isNaN(o=h3(i,s))&&(r.precision=o),ny(r,s)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(o=p3(i,Math.max(Math.abs(n),Math.abs(t))))&&(r.precision=o-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(o=u3(i))&&(r.precision=o-(r.type==="%")*2);break}}return ey(r)}function Ss(n){var t=n.domain;return n.ticks=function(e){var r=t();return Tv(r[0],r[r.length-1],e==null?10:e)},n.tickFormat=function(e,r){var i=t();return x3(i[0],i[i.length-1],e==null?10:e,r)},n.nice=function(e){e==null&&(e=10);var r=t(),i=0,o=r.length-1,s=r[i],a=r[o],l;return a0?(s=Math.floor(s/l)*l,a=Math.ceil(a/l)*l,l=nu(s,a,e)):l<0&&(s=Math.ceil(s*l)/l,a=Math.floor(a*l)/l,l=nu(s,a,e)),l>0?(r[i]=Math.floor(s/l)*l,r[o]=Math.ceil(a/l)*l,t(r)):l<0&&(r[i]=Math.ceil(s*l)/l,r[o]=Math.floor(a*l)/l,t(r)),n},n}function Vi(){var n=iy(Zn,Zn);return n.copy=function(){return Ha(n,Vi())},pr.apply(n,arguments),Ss(n)}function SO(n){return function(t){return t<0?-Math.pow(-t,n):Math.pow(t,n)}}function Blt(n){return n<0?-Math.sqrt(-n):Math.sqrt(n)}function Vlt(n){return n<0?-n*n:n*n}function v3(n){var t=n(Zn,Zn),e=1;function r(){return e===1?n(Zn,Zn):e===.5?n(Blt,Vlt):n(SO(e),SO(1/e))}return t.exponent=function(i){return arguments.length?(e=+i,r()):e},Ss(t)}function zd(){var n=v3(Dd());return n.copy=function(){return Ha(n,zd()).exponent(n.exponent())},pr.apply(n,arguments),n}var Hlt=1e3,$lt=Hlt*60,Ult=$lt*60,y3=Ult*24,Kde=y3*7,Yde=y3*30,Zde=y3*365;function MO(n){for(var t=n.length/6|0,e=new Array(t),r=0;r0)){if(m/=d,d<0){if(m0){if(m>p)return;m>h&&(h=m)}if(m=r-a,!(!d&&m<0)){if(m/=d,d<0){if(m>p)return;m>h&&(h=m)}else if(d>0){if(m0)){if(m/=f,f<0){if(m0){if(m>p)return;m>h&&(h=m)}if(m=i-l,!(!f&&m<0)){if(m/=f,f<0){if(m>p)return;m>h&&(h=m)}else if(f>0){if(m0)&&!(p<1)||(h>0&&(n[0]=[a+h*d,l+h*f]),p<1&&(n[1]=[a+p*d,l+p*f])),!0}}}}}function qlt(n,t,e,r,i){var o=n[1];if(o)return!0;var s=n[0],a=n.left,l=n.right,c=a[0],u=a[1],h=l[0],p=l[1],d=(c+h)/2,f=(u+p)/2,m,x;if(p===u){if(d=r)return;if(c>h){if(!s)s=[d,e];else if(s[1]>=i)return;o=[d,i]}else{if(!s)s=[d,i];else if(s[1]1)if(c>h){if(!s)s=[(e-x)/m,e];else if(s[1]>=i)return;o=[(i-x)/m,i]}else{if(!s)s=[(i-x)/m,i];else if(s[1]=r)return;o=[r,m*r+x]}else{if(!s)s=[r,m*r+x];else if(s[0]Ne||Math.abs(o[0][1]-o[1][1])>Ne))&&delete zn[i]}function AO(n){return or[n.index]={site:n,halfedges:[]}}function Xlt(n,t){var e=n.site,r=t.left,i=t.right;return e===i&&(i=r,r=e),i?Math.atan2(i[1]-r[1],i[0]-r[0]):(e===r?(r=t[1],i=t[0]):(r=t[0],i=t[1]),Math.atan2(r[0]-i[0],i[1]-r[1]))}function S3(n,t){return t[+(t.left!==n.site)]}function Klt(n,t){return t[+(t.left===n.site)]}function IO(){for(var n=0,t=or.length,e,r,i,o;nNe||Math.abs(x-d)>Ne)&&(c.splice(l,0,zn.push(pu(a,f,Math.abs(m-n)Ne?[n,Math.abs(p-n)Ne?[Math.abs(d-r)Ne?[e,Math.abs(p-e)Ne?[Math.abs(d-t)=-PO)){var d=l*l+c*c,f=u*u+h*h,m=(h*d-c*f)/p,x=(l*f-u*d)/p,g=RO.pop()||new Ylt;g.arc=n,g.site=i,g.x=m+s,g.y=(g.cy=x+a)+Math.sqrt(m*m+x*x),n.circle=g;for(var v=null,b=du._;b;)if(g.yNe)a=a.L;else if(s=t-Jlt(a,e),s>Ne){if(!a.R){r=a;break}a=a.R}else{o>-Ne?(r=a.P,i=a):s>-Ne?(r=a,i=a.N):r=i=a;break}AO(n);var l=NO(n);if(Wa.insert(r,l),!(!r&&!i)){if(r===i){Ua(r),i=NO(r.site),Wa.insert(l,i),l.edge=i.edge=hu(r.site,l.site),$a(r),$a(i);return}if(!i){l.edge=hu(r.site,l.site);return}Ua(r),Ua(i);var c=r.site,u=c[0],h=c[1],p=n[0]-u,d=n[1]-h,f=i.site,m=f[0]-u,x=f[1]-h,g=2*(p*x-d*m),v=p*p+d*d,b=m*m+x*x,y=[(x*v-d*b)/g+u,(p*b-m*v)/g+h];Bd(i.edge,c,f,y),l.edge=hu(c,n,null,y),i.edge=hu(n,f,null,y),$a(r),$a(i)}}function FO(n,t){var e=n.site,r=e[0],i=e[1],o=i-t;if(!o)return r;var s=n.P;if(!s)return-1/0;e=s.site;var a=e[0],l=e[1],c=l-t;if(!c)return a;var u=a-r,h=1/o-1/c,p=u/c;return h?(-p+Math.sqrt(p*p-2*h*(u*u/(-2*c)-l+c/2+i-o/2)))/h+r:(r+a)/2}function Jlt(n,t){var e=n.N;if(e)return FO(e,t);var r=n.site;return r[1]===t?r[0]:1/0}var Ne=1e-6,PO=1e-12,Wa,or,du,zn;function Qlt(n,t,e){return(n[0]-e[0])*(t[1]-n[1])-(n[0]-t[0])*(e[1]-n[1])}function tct(n,t){return t[1]-n[1]||t[0]-n[0]}function sy(n,t){var e=n.sort(tct).pop(),r,i,o;for(zn=[],or=new Array(n.length),Wa=new w3,du=new w3;;)if(o=oy,e&&(!o||e[1]=s)return null;var l=n-a.site[0],c=t-a.site[1],u=l*l+c*c;do a=r.cells[i=o],o=null,a.halfedges.forEach(function(h){var p=r.edges[h],d=p.left;if(!((d===a.site||!d)&&!(d=p.right))){var f=n-d[0],m=t-d[1],x=f*f+m*m;x=0,"Norm of the vector must be > 0");for(let e=0;er),eu(n.length>=0,"`vectors` must be of length >= 1");let e=new Float32Array(t(n[0]).length);for(let r=0;rr){let _=[[0,a*s-r],[0,0]];v=i_(g,_)}let b=p_(v,new Array(s).fill(a),0);function y(_){let S="Finding nearest neighbors: "+(u*100).toFixed()+"%";Di(S,()=>Jt(this,null,function*(){let E=yield b[p].data();u+=h;for(let M=0;M=r)break;for(let w=0;w=0&&P.add(I,{index:w,dist:I})}o[D]=P.getMinKItems()}u+=h,c+=a,p++}),I3).then(()=>{pE.dispose()),_(o))},E=>{ve(null,I3),k3(n,t,e,(P,D,w)=>uy(P,D)).then(P=>{_(P)})})}return new Promise(_=>y(_))}function k3(n,t,e,r){return Di("Finding nearest neighbors...",()=>{let i=n.length,o=new Array(i),s=new Array(i);for(let a=0;a=0&&(c.add(m,{index:u,dist:m}),h.add(m,{index:a,dist:m}))}}for(let a=0;a=0,ja=1e4,dy=5e3,fy=5e4,Wd=200,R3=10,hy="umap-optimization",sct=300,act=["__next__","__seq_next__"];function UO(n){let t=null;for(let e of act)if(e in n&&n[e]!==""){t=n[e];break}return t==null?null:+t}var si=class{constructor(t,e){this.shuffledDataIndices=[],this.projections={},this.tSNEIteration=0,this.tSNEShouldPause=!1,this.tSNEShouldStop=!0,this.superviseInput="",this.dim=[0,0],this.hasTSNERun=!1,this.hasUmapRun=!1,this.points=t,this.shuffledDataIndices=hF(tu(this.points.length)),this.sequences=this.computeSequences(t),this.dim=[this.points.length,this.points[0].vector.length],e&&(this.spriteAndMetadataInfo=e)}computeSequences(t){let e=new Int8Array(t.length),r={},i=[];for(let o=0;o0}getSubset(t){let r=(t!=null&&t.length>0?t.map(i=>this.points[i]):this.points).map(i=>({metadata:i.metadata,index:i.index,vector:i.vector.slice(),projections:{}}));return new si(r,this.spriteAndMetadataInfo)}normalize(){let t=cy(this.points,e=>e.vector);if(t==null)throw Error("centroid should not be null");for(let e=0;e0&&OO(r.vector)}}projectLinear(t,e){this.projections[e]=!0,this.points.forEach(r=>{r.projections[e]=Hd(r.vector,t)})}projectPCA(){return this.projections["pca-0"]!=null?Promise.resolve(null):Di("Computing PCA...",()=>{let t=this.points[0].vector.length,e=this.shuffledDataIndices.map(m=>this.points[m].vector);t>Wd&&(e=BO(e,Wd));let r=e.slice(0,fy),{dot:i,transpose:o,svd:s}=eh.default,a=eh.default.div,l=i(o(r),r),c=a(l,r.length),u=s(c),h=u.S,p=0;for(let m=0;m{let x=new Float32Array(R3);for(let g=0;g{if(!this.tsne.getSolution()){this.initTsneSolutionFromCurrentProjection();return}if(this.tSNEShouldStop){this.projections.tsne=!1,i(null),this.tsne=null,this.hasTSNERun=!1;return}if(!this.tSNEShouldPause){this.tsne.step();let h=this.tsne.getSolution(),p=this.tsne.getDim();a.forEach((d,f)=>{let m=this.points[d];for(let x=0;xthis.points[h]);this.computeKnn(c,o).then(h=>{Di("Initializing T-SNE...",()=>{this.tsne.initDataDist(h)}).then(l)})}projectUmap(t,e,r,i){return Jt(this,null,function*(){this.hasUmapRun=!0,this.umap=new WO.UMAP({nComponents:t,nNeighbors:e,minDist:r});let o=0,s=10,a=this.shuffledDataIndices.slice(0,dy),l=a.map(p=>this.points[p]),c=l.map(p=>Array.from(p.vector)),u=yield this.computeKnn(l,e),h=yield Di("Initializing UMAP...",()=>{let p=u.map(f=>f.map(m=>m.index)),d=u.map(f=>f.map(m=>m.dist));return this.umap.setPrecomputedKNN(p,d),this.umap.initializeFit(c)},hy);return new Promise((p,d)=>{let f=()=>{let m=Math.min(s,h-o);for(let g=0;g{if(o{let y=this.points[v];y.projections["umap-0"]=g[b][0],y.projections["umap-1"]=g[b][1],t===3&&(y.projections["umap-2"]=g[b][2])}),this.projections.umap=!0,ve(null,hy),this.hasUmapRun=!0,i(o),p()}},hy,0).catch(g=>{ve(null,hy),d(g)})};requestAnimationFrame(f)})})}computeKnn(t,e){return Jt(this,null,function*(){let r=this.nearest&&this.nearest.length?this.nearest[0].length:0;if(this.nearest!=null&&this.nearest.length===t.length&&r>=e)return Promise.resolve(this.nearest.map(i=>i.slice(0,e)));{let i=(yield Cv())&&!oct,o=Math.max(e,sct),s=yield i?HO(t,o,a=>a.vector):k3(t,o,a=>a.vector,(a,l)=>uy(a,l));return this.nearest=s,Promise.resolve(s.map(a=>a.slice(0,e)))}})}initTsneSolutionFromCurrentProjection(){let t=this.shuffledDataIndices.slice(0,ja),e=this.tsne.getRng(),r=this.tsne.getDim(),i=new Float64Array(t.length*r);t.forEach((o,s)=>{var l;let a=this.points[o];for(let c=0;c{let s=this.points[i];s.projections["tsne-0"]=e[o*t+0],s.projections["tsne-1"]=e[o*t+1],t===3&&(s.projections["tsne-2"]=e[o*t+2])})}}setTsneLearningRate(t){this.tsne&&this.tsne.setEpsilon(t)}setSupervision(t,e){t!=null&&(this.superviseLabels=this.shuffledDataIndices.slice(0,ja).map(r=>this.points[r].metadata[t]!==void 0?String(this.points[r].metadata[t]):`Unknown #${r}`)),e!=null&&(this.superviseInput=e),this.tsne&&this.tsne.setSupervision(this.superviseLabels,this.superviseInput)}setSuperviseFactor(t){t!=null&&(this.superviseFactor=t,this.tsne&&this.tsne.setSuperviseFactor(t))}mergeMetadata(t){var e,r,i,o,s,a,l;if(((e=t.pointsInfo)==null?void 0:e.length)!==this.points.length){let c=`Number of tensors (${this.points.length}) do not match the number of lines in metadata (${(r=t.pointsInfo)==null?void 0:r.length}).`;if(((i=t.stats)==null?void 0:i.length)===1&&this.points.length+1===((o=t.pointsInfo)==null?void 0:o.length))return We(c+" Single column metadata should not have a header row.","merging metadata"),!1;if(((s=t.stats)==null?void 0:s.length)>1&&this.points.length-1===((a=t.pointsInfo)==null?void 0:a.length))return We(c+" Multi-column metadata should have a header row with column labels.","merging metadata"),!1;pc(c)}return this.spriteAndMetadataInfo=t,(l=t.pointsInfo)==null||l.slice(0,this.points.length).forEach((c,u)=>this.points[u].metadata=c),!0}stopTSNE(){this.tSNEShouldStop=!0}findNeighbors(t,e,r){return $O(this.points,t,r,s=>s.vector,e).slice(0,r)}query(t,e,r){let i=fF(t,e,r),o=[];return this.points.forEach((s,a)=>{i(s)&&o.push(a)}),o}},bo=class{constructor(t,e,r,i){this.projectionType=t,this.projectionComponents=e,this.dimensionality=r,this.dataSet=i}},py=class{constructor(){this.label="",this.isSelected=!1,this.tSNEIteration=0,this.tSNEPerplexity=0,this.tSNELearningRate=0,this.tSNEis3d=!0,this.umapIs3d=!0,this.umapNeighbors=15,this.umapMinDist=.1,this.pcaComponentDimensions=[],this.projections=[],this.selectedPoints=[],this.shuffledDataIndices=[]}};function qa(n,t){if(t.length>3)throw new RangeError("components length must be <= 3");let e=[null,null,null],r=n==="custom"?"linear":n;for(let i=0;i{if(a.lengthComputable){let l=(a.loaded*100/a.total).toFixed(1);ve("Fetching tensor values: "+l+"%",Cs)}},s.onload=()=>{if(s.status!==200){let u=String.fromCharCode.apply(null,new Uint8Array(s.response));We(u,"fetching tensors");return}let a;try{a=new Float32Array(s.response)}catch(u){We(u.message,"parsing tensor bytes");return}let l=t.tensorShape[1],c=a.length/l;t.tensorShape[0]>c&&pc(`Showing the first ${c.toLocaleString()} of ${t.tensorShape[0].toLocaleString()} data points`),cct(a,l).then(u=>{o(new si(u))})},s.send()}function jO(n,t){N3(n).then(e=>{t(new si(e))})}function qO(n,t){KO(n).then(e=>t(e))}function XO(n,t,e=1e6,r=` +`){return new Promise((i,o)=>{let s=0,a=n.byteLength-1,l="";function c(h){s+=e;let p=h.split(r),d=l+p[0];if(p.length===1){l=d,u(s,e);return}l=p[p.length-1],t(d);for(let f=1;f=a){l&&t(l),i();return}u(s,e)}function u(h,p){let d=n.slice(h,h+p),f=new Blob([d]),m=new FileReader;m.onload=x=>c(x.target.result),m.readAsText(f)}u(s,e)})}function N3(n,t=" "){return ve("Parsing tensors...",Cs),new Promise((e,r)=>{let i=[],o;XO(n,s=>{if(s=s.trim(),s==="")return;let a=s.split(t),l={metadata:{},vector:null,index:i.length,projections:null};if(isNaN(a[0])||o===a.length-1?(l.metadata.label=a[0],l.vector=new Float32Array(a.slice(1).map(Number))):l.vector=new Float32Array(a.map(Number)),i.push(l),o==null&&(o=l.vector.length),o!==l.vector.length)throw We("Vector dimensions do not match","parsing tensors"),Error("Parsing failed");if(o<=1)throw We("Found a vector with only one dimension?","parsing tensors"),Error("Parsing failed")}).then(()=>{ve(null,Cs),e(i)})})}function cct(n,t){return Di("Parsing tensors...",()=>{let e=n.length/t,r=[],i=0;for(let o=0;o(ve(null,Cs),e))}function Gd(n,t){let e=n.map(i=>({name:i,isNumeric:!0,tooManyUniqueValues:!1,min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY})),r=n.map(()=>new Object);return t.forEach(i=>{n.forEach((o,s)=>{let a=e[s],l=r[s],c=i[o];c!=null&&(a.tooManyUniqueValues||(c in l?l[c]++:l[c]=1,Object.keys(l).length>lct&&(a.tooManyUniqueValues=!0)),isNaN(c)?a.isNumeric=!1:(i[o]=+c,a.min=Math.min(a.min,+c),a.max=Math.max(a.max,+c)))})}),e.forEach((i,o)=>{i.uniqueEntries=Object.keys(r[o]).map(s=>({label:s,count:r[o][s]}))}),e}function KO(n){return ve("Parsing metadata...",P3),new Promise((t,e)=>{let r=[],i=!1,o=0,s=["label"];XO(n,a=>{if(a.trim().length===0)return;if(o===0&&(i=a.indexOf(" ")>=0,i)){s=a.split(" "),o++;return}o++;let l=a.split(" "),c={};r.push(c),s.forEach((u,h)=>{let p=l[h];p=p===""?null:p,c[u]=p})}).then(()=>{ve(null,P3),t({stats:Gd(s,r),pointsInfo:r})})})}function uct(n){return new Promise((t,e)=>{let r=new Image;r.onload=()=>t(r),r.onerror=i=>e(i),r.crossOrigin="",r.src=n})}function xy(n,t,e,r){let i=Promise.resolve({});n&&(i=new Promise((a,l)=>{ve("Fetching metadata...",P3);let c=new XMLHttpRequest;c.open("GET",n),c.responseType="arraybuffer",c.onreadystatechange=()=>{if(c.readyState===4)if(c.status===200)a(KO(c.response));else{let u=new FileReader;u.onload=()=>{We(u.result,"fetching metadata"),l()},u.readAsText(new Blob([c.response]))}},c.send(null)}));let o=null,s=null;t&&(o=ve("Fetching sprite image..."),s=uct(t)),Promise.all([i,s]).then(a=>{o&&ve(null,o);let[l,c]=a;if(c&&(c.height>my||c.width>my))We(`Error: Sprite image of dimensions ${c.width}px x ${c.height}px exceeds maximum dimensions ${my}px x ${my}px`,"parsing sprite images");else{l.spriteImage=c,l.spriteMetadata=e;try{r(l)}catch(u){We(u.message,"parsing sprite metadata")}}})}var YO=".bytes",vy=class{constructor(t){this.projectorConfigPath=t}getEmbeddingInfo(t){let e=this.projectorConfig.embeddings;for(let r=0;r{let s=o.message;i.responseText!=null&&(s="Cannot fetch projector config, possibly a Cross-Origin request error."),We(s,"fetching projector config")},i.onload=()=>{let o=JSON.parse(i.responseText);ve(null,r),this.projectorConfig=o,e(o)},i.send()}retrieveTensor(t,e,r){var s;let i=this.getEmbeddingInfo(e),o=`${i.tensorPath}`;if(((s=i.tensorPath)==null?void 0:s.substr(-1*YO.length))===YO)gy(this,this.getEmbeddingInfo(e),t,e,o,r);else{ve("Fetching tensors...",Cs);let a=new XMLHttpRequest;a.open("GET",o),a.responseType="arraybuffer",a.onerror=()=>{We(a.responseText,"fetching tensors")},a.onload=()=>{N3(a.response).then(l=>{r(new si(l))})},a.send()}}retrieveSpriteAndMetadata(t,e,r){let i=this.getEmbeddingInfo(e),o=null;i.sprite&&i.sprite.imagePath&&(o=i.sprite.imagePath),xy(i.metadataPath,o,i.sprite,r)}getBookmarks(t,e,r){let i=this.getEmbeddingInfo(e),o=ve("Fetching bookmarks..."),s=new XMLHttpRequest;s.open("GET",i.bookmarksPath),s.onerror=a=>{We(s.responseText,"fetching bookmarks")},s.onload=()=>{let a=JSON.parse(s.responseText);ve(null,o),r(a)},s.send()}};var yy=class{constructor(t){this.dataProto=t}retrieveRuns(t){t(["proto"])}retrieveProjectorConfig(t,e){e({modelCheckpointPath:"proto",embeddings:[{tensorName:"proto",tensorShape:this.dataProto.shape,metadataPath:"proto"}]})}retrieveTensor(t,e,r){r(this.flatArrayToDataset(this.dataProto.tensor))}retrieveSpriteAndMetadata(t,e,r){let i=this.dataProto.metadata.columns.map(l=>l.name),o=this.dataProto.shape[0],s=new Array(o);this.dataProto.metadata.columns.forEach(l=>{let c=l.numericValues||l.stringValues;for(let u=0;u{let u=new Image;u.onload=()=>l(u),u.onerror=()=>c("Failed converting base64 to an image"),u.src=this.dataProto.metadata.sprite.imageBase64})),a.then(l=>{let c={stats:Gd(i,s),pointsInfo:s};l!=null&&(c.spriteImage=l,c.spriteMetadata={singleImageDim:this.dataProto.metadata.sprite.singleImageDim,imagePath:"proto"}),r(c)})}getBookmarks(t,e,r){return r([])}flatArrayToDataset(t){let e=[],r=this.dataProto.shape[0],i=this.dataProto.shape[1];if(r*i!==t.length)throw"The shape doesn't match the length of the flattened array";for(let o=0;o{let o=i.embeddings;for(let s=0;s{We(r.responseText,"fetching runs")},r.onload=()=>{let i=JSON.parse(r.responseText);ve(null,e),t(i)},r.send()}retrieveProjectorConfig(t,e){if(t in this.runProjectorConfigCache){e(this.runProjectorConfigCache[t]);return}let r=ve("Fetching projector config..."),i=new XMLHttpRequest;i.open("GET",`${this.routePrefix}/info?run=${t}`),i.onerror=o=>{We(i.responseText,"fetching projector config")},i.onload=()=>{let o=JSON.parse(i.responseText);ve(null,r),this.runProjectorConfigCache[t]=o,e(o)},i.send()}retrieveTensor(t,e,r){this.getEmbeddingInfo(t,e,i=>{gy(this,i,t,e,`${this.routePrefix}/tensor?run=${t}&name=${e}&num_rows=${ZO}`,r)})}retrieveSpriteAndMetadata(t,e,r){this.getEmbeddingInfo(t,e,i=>{let o=null;i.metadataPath&&(o=`${this.routePrefix}/metadata?run=${t}&name=${e}&num_rows=${ZO}`);let s=null;i.sprite&&i.sprite.imagePath&&(s=`${this.routePrefix}/sprite_image?run=${t}&name=${e}`),xy(o,s,i.sprite,r)})}getBookmarks(t,e,r){let i=ve("Fetching bookmarks..."),o=new XMLHttpRequest;o.open("GET",`${this.routePrefix}/bookmarks?run=${t}&name=${e}`),o.onerror=s=>{We(o.responseText,"fetching bookmarks")},o.onload=()=>{ve(null,i);let s=JSON.parse(o.responseText);r(s)},o.send()}};var _y=class{constructor(t,e,r,i,o,s,a){this.pointIndices=t,this.labelStrings=e,this.scaleFactors=r,this.useSceneOpacityFlags=i,this.defaultFontSize=o,this.fillColors=s,this.strokeColors=a}},_o;(function(n){n[n.Perspective=0]="Perspective",n[n.Orthographic=1]="Orthographic"})(_o||(_o={}));var wy=class{constructor(t,e,r,i,o,s,a,l,c,u,h,p,d,f){this.camera=t,this.cameraType=e,this.cameraTarget=r,this.screenWidth=i,this.screenHeight=o,this.nearestCameraSpacePointZ=s,this.farthestCameraSpacePointZ=a,this.backgroundColor=l,this.pointColors=c,this.pointScaleFactors=u,this.labels=h,this.polylineColors=p,this.polylineOpacities=d,this.polylineWidths=f}};var JO={type:"change"},L3={type:"start"},QO={type:"end"},Sy=class extends ii{constructor(t,e){super(),e===void 0&&console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.'),e===document&&console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'),this.object=t,this.domElement=e,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new j,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:cn.ROTATE,MIDDLE:cn.DOLLY,RIGHT:cn.PAN},this.touches={ONE:ka.ROTATE,TWO:ka.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return a.phi},this.getAzimuthalAngle=function(){return a.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(J){J.addEventListener("keydown",re),this._domElementKeyEvents=J},this.saveState=function(){r.target0.copy(r.target),r.position0.copy(r.object.position),r.zoom0=r.object.zoom},this.reset=function(){r.target.copy(r.target0),r.object.position.copy(r.position0),r.object.zoom=r.zoom0,r.object.updateProjectionMatrix(),r.dispatchEvent(JO),r.update(),o=i.NONE},this.update=function(){let J=new j,mt=new wn().setFromUnitVectors(t.up,new j(0,1,0)),It=mt.clone().invert(),Wt=new j,Q=new wn,Vt=2*Math.PI;return function(){let ee=r.object.position;J.copy(ee).sub(r.target),J.applyQuaternion(mt),a.setFromVector3(J),r.autoRotate&&o===i.NONE&&P(E()),r.enableDamping?(a.theta+=l.theta*r.dampingFactor,a.phi+=l.phi*r.dampingFactor):(a.theta+=l.theta,a.phi+=l.phi);let xt=r.minAzimuthAngle,jt=r.maxAzimuthAngle;return isFinite(xt)&&isFinite(jt)&&(xt<-Math.PI?xt+=Vt:xt>Math.PI&&(xt-=Vt),jt<-Math.PI?jt+=Vt:jt>Math.PI&&(jt-=Vt),xt<=jt?a.theta=Math.max(xt,Math.min(jt,a.theta)):a.theta=a.theta>(xt+jt)/2?Math.max(xt,a.theta):Math.min(jt,a.theta)),a.phi=Math.max(r.minPolarAngle,Math.min(r.maxPolarAngle,a.phi)),a.makeSafe(),a.radius*=c,a.radius=Math.max(r.minDistance,Math.min(r.maxDistance,a.radius)),r.enableDamping===!0?r.target.addScaledVector(u,r.dampingFactor):r.target.add(u),J.setFromSpherical(a),J.applyQuaternion(It),ee.copy(r.target).add(J),r.object.lookAt(r.target),r.enableDamping===!0?(l.theta*=1-r.dampingFactor,l.phi*=1-r.dampingFactor,u.multiplyScalar(1-r.dampingFactor)):(l.set(0,0,0),u.set(0,0,0)),c=1,h||Wt.distanceToSquared(r.object.position)>s||8*(1-Q.dot(r.object.quaternion))>s?(r.dispatchEvent(JO),Wt.copy(r.object.position),Q.copy(r.object.quaternion),h=!1,!0):!1}}(),this.dispose=function(){r.domElement.removeEventListener("contextmenu",ht),r.domElement.removeEventListener("pointerdown",ct),r.domElement.removeEventListener("pointercancel",Rt),r.domElement.removeEventListener("wheel",Zt),r.domElement.removeEventListener("pointermove",bt),r.domElement.removeEventListener("pointerup",gt),r._domElementKeyEvents!==null&&r._domElementKeyEvents.removeEventListener("keydown",re)};let r=this,i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},o=i.NONE,s=1e-6,a=new hd,l=new hd,c=1,u=new j,h=!1,p=new Mt,d=new Mt,f=new Mt,m=new Mt,x=new Mt,g=new Mt,v=new Mt,b=new Mt,y=new Mt,_=[],S={};function E(){return 2*Math.PI/60/60*r.autoRotateSpeed}function M(){return Math.pow(.95,r.zoomSpeed)}function P(J){l.theta-=J}function D(J){l.phi-=J}let w=function(){let J=new j;return function(It,Wt){J.setFromMatrixColumn(Wt,0),J.multiplyScalar(-It),u.add(J)}}(),I=function(){let J=new j;return function(It,Wt){r.screenSpacePanning===!0?J.setFromMatrixColumn(Wt,1):(J.setFromMatrixColumn(Wt,0),J.crossVectors(r.object.up,J)),J.multiplyScalar(It),u.add(J)}}(),N=function(){let J=new j;return function(It,Wt){let Q=r.domElement;if(r.object.isPerspectiveCamera){let Vt=r.object.position;J.copy(Vt).sub(r.target);let zt=J.length();zt*=Math.tan(r.object.fov/2*Math.PI/180),w(2*It*zt/Q.clientHeight,r.object.matrix),I(2*Wt*zt/Q.clientHeight,r.object.matrix)}else r.object.isOrthographicCamera?(w(It*(r.object.right-r.object.left)/r.object.zoom/Q.clientWidth,r.object.matrix),I(Wt*(r.object.top-r.object.bottom)/r.object.zoom/Q.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}}();function L(J){r.object.isPerspectiveCamera?c/=J:r.object.isOrthographicCamera?(r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom*J)),r.object.updateProjectionMatrix(),h=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function O(J){r.object.isPerspectiveCamera?c*=J:r.object.isOrthographicCamera?(r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/J)),r.object.updateProjectionMatrix(),h=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function z(J){p.set(J.clientX,J.clientY)}function V(J){v.set(J.clientX,J.clientY)}function $(J){m.set(J.clientX,J.clientY)}function X(J){d.set(J.clientX,J.clientY),f.subVectors(d,p).multiplyScalar(r.rotateSpeed);let mt=r.domElement;P(2*Math.PI*f.x/mt.clientHeight),D(2*Math.PI*f.y/mt.clientHeight),p.copy(d),r.update()}function W(J){b.set(J.clientX,J.clientY),y.subVectors(b,v),y.y>0?L(M()):y.y<0&&O(M()),v.copy(b),r.update()}function K(J){x.set(J.clientX,J.clientY),g.subVectors(x,m).multiplyScalar(r.panSpeed),N(g.x,g.y),m.copy(x),r.update()}function Z(J){J.deltaY<0?O(M()):J.deltaY>0&&L(M()),r.update()}function Y(J){let mt=!1;switch(J.code){case r.keys.UP:N(0,r.keyPanSpeed),mt=!0;break;case r.keys.BOTTOM:N(0,-r.keyPanSpeed),mt=!0;break;case r.keys.LEFT:N(r.keyPanSpeed,0),mt=!0;break;case r.keys.RIGHT:N(-r.keyPanSpeed,0),mt=!0;break}mt&&(J.preventDefault(),r.update())}function tt(){if(_.length===1)p.set(_[0].pageX,_[0].pageY);else{let J=.5*(_[0].pageX+_[1].pageX),mt=.5*(_[0].pageY+_[1].pageY);p.set(J,mt)}}function q(){if(_.length===1)m.set(_[0].pageX,_[0].pageY);else{let J=.5*(_[0].pageX+_[1].pageX),mt=.5*(_[0].pageY+_[1].pageY);m.set(J,mt)}}function et(){let J=_[0].pageX-_[1].pageX,mt=_[0].pageY-_[1].pageY,It=Math.sqrt(J*J+mt*mt);v.set(0,It)}function rt(){r.enableZoom&&et(),r.enablePan&&q()}function at(){r.enableZoom&&et(),r.enableRotate&&tt()}function nt(J){if(_.length==1)d.set(J.pageX,J.pageY);else{let It=Ht(J),Wt=.5*(J.pageX+It.x),Q=.5*(J.pageY+It.y);d.set(Wt,Q)}f.subVectors(d,p).multiplyScalar(r.rotateSpeed);let mt=r.domElement;P(2*Math.PI*f.x/mt.clientHeight),D(2*Math.PI*f.y/mt.clientHeight),p.copy(d)}function wt(J){if(_.length===1)x.set(J.pageX,J.pageY);else{let mt=Ht(J),It=.5*(J.pageX+mt.x),Wt=.5*(J.pageY+mt.y);x.set(It,Wt)}g.subVectors(x,m).multiplyScalar(r.panSpeed),N(g.x,g.y),m.copy(x)}function vt(J){let mt=Ht(J),It=J.pageX-mt.x,Wt=J.pageY-mt.y,Q=Math.sqrt(It*It+Wt*Wt);b.set(0,Q),y.set(0,Math.pow(b.y/v.y,r.zoomSpeed)),L(y.y),v.copy(b)}function it(J){r.enableZoom&&vt(J),r.enablePan&&wt(J)}function yt(J){r.enableZoom&&vt(J),r.enableRotate&&nt(J)}function ct(J){r.enabled!==!1&&(_.length===0&&(r.domElement.setPointerCapture(J.pointerId),r.domElement.addEventListener("pointermove",bt),r.domElement.addEventListener("pointerup",gt)),kt(J),J.pointerType==="touch"?G(J):Lt(J))}function bt(J){r.enabled!==!1&&(J.pointerType==="touch"?H(J):Yt(J))}function gt(J){Bt(J),_.length===0&&(r.domElement.releasePointerCapture(J.pointerId),r.domElement.removeEventListener("pointermove",bt),r.domElement.removeEventListener("pointerup",gt)),r.dispatchEvent(QO),o=i.NONE}function Rt(J){Bt(J)}function Lt(J){let mt;switch(J.button){case 0:mt=r.mouseButtons.LEFT;break;case 1:mt=r.mouseButtons.MIDDLE;break;case 2:mt=r.mouseButtons.RIGHT;break;default:mt=-1}switch(mt){case cn.DOLLY:if(r.enableZoom===!1)return;V(J),o=i.DOLLY;break;case cn.ROTATE:if(J.ctrlKey||J.metaKey||J.shiftKey){if(r.enablePan===!1)return;$(J),o=i.PAN}else{if(r.enableRotate===!1)return;z(J),o=i.ROTATE}break;case cn.PAN:if(J.ctrlKey||J.metaKey||J.shiftKey){if(r.enableRotate===!1)return;z(J),o=i.ROTATE}else{if(r.enablePan===!1)return;$(J),o=i.PAN}break;default:o=i.NONE}o!==i.NONE&&r.dispatchEvent(L3)}function Yt(J){if(r.enabled!==!1)switch(o){case i.ROTATE:if(r.enableRotate===!1)return;X(J);break;case i.DOLLY:if(r.enableZoom===!1)return;W(J);break;case i.PAN:if(r.enablePan===!1)return;K(J);break}}function Zt(J){r.enabled===!1||r.enableZoom===!1||o!==i.NONE||(J.preventDefault(),r.dispatchEvent(L3),Z(J),r.dispatchEvent(QO))}function re(J){r.enabled===!1||r.enablePan===!1||Y(J)}function G(J){switch(ft(J),_.length){case 1:switch(r.touches.ONE){case ka.ROTATE:if(r.enableRotate===!1)return;tt(),o=i.TOUCH_ROTATE;break;case ka.PAN:if(r.enablePan===!1)return;q(),o=i.TOUCH_PAN;break;default:o=i.NONE}break;case 2:switch(r.touches.TWO){case ka.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;rt(),o=i.TOUCH_DOLLY_PAN;break;case ka.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;at(),o=i.TOUCH_DOLLY_ROTATE;break;default:o=i.NONE}break;default:o=i.NONE}o!==i.NONE&&r.dispatchEvent(L3)}function H(J){switch(ft(J),o){case i.TOUCH_ROTATE:if(r.enableRotate===!1)return;nt(J),r.update();break;case i.TOUCH_PAN:if(r.enablePan===!1)return;wt(J),r.update();break;case i.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;it(J),r.update();break;case i.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;yt(J),r.update();break;default:o=i.NONE}}function ht(J){r.enabled!==!1&&J.preventDefault()}function kt(J){_.push(J)}function Bt(J){delete S[J.pointerId];for(let mt=0;mt<_.length;mt++)if(_[mt].pointerId==J.pointerId){_.splice(mt,1);return}}function ft(J){let mt=S[J.pointerId];mt===void 0&&(mt=new Mt,S[J.pointerId]=mt),mt.set(J.pageX,J.pageY)}function Ht(J){let mt=J.pointerId===_[0].pointerId?_[1]:_[0];return S[mt.pointerId]}r.domElement.addEventListener("contextmenu",ht),r.domElement.addEventListener("pointerdown",ct),r.domElement.addEventListener("pointercancel",Rt),r.domElement.addEventListener("wheel",Zt,{passive:!1}),this.update()}};var hct="#dddddd";var pct="#aaaaaa";var dct="10 5",Cy=class{constructor(t,e){this.svgElement=t.querySelector("#selector"),this.rectElement=document.createElementNS("http://www.w3.org/2000/svg","rect"),this.rectElement.style.stroke=pct,this.rectElement.style.strokeDasharray=dct,this.rectElement.style.strokeWidth=""+2,this.rectElement.style.fill=hct,this.rectElement.style.fillOpacity=""+.2,this.svgElement.appendChild(this.rectElement),this.selectionCallback=e,this.isMouseDown=!1}onMouseDown(t,e){this.isMouseDown=!0,this.svgElement.style.display="block",this.startCoordinates=[t,e],this.lastBoundingBox={x:this.startCoordinates[0],y:this.startCoordinates[1],width:1,height:1}}onMouseMove(t,e){!this.isMouseDown||(this.lastBoundingBox.x=Math.min(t,this.startCoordinates[0]),this.lastBoundingBox.y=Math.max(e,this.startCoordinates[1]),this.lastBoundingBox.width=Math.max(t,this.startCoordinates[0])-this.lastBoundingBox.x,this.lastBoundingBox.height=this.lastBoundingBox.y-Math.min(e,this.startCoordinates[1]),this.rectElement.setAttribute("x",""+this.lastBoundingBox.x),this.rectElement.setAttribute("y",""+(this.lastBoundingBox.y-this.lastBoundingBox.height)),this.rectElement.setAttribute("width",""+this.lastBoundingBox.width),this.rectElement.setAttribute("height",""+this.lastBoundingBox.height))}onMouseUp(){this.isMouseDown=!1,this.svgElement.style.display="none",this.rectElement.setAttribute("width","0"),this.rectElement.setAttribute("height","0"),this.selectionCallback(this.lastBoundingBox)}};var t7=16777215,i7=2,fct=5*i7,mct=.025*i7,gct=70,xct=.01,vct=100,My=1.2,e7=16,n7=17,r7=1,yct=7,wo;(function(n){n[n.AREA_SELECT=0]="AREA_SELECT",n[n.CAMERA_AND_CLICK_SELECT=1]="CAMERA_AND_CLICK_SELECT"})(wo||(wo={}));var Ey=class{constructor(){this.orthographic=!1}},Ty=class{constructor(t,e){this.container=t,this.projectorEventContext=e,this.START_CAMERA_POS_3D=new j(.45,.9,1.6),this.START_CAMERA_TARGET_3D=new j(0,0,0),this.START_CAMERA_POS_2D=new j(0,0,4),this.START_CAMERA_TARGET_2D=new j(0,0,0),this.visualizers=[],this.onCameraMoveListeners=[],this.backgroundColor=t7,this.dimensionality=3,this.cameraDef=null,this.orbitAnimationOnNextCameraCreation=!1,this.selecting=!1,this.mouseIsDown=!1,this.isDragSequence=!1,this.getLayoutValues(),this.scene=new jc,this.renderer=new Ie({alpha:!0,premultipliedAlpha:!1,antialias:!1}),this.renderer.setClearColor(t7,1),this.container.appendChild(this.renderer.domElement),this.light=new ld(16772287,1,0),this.scene.add(this.light),this.setDimensions(3),this.recreateCamera(this.makeDefaultCameraDef(this.dimensionality)),this.renderer.render(this.scene,this.camera),this.rectangleSelector=new Cy(this.container,r=>this.selectBoundingBox(r)),this.addInteractionListeners()}addInteractionListeners(){this.container.addEventListener("mousemove",this.onMouseMove.bind(this)),this.container.addEventListener("mousedown",this.onMouseDown.bind(this)),this.container.addEventListener("mouseup",this.onMouseUp.bind(this)),this.container.addEventListener("click",this.onClick.bind(this)),window.addEventListener("keydown",this.onKeyDown.bind(this),!1),window.addEventListener("keyup",this.onKeyUp.bind(this),!1)}addCameraControlsEventListeners(t){t.addEventListener("start",()=>{this.stopOrbitAnimation(),this.onCameraMoveListeners.forEach(e=>e(this.camera.position,t.target))}),t.addEventListener("change",()=>{this.render()}),t.addEventListener("end",()=>{})}makeOrbitControls(t,e,r){this.orbitCameraControls!=null&&this.orbitCameraControls.dispose();let i=new Sy(t,this.renderer.domElement);i.target0=new j(e.target[0],e.target[1],e.target[2]),i.position0=new j().copy(t.position),i.zoom0=e.zoom,i.enableRotate=r,i.autoRotate=!1,i.rotateSpeed=r7,r?(i.mouseButtons.ORBIT=cn.LEFT,i.mouseButtons.PAN=cn.RIGHT):(i.mouseButtons.ORBIT=null,i.mouseButtons.PAN=cn.LEFT),i.reset(),this.camera=t,this.orbitCameraControls=i,this.addCameraControlsEventListeners(this.orbitCameraControls)}makeCamera3D(t,e,r){let i;{let o=e/r;i=new ln(gct,o,xct,vct),i.position.set(t.position[0],t.position[1],t.position[2]);let s=new j(t.target[0],t.target[1],t.target[2]);i.lookAt(s),i.zoom=t.zoom,i.updateProjectionMatrix()}this.camera=i,this.makeOrbitControls(i,t,!0)}makeCamera2D(t,e,r){let i,o=new j(t.target[0],t.target[1],t.target[2]);{let s=e/r,a=-My,l=My,c=-My,u=My;s>1?(a*=s,l*=s):(u/=s,c/=s),i=new Sa(a,l,u,c,-1e3,1e3),i.position.set(t.position[0],t.position[1],t.position[2]),i.up=new j(0,1,0),i.lookAt(o),i.zoom=t.zoom,i.updateProjectionMatrix()}this.camera=i,this.makeOrbitControls(i,t,!1)}makeDefaultCameraDef(t){let e=new Ey;return e.orthographic=t===2,e.zoom=1,e.orthographic?(e.position=[this.START_CAMERA_POS_2D.x,this.START_CAMERA_POS_2D.y,this.START_CAMERA_POS_2D.z],e.target=[this.START_CAMERA_TARGET_2D.x,this.START_CAMERA_TARGET_2D.y,this.START_CAMERA_TARGET_2D.z]):(e.position=[this.START_CAMERA_POS_3D.x,this.START_CAMERA_POS_3D.y,this.START_CAMERA_POS_3D.z],e.target=[this.START_CAMERA_TARGET_3D.x,this.START_CAMERA_TARGET_3D.y,this.START_CAMERA_TARGET_3D.z]),e}recreateCamera(t){t.orthographic?this.makeCamera2D(t,this.width,this.height):this.makeCamera3D(t,this.width,this.height),this.orbitCameraControls.minDistance=mct,this.orbitCameraControls.maxDistance=fct,this.orbitCameraControls.update(),this.orbitAnimationOnNextCameraCreation&&this.startOrbitAnimation()}onClick(t,e=!0){if(!(t&&this.selecting)){if(!this.isDragSequence&&e){let r=this.nearestPoint!=null?[this.nearestPoint]:[];this.projectorEventContext.notifySelectionChanged(r)}this.isDragSequence=!1,this.render()}}onMouseDown(t){this.isDragSequence=!1,this.mouseIsDown=!0,this.selecting?(this.orbitCameraControls.enabled=!1,this.rectangleSelector.onMouseDown(t.offsetX,t.offsetY),this.setNearestPointToMouse(t)):!t.ctrlKey&&this.sceneIs3D()&&this.orbitCameraControls.mouseButtons.ORBIT===cn.RIGHT?(this.orbitCameraControls.mouseButtons.ORBIT=cn.LEFT,this.orbitCameraControls.mouseButtons.PAN=cn.RIGHT):t.ctrlKey&&this.sceneIs3D()&&this.orbitCameraControls.mouseButtons.ORBIT===cn.LEFT&&(this.orbitCameraControls.mouseButtons.ORBIT=cn.RIGHT,this.orbitCameraControls.mouseButtons.PAN=cn.LEFT)}onMouseUp(t){(this.selecting||!this.orbitCameraControls.enabled)&&(this.orbitCameraControls.enabled=!0,this.rectangleSelector.onMouseUp(),this.render()),this.mouseIsDown=!1}onMouseMove(t){this.isDragSequence=this.mouseIsDown,this.selecting&&this.mouseIsDown?(this.rectangleSelector.onMouseMove(t.offsetX,t.offsetY),this.render()):this.mouseIsDown||(this.setNearestPointToMouse(t),this.projectorEventContext.notifyHoverOverPoint(this.nearestPoint))}onKeyDown(t){t.keyCode===n7&&this.sceneIs3D()&&(this.orbitCameraControls.mouseButtons.ORBIT=cn.RIGHT,this.orbitCameraControls.mouseButtons.PAN=cn.LEFT),t.keyCode===e7&&(this.selecting=!0,this.container.style.cursor="crosshair")}onKeyUp(t){t.keyCode===n7&&this.sceneIs3D()&&(this.orbitCameraControls.mouseButtons.ORBIT=cn.LEFT,this.orbitCameraControls.mouseButtons.PAN=cn.RIGHT),t.keyCode===e7&&(this.selecting=this.getMouseMode()===wo.AREA_SELECT,this.selecting||(this.container.style.cursor="default"),this.render())}getPointIndicesFromPickingTexture(t){if(this.worldSpacePointPositions==null)return null;let e=this.worldSpacePointPositions.length/3,r=window.devicePixelRatio||1,i=Math.floor(t.x*r),o=Math.floor(t.y*r),s=Math.floor(t.width*r),a=Math.floor(t.height*r),l=new Uint8Array(s*a*4);this.renderer.readRenderTargetPixels(this.pickingTexture,i,this.pickingTexture.height-o,s,a,l);let c=new Uint8Array(this.worldSpacePointPositions.length);for(let h=0;hthis.updateOrbitAnimation())}stopOrbitAnimation(){this.orbitCameraControls.autoRotate=!1,this.orbitCameraControls.rotateSpeed=r7,this.orbitAnimationId!=null&&(cancelAnimationFrame(this.orbitAnimationId),this.orbitAnimationId=null)}addVisualizer(t){this.scene&&t.setScene(this.scene),t.onResize(this.width,this.height),t.onPointPositionsChanged(this.worldSpacePointPositions),this.visualizers.push(t)}removeAllVisualizers(){this.visualizers.forEach(t=>t.dispose()),this.visualizers=[]}setPointPositions(t){this.worldSpacePointPositions=t,this.visualizers.forEach(e=>e.onPointPositionsChanged(t))}render(){{let i=this.camera.position.clone();i.x+=1,i.y+=1,this.light.position.set(i.x,i.y,i.z)}let t=this.camera instanceof ln?_o.Perspective:_o.Orthographic,e=[0,0];this.worldSpacePointPositions!=null&&(e=dF(this.worldSpacePointPositions,this.camera.position,this.orbitCameraControls.target));let r=new wy(this.camera,t,this.orbitCameraControls.target,this.width,this.height,e[0],e[1],this.backgroundColor,this.pointColors,this.pointScaleFactors,this.labels,this.polylineColors,this.polylineOpacities,this.polylineWidths);this.visualizers.forEach(i=>i.onPickingRender(r));{let i=this.remove3dAxisFromScene();this.pickingTexture?this.renderer.setRenderTarget(this.pickingTexture):this.renderer.setRenderTarget(null),this.renderer.render(this.scene,this.camera),this.renderer.setRenderTarget(null),i!=null&&this.scene.add(i)}this.visualizers.forEach(i=>i.onRender(r)),this.renderer.render(this.scene,this.camera)}setMouseMode(t){this.mouseMode=t,t===wo.AREA_SELECT?(this.selecting=!0,this.container.style.cursor="crosshair"):(this.selecting=!1,this.container.style.cursor="default")}setPointColors(t){this.pointColors=t}setPointScaleFactors(t){this.pointScaleFactors=t}setLabels(t){this.labels=t}setPolylineColors(t){this.polylineColors=t}setPolylineOpacities(t){this.polylineOpacities=t}setPolylineWidths(t){this.polylineWidths=t}getMouseMode(){return this.mouseMode}resetZoom(){this.recreateCamera(this.makeDefaultCameraDef(this.dimensionality)),this.render()}setDayNightMode(t){let e=this.container.querySelectorAll("canvas"),r=t?"invert(100%)":null;for(let i=0;ia.onResize(i,o)),t&&this.render()}onCameraMove(t){this.onCameraMoveListeners.push(t)}clickOnPoint(t){this.nearestPoint=t,this.onClick(void 0,!1)}};var qd=80,bct=1/qd,_ct=2.2,wct="black",Sct="white",D3=8192,z3=256,ai=3,jd=3,o7=2,sr=2*3,Cct=` + attribute vec2 posObj; + attribute vec3 color; + varying vec2 vUv; + varying vec3 vColor; + + void main() { + vUv = uv; + vColor = color; + + // Rotate label to face camera. + + vec4 vRight = vec4( + modelViewMatrix[0][0], modelViewMatrix[1][0], modelViewMatrix[2][0], 0); + + vec4 vUp = vec4( + modelViewMatrix[0][1], modelViewMatrix[1][1], modelViewMatrix[2][1], 0); + + vec4 vAt = -vec4( + modelViewMatrix[0][2], modelViewMatrix[1][2], modelViewMatrix[2][2], 0); + + mat4 pointToCamera = mat4(vRight, vUp, vAt, vec4(0, 0, 0, 1)); + + vec2 scaledPos = posObj * ${bct} * ${_ct}; + + vec4 posRotated = pointToCamera * vec4(scaledPos, 0, 1); + vec4 mvPosition = modelViewMatrix * (vec4(position, 0) + posRotated); + gl_Position = projectionMatrix * mvPosition; + }`,Mct=` + uniform sampler2D shaderTexture; + uniform bool picking; + varying vec2 vUv; + varying vec3 vColor; + + void main() { + if (picking) { + gl_FragColor = vec4(vColor, 1.0); + } else { + vec4 fromTexture = texture2D(shaderTexture, vUv); + gl_FragColor = vec4(vColor, 1.0) * fromTexture; + } + }`,Ay=class{createGlyphTexture(){let t=document.createElement("canvas");t.width=D3,t.height=qd;let e=t.getContext("2d");e&&(e.font="bold "+qd*.75+"px roboto",e.textBaseline="top",e.fillStyle=Sct,e.rect(0,0,t.width,t.height),e.fill(),e.fillStyle=wct);let r=e==null?void 0:e.measureText(" ").width,i=new Float32Array(z3),o=new Float32Array(z3),s=0;for(let l=0;l{this.pickingColors[ai*i]=r.r,this.pickingColors[ai*i+1]=r.g,this.pickingColors[ai*i+2]=r.b,this.renderColors[ai*i]=1,this.renderColors[ai*i+1]=1,this.renderColors[ai*i+2]=1})}}createLabels(){if(this.labelStrings==null||this.worldSpacePointPositions==null)return;let t=this.worldSpacePointPositions.length/jd;if(t!==this.labelStrings.length)return;this.glyphTexture=this.createGlyphTexture(),this.uniforms={shaderTexture:{type:"t"},picking:{type:"bool"}},this.material=new ur({uniforms:this.uniforms,transparent:!0,vertexShader:Cct,fragmentShader:Mct}),this.processLabelVerts(t),this.createColorBuffers(t);let e=new Float32Array(this.totalVertexCount*jd);this.positions=new se(e,jd);let r=new Float32Array(this.totalVertexCount*jd),i=new Float32Array(this.totalVertexCount*o7),o=new Float32Array(this.totalVertexCount*ai),s=new se(r,2),a=new se(i,o7),l=new se(o,ai);this.geometry=new _e,this.geometry.setAttribute("posObj",s),this.geometry.setAttribute("position",this.positions),this.geometry.setAttribute("uv",a),this.geometry.setAttribute("color",l);let c=0;for(let u=0;u{this.positions.setXYZ(p,h.x,h.y,h.z)})}this.labelsMesh=new Ln(this.geometry,this.material),this.labelsMesh.frustumCulled=!1,this.scene.add(this.labelsMesh)}colorLabels(t){if(this.labelStrings==null||this.geometry==null||t==null)return;let e=new se(this.renderColors,3);this.geometry.setAttribute("color",e);let r=t.length/jd,i=0;for(let o=0;oe.hiX||t.loY>e.hiY||t.hiXthis.bound.hiX||t.hiYthis.bound.hiY)return!1;let r=this.getCellX(t.loX),i=this.getCellX(t.hiX),o=this.getCellY(t.loY),s=this.getCellY(t.hiY),a=o*this.numHorizCells+r,l=a;for(let c=o;c<=s;c++){for(let u=r;u<=i;u++){let h=this.grid[l++];if(h){for(let p=0;p 0.0) && (p_in_v1_v2 > 0.0); + } + + bool point_in_unit_square(vec2 spriteCoord) { + return true; + } +`;function Pct(){return` + varying vec2 xyIndex; + varying vec3 vColor; + + uniform sampler2D spriteTexture; + uniform float spritesPerRow; + uniform float spritesPerColumn; + uniform bool isImage; + + ${ue.common} + ${ue.fog_pars_fragment} + ${h7} + + void main() { + if (isImage) { + // Coordinates of the vertex within the entire sprite image. + vec2 coords = + (gl_PointCoord + xyIndex) / vec2(spritesPerRow, spritesPerColumn); + if (texture2D(spriteTexture, coords).a==0.0) { + discard; + } + gl_FragColor = vec4(vColor, 1.0) * texture2D(spriteTexture, coords); + } else { + bool inside = point_in_unit_circle(gl_PointCoord); + if (!inside) { + discard; + } + gl_FragColor = vec4(vColor, 1); + } + ${ue.fog_fragment} + }`}var Nct=` + varying vec2 xyIndex; + varying vec3 vColor; + uniform bool isImage; + + ${h7} + + void main() { + xyIndex; // Silence 'unused variable' warning. + if (isImage) { + gl_FragColor = vec4(vColor, 1); + } else { + bool inside = point_in_unit_circle(gl_PointCoord); + if (!inside) { + discard; + } + gl_FragColor = vec4(vColor, 1); + } + }`,Ny=class{constructor(){this.VERTEX_SHADER=Rct(),this.FRAGMENT_SHADER=Pct(),this.texture=null,this.standinTextureForPoints=fd(document.createElement("canvas")),this.renderMaterial=this.createRenderMaterial(!1),this.pickingMaterial=this.createPickingMaterial(!1)}createTextureFromSpriteAtlas(t,e,r){this.texture=fd(t),this.spritesPerRow=t.width/e[0],this.spritesPerColumn=t.height/e[1],this.spriteDimensions=e,this.spriteIndexBufferAttribute=new se(r,u7),this.points!=null&&this.points.geometry.setAttribute("spriteIndex",this.spriteIndexBufferAttribute)}createUniforms(){return{spriteTexture:{type:"t"},spritesPerRow:{type:"f"},spritesPerColumn:{type:"f"},fogColor:{type:"c"},fogNear:{type:"f"},fogFar:{type:"f"},isImage:{type:"bool"},sizeAttenuation:{type:"bool"},pointSize:{type:"f"}}}createRenderMaterial(t){let e=this.createUniforms();return new ur({uniforms:e,vertexShader:this.VERTEX_SHADER,fragmentShader:this.FRAGMENT_SHADER,transparent:!t,depthTest:t,depthWrite:t,fog:!0,blending:is})}createPickingMaterial(t){let e=this.createUniforms();return new ur({uniforms:e,vertexShader:this.VERTEX_SHADER,fragmentShader:Nct,transparent:!0,depthTest:!0,depthWrite:!0,fog:!1,blending:is})}createPointSprites(t,e){let r=e!=null?e.length/Py:0,i=this.createGeometry(r);this.fog=new Ca(16777215),this.points=new Jp(i,this.renderMaterial),this.points.frustumCulled=!1,this.spriteIndexBufferAttribute!=null&&this.points.geometry.setAttribute("spriteIndex",this.spriteIndexBufferAttribute),t.add(this.points)}calculatePointSize(t){if(this.texture!=null)return t?kct:this.spriteDimensions[0];let e=this.worldSpacePointPositions!=null?this.worldSpacePointPositions.length/Py:1,r=200,i=8,o=1.5,s=r/Math.log(e)/Math.log(i);return t?s:s/o}createGeometry(t){let e=t;this.pickingColors=new Float32Array(e*c7);{let i=0;for(let o=0;o{this.projection=r,this.updateScatterPlotWithNewProjection(r)}),e.registerSelectionChangedListener((r,i)=>{this.selectedPointIndices=r,this.neighborsOfFirstSelectedPoint=i,this.updateScatterPlotPositions(),this.updateScatterPlotAttributes(),this.scatterPlot.render()}),e.registerHoverListener(r=>{this.hoverPointIndex=r,this.updateScatterPlotAttributes(),this.scatterPlot.render()}),e.registerDistanceMetricChangedListener(r=>{this.distanceMetric=r,this.updateScatterPlotAttributes(),this.scatterPlot.render()}),this.createVisualizers(!1)}notifyProjectionPositionsUpdated(){this.updateScatterPlotPositions(),this.scatterPlot.render()}setDataSet(t){if(this.projection!=null&&(this.projection.dataSet=t),this.polylineVisualizer!=null&&this.polylineVisualizer.setDataSet(t),this.labels3DVisualizer!=null&&this.labels3DVisualizer.setLabelStrings(this.generate3DLabelsArray(t,this.labelPointAccessor)),this.spriteVisualizer==null||(this.spriteVisualizer.clearSpriteAtlas(),t==null||t.spriteAndMetadataInfo==null))return;let e=t.spriteAndMetadataInfo;if(e.spriteImage==null||e.spriteMetadata==null)return;let r=t.points.length,i=new Float32Array(r);for(let o=0;ot.points[p].projections[e[0]]),c=Na(t.points,(h,p)=>t.points[p].projections[e[1]]),u=[-f7/2,f7/2];if(r.domain(l).range(u),i.domain(c).range(u),e[2]!=null){let h=Na(t.points,(p,d)=>t.points[d].projections[e[2]]);o=Vi(),o.domain(h).range(u)}}let s=new Float32Array(t.points.length*3),a=0;return t.points.forEach((l,c)=>{s[a++]=r(t.points[c].projections[e[0]]),s[a++]=i(t.points[c].projections[e[1]]),s[a++]=0}),o&&(a=2,t.points.forEach((l,c)=>{s[a]=o(t.points[c].projections[e[2]]),a+=3})),s}generateVisibleLabelRenderParams(t,e,r,i){if(t==null)return null;let o=e==null?0:e.length,s=r==null?0:r.length,a=o+s+(i!=null?1:0),l=new Uint32Array(a),c=new Float32Array(a),u=new Int8Array(a),h=new Uint8Array(a*3),p=new Uint8Array(a*3),d=[];c.fill(Dct),u.fill(1);let f=0;if(i!=null){d.push(this.getLabelText(t,i,this.labelPointAccessor)),l[f]=i,c[f]=p7,u[f]=0;let m=mu(Fct);fu(h,f,m[0],m[1],m[2]);let x=mu(Vct);fu(p,f,x[0],x[1],x[1]),++f}{let m=o,x=mu(zct),g=mu(Bct);for(let v=0;v0){r.fill(aut);let o=t.points[e[0]].sequenceIndex;r[o]=out}else r.fill(rut);return r}generateLineSegmentWidthArray(t,e){if(t==null)return new Float32Array(0);let r=new Float32Array(t.sequences.length);if(r.fill(iut),(e==null?0:e.length)>0){let o=t.points[e[0]].sequenceIndex;r[o]=sut}return r}generatePointColorArray(t,e,r,i,o,s,a,l){if(t==null)return new Float32Array(0);let c=i==null?0:i.length,u=o==null?0:o.length,h=new Float32Array(t.points.length*3),p=$ct,d=Uct;a&&(p=Yct,d=Zct),l&&(p=Jct,d=Qct);{let f=t.points.length,m=0;if(c>0){let x=new Pt(p);for(let g=0;g0?o[0].dist:0;for(let x=0;x + + + +
+ + + +
+ + + + +
+ + + + +
+
+
+
+`;var xu=class extends Ke(Ae){constructor(){super(...arguments),this.hasStates=!1}ready(){super.ready(),this.savedStates=[],this.setupUploadButton(),this.ignoreNextProjectionEvent=!1,this.expandLessButton=this.$$("#expand-less"),this.expandMoreButton=this.$$("#expand-more")}initialize(t,e){this.projector=t,e.registerProjectionChangedListener(()=>{this.ignoreNextProjectionEvent?this.ignoreNextProjectionEvent=!1:this.clearStateSelection()})}setSelectedTensor(t,e,r){this.addStates(),e&&e.bookmarksPath?r.getBookmarks(t,e.tensorName,i=>{this.addStates(i),this._expandMore()}):this._expandLess()}_expandMore(){this.$.panel.show(),this.expandMoreButton.style.display="none",this.expandLessButton.style.display=""}_expandLess(){this.$.panel.hide(),this.expandMoreButton.style.display="",this.expandLessButton.style.display="none"}_addBookmark(){let t=this.projector.getCurrentState();t.label="State "+this.savedStates.length,t.isSelected=!0,this.selectedState=this.savedStates.length;for(let e=0;e{var i;let e=(i=t.files)==null?void 0:i[0];t.value="";let r=new FileReader;r.onload=o=>{let s=r.result,a=JSON.parse(s);this.savedStatesValid(a)?(this.addStates(a),this.loadSavedState(0)):pc(`Unable to load bookmarks: wrong dataset, expected dataset with shape (${a[0].dataSetDimensions}).`)},r.readAsText(e)}}addStates(t){if(t==null)this.savedStates=[];else for(let e=0;e + + `;Et([Dt({type:String}),_t("design:type",String)],vu.prototype,"value",void 0);Et([Dt({type:String}),_t("design:type",String)],vu.prototype,"delimiterPattern",void 0);Et([kM("value","delimiterPattern"),_t("design:type",Array),_t("design:paramtypes",[])],vu.prototype,"_parts",null);vu=Et([Xe("tf-wbr-string")],vu);var x7=dt` + + +
DATA
+
+ + + + + +
+
+ + + + + + + + + + + + +
+
+ Use categorical coloring + + + For metadata fields that have many unique values we use a gradient + color map by default. This checkbox allows you to force categorical + coloring by a given metadata field. + +
+ +
+ +
+ + + Load data from your computer + + Load + + + + Publish your embedding visualization and data + + Publish + + + + Download the metadata with applied modifications + + Download + + + + + Label selected metadata + + Label + +
+
+ +

Load data from your computer

+ +
+
+
+ Step 1: Load a TSV file of + vectors. +
+
+
+
+ Example of 3 vectors with dimension 4: +
+ 0.1\t0.2\t0.5\t0.9
+ 0.2\t0.1\t5.0\t0.2
+ 0.4\t0.1\t7.0\t0.8 +
+
+
+ Choose file + +
+
+
+
+
+
+ Step 2 (optional): + Load a TSV file of metadata. +
+
+
+
+ Example of 3 data points and 2 columns.
+ Note: If there is more than one column, the first row will be + parsed as column labels. +
+ Pokémon\tSpecies
+ Wartortle\tTurtle
+ Venusaur\tSeed
+ Charmeleon\tFlame +
+
+
+ Choose file + +
+
+
+
+
Click outside to dismiss.
+
+ +

Publish your embedding visualization and data

+ +
+

+ If you'd like to share your visualization with the world, follow + these simple steps. See + this tutorial + for more. +

+

Step 1: Make data public

+

+ Host tensors, metadata, sprite image, and bookmarks TSV files + publicly on the web. +

+

+ One option is using a + github gist. If you choose this approach, make sure to link directly to the + raw file. +

+
+
+

Step 2: Projector config

+
+ Optional: +
+ Metadata +
+
+ Sprite +
+
+ Bookmarks +
+
+
+ +
+

+ Step 3: Host projector config +

+ After you have hosted the projector config JSON file you built + above, paste the URL to the config below. +
+ + + +
+
Click outside to dismiss.
+
+
+ + Spherize data + + + + The data is normalized by shifting each point by the centroid and making + it unit norm. + +
+ + + + + + + + + +
Checkpoint: + + + +
Metadata: + + + +
+
+
+`;var Xd=class extends Ke(Ae){_renderInfoChanged(){var t;this.renderInfo!=null&&(t=this.renderInfo.thresholds)!=null&&t.length&&this.async(()=>this.setupLinearGradient(),150)}_getLastThreshold(){var t;if(!(this.renderInfo==null||!((t=this.renderInfo.thresholds)!=null&&t.length)))return this.renderInfo.thresholds[this.renderInfo.thresholds.length-1].value}getOffset(t){let e=this.renderInfo.thresholds[0].value,r=this.renderInfo.thresholds[this.renderInfo.thresholds.length-1].value;return(100*(t-e)/(r-e)).toFixed(2)+"%"}setupLinearGradient(){let t=this.$$("#gradient"),e=this.$$("svg.gradient").clientWidth;this.$$("svg.gradient rect").style.width=e+"px",t.textContent="",this.renderInfo.thresholds.forEach(r=>{let i=document.createElementNS("http://www.w3.org/2000/svg","stop");i.setAttribute("offset",this.getOffset(r.value)),i.setAttribute("stop-color",r.color),t.appendChild(i)})}};Xd.template=dt` + + + + + + + `;Et([Dt({type:Object}),_t("design:type",Object)],Xd.prototype,"renderInfo",void 0);Et([En("renderInfo"),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Xd.prototype,"_renderInfoChanged",null);Xd=Et([Xe("vz-projector-legend")],Xd);var tn=class extends Ke(Ae){constructor(){super(...arguments),this.metadataEditorInputLabel="Tag selection as",this.superviseInputLabel="Ignored label",this.showSuperviseSettings=!1,this._wordDelimiter="[/=_,-]",this.forceCategoricalColoring=!1}ready(){super.ready(),this.normalizeData=!0,this.superviseInputSelected=""}initialize(t,e){var i;this.projector=t,this.dataProvider=e,this.setupUploadButtons(),(i=this.$$("#normalize-data-checkbox"))==null||i.addEventListener("change",()=>{this.projector.setNormalizeData(this.normalizeData)});let r=this.$$("#force-categorical-checkbox");r==null||r.addEventListener("change",()=>{this.setForceCategoricalColoring(r.checked)}),this.dataProvider.retrieveRuns(o=>{this.runNames=o,this.runNames.length>0&&(this.selectedRun!=o[0]?this.selectedRun=o[0]:this._generateUiForNewCheckpointForRun(this.selectedRun))})}setForceCategoricalColoring(t){this.forceCategoricalColoring=t,this.$$("#force-categorical-checkbox").checked=this.forceCategoricalColoring,this.updateMetadataUI(this.spriteAndMetadata.stats,this.metadataFile),this._selectedColorOptionNameChanged()}getSeparatorClass(t){return t?"separator":null}metadataChanged(t,e){this.spriteAndMetadata=t,e!=null&&(this.metadataFile=e),this.updateMetadataUI(this.spriteAndMetadata.stats,this.metadataFile),(this.selectedColorOptionName==null||this.colorOptions.filter(i=>i.name===this.selectedColorOptionName).length===0)&&(this.selectedColorOptionName=this.colorOptions[0].name);let r=-1;t.stats&&(this.metadataFields=t.stats.map((i,o)=>(!i.isNumeric&&r===-1&&(r=o),i.name))),(this.metadataEditorColumn==null||this.metadataFields.filter(i=>i===this.metadataEditorColumn).length===0)&&(this.metadataEditorColumn=this.metadataFields[Math.max(0,r)]),(this.superviseColumn==null||this.metadataFields.filter(i=>i===this.superviseColumn).length===0)&&(this.superviseColumn=this.metadataFields[Math.max(0,r)],this.superviseInput=""),this.superviseInputChange()}projectionChanged(t){if(t)switch(t.projectionType){case"tsne":this.set("showSuperviseSettings",!0);break;default:this.set("showSuperviseSettings",!1)}}onProjectorSelectionChanged(t,e){this.selectedPointIndices=t,this.neighborsOfFirstPoint=e,this.metadataEditorInputChange()}updateMetadataUI(t,e){let r=-1;this.labelOptions=t.map((s,a)=>(!s.isNumeric&&r===-1&&(r=a),s.name)),(this.selectedLabelOption==null||this.labelOptions.filter(s=>s===this.selectedLabelOption).length===0)&&(this.selectedLabelOption=this.labelOptions[Math.max(0,r)]),(this.metadataEditorColumn==null||this.labelOptions.filter(s=>s===this.metadataEditorColumn).length===0)&&(this.metadataEditorColumn=this.labelOptions[Math.max(0,r)]);let i=[{name:"No color map"}],o=t.filter(s=>!s.tooManyUniqueValues||s.isNumeric).map(s=>{var p;let a,l=[],c=[],u=this.forceCategoricalColoring||!s.tooManyUniqueValues,h;if(u){let d=cu(b3),f=d.range(),m=f.map((g,v)=>{let b=v*3%f.length;return f[b]});l=s.uniqueEntries,d.range(m).domain(l.map(g=>g.label)),a=d;let x=(p=s.uniqueEntries)==null?void 0:p.length;h=`${x} ${x>f.length?" non-unique":""} colors`}else c=[{color:"#ffffdd",value:s.min},{color:"#1f2d86",value:s.max}],a=Vi().domain(c.map(d=>d.value)).range(c.map(d=>d.color)),h="gradient";return{name:s.name,desc:h,map:a,items:l,thresholds:c,tooManyUniqueValues:s.tooManyUniqueValues}});o.length>0&&i.push({name:"Metadata",isSeparator:!0}),this.colorOptions=i.concat(o)}metadataEditorContext(t){this.metadataEditorButtonDisabled=!t,this.projector&&this.projector.metadataEditorContext(t,this.metadataEditorColumn)}metadataEditorInputChange(){var i;let t=this.metadataEditorColumn,e=this.metadataEditorInput,r=this.selectedPointIndices.length+this.neighborsOfFirstPoint.length;r>0?e!=null&&e.trim()!==""?((i=this.spriteAndMetadata.stats)==null?void 0:i.filter(o=>o.name===t)[0].isNumeric)&&isNaN(+e)?(this.metadataEditorInputLabel="Label must be numeric",this.metadataEditorContext(!1)):(this.projector.dataSet.points.filter(s=>s.metadata[t].toString()===e.trim()).length===0?this.metadataEditorInputLabel=`Tag ${r} with new label`:this.metadataEditorInputLabel=`Tag ${r} points as`,this.metadataEditorContext(!0)):(this.metadataEditorInputLabel="Tag selection as",this.metadataEditorContext(!1)):(this.metadataEditorContext(!1),e!=null&&e.trim()!==""?this.metadataEditorInputLabel="Select points to tag":this.metadataEditorInputLabel="Tag selection as")}metadataEditorInputKeydown(t){t.keyCode===13&&this.metadataEditorButtonClicked(),t.stopPropagation()}metadataEditorColumnChange(){this.metadataEditorInputChange()}metadataEditorButtonClicked(){if(!this.metadataEditorButtonDisabled){let t=this.metadataEditorInput.trim(),e=this.selectedPointIndices.length+this.neighborsOfFirstPoint.length;this.projector.metadataEdit(this.metadataEditorColumn,t),this.projector.metadataEditorContext(!0,this.metadataEditorColumn),this.metadataEditorInputLabel=`${e} labeled as '${t}'`}}downloadMetadataClicked(){if(this.projector&&this.projector.dataSet&&this.projector.dataSet.spriteAndMetadataInfo){let t=this.projector.dataSet.spriteAndMetadataInfo.stats.map(i=>i.name).join(" ");this.projector.dataSet.spriteAndMetadataInfo.pointsInfo.forEach(i=>{let o=[];for(let s in i)o.push(i[s]);t+=` +`+o.join(" ")});let e=new Blob([t],{type:"text/plain"}),r=this.$.downloadMetadataLink;r.download="metadata-edited.tsv",Object.assign(r,{href:window.URL.createObjectURL(e)}),r.click()}}superviseInputTyping(){let t=this.superviseInput.trim();if(t==null||t.trim()===""){this.superviseInputSelected===""?this.superviseInputLabel="No ignored label":this.superviseInputLabel=`Supervising without '${this.superviseInputSelected}'`;return}if(this.projector&&this.projector.dataSet){let e=this.projector.dataSet.points.filter(r=>r.metadata[this.superviseColumn].toString().trim()===t).length;e===0?this.superviseInputLabel="Label not found":this.projector.dataSet.superviseInput!=t&&(this.superviseInputLabel=`Supervise without '${t}' [${e} points]`)}}superviseInputChange(){let t=this.superviseInput.trim();if(t==null||t.trim()===""){this.superviseInputSelected="",this.superviseInputLabel="No ignored label",this.setSupervision(this.superviseColumn,"");return}if(this.projector&&this.projector.dataSet){let e=this.projector.dataSet.points.filter(r=>r.metadata[this.superviseColumn].toString().trim()===t).length;e===0?this.superviseInputLabel=`Supervising without '${this.superviseInputSelected}'`:(this.superviseInputSelected=t,this.superviseInputLabel=`Supervising without '${t}' [${e} points]`,this.setSupervision(this.superviseColumn,t))}}superviseColumnChanged(){this.superviseInput="",this.superviseInputChange()}setSupervision(t,e){this.projector&&this.projector.dataSet&&this.projector.dataSet.setSupervision(t,e)}setNormalizeData(t){this.normalizeData=t}_selectedTensorChanged(){this.projector.updateDataSet(null,null,null),this.selectedTensor!=null&&(this.dataProvider.retrieveTensor(this.selectedRun,this.selectedTensor,t=>{var r;let e=(r=this.getEmbeddingInfoByName(this.selectedTensor))==null?void 0:r.metadataPath;this.dataProvider.retrieveSpriteAndMetadata(this.selectedRun,this.selectedTensor,i=>{this.projector.updateDataSet(t,i,e)})}),this.projector.setSelectedTensor(this.selectedRun,this.getEmbeddingInfoByName(this.selectedTensor)))}_generateUiForNewCheckpointForRun(t){this.dataProvider.retrieveProjectorConfig(t,e=>{this.projectorConfig=e;let r=this.projectorConfig.embeddings.map(o=>o.tensorName).filter(o=>{var a;let s=(a=this.getEmbeddingInfoByName(o))==null?void 0:a.tensorShape;return(s==null?void 0:s.length)===2&&s[0]>1&&s[1]>1}).sort((o,s)=>{let a=this.getEmbeddingInfoByName(o),l=this.getEmbeddingInfoByName(s);if(LC(!!(a!=null&&a.metadataPath),!!(l!=null&&l.metadataPath)))return a!=null&&a.metadataPath?-1:1;let c=NC(o),u=NC(s);if(LC(c,u))return u?-1:1;let h=a==null?void 0:a.tensorShape[0],p=l==null?void 0:l.tensorShape[0];return h!==p?p-h:o<=s?-1:1});this.tensorNames=r.map(o=>{var s;return{name:o,shape:(s=this.getEmbeddingInfoByName(o))==null?void 0:s.tensorShape}});let i=this.projector.servingMode==="demo"?this.projectorConfig.embeddings[0].tensorName:r[0];this.selectedTensor===i?this._selectedTensorChanged():this.selectedTensor=i})}_selectedLabelOptionChanged(){this.projector.setSelectedLabelOption(this.selectedLabelOption)}_selectedColorOptionNameChanged(){var e;let t=null;for(let r=0;r{var o;return{color:(o=t==null?void 0:t.map)==null?void 0:o.call(t,i.label),label:i.label,count:i.count}});this.colorLegendRenderInfo={items:r,thresholds:[]}}else this.colorLegendRenderInfo={items:[],thresholds:t.thresholds};this.projector.setSelectedColorOption(t)}}tensorWasReadFromFile(t,e){jO(t,r=>{let i=this.$$("#checkpoint-file");i.innerText=e,i.title=e,this.projector.updateDataSet(r)})}metadataWasReadFromFile(t,e){qO(t,r=>{this.projector.updateDataSet(this.projector.dataSet,r,e)})}getEmbeddingInfoByName(t){for(let e=0;e{var m;let d=(m=t.files)==null?void 0:m[0];t.value="";let f=new FileReader;f.onload=x=>{let g=f.result;this.tensorWasReadFromFile(g,d.name)},f.readAsArrayBuffer(d)};let e=this.$$("#upload-tensors");e.onclick=()=>{t.click()};let r=this.$$("#file-metadata");r.onchange=()=>{var m;let d=(m=r.files)==null?void 0:m[0];r.value="";let f=new FileReader;f.onload=x=>{let g=f.result;this.metadataWasReadFromFile(g,d.name)},f.readAsArrayBuffer(d)};let i=this.$$("#upload-metadata");i.onclick=()=>{r.click()},this.projector.servingMode!=="demo"&&(this.$$("#publish-container").style.display="none",this.$$("#upload-tensors-step-container").style.display="none",this.$$("#upload-metadata-label").style.display="none"),this.$$("#demo-data-buttons-container").style.display="flex";let o=this.$$("#projector-config-template"),s={embeddings:[{tensorName:"My tensor",tensorShape:[1e3,50],tensorPath:"https://raw.githubusercontent.com/.../tensors.tsv",metadataPath:"https://raw.githubusercontent.com/.../optional.metadata.tsv"}]};this.setProjectorConfigTemplateJson(o,s);let a=this.$$("#config-sprite-checkbox");a.onchange=()=>{a.checked?s.embeddings[0].sprite={imagePath:"https://github.com/.../optional.sprite.png",singleImageDim:[32,32]}:delete s.embeddings[0].sprite,this.setProjectorConfigTemplateJson(o,s)};let l=this.$$("#config-bookmarks-checkbox");l.onchange=()=>{l.checked?s.embeddings[0].bookmarksPath="https://raw.githubusercontent.com/.../bookmarks.txt":delete s.embeddings[0].bookmarksPath,this.setProjectorConfigTemplateJson(o,s)};let c=this.$$("#config-metadata-checkbox");c.onchange=()=>{c.checked?s.embeddings[0].metadataPath="https://raw.githubusercontent.com/.../optional.metadata.tsv":delete s.embeddings[0].metadataPath,this.setProjectorConfigTemplateJson(o,s)};let u=this.$$("#projector-config-url"),h=this.$$("#projector-share-url"),p=this.$$("#projector-share-url-link");u.onchange=()=>{let d=location.protocol+"//"+location.host+location.pathname+"?config="+u.value;h.value=d,Object.assign(p,{href:d})}}setProjectorConfigTemplateJson(t,e){t.value=JSON.stringify(e,null,2)}_getNumTensorsLabel(){return this.tensorNames.length===1?"1 tensor":this.tensorNames.length+" tensors"}_getNumRunsLabel(){return this.runNames.length===1?"1 run":this.runNames.length+" runs"}_hasChoice(t){return t.length>0}_hasChoices(t){return t.length>1}_openDataDialog(){this.$.dataDialog.open()}_openConfigDialog(){this.$.projectorConfigDialog.open()}};tn.template=x7;Et([Dt({type:String}),_t("design:type",String)],tn.prototype,"selectedTensor",void 0);Et([Dt({type:String}),_t("design:type",String)],tn.prototype,"selectedRun",void 0);Et([Dt({type:String,notify:!0}),_t("design:type",String)],tn.prototype,"selectedColorOptionName",void 0);Et([Dt({type:String,notify:!0}),_t("design:type",String)],tn.prototype,"selectedLabelOption",void 0);Et([Dt({type:Boolean}),_t("design:type",Boolean)],tn.prototype,"normalizeData",void 0);Et([Dt({type:Boolean}),_t("design:type",Boolean)],tn.prototype,"showForceCategoricalColorsCheckbox",void 0);Et([Dt({type:String}),_t("design:type",String)],tn.prototype,"metadataEditorInput",void 0);Et([Dt({type:String}),_t("design:type",String)],tn.prototype,"metadataEditorInputLabel",void 0);Et([Dt({type:String}),_t("design:type",String)],tn.prototype,"metadataEditorColumn",void 0);Et([Dt({type:Boolean}),_t("design:type",Boolean)],tn.prototype,"metadataEditorButtonDisabled",void 0);Et([Dt({type:String}),_t("design:type",String)],tn.prototype,"superviseInput",void 0);Et([Dt({type:String}),_t("design:type",String)],tn.prototype,"superviseInputLabel",void 0);Et([Dt({type:String}),_t("design:type",String)],tn.prototype,"superviseColumn",void 0);Et([Dt({type:Boolean}),_t("design:type",Boolean)],tn.prototype,"showSuperviseSettings",void 0);Et([Dt({type:String}),_t("design:type",Object)],tn.prototype,"_wordDelimiter",void 0);Et([En("selectedTensor"),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],tn.prototype,"_selectedTensorChanged",null);Et([En("selectedRun"),_t("design:type",Function),_t("design:paramtypes",[Object]),_t("design:returntype",void 0)],tn.prototype,"_generateUiForNewCheckpointForRun",null);Et([En("selectedLabelOption"),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],tn.prototype,"_selectedLabelOptionChanged",null);Et([En("selectedColorOptionName"),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],tn.prototype,"_selectedColorOptionNameChanged",null);tn=Et([Xe("vz-projector-data-panel")],tn);var Kd=class extends Ke(Ae){registerInputChangedListener(t){this.textChangedListeners.push(t)}ready(){super.ready(),this.inRegexMode=!1,this.textChangedListeners=[],this.paperInput=this.$$("paper-input"),this.inRegexModeButton=this.$$("paper-button"),this.paperInput.setAttribute("error-message","Invalid regex"),this.paperInput.addEventListener("input",()=>{this.onTextChanged()}),this.paperInput.addEventListener("keydown",t=>{t.stopPropagation()}),this.inRegexModeButton.addEventListener("click",()=>this.onClickRegexModeButton()),this.updateRegexModeDisplaySlashes(),this.onTextChanged()}onClickRegexModeButton(){this.inRegexMode=this.inRegexModeButton.active,this.updateRegexModeDisplaySlashes(),this.onTextChanged()}notifyInputChanged(t,e){this.textChangedListeners.forEach(r=>r(t,e))}onTextChanged(){try{this.inRegexMode&&new RegExp(this.paperInput.value)}catch(t){this.paperInput.setAttribute("invalid","true"),this.message="",this.notifyInputChanged(null,!0);return}this.paperInput.removeAttribute("invalid"),this.notifyInputChanged(this.paperInput.value,this.inRegexMode)}updateRegexModeDisplaySlashes(){let t=this.paperInput.querySelectorAll(".slash"),e=this.inRegexMode?"":"none";for(let r=0;r + + + +
/
+
+
/
+ .* +
+
+ + Enable/disable regex mode. + + [[message]] + `;Et([Dt({type:String}),_t("design:type",String)],Kd.prototype,"label",void 0);Et([Dt({type:String}),_t("design:type",String)],Kd.prototype,"message",void 0);Kd=Et([Xe("vz-projector-input")],Kd);var v7=dt` + + +
+
+ + + +
+
+ + + + + + +
+
+
+ + + +
+`;var y7=100,cut=100,Ur=class extends Ke(Ae){constructor(){super(...arguments),this.numNN=cut,this.showNeighborImages=!0,this.spriteImagesAvailable=!0}ready(){super.ready(),this.resetFilterButton=this.$$(".reset-filter"),this.setFilterButton=this.$$(".set-filter"),this.clearSelectionButton=this.$$(".clear-selection"),this.limitMessage=this.$$(".limit-msg"),this.searchBox=this.$$("#search-box"),this.displayContexts=[]}initialize(t,e){this.projector=t,this.projectorEventContext=e,this.setupUI(t),e.registerSelectionChangedListener((r,i)=>this.updateInspectorPane(r,i))}updateInspectorPane(t,e){this.neighborsOfFirstPoint=e,this.selectedPointIndices=t,this.updateFilterButtons(t.length+e.length),this.updateNeighborsList(e),e.length===0?this.updateSearchResults(t):this.updateSearchResults([]),this.searchBox.message=""}enableResetFilterButton(t){this.resetFilterButton.disabled=!t}restoreUIFromBookmark(t){this.enableResetFilterButton(t.filteredPoints!=null)}metadataChanged(t){var r,i;let e=-1;if(t.stats&&(this.metadataFields=t.stats.map((o,s)=>(!o.isNumeric&&e===-1&&(e=s),o.name))),t.spriteMetadata&&t.spriteMetadata.imagePath){let[o,s]=t.spriteMetadata.singleImageDim;this.spriteMeta={imagePath:(r=t.spriteImage)==null?void 0:r.src,aspectRatio:o/s,nCols:Math.floor(((i=t.spriteImage)==null?void 0:i.width)/o),singleImageDim:[o,s]}}else this.spriteMeta={};this.spriteImagesAvailable=!!this.spriteMeta.imagePath,(this.selectedMetadataField==null||this.metadataFields.filter(o=>o===this.selectedMetadataField).length===0)&&(this.selectedMetadataField=this.metadataFields[Math.max(0,e)]),this.updateInspectorPane(this.selectedPointIndices,this.neighborsOfFirstPoint),this.searchBox.setValue("",!1)}datasetChanged(){this.enableResetFilterButton(!1)}_refreshNeighborsList(){this.updateNeighborsList()}_selectedMetadataFieldChanged(){this.searchBox.setValue("",!1)}metadataEditorContext(t,e){if(!this.projector||!this.projector.dataSet)return;let r=this.projector.dataSet.spriteAndMetadataInfo.stats.filter(a=>a.name===e);if(!t||r.length===0||r[0].tooManyUniqueValues){this.removeContext(".metadata-info");return}this.metadataColumn=e,this.addContext(".metadata-info");let i=this.$$(".metadata-list");i.textContent="";let o=r[0].uniqueEntries.sort((a,l)=>a.count-l.count),s=o[o.length-1].count;o.forEach(a=>{let l=document.createElement("div");l.className="metadata";let c=document.createElement("a");c.className="metadata-link",c.title=a.label;let u=document.createElement("div");u.className="label-and-value";let h=document.createElement("div");h.className="label",h.style.color=gu(this.distFunc,s,a.count),h.innerText=a.label;let p=document.createElement("div");p.className="value",p.innerText=a.count.toString(),u.appendChild(h),u.appendChild(p);let d=document.createElement("div");d.className="bar";let f=document.createElement("div");f.className="fill",f.style.borderTopColor=gu(this.distFunc,s,a.count),f.style.width=Dy(this.distFunc,s,a.count)*100+"%",d.appendChild(f);for(let m=1;m<4;m++){let x=document.createElement("div");x.className="tick",x.style.left=m*100/4+"%",d.appendChild(x)}c.appendChild(u),c.appendChild(d),l.appendChild(c),i.appendChild(l),c.onclick=()=>{this.projector.metadataEdit(e,a.label)}})}addContext(t){this.displayContexts.indexOf(t)===-1&&this.displayContexts.push(t),this.displayContexts.forEach(e=>{this.$$(e).style.display="none"}),this.$$(t).style.display=null}removeContext(t){if(this.displayContexts=this.displayContexts.filter(e=>e!==t),this.$$(t).style.display="none",this.displayContexts.length>0){let e=this.displayContexts[this.displayContexts.length-1];this.$$(e).style.display=null}}updateSearchResults(t){let r=this.$$(".matches-list").querySelector(".list");if(r.textContent="",t.length===0){this.removeContext(".matches-list");return}this.addContext(".matches-list"),this.limitMessage.style.display=t.length<=y7?"none":null,t=t.slice(0,y7);for(let i=0;i{this.projectorEventContext.notifyHoverOverPoint(o)},l.onmouseleave=()=>{this.projectorEventContext.notifyHoverOverPoint(null)},l.onclick=()=>{this.projectorEventContext.notifySelectionChanged([o])},s.appendChild(l),r.appendChild(s)}}getLabelFromIndex(t){let e=this.projector.dataSet.points[t].metadata[this.selectedMetadataField];return e!==void 0?String(e):`Unknown #${t}`}spriteImageRenderer(){let t=this.spriteMeta.imagePath,{aspectRatio:e,nCols:r}=this.spriteMeta,i=100/e+"%",o=`${r*100}% ${r*100}%`,s=`url(${CSS.escape(t)})`;return a=>{let l=document.createElement("div");l.className="sprite-image",l.style.backgroundImage=s,l.style.paddingBottom=i,l.style.backgroundSize=o;let[c,u]=[Math.floor(a.index/r),a.index%r],[h,p]=[c/(r-1)*100,u/(r-1)*100];return l.style.backgroundPosition=`${p}% ${h}%`,l}}updateNeighborsList(t){if(t=t||this._currentNeighbors,this._currentNeighbors=t,t==null)return;let e=this.$$(".nn-list");if(e.textContent="",t.length===0){this.removeContext(".nn");return}this.addContext(".nn"),this.searchBox.message="";let r=t.length>0?t[0].dist:0;for(let i=0;i{this.projectorEventContext.notifyHoverOverPoint(o.index)},a.onmouseleave=()=>{this.projectorEventContext.notifyHoverOverPoint(null)},a.onclick=()=>{this.projectorEventContext.notifySelectionChanged([o.index])}}}updateFilterButtons(t){t>1?(this.setFilterButton.innerText=`Isolate ${t} points`,this.setFilterButton.disabled=null,this.clearSelectionButton.disabled=null):(this.setFilterButton.innerText="Isolate selection",this.setFilterButton.disabled=!0,this.clearSelectionButton.disabled=!0)}setupUI(t){this.distFunc=A3;let e=this.$$(".distance a.euclidean");e.onclick=()=>{var a;let o=(a=this.root)==null?void 0:a.querySelectorAll(".distance a");if(o)for(let l=0;l{var a;let o=(a=this.root)==null?void 0:a.querySelectorAll(".distance a");if(o)for(let l=0;l{if(o==null||o.trim()===""){this.searchBox.message="",this.projectorEventContext.notifySelectionChanged([]);return}let a=t.dataSet.query(o,s,this.selectedMetadataField);this.projectorEventContext.notifySelectionChanged(a),a.length===0?this.searchBox.message="0 matches.":this.searchBox.message=`${a.length} matches.`};this.searchBox.registerInputChangedListener((o,s)=>{i(o,s)}),this.setFilterButton.onclick=()=>{let o=this.selectedPointIndices.concat(this.neighborsOfFirstPoint.map(s=>s.index));t.filterDataset(o),this.enableResetFilterButton(!0),this.updateFilterButtons(0)},this.resetFilterButton.onclick=()=>{t.resetFilterDataset(),this.enableResetFilterButton(!1)},this.clearSelectionButton.onclick=()=>{t.adjustSelectionAndHover([])},this.enableResetFilterButton(!1)}updateNumNN(){this.selectedPointIndices!=null&&this.projectorEventContext.notifySelectionChanged([this.selectedPointIndices[0]])}};Ur.template=v7;Et([Dt({type:String}),_t("design:type",String)],Ur.prototype,"selectedMetadataField",void 0);Et([Dt({type:Array}),_t("design:type",Array)],Ur.prototype,"metadataFields",void 0);Et([Dt({type:String}),_t("design:type",String)],Ur.prototype,"metadataColumn",void 0);Et([Dt({type:Number}),_t("design:type",Number)],Ur.prototype,"numNN",void 0);Et([Dt({type:Object}),_t("design:type",Object)],Ur.prototype,"spriteMeta",void 0);Et([Dt({type:Boolean}),_t("design:type",Boolean)],Ur.prototype,"showNeighborImages",void 0);Et([Dt({type:Boolean}),_t("design:type",Boolean)],Ur.prototype,"spriteImagesAvailable",void 0);Et([En("showNeighborImages","spriteImagesAvailable"),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Ur.prototype,"_refreshNeighborsList",null);Et([En("selectedMetadataField"),_t("design:type",Function),_t("design:paramtypes",[]),_t("design:returntype",void 0)],Ur.prototype,"_selectedMetadataFieldChanged",null);Ur=Et([Xe("vz-projector-inspector-panel")],Ur);var Ms=class extends Ke(Ae){constructor(){super(...arguments),this.hasMetadata=!1,this.isCollapsed=!1,this.collapseIcon="expand-less"}_toggleMetadataContainer(){this.$$("#metadata-container").toggle(),this.isCollapsed=!this.isCollapsed,this.set("collapseIcon",this.isCollapsed?"expand-more":"expand-less")}updateMetadata(t){if(this.hasMetadata=t!=null,t){this.pointMetadata=t;let e=[];for(let r in t)!t.hasOwnProperty(r)||e.push({key:r,value:t[r]});this.metadata=e,this.label=""+this.pointMetadata[this.labelOption]}}setLabelOption(t){this.labelOption=t,this.pointMetadata&&(this.label=""+this.pointMetadata[this.labelOption])}};Ms.template=dt` + + + + `;Et([Dt({type:Boolean}),_t("design:type",Boolean)],Ms.prototype,"hasMetadata",void 0);Et([Dt({type:Boolean}),_t("design:type",Boolean)],Ms.prototype,"isCollapsed",void 0);Et([Dt({type:String}),_t("design:type",String)],Ms.prototype,"collapseIcon",void 0);Et([Dt({type:Array}),_t("design:type",Array)],Ms.prototype,"metadata",void 0);Et([Dt({type:String}),_t("design:type",String)],Ms.prototype,"label",void 0);Ms=Et([Xe("vz-projector-metadata-card")],Ms);var b7,_7=dt(b7||(b7=U3([` + + +
+
+
+
+ UMAP +
+
+ t-SNE +
+
+ PCA +
+
+ Custom +
+
+
+
+ +
+
+ +
+ 2D + 3D +
+
+
+ + + [[umapNeighbors]] +
+
+ + + [[umapMinDist]] +
+

+ +

+

+ For faster results, the data will be sampled down to + [[getUmapSampleSizeText()]] points. +

+

+ + + Learn more about UMAP. + +

+
+ +
+
+ +
+ 2D + 3D +
+
+
+ + + +
+
+ + + + +
+
+ + + + +
+

+ + + +

+

Iteration: 0

+

+ For faster results, the data will be sampled down to + [[getTsneSampleSizeText()]] points. +

+

+ + + How to use t-SNE effectively. + +

+
+ +
+
+
+ + + + +
#
+
Variance (%)
+
+ +
+
+ + + +
#
+
Variance (%)
+
+ +
+
+
+
+ + + + +
#
+
Variance (%)
+
+ +
+
+ +
+
+

+ PCA is approximate. + +

+
Total variance
+ + For fast results, the data was sampled to [[getPcaSampleSizeText()]] + points and randomly projected down to [[getPcaSampledDimText()]] + dimensions. + +
+ +
+ + + + + +
+ + +
+
+ + +
+
+
+
+ +