commit 60a45b4d385092f97c61e30e0219ad1ab6d1ac4d Author: Michal Fratczak Date: Thu Jun 10 11:42:10 2021 +0200 Init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..208a93d --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +*.pyc +*.vscode +build +cacert.pem +privkey.pem + +data_server/code/*.txt +data_server/code/*.db +data_server/code/*.txt* +data_server/code/pred +data_server/code/cusfpredict +data_server/code/basic_example.py + +webUI/code/habdec_gui +webUI/code/js/test.html +webUI/code/osm +webUI/code/osm/* +data_server/code/test_car.py +data_server/code/bottle_sslify.py +habboy_data/code/habboy_data.db diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5fd94a1 --- /dev/null +++ b/README.md @@ -0,0 +1,50 @@ +![HabBoy_Radio](./docs/HabBoy_Habdec.jpg) + +![HabBoy_Map](./docs/HabBoy_Osm.jpg) + +# HABBOY + +HabBoy is a linux/webApp to help observe and chase after High Altitude Balloons. (https://ukhas.org.uk/) + +https://www.youtube.com/watch?v=ZuoNf171e_A +https://twitter.com/froszu/status/1274308780923269120 +https://twitter.com/froszu/status/1271166163993661440 + + +## Features +* server backend for linux, python3 and SQLite +* web browser GUI - run it on any device (tablet,smartphone,desktop...) +* optimized for use in a car (large buttons, simple operation, 100% offline) +* read balloon telemetry from [HabDec](https://github.com/ogre/habdec/), [Habitat](https://habitat.habhub.org/), [dl-fldigi](https://ukhas.org.uk/projects:dl-fldigi) +* display Balloon position and landspot prediction on OpenStreetMap (offline vector tiles) +* display Balloon position on GoogleMaps (requires internet connection) +* display Balloons telemetry as graphs and gauges (HighCharts.js) + +## Project Status +HabBoy is an experimental software, which means no guarantees are made. To make it run you probably need some code tinkering to adjust to your needs. Also, the installation is not an automatic process - you need to generate OSM vector tiles, install Apache (or other web server) and compile/install wind prediction software. + +That being said, it was used in 3 HAB missions and performed very well. + +It was developed and tested on SBCs like RaspberryPI(raspiOS) and OdroidXU4(Ubuntu 18.04). +For GPS location you need an USB receiver like this one: https://www.hardkernel.com/shop/usb-gps-module/ + +## Structure Overview +HabBoy is a multi component software: + +![alt text](./docs/habboy_structure.png) + +### Components +* [data server](./data_server/README.md) +* [web browser UI](./webUI/README.md) +* [OpenStreetMap](./docs/VECTOR_TILES.md) +* [HabDec](https://github.com/ogre/habdec/) +* [fldigi bridge](./bridge/fldigi/README.md) + +### discovery +* helper system to find HABBOY/HabDec in LAN without DNS and static IPs + + +### Now Defunct Components - this is unmaintained and depreciated +* [hw_iface](./hw_iface/README.md) - websocket interface to any external hardware (ie. arduino) +* [arduino](./arduino/README.md) - arduino code to read GPS data from uBLOX module + diff --git a/arduino/README.md b/arduino/README.md new file mode 100644 index 0000000..78db572 --- /dev/null +++ b/arduino/README.md @@ -0,0 +1,3 @@ +Arduino program to read GPS data and print it to serial. + +This will be read over serial port by rPI/odroid/whatever and served with hw_iface websocket server to webUI. \ No newline at end of file diff --git a/arduino/code/habboy_arduino.ino b/arduino/code/habboy_arduino.ino new file mode 100644 index 0000000..032935b --- /dev/null +++ b/arduino/code/habboy_arduino.ino @@ -0,0 +1,60 @@ + +#include "helpers/gps.h" +#include "helpers/rotary_mod16.h" + + + +void setup() +{ + // Serial.begin(115200); + Serial.begin(9600); + while (!Serial) + ; //Wait for user to open terminal + + Serial.println(F("interrupts()")); + interrupts(); + + Serial.println(F("Wire.begin()")); + Wire.begin(); + + Serial.println(F("SetupUBlox()")); + bool gps_ok = SetupUBlox(); + while(!gps_ok) + { + Serial.println(F("err::gps")); + delay(1000); + } + + Serial.println(F("SetupMod16RotSwitch()")); + SetupMod16RotSwitch(11, 12, 0); + + Serial.println(F("setup() done")); + +} + + +long G_GPS_WAIT = 0; +long G_ROT_WAIT = 0; +void loop() +{ + /*if( G_ROT_SWITCH_COUNTER && (millis()-G_GPS_WAIT)>50 ) + { + { + int rot_switch_counter = G_ROT_SWITCH_COUNTER; + G_ROT_SWITCH_COUNTER = 0; + Serial.print(F("rot::")); Serial.println(rot_switch_counter/2); + G_ROT_WAIT = millis(); + } + } + */ + + if (millis() - G_GPS_WAIT > 300) + { + UpdateGps(); + PrintGpsState(); + Serial.println(); + + G_GPS_WAIT = millis(); + } + +} \ No newline at end of file diff --git a/arduino/code/helpers/gps.h b/arduino/code/helpers/gps.h new file mode 100644 index 0000000..0ffca6a --- /dev/null +++ b/arduino/code/helpers/gps.h @@ -0,0 +1,132 @@ +#pragma once + +#include //Needed for I2C to GPS + +// https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library +// http://librarymanager/All#SparkFun_Ublox_GPS + +#include "SparkFun_Ublox_Arduino_Library.h" +SFE_UBLOX_GPS myGPS; + +bool SetupUBlox() +{ + Wire.begin(); + + if (myGPS.begin() == false) //Connect to the Ublox module using Wire port + return false; + + myGPS.setI2COutput(COM_TYPE_UBX); //Set the I2C port to output UBX only (turn off NMEA noise) + myGPS.setNavigationFrequency(3); //Set output to X times a second + myGPS.setAutoPVT(true); //Tell the GPS to "send" each solution -- NONBLOCKING + + return true; +} + +/* +void PrintGps() +{ + Serial.print(F("gps::")); + + long latitude = myGPS.getLatitude(); + Serial.print(F("lat=")); + Serial.print(latitude); + + long longitude = myGPS.getLongitude(); + Serial.print(F(",lon=")); + Serial.print(longitude); + // Serial.print(F(" (degrees * 10^-7)")); + + long altitude = myGPS.getAltitude(); + Serial.print(F(",alt=")); + Serial.print(altitude); + // Serial.print(F(" (mm)")); + + long altitudeMSL = myGPS.getAltitudeMSL(); + Serial.print(F(",altmsl=")); + Serial.print(altitudeMSL); + + byte SIV = myGPS.getSIV(); + Serial.print(F(",siv=")); + Serial.print(SIV); + + long speed = myGPS.getGroundSpeed(); + Serial.print(F(",speed=")); + Serial.print(speed); + // Serial.print(F(" (mm/s)")); + + long heading = myGPS.getHeading(); + Serial.print(F(",heading=")); + Serial.print(heading); + // Serial.print(F(" (degrees * 10^-5)")); + + uint32_t acu = myGPS.getPositionAccuracy(); + Serial.print(F(",acu=")); + Serial.print(acu); + + uint8_t fixtype = myGPS.getFixType(); + Serial.print(F(",fixtype=")); + Serial.print(fixtype); + + Serial.print(F("\n")); +} +*/ + +struct GPS_STATE_T +{ + long latitude; + long longitude; + int16_t altitude; + int16_t altitudeMSL; + uint8_t SIV; + uint16_t speed; + uint16_t heading; + uint32_t acu; + uint8_t fixtype; +}; + +GPS_STATE_T G_GPS_STATE; + +void UpdateGps() // this takes 500ms +{ + G_GPS_STATE.latitude = myGPS.getLatitude(); + G_GPS_STATE.longitude = myGPS.getLongitude(); + G_GPS_STATE.altitude = myGPS.getAltitude(); + G_GPS_STATE.altitudeMSL = myGPS.getAltitudeMSL(); + G_GPS_STATE.SIV = myGPS.getSIV(); + G_GPS_STATE.speed = myGPS.getGroundSpeed(); + G_GPS_STATE.heading = myGPS.getHeading(); + G_GPS_STATE.acu = myGPS.getPositionAccuracy(); + G_GPS_STATE.fixtype = myGPS.getFixType(); +} + +void PrintGpsState() +{ + Serial.print(F("gps::")); + + Serial.print(F("lat=")); + Serial.print(G_GPS_STATE.latitude); + + Serial.print(F(",lon=")); + Serial.print(G_GPS_STATE.longitude); + + Serial.print(F(",alt=")); + Serial.print(G_GPS_STATE.altitude); + + Serial.print(F(",altmsl=")); + Serial.print(G_GPS_STATE.altitudeMSL); + + Serial.print(F(",siv=")); + Serial.print(G_GPS_STATE.SIV); + + Serial.print(F(",speed=")); + Serial.print(G_GPS_STATE.speed); + + Serial.print(F(",heading=")); + Serial.print(G_GPS_STATE.heading); + + Serial.print(F(",acu=")); + Serial.print(G_GPS_STATE.acu); + + Serial.print(F(",fixtype=")); + Serial.print(G_GPS_STATE.fixtype); +} \ No newline at end of file diff --git a/arduino/code/helpers/rotary_mod16.h b/arduino/code/helpers/rotary_mod16.h new file mode 100644 index 0000000..212b6bf --- /dev/null +++ b/arduino/code/helpers/rotary_mod16.h @@ -0,0 +1,44 @@ +#pragma once + +// modulowo.com mod 16-z +// https://kamami.pl/klawiatury-przyciski/557576-przelacznik-obrotowy-dzialajacy-w-oparciu-o-enkoder.html +// https://dl.btc.pl/kamami_wa/instrukcja-mod-16z.pdf + +// S1A, S1B – axis click +// S2 i S3 – right/left rotation + +short G_MOD16_ROT_LEFT_PIN = 0; +short G_MOD16_ROT_RIGHT_PIN = 0; +short G_MOD16_CLICK_PIN = 0; + +void RotSwitchISR2(); +void RotSwitchISR3(); + +void SetupMod16RotSwitch(short pinLeft, short pinRight, short pinClick) +{ + G_MOD16_ROT_LEFT_PIN = pinLeft; + G_MOD16_ROT_RIGHT_PIN = pinRight; + G_MOD16_CLICK_PIN = pinClick; + + // pinMode(0, INPUT); + pinMode(G_MOD16_ROT_LEFT_PIN, INPUT); + pinMode(G_MOD16_ROT_RIGHT_PIN, INPUT); + + // digitalWrite (2, HIGH); + // digitalWrite (3, HIGH); + attachInterrupt(digitalPinToInterrupt(2), RotSwitchISR2, CHANGE); + attachInterrupt(digitalPinToInterrupt(3), RotSwitchISR3, CHANGE); +} + +volatile int G_ROT_SWITCH_COUNTER = 0; +void RotSwitchISR2() +{ + G_ROT_SWITCH_COUNTER += 1; + // delayMicroseconds(1000); +} + +void RotSwitchISR3() +{ + G_ROT_SWITCH_COUNTER -= 1; + // delayMicroseconds(1000); +} diff --git a/arduino/code/serial_test.py b/arduino/code/serial_test.py new file mode 100644 index 0000000..2db73e7 --- /dev/null +++ b/arduino/code/serial_test.py @@ -0,0 +1,19 @@ +#! /usr/bin/python + +import serial, time, sys + + +ser = serial.Serial(sys.argv[1], 115200) + +while 1: + serial_line = ser.readline() + + print(serial_line) # If using Python 2.x use: print serial_line + # Do some other work on the data + + time.sleep(.333) # sleep 5 minutes + + # Loop restarts once the sleep is finished + +ser.close() # Only executes once the loop exits + diff --git a/bridge/fldigi/README.md b/bridge/fldigi/README.md new file mode 100644 index 0000000..e75f5f3 --- /dev/null +++ b/bridge/fldigi/README.md @@ -0,0 +1,2 @@ +# fldigi bridge +connect to running instance of fldigi, reads RTTY texts, scans for valid UKHAS sentence and report to HabBoy data_server \ No newline at end of file diff --git a/bridge/fldigi/fldigi2habboy.py b/bridge/fldigi/fldigi2habboy.py new file mode 100644 index 0000000..47fadcd --- /dev/null +++ b/bridge/fldigi/fldigi2habboy.py @@ -0,0 +1,184 @@ +#!/bin/env python + +# dl-fldigi.exe --hab --arq-server-address 127.0.0.1 --arq-server-port 7777 +# fldigi.exe --arq-server-address 127.0.0.1 --arq-server-port 7777 + +from __future__ import print_function + +import string +import socket +import select +import time +import re +import traceback +import threading +import queue +import urllib3 + +def crc(i_str): + def _hex(n): return hex(int(n))[2:] + + i_str = str(i_str) + CRC = 0xffff + for i in xrange(len(i_str)): + CRC ^= ord(i_str[i]) << 8 + for j in xrange(8): + if (CRC & 0x8000): + CRC = (CRC << 1) ^ 0x1021 + else: + CRC <<= 1 + result = '' + result += _hex((CRC >> 12) & 15) + result += _hex((CRC >> 8) & 15) + result += _hex((CRC >> 4) & 15) + result += _hex(CRC & 15) + + return result.lower() + + +def make_connection(host='localhost', port='7777'): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + port = int(port) + sock.connect(( host, port )) + sock.setblocking(0) + except: + print("fldigi2habboy: make_connection failed.") + print(traceback.format_exc()) + return sock + + +def read_from_fldigi(sock, callback = None): + timeout_in_seconds = 10 + while 1: + try: + ready = select.select([sock], [], [], timeout_in_seconds) + if ready[0]: + chunk = sock.recv(4096) + if callback: + callback(chunk) + else: + print("Waiting for some fldigi data ...") + except KeyboardInterrupt: + return + except: + print(traceback.format_exc()) + + +class UkhasSentenceScanner(object): + ''' + 1. push() some characters into internal buffer + 2. if a valid sentence is found, run callback(sentence) + ''' + def __init__(self): + self.__buff__ = '' + self.__rex__ = re.compile( r'''(.*?)\$+(.+)(\*)(\w{4})(.*)''' ) + self.__sentence_callback__ = print + + def set_callback(self, cb): + self.__sentence_callback__ = cb + + def push(self, chars): + # print(chars, end='') + if len(self.__buff__) > 5000: + self.__buff__ = '' + self.__buff__ += chars + sentences = self.__scan__() + for s in sentences: + self.__sentence_callback__(s) + + def __scan__(self): + sentences = [] + for line in string.split(self.__buff__, '\n'): + mo = self.__rex__.match( string.strip(line), re.I ) + if not mo: + self.__buff__ = line + continue + if len(mo.groups()) != 5: + self.__buff__ = line #sentence might be not complete yet + continue + self.__buff__ = '' + sentence_no_crc = mo.group(2) + _crc = mo.group(4) + if crc(sentence_no_crc).lower() == _crc.lower(): + sentences.append( (sentence_no_crc, _crc) ) + else: + print('CRC not valid', sentence_no_crc, _crc, crc(sentence_no_crc) ) + return sentences + + +class HabBoyBridge(object): + ''' + Sends sentences to HabBoy server. + usage: + hbb = HabBoyBridge(host,port) + hbb.run() # run sending thread + hbb.push(sentence) # adds sentence to internal que + ''' + def __init__(self, host = 'localhost', port = 8888): + self.__host__ = str(host) + self.__port__ = int(port) + self.__sentence_que__ = queue.Queue() + self.__run__ = False #que sending thread + self.__http__ = urllib3.PoolManager() + + def push(self, sentence): + self.__sentence_que__.put(sentence) + + def run(self): + self.__thread__ = threading.Thread(target = self.__send_loop__) + try: + self.__run__ = True + self.__thread__.start() + except KeyboardInterrupt: + self.stop() + + def stop(self): + self.__run__ = False + if self.__thread__: + self.__thread__.join() + self.__thread__ = None + + def __send_loop__(self): + while self.__run__: + try: + s = self.__sentence_que__.get(block=True, timeout=.5) + is_success = self.send(s) + print("send result OK ?", is_success) + except queue.Empty: + pass + except KeyboardInterrupt: + self.stop() + return + + def send(self, sentence): + _url = 'http://{}:{}'.format(self.__host__, self.__port__) + _url += "/habboy/api/v1/sentence/fldigi/" + sentence + print("Sending sentence ", sentence, ' to ', _url) + try: + r = self.__http__.request('PUT', _url, timeout=2.0) + except: + print("Failed sending to habboy") + print(traceback.format_exc()) + return False + return True + +def main(): + print("HabBoy connection...") + hbb = HabBoyBridge('habboy', 8888) + hbb.run() + + print("Scanner") + scanner = UkhasSentenceScanner() + scanner.set_callback( lambda sent_and_crc: + hbb.send( sent_and_crc[0] + '*' + sent_and_crc[1] ) ) + + print("fldigi connection") + con = make_connection() + print("Connected to fldigi") + + print("Go !") + read_from_fldigi( con, lambda chars: scanner.push(chars) ) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/data_server/README.md b/data_server/README.md new file mode 100644 index 0000000..f1f4f73 --- /dev/null +++ b/data_server/README.md @@ -0,0 +1,66 @@ +# data_server + +```data_server``` is a backend of HabBoy. It's responsibility is: +* collects telemetry from multiple HABDECs, Habitat (and others sources) +* saves telemetry to SQLITE database +* computes telemetry dynamics (change over time, etc.) +* calculate landing prediction +* get HabBoy position from USB gps receiver +* upload HabBoy position as Habitat ChaseCar +* serves data over http REST (used by webUI) + + +## Installation + +### data_server dependencies + sudo pip3 install python-dateutil ws4py bottle cheroot setproctitle pyserial psutil urllib3 + +### data_server - Install As Service + sudo cp ./data_server/code/HabBoy.service /etc/systemd/system/ + sudo systemctl enable HabBoy.service + sudo systemctl daemon-reload + sudo systemctl start HabBoy.service + sudo journalctl -u HabBoy.service + + +## Usage + +### First Use +```data_server``` saves telemetry to SQLite database. Before first use, you need to initialise DB with `main.py --initDB`, this command will create a ```habboy_data.db```. + +### Updating database with payloads info +```data_server``` needs to know what flights are currently available and some information about sentence structure for each flight. Use command `main.py --updateDB` to download that information from UKHAS Habitat. Only approved flights will be downloaded, and only those with RTTY payloads. + +After update, you can list what payloads are saved in DB file: `main.py --dbinfo` + +If you wish to test your payload before it is approved by UKHAS admins, you need to manualy edit DB file with tool like [SQLiteBrowser](https://sqlitebrowser.org/). Edit ```PayloadInfo``` table providing PayloadId, callsign and SentenceInfo as ukhas JSON string. Use existing flights as template or look into file ```data_server/code/example_payload.info.json```. + + +### cusf predictor installation + +To use landspot prediction, you need [cusf predictor with python wrapper](https://github.com/darksidelemm/cusf_predictor_wrapper). + +After successful compilation, create symlink to cusf predictor executable: + +```ln -s cusfpredict habboy_sw/data_server/code/cusfpredict``` + +### Downloading wind data + +cusf predictor needs wind data to operate. +Here is example command to download it for Poland: + +```python get_wind_data.py --lat=52 --lon=21 --latdelta=10 --londelta=10 -f 24 -m 0p25_1hr -o ~/data/noaa_wind/gfs``` + +### IMPORTANT +Currently prediction gives incorrect results, and until this is fixed, HabBoy connects to UKHAS Habitat for landspot data (requires internet connection). + +### Launching HabBoy +After updating DB with your payload info and downloading wind data, you can start data_server with command ```./main.py --payload_id 2441777fbce3ce296e079b39ddb41a4a --wind ~/data/noaa_wind/gfs``` + +## HTTPS vs HTTPS +```data_server``` is a REST server over HTTP. It is possible to run it in HTTPS mode with ```--https``` flag, but you need to generate self signed certificate. + +`openssl req -new -x509 -days 1095 -nodes -newkey rsa:2048 -out cacert.pem -keyout privkey.pem -subj "/CN=192.168.100.53"` + +Running in HTTPS mode is not recommended. It is needed only if you wish to embed external HTTPS website as one of tabs in webUI (like www.spacenear.us). +It is also needed if you would like to use GPS build in your tablet/smartphone. diff --git a/data_server/code/DummySentenceCreator.py b/data_server/code/DummySentenceCreator.py new file mode 100644 index 0000000..bdf1e16 --- /dev/null +++ b/data_server/code/DummySentenceCreator.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 + +from datetime import datetime as dtime +import os +import time +import math +import random +import formatSentence +import json +import urllib3 + +urllib3.disable_warnings() +http = urllib3.PoolManager() + +C_BLACK = "\033[1;30m" +C_RED = "\033[1;31m" +C_GREEN = "\033[1;32m" +C_BROWN = "\033[1;33m" +C_BLUE = "\033[1;34m" +C_MAGENTA = "\033[1;35m" +C_CYAN = "\033[1;36m" +C_LIGHTGREY = "\033[1;37m" +C_OFF = "\033[0m" +C_CLEAR = "\033[2K" + +if os.name == 'nt': + C_BLACK=C_RED=C_GREEN=C_BROWN=C_BLUE=C_MAGENTA=C_CYAN=C_LIGHTGREY=C_OFF=C_CLEAR='' + + +def DummySentenceCreator(i_payloadId, i_callsign, i_sensors_info, lat=None, lon=None, alt=None): + + if not DummySentenceCreator.sentence_id: + # get last ID from DB to maintain continuity + # or comment out to test for real payloads that can restart and start from 0 + #DummySentenceCreator.sentence_id = G_SentencesDB.getLastSentenceId(i_payloadId) + + if not DummySentenceCreator.sentence_id: + DummySentenceCreator.sentence_id = 1 + + sentence = i_callsign + s_id = DummySentenceCreator.sentence_id + DummySentenceCreator.sentence_id += 1 + + for si in i_sensors_info: + if not "sensor" in si: + continue + + if si["name"] == "sentence_id": + sentence += "," + str(int(s_id)) + elif si["name"] == "date": + sentence += "," + dtime.utcnow().strftime("%m%D") + elif si["name"] == "time": + sentence += "," + dtime.utcnow().strftime("%H%M%S") + elif si["name"] == "latitude": + if lat: + sentence += ",{0:.6f}".format(lat) + else: + sentence += ",{0:.6f}".format(52.0 + math.sin(0.01 * s_id) + .0001 * random.randrange(0, 100)) + elif si["name"] == "longitude": + if lon: + sentence += ",{0:.6f}".format(lon) + else: + sentence += ",{0:.6f}".format(21.0 + math.cos(0.01 * s_id) + .0001 * random.randrange(0, 100)) + elif si["name"] == "altitude": + if alt: + sentence += ",{}".format(int(alt)) + else: + sentence += ",{}".format(int(100 + s_id * 10)) + elif si["name"] == "satellites": + sentence += "," + str(random.randrange(3, 12)) + else: + if si["sensor"] == "base.ascii_float": + sentence += ",{0:.2f}".format(random.random()) + elif si["sensor"] == "base.ascii_int": + sentence += "," + str(random.randrange(-100, 100)) + else: + sentence += "," + si["sensor"] + + sentence += "*" + formatSentence.crc(sentence) + # print(C_RED, "DUMMY ", sentence, C_OFF) + return sentence + +DummySentenceCreator.sentence_id = 0 + + +if __name__ == "__main__": + while True: + time.sleep(5) + snt =DummySentenceCreator( + i_payloadId = None, + i_callsign = 'SP5WWL', + i_sensors_info = [ + { + "name": "sentence_id", + "sensor": "base.ascii_int" + }, + { + "name": "time", + "sensor": "base.string" + }, + { + "format": "ddmm.mmmm", + "name": "latitude", + "sensor": "stdtelem.coordinate" + }, + { + "format": "ddmm.mmmm", + "name": "longitude", + "sensor": "stdtelem.coordinate" + }, + { + "name": "altitude", + "sensor": "base.ascii_float" + }, + { + "name": "battery", + "sensor": "base.ascii_float" + }, + { + "name": "satellites", + "sensor": "base.ascii_int" + }, + { + "name": "telemetry", + "sensor": "base.string" + } + ], + ) + + res = http.request('PUT', 'http://localhost:8888/habboy/api/v1/sentence/dummy/' + snt) + res = json.loads( res.data.decode("utf-8") ) + print (res, snt) diff --git a/data_server/code/HabBoy.service b/data_server/code/HabBoy.service new file mode 100644 index 0000000..b8eb559 --- /dev/null +++ b/data_server/code/HabBoy.service @@ -0,0 +1,10 @@ +[Unit] +Description=HabBoy +Wants=network-online.target +After=network-online.target + +[Service] +ExecStart=/home/mfratczak/share/dev/habboy_dev/habboy_sw/data_server/code/main.py --https --host ip --dbfile /home/mfratczak/share/dev/habboy_dev/habboy_sw/data_server/code/habboy_data.db --payload_id e11 + +[Install] +WantedBy=multi-user.target diff --git a/data_server/code/HabHubClient.py b/data_server/code/HabHubClient.py new file mode 100644 index 0000000..748fe99 --- /dev/null +++ b/data_server/code/HabHubClient.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 + + +import string +import time +import datetime +import threading +import urllib3 +import traceback +import math +import random + +import HabHubInterface +import formatSentence + + +def fake_sentence(): + # 'CALLSIGN,25,15:41:24,44.32800,-74.14427,00491,0,0,12,30.7,0.0,0.001,20.2,958,1b*6BC9' + # CALLSIGN,3748,15:41:24,44.32800,-74.14427,00491,0,0,12,30.7,0.0,0.001,20.2,958,1b*D55E + res = "" + + res += "ARY_test" + + res += "," + str(fake_sentence.id) + fake_sentence.id += 1 + + res += "," + datetime.datetime.utcnow().strftime("%H%M%S") + res += "," + str(52.0 + math.sin(float(fake_sentence.id) / 50)) # lat + res += "," + str(21.0 + math.sin(float(fake_sentence.id) / 50)) # lon + res += "," + str(80 + int(35000.0 * math.sin(float(fake_sentence.id) / 250))) # alt + res += "," + str(300 + int(100.0 * math.sin(float(fake_sentence.id) / 250))) # elev + res += "," + str( + 15.0 + 20.0 * math.sin(float(fake_sentence.id) / 250) + ) # temperature_internal + res += "," + str( + -10.0 + 20.0 * math.sin(float(fake_sentence.id) / 250) + ) # temperature_external + res += "," + str(1000.0 * (1.0 / (1 + 0.1 * fake_sentence.id))) # pressure + res += ",A" + # flags + + res += "*" + formatSentence.crc(res) + return res + + +fake_sentence.id = 1 + + +class HabHubClient(object): + """ + periodically polls habitat for specific payload telemetry + """ + + interval_seconds = 15 + + def __init__(self, i_payload_id, i_interval_seconds = None): + self.__payload_id = i_payload_id + self.__sentence_thread = None + self.__sentence_run = False + + self.__sentences_dict = {} + self.__sentence_mtx = threading.Lock() + + self.__interval_seconds = i_interval_seconds or HabHubClient.interval_seconds + + self.__last_connection_time = datetime.datetime.utcfromtimestamp(0) + self.__last_sentence_time = datetime.datetime.utcfromtimestamp(0) + + print("Initialized HabHub client with payload_id ", i_payload_id) + + def __habhub_thread_f(self): + while self.__sentence_run: + time.sleep( self.__interval_seconds ) + + sentences = [ HabHubInterface.getLastSentence(self.__payload_id) ] + self.__last_connection_time = datetime.datetime.utcnow() + # sentences = [fake_sentence()] + # print ("!!!!!!!!!!!!! FAKE !!!!!!!!!!!!!!!") + + if not sentences: + continue + + sentence = sentences[-1] + sent_id = formatSentence.sentenceToId(sentence) + + if sent_id: + with self.__sentence_mtx: + if sent_id not in self.__sentences_dict: + self.__sentences_dict[sent_id] = sentence + self.__last_sentence_time = datetime.datetime.utcnow() + # print("Habitat: ", sentence) + + def Start(self): + self.__sentence_run = True + self.__sentence_thread = threading.Thread(target=self.__habhub_thread_f) + self.__sentence_thread.start() + + def Stop(self): + print("HabHub Client Stopping ", self.__payload_id) + self.__sentence_run = False + if self.__sentence_thread and self.__sentence_thread.is_alive(): + self.__sentence_thread.join() + self.__sentence_thread = None + + def GetLastSentence(self): + res = None + with self.__sentence_mtx: + if len(self.__sentences_dict): + max_id = max(self.__sentences_dict.keys()) + if max_id: + res = self.__sentences_dict[max_id] + # return 'CALLSIGN,25,15:41:24,44.32800,-74.14427,00491,0,0,12,30.7,0.0,0.001,20.2,958,1b*6BC9' + # return fake_sentence() + return res + + def GetLastSentenceReceiveTime(self): + with self.__sentence_mtx: + return self.__last_sentence_time + + def GetLastConnectionTime(self): + return self.__last_connection_time \ No newline at end of file diff --git a/data_server/code/HabHubInterface.json b/data_server/code/HabHubInterface.json new file mode 100644 index 0000000..396023c --- /dev/null +++ b/data_server/code/HabHubInterface.json @@ -0,0 +1,106 @@ + +Flights: + +[{u"doc": {u"_id": u"af21bc2ee2b36528550e62c27dda3620", + u"_rev": u"2-f9e141dbf0f896b8b683407141cf3ce9", + u"approved": True, + u"end": u"2019-02-23T23:59:59+00:00", + u"launch": {u"location": {u"altitude": 120, + u"latitude": 52.362, + u"longitude": 21.137}, + u"time": u"2019-02-23T11:00:00+00:00", + u"timezone": u"Europe/London"}, + u"metadata": {u"group": u"SP5WWL & SP5YAM", + u"location": u"Marki, Poland", + u"project": u"Balon z Marek"}, + u"name": u"SP5WWL - 437.600MHz 75/540 7N1 RTTY & 432.500MHz APRS", + u"payloads": [u"e0ce9ad8b0d7e8b7f8deb978727f3aa7"], + u"start": u"2019-02-23T00:00:00+00:00", + u"type": u"flight"}, + u"id": u"af21bc2ee2b36528550e62c27dda3620", + u"key": [1550966399, 1550880000, u"af21bc2ee2b36528550e62c27dda3620", 0], + u"value": [u"e0ce9ad8b0d7e8b7f8deb978727f3aa7"]}] + + + + +payloads: + +[{u"doc": {u"_id": u"e0ce9ad8b0d7e8b7f8deb978727f3aa7", + u"_rev": u"1-976702d368c96a27a41fae3f56950ac5", + u"metadata": {u"description": u"Tracker_2"}, + u"name": u"SP5WWL RTTY 437.600 75/540 7N1 APRS 432.500", + u"sentences": [{u"callsign": u"SP5WWL-b", + u"checksum": u"crc16-ccitt", + u"fields": [{u"name": u"sentence_id", + u"sensor": u"base.ascii_int"}, + {u"name": u"time", + u"sensor": u"stdtelem.time"}, + {u"format": u"dd.dddd", + u"name": u"latitude", + u"sensor": u"stdtelem.coordinate"}, + {u"format": u"dd.dddd", + u"name": u"longitude", + u"sensor": u"stdtelem.coordinate"}, + {u"name": u"altitude", + u"sensor": u"base.ascii_int"}, + {u"name": u"temperature_internal", + u"sensor": u"base.ascii_int"}, + {u"name": u"battery", + u"sensor": u"base.ascii_int"}, + {u"name": u"satellites", + u"sensor": u"base.ascii_int"}, + {u"name": u"packets_ok", + u"sensor": u"base.ascii_int"}, + {u"name": u"packets_err", + u"sensor": u"base.ascii_int"}, + {u"name": u"flags", + u"sensor": u"base.string"}], + u"filters": {u"post": [{u"factor": 0.01, + u"filter": u"common.numeric_scale", + u"round": 3, + u"source": u"battery", + u"type": u"normal"}, + {u"filter": u"common.invalid_location_zero", + u"type": u"normal"}]}, + u"protocol": u"UKHAS"}], + u"time_created": u"2019-02-20T00:40:29+01:00", + u"transmissions": [{u"baud": 75, + u"description": u"UHF", + u"encoding": u"ASCII-7", + u"frequency": 437600000, + u"mode": u"USB", + u"modulation": u"RTTY", + u"parity": u"none", + u"shift": 540, + u"stop": 1}], + u"type": u"payload_configuration"}, + u"id": u"af21bc2ee2b36528550e62c27dda3620", + u"key": [1550966399, 1550880000, u"af21bc2ee2b36528550e62c27dda3620", 1], + "telemetry": [{u"callsign": u"SQ9PPT", + u"data": {u"battery": u"2.6", + u"flags": u"80", + u"packets_err": 2, + u"packets_ok": 6233, + u"satellites": 9, + u"temperature_internal": 16}, + u"gps_alt": u"621", + u"gps_heading": u"", + u"gps_lat": u"50.37177", + u"gps_lon": u"19.60548", + u"gps_speed": u"", + u"gps_time": u"2019-02-23 14:28:11", + u"mission_id": u"0", + u"picture": u"", + u"position_id": u"25950359", + u"sequence": u"993", + u"server_time": u"2019-02-23 14:28:24.613321", + u"temp_inside": u"", + u"vehicle": u"SP5WWL-b"}], + u"value": {u"_id": u"e0ce9ad8b0d7e8b7f8deb978727f3aa7"}}] + + + + + telemetry: +[] diff --git a/data_server/code/HabHubInterface.py b/data_server/code/HabHubInterface.py new file mode 100644 index 0000000..1ea9472 --- /dev/null +++ b/data_server/code/HabHubInterface.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python3 + +""" +misc utility functions for habitat queries +""" + +import string +import sys +import json +from time import time +from pprint import pprint +import urllib3 + +urllib3.disable_warnings() +http = urllib3.PoolManager() + +import formatSentence + + +def getFlights(): + _url = ( + "http://habitat.habhub.org/habitat/_design/flight/_view/end_start_including_payloads?startkey=[" + + str(int(time())) + + "]&include_docs=True" + ) + flights_json = http.request("GET", _url) + flights = json.loads(flights_json.data.decode("utf-8"))["rows"] + res = [f for f in flights if f["doc"]["type"] == "flight"] + return res + + +def getPayloads(i_flights=None): + _url = ( + "http://habitat.habhub.org/habitat/_design/flight/_view/end_start_including_payloads?startkey=[" + + str(int(time())) + + "]&include_docs=True" + ) + all_docs = http.request("GET", _url) + all_docs = json.loads(all_docs.data.decode("utf-8"))["rows"] + + if not i_flights: + i_flights = getFlights() + + flyingPayloadsIds = [] + for f in i_flights: + flyingPayloadsIds.extend(f["doc"]["payloads"]) + + res = [] + for f in all_docs: + if ( + f["doc"]["type"] == "payload_configuration" + and f["doc"]["_id"] in flyingPayloadsIds + ): + # f['telemetry'] = getTelemetry( f['doc']['sentences'][0]['callsign'] ) + res.append(f) + + return res + + +def getCallsignsForPayloadId(payload_id): + flights = getFlights() + payloads = getPayloads(flights) + for p in payloads: + if p["doc"]["_id"] == payload_id: + return p["doc"]["sentences"][0]["callsign"] + return None + + +""" +def getTelemetry(i_payloadName, max_positions=1 ): + data_url = "http://spacenear.us/tracker/datanew.php" + data_str = "mode=position&type=positions&format=json&max_positions=" + str(max_positions) + "&position_id=0&vehicles=" + urllib2.quote(i_payloadName) + _url = data_url + '?' + data_str + res = http.request('GET', _url) + res = json.loads(res.data.decode('utf-8')) + res = res['positions']['position'] + + return res +""" + + +def defaultSensorsInfo(i_sentence): + """ + treat all sensors as string + except: sentence_id, time, lat, lon, alt + """ + + if not i_sentence: + return None + + num_sensors = len(formatSentence.getData(i_sentence)) + + sensors_info_arr = [ + {"name": "sensor_" + str(x), "sensor": "base.string"} + for x in range(num_sensors) + ] + + # sentence_id + sensors_info_arr[0]["name"] = "sentence_id" + sensors_info_arr[0]["sensor"] = "base.ascii_int" + + # time + sensors_info_arr[1]["name"] = "time" + sensors_info_arr[1]["sensor"] = "stdtelem.time" + + # lat + sensors_info_arr[2]["name"] = "latitude" + sensors_info_arr[2]["sensor"] = "stdtelem.coordinate" + + # lon + sensors_info_arr[3]["name"] = "longitude" + sensors_info_arr[3]["sensor"] = "stdtelem.coordinate" + + # alt + sensors_info_arr[4]["name"] = "altitude" + sensors_info_arr[4]["sensor"] = "base.ascii_float" + + return sensors_info_arr + + +def getSentenceInfo(i_payload_id, i_sentence=None): + # print('getSentenceInfo', (i_payload_id, i_sentence)) + example_output = [ + {"name": "sentence_id", "sensor": "base.ascii_int"}, + {"name": "time", "sensor": "stdtelem.time"}, + {"name": "latitude", "sensor": "stdtelem.coordinate", "format": "dd.dddd"}, + {"name": "longitude", "sensor": "stdtelem.coordinate", "format": "dd.dddd"}, + {"name": "altitude", "sensor": "base.ascii_int"}, + {"name": "temperature_internal", "sensor": "base.ascii_float"}, + {"name": "temperature_external", "sensor": "base.ascii_float"}, + {"name": "satellites", "sensor": "base.ascii_int"}, + {"name": "some_float1", "sensor": "base.ascii_float"}, + {"name": "some_float2", "sensor": "base.ascii_float"}, + {"name": "some_float3", "sensor": "base.ascii_float"}, + {"name": "some_float4", "sensor": "base.ascii_float"}, + {"name": "packets_err", "sensor": "base.ascii_int"}, + {"name": "flags", "sensor": "base.string"}, + ] + + # ARY + example_output = [ + {"name": "sentence_id", "sensor": "base.ascii_int"}, + {"name": "time", "sensor": "stdtelem.time"}, + {"name": "latitude", "sensor": "stdtelem.coordinate", "format": "dd.dddd"}, + {"name": "longitude", "sensor": "stdtelem.coordinate", "format": "dd.dddd"}, + {"name": "altitude", "sensor": "base.ascii_int"}, + {"name": "elev", "sensor": "base.ascii_int"}, + {"name": "temperature_internal", "sensor": "base.ascii_float"}, + {"name": "temperature_external", "sensor": "base.ascii_float"}, + {"name": "pressure", "sensor": "base.ascii_float"}, + {"name": "mesg", "sensor": "base.string"}, + ] + + # return example_output + + result = None + + payloads = getPayloads(getFlights()) + for p in payloads: + # print("payload ", p['doc']['_id'], p['doc']['name'], i_payload_id) + # if p['doc']['_id'] == i_payload_id or p['doc']['name'] == i_payload_id: + if ( + p["doc"]["_id"] == i_payload_id + or p["doc"]["sentences"][0]["callsign"] == i_payload_id + ): + result = p["doc"]["sentences"][0]["fields"] + break + else: + pass + # print(p) + + ''' + if not result and i_sentence: + result = defaultSensorsInfo(i_sentence) + print("Building Default sensor datainfo based on sentence: " + i_sentence) + pprint(result) + return result + ''' + + return result + + +""" +def getLastSentence_faked(i_payload_name): + getLastSentence.last_id += 1 + result = "CALLSIGN," + str(getLastSentence.last_id) + ",15:41:24,44.32800,-74.14427,00491,0,0,12,30.7,0.0,0.001,20.2,958,1b*6BC9" + result = formatSentence.formatSentence(result) + return "" + return result +getLastSentence_faked.last_id = 0 +""" + + +def getLastSentence(i_payload_id): + _url = ( + "http://habitat.habhub.org/habitat/_design/flight/_view/end_start_including_payloads?startkey=[" + + str(int(time())) + + "]&include_docs=True" + ) + + try: + flights_json = http.request("GET", _url) + except urllib3.exceptions.MaxRetryError: + return None + + flights = json.loads(flights_json.data.decode("utf-8"))["rows"] + + flight_id = None + for f in flights: + if f["doc"]["type"] != "flight": + continue + if i_payload_id in f["doc"]["payloads"]: + flight_id = f["doc"]["_id"] + break + + if flight_id: + try: + r = http.request( + "GET", + 'http://habitat.habhub.org/habitat/_design/payload_telemetry/_view/flight_payload_time?startkey=["' + + flight_id + + '","' + + i_payload_id + + '",[]]&endkey=["' + + flight_id + + '","' + + i_payload_id + + '"]&include_docs=True&descending=True&limit=1', + ) + except urllib3.exceptions.MaxRetryError: + return None + + telemetry = json.loads(r.data.decode("utf-8"))["rows"] + if telemetry: + try: + telemetry = json.loads(r.data.decode("utf-8"))["rows"][-1] + last_sentence = telemetry["doc"]["data"]["_sentence"] + last_sentence = last_sentence.strip() + except KeyError: + pprint(telemetry) + return "" + print(last_sentence) + return last_sentence + return None + + +def uploadChaseCar(car_data): + r = None + try: + r = http.request( + "GET", + 'http://spacenear.us/tracker/track.php', + fields = car_data + ) + except urllib3.exceptions.MaxRetryError: + return False + + if r.status != 200: + print(r.data) + return False + + return True + +if __name__ == "__main__": + + flights = getFlights() + payloads = getPayloads(flights) + + """ + print "Flights:" + pprint(flights) + print "===================================" + + print "payloads:" + pprint(payloads) + print "===================================" + + for p in payloads: + print "telemetry ", p['doc']['name'] + pprint( getTelemetry(p['doc']['name']) ) + print "===================================" + + print('M6') + pprint ( getTelemetry('M6') ) + print "===================================" + + print( getSentenceInfo('MI6') ) + """ + + pprint(getSentenceInfo("5facec9731fc190ce510c9f1ee6e4bb8")) + # pprint( getLastSentence('5facec9731fc190ce510c9f1ee6e4bb8') ) + + # ////////////////////////////// + + # print( getSentenceInfo( 0, 'fro3,3,220759,52.029996,21.999550,130.0,80.0,80.0,80.0*CE7D') ) + diff --git a/data_server/code/HabdecClient.py b/data_server/code/HabdecClient.py new file mode 100644 index 0000000..af191a9 --- /dev/null +++ b/data_server/code/HabdecClient.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 + +# BASIC COMMUNICATION WITH HABDEC WEBSOCKET SERVER +# + + +import sys +import string +from ws4py.client.threadedclient import WebSocketClient # pip install ws4py +import struct +import time +import threading +import bisect +import traceback +import datetime + +import HabHubInterface +import formatSentence + +# GLOBAL VARIABLES: +# +WS = None # websocket +WS_THREAD = None +SENTENCES = [] + + +# WEBSOCKET CLIENT +# +class HabdecClient(WebSocketClient): + def __init__(self, i_habdec_server): + if not i_habdec_server.lower().startswith('ws://'): + i_habdec_server = 'ws://' + i_habdec_server + self.habdec_server = i_habdec_server + WebSocketClient.__init__(self, self.habdec_server) + + # self.__sentences_dict = {} + # self.__sentences_sorted_ids = [] + self.__sentences_arr = [] + self.__sentence_mtx = threading.Lock() + + self.__sentence_thread = None + self.__sentence_run = False + self.__habdec_thread = None + self.__habdec_run = False + self.__habdec_connection_initialized = False + + self.__last_connection_time = datetime.datetime.utcfromtimestamp(0) + self.__last_sentence_time = datetime.datetime.utcfromtimestamp(0) + + def opened(self): + print("Opened Connection") + + def closed(self, code, reason=None): + print("Closed down", code, reason) + + def __connect(self): + if self.terminated: + WebSocketClient.__init__(self, self.habdec_server) + + # while self.__sentence_run: + while self.__habdec_run: + try: + print("Connecting to Habdec ", self.habdec_server, "... ") + self.connect() + print("Connected to Habdec ", self.habdec_server, "... ") + return + except KeyboardInterrupt: + print("Connection interruped KeyboardInterrupt") + return + except: + # print("Failed connection.") + # print('traceback: ', traceback.format_exc()) + time.sleep(1) + + def Start(self): + self.__habdec_run = True + self.__habdec_thread = threading.Thread(target=self.run_forever) + self.__habdec_thread.start() + + self.__sentence_run = True + self.__sentence_thread = threading.Thread(target=self.__get_sentence_thread_f) + self.__sentence_thread.start() + + def Stop(self): + print("Habdec Client Stopping... " + self.habdec_server) + self.__sentence_run = False + self.__habdec_run = False + + if self.__sentence_thread and self.__sentence_thread.is_alive(): + self.__sentence_thread.join() + + try: + self.close() + self.__habdec_connection_initialized = False + except: + print("Error HabdecClient::Stop -> close()") + print(traceback.format_exc()) + self.__habdec_thread = None + + def __get_sentence_thread_f(self): + if not self.__habdec_connection_initialized: + self.__connect() + self.__habdec_connection_initialized = True + while self.__sentence_run: + if self.terminated: + self.__connect() + try: + self.send("cmd::sentence") + except: + print("Problem communicating Habdec") + print("traceback: ", traceback.format_exc()) + time.sleep(1) + + def received_message(self, m): + self.__last_connection_time = datetime.datetime.utcnow() + i_data = None + try: + i_data = m.data.decode() + except: + print(self.habdec_server + " - Can't decode data.") + if not i_data: + return + + if i_data.startswith("cmd::info:sentence"): + sent_str = i_data[len("cmd::info:sentence:") :] + sentences = formatSentence.formatSentence(sent_str) + if sentences: + sent = sentences[-1] + sent_id = formatSentence.sentenceToId(sent) + if sent_id: + with self.__sentence_mtx: + self.__sentences_arr.append( sent ) + self.__last_sentence_time = datetime.datetime.utcnow() + # if sent_id not in self.__sentences_dict: + # self.__sentences_dict[sent_id] = sent + # bisect.insort(self.__sentences_sorted_ids, sent_id) + # self.__last_sentence_time = datetime.datetime.utcnow() + + def GetLastSentence(self): + res = None + with self.__sentence_mtx: + if len(self.__sentences_arr): + return self.__sentences_arr[-1] + # if len(self.__sentences_sorted_ids): + # res = self.__sentences_dict[self.__sentences_sorted_ids[-1]] + return res + + def GetLastSentenceReceiveTime(self): + with self.__sentence_mtx: + return self.__last_sentence_time + + def GetLastConnectionTime(self): + return self.__last_connection_time \ No newline at end of file diff --git a/data_server/code/HttpInterface.py b/data_server/code/HttpInterface.py new file mode 100644 index 0000000..dbfd8bb --- /dev/null +++ b/data_server/code/HttpInterface.py @@ -0,0 +1,616 @@ +#!/usr/bin/env python3 + +# access over HTTP +# + +''' +("/habboy/api/v1/params", method=['OPTIONS', 'GET']) +("/habboy/api/v1/params/payload_id", method=['OPTIONS', 'GET', 'PUT']) +("/habboy/api/v1/payloads", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//sensors", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//sensors/", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//sensors//last", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//gps", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//gps/last", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//sentences/last", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//sentences/lastdata", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//sentences/lastId", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//receiver_stats", method=['OPTIONS', 'GET']) +("/habboy/api/v1/payloads//predict", method=['OPTIONS', 'GET']) +("/habboy/api/v1/habdec/add/", method=['OPTIONS', 'GET']) +("/habboy/api/v1/habdec/del/", method=['OPTIONS', 'GET']) +("/habboy/api/v1/habdec/get", method=['OPTIONS', 'GET']) +("/habboy/api/v1/sentence//", method=['OPTIONS', 'PUT']) +("/habboy/api/v1/chasecar/", method=['OPTIONS', 'POST']) +("/habboy/api/v1/ctrl/habdec_stop", method=['OPTIONS', 'GET']) +("/habboy/api/v1/ctrl/habdec_start", method=['OPTIONS', 'GET']) +("/habboy/api/v1/ctrl/spy_stop", method=['OPTIONS', 'GET']) +("/habboy/api/v1/ctrl/spy_start", method=['OPTIONS', 'GET']) +("/habboy/api/v1/ctrl/reboot", method=['OPTIONS', 'GET']) +("/habboy/api/v1/ctrl/restart", method=['OPTIONS', 'GET']) +("/habboy/api/v1/ctrl/halt", method=['OPTIONS', 'GET']) +("/habboy/api/v1/gps", method=['OPTIONS', 'GET']) +("/habboy/api/v1/utcnow", method=['OPTIONS', 'GET']) +("/habboy/api/v1/info", method=['OPTIONS', 'GET']) +("/habboy", method=['OPTIONS', 'GET']) +('/') +''' + +__all__ = ['RUN'] + + +import os +import json +import bottle +import time +import datetime +import traceback +import sys +import shlex +import subprocess +import formatSentence +from pprint import pprint +from copy import deepcopy + +from cheroot import wsgi +from cheroot.ssl.builtin import BuiltinSSLAdapter + +import HabdecClient +import HabHubClient +import HabHubInterface +from get_ip import get_ip_local + +DB = None +# G_EXP_BURST_ALT = 30000 # expected burst altitude - meters +G_PREDICTOR = None +G_HABDEC_CLIENTS = {} +G_HABHUB_CLIENTS = {} +G_OPTIONS = {} +G_HABDEC_CLIENTS = None + +def eprint(*args, **kwargs): + print(*args, file=sys.stderr, **kwargs) + +class JSONEncoder(json.JSONEncoder): + def default(self, o): + if isinstance(o, datetime.datetime): + return o.isoformat() + '+00:00' + else: + return json.JSONEncoder.default(self, o) + + +def merge_dicts(*args): + result = {} + for dictionary in args: + result.update(dictionary) + return result + + +def redirect_http_to_https(callback): + '''Bottle plugin that redirects all http requests to https''' + + def wrapper(*args, **kwargs): + scheme = bottle.request.urlparts[0] + if scheme == 'http': + # request is http; redirect to https + bottle.redirect(bottle.request.url.replace('http', 'https', 1)) + else: + # request is already https; okay to proceed + return callback(*args, **kwargs) + return wrapper + + +def time_to_string(i_datetime): + return i_datetime.isoformat() + '+00:00' + # return datetime.datetime.strftime(i_datetime, "%Y-%m-%d %H:%M:%S") + + + + +class EnableCors(object): + name = "enable_cors" + api = 2 + + def apply(self, fn, context): + def _enable_cors(*args, **kwargs): + # set CORS headers + bottle.response.headers["Access-Control-Allow-Origin"] = "*" + bottle.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS" + bottle.response.headers["Access-Control-Allow-Headers"] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token" + + # actual request; reply with the actual response + if bottle.request.method != "OPTIONS": + return fn(*args, **kwargs) + + return _enable_cors + + +# Create our own sub-class of Bottle's ServerAdapter +# so that we can specify SSL. Using just server='cherrypy' +# uses the default cherrypy server, which doesn't use SSL +class SSLCherryPyServer(bottle.ServerAdapter): + def run(self, handler): + server = wsgi.Server( (self.host, self.port), handler) + server.ssl_adapter = BuiltinSSLAdapter("cacert.pem", "privkey.pem") + + # By default, the server will allow negotiations with extremely old protocols + # that are susceptible to attacks, so we only allow TLSv1.2 + # server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1 + # server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1_1 + + try: + server.start() + finally: + server.stop() + + +application = bottle.app() +application.install(EnableCors()) + + +###################################################################### +###################################################################### + + +def GetRequestValueWithDefault(i_req, i_token, i_type, defaultValue): + """ + get value from GET request + ensure proper type + return defaultValue on error or missing + """ + if type(defaultValue) != i_type: + raise ValueError("defaultValue is of wrong type") + + if i_token not in i_req: + return defaultValue + val_str = i_req[i_token] + + if i_type == bool: + res = defaultValue + if val_str == "1" or val_str.lower() == "true": + res = True + elif val_str == "0" or val_str.lower() == "false": + res = False + return res + elif i_type == int: + try: + res = int(val_str) + return res + except: + return defaultValue + else: + # string + return val_str + + return defaultValue + + +@application.route("/habboy/api/v1/params", method=['OPTIONS', 'GET']) +def GetPayloadIdAndCallsign(): + bottle.response.content_type = "application/javascript" + global G_OPTIONS + res = {} + res['payload_id'] = G_OPTIONS['payload_id'] + res['callsign'] = G_OPTIONS['callsign'] + res['payloads'] = G_OPTIONS['payloads'] + res['burst'] = G_OPTIONS['burst'] + with G_OPTIONS['clients_mutex']: + res['habdec_clients'] = list( G_OPTIONS['habdec_clients'].keys() ) + return JSONEncoder().encode(res) + + +@application.route("/habboy/api/v1/params/payload_id", method=['OPTIONS', 'GET', 'PUT']) +def PayloadId(): + global G_PAYLOAD_ID + global G_CALLSIGN + if bottle.request.method == 'GET': + bottle.response.content_type = "application/json" + return json.dumps( {'payload_id': G_OPTIONS['payload_id'], 'callsign': G_OPTIONS['callsign']} ) + + if bottle.request.method == 'PUT': + data = bottle.request.json + if 'callsign' in data and 'payload_id' in data: + old_pid = G_OPTIONS['payload_id'] + new_pid = data['payload_id'] + if old_pid in G_OPTIONS['habhub_clients']: + G_OPTIONS['habhub_clients'][old_pid].Stop() + del G_OPTIONS['habhub_clients'][old_pid] + + G_OPTIONS['callsign'] = data['callsign'] + G_OPTIONS['payload_id'] = new_pid + + G_OPTIONS['habhub_clients'][new_pid] = HabHubClient.HabHubClient(new_pid) + G_OPTIONS['habhub_clients'][new_pid].Start() + + +@application.route("/habboy/api/v1/payloads", method=['OPTIONS', 'GET']) +def GetVehicles(): + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "application/json" + data = DB.getAllPayloadIds() + return json.dumps(data) + + +@application.route("/habboy/api/v1/payloads//sensors", method=['OPTIONS', 'GET']) +def GetVehicleSensors(payload): + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "application/json" + sensors_info = DB.getSensorsInfo(payload) + res = [{ + 'name': sens['name'], + 'sensor': sens['sensor'], + 'sql_data_type': sens['sql_data_type'], + } for sens in sensors_info] + return JSONEncoder().encode(res) + + +@application.route("/habboy/api/v1/payloads//sensors/", method=['OPTIONS', 'GET']) +def GetSensorData(payload, sensor): + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "application/json" + + last_time = GetRequestValueWithDefault(bottle.request.query, "time", str, time_to_string(datetime.datetime.utcfromtimestamp(0))) + + sensors = [sensor] + if sensor == "*": + sensors = DB.getSensorsList(payload) + elif "," in sensor: + sensors = sensor.split(",") + + if "time" in sensors: + sensors.remove("time") + + res = {} + for _sensor in sensors: + data = DB.getTelemetryByTime(payload, _sensor, last_time) + if data: + data["times"] = [ + time_to_string(x) for x in data["times"] + ] + res[_sensor] = data + + return json.dumps(res) + + +@application.route("/habboy/api/v1/payloads//sensors//last", method=['OPTIONS', 'GET']) +def GetSensorDataLast(payload, sensor): + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "application/json" + + sensors = [sensor] + if sensor == "*": + sensors = DB.getSensorsList(payload) + elif "," in sensor: + sensors = sensor.split(",") + if "time" in sensors: + sensors.remove("time") + + res = {} + for _sensor in sensors: + data = DB.getTelemetryLast(payload, _sensor) + if data: + data["times"] = [time_to_string(x) for x in data["times"] ] + res[_sensor] = data + + return json.dumps(res) + + +@application.route("/habboy/api/v1/payloads//gps", method=['OPTIONS', 'GET']) +def GetGps(payload): + """ + result: + [ ["014056", [52.15429, 21.03445, 7223]], ... ] + """ + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "application/json" + + last_time = GetRequestValueWithDefault(bottle.request.query, "time", str, time_to_string(datetime.datetime.utcfromtimestamp(0))) + + lat = DB.getTelemetryByTime(payload, "latitude", time_to_string(datetime.datetime.utcfromtimestamp(0))) + lon = DB.getTelemetryByTime(payload, "longitude", time_to_string(datetime.datetime.utcfromtimestamp(0))) + alt = DB.getTelemetryByTime(payload, "altitude", time_to_string(datetime.datetime.utcfromtimestamp(0))) + + if not lat or not lon or not alt: + return "{}" + + lat["times"] = [time_to_string(x) for x in lat["times"]] + lon["times"] = [time_to_string(x) for x in lon["times"]] + alt["times"] = [time_to_string(x) for x in alt["times"]] + + data = list(zip(lat["values"], lon["values"], alt["values"])) + times = lat["times"] + res = list(zip(times, data)) + return json.dumps(res) + + +@application.route("/habboy/api/v1/payloads//gps/last", method=['OPTIONS', 'GET']) +def GetGpsLast(payload): + """ + result: + [ ["014059", [52.15429, 21.03445, 12223]] ] + """ + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "application/json" + + lat = DB.getTelemetryLast(payload, "latitude") + lon = DB.getTelemetryLast(payload, "longitude") + alt = DB.getTelemetryLast(payload, "altitude") + + if not lat or not lon or not alt: + return "{}" + + lat["times"] = [time_to_string(x) for x in lat["times"]] + lon["times"] = [time_to_string(x) for x in lon["times"]] + alt["times"] = [time_to_string(x) for x in alt["times"]] + + data = list(zip(lat["values"], lon["values"], alt["values"])) + times = lat["times"] + res = list(zip(times, data)) + return json.dumps(res) + + +@application.route("/habboy/api/v1/payloads//sentences/last", method=['OPTIONS', 'GET']) +def GetSentenceLast(payload): + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "text/plain" + + last_sentence_data = DB.getLastSentence(payload) + # return last_sentence_data[-3] + return last_sentence_data['_SENTENCE'] + +@application.route("/habboy/api/v1/payloads//sentences/lastdata", method=['OPTIONS', 'GET']) +def GetSentenceLastData(payload): + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "application/json" + + last_sentence_data = DB.getLastSentence(payload) + return JSONEncoder().encode( last_sentence_data ) + +@application.route("/habboy/api/v1/payloads//sentences/lastId", method=['OPTIONS', 'GET']) +def GetSentenceLastId(payload): + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "text/plain" + + last_sentence_id = DB.getLastSentenceId(payload) + return last_sentence_id + +@application.route("/habboy/api/v1/payloads//receiver_stats", method=['OPTIONS', 'GET']) +def GetReceiverStats(payload): + global G_OPTIONS + DB = G_OPTIONS['sentences_db'] + bottle.response.content_type = "json" + + res = DB.getReceiversStats(payload) + return res + +@application.route("/habboy/api/v1/payloads//predict", method=['OPTIONS', 'GET']) +def GetPayloadPrediction(payload): + bottle.response.content_type = "application/json" + global G_OPTIONS + get_predict_fun = G_OPTIONS['get_predict'] + if get_predict_fun: + flight_path = get_predict_fun() + return JSONEncoder().encode( flight_path ) + return json.dumps( {} ) + +@application.route("/habboy/api/v1/habdec/add/", method=['OPTIONS', 'GET']) +def HabdecAdd(habdec_addr): + bottle.response.content_type = "text/plain" + global G_OPTIONS + + if not habdec_addr.lower().startswith('ws://'): + habdec_addr = 'ws://' + habdec_addr + + with G_OPTIONS['clients_mutex']: + if habdec_addr in G_OPTIONS['habdec_clients']: + return 'already exists' + + if not habdec_addr.lower().startswith('ws://'): + habdec_addr = 'ws://' + habdec_addr + + if habdec_addr not in G_OPTIONS['habdec_clients']: + G_OPTIONS['habdec_clients'][habdec_addr] = HabdecClient.HabdecClient(habdec_addr) + G_OPTIONS['habdec_clients'][habdec_addr].Start() + + return "OK" + + +@application.route("/habboy/api/v1/habdec/del/", method=['OPTIONS', 'GET']) +def HabdecDel(habdec_addr): + global G_OPTIONS + if not habdec_addr.lower().startswith('ws://'): + habdec_addr = 'ws://' + habdec_addr + with G_OPTIONS['clients_mutex']: + if habdec_addr in G_OPTIONS['habdec_clients']: + G_OPTIONS['habdec_clients'][habdec_addr].Stop() + del G_OPTIONS['habdec_clients'][habdec_addr] + + bottle.response.content_type = "text/plain" + return "OK" + + +@application.route("/habboy/api/v1/habdec/get", method=['OPTIONS', 'GET']) +def HabdecGet(): + global G_OPTIONS + bottle.response.content_type = "application/json" + with G_OPTIONS['clients_mutex']: + habdecs = G_OPTIONS['habdec_clients'].keys() + return json.dumps( list(habdecs) ) + + +@application.route("/habboy/api/v1/gps", method=['OPTIONS', 'GET']) +def GetHabboyGps(): + bottle.response.content_type = "application/json" + if G_OPTIONS['get_gps']: + gps = deepcopy( G_OPTIONS['get_gps']() ) + gps['time'] = gps['time'].isoformat() + '+00:00' + gps['parse_timestamp'] = gps['parse_timestamp'].isoformat() + '+00:00' + return json.dumps( gps ) + return json.dumps( {} ) + + +@application.route("/habboy/api/v1/utcnow", method=['OPTIONS', 'GET']) +def GetUtcNow(): + bottle.response.content_type = "text/plain" + return datetime.datetime.utcnow().isoformat() + '+00:00' + + +@application.route("/habboy/api/v1/info", method=['OPTIONS', 'GET']) +def GetHabboyInfo(): + global G_OPTIONS + bottle.response.content_type = "application/json" + res = {} + if G_OPTIONS['get_stats']: + res = G_OPTIONS['get_stats']() + return JSONEncoder().encode( res ) + + +@application.route("/habboy/api/v1/chasecar/", method=['OPTIONS', 'POST']) +def Habdec_ChasecarUpload(chasecar_name): + bottle.response.content_type = "application/json" + + if not chasecar_name.endswith('_chase'): + return JSONEncoder().encode( {'result': 'error', 'what': 'car name does not end with _chase'} ) + + if bottle.request.method == 'POST': + params = merge_dicts(dict(bottle.request.forms), dict(bottle.request.query.decode())) + params = list(params.keys())[0] # this is very weird + params = json.loads(params) + + try: + data = {'vehicle' : chasecar_name, + 'time' : datetime.datetime.utcnow().strftime("%H%M%S"), + 'lat' : params["latitude"], + 'lon' : params["longitude"], + 'alt' : params["altitude"], + 'speed' : params["ground_speed_mps"], + 'heading' : params["heading"], + 'pass' : "aurora"} + except KeyError as e: + return JSONEncoder().encode( {'result': 'error', 'what': 'KeyError: ' + str(e)} ) + try: + if not HabHubInterface.uploadChaseCar(data): + return JSONEncoder().encode( {'result': 'error', 'what': 'Connection Error'} ) + except: + eprint(traceback.format_exc()) + return JSONEncoder().encode( {'result': 'error', 'what': 'Other Exception'} ) + + return JSONEncoder().encode( {'result': 'ok'} ) + return json.dumps( {} ) + + +@application.route("/habboy/api/v1/ctrl/habdec_stop", method=['OPTIONS', 'GET']) +def habdec_stop(): + os.system('sudo systemctl stop habdec') + bottle.response.content_type = "application/json" + return json.dumps({}) + +@application.route("/habboy/api/v1/ctrl/habdec_start", method=['OPTIONS', 'GET']) +def habdec_start(): + os.system('sudo systemctl start habdec') + bottle.response.content_type = "application/json" + return json.dumps({}) + + +@application.route("/habboy/api/v1/ctrl/spy_stop", method=['OPTIONS', 'GET']) +def spy_stop(): + os.system('sudo systemctl stop spyserver') + bottle.response.content_type = "application/json" + return json.dumps({}) + +@application.route("/habboy/api/v1/ctrl/spy_start", method=['OPTIONS', 'GET']) +def spy_start(): + os.system('sudo systemctl start spyserver') + bottle.response.content_type = "application/json" + return json.dumps({}) + + +@application.route("/habboy/api/v1/ctrl/reboot", method=['OPTIONS', 'GET']) +def Reboot(): + os.system('sudo reboot') + + +@application.route("/habboy/api/v1/sentence//", method=['OPTIONS', 'PUT']) +def SententenceUpload(uploader, sentence): + if bottle.request.method == 'PUT': + # data = bottle.request.json + if sentence: + if G_OPTIONS['sentences_db'].insert(i_sentence = sentence, i_RECEIVER = uploader): + return json.dumps ( {'result': 1} ) + else: + eprint('DB Input FAIL') + return json.dumps ( {'result': 0} ) + + +@application.route("/habboy/api/v1/ctrl/restart", method=['OPTIONS', 'GET']) +def Restart(): + os.system('sudo systemctl daemon-reload') + os.system('sudo systemctl restart habboy_advertise.service') + os.system('sudo systemctl restart habdec_advertise.service') + os.system('sudo systemctl restart habdec.service') + os.system('sudo systemctl restart habboy.service') + bottle.response.content_type = "application/json" + return json.dumps({}) + + +@application.route("/habboy/api/v1/ctrl/halt", method=['OPTIONS', 'GET']) +def Halt(): + os.system('sudo shutdown now') + bottle.response.content_type = "application/json" + return json.dumps({}) + + +@application.route("/habboy", method=['OPTIONS', 'GET']) +def HabboyDiscovery(): + bottle.response.content_type = "application/json" + return json.dumps({'HABBOY': 1}) + + +@application.route('/') +def route_root(): + new_url = bottle.request.url[0:bottle.request.url.rindex(':')] + '/habboy' + res = ''.format(new_url) + return res + + +def RUN(hostname, + port, + is_https, + i_opts, + debug=True, + reloader=True): + + global DB + DB = i_opts['sentences_db'] + + global G_OPTIONS + G_OPTIONS = i_opts + G_OPTIONS['start_time'] = datetime.datetime.utcnow() + + if not hostname: + hostname = get_ip_local() + + if is_https: + print("AS HTTPS") + application.install(redirect_http_to_https) + bottle.run( + host=hostname, + port=port, + debug=debug, + reloader=reloader, + server=SSLCherryPyServer, + ) + else: + bottle.run(host=hostname, port=port, debug=debug, reloader=reloader, quiet=True) + +if __name__ == "__main__": + pprint( get_process_stats(['habdecWebsocketServer', 'habboy_data']) ) \ No newline at end of file diff --git a/data_server/code/SentencesDB.py b/data_server/code/SentencesDB.py new file mode 100644 index 0000000..88cffb8 --- /dev/null +++ b/data_server/code/SentencesDB.py @@ -0,0 +1,801 @@ +#!/usr/bin/env python3 + + +import os +import string +import threading +from pprint import pprint, pformat +# import bisect +import datetime +import dateutil.parser +import traceback +import json +import math +from copy import deepcopy + +import formatSentence +import HabHubInterface + +import sqlite3 +from sqlite3 import Error as sqerr + + +C_BLACK = "\033[1;30m" +C_RED = "\033[1;31m" +C_GREEN = "\033[1;32m" +C_BROWN = "\033[1;33m" +C_BLUE = "\033[1;34m" +C_MAGENTA = "\033[1;35m" +C_CYAN = "\033[1;36m" +C_LIGHTGREY = "\033[1;37m" +C_OFF = "\033[0m" +C_CLEAR = "\033[2K" + + +def sentence_time_formatter(i_str): + result = datetime.datetime.utcnow() + in_time = None + if ":" in i_str: + in_time = datetime.datetime.strptime(i_str, "%H:%M:%S") + else: + if len(i_str) < 6: + i_str = i_str.zfill(6) + in_time = datetime.datetime.strptime(i_str, "%H%M%S") + + result = result.replace(hour = in_time.hour) + result = result.replace(minute = in_time.minute) + result = result.replace(second = in_time.second) + result = result.replace(microsecond = 0) + return result + +def coordinate_formatter(i_coord, i_format): + if i_format == 'dd.dddd': # decimals + degrees = float(i_coord) + return degrees + elif i_format == 'ddmm.mmmm': # degrees/minutes 02145.4512 = 21 degrees, 45 minutes 45.12 seconds + coord = float(i_coord) + degrees = math.trunc(coord/100.0) + minutes = coord - 100.0 * degrees + return (degrees + minutes/60.0) + +def sensor_type_converter( i_sensor ): + s_name = i_sensor['name'] + s_type = i_sensor['sensor'] + if s_type == "base.ascii_int": + return lambda x: int(float(x)) + elif s_type == "base.ascii_float": + return lambda x: float(x) + elif s_type == "base.string": + if s_name == 'time': + return sentence_time_formatter + return lambda x: x + elif s_type == "stdtelem.time": + return sentence_time_formatter + elif s_type == "stdtelem.coordinate": + if 'format' in i_sensor: + return lambda x: coordinate_formatter(x, i_sensor['format']) + else: + return lambda x: float(x) + else: + lambda x: x + +def is_sensor_numeric(i_sensor_type): + if i_sensor_type == "base.ascii_int": + return True + elif i_sensor_type == "base.ascii_float": + return True + elif i_sensor_type == "base.string": + return False + elif i_sensor_type == "stdtelem.time": + return False + elif i_sensor_type == "stdtelem.coordinate": + return False + else: + return False + +def sensor_sql_type(i_sensor): + s_type = i_sensor["sensor"] + if s_type == "base.ascii_int": + return "integer" + elif s_type == "base.ascii_float": + return "real" + elif s_type == "base.string": + if(i_sensor['name'] == 'time'): + return 'timestamp' + return "text" + elif s_type == "stdtelem.time": + return "timestamp" + elif s_type == "stdtelem.coordinate": + return "real" + else: + return "text" + +class VehicleData(object): + """ + keeps parsed data for specific callsign + """ + + def __init__(self, i_sentence_info): + # print("VehicleData init") + # pprint(i_sentence_info) + + if not i_sentence_info: + print('VehicleData init, no sentence info') + raise ValueError + + self.__IDs = [] # list of sentence TIMESTAMPS + + # indexed with telemetry sensor name + # each item is a dict + # self.__data['altitude']['values'] = [] # raw values + # self.__data['altitude']['accum'] = [] # sum of values + # self.__data['altitude']['min'] = [] + # self.__data['altitude']['max'] = [] + # self.__data['altitude']['avg'] = [] + self.__data = {} + + # info about telemetry datatypes + # indexed by position in sentence, excluding callsing + self.__data_info = deepcopy(i_sentence_info) + # self.__data_info = HabHubInterface.getSentenceInfo( + # self.__payloadName, i_sentence + # ) + + if not self.__data_info: + print(10 * "VehicleData init - no sentence info. exit.\n") + return + raise ValueError + + for i in range(len(self.__data_info)): + for k in self.__data_info[i]: + self.__data_info[i][str(k)] = str(self.__data_info[i][k]) + + for i in range(len(self.__data_info)): + if "sensor" not in self.__data_info[i]: + continue + self.__data_info[i]["converter"] = sensor_type_converter( self.__data_info[i] ) + self.__data_info[i]["is_numeric"] = is_sensor_numeric( self.__data_info[i]["sensor"] ) + + def __repr__(self): + print("Vehicle Data:") + print("__data") + pprint(self.__data) + pprint(self.__data_info) + + def to_str(self): + return pformat(self.__data) + + def add(self, i_sentence, i_sentence_timestamp): + sentences = formatSentence.formatSentence(i_sentence) + for s in sentences: + + sensor_values_str_arr = formatSentence.getData(s) + if len(sensor_values_str_arr) != len(self.__data_info): + pprint(self.__data_info) + raise ValueError( + "VehicleData ", + # self.__payloadName, + " Wrong Sentence Format (values count): ", + i_sentence, + len(sensor_values_str_arr), + len(self.__data_info), + ) + + sentence_id = i_sentence_timestamp + + # do not accept sentences older than last - this would require to recompute all stats + if self.__IDs and sentence_id <= self.__IDs[-1]: + return + + self.__IDs.append(sentence_id) + # insert_index = self.__IDs.index(sentence_id) + + # sentence_time = sentence_time_formatter(sensor_values_str_arr[1]) + # self.__times.append(i_sentence_timestamp) + + if not self.__data: + for i in range( 2, len(sensor_values_str_arr) ): # skip sentence_id and time + sensor = self.__data_info[i]["name"] + self.__data[sensor] = {} + self.__data[sensor]["is_numeric"] = self.__data_info[i]["is_numeric"] + self.__data[sensor]["values"] = [] # raw values + if self.__data_info[i]["is_numeric"]: + self.__data[sensor]["accum"] = [] # sum of values + self.__data[sensor]["min"] = [] + self.__data[sensor]["max"] = [] + self.__data[sensor]["avg"] = [] + self.__data[sensor]["dVdT"] = [] + + for i in range(2, len(sensor_values_str_arr)): # skip sentence_id and time + sensor = self.__data_info[i]["name"] + + # value + converter = self.__data_info[i]["converter"] + value = converter(sensor_values_str_arr[i]) + self.__data[sensor]["values"].append(value) + + if not self.__data_info[i]["is_numeric"]: + continue + + # update min/max/avg + # + self.__data[sensor]["accum"].append(value) + self.__data[sensor]["min"].append(value) + self.__data[sensor]["max"].append(value) + self.__data[sensor]["avg"].append(value) + self.__data[sensor]["dVdT"].append(value) # not a good initial value - fix later + + if len(self.__data[sensor]["values"]) > 1: + self.__data[sensor]["min"][-1] = min( + self.__data[sensor]["min"][-2], + value + ) + self.__data[sensor]["max"][-1] = max( + self.__data[sensor]["max"][-2], + value + ) + self.__data[sensor]["accum"][-1] = self.__data[sensor]["accum"][-2] + value + self.__data[sensor]["avg"][-1] = float(self.__data[sensor]["accum"][-1]) / len(self.__data[sensor]["accum"]) + + + # compute change over time - with dT at least 5 seconds + # + + prev_index = len(self.__IDs) - 2 + prev_time = self.__IDs[prev_index] + prev_value = self.__data[sensor]["values"][prev_index] + dT = float( (i_sentence_timestamp - prev_time).total_seconds() ) or 1 + dVdT = float(value-prev_value) / dT + + while prev_index >= 0: + prev_time = self.__IDs[prev_index] + dT = float( (i_sentence_timestamp - prev_time).total_seconds() ) + if dT < 5: + prev_index -= 1 + continue + else: + prev_value = self.__data[sensor]["values"][prev_index] + dVdT = float(value-prev_value) / dT + break + self.__data[sensor]["dVdT"][-1] = dVdT + + # fix first dVdT value + if len(self.__data[sensor]["dVdT"]) == 2: + self.__data[sensor]["dVdT"][0] = self.__data[sensor]["dVdT"][1] + + def get_last(self, i_sensor_name): + result = {} + try: + result["is_numeric"] = self.__data[i_sensor_name]["is_numeric"] + result["values"] = [self.__data[i_sensor_name]["values"][-1]] + result["times"] = [self.__IDs[-1]] + if self.__data[i_sensor_name]["is_numeric"]: + result["min"] = [self.__data[i_sensor_name]["min"][-1]] + result["max"] = [self.__data[i_sensor_name]["max"][-1]] + result["avg"] = [self.__data[i_sensor_name]["avg"][-1]] + result["dVdT"] = [self.__data[i_sensor_name]["dVdT"][-1]] + except KeyError: + return result + return result + + def get_by_time(self, i_sensor_name, i_time): + """ + return sensor data past i_time (excluded) + """ + + if i_sensor_name not in self.__data: + return {} + + left_i = 0 + for i in range(len(self.__IDs)): + left_i = i + # print(self.__IDs[left_i], i_time, self.__IDs[left_i] > i_time) + if self.__IDs[left_i] > i_time: + break + + result = {} + result["is_numeric"] = self.__data[i_sensor_name]["is_numeric"] + result["values"] = self.__data[i_sensor_name]["values"][left_i:] + result["times"] = self.__IDs[left_i:] + if self.__data[i_sensor_name]["is_numeric"]: + result["min"] = self.__data[i_sensor_name]["min"][left_i:] + result["max"] = self.__data[i_sensor_name]["max"][left_i:] + result["avg"] = self.__data[i_sensor_name]["avg"][left_i:] + result["dVdT"] = self.__data[i_sensor_name]["dVdT"][left_i:] + # print(i_sensor_name, len(result['times']),len(result['values']), len(result['dt']) ) + return result + + def sensorsList(self): + # if self.__data: return list(self.__data.keys()) + if self.__data_info: + return [ s['name'] for s in self.__data_info ] + return [None] + + def sensorsInfo(self): + if self.__data_info: + return copy.deepcopy( self.__data_info ) + # return [ s['name'] for s in self.__data_info ] + return [None] + + def verify(self): + if self.__IDs != sorted(self.__IDs): + print ("IDs - unsorted") + if self.__IDs != sorted(self.__IDs): + print ('times unsorted') + pprint(self.__IDs) + + +class SentencesDB(object): + def __init__(self, db_file): + if not db_file or db_file == "": + raise ValueError("SentencesDB: no file specified.") + + self.__mutex = threading.Lock() + + self.__sensorsInfo = ( + {} + ) # functions to convert from string to real data, indexed with payloadId + self.__sqldb = None + self.__sqldb_file = db_file + self.__callsignToPayloadId = {} + self.__sensorToPosition = {} # convert payload_id/sensor_name to position in sentence INCLUDING callsign + + self.__vehicles_data = {} # class VehicleData, indexed by payloadId + + self.__initSQLDB() + + def __initSQLDB(self): + if self.__sqldb: + return + self.__sqldb = sqlite3.connect(self.__sqldb_file, check_same_thread=False, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) + self.__sqldb.row_factory = sqlite3.Row + self.__createPayloadInfoTable() + self.__loadSensorsInfo() + for payload_id in self.__sensorsInfo: + self.__createPayloadTable(payload_id) + self.__initVehiclesData() + + def __createPayloadInfoTable(self): + """ + one global metadata table + keeps info for each table + """ + + meta_table_creation_ = "CREATE TABLE IF NOT EXISTS PayloadInfo (" + meta_table_creation_ += " PayloadId TEXT PRIMARY KEY," + meta_table_creation_ += " callsign TEXT NOT NULL," + meta_table_creation_ += " SentenceInfo TEXT NOT NULL" + meta_table_creation_ += ");" + + try: + with self.__mutex: + cur = self.__sqldb.cursor() + cur.execute(meta_table_creation_) + self.__sqldb.commit() + except sqerr as e: + print(e) + import traceback + + print(traceback.format_exc()) + except: + import traceback + + print(traceback.format_exc()) + + def __createPayloadTable(self, i_payloadId): + """ + per payload table + """ + + payload_table_creation_ = "CREATE TABLE IF NOT EXISTS {} (".format( + "P_" + i_payloadId + ) + + for sensor_info in self.__sensorsInfo[i_payloadId]: + payload_table_creation_ += ( + "\n\t" + sensor_info["name"] + " " + sensor_info["sql_data_type"] + "," + ) + + payload_table_creation_ += "\n\t_SENTENCE text,\n\t_RECEIVER text,\n\t_INSERT_TIME timestamp," + payload_table_creation_ += "\n\tPRIMARY KEY(sentence_id, time, _RECEIVER)\n);" + + cur = self.__sqldb.cursor() + try: + cur.execute(payload_table_creation_) + self.__sqldb.commit() + except sqerr as e: + print( + "error cur.execute(payload_table_creation_) - payload_id = ", + i_payloadId, + ) + print(e) + print(payload_table_creation_) + import traceback + print(traceback.format_exc()) + except: + import traceback + + print(traceback.format_exc()) + + def __loadSensorsInfo(self): + if self.__sensorsInfo and len(self.__sensorsInfo.keys()): + print("__loadSensorsInfo - early exit") + return + + # load from disk + # + + habitat_data = {} + try: + with self.__mutex: + cur = self.__sqldb.cursor() + cur.execute("SELECT PayloadId,callsign,SentenceInfo FROM PayloadInfo;") + for PayloadId, callsign, sensors_info_str in cur.fetchall(): + habitat_data[PayloadId] = json.loads(sensors_info_str) + self.__callsignToPayloadId[callsign] = PayloadId + except sqerr as e: + print(e) + import traceback + + print(traceback.format_exc()) + + # convert from habitat data + # + + for PayloadId in habitat_data: + + self.__sensorsInfo[PayloadId] = [] + + self.__sensorToPosition[PayloadId] = {'callsign': 0} + sensorPostiion = 1 # start with 1 because callsign is counted in indexing + + for sensor_info in habitat_data[PayloadId]: + sensor_info["sql_data_type"] = sensor_sql_type( sensor_info ) + sensor_info["converter"] = sensor_type_converter( sensor_info ) + # sensor_info["sql_primary_key"] = sensor_info["name"] == "sentence_id" + self.__sensorsInfo[PayloadId].append(sensor_info) + self.__sensorToPosition[PayloadId][sensor_info['name']] = sensorPostiion + sensorPostiion += 1 + + + def __initVehiclesData(self): + # return + if not self.__sqldb: + return + + allPayloadIds = self.getAllPayloadIds() + print("allPayloadIds:") + pprint(allPayloadIds) + sentences_count = {} + + cur = self.__sqldb.cursor() + for pid,callsign in allPayloadIds: + sentences_count[pid] = 0 + + # update vehicles data + if pid not in self.__vehicles_data: + _t = VehicleData(self.getSensorsInfo(pid)) + self.__vehicles_data[pid] = _t + + try: + cur.execute(" select time,_SENTENCE from {};".format("P_" + pid)) + except sqlite3.OperationalError as e: + if 'no such table: P_' in str(e): + continue # no data/table for this payload_id + else: + print(traceback.format_exc()) + continue + + for time, sentence in cur.fetchall(): + try: + self.__vehicles_data[pid].add(sentence, time) + sentences_count[pid] += 1 + except: + print("Can't parse ", sentence) + print(traceback.format_exc()) + + # if pid in self.__vehicles_data: print( self.__vehicles_data[pid].to_str() ) + + + if sentences_count: + print("Restored Vehicles Data from DB:") + for k, v in sentences_count.items(): + callsign = self.payloadIdToCallsign(k) + print("\t", callsign, v) + + # for pid in self.__vehicles_data: + # print(pid) + # print(self.__vehicles_data[pid]) + + # for pid in self.__vehicles_data: + # self.__vehicles_data[pid].verify() + + def callsignToPayloadId(self, i_callsign): + if i_callsign in self.__callsignToPayloadId: + return self.__callsignToPayloadId[i_callsign] + return None + + def create_empty(self): + self.__initSQLDB() + + + def payloadIdToCallsign(self, i_payloadId): + try: + with self.__mutex: + cur = self.__sqldb.cursor() + cur.execute( + 'SELECT callsign FROM PayloadInfo WHERE PayloadId is "{}";'.format( + str(i_payloadId) + ) + ) + return cur.fetchall()[0][0] + except sqerr as e: + print(e) + import traceback + print(traceback.format_exc()) + return None + except IndexError: + return None + + def updatePayloadInfo(self, i_payloadId, i_sentence=None): + callsign = HabHubInterface.getCallsignsForPayloadId(i_payloadId) + + sentence_info = HabHubInterface.getSentenceInfo(i_payloadId, i_sentence) + if not sentence_info: + print("UpdatePayloadInfo - No Sentence Info for payload ", i_payloadId) + return + + # HACK ! + # time field can have many names, lets always use 'time' + for i in range(len(sentence_info)): + if 'time' in sentence_info[i]['name']: + sentence_info[i]['name'] = 'time' + break + + + sql_insert = ( + "REPLACE INTO PayloadInfo(PayloadId, callsign, SentenceInfo) VALUES(?,?,?)" + ) + + try: + with self.__mutex: + cur = self.__sqldb.cursor() + cur.execute( + sql_insert, + ( + i_payloadId, + callsign, + json.dumps(sentence_info, sort_keys=True, indent=4), + ), + ) + self.__sqldb.commit() + except sqerr as e: + print(e) + import traceback + + print(traceback.format_exc()) + + def getAllPayloadIds(self): + try: + with self.__mutex: + cur = self.__sqldb.cursor() + cur.execute("select PayloadId, callsign from PayloadInfo;") + res = [ [x[0], x[1]] for x in cur.fetchall()] + return res + except sqerr as e: + print(e) + import traceback + + print(traceback.format_exc()) + + def getInfo(self): + try: + with self.__mutex: + cur = self.__sqldb.cursor() + cur.execute("select * from PayloadInfo;") + res = [list(x) for x in cur.fetchall()] + res = [ [x[0], x[1], json.loads(x[2])] for x in res] + return res + except sqerr as e: + print(e) + import traceback + print(traceback.format_exc()) + + def insert(self, i_sentence, i_RECEIVER="unknown"): + if not i_sentence: + return + + sentences = formatSentence.formatSentence(i_sentence) + if not sentences: + return + + with self.__mutex: + for sentence in sentences: + callsign = formatSentence.sentenceToCallsign(sentence) + payload_id = self.callsignToPayloadId(callsign) + if not payload_id: + print("DB Insert -- Unknown callsign: ", callsign) + continue + + sent_id = formatSentence.sentenceToId(sentence) + + if not self.__sensorsInfo: + print("DB Insert -- No sentence data info. returning.") + return + + # get data from sentence and convert from string to real types + sensors_data = formatSentence.getData(sentence) + try: + for i in range(len(sensors_data)): + converter = self.__sensorsInfo[payload_id][i]["converter"] + sensors_data[i] = converter(sensors_data[i]) + except: + print("DB Insert -- Error converting sentence fields to data.") + print(traceback.format_exc()) + continue + + # _SENTENCE field + sensors_data.append(sentence) + + # _RECEIVER field + sensors_data.append(str(i_RECEIVER)) + + # _INSERT_TIME field + sensors_data.append(datetime.datetime.utcnow()) + + + sql_insert = "INSERT INTO {}(".format("P_" + payload_id) + sql_insert += ",".join( + [sensor["name"] for sensor in self.__sensorsInfo[payload_id]] + ) + sql_insert += ", _SENTENCE, _RECEIVER, _INSERT_TIME" + sql_insert += ")" + sql_insert += ( + "\n\tVALUES(" + ",".join(["?"] * len(sensors_data)) + ")" + ) + + cur = self.__sqldb.cursor() + try: + cur.execute(sql_insert, sensors_data) + self.__sqldb.commit() + # print( cur.lastrowid ) + except sqlite3.IntegrityError: + pass + # print("sqlite3.IntegrityError - already inserted ?") + except sqerr as e: + print(e) + + # update vehicles data + if payload_id not in self.__vehicles_data: + self.__vehicles_data[payload_id] = VehicleData( + self.getSensorsInfo(payload_id) + ) + try: + sentence_timestamp = sensors_data[ self.__sensorToPosition[payload_id]['time'] -1 ] + self.__vehicles_data[payload_id].add(sentence, sentence_timestamp) + except: + print("DB Insert -- Can't parse ", sentence) + print(traceback.format_exc()) + return True + + def getSensorsList(self, i_payloadId): + with self.__mutex: + if i_payloadId in self.__vehicles_data: + return deepcopy( self.__vehicles_data[i_payloadId].sensorsList() ) + else: + pass + # print(self.__vehicles_data.keys()) + return [] + + def getSensorsInfo(self, i_payloadId): + with self.__mutex: + if i_payloadId in self.__sensorsInfo: + return deepcopy( self.__sensorsInfo[i_payloadId] ) + return None + + def getTelemetryLast(self, i_payloadId, i_sensor_name): + with self.__mutex: + if not list(self.__vehicles_data.keys()): + return {} + + if i_payloadId not in self.__vehicles_data: + return {} + + return self.__vehicles_data[i_payloadId].get_last(i_sensor_name) + + def getTelemetryByTime(self, i_payloadId, i_sensor_name, i_time): + _t = i_time + if type(_t) == type(""): + # _t = datetime.datetime.strptime(_t, "%Y-%m-%d %H:%M:%S") + _t = dateutil.parser.parse(_t, ignoretz=1) + + with self.__mutex: + if not list(self.__vehicles_data.keys()): + return [] + + if i_payloadId not in self.__vehicles_data: + return [] + + return self.__vehicles_data[i_payloadId].get_by_time(i_sensor_name, _t) + + def getLastSentence(self, i_payloadId): + if not i_payloadId: + print("getLastSentence: i_payloadId = ", i_payloadId) + return + + if not self.__sqldb: + return None + + with self.__mutex: + tab_name = "P_" + i_payloadId + cur = self.__sqldb.cursor() + # cur.execute("select MAX(time) from {};".format(tab_name)) + cur.execute("select MAX(_INSERT_TIME) from {};".format(tab_name)) + last_time = cur.fetchone()[0] + if last_time: + cur.execute( + # "select * from {} where time is '{}';".format( + "select * from {} where _INSERT_TIME is '{}';".format( + tab_name, last_time + ) + ) + values = cur.fetchall() + return dict(values[0]) + + def getLastSentenceId(self, i_payloadId): + if not i_payloadId: + print("getLastSentenceId: i_payloadId = ", i_payloadId) + return + + if not self.__sqldb: + return + + with self.__mutex: + tab_name = "P_" + i_payloadId + cur = self.__sqldb.cursor() + cur.execute("select MAX(sentence_id) from {};".format(tab_name)) + last_sentence_id = cur.fetchone()[0] + if last_sentence_id: + return last_sentence_id + + return + + def getReceiversStats(self, i_payloadId): + if not i_payloadId: + return + + if not self.__sqldb: + return + + with self.__mutex: + try: + c = self.__sqldb.cursor() + tab_name = "P_" + i_payloadId + c.execute("SELECT DISTINCT _RECEIVER FROM {}".format(tab_name)) + all_receivers = c.fetchall() + all_receivers = [a[0] for a in all_receivers] + # print(all_receivers) + + receiver_stats = {} + for r in all_receivers: + c.execute( + 'SELECT COUNT(sentence_id) FROM "{}" WHERE _RECEIVER = "{}"'.format( + tab_name, r + ) + ) + receiver_stats[r] = int(c.fetchone()[0]) + + # pprint(receiver_stats) + return receiver_stats + except sqlite3.OperationalError as e: + if 'no such table: P_' in str(e): + return None # no data/table for this payload_id + else: + print(traceback.format_exc()) + return None + + return + +if __name__ == "__main__": + print(sentence_time_formatter('123456')) + print(sentence_time_formatter('12:34:56')) \ No newline at end of file diff --git a/data_server/code/example_payload.info.json b/data_server/code/example_payload.info.json new file mode 100644 index 0000000..19c0312 --- /dev/null +++ b/data_server/code/example_payload.info.json @@ -0,0 +1,36 @@ +[ + { + "name": "sentence_id", + "sensor": "base.ascii_int" + }, + { + "name": "time", + "sensor": "stdtelem.time" + }, + { + "format": "dd.dddd", + "name": "latitude", + "sensor": "stdtelem.coordinate" + }, + { + "format": "dd.dddd", + "name": "longitude", + "sensor": "stdtelem.coordinate" + }, + { + "name": "altitude", + "sensor": "base.ascii_int" + }, + { + "name": "satellites", + "sensor": "base.ascii_int" + }, + { + "name": "fix_age", + "sensor": "base.ascii_int" + }, + { + "name": "temp", + "sensor": "base.ascii_int" + } +] \ No newline at end of file diff --git a/data_server/code/formatSentence.py b/data_server/code/formatSentence.py new file mode 100644 index 0000000..37c421a --- /dev/null +++ b/data_server/code/formatSentence.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 + +import string + +""" +Sanitize sentence string. +Calc and verify CRC code. +""" + + +def _hex(Character): + _hexTable = "0123456789ABCDEF" + return _hexTable[Character] + + +def crc(i_str): + CRC = 0xFFFF + # xPolynomial = 0x1021; + + for i in range(len(i_str)): + CRC ^= ord(i_str[i]) << 8 + for j in range(8): + if CRC & 0x8000: + CRC = (CRC << 1) ^ 0x1021 + else: + CRC <<= 1 + + result = "" + result += _hex((CRC >> 12) & 15) + result += _hex((CRC >> 8) & 15) + result += _hex((CRC >> 4) & 15) + result += _hex(CRC & 15) + + return result + + +def verifyCrc(i_sent): + i_crc = i_sent[i_sent.rfind("*") + 1 :] + sent = i_sent[: i_sent.rfind("*")] + return i_crc == crc(sent) + + +def formatSentence(i_sent): + if not i_sent: + return [] + + lines = i_sent.split("\n") + result = [] + + for l in lines: + dollar_index = l.rfind("$") + l = l[dollar_index + 1 :] + + star_index = l.find("*") + if star_index == -1: + continue + l = l[: star_index + 5] + + sentence = l[:-5] + crc = l[-4:] + + result.append(sentence + "*" + crc) + + return result + +def sentenceToCallsign(i_sent): + sentences = formatSentence(i_sent) + if not sentences: + return None + sentence = sentences[-1] + tokens = sentence.split(",") + if tokens: + return str(tokens[0]) + return None + +def sentenceToId(i_sent): + sentences = formatSentence(i_sent) + if not sentences: + return None + sentence = sentences[-1] + tokens = sentence.split(",") + if len(tokens) > 1: + return int(tokens[1]) + return None + +def getData(i_sent): + sentences = formatSentence(i_sent) + if not sentences: + return None + sentence = sentences[-1] + tokens = sentence.split(",") + + if not tokens: + return None + + # remove callsign + tokens = tokens[1:] + + # remove CRC + tokens[-1] = tokens[-1][0 : tokens[-1].find("*")] + return tokens + + +if __name__ == "__main__": + s = formatSentence( + "$$$fro3,2141,224553,52.09318,21.00429,127,0,0,0,0,D*5094 DESCEND" + )[-1] + print(s) + print((sentenceToId(s))) + print((getData(s))) diff --git a/data_server/code/get_ip.py b/data_server/code/get_ip.py new file mode 100644 index 0000000..c086784 --- /dev/null +++ b/data_server/code/get_ip.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python +import subprocess +#import urllib as urllib +import socket +import datetime +from pprint import pprint + +""" +This module is designed to fetch your external IP address from the internet. +It is used mostly when behind a NAT. +It picks your IP randomly from a serverlist to minimize request +overhead on a single server + +If you want to add or remove your server from the list contact me on github + + +API Usage +========= + + >>> import ipgetter + >>> myip = ipgetter.myip() + >>> myip + '8.8.8.8' + + >>> ipgetter.IPgetter().test() + + Number of servers: 47 + IP's : + 8.8.8.8 = 47 ocurrencies + + +Copyright 2014 phoemur@gmail.com +This work is free. You can redistribute it and/or modify it under the +terms of the Do What The Fuck You Want To Public License, Version 2, +as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. +""" + +__all__ = ['get_ip_local', 'get_ip_world'] + + +import re +import random + +from sys import version_info + +PY3K = version_info >= (3, 0) + +if PY3K: + import urllib.request as urllib +else: + import urllib2 as urllib + +__version__ = "0.6" + + +class IPgetter(object): + + ''' + This class is designed to fetch your external IP address from the internet. + It is used mostly when behind a NAT. + It picks your IP randomly from a serverlist to minimize request overhead + on a single server + ''' + + def __init__(self): + self.server_list = ['http://ip.dnsexit.com', + 'http://ifconfig.me/ip', + 'http://ipecho.net/plain', + 'http://checkip.dyndns.org/plain', + 'http://ipogre.com/linux.php', + 'http://whatismyipaddress.com/', + 'http://ip.my-proxy.com/', + 'http://websiteipaddress.com/WhatIsMyIp', + 'http://getmyipaddress.org/', + 'http://www.my-ip-address.net/', + 'http://myexternalip.com/raw', + 'http://www.canyouseeme.org/', + 'http://www.trackip.net/', + 'http://icanhazip.com/', + 'http://www.iplocation.net/', + 'http://www.howtofindmyipaddress.com/', + 'http://www.ipchicken.com/', + 'http://whatsmyip.net/', + 'http://www.ip-adress.com/', + 'http://checkmyip.com/', + 'http://www.tracemyip.org/', + 'http://checkmyip.net/', + 'http://www.lawrencegoetz.com/programs/ipinfo/', + 'http://www.findmyip.co/', + 'http://ip-lookup.net/', + 'http://www.dslreports.com/whois', + 'http://www.mon-ip.com/en/my-ip/', + 'http://www.myip.ru', + 'http://ipgoat.com/', + 'http://www.myipnumber.com/my-ip-address.asp', + 'http://www.whatsmyipaddress.net/', + 'http://formyip.com/', + 'https://check.torproject.org/', + 'http://www.displaymyip.com/', + 'http://www.bobborst.com/tools/whatsmyip/', + 'http://www.geoiptool.com/', + 'https://www.whatsmydns.net/whats-my-ip-address.html', + 'https://www.privateinternetaccess.com/pages/whats-my-ip/', + 'http://checkip.dyndns.com/', + 'http://myexternalip.com/', + 'http://www.ip-adress.eu/', + 'http://www.infosniper.net/', + 'http://wtfismyip.com/', + 'http://ipinfo.io/', + 'http://httpbin.org/ip'] + + def get_externalip(self): + ''' + This function gets your IP from a random server + ''' + + random.shuffle(self.server_list) + myip = '' + for server in self.server_list: + myip = self.fetch(server) + if myip != '': + return myip + else: + continue + return '' + + def fetch(self, server): + ''' + This function gets your IP from a specific server + ''' + url = None + opener = urllib.build_opener() + opener.addheaders = [('User-agent', + "Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0")] + + try: + url = opener.open(server) + content = url.read() + + # Didn't want to import chardet. Prefered to stick to stdlib + if PY3K: + try: + content = content.decode('UTF-8') + except UnicodeDecodeError: + content = content.decode('ISO-8859-1') + + m = re.search( + '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', + content) + myip = m.group(0) + return myip if len(myip) > 0 else '' + except Exception: + return '' + finally: + if url: + url.close() + + def test(self): + ''' + This functions tests the consistency of the servers + on the list when retrieving your IP. + All results should be the same. + ''' + + resultdict = {} + for server in self.server_list: + resultdict.update(**{server: self.fetch(server)}) + + ips = sorted(resultdict.values()) + ips_set = set(ips) + print('\nNumber of servers: {}'.format(len(self.server_list))) + print("IP's :") + for ip, ocorrencia in zip(ips_set, map(lambda x: ips.count(x), ips_set)): + print('{0} = {1} ocurrenc{2}'.format(ip if len(ip) > 0 else 'broken server', ocorrencia, 'y' if ocorrencia == 1 else 'ies')) + print('\n') + print(resultdict) + + +def get_ip_world(): + try: + return IPgetter().get_externalip() + except: + return None + +# Very Linux Specific +def get_ip_local(): + try: + arg='ip route list' + p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE, universal_newlines='\n') + data = p.communicate() + data = data[0].split('\n') + while '' in data: + data.remove('') + split_data = data[-1].split() + + ipaddr = split_data[split_data.index('src')+1] + return ipaddr + except: + return None + + +if __name__ == '__main__': + print(get_ip_world()) + print(get_ip_local()) \ No newline at end of file diff --git a/data_server/code/keygen.py b/data_server/code/keygen.py new file mode 100644 index 0000000..998b083 --- /dev/null +++ b/data_server/code/keygen.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +import os +import subprocess + +# generate self-signed certificate + +# Very Linux Specific +def get_ip(): + arg='ip route list' + p = subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE, universal_newlines=True) + data = p.communicate() + data = data[0].split('\n') + while '' in data: + data.remove('') + split_data = data[-1].split() + + ipaddr = split_data[split_data.index('src')+1] + return ipaddr + +def keygen(): + cmd = 'openssl req -new -x509 -days 1095 -nodes -newkey rsa:2048 -out cacert.pem -keyout privkey.pem -subj "/CN={}"' + cmd = cmd.format(get_ip()) + print(cmd) + os.system(cmd) + +if __name__ == "__main__": + keygen() \ No newline at end of file diff --git a/data_server/code/kil.py b/data_server/code/kil.py new file mode 100644 index 0000000..f11f2d9 --- /dev/null +++ b/data_server/code/kil.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python + +import os +import string +import subprocess +from pprint import pprint + +def get_proc(): + res = [] + p = subprocess.Popen("ps",stdout=subprocess.PIPE) + line = p.stdout.readline() + while line: + res.append(line) + line = p.stdout.readline() + return res + +def get_dsp_id(p_arr, p_name = "habboy_data"): + for p in p_arr: + if p_name in p: + tokens = p.split() + pid = int(tokens[0]) + return pid + return None + +if __name__ == '__main__': + pid = get_dsp_id(get_proc()) + while pid: + print(pid) + os.system('kill -9 %d' % pid) + pid = get_dsp_id(get_proc()) diff --git a/data_server/code/main.py b/data_server/code/main.py new file mode 100644 index 0000000..ba6b0bf --- /dev/null +++ b/data_server/code/main.py @@ -0,0 +1,822 @@ +#!/usr/bin/env python3 + +import os +import sys +import time +import threading +import functools +import traceback +import argparse +from pprint import pprint +import urllib3 +import subprocess +from datetime import datetime as dtime +import string +import datetime +import math +import serial +from copy import deepcopy +import psutil +import platform + +import formatSentence +import HabdecClient +import HabHubClient +import HabHubInterface +import SentencesDB +import HttpInterface +import nmea +from get_ip import get_ip_local + +from DummySentenceCreator import DummySentenceCreator + +G_RUN = True + +C_BLACK = "\033[1;30m" +C_RED = "\033[1;31m" +C_GREEN = "\033[1;32m" +C_BROWN = "\033[1;33m" +C_BLUE = "\033[1;34m" +C_MAGENTA = "\033[1;35m" +C_CYAN = "\033[1;36m" +C_LIGHTGREY = "\033[1;37m" +C_OFF = "\033[0m" +C_CLEAR = "\033[2K" + +if os.name == 'nt': + C_BLACK=C_RED=C_GREEN=C_BROWN=C_BLUE=C_MAGENTA=C_CYAN=C_LIGHTGREY=C_OFF=C_CLEAR='' + +# collect sentences from habitat and habdec +G_SENTENCES_DB = None +G_HABDEC_CLIENTS = {} +G_HABHUB_CLIENTS = {} +G_CLIENTS_MTX = threading.Lock() + +# process statistics +G_HABBOY_STATS = {} +G_HABBOY_STATS_MTX = threading.Lock() + +# flight prediction path +G_PREDICT_PATH = {} +G_PREDICT_PATH_MTX = threading.Lock() + +# GPS for HABBOY/DEVICE +G_GPS_Data = { + 'time': datetime.datetime.utcnow(), + 'parse_timestamp': datetime.datetime.utcnow(), + "latitude": 52, + "longitude": 21, + "altitude": 100, + 'heading': 0, + 'ground_speed_mps': 0, + 'sats': 0, +} + +def get_ip(): + p = subprocess.Popen("ip route list", shell=True, stdout=subprocess.PIPE) + data = p.communicate() + data = data[0].decode().split("\n") + while "" in data: + data.remove("") + split_data = data[-1].split() + + ipaddr = split_data[split_data.index("src") + 1] + return ipaddr + + + +def GpsDataFileRead(gps_data_file): + if gps_data_file: + with open(gps_data_file) as fh: + lat_lon_alt = fh.read() + sep = ',' if (',' in lat_lon_alt) else ' ' + lat_lon_alt = lat_lon_alt.split('\n') + lat_lon_alt = [x.strip() for x in lat_lon_alt] + while '' in lat_lon_alt: lat_lon_alt.remove('') + lat_lon_alt = [ l.split(sep) for l in lat_lon_alt ] + lat_lon_alt = [ (float(t[1]), float(t[0]), float(t[2])) for t in lat_lon_alt] + return lat_lon_alt + + +def DummySentenceThreadF(i_payloadId, interval_seconds, gps_data_file): + callsign = G_SENTENCES_DB.payloadIdToCallsign(i_payloadId) + sensors_info = G_SENTENCES_DB.getSensorsInfo(i_payloadId) + + lat_lon_alt = GpsDataFileRead(gps_data_file) + + global G_RUN + while G_RUN: + time.sleep(interval_seconds) + lat, lon, alt = (0,0,0) + if lat_lon_alt: + lat, lon, alt = lat_lon_alt.pop(0) + s = DummySentenceCreator(i_payloadId, callsign, sensors_info, lat, lon, alt) + print(s) + G_SENTENCES_DB.insert(s, "debug") + + +def SentenceGatherThreadF(habdec_addr_arr, i_payload_id): + """ + collect sentences from habitat and habdec + """ + + global G_HABDEC_CLIENTS + global G_HABHUB_CLIENTS + + with G_CLIENTS_MTX: + for habdec_addr in habdec_addr_arr: + G_HABDEC_CLIENTS[habdec_addr] = HabdecClient.HabdecClient( + habdec_addr + ) # "ws://localhost:5555" + G_HABDEC_CLIENTS[habdec_addr].Start() + + G_HABHUB_CLIENTS[i_payload_id] = HabHubClient.HabHubClient(i_payload_id) + G_HABHUB_CLIENTS[i_payload_id].Start() + + habdec_last_querry_time = dtime.utcnow() + habhub_last_querry_time = dtime.utcnow() + + while G_RUN: + time.sleep(1) + + with G_CLIENTS_MTX: + if (dtime.utcnow() - habdec_last_querry_time).total_seconds() > 1: + for habdec in G_HABDEC_CLIENTS: + HabdecClient_GetLastSentence = G_HABDEC_CLIENTS[habdec].GetLastSentence() + if HabdecClient_GetLastSentence: + print(C_RED, "Habdec: " + habdec + " ", HabdecClient_GetLastSentence, C_OFF) + G_SENTENCES_DB.insert(HabdecClient_GetLastSentence, habdec) + else: + pass + # print("habdec no last sentence") + habdec_last_querry_time = dtime.utcnow() + + if (dtime.utcnow() - habhub_last_querry_time).total_seconds() > 3: + for payload_id in G_HABHUB_CLIENTS: + HabHubClient_GetLastSentence = G_HABHUB_CLIENTS[payload_id].GetLastSentence() + if HabHubClient_GetLastSentence: + print(C_MAGENTA, "HabHub: ", HabHubClient_GetLastSentence, C_OFF) + G_SENTENCES_DB.insert(HabHubClient_GetLastSentence, "habhub") + habhub_last_querry_time = dtime.utcnow() + + with G_CLIENTS_MTX: + if G_HABDEC_CLIENTS: + for k, v in G_HABDEC_CLIENTS.items(): + v.Stop() + G_HABDEC_CLIENTS = {} + + if G_HABHUB_CLIENTS: + for k, v in G_HABHUB_CLIENTS.items(): + v.Stop() + G_HABHUB_CLIENTS = {} + + +def GPSD_ReadThread(): + try: + import gps + except ImportError: + print("No gps module") + return + session = gps.gps("localhost", "2947") + session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) + global G_GPS_Data + sats = 0 + while G_RUN: + try: + report = session.next() + # print(report) + + if report['class'] == 'SKY': + used = [s.used for s in report.satellites] + sats = sum(used) + elif report['class'] == 'TPV': + _res = { + 'time': report.time, #probably need to convert from str to datetime + "latitude": report.lat, + "longitude": report.lon, + "altitude": report.alt, + 'heading': report.track, + 'ground_speed_mps': report.speed, + 'sats': sats + } + G_GPS_Data = _res + except KeyError: + pass + except StopIteration: + session = None + print("GPSD has terminated") + except: + # print(traceback.format_exc()) + # print(report) + pass + + +def GPS_Serial_Thread(i_dev, line_callback): + global G_GPS_Data + nmea_parser = nmea.nmea_parser() + _ser = None + + while G_RUN: + + if not _ser: + try: + _ser = serial.Serial(i_dev, 115200) + except: + print(traceback.format_exc()) + time.sleep(1) + continue + + try: + line = _ser.readline() + except: + print(traceback.format_exc()) + _ser = None + + if line: + try: + if line_callback: + line_callback(line) + except: + pass + + try: + nmea_data = nmea_parser.feed_line(line) + if nmea_data: + new_gps_data = { + 'time': nmea_data.utc_time, + "latitude": nmea_data.lat, + "longitude": nmea_data.lon, + "altitude": nmea_data.alt, + 'heading': nmea_data.heading, + 'ground_speed_mps': nmea_data.ground_speed_mps, + 'sats': nmea_data.sats, + 'parse_timestamp': nmea_data.parse_timestamp + } + G_GPS_Data = new_gps_data + except: + print(traceback.format_exc()) + + + +def GPS_Serial_Thread_Fake(): + global G_GPS_Data + while G_RUN: + new_gps_data = { + 'time': datetime.datetime.utcnow(), + "latitude": 52 + .01 * math.sin(.1 * GPS_Serial_Thread_Fake.T), + "longitude": 21 + .01 * math.cos(.1 * GPS_Serial_Thread_Fake.T), + "altitude": 100, + 'heading': 0, + 'ground_speed_mps': 50, + 'sats': 11, + 'parse_timestamp': datetime.datetime.utcnow() + } + G_GPS_Data = new_gps_data + GPS_Serial_Thread_Fake.T += 1 + time.sleep(1) + +GPS_Serial_Thread_Fake.T = 0 + + +def GET_HABBOY_GPS(): + ''' + get current HABBOY GPS + add 'fix_age' and 'data_age' fields + ''' + global G_GPS_Data + gps = deepcopy(G_GPS_Data) + _now = datetime.datetime.utcnow() + gps['fix_age'] = (_now - gps['time']).total_seconds() + gps['data_age'] = (_now - gps['parse_timestamp']).total_seconds() + return gps + + + +def get_process_stats(i_proc_name_list): + start = datetime.datetime.utcnow() + result = {} + + try: + result['global'] = {} + result['global']['cpu_load_%'] = psutil.cpu_percent(interval=1) + except: + pass + + try: + vmem = psutil.virtual_memory() + result['global']['mem_%'] = vmem.used / vmem.total * 100 + except: + pass + + try: + disk = psutil.disk_usage('/') + result['global']['disk_%'] = disk.used / disk.total * 100 + except: + pass + + try: + temp = psutil.sensors_temperatures() + result['global']['temp'] = 0 + except: + pass + + try: + result['global']['temp'] = temp['cpu_thermal'][0].current + except: + pass + + + # processes + procs_pid2name = {} + for proc in psutil.process_iter(['pid', 'name']): + procs_pid2name[proc.info['name']] = proc.info['pid'] + result['proc'] = {} + for pname in i_proc_name_list: + if pname not in procs_pid2name: + print('not', pname) + continue + p = psutil.Process(procs_pid2name[pname]) + if not p: + continue + result['proc'][pname] = {} + # result['proc'][pname]['stat'] = p.status() + result['proc'][pname]['cpu_load_%'] = p.cpu_percent(interval=1) + result['proc'][pname]['runtime'] = time.time() - p.create_time() + result['proc'][pname]['mem_MB'] = p.memory_full_info().rss / 1e6 + # result['proc'][pname]['mem'] = p.memory_percent() + result['proc'][pname]['connections'] = len( p.connections() ) + + return result + + +def PROC_STATS_THREAD_F(proc_list): + global G_RUN + while G_RUN: + stats = {} + try: + stats = get_process_stats(proc_list) + except: + print(traceback.format_exc()) + + stats['telemetry'] = {} + stats['telemetry']['habdec'] = {} + stats['telemetry']['habhub'] = {} + global G_HABDEC_CLIENTS + global G_HABHUB_CLIENTS + global G_CLIENTS_MTX + try: + with G_CLIENTS_MTX: + now = datetime.datetime.utcnow() + for hd in G_HABDEC_CLIENTS: + stats['telemetry']['habdec'][hd] = {} + stats['telemetry']['habdec'][hd]['connection_age'] = (now - G_HABDEC_CLIENTS[hd].GetLastConnectionTime()).total_seconds() + stats['telemetry']['habdec'][hd]['sentence_age'] = (now - G_HABDEC_CLIENTS[hd].GetLastSentenceReceiveTime()).total_seconds() + for hh in G_HABHUB_CLIENTS: + stats['telemetry']['habhub'][hh] = {} + stats['telemetry']['habhub'][hh]['connection_age'] = (now - G_HABHUB_CLIENTS[hh].GetLastConnectionTime()).total_seconds() + stats['telemetry']['habhub'][hh]['sentence_age'] = (now - G_HABHUB_CLIENTS[hh].GetLastSentenceReceiveTime()).total_seconds() + except: + print(traceback.format_exc()) + + global G_HABBOY_STATS + global G_HABBOY_STATS_MTX + with G_HABBOY_STATS_MTX: + G_HABBOY_STATS = deepcopy(stats) + + time.sleep(5) + + +def GET_HABBOY_STATS(): + stats = {} + global G_HABBOY_STATS + global G_HABBOY_STATS_MTX + with G_HABBOY_STATS_MTX: + stats = deepcopy(G_HABBOY_STATS) + return stats + + +def CalcPayloadPrediction(payload_id, predictor, expected_burst): + if not predictor: + print("NO PREDICTOR") + return {} + + # https://github.com/projecthorus/chasemapper/blob/master/horusmapper.py#L341 + + lat = G_SENTENCES_DB.getTelemetryLast(payload_id, "latitude") + lon = G_SENTENCES_DB.getTelemetryLast(payload_id, "longitude") + alt = G_SENTENCES_DB.getTelemetryLast(payload_id, "altitude") + + descent_rate = 6 # default value + is_descending = False + if alt['dVdT'][-1] < 0: + descent_rate = abs(alt['dVdT'][-1]) + is_descending = True + + flight_path = predictor.predict( + launch_lat = lat['values'][-1], + launch_lon = lon['values'][-1], + launch_alt = max(100, alt['values'][-1]), + ascent_rate = max(3, abs(alt['dVdT'][-1])), + descent_rate = descent_rate, + burst_alt = max(alt['values'][-1]+100, expected_burst), + launch_time = datetime.datetime.utcnow(), # this better be sentence time + descent_mode = is_descending + ) + return flight_path + + +def PREDICT_THREAD_F(payload_id, predictor, expected_burst): + global G_RUN + while G_RUN: + path = {} + try: + path = CalcPayloadPrediction(payload_id, predictor, expected_burst) + except: + print(traceback.format_exc()) + + global G_PREDICT_PATH + global G_PREDICT_PATH_MTX + with G_PREDICT_PATH_MTX: + G_PREDICT_PATH = deepcopy(path) + time.sleep(5) + + +def GetPayloadPredictPath(): + global G_PREDICT_PATH + global G_PREDICT_PATH_MTX + res = {} + with G_PREDICT_PATH_MTX: + res = deepcopy(G_PREDICT_PATH) + return res + + +def CliArgs(): + parser = argparse.ArgumentParser() + + # if len(sys.argv)==1: + # parser.print_help() + # sys.exit(1) + + parser.add_argument( + "--dbfile", nargs="?", type=str, const="", help="Sentences DB file" + ) + parser.add_argument( + "--initDB", action='store_true', help="Create empty DB" + ) + parser.add_argument( + "--updateDB", nargs="*", type=str, help="Update local DB from HABITAT. Optional args are payload_id." + ) + parser.add_argument( + "--dbinfo", action="store_true", help="print payloads from local DB file" + ) + + parser.add_argument( + "--payloads", action="store_true", help="List flights from HABITAT" + ) + parser.add_argument( + "--payload_id", type=str, default="", help="Payload ID" + ) + parser.add_argument( + "--payloads_info", nargs="?", type=str, const="*", help="Show flights info from HABITAT" + ) + + + # parser.add_argument('--callsign', nargs='?', type=str, const='*', help='callsign. if empty, deduce from payload_id') + + parser.add_argument( + "--habdec", + nargs="*", + type=str, + # default=["127.0.0.1:5555"], + help="habdec WS addr. 127.0.0.1:5555", + ) + + parser.add_argument("--host", type=str, default = '0.0.0.0', help="hostname") + parser.add_argument( "--port", type=int, default=8888, help="http port, default 8888" ) + parser.add_argument("--https", action="store_true", help="serve on https://") + + + parser.add_argument("--test", type=int, help="generate fake sentence every N seconds") + parser.add_argument("--test_file", type=str, help="replay GPS/alt from file. lat,lon,alt\\n") + + parser.add_argument("--burst", type=int, default=30000, help="expected burst alt" ) + + parser.add_argument("--wind", type=str, help="NOAA wind dir") + + parser.add_argument( "--hab_interval", type=int, help="Habitat query seconds interval" ) + + args = parser.parse_args() + + return args + + +def CurDir(): + d = os.path.dirname(sys.argv[0]) + if d == '' or d == '.': + if 'PWD' in os.environ: + d = os.environ['PWD'] + else: + d = os.getcwd() + return d + + +def HABBOY_DATA_MAIN(): + os.chdir(CurDir()) + + args = CliArgs() + + # payloads + # + payloads = [] + try: + flights = HabHubInterface.getFlights() + payloads = HabHubInterface.getPayloads(flights) + if not payloads: + print("HabHub - no current payloads.") + except urllib3.exceptions.MaxRetryError: + print(C_RED, "Failed connecting to HabHub", C_OFF) + pass + + + # print payloads info + # + if args.payloads: + for p in payloads: + if not p["doc"]["transmissions"]: + continue + + for i in range(len(p["doc"]["transmissions"])): + if p["doc"]["transmissions"][i]['modulation'].lower() != 'rtty': + continue + + print( + p["doc"]["name"], + + " --callsign:", + C_MAGENTA, p["doc"]["sentences"][i]["callsign"], C_OFF, + + "--payload:", + C_RED, p["doc"]["_id"], C_OFF, + + "--RTTY:", + C_MAGENTA, "{}/{}/{}".format( + p["doc"]["transmissions"][i]["baud"], + p["doc"]["transmissions"][i]["encoding"], + p["doc"]["transmissions"][i]["stop"] ), C_OFF, + + "--freq:", + C_MAGENTA, p["doc"]["transmissions"][0]["frequency"], C_OFF, + ) + return + + + # DB object + # + dbfile = "habboy_data.db" + if args.dbfile: + dbfile = args.dbfile + print("dbfile ", dbfile) + + global G_SENTENCES_DB + G_SENTENCES_DB = SentencesDB.SentencesDB(dbfile) + + + # print dbinfo + # + if args.dbinfo: + info = G_SENTENCES_DB.getInfo() + for i in info: + print( C_RED, i[0], C_MAGENTA, i[1], C_OFF) + pprint(i[2:]) + return + + + # payloads info + # + if args.payloads_info: + for p in payloads: + if args.payloads_info != "*" and p["doc"]["_id"] != args.payloads_info: + continue + print("\n") + print(C_MAGENTA, p["doc"]["name"], p["doc"]["_id"], C_OFF) + pprint(p) + print("\n") + return + + if args.initDB: + print("Init DB") + G_SENTENCES_DB.create_empty() + return + + if args.updateDB != None: + update_payloads = args.updateDB + if update_payloads == []: + update_payloads = [p["doc"]["_id"] for p in HabHubInterface.getPayloads()] + for pid in update_payloads: + print("Updating Info on ", pid) + G_SENTENCES_DB.updatePayloadInfo(pid) + + return + + + # payload_id and callsign + # + payload_id = args.payload_id + if payload_id: + for p in payloads: + if p["doc"]["_id"].startswith(payload_id): + payload_id = p["doc"]["_id"] + break + print("payload_id ", payload_id) + else: + payload_id = 'NoPayload' + # print(C_RED, "No --payload_id specified. List payloads with --payloads.", C_OFF) + # return + + try: + callsign_from_payload_id = HabHubInterface.getCallsignsForPayloadId(payload_id) + print("callsign from payload_id (HabHub) ", callsign_from_payload_id) + except urllib3.exceptions.MaxRetryError: + print( + C_RED, + "HabHubInterface.getCallsignsForPayloadId -- Failed connecting to HabHub", + C_OFF, + ) + callsign_from_payload_id = None + + if callsign_from_payload_id == None: + callsign_from_payload_id = G_SENTENCES_DB.payloadIdToCallsign(payload_id) + print("callsign from payload_id (DB) ", callsign_from_payload_id) + + if callsign_from_payload_id == None: + callsign_from_payload_id = 'NoCallsign' + print(C_RED, "NO CALLSIGN", C_OFF) + + + # habdec addresses + # + habdec_addr_arr = [] + if args.habdec: + habdec_addr_arr = args.habdec + for i in range(len(habdec_addr_arr)): + if habdec_addr_arr[i] and not habdec_addr_arr[i].startswith("ws://"): + habdec_addr_arr[i] = "ws://" + habdec_addr_arr[i] + + + # host and port + # + host = args.host or "0.0.0.0" + # host = args.host or get_ip() + if host.lower() == "ip": + host = get_ip() + is_https = args.https + port = args.port or 8888 + + + # wind data + # + try: + from cusfpredict.predict import Predictor + try: + wind = args.wind or os.path.join( os.environ['HOME'], 'data/noaa_wind/gfs' ) + print('Wind Dir:', wind) + predictor = Predictor(bin_path = './pred', gfs_path = wind) + except: + print(traceback.format_exc()) + print("No Wind Dir") + predictor = None + except ImportError: + print("Cusf Predictor import error") + predictor = None + + + # some globals + # + + global G_RUN + global G_HABDEC_CLIENTS + global G_HABHUB_CLIENTS + + global_opts = { + 'payload_id': payload_id, + 'callsign': callsign_from_payload_id, + 'sentences_db': G_SENTENCES_DB, + 'habdec_clients': G_HABDEC_CLIENTS, + 'habhub_clients': G_HABHUB_CLIENTS, + 'clients_mutex': G_CLIENTS_MTX, + 'payloads': G_SENTENCES_DB.getAllPayloadIds(), + 'get_gps': GET_HABBOY_GPS, + 'get_predict': GetPayloadPredictPath, + 'get_stats': GET_HABBOY_STATS, + 'burst': args.burst + } + + + ############################ START ALL THREADS ############################ + + + # sentence gathering thread + # + HabHubClient.HabHubClient.interval_seconds = args.hab_interval or 15 + + if args.test: + test_file = args.test_file or '' + sentence_gather_thread = threading.Thread( + target=functools.partial(DummySentenceThreadF, payload_id, args.test, test_file) + ) + else: + sentence_gather_thread = threading.Thread( + target=functools.partial(SentenceGatherThreadF, habdec_addr_arr, payload_id) + ) + + sentence_gather_thread.start() + time.sleep(.25) + + + # http thread + # + http_server_thread = threading.Thread( + target=functools.partial( + HttpInterface.RUN, + host, port, is_https, + global_opts, + False, False, + ) + ) + http_server_thread.start() + time.sleep(.25) + + + # GPS thread + # + # gps_thread = threading.Thread(target=GPSD_ReadThread) + gps_device = '/dev/serial/by-id/usb-u-blox_AG_-_www.u-blox.com_u-blox_GNSS_receiver-if00' + gps_thread = threading.Thread( target=functools.partial(GPS_Serial_Thread, gps_device, None) ) + # gps_thread = threading.Thread(target=GPS_Serial_Thread_Fake) + if os.path.isfile(gps_device): + gps_thread.start() + else: + print(gps_device, 'does not exits.') + time.sleep(.25) + + # flight path predict thread + predict_thread = threading.Thread( target=functools.partial(PREDICT_THREAD_F, payload_id, predictor, args.burst) ) + predict_thread.start() + + # proc stats thread + # + if (platform.system() != "Windows"): + habboy_stats_thread = threading.Thread( target=functools.partial(PROC_STATS_THREAD_F, ['habboy_data', 'habdecWebsocketServer']) ) + habboy_stats_thread.start() + + + # main loop + # + while G_RUN: + try: + time.sleep(1) + except KeyboardInterrupt: + print("\nExiting...\n") + G_RUN = False + if G_HABDEC_CLIENTS: + for k, v in G_HABDEC_CLIENTS.items(): + v.Stop() + G_HABDEC_CLIENTS = {} + if G_HABHUB_CLIENTS: + for k, v in G_HABHUB_CLIENTS.items(): + v.Stop() + G_HABHUB_CLIENTS = {} + + # EXITING + # + if sentence_gather_thread and sentence_gather_thread.is_alive(): + sentence_gather_thread.join() + + if gps_thread and gps_thread.is_alive(): + gps_thread.join() + + if predict_thread and predict_thread.is_alive(): + predict_thread.join() + + if habboy_stats_thread and habboy_stats_thread.is_alive(): + habboy_stats_thread.join() + + +def test_gps(): + gps_device = '/dev/serial/by-id/usb-u-blox_AG_-_www.u-blox.com_u-blox_GNSS_receiver-if00' + gps_thread = threading.Thread( target=functools.partial(GPS_Serial_Thread, gps_device, lambda l: None) ) + gps_thread.start() + if gps_thread and gps_thread.is_alive(): + gps_thread.join() + + + +if __name__ == "__main__": + try: + import setproctitle + setproctitle.setproctitle("habboy_data") + except: + print("No setproctitle") + + HABBOY_DATA_MAIN() + # test_gps() diff --git a/data_server/code/nmea.py b/data_server/code/nmea.py new file mode 100644 index 0000000..7c84f79 --- /dev/null +++ b/data_server/code/nmea.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 + +import string +import datetime +import math +from enum import Enum + +def degree_2_decimal(i_pos): + i_pos = float(i_pos) + degs = math.trunc(i_pos / 100) + mins = i_pos - 100.0 * degs + res = degs + mins / 60.0 + return res + + +def NMEA_checksum(buff): + c = 0 + for i in range(len(buff)): + c ^= ord(buff[i]) + return hex(c)[2:] + + +class nmea_t(object): + class fix_status_t(Enum): + kInvalid = 0 + kValid = 1 + class fix_quality_t(Enum): + kNoFix = 0 + kAutonomous = 1 + kDifferential = 2 + kRtkFixed = 4 + kRtkFloat = 5 + kEstimated = 6 + def __init__(self): + self.msg = '$' # RMC or GGA + self.parse_timestamp = datetime.datetime.utcnow() + self.utc_str = '' + self.utc_time = '' + self.lat = 0.0 + self.lon = 0.0 + self.alt = 0.0 + self.sats = 0 + self.ground_speed_mps = 0.0 + self.heading = 0.0 + self.fix_status = nmea_t.fix_status_t( nmea_t.fix_status_t.kInvalid) + self.fix_quality = nmea_t.fix_quality_t( nmea_t.fix_quality_t.kNoFix) + def __str__(self): + res = self.msg + res += ' timestamp:' + str(self.parse_timestamp) + res += ' UTC:' + str(self.utc_time) + res += ' lat:' + str(self.lat) + res += ' lon:' + str(self.lon) + res += ' alt:' + str(self.alt) + res += ' sats:' + str(self.sats) + res += ' ground_speed_mps:' + str(self.ground_speed_mps) + res += ' heading:' + str(self.heading) + res += ' fix_status:' + str(self.fix_status) + res += ' fix_quality:' + str(self.fix_quality) + return res + + + +def __utcstr2date__(i_utcstr): + res_utc = datetime.datetime.utcnow() # 152041.00 + res_utc.replace(hour = int(i_utcstr[0:2])) + res_utc.replace(minute = int(i_utcstr[2:4])) + res_utc.replace(second = int(i_utcstr[5:6])) + microsecs = i_utcstr[8:] #after . + microsecs = int(float('0.' + microsecs) * 1000) + res_utc.replace(microsecond = microsecs) # this does not work somehow + return res_utc + + +class nmea_parser(object): + def __init__(self): + self.__valid_nmea__ = nmea_t() + self.__valid_nmea__.fix_status = nmea_t.fix_status_t( nmea_t.fix_status_t.kInvalid) + self.__valid_nmea__.fix_quality = nmea_t.fix_quality_t( nmea_t.fix_quality_t.kNoFix) + + def feed_line(self, line): + line = line.decode('ascii').strip() + if '*' not in line: + return + while line.startswith('$'): + line = line[1:] + + data_str = line[:line.index('*')] + chcksm = line[line.index('*')+1:] + + if NMEA_checksum(data_str).lower() != chcksm.lower(): + print("NMEA checksum fail:") + print(line) + return + + nmea_current = None + if 'gga' in data_str.lower(): + nmea_current = self.parse_gga(data_str) + # print(nmea_current) + elif 'rmc' in data_str.lower(): + nmea_current = self.parse_rmc(data_str) + # print(nmea_current) + if nmea_current: + if nmea_current.fix_status == nmea_t.fix_status_t.kValid or nmea_current.fix_quality != nmea_t.fix_quality_t.kNoFix: + if nmea_current.msg == 'RMC': + # copy previous values from GGA type + nmea_current.alt = self.__valid_nmea__.alt + nmea_current.sats = self.__valid_nmea__.sats + elif nmea_current.msg == 'GGA': + # copy previous values from RMC type + nmea_current.ground_speed_mps = self.__valid_nmea__.ground_speed_mps + nmea_current.heading = self.__valid_nmea__.heading + + # print(nmea_current) + self.__valid_nmea__ = nmea_current + return self.__valid_nmea__ + + + def parse_gga(self, line): + ''' + $GNGGA,152041.00,,,,,0,00,99.99,,,,,,*7B + GNGGA,180602.00,5206.72454,N,01957.52547,E,1,12,0.95,87.8,M,35.6,M,,*7D + return None when even UTC is not decoded + ''' + res = nmea_t() + res.msg = 'GGA' + + tokens = line.split(',') # should be 15 tokens + # print(tokens, len(tokens)) + if len(tokens) != 15: + return + + if not tokens[1]: + return + else: + res.utc_str = tokens[1] + res.utc_time = __utcstr2date__(res.utc_str) + + if(not tokens[2]): + return res + else: + res.lat = degree_2_decimal(tokens[2]) + if tokens[3].lower() == 's': + res.lat = -res.lat + + if(not tokens[4]): + return res + else: + res.lon = degree_2_decimal(tokens[4]) + if tokens[5].lower() == 'w': + res.lon = -res.lon + + quality = tokens[6] + if not quality: + return res + else: + quality = int(quality) + if quality == 0: + res.fix_quality = nmea_t.fix_quality_t.kNoFix + if quality == 1: + res.fix_quality = nmea_t.fix_quality_t.kAutonomous + if quality == 2: + res.fix_quality = nmea_t.fix_quality_t.kDifferential + if quality == 4: + res.fix_quality = nmea_t.fix_quality_t.kRtkFixed + if quality == 5: + res.fix_quality = nmea_t.fix_quality_t.kRtkFloat + if quality == 6: + res.fix_quality = nmea_t.fix_quality_t.kEstimated + + if not tokens[7]: + return res + else: + res.sats = int(tokens[7]) + + if not tokens[9]: + return res + else: + res.alt = float(tokens[9]) + + return res + + + + + def parse_rmc(self, line): + ''' + $GNRMC,154248.00,V,,,,,,,010620,,,N*68 + GNRMC,180602.00,A,5206.72454,N,01957.52547,E,0.023,,010620,,,A*6D + return None when even UTC is not decoded + ''' + res = nmea_t() + res.msg = 'RMC' + + tokens = line.split(',') # should be 13 tokens + # print(tokens, len(tokens)) + if len(tokens) != 13: + return + + if not tokens[1]: + return + else: + res.utc_str = tokens[1] + res.utc_time = __utcstr2date__(res.utc_str) + + if not tokens[2]: + return res + else: + if tokens[2].lower() == 'a': + res.fix_status = nmea_t.fix_status_t.kValid + elif tokens[2].lower() == 'v': + res.fix_status = nmea_t.fix_status_t.kInvalid + + if(not tokens[3]): + return res + else: + res.lat = degree_2_decimal(tokens[3]) + if tokens[4].lower() == 's': + res.lat = -res.lat + + if(not tokens[5]): + return res + else: + res.lon = degree_2_decimal(tokens[5]) + if tokens[6].lower() == 'w': + res.lon = -res.lon + + if not tokens[7]: + res.ground_speed_mps = 0 + else: + res.ground_speed_mps = 0.514444444 * float(tokens[7]) # from knots to m/s + + if not tokens[8]: + res.heading = 0 + else: + res.heading = float(tokens[8]) + + return res diff --git a/discovery/README.md b/discovery/README.md new file mode 100644 index 0000000..6136a01 --- /dev/null +++ b/discovery/README.md @@ -0,0 +1,4 @@ +# Discovery +Tools to help find Habdec/habboy in a network without DNS and static IPs. + +[discovery - Install As Service](./lan/README.md) diff --git a/discovery/inet/get.php b/discovery/inet/get.php new file mode 100644 index 0000000..6405572 --- /dev/null +++ b/discovery/inet/get.php @@ -0,0 +1,7 @@ + diff --git a/discovery/inet/index.html b/discovery/inet/index.html new file mode 100644 index 0000000..db23fc6 --- /dev/null +++ b/discovery/inet/index.html @@ -0,0 +1,29 @@ + + + + + + + + + + diff --git a/discovery/inet/ip.json b/discovery/inet/ip.json new file mode 100644 index 0000000..7332021 --- /dev/null +++ b/discovery/inet/ip.json @@ -0,0 +1,4 @@ +{ + "habboy": "2019-10-16|22:00:01.379700|192.168.1.53|83.238.169.175", + "pi1": "2019-10-16|21:57:03.096608|192.168.1.12|83.238.169.175" +} \ No newline at end of file diff --git a/discovery/inet/ip.php b/discovery/inet/ip.php new file mode 100644 index 0000000..eccbb7a --- /dev/null +++ b/discovery/inet/ip.php @@ -0,0 +1,15 @@ + + + + + \ No newline at end of file diff --git a/discovery/inet/reportIP.py b/discovery/inet/reportIP.py new file mode 100644 index 0000000..0be0719 --- /dev/null +++ b/discovery/inet/reportIP.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python +import string +import subprocess +import socket +import datetime +import re +import random + +from sys import version_info + +PY3K = version_info >= (3, 0) + +if PY3K: + import urllib.request as urllib +else: + import urllib2 as urllib + +__version__ = "0.6" + + +def myip(): + return IPgetter().get_externalip() + + +class IPgetter(object): + + ''' + This class is designed to fetch your external IP address from the internet. + It is used mostly when behind a NAT. + It picks your IP randomly from a serverlist to minimize request overhead + on a single server + ''' + + def __init__(self): + self.server_list = ['http://ip.dnsexit.com', + 'http://ifconfig.me/ip', + 'http://ipecho.net/plain', + 'http://checkip.dyndns.org/plain', + 'http://ipogre.com/linux.php', + 'http://whatismyipaddress.com/', + 'http://ip.my-proxy.com/', + 'http://websiteipaddress.com/WhatIsMyIp', + 'http://getmyipaddress.org/', + 'http://www.my-ip-address.net/', + 'http://myexternalip.com/raw', + 'http://www.canyouseeme.org/', + 'http://www.trackip.net/', + 'http://icanhazip.com/', + 'http://www.iplocation.net/', + 'http://www.howtofindmyipaddress.com/', + 'http://www.ipchicken.com/', + 'http://whatsmyip.net/', + 'http://www.ip-adress.com/', + 'http://checkmyip.com/', + 'http://www.tracemyip.org/', + 'http://checkmyip.net/', + 'http://www.lawrencegoetz.com/programs/ipinfo/', + 'http://www.findmyip.co/', + 'http://ip-lookup.net/', + 'http://www.dslreports.com/whois', + 'http://www.mon-ip.com/en/my-ip/', + 'http://www.myip.ru', + 'http://ipgoat.com/', + 'http://www.myipnumber.com/my-ip-address.asp', + 'http://www.whatsmyipaddress.net/', + 'http://formyip.com/', + 'https://check.torproject.org/', + 'http://www.displaymyip.com/', + 'http://www.bobborst.com/tools/whatsmyip/', + 'http://www.geoiptool.com/', + 'https://www.whatsmydns.net/whats-my-ip-address.html', + 'https://www.privateinternetaccess.com/pages/whats-my-ip/', + 'http://checkip.dyndns.com/', + 'http://myexternalip.com/', + 'http://www.ip-adress.eu/', + 'http://www.infosniper.net/', + 'http://wtfismyip.com/', + 'http://ipinfo.io/', + 'http://httpbin.org/ip'] + + def get_externalip(self): + ''' + This function gets your IP from a random server + ''' + + random.shuffle(self.server_list) + myip = '' + for server in self.server_list: + myip = self.fetch(server) + if myip != '': + return myip + else: + continue + return '' + + def fetch(self, server): + ''' + This function gets your IP from a specific server + ''' + url = None + opener = urllib.build_opener() + opener.addheaders = [('User-agent', + "Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0")] + + try: + url = opener.open(server) + content = url.read() + + # Didn't want to import chardet. Prefered to stick to stdlib + if PY3K: + try: + content = content.decode('UTF-8') + except UnicodeDecodeError: + content = content.decode('ISO-8859-1') + + m = re.search( + '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', + content) + myip = m.group(0) + return myip if len(myip) > 0 else '' + except Exception: + return '' + finally: + if url: + url.close() + + def test(self): + ''' + This functions tests the consistency of the servers + on the list when retrieving your IP. + All results should be the same. + ''' + + resultdict = {} + for server in self.server_list: + resultdict.update(**{server: self.fetch(server)}) + + ips = sorted(resultdict.values()) + ips_set = set(ips) + print('\nNumber of servers: {}'.format(len(self.server_list))) + print("IP's :") + for ip, ocorrencia in zip(ips_set, map(lambda x: ips.count(x), ips_set)): + print('{0} = {1} ocurrenc{2}'.format(ip if len(ip) > 0 else 'broken server', ocorrencia, 'y' if ocorrencia == 1 else 'ies')) + print('\n') + print(resultdict) + +# Change to your own account information + +# Very Linux Specific +def get_ip(): + arg='ip route list' + p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE) + data = p.communicate() + split_data = data[0].split() + ipaddr = split_data[split_data.index('src')+1] + return ipaddr + +def get_local_ips(): + arg='ip route list' + p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE) + data = p.communicate() + split_data = data[0].split() + # ipaddr = split_data[split_data.index('src')+1] + res = [] + for i in xrange(len(split_data)): + if split_data[i] == 'src': + res.append(split_data[i+1]) + return res + +def send_to_www(IP): + H = socket.gethostname() + url = 'http://cgarea.com/ip/ip.php?HOST=%s&IP=%s' % (H, IP) + print url + + hdr = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'Accept-Encoding': 'gzip, deflate, sdch', + 'Accept-Language': 'pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4', + 'Cache-Control': 'max-age=0', + 'Connection': 'keep-alive', + 'Upgrade-Insecure-Requests': '1', + 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' + } + req = urllib.Request(url, headers = hdr) + urllib.urlopen( req ) + +if __name__ == '__main__': + ip = str( datetime.datetime.now() ).replace(' ', '|') + # ip += '|' + get_ip() + ip += '|' + string.join( get_local_ips(), '|') + ip += '|' + myip() + try: + send_to_www(ip) + except: + import traceback + print traceback.format_exc() + pass + print ip + + diff --git a/discovery/lan/HabBoyAdvertise.py b/discovery/lan/HabBoyAdvertise.py new file mode 100644 index 0000000..595da8d --- /dev/null +++ b/discovery/lan/HabBoyAdvertise.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 + +__all__ = ['RUN'] + +import argparse +import subprocess +import bottle + +HELP_STRING = r'''HabBoyAdvertise +Simple HTTP server running on port 8889 +Answers on "/habboy" URL and redirects to true HabBoy server +This is usefull if HabBoy runs on HTTPS and can't respond to HTTP requests +''' + +def get_ip(): + p = subprocess.Popen("ip route list", shell=True, stdout=subprocess.PIPE) + data = p.communicate() + data = data[0].decode().split("\n") + while "" in data: + data.remove("") + split_data = data[-1].split() + + ipaddr = split_data[split_data.index("src") + 1] + return ipaddr + + +class EnableCors(object): + name = "enable_cors" + api = 2 + + def apply(self, fn, context): + def _enable_cors(*args, **kwargs): + # set CORS headers + bottle.response.headers["Access-Control-Allow-Origin"] = "*" + bottle.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS" + bottle.response.headers["Access-Control-Allow-Headers"] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token" + + # actual request; reply with the actual response + if bottle.request.method != "OPTIONS": + return fn(*args, **kwargs) + + return _enable_cors + +application = bottle.app() +application.install(EnableCors()) + + +# @application.route('/') +@application.route('/habboy') +def route_root(): + new_url = bottle.request.url[0:bottle.request.url.rindex(':')] + new_port = '8888' + res = ''.format(new_url, new_port) + return res + + +def RUN(host,port): + bottle.run(host=host, port=port, debug=False, reloader=False) + print(host,port) + + +def main(): + try: + import setproctitle + setproctitle.setproctitle("HabBoyAdvertise") + except: + print("No setproctitle") + + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="0.0.0.0", help="hostname") + parser.add_argument("--port", type=int, default=8889, help="http port, default 8889") + args = parser.parse_args() + RUN(host=args.host, port=args.port) + + +if __name__ == "__main__": + main() diff --git a/discovery/lan/HabBoyDiscovery.py b/discovery/lan/HabBoyDiscovery.py new file mode 100644 index 0000000..f8118b1 --- /dev/null +++ b/discovery/lan/HabBoyDiscovery.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 + + +import sys +import subprocess +import socket +import urllib3 +import traceback +import argparse +import time + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) +http = urllib3.PoolManager(cert_reqs='CERT_NONE') + +__all__ = ['habboy_discovery', 'is_habboy', 'get_ip', 'ip_increment'] + +HELP_STRING = r''' +HabBoy Discovery +Attempts to find running HabBoy server in local network. +Loop over IP addresses starting from start_IP. +Probes for Habboy or HabboyAdvertise server on port 8888 or 8889 +If not found, increments IP address and scans again. +''' + + +def get_ip_old(): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(('10.255.255.255', 1)) # doesn't even have to be reachable + IP = s.getsockname()[0] + except: + IP = None + finally: + s.close() + return IP + + +def get_ip(): + try: + arg='ip route list' + p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE, universal_newlines='\n') + data = p.communicate() + data = data[0].split('\n') + while '' in data: + data.remove('') + split_data = data[-1].split() + + ipaddr = split_data[split_data.index('src')+1] + return ipaddr + except: + return None + +def ip_increment(i_ip): + tokens = i_ip.split('.') + tokens[3] = int(tokens[3]) + 1 + if tokens[3] > 254: + return "" + # do not increment to next network + ''' + tokens[3] = 2 + tokens[2] = int(tokens[2]) + 1 + if tokens[2] > 254: + return "" + ''' + tokens = map(str, tokens) + return '.'.join(tokens) + + +def test_ip_increment(i_ip): + ip = i_ip + while ip != "": + # print(ip) + ip = ip_increment(ip) + return "" + + +def is_habboy(i_url, timeout_ms = 2000): + timeout_ms = timeout_ms or 2000 + + try: + try: + r = http.request('GET', 'http://' + i_url, timeout=.001 * timeout_ms) + except urllib3.exceptions.MaxRetryError: + r = http.request('GET', 'https://' + i_url, timeout=.001 * timeout_ms) + except KeyboardInterrupt: + sys.exit(0) + except: + return False + + if r.status == 200: + return True + + return False + + +def habboy_discovery(start_ip = '', port = 8888, timeout_ms = None, verbose = False): + + while not start_ip: + start_ip = get_ip() + if start_ip: + start_ip = start_ip.split('.') + start_ip[-1] = '2' + start_ip = '.'.join(start_ip) + break + time.sleep(1) + + ip = start_ip + + while True: + if not ip: + break + + _url = '{}:{}/habboy'.format(ip, port) + if verbose: + print(_url) + + if is_habboy(_url, timeout_ms): + return ip + + ip = ip_increment(ip) + + return None + + +def CliArgs(): + parser = argparse.ArgumentParser() + parser.add_argument("--start_ip", type=str, default="", help="Scan for HabBoy/HabBoyAdvertise server starting from IP upwards.") + parser.add_argument("--port", type=int, default=8888, help="habboy discovery port. 8888 or 8889. default 8888.") + parser.add_argument("--timeout_ms", type=int, help="probing timeout milliseconds") + parser.add_argument("--verbose", action="store_true", help="print IPs") + + args = parser.parse_args() + return args + + +def main(): + args = CliArgs() + start_ip = args.start_ip + port = args.port + verbose = args.verbose + timeout = args.timeout_ms + + try: + while(True): + res = habboy_discovery(start_ip = start_ip, port=port, verbose = verbose, timeout_ms = timeout) + if verbose: + print(res) + if res: + print(res) + sys.exit(0) + except KeyboardInterrupt: + sys.exit(0) + + +if __name__ == "__main__": + main() + diff --git a/discovery/lan/HabDecAdvertise.py b/discovery/lan/HabDecAdvertise.py new file mode 100644 index 0000000..6bb2ac0 --- /dev/null +++ b/discovery/lan/HabDecAdvertise.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 + +''' +find habboy +and periodically add habdec to it +''' + +import time +import argparse +import traceback + +import urllib3 +http = urllib3.PoolManager(cert_reqs='CERT_NONE') + +import HabBoyDiscovery + +HELP_STRING = r'''HabDecAdvertise +Loops over IP range to find running HabBoy server and inform it that habdec is running. +Parameters: + --start_ip - scan for habboy from this address upward + --disco_port - probe habboy on discovery port. 8888 if HabBoy works over HTTP or 8889 for HTTPS + --habboy_port - port on which habboy runs + --timeout_ms + --pause + --verbose +Habdec IP = habboy IP +Habdec port = 5555 +''' + +def RegisterHabDec(habboy_ip, habboy_port='8888', habdec_ip = None, habdec_port='5555' ): + while not habdec_ip: + habdec_ip = HabBoyDiscovery.get_ip() + + _url = '{}:{}/habboy/api/v1/habdec/add/{}:{}'.format( + habboy_ip, habboy_port, habdec_ip, habdec_port + ) + # print (_url) + + try: + r = http.request('GET', 'http://' + _url) + except urllib3.exceptions.MaxRetryError: + try: + r = http.request('GET', 'https://' + _url) + except: + return False + + if r.status == 200: + # print(r.data) + return r.data == b'OK' or r.data == b'already exists' + else: + # print(r) + return False + +def RegisterHabDecLoop(i_start_ip, disco_port, habboy_port, pause = 1, timeout_ms = None, verbose=0): + while True: + try: + habboy_ip = HabBoyDiscovery.habboy_discovery(start_ip = i_start_ip, port = disco_port, verbose = verbose, timeout_ms = timeout_ms) + if habboy_ip: + res = RegisterHabDec(habboy_ip, habboy_port) + if verbose: + print(habboy_ip, res) + except: + # print("Connection Error") + print(traceback.format_exc()) + pass + time.sleep(pause) + +def test(): + habboy_ip = HabBoyDiscovery.habboy_discovery('192.168.2.170') + print('habboy_ip: ', habboy_ip) + print( RegisterHabDec(habboy_ip) ) + +def CliArgs(): + parser = argparse.ArgumentParser() + parser.add_argument("--start_ip", type=str, default="", help="Scan for HabBoy starting from this IP upward.") + parser.add_argument("--disco_port", type=int, default=8888, help="Probe habboy on discovery port. 8888 for HTTP or 8889 for HTTPS. Default 8888.") + parser.add_argument("--habboy_port", type=int, default=8888, help="habboy server port. Default 8888.") + parser.add_argument("--timeout_ms", type=int, help="Probing timeout milliseconds") + parser.add_argument("--pause", type=int, default=15, help="Looping interval pause") + parser.add_argument("--verbose", action="store_true", help="Print IPs") + + args = parser.parse_args() + return args + + +def main(): + try: + import setproctitle + setproctitle.setproctitle("HabDecAdvertise") + except: + print("No setproctitle") + + print(HELP_STRING) + + args = CliArgs() + + timeout_ms = args.timeout_ms + + + RegisterHabDecLoop( args.start_ip, args.disco_port, args.habboy_port, args.pause, timeout_ms, args.verbose ) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/discovery/lan/README.md b/discovery/lan/README.md new file mode 100644 index 0000000..560e3b6 --- /dev/null +++ b/discovery/lan/README.md @@ -0,0 +1,42 @@ +### HabDecAdvertise.py + HabDec Advertise + Loops over IP range to find running HabBoy server and inform it that habdec is running. + Parameters: + --start_ip - scan for habboy from this address upward + --disco_port - probe habboy on discovery port. 8888 if HabBoy works over HTTP or 8889 for HTTPS + --habboy_port - port on which habboy runs + --timeout_ms + --pause + --verbose + Habdec IP = habboy IP + Habdec port = 5555 + +### HabBoyAdvertise.py + HabBoy Advertise + Simple HTTP server running on port 8889 + Answers on "/habboy" URL and redirects to true HabBoy server + This is usefull if HabBoy runs on HTTPS and can't respond to HTTP requests + +##### HabBoy Advertise - Install As Service + sudo cp ./discovery/lan/HabBoyAdvertise.service /etc/systemd/system/ + sudo systemctl enable HabBoyAdvertise.service + sudo systemctl daemon-reload + sudo systemctl start HabBoyAdvertise.service + sudo journalctl -u HabBoyAdvertise.service + + Open index.html in browser - it will find HabBoy in your LAN + + +### HabBoyDiscovery.py + HabBoy Discovery + Attempts to find running HabBoy server in local network. + Loop over IP addresses starting from start_IP. + Probes for Habboy or HabboyAdvertise server on port 8888 or 8889 + If not found, increments IP address and scans again. + +### index.html + Scans over IP range looking for running HabBoy server. + Probes http://IP:8888/habboy + This is javascript equvalent of HabBoyDiscovery.py + URL parameter: ip - scan from this IP upwards HabBoyDiscovery.py + For example: http://index.html?ip=192.168.88.235 \ No newline at end of file diff --git a/discovery/lan/habboy.service b/discovery/lan/habboy.service new file mode 100644 index 0000000..48a04f0 --- /dev/null +++ b/discovery/lan/habboy.service @@ -0,0 +1,14 @@ +[Unit] +Description=habboy +Wants=network.target network-online.target +After=network.target network-online.target + +[Service] +#Type=simple +User=mfratczak +Group=mfratczak +ExecStart=/home/mfratczak/share/dev/habboy_dev/habboy_sw/data_server/code/main.py +WorkingDirectory=/home/mfratczak/share/dev/habboy_dev/habboy_sw/data_server/code/ + +[Install] +WantedBy=multi-user.target diff --git a/discovery/lan/habboy_advertise.service b/discovery/lan/habboy_advertise.service new file mode 100644 index 0000000..ea4a858 --- /dev/null +++ b/discovery/lan/habboy_advertise.service @@ -0,0 +1,14 @@ +[Unit] +Description=habboy_advertise +Wants=network.target network-online.target +After=network.target network-online.target + +[Service] +#Type=simple +User=mfratczak +Group=mfratczak +ExecStart=/home/mfratczak/share/dev/habboy_dev/habboy_sw/discovery/lan/HabBoyAdvertise.py +WorkingDirectory=/home/mfratczak/share/dev/habboy_dev/habboy_sw/discovery/lan + +[Install] +WantedBy=multi-user.target diff --git a/discovery/lan/habdec.service b/discovery/lan/habdec.service new file mode 100644 index 0000000..03b1eef --- /dev/null +++ b/discovery/lan/habdec.service @@ -0,0 +1,15 @@ +[Unit] +Description=habdec +Wants=network.target network-online.target +After=network.target network-online.target + +[Service] +#Type=simple +User=mfratczak +Group=mfratczak +ExecStart=/home/mfratczak/share/dev/habdec/build/install/habdecWebsocketServer --config service.config --print 0 --no_exit 1 +WorkingDirectory=/home/mfratczak/share/dev/habdec/build/install/ +Restart=on-failure + +[Install] +WantedBy=multi-user.target diff --git a/discovery/lan/habdec_advertise.service b/discovery/lan/habdec_advertise.service new file mode 100644 index 0000000..5e59078 --- /dev/null +++ b/discovery/lan/habdec_advertise.service @@ -0,0 +1,14 @@ +[Unit] +Description=habdec_advertise +Wants=network.target network-online.target +After=network.target network-online.target + +[Service] +#Type=simple +User=mfratczak +Group=mfratczak +ExecStart=/home/mfratczak/share/dev/habboy_dev/habboy_sw/discovery/lan/HabDecAdvertise.py --start_ip 192.168.1.240 --timeout_ms 500 --verbose + + +[Install] +WantedBy=multi-user.target diff --git a/discovery/lan/index.html b/discovery/lan/index.html new file mode 100644 index 0000000..f1bb83c --- /dev/null +++ b/discovery/lan/index.html @@ -0,0 +1,92 @@ + + + + +

+ Scanning network for HABBOY +
+

+ + + + + \ No newline at end of file diff --git a/docs/HabBoy_Habdec.jpg b/docs/HabBoy_Habdec.jpg new file mode 100644 index 0000000..449df70 Binary files /dev/null and b/docs/HabBoy_Habdec.jpg differ diff --git a/docs/HabBoy_Osm.jpg b/docs/HabBoy_Osm.jpg new file mode 100644 index 0000000..cfa9b3b Binary files /dev/null and b/docs/HabBoy_Osm.jpg differ diff --git a/docs/VECTOR_TILES.md b/docs/VECTOR_TILES.md new file mode 100644 index 0000000..3d48e6f --- /dev/null +++ b/docs/VECTOR_TILES.md @@ -0,0 +1,14 @@ +# OpenStreetMap Vector Tiles + +![](./HabBoy_Osm.jpg) + +To use Open Street Map in HabBoy, you need to generate vector tiles in MapBox format. It is recommended to use [tilemaker](https://github.com/systemed/tilemaker). + +You can use [this repo](https://github.com/ogre/tilemaker_config) as guideline to tilemaker configuration and usage. + +Folder ```tilemaker_config``` in this repo contains tilemaker configuration for HabBoy. + +After successful generation of tiles, symlink tiles folder to correct webserver location. The exact URL at which tiles must be accesible is defined in file ```webUI/code/js/HB_map_style_default.js``` in ```var data_root = HABBOY_URL + "/osm/tiles";```. + +For example: +```ln -s ~/osm /var/www/html/osm``` diff --git a/docs/habboy_structure.drawio b/docs/habboy_structure.drawio new file mode 100644 index 0000000..15eb97a --- /dev/null +++ b/docs/habboy_structure.drawio @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/habboy_structure.png b/docs/habboy_structure.png new file mode 100644 index 0000000..6051f23 Binary files /dev/null and b/docs/habboy_structure.png differ diff --git a/docs/misc.md b/docs/misc.md new file mode 100644 index 0000000..894d9ab --- /dev/null +++ b/docs/misc.md @@ -0,0 +1,73 @@ +### BROWSER SETTINGS for relaxed HTTPS + +#### FIREFOX: + about:config --> + - security.mixed_content.block_active_content = false + - network.websocket.allowInsecureFromHTTPS = true <<< this should be enough for habdec websocket + network.stricttransportsecurity.preloadlist = false + +#### CHROME: + chrome://flags --> + - Insecure origins treated as secure + + + +### SSL cert generate - for data server + + openssl req -new -x509 -days 1095 -nodes -newkey rsa:2048 -out cacert.pem -keyout privkey.pem -subj "/CN=192.168.100.53" + + + +### UBUNTU SERVER CONFIG + +### disable firewall: ```sudo ufw disable``` + +### apache ssl: +``` +su - +a2enmod ssl +systemctl restart apache2 +openssl genrsa -out ca.key 2048 +openssl req -nodes -new -key ca.key -out ca.csr +openssl x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt +mkdir /etc/apache2/ssl/ +cp ca.crt ca.key ca.csr /etc/apache2/ssl/ +``` + +``` +nano /etc/apache2/sites-enable/000-default.conf + + "Comment out all the lines by adding a “#” in front of each line and add the following lines:" + + ServerAdmin webmaster@localhost + DocumentRoot /var/www/html + ErrorLog ${APACHE_LOG_DIR}/error.log + CustomLog ${APACHE_LOG_DIR}/access.log combined + SSLEngine on + SSLCertificateFile /etc/apache2/ssl/ca.crt + SSLCertificateKeyFile /etc/apache2/ssl/ca.key + + +systemctl restart apache2 +``` + +### Disable Unattended Upgrade in Ubuntu 16.04 +https://askubuntu.com/questions/953779/programmatically-disable-apt-unattended-upgrades + +``` +sudo nano /etc/apt/apt.conf.d/10periodic + +APT::Periodic::Update-Package-Lists "0"; +APT::Periodic::Unattended-Upgrade "0"; +``` + +``` +sudo nano /etc/apt/apt.conf.d/20auto-upgrades + +APT::Periodic::Update-Package-Lists "0"; +APT::Periodic::Unattended-Upgrade "0"; +``` + +``` +sudo cp /usr/share/unattended-upgrades/20auto-upgrades-disabled /etc/apt/apt.conf.d/ +``` \ No newline at end of file diff --git a/hw_iface/README.md b/hw_iface/README.md new file mode 100644 index 0000000..8340c63 --- /dev/null +++ b/hw_iface/README.md @@ -0,0 +1,5 @@ +An interface between hardware and other HABBOY components. +Specifically a websocket interface for browser GUI. +It gathers GPS, joystick and buttons signals and provides them through different interfaces, ie: websocket, UDP, REST-like http + +Currently this is very outdated. \ No newline at end of file diff --git a/hw_iface/code/CMake/GetGitRevisionDescription.cmake b/hw_iface/code/CMake/GetGitRevisionDescription.cmake new file mode 100644 index 0000000..d678ee1 --- /dev/null +++ b/hw_iface/code/CMake/GetGitRevisionDescription.cmake @@ -0,0 +1,170 @@ +# https://github.com/rpavlik/cmake-modules + +# - Returns a version string from Git +# +# These functions force a re-configure on each git commit so that you can +# trust the values of the variables in your build system. +# +# get_git_head_revision( [ ...]) +# +# Returns the refspec and sha hash of the current head revision +# +# git_describe( [ ...]) +# +# Returns the results of git describe on the source tree, and adjusting +# the output so that it tests false if an error occurs. +# +# git_get_exact_tag( [ ...]) +# +# Returns the results of git describe --exact-match on the source tree, +# and adjusting the output so that it tests false if there was no exact +# matching tag. +# +# git_local_changes() +# +# Returns either "CLEAN" or "DIRTY" with respect to uncommitted changes. +# Uses the return code of "git diff-index --quiet HEAD --". +# Does not regard untracked files. +# +# Requires CMake 2.6 or newer (uses the 'function' command) +# +# Original Author: +# 2009-2010 Ryan Pavlik +# http://academic.cleardefinition.com +# Iowa State University HCI Graduate Program/VRAC +# +# Copyright Iowa State University 2009-2010. +# Distributed under the Boost Software License, Version 1.0. +# (See accompanying file LICENSE_1_0.txt or copy at +# http://www.boost.org/LICENSE_1_0.txt) + +if(__get_git_revision_description) + return() +endif() +set(__get_git_revision_description YES) + +# We must run the following at "include" time, not at function call time, +# to find the path to this module rather than the path to a calling list file +get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH) + +function(get_git_head_revision _refspecvar _hashvar) + set(GIT_PARENT_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + set(GIT_DIR "${GIT_PARENT_DIR}/.git") + while(NOT EXISTS "${GIT_DIR}") # .git dir not found, search parent directories + set(GIT_PREVIOUS_PARENT "${GIT_PARENT_DIR}") + get_filename_component(GIT_PARENT_DIR ${GIT_PARENT_DIR} PATH) + if(GIT_PARENT_DIR STREQUAL GIT_PREVIOUS_PARENT) + # We have reached the root directory, we are not in git + set(${_refspecvar} "GITDIR-NOTFOUND" PARENT_SCOPE) + set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE) + return() + endif() + set(GIT_DIR "${GIT_PARENT_DIR}/.git") + endwhile() + # check if this is a submodule + if(NOT IS_DIRECTORY ${GIT_DIR}) + file(READ ${GIT_DIR} submodule) + string(REGEX REPLACE "gitdir: (.*)\n$" "\\1" GIT_DIR_RELATIVE ${submodule}) + get_filename_component(SUBMODULE_DIR ${GIT_DIR} PATH) + get_filename_component(GIT_DIR ${SUBMODULE_DIR}/${GIT_DIR_RELATIVE} ABSOLUTE) + endif() + set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data") + if(NOT EXISTS "${GIT_DATA}") + file(MAKE_DIRECTORY "${GIT_DATA}") + endif() + + if(NOT EXISTS "${GIT_DIR}/HEAD") + return() + endif() + set(HEAD_FILE "${GIT_DATA}/HEAD") + configure_file("${GIT_DIR}/HEAD" "${HEAD_FILE}" COPYONLY) + + configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in" + "${GIT_DATA}/grabRef.cmake" + @ONLY) + include("${GIT_DATA}/grabRef.cmake") + + set(${_refspecvar} "${HEAD_REF}" PARENT_SCOPE) + set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE) +endfunction() + +function(git_describe _var) + if(NOT GIT_FOUND) + find_package(Git QUIET) + endif() + get_git_head_revision(refspec hash) + if(NOT GIT_FOUND) + set(${_var} "GIT-NOTFOUND" PARENT_SCOPE) + return() + endif() + if(NOT hash) + set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE) + return() + endif() + + # TODO sanitize + #if((${ARGN}" MATCHES "&&") OR + # (ARGN MATCHES "||") OR + # (ARGN MATCHES "\\;")) + # message("Please report the following error to the project!") + # message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}") + #endif() + + #message(STATUS "Arguments to execute_process: ${ARGN}") + + execute_process(COMMAND + "${GIT_EXECUTABLE}" + describe + ${hash} + ${ARGN} + WORKING_DIRECTORY + "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE + res + OUTPUT_VARIABLE + out + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if(NOT res EQUAL 0) + set(out "${out}-${res}-NOTFOUND") + endif() + + set(${_var} "${out}" PARENT_SCOPE) +endfunction() + +function(git_get_exact_tag _var) + git_describe(out --exact-match ${ARGN}) + set(${_var} "${out}" PARENT_SCOPE) +endfunction() + +function(git_local_changes _var) + if(NOT GIT_FOUND) + find_package(Git QUIET) + endif() + get_git_head_revision(refspec hash) + if(NOT GIT_FOUND) + set(${_var} "GIT-NOTFOUND" PARENT_SCOPE) + return() + endif() + if(NOT hash) + set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE) + return() + endif() + + execute_process(COMMAND + "${GIT_EXECUTABLE}" + diff-index --quiet HEAD -- + WORKING_DIRECTORY + "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE + res + OUTPUT_VARIABLE + out + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if(res EQUAL 0) + set(${_var} "CLEAN" PARENT_SCOPE) + else() + set(${_var} "DIRTY" PARENT_SCOPE) + endif() +endfunction() diff --git a/hw_iface/code/CMake/GetGitRevisionDescription.cmake.in b/hw_iface/code/CMake/GetGitRevisionDescription.cmake.in new file mode 100644 index 0000000..0d0ba7c --- /dev/null +++ b/hw_iface/code/CMake/GetGitRevisionDescription.cmake.in @@ -0,0 +1,43 @@ +# https://github.com/rpavlik/cmake-modules + +# +# Internal file for GetGitRevisionDescription.cmake +# +# Requires CMake 2.6 or newer (uses the 'function' command) +# +# Original Author: +# 2009-2010 Ryan Pavlik +# http://academic.cleardefinition.com +# Iowa State University HCI Graduate Program/VRAC +# +# Copyright Iowa State University 2009-2010. +# Distributed under the Boost Software License, Version 1.0. +# (See accompanying file LICENSE_1_0.txt or copy at +# http://www.boost.org/LICENSE_1_0.txt) + +set(HEAD_HASH) + +file(READ "@HEAD_FILE@" HEAD_CONTENTS LIMIT 1024) + +string(STRIP "${HEAD_CONTENTS}" HEAD_CONTENTS) +if(HEAD_CONTENTS MATCHES "ref") + # named branch + string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}") + if(EXISTS "@GIT_DIR@/${HEAD_REF}") + configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY) + else() + configure_file("@GIT_DIR@/packed-refs" "@GIT_DATA@/packed-refs" COPYONLY) + file(READ "@GIT_DATA@/packed-refs" PACKED_REFS) + if(${PACKED_REFS} MATCHES "([0-9a-z]*) ${HEAD_REF}") + set(HEAD_HASH "${CMAKE_MATCH_1}") + endif() + endif() +else() + # detached HEAD + configure_file("@GIT_DIR@/HEAD" "@GIT_DATA@/head-ref" COPYONLY) +endif() + +if(NOT HEAD_HASH) + file(READ "@GIT_DATA@/head-ref" HEAD_HASH LIMIT 1024) + string(STRIP "${HEAD_HASH}" HEAD_HASH) +endif() diff --git a/hw_iface/code/CMakeLists.txt b/hw_iface/code/CMakeLists.txt new file mode 100644 index 0000000..4cd99e5 --- /dev/null +++ b/hw_iface/code/CMakeLists.txt @@ -0,0 +1,86 @@ +cmake_minimum_required( VERSION 3.8.2 ) + +project (habboy_hw_iface) +set ( CMAKE_CXX_STANDARD 17 ) + +# set ( CMAKE_BUILD_TYPE "Debug" ) +# set ( CMAKE_BUILD_TYPE "Release" ) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Release") +endif() + +if ( CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT ) + set ( CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Install dir" FORCE) +endif() +message ( "CMAKE_INSTALL_PREFIX: " ${CMAKE_INSTALL_PREFIX} ) + + + +list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/CMake/") +include(GetGitRevisionDescription) +get_git_head_revision(GIT_REFSPEC GIT_SHA1) + +include_directories( ${PROJECT_SOURCE_DIR} ) +include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ) + +# boost +set ( Boost_NO_BOOST_CMAKE ON ) +set ( Boost_NO_SYSTEM_PATHS ON ) +set ( Boost_USE_STATIC_LIBS ON ) +add_definitions ( -DBOOST_ALL_NO_LIB ) +find_package(Boost REQUIRED COMPONENTS program_options system date_time ) +include_directories( ${Boost_INCLUDE_DIRS} ) +message ( "Boost_INCLUDE_DIRS " ${Boost_INCLUDE_DIRS} ) +message ( "Boost_LIBRARY_DIRS " ${Boost_LIBRARY_DIRS} ) + +set( CMAKE_CXX_FLAGS " -O3 " ) +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + # set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wshadow" ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-class-memaccess" ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable" ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter" ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=return-type" ) +elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + SET(CMAKE_CXX_FLAGS "/EHsc") + add_definitions( -D_USE_MATH_DEFINES ) +endif() + +set (PlatformSpecificLinking "") +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + set (PlatformSpecificLinking "pthread") +endif() + +set ( habboy_hw_iface_src + console_colors.h console_colors.cpp + pystring.h pystring.cpp + program_options.h program_options.cpp + GpsState.h GpsState.cpp + ws_server.h ws_server.cpp + hb_serial.h hb_serial.cpp + listener.h listener.cpp + http_session.h http_session.cpp + websocket_session.h websocket_session.cpp + msg_broker.h msg_broker.cpp + main.cpp + ) + +# compile in git repo version +configure_file("${PROJECT_SOURCE_DIR}/git_repo_sha1.cpp.in" "${CMAKE_CURRENT_BINARY_DIR}/git_repo_sha1.cpp" @ONLY) +list(APPEND habboy_hw_iface_src "${CMAKE_CURRENT_BINARY_DIR}/git_repo_sha1.cpp" ${PROJECT_SOURCE_DIR}/git_repo_sha1.h) + +add_executable ( habboy_hw_iface ${habboy_hw_iface_src} ) +target_link_libraries( habboy_hw_iface + ${Boost_LIBRARIES} + ${PlatformSpecificLinking} ) + +install ( TARGETS habboy_hw_iface DESTINATION ${CMAKE_INSTALL_PREFIX} ) +install ( FILES ${PROJECT_SOURCE_DIR}/habLogger/habLogger.py + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ + DESTINATION ${CMAKE_INSTALL_PREFIX} ) + + +file( WRITE ${CMAKE_CURRENT_BINARY_DIR}/run_loop.sh "#!/bin/sh\n while true; do ./habboy_hw_iface --config ./habdechabboy_hw_iface.opts; done\n" ) +install ( FILES ${CMAKE_CURRENT_BINARY_DIR}/run_loop.sh + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ + DESTINATION ${CMAKE_INSTALL_PREFIX} ) + diff --git a/hw_iface/code/GLOBALS.h b/hw_iface/code/GLOBALS.h new file mode 100644 index 0000000..212cd91 --- /dev/null +++ b/hw_iface/code/GLOBALS.h @@ -0,0 +1,69 @@ + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "websocket_session.h" +#include "GpsState.h" +#include "hb_serial.h" + + +// singleton class keeping all global data +class GLOBALS +{ +public: + GLOBALS(GLOBALS const&) = delete; + void operator=(GLOBALS const&) = delete; + + static GLOBALS& get() + { + static GLOBALS instance_; + return instance_; + } + + // CLI parameters + struct PARAMS + { + std::string ws_host_ = "0.0.0.0"; //websocket + int ws_port_ = 5565; //websocket + std::string serial_ = "/dev/ttySAC0"; // serial port to arduino + habboy_hw_iface::SerialConnection::Baud baud_ = habboy_hw_iface::SerialConnection::Baud::b9600; + }; + PARAMS par_; + + // state + habboy_hw_iface::GpsState gps_; + + static bool DumpToFile(std::string fName) + { + using namespace std; + try{ + fstream oFile(fName, fstream::out); + oFile<<"port = "< +#include +#include "pystring.h" + +namespace habboy_hw_iface +{ + +std::string GpsState::to_str() const +{ + using namespace std; + + string res; + res += "time=" + to_string(time) + ","; + res += "lat=" + to_string(lat) + ","; + res += "lon=" + to_string(lon) + ","; + res += "alt=" + to_string(alt) + ","; + res += "altmsl=" + to_string(altmsl) + ","; + res += "sats=" + to_string(sats) + ","; + res += "speed=" + to_string(speed) + ","; + res += "heading=" + to_string(heading); + return res; +} + +void GpsState::from_str(std::string str) +{ + using namespace std; + + vector tokens; + pystring::split( str, tokens, "," ); + for(auto t : tokens) + { + vector kv; + pystring::split( t, kv, "=" ); + if(kv.size() == 2) + { + if( kv[0] == "time" ) try { time = stoi(kv[1]); } catch(exception& e) { cout<<"ERR "< + +namespace habboy_hw_iface +{ + +class GpsState +{ +public: + int time = 0; + float lat = 0; + float lon = 0; + float alt = 0; + float altmsl = 0; + int sats = -1; + float speed = 0; + float heading = 0; + + std::string to_str() const; + void from_str(std::string str); +}; + +} //ns \ No newline at end of file diff --git a/hw_iface/code/console_colors.cpp b/hw_iface/code/console_colors.cpp new file mode 100644 index 0000000..405c3ee --- /dev/null +++ b/hw_iface/code/console_colors.cpp @@ -0,0 +1,28 @@ +#ifdef __linux__ + const char* C_BLACK = "\033[1;30m"; + const char* C_RED = "\033[1;31m"; + const char* C_GREEN = "\033[1;32m"; + const char* C_BROWN = "\033[1;33m"; + const char* C_BLUE = "\033[1;34m"; + const char* C_MAGENTA = "\033[1;35m"; + const char* C_CYAN = "\033[1;36m"; + const char* C_LIGHTGREY = "\033[1;37m"; + const char* C_OFF = "\033[0m"; + const char* C_CLEAR = "\033[2K"; +// #elif _WIN32 +// #elif __APPLE__ +// #elif __unix__ // all unices not caught above +// #elif defined(_POSIX_VERSION) +#else + const char* C_BLACK = ""; + const char* C_RED = ""; + const char* C_GREEN = ""; + const char* C_BROWN = ""; + const char* C_BLUE = ""; + const char* C_MAGENTA = ""; + const char* C_CYAN = ""; + const char* C_LIGHTGREY = ""; + const char* C_OFF = ""; + const char* C_CLEAR = ""; + +#endif \ No newline at end of file diff --git a/hw_iface/code/console_colors.h b/hw_iface/code/console_colors.h new file mode 100644 index 0000000..047caa4 --- /dev/null +++ b/hw_iface/code/console_colors.h @@ -0,0 +1,12 @@ +#pragma once + +extern const char* C_BLACK; +extern const char* C_RED; +extern const char* C_GREEN; +extern const char* C_BROWN; +extern const char* C_BLUE; +extern const char* C_MAGENTA; +extern const char* C_CYAN; +extern const char* C_LIGHTGREY; +extern const char* C_OFF; +extern const char* C_CLEAR; \ No newline at end of file diff --git a/hw_iface/code/git_repo_sha1.cpp.in b/hw_iface/code/git_repo_sha1.cpp.in new file mode 100644 index 0000000..a1ac6ea --- /dev/null +++ b/hw_iface/code/git_repo_sha1.cpp.in @@ -0,0 +1,2 @@ +#define GIT_SHA1 "@GIT_SHA1@" +char g_GIT_SHA1[] = GIT_SHA1; \ No newline at end of file diff --git a/hw_iface/code/git_repo_sha1.h b/hw_iface/code/git_repo_sha1.h new file mode 100644 index 0000000..7004b4b --- /dev/null +++ b/hw_iface/code/git_repo_sha1.h @@ -0,0 +1 @@ +extern char g_GIT_SHA1[]; \ No newline at end of file diff --git a/hw_iface/code/hb_serial.cpp b/hw_iface/code/hb_serial.cpp new file mode 100644 index 0000000..d2d8770 --- /dev/null +++ b/hw_iface/code/hb_serial.cpp @@ -0,0 +1,191 @@ +#include + +#include +#include +#include +#include + +// serial +#include +#include +#include +#include +#include +#include + +namespace +{ + +void error_message(const char* err_m, int _errno, ...) +{ + printf(err_m); + // printf("\n"); +} + +int set_interface_attribs(int fd, int speed, int parity) +{ + struct termios tty; + memset(&tty, 0, sizeof tty); + if (tcgetattr(fd, &tty) != 0) + { + error_message("error %d from tcgetattr", errno); + return -1; + } + + cfsetospeed(&tty, speed); + cfsetispeed(&tty, speed); + + tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars + // disable IGNBRK for mismatched speed tests; otherwise receive break + // as \000 chars + tty.c_iflag &= ~IGNBRK; // disable break processing + tty.c_lflag = 0; // no signaling chars, no echo, + // no canonical processing + tty.c_oflag = 0; // no remapping, no delays + tty.c_cc[VMIN] = 0; // read doesn't block + tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout + + tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl + + tty.c_cflag |= (CLOCAL | CREAD); // ignore modem controls, + // enable reading + tty.c_cflag &= ~(PARENB | PARODD); // shut off parity + tty.c_cflag |= parity; + tty.c_cflag &= ~CSTOPB; + tty.c_cflag &= ~CRTSCTS; + + if (tcsetattr(fd, TCSANOW, &tty) != 0) + { + error_message("error %d from tcsetattr", errno); + return -1; + } + return 0; +} + + +void set_blocking(int fd, int should_block) +{ + struct termios tty; + memset(&tty, 0, sizeof tty); + if (tcgetattr(fd, &tty) != 0) + { + error_message("error %d from tggetattr", errno); + return; + } + + tty.c_cc[VMIN] = should_block ? 1 : 0; + tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout + + if (tcsetattr(fd, TCSANOW, &tty) != 0) + error_message("error %d setting term attributes", errno); +} + + +} //ns + + +namespace habboy_hw_iface +{ + +void SerialConnection::add_callback(callback_type cb) +{ + callbacks_.push_back(cb); +} + +void SerialConnection::operator()() +{ + using namespace std; + + int fd = open(port_.c_str(), O_RDWR | O_NOCTTY | O_SYNC); + if (fd < 0) + { + cerr<<("error opening serial port. ", errno, port_, strerror(errno)); + return; + } + + set_interface_attribs(fd, baud_, 0); // set speed to 115,200 bps, 8n1 (no parity) + set_blocking(fd, 0); // set no blocking + + // write(fd, "hello!\n", 7); // send 7 character greeting + + char buf[100]; + string buf_str; + while(keep_running_) + { + // usleep((7 + 25) * 100); // sleep enough to transmit the 7 plus + // receive 25: approx 100 uS per char transmit + + usleep(1 * 100000); // sleep enough to transmit the 7 plus + + int n = read(fd, buf, sizeof buf); // read up to 100 characters if ready to read + string part(buf, n); + buf_str += part; + + auto _end = buf_str.find("\n"); + if(_end != std::string::npos) + { + string msg = buf_str.substr(0, _end); + std::cout<<"SERIAL : "<>(std::istream& in, SerialConnection::Baud& b) +{ + std::string token; + in >> token; + + if (token == "0") b = SerialConnection::Baud::b0; + else if (token == "1") b = SerialConnection::Baud::b50; + else if (token == "2") b = SerialConnection::Baud::b75; + else if (token == "3") b = SerialConnection::Baud::b110; + else if (token == "4") b = SerialConnection::Baud::b134; + else if (token == "5") b = SerialConnection::Baud::b150; + else if (token == "6") b = SerialConnection::Baud::b200; + else if (token == "7") b = SerialConnection::Baud::b300; + else if (token == "8") b = SerialConnection::Baud::b600; + else if (token == "9") b = SerialConnection::Baud::b1200; + else if (token == "10") b = SerialConnection::Baud::b1800; + else if (token == "10") b = SerialConnection::Baud::b2400; + else if (token == "12") b = SerialConnection::Baud::b4800; + else if (token == "13") b = SerialConnection::Baud::b9600; + else if (token == "14") b = SerialConnection::Baud::b19200; + else if (token == "15") b = SerialConnection::Baud::b38400; + else if (token == "16") b = SerialConnection::Baud::b57600; + else if (token == "17") b = SerialConnection::Baud::b115200; + else if (token == "18") b = SerialConnection::Baud::b230400; + return in; +} + +std::ostream& operator<<(std::ostream& os, const SerialConnection::Baud& b) +{ + if (b == SerialConnection::Baud::b0) os<<"B0"; + else if (b == SerialConnection::Baud::b50) os<<"B50"; + else if (b == SerialConnection::Baud::b75) os<<"B75"; + else if (b == SerialConnection::Baud::b110) os<<"B110"; + else if (b == SerialConnection::Baud::b134) os<<"B134"; + else if (b == SerialConnection::Baud::b150) os<<"B150"; + else if (b == SerialConnection::Baud::b200) os<<"B200"; + else if (b == SerialConnection::Baud::b300) os<<"B300"; + else if (b == SerialConnection::Baud::b600) os<<"B600"; + else if (b == SerialConnection::Baud::b1200) os<<"B1200"; + else if (b == SerialConnection::Baud::b1800) os<<"B1800"; + else if (b == SerialConnection::Baud::b2400) os<<"B2400"; + else if (b == SerialConnection::Baud::b4800) os<<"B4800"; + else if (b == SerialConnection::Baud::b9600) os<<"B9600"; + else if (b == SerialConnection::Baud::b19200) os<<"B19200"; + else if (b == SerialConnection::Baud::b38400) os<<"B38400"; + else if (b == SerialConnection::Baud::b57600) os<<"B57600"; + else if (b == SerialConnection::Baud::b115200) os<<"B115200"; + else if (b == SerialConnection::Baud::b230400) os<<"B230400"; + + return os; +} + +} //ns habboy_hw_iface \ No newline at end of file diff --git a/hw_iface/code/hb_serial.h b/hw_iface/code/hb_serial.h new file mode 100644 index 0000000..7be3787 --- /dev/null +++ b/hw_iface/code/hb_serial.h @@ -0,0 +1,64 @@ +#pragma once + +#include +#include +#include + +#include + +namespace habboy_hw_iface +{ + +// void RunSerialConnection( std::function msg_callback); + +class SerialConnection +{ +public: + typedef std::function callback_type; + enum Baud { + b0 = B0, + b50 = B50, + b75 = B75, + b110 = B110, + b134 = B134, + b150 = B150, + b200 = B200, + b300 = B300, + b600 = B600, + b1200 = B1200, + b1800 = B1800, + b2400 = B2400, + b4800 = B4800, + b9600 = B9600, + b19200 = B19200, + b38400 = B38400, + b57600 = B57600, + b115200 = B115200, + b230400 = B230400 + }; + + SerialConnection() = delete; + SerialConnection(const SerialConnection&) = delete; + SerialConnection& operator=(const SerialConnection&) = delete; + + SerialConnection(std::string port, Baud baud) : port_(port), baud_(baud) {}; + + void add_callback(callback_type); + void operator()(); + void Stop() {keep_running_ = false;} + +private: + std::string port_{""}; + // unsigned int baud_{0}; + Baud baud_{Baud::b115200}; + std::vector callbacks_; + bool keep_running_ = true; +}; + + +// needed for boost::program_options +std::istream& operator>>(std::istream& in, SerialConnection::Baud& b); +std::ostream& operator<<(std::ostream& os, const SerialConnection::Baud& b); + + +} \ No newline at end of file diff --git a/hw_iface/code/http_session.cpp b/hw_iface/code/http_session.cpp new file mode 100644 index 0000000..0c1309f --- /dev/null +++ b/hw_iface/code/http_session.cpp @@ -0,0 +1,277 @@ +#include "http_session.h" +#include "websocket_session.h" +#include + +//------------------------------------------------------------------------------ + +// Return a reasonable mime type based on the extension of a file. +/* +boost::beast::string_view +mime_type(boost::beast::string_view path) +{ + using boost::beast::iequals; + auto const ext = [&path] + { + auto const pos = path.rfind("."); + if(pos == boost::beast::string_view::npos) + return boost::beast::string_view{}; + return path.substr(pos); + }(); + if(iequals(ext, ".htm")) return "text/html"; + if(iequals(ext, ".html")) return "text/html"; + if(iequals(ext, ".php")) return "text/html"; + if(iequals(ext, ".css")) return "text/css"; + if(iequals(ext, ".txt")) return "text/plain"; + if(iequals(ext, ".js")) return "application/javascript"; + if(iequals(ext, ".json")) return "application/json"; + if(iequals(ext, ".xml")) return "application/xml"; + if(iequals(ext, ".swf")) return "application/x-shockwave-flash"; + if(iequals(ext, ".flv")) return "video/x-flv"; + if(iequals(ext, ".png")) return "image/png"; + if(iequals(ext, ".jpe")) return "image/jpeg"; + if(iequals(ext, ".jpeg")) return "image/jpeg"; + if(iequals(ext, ".jpg")) return "image/jpeg"; + if(iequals(ext, ".gif")) return "image/gif"; + if(iequals(ext, ".bmp")) return "image/bmp"; + if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon"; + if(iequals(ext, ".tiff")) return "image/tiff"; + if(iequals(ext, ".tif")) return "image/tiff"; + if(iequals(ext, ".svg")) return "image/svg+xml"; + if(iequals(ext, ".svgz")) return "image/svg+xml"; + return "application/text"; +} +*/ + +// Append an HTTP rel-path to a local filesystem path. +// The returned path is normalized for the platform. +/* +std::string +path_cat( + boost::beast::string_view base, + boost::beast::string_view path) +{ + if(base.empty()) + return path.to_string(); + std::string result = base.to_string(); +#if BOOST_MSVC + char constexpr path_separator = '\\'; + if(result.back() == path_separator) + result.resize(result.size() - 1); + result.append(path.data(), path.size()); + for(auto& c : result) + if(c == '/') + c = path_separator; +#else + char constexpr path_separator = '/'; + if(result.back() == path_separator) + result.resize(result.size() - 1); + result.append(path.data(), path.size()); +#endif + return result; +} +*/ + +// This function produces an HTTP response for the given +// request. The type of the response object depends on the +// contents of the request, so the interface requires the +// caller to pass a generic lambda for receiving the response. +/* +template< + class Body, class Allocator, + class Send> +void +handle_request( + boost::beast::string_view doc_root, + http::request>&& req, + Send&& send) +{ + // Returns a bad request response + auto const bad_request = + [&req](boost::beast::string_view why) + { + http::response res{http::status::bad_request, req.version()}; + res.set(http::field::server, BOOST_BEAST_VERSION_STRING); + res.set(http::field::content_type, "text/html"); + res.keep_alive(req.keep_alive()); + res.body() = why.to_string(); + res.prepare_payload(); + return res; + }; + + // Returns a not found response + auto const not_found = + [&req](boost::beast::string_view target) + { + http::response res{http::status::not_found, req.version()}; + res.set(http::field::server, BOOST_BEAST_VERSION_STRING); + res.set(http::field::content_type, "text/html"); + res.keep_alive(req.keep_alive()); + res.body() = "The resource '" + target.to_string() + "' was not found."; + res.prepare_payload(); + return res; + }; + + // Returns a server error response + auto const server_error = + [&req](boost::beast::string_view what) + { + http::response res{http::status::internal_server_error, req.version()}; + res.set(http::field::server, BOOST_BEAST_VERSION_STRING); + res.set(http::field::content_type, "text/html"); + res.keep_alive(req.keep_alive()); + res.body() = "An error occurred: '" + what.to_string() + "'"; + res.prepare_payload(); + return res; + }; + + // Make sure we can handle the method + if( req.method() != http::verb::get && + req.method() != http::verb::head) + return send(bad_request("Unknown HTTP-method")); + + // Request path must be absolute and not contain "..". + if( req.target().empty() || + req.target()[0] != '/' || + req.target().find("..") != boost::beast::string_view::npos) + return send(bad_request("Illegal request-target")); + + // Build the path to the requested file + std::string path = path_cat(doc_root, req.target()); + if(req.target().back() == '/') + path.append("index.html"); + + // Attempt to open the file + boost::beast::error_code ec; + http::file_body::value_type body; + body.open(path.c_str(), boost::beast::file_mode::scan, ec); + + // Handle the case where the file doesn't exist + if(ec == boost::system::errc::no_such_file_or_directory) + return send(not_found(req.target())); + + // Handle an unknown error + if(ec) + return send(server_error(ec.message())); + + // Cache the size since we need it after the move + auto const size = body.size(); + + // Respond to HEAD request + if(req.method() == http::verb::head) + { + http::response res{http::status::ok, req.version()}; + res.set(http::field::server, BOOST_BEAST_VERSION_STRING); + res.set(http::field::content_type, mime_type(path)); + res.content_length(size); + res.keep_alive(req.keep_alive()); + return send(std::move(res)); + } + + // Respond to GET request + http::response res{ + std::piecewise_construct, + std::make_tuple(std::move(body)), + std::make_tuple(http::status::ok, req.version())}; + res.set(http::field::server, BOOST_BEAST_VERSION_STRING); + res.set(http::field::content_type, mime_type(path)); + res.content_length(size); + res.keep_alive(req.keep_alive()); + return send(std::move(res)); +} +*/ +//------------------------------------------------------------------------------ + +namespace habboy_hw_iface +{ + +http_session::http_session( + tcp::socket socket, + std::shared_ptr p_ws_server) + : socket_(std::move(socket)), + p_ws_server_(p_ws_server) +{ +} + +void http_session::run() +{ + boost::beast::http::async_read(socket_, buffer_, req_, + [self = shared_from_this()] + (error_code ec, std::size_t bytes) + { + self->on_read(ec, bytes); + }); +} + +void http_session::fail(error_code ec, char const* what) +{ + if(ec == net::error::operation_aborted) + return; + std::cerr << what << ": " << ec.message() << "\n"; +} + +void http_session::on_read(error_code ec, std::size_t) +{ + if(ec == boost::beast::http::error::end_of_stream) + { + socket_.shutdown(tcp::socket::shutdown_send, ec); + return; + } + + if(ec) + return fail(ec, "read"); + + if(boost::beast::websocket::is_upgrade(req_)) + { + std::make_shared( + std::move(socket_), p_ws_server_ + )->run(std::move(req_)); + return; + } + + // Send the response + /* + handle_request(state_->doc_root(), std::move(req_), + [this](auto&& response) + { + // The lifetime of the message has to extend + // for the duration of the async operation so + // we use a shared_ptr to manage it. + using response_type = typename std::decay::type; + auto sp = std::make_shared(std::forward(response)); + + // Write the response + auto self = shared_from_this(); + http::async_write(this->socket_, *sp, + [self, sp]( + error_code ec, std::size_t bytes) + { + self->on_write(ec, bytes, sp->need_eof()); + }); + }); + */ +} + +void http_session::on_write(error_code ec, std::size_t, bool close) +{ + if(ec) + return fail(ec, "write"); + + if(close) + { + socket_.shutdown(tcp::socket::shutdown_send, ec); + return; + } + + // Clear contents of the request message, + // otherwise the read behavior is undefined. + req_ = {}; + + boost::beast::http::async_read(socket_, buffer_, req_, + [self = shared_from_this()] + (error_code ec, std::size_t bytes) + { + self->on_read(ec, bytes); + }); +} + +} //ns \ No newline at end of file diff --git a/hw_iface/code/http_session.h b/hw_iface/code/http_session.h new file mode 100644 index 0000000..d596716 --- /dev/null +++ b/hw_iface/code/http_session.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +#include +#include + +#include "ws_server.h" + +namespace net = boost::asio; // namespace asio +using tcp = net::ip::tcp; // from +using error_code = boost::system::error_code; // from + + +namespace habboy_hw_iface +{ + +class http_session : public std::enable_shared_from_this +{ + tcp::socket socket_; + boost::beast::flat_buffer buffer_; + boost::beast::http::request req_; + std::shared_ptr p_ws_server_; + + void fail(error_code ec, char const* what); + void on_read(error_code ec, std::size_t); + void on_write(error_code ec, std::size_t, bool close); + +public: + http_session(tcp::socket socket, std::shared_ptr p_ws_server); + void run(); +}; + +} //ns \ No newline at end of file diff --git a/hw_iface/code/listener.cpp b/hw_iface/code/listener.cpp new file mode 100644 index 0000000..a943c4f --- /dev/null +++ b/hw_iface/code/listener.cpp @@ -0,0 +1,80 @@ +#include "listener.h" +#include "http_session.h" +#include + +namespace habboy_hw_iface +{ + +listener::listener(net::io_context& ioc, tcp::endpoint endpoint, habboy_hw_iface::WebsocketServer& ws_server) + : acceptor_(ioc) , socket_(ioc), p_ws_server_(&ws_server) + +{ + error_code ec; + + acceptor_.open(endpoint.protocol(), ec); + if(ec) + { + fail(ec, "open"); + return; + } + + acceptor_.set_option(net::socket_base::reuse_address(true)); + if(ec) + { + fail(ec, "set_option"); + return; + } + + acceptor_.bind(endpoint, ec); + if(ec) + { + fail(ec, "bind"); + return; + } + + acceptor_.listen( + net::socket_base::max_listen_connections, ec); + if(ec) + { + fail(ec, "listen"); + return; + } +} + +void listener::run() +{ + acceptor_.async_accept( + socket_, + [self = shared_from_this()](error_code ec) + { + self->on_accept(ec); + }); +} + +// Report a failure +void listener::fail(error_code ec, char const* what) +{ + if(ec == net::error::operation_aborted) + return; + std::cerr << what << ": " << ec.message() << "\n"; +} + +void listener::on_accept(error_code ec) +{ + if(ec) + return fail(ec, "accept"); + else + std::make_shared( + std::move(socket_), p_ws_server_ + )->run(); // moved-from socket is still valid + + // Accept another connection + acceptor_.async_accept( + socket_, + [self = shared_from_this()](error_code ec) + { + self->on_accept(ec); + }); +} + +} //ns \ No newline at end of file diff --git a/hw_iface/code/listener.h b/hw_iface/code/listener.h new file mode 100644 index 0000000..b22b136 --- /dev/null +++ b/hw_iface/code/listener.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +#include + +#include "ws_server.h" + +namespace net = boost::asio; // namespace asio +using tcp = net::ip::tcp; // from +using error_code = boost::system::error_code; // from + +namespace habboy_hw_iface +{ + +class listener : public std::enable_shared_from_this +{ + tcp::acceptor acceptor_; + tcp::socket socket_; + std::shared_ptr p_ws_server_; + + void fail(error_code ec, char const* what); + void on_accept(error_code ec); + +public: + listener(net::io_context& ioc, tcp::endpoint endpoint, habboy_hw_iface::WebsocketServer& ws_server); + void run(); +}; + +} //ns \ No newline at end of file diff --git a/hw_iface/code/main.cpp b/hw_iface/code/main.cpp new file mode 100644 index 0000000..18e5d65 --- /dev/null +++ b/hw_iface/code/main.cpp @@ -0,0 +1,105 @@ + + +#include +#include +#include +#include + + +#include "program_options.h" +#include "console_colors.h" +#include "GLOBALS.h" +#include "git_repo_sha1.h" +#include "ws_server.h" +#include "hb_serial.h" +#include "msg_broker.h" +#include "GpsState.h" + + +bool G_KEEP_RUNNING; + + +int MAIN(int argc, char** argv) +{ + using namespace std; + using namespace habboy_hw_iface; + + cout<<"git version: "< threads; + + + // websocket server + WebsocketServer ws_server(GLOBALS::get().par_.ws_host_, GLOBALS::get().par_.ws_port_); + threads.emplace( new thread( + [&ws_server]() { ws_server(); } + ) ); + + + // message broker + MessageBroker msg_broker(ws_server); + threads.emplace( new thread( + [&msg_broker]() { msg_broker(); } + ) ); + + + // serial connection -- use 'msg_broker.push()' as callback + SerialConnection srl( GLOBALS::get().par_.serial_, GLOBALS::get().par_.baud_ ); + srl.add_callback( + [&msg_broker](const std::string& msg) { msg_broker.push(msg); } + ); + threads.emplace( new thread( + [&srl]() { srl(); } + ) ); + + + // print some info + /* + threads.emplace( new thread( + []() + { + while(G_KEEP_RUNNING) + { + this_thread::sleep_for(std::chrono::milliseconds(1000)); + cout<join(); + + return 0; +} + + +int main(int argc, char** argv) +{ + return MAIN(argc,argv); +} \ No newline at end of file diff --git a/hw_iface/code/msg_broker.cpp b/hw_iface/code/msg_broker.cpp new file mode 100644 index 0000000..b130412 --- /dev/null +++ b/hw_iface/code/msg_broker.cpp @@ -0,0 +1,126 @@ +#include + +#include +#include +#include +#include + +#include "GLOBALS.h" + +namespace habboy_hw_iface +{ + + +MessageBroker::MessageBroker(habboy_hw_iface::WebsocketServer& ws_server) +{ + p_ws_server_.reset(&ws_server); +} + + +void MessageBroker::push(std::string msg) +{ + using Ms = std::chrono::milliseconds; + + /* + if( msg_que_mtx_.try_lock_for(Ms(100)) ) + { + std::lock_guard _lock(msg_que_mtx_); + msg_que_.push(msg); + msg_que_mtx_.unlock(); + } + else + { + std::cout<<"push timed out: "< _lock(msg_que_mtx_); + msg_que_.push(msg); + } + msg_que_cv_.notify_one(); +} + + +void MessageBroker::operator()() +{ + while(keep_running_) + { + using namespace std; + using Ms = std::chrono::milliseconds; + + // this_thread::sleep_for(std::chrono::milliseconds(100)); + + queue msgs; + + /* + if( msg_que_mtx_.try_lock_for(Ms(1000)) ) + { + msg_que_cv_.wait( msg_que_mtx_ ); + msgs = std::move(msg_que_); + msg_que_mtx_.unlock(); + } + else + { + std::cout<<"consume timed out."< lock_(msg_que_mtx_); + msg_que_cv_.wait(lock_); + + msgs = std::move(msg_que_); + + lock_.unlock(); + msg_que_cv_.notify_one(); + } + + while(msgs.size()) + { + bool handled = handle_msg( msgs.front() ); + msgs.pop(); + } + } +} + + +bool MessageBroker::handle_msg(const std::string msg) +{ + using namespace std; + + // p_ws_server_->sessions_send(msg); + + + auto type_split = msg.find("::"); + if(type_split == string::npos) + return false; + + string m_type = msg.substr(0, type_split); + string m_body = msg.substr(type_split+2); + + if(m_type == "gps") + { + GpsState _gps = GLOBALS::get().gps_; + _gps.from_str(m_body); + _gps.alt /= 1000; + _gps.altmsl /= 1000; + _gps.heading /= 1000; + GLOBALS::get().gps_ = _gps; + p_ws_server_->sessions_send( "gps::" + _gps.to_str() ); + } + else + { + // unknown -- just send + p_ws_server_->sessions_send( msg ); + } + + + return true; + +} + + +} //ns \ No newline at end of file diff --git a/hw_iface/code/msg_broker.h b/hw_iface/code/msg_broker.h new file mode 100644 index 0000000..864b941 --- /dev/null +++ b/hw_iface/code/msg_broker.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "ws_server.h" +#include "GpsState.h" + +namespace habboy_hw_iface +{ + +class MessageBroker +{ +public: + MessageBroker() = delete; + MessageBroker(const MessageBroker&) = delete; + MessageBroker& operator=(const MessageBroker&) = delete; + + MessageBroker(habboy_hw_iface::WebsocketServer& ws_server); + + void push(std::string msg); + void operator()(); + void Stop() { keep_running_=false; } + +private: + std::queue msg_que_; + // std::timed_mutex msg_que_mtx_; + std::mutex msg_que_mtx_; + std::condition_variable msg_que_cv_; + + bool keep_running_ = true; + + std::shared_ptr p_ws_server_; + + bool handle_msg(const std::string msg); +}; + +} //ns \ No newline at end of file diff --git a/hw_iface/code/program_options.cpp b/hw_iface/code/program_options.cpp new file mode 100644 index 0000000..17a588f --- /dev/null +++ b/hw_iface/code/program_options.cpp @@ -0,0 +1,117 @@ + +#include +#include +#include +#include + +#include + +#include "console_colors.h" +#include "GLOBALS.h" +#include "hb_serial.h" + +void prog_opts(int ac, char* av[]) +{ + namespace po = boost::program_options; + using namespace std; + using namespace habboy_hw_iface; + + try + { + po::options_description generic("CLI opts"); + generic.add_options() + ("help", "Display help message") + ("wsport", po::value(), "websocket Port, example: --wsport 127.0.0.1:5565") + ("serial", po::value(), "arduino serial port. defaults to /dev/ttyUSB0") + ("baud", po::value(), "Serial Baud speed - defaults to 115200") + ; + + po::options_description cli_options("Command Line Interface options"); + cli_options.add(generic); + + string config_file; + cli_options.add_options() + ("config", po::value(&config_file), "Config file."); + + po::options_description file_options; + file_options.add(generic); + + po::variables_map vm; + store( po::command_line_parser(ac, av).options(cli_options).allow_unregistered().run(), vm ); + notify(vm); + + if(vm.count("help")) + { + cout<(), match, std::regex(R"_(([\w\.]*)(\:?)(\d*))_") ); + + if(match.size() == 4) + { + if(match[2] == "" && match[3] == "") // special case when only port is given: --port 5565 + { + GLOBALS::get().par_.ws_port_ = stoi(match[1]); + } + else + { + if(match[1] != "") GLOBALS::get().par_.ws_host_ = match[1]; + if(match[3] != "") GLOBALS::get().par_.ws_port_ = stoi(match[3]); + } + } + } + if (vm.count("serial")) + { + GLOBALS::get().par_.serial_ = vm["serial"].as(); + } + if (vm.count("baud")) + { + std::string b = vm["baud"].as(); + + if(b == "0") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b0; + if(b == "50") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b50; + if(b == "75") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b75; + if(b == "110") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b110; + if(b == "134") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b134; + if(b == "150") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b150; + if(b == "200") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b200; + if(b == "300") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b300; + if(b == "600") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b600; + if(b == "1200") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b1200; + if(b == "1800") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b1800; + if(b == "2400") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b2400; + if(b == "4800") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b4800; + if(b == "9600") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b9600; + if(b == "19200") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b19200; + if(b == "38400") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b38400; + if(b == "57600") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b57600; + if(b == "115200") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b115200; + if(b == "230400") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b230400; + } + } + catch(exception& e) + { + cout << e.what() << "\n"; + } + + GLOBALS::DumpToFile("./habboy_hw_iface.opts"); +} \ No newline at end of file diff --git a/hw_iface/code/program_options.h b/hw_iface/code/program_options.h new file mode 100644 index 0000000..d91ce1d --- /dev/null +++ b/hw_iface/code/program_options.h @@ -0,0 +1,3 @@ + +#pragma once +void prog_opts(int ac, char* av[]); diff --git a/hw_iface/code/pystring.cpp b/hw_iface/code/pystring.cpp new file mode 100644 index 0000000..ec30d8b --- /dev/null +++ b/hw_iface/code/pystring.cpp @@ -0,0 +1,1666 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2008-2010, Sony Pictures Imageworks Inc +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// Neither the name of the organization Sony Pictures Imageworks nor the +// names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS +// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER +// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/////////////////////////////////////////////////////////////////////////////// + +#include "pystring.h" + +#include +#include +#include +#include +#include + +namespace pystring +{ + +#if defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS) || defined(_MSC_VER) +#ifndef WINDOWS +#define WINDOWS +#endif +#endif + +// This definition codes from configure.in in the python src. +// Strictly speaking this limits us to str sizes of 2**31. +// Should we wish to handle this limit, we could use an architecture +// specific #defines and read from ssize_t (unistd.h) if the header exists. +// But in the meantime, the use of int assures maximum arch compatibility. +// This must also equal the size used in the end = MAX_32BIT_INT default arg. + +typedef int Py_ssize_t; + +/* helper macro to fixup start/end slice values */ +#define ADJUST_INDICES(start, end, len) \ + if (end > len) \ + end = len; \ + else if (end < 0) { \ + end += len; \ + if (end < 0) \ + end = 0; \ + } \ + if (start < 0) { \ + start += len; \ + if (start < 0) \ + start = 0; \ + } + + + namespace { + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// why doesn't the std::reverse work? + /// + void reverse_strings( std::vector< std::string > & result) + { + for (std::vector< std::string >::size_type i = 0; i < result.size() / 2; i++ ) + { + std::swap(result[i], result[result.size() - 1 - i]); + } + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + void split_whitespace( const std::string & str, std::vector< std::string > & result, int maxsplit ) + { + std::string::size_type i, j, len = str.size(); + for (i = j = 0; i < len; ) + { + + while ( i < len && ::isspace( str[i] ) ) i++; + j = i; + + while ( i < len && ! ::isspace( str[i]) ) i++; + + + + if (j < i) + { + if ( maxsplit-- <= 0 ) break; + + result.push_back( str.substr( j, i - j )); + + while ( i < len && ::isspace( str[i])) i++; + j = i; + } + } + if (j < len) + { + result.push_back( str.substr( j, len - j )); + } + } + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + void rsplit_whitespace( const std::string & str, std::vector< std::string > & result, int maxsplit ) + { + std::string::size_type len = str.size(); + std::string::size_type i, j; + for (i = j = len; i > 0; ) + { + + while ( i > 0 && ::isspace( str[i - 1] ) ) i--; + j = i; + + while ( i > 0 && ! ::isspace( str[i - 1]) ) i--; + + + + if (j > i) + { + if ( maxsplit-- <= 0 ) break; + + result.push_back( str.substr( i, j - i )); + + while ( i > 0 && ::isspace( str[i - 1])) i--; + j = i; + } + } + if (j > 0) + { + result.push_back( str.substr( 0, j )); + } + //std::reverse( result, result.begin(), result.end() ); + reverse_strings( result ); + } + + } //anonymous namespace + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + void split( const std::string & str, std::vector< std::string > & result, const std::string & sep, int maxsplit ) + { + result.clear(); + + if ( maxsplit < 0 ) maxsplit = MAX_32BIT_INT;//result.max_size(); + + + if ( sep.size() == 0 ) + { + split_whitespace( str, result, maxsplit ); + return; + } + + std::string::size_type i,j, len = str.size(), n = sep.size(); + + i = j = 0; + + while ( i+n <= len ) + { + if ( str[i] == sep[0] && str.substr( i, n ) == sep ) + { + if ( maxsplit-- <= 0 ) break; + + result.push_back( str.substr( j, i - j ) ); + i = j = i + n; + } + else + { + i++; + } + } + + result.push_back( str.substr( j, len-j ) ); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + void rsplit( const std::string & str, std::vector< std::string > & result, const std::string & sep, int maxsplit ) + { + if ( maxsplit < 0 ) + { + split( str, result, sep, maxsplit ); + return; + } + + result.clear(); + + if ( sep.size() == 0 ) + { + rsplit_whitespace( str, result, maxsplit ); + return; + } + + Py_ssize_t i,j, len = (Py_ssize_t) str.size(), n = (Py_ssize_t) sep.size(); + + i = j = len; + + while ( i >= n ) + { + if ( str[i - 1] == sep[n - 1] && str.substr( i - n, n ) == sep ) + { + if ( maxsplit-- <= 0 ) break; + + result.push_back( str.substr( i, j - i ) ); + i = j = i - n; + } + else + { + i--; + } + } + + result.push_back( str.substr( 0, j ) ); + reverse_strings( result ); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + #define LEFTSTRIP 0 + #define RIGHTSTRIP 1 + #define BOTHSTRIP 2 + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string do_strip( const std::string & str, int striptype, const std::string & chars ) + { + Py_ssize_t len = (Py_ssize_t) str.size(), i, j, charslen = (Py_ssize_t) chars.size(); + + if ( charslen == 0 ) + { + i = 0; + if ( striptype != RIGHTSTRIP ) + { + while ( i < len && ::isspace( str[i] ) ) + { + i++; + } + } + + j = len; + if ( striptype != LEFTSTRIP ) + { + do + { + j--; + } + while (j >= i && ::isspace(str[j])); + + j++; + } + + + } + else + { + const char * sep = chars.c_str(); + + i = 0; + if ( striptype != RIGHTSTRIP ) + { + while ( i < len && memchr(sep, str[i], charslen) ) + { + i++; + } + } + + j = len; + if (striptype != LEFTSTRIP) + { + do + { + j--; + } + while (j >= i && memchr(sep, str[j], charslen) ); + j++; + } + + + } + + if ( i == 0 && j == len ) + { + return str; + } + else + { + return str.substr( i, j - i ); + } + + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + void partition( const std::string & str, const std::string & sep, std::vector< std::string > & result ) + { + result.resize(3); + int index = find( str, sep ); + if ( index < 0 ) + { + result[0] = str; + result[1] = ""; + result[2] = ""; + } + else + { + result[0] = str.substr( 0, index ); + result[1] = sep; + result[2] = str.substr( index + sep.size(), str.size() ); + } + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + void rpartition( const std::string & str, const std::string & sep, std::vector< std::string > & result ) + { + result.resize(3); + int index = rfind( str, sep ); + if ( index < 0 ) + { + result[0] = ""; + result[1] = ""; + result[2] = str; + } + else + { + result[0] = str.substr( 0, index ); + result[1] = sep; + result[2] = str.substr( index + sep.size(), str.size() ); + } + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string strip( const std::string & str, const std::string & chars ) + { + return do_strip( str, BOTHSTRIP, chars ); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string lstrip( const std::string & str, const std::string & chars ) + { + return do_strip( str, LEFTSTRIP, chars ); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string rstrip( const std::string & str, const std::string & chars ) + { + return do_strip( str, RIGHTSTRIP, chars ); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string join( const std::string & str, const std::vector< std::string > & seq ) + { + std::vector< std::string >::size_type seqlen = seq.size(), i; + + if ( seqlen == 0 ) return ""; + if ( seqlen == 1 ) return seq[0]; + + std::string result( seq[0] ); + + for ( i = 1; i < seqlen; ++i ) + { + result += str + seq[i]; + + } + + + return result; + } + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + + namespace + { + /* Matches the end (direction >= 0) or start (direction < 0) of self + * against substr, using the start and end arguments. Returns + * -1 on error, 0 if not found and 1 if found. + */ + + int _string_tailmatch(const std::string & self, const std::string & substr, + Py_ssize_t start, Py_ssize_t end, + int direction) + { + Py_ssize_t len = (Py_ssize_t) self.size(); + Py_ssize_t slen = (Py_ssize_t) substr.size(); + + const char* sub = substr.c_str(); + const char* str = self.c_str(); + + ADJUST_INDICES(start, end, len); + + if (direction < 0) { + // startswith + if (start+slen > len) + return 0; + } else { + // endswith + if (end-start < slen || start > len) + return 0; + if (end-slen > start) + start = end - slen; + } + if (end-start >= slen) + return (!std::memcmp(str+start, sub, slen)); + + return 0; + } + } + + bool endswith( const std::string & str, const std::string & suffix, int start, int end ) + { + int result = _string_tailmatch(str, suffix, + (Py_ssize_t) start, (Py_ssize_t) end, +1); + //if (result == -1) // TODO: Error condition + + return static_cast(result); + } + + + bool startswith( const std::string & str, const std::string & prefix, int start, int end ) + { + int result = _string_tailmatch(str, prefix, + (Py_ssize_t) start, (Py_ssize_t) end, -1); + //if (result == -1) // TODO: Error condition + + return static_cast(result); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + + bool isalnum( const std::string & str ) + { + std::string::size_type len = str.size(), i; + if ( len == 0 ) return false; + + + if( len == 1 ) + { + return ::isalnum( str[0] ); + } + + for ( i = 0; i < len; ++i ) + { + if ( !::isalnum( str[i] ) ) return false; + } + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + bool isalpha( const std::string & str ) + { + std::string::size_type len = str.size(), i; + if ( len == 0 ) return false; + if( len == 1 ) return ::isalpha( (int) str[0] ); + + for ( i = 0; i < len; ++i ) + { + if ( !::isalpha( (int) str[i] ) ) return false; + } + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + bool isdigit( const std::string & str ) + { + std::string::size_type len = str.size(), i; + if ( len == 0 ) return false; + if( len == 1 ) return ::isdigit( str[0] ); + + for ( i = 0; i < len; ++i ) + { + if ( ! ::isdigit( str[i] ) ) return false; + } + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + bool islower( const std::string & str ) + { + std::string::size_type len = str.size(), i; + if ( len == 0 ) return false; + if( len == 1 ) return ::islower( str[0] ); + + for ( i = 0; i < len; ++i ) + { + if ( !::islower( str[i] ) ) return false; + } + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + bool isspace( const std::string & str ) + { + std::string::size_type len = str.size(), i; + if ( len == 0 ) return false; + if( len == 1 ) return ::isspace( str[0] ); + + for ( i = 0; i < len; ++i ) + { + if ( !::isspace( str[i] ) ) return false; + } + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + bool istitle( const std::string & str ) + { + std::string::size_type len = str.size(), i; + + if ( len == 0 ) return false; + if ( len == 1 ) return ::isupper( str[0] ); + + bool cased = false, previous_is_cased = false; + + for ( i = 0; i < len; ++i ) + { + if ( ::isupper( str[i] ) ) + { + if ( previous_is_cased ) + { + return false; + } + + previous_is_cased = true; + cased = true; + } + else if ( ::islower( str[i] ) ) + { + if (!previous_is_cased) + { + return false; + } + + previous_is_cased = true; + cased = true; + + } + else + { + previous_is_cased = false; + } + } + + return cased; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + bool isupper( const std::string & str ) + { + std::string::size_type len = str.size(), i; + if ( len == 0 ) return false; + if( len == 1 ) return ::isupper( str[0] ); + + for ( i = 0; i < len; ++i ) + { + if ( !::isupper( str[i] ) ) return false; + } + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string capitalize( const std::string & str ) + { + std::string s( str ); + std::string::size_type len = s.size(), i; + + if ( len > 0) + { + if (::islower(s[0])) s[0] = (char) ::toupper( s[0] ); + } + + for ( i = 1; i < len; ++i ) + { + if (::isupper(s[i])) s[i] = (char) ::tolower( s[i] ); + } + + return s; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string lower( const std::string & str ) + { + std::string s( str ); + std::string::size_type len = s.size(), i; + + for ( i = 0; i < len; ++i ) + { + if ( ::isupper( s[i] ) ) s[i] = (char) ::tolower( s[i] ); + } + + return s; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string upper( const std::string & str ) + { + std::string s( str ) ; + std::string::size_type len = s.size(), i; + + for ( i = 0; i < len; ++i ) + { + if ( ::islower( s[i] ) ) s[i] = (char) ::toupper( s[i] ); + } + + return s; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string swapcase( const std::string & str ) + { + std::string s( str ); + std::string::size_type len = s.size(), i; + + for ( i = 0; i < len; ++i ) + { + if ( ::islower( s[i] ) ) s[i] = (char) ::toupper( s[i] ); + else if (::isupper( s[i] ) ) s[i] = (char) ::tolower( s[i] ); + } + + return s; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string title( const std::string & str ) + { + std::string s( str ); + std::string::size_type len = s.size(), i; + bool previous_is_cased = false; + + for ( i = 0; i < len; ++i ) + { + int c = s[i]; + if ( ::islower(c) ) + { + if ( !previous_is_cased ) + { + s[i] = (char) ::toupper(c); + } + previous_is_cased = true; + } + else if ( ::isupper(c) ) + { + if ( previous_is_cased ) + { + s[i] = (char) ::tolower(c); + } + previous_is_cased = true; + } + else + { + previous_is_cased = false; + } + } + + return s; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string translate( const std::string & str, const std::string & table, const std::string & deletechars ) + { + std::string s; + std::string::size_type len = str.size(), dellen = deletechars.size(); + + if ( table.size() != 256 ) + { + // TODO : raise exception instead + return str; + } + + //if nothing is deleted, use faster code + if ( dellen == 0 ) + { + s = str; + for ( std::string::size_type i = 0; i < len; ++i ) + { + s[i] = table[ s[i] ]; + } + return s; + } + + + int trans_table[256]; + for ( int i = 0; i < 256; i++) + { + trans_table[i] = table[i]; + } + + for ( std::string::size_type i = 0; i < dellen; i++) + { + trans_table[(int) deletechars[i] ] = -1; + } + + for ( std::string::size_type i = 0; i < len; ++i ) + { + if ( trans_table[ (int) str[i] ] != -1 ) + { + s += table[ str[i] ]; + } + } + + return s; + + } + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string zfill( const std::string & str, int width ) + { + int len = (int)str.size(); + + if ( len >= width ) + { + return str; + } + + std::string s( str ); + + int fill = width - len; + + s = std::string( fill, '0' ) + s; + + + if ( s[fill] == '+' || s[fill] == '-' ) + { + s[0] = s[fill]; + s[fill] = '0'; + } + + return s; + + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string ljust( const std::string & str, int width ) + { + std::string::size_type len = str.size(); + if ( (( int ) len ) >= width ) return str; + return str + std::string( width - len, ' ' ); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string rjust( const std::string & str, int width ) + { + std::string::size_type len = str.size(); + if ( (( int ) len ) >= width ) return str; + return std::string( width - len, ' ' ) + str; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string center( const std::string & str, int width ) + { + int len = (int) str.size(); + int marg, left; + + if ( len >= width ) return str; + + marg = width - len; + left = marg / 2 + (marg & width & 1); + + return std::string( left, ' ' ) + str + std::string( marg - left, ' ' ); + + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string slice( const std::string & str, int start, int end ) + { + ADJUST_INDICES(start, end, (int) str.size()); + if ( start >= end ) return ""; + return str.substr( start, end - start ); + } + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + int find( const std::string & str, const std::string & sub, int start, int end ) + { + ADJUST_INDICES(start, end, (int) str.size()); + + std::string::size_type result = str.find( sub, start ); + + // If we cannot find the string, or if the end-point of our found substring is past + // the allowed end limit, return that it can't be found. + if( result == std::string::npos || + (result + sub.size() > (std::string::size_type)end) ) + { + return -1; + } + + return (int) result; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + int index( const std::string & str, const std::string & sub, int start, int end ) + { + return find( str, sub, start, end ); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + int rfind( const std::string & str, const std::string & sub, int start, int end ) + { + ADJUST_INDICES(start, end, (int) str.size()); + + std::string::size_type result = str.rfind( sub, end ); + + if( result == std::string::npos || + result < (std::string::size_type)start || + (result + sub.size() > (std::string::size_type)end)) + return -1; + + return (int)result; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + int rindex( const std::string & str, const std::string & sub, int start, int end ) + { + return rfind( str, sub, start, end ); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string expandtabs( const std::string & str, int tabsize ) + { + std::string s( str ); + + std::string::size_type len = str.size(), i = 0; + int offset = 0; + + int j = 0; + + for ( i = 0; i < len; ++i ) + { + if ( str[i] == '\t' ) + { + + if ( tabsize > 0 ) + { + int fillsize = tabsize - (j % tabsize); + j += fillsize; + s.replace( i + offset, 1, std::string( fillsize, ' ' )); + offset += fillsize - 1; + } + else + { + s.replace( i + offset, 1, "" ); + offset -= 1; + } + + } + else + { + j++; + + if (str[i] == '\n' || str[i] == '\r') + { + j = 0; + } + } + } + + return s; + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + int count( const std::string & str, const std::string & substr, int start, int end ) + { + int nummatches = 0; + int cursor = start; + + while ( 1 ) + { + cursor = find( str, substr, cursor, end ); + + if ( cursor < 0 ) break; + + cursor += (int) substr.size(); + nummatches += 1; + } + + return nummatches; + + + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + + std::string replace( const std::string & str, const std::string & oldstr, const std::string & newstr, int count ) + { + int sofar = 0; + int cursor = 0; + std::string s( str ); + + std::string::size_type oldlen = oldstr.size(), newlen = newstr.size(); + + cursor = find( s, oldstr, cursor ); + + while ( cursor != -1 && cursor <= (int)s.size() ) + { + if ( count > -1 && sofar >= count ) + { + break; + } + + s.replace( cursor, oldlen, newstr ); + cursor += (int) newlen; + + if ( oldlen != 0) + { + cursor = find( s, oldstr, cursor ); + } + else + { + ++cursor; + } + + ++sofar; + } + + return s; + + } + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + void splitlines( const std::string & str, std::vector< std::string > & result, bool keepends ) + { + result.clear(); + std::string::size_type len = str.size(), i, j, eol; + + for (i = j = 0; i < len; ) + { + while (i < len && str[i] != '\n' && str[i] != '\r') i++; + + eol = i; + if (i < len) + { + if (str[i] == '\r' && i + 1 < len && str[i+1] == '\n') + { + i += 2; + } + else + { + i++; + } + if (keepends) + eol = i; + + } + + result.push_back( str.substr( j, eol - j ) ); + j = i; + + } + + if (j < len) + { + result.push_back( str.substr( j, len - j ) ); + } + + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + std::string mul( const std::string & str, int n ) + { + // Early exits + if (n <= 0) return ""; + if (n == 1) return str; + + std::ostringstream os; + for(int i=0; i & paths) + { + if(paths.empty()) return ""; + if(paths.size() == 1) return paths[0]; + + std::string path = paths[0]; + + for(unsigned int i=1; i3) || + ((path.size()==3) && !pystring::endswith(path, "/") && !pystring::endswith(path, "\\"))) + { + b_nts = true; + } + } + + if(b_nts) + { + path = b; + } + else + { + // Join, and ensure there's a separator. + // assert len(path) > 0 + if( pystring::endswith(path, "/") || pystring::endswith(path, "\\")) + { + if(pystring::startswith(b,"/") || pystring::startswith(b,"\\")) + { + path += pystring::slice(b, 1); + } + else + { + path += b; + } + } + else if(pystring::endswith(path, ":")) + { + path += b; + } + else if(!b.empty()) + { + if(pystring::startswith(b,"/") || pystring::startswith(b,"\\")) + { + path += b; + } + else + { + path += "\\" + b; + } + } + else + { + // path is not empty and does not end with a backslash, + // but b is empty; since, e.g., split('a/') produces + // ('a', ''), it's best if join() adds a backslash in + // this case. + path += "\\"; + } + } + } + + return path; + } + + // Join two or more pathname components, inserting "\\" as needed. + std::string join_nt(const std::string & a, const std::string & b) + { + std::vector< std::string > paths(2); + paths[0] = a; + paths[1] = b; + return join_nt(paths); + } + + // Join pathnames. + // If any component is an absolute path, all previous path components + // will be discarded. + // Ignore the previous parts if a part is absolute. + // Insert a '/' unless the first part is empty or already ends in '/'. + + std::string join_posix(const std::vector< std::string > & paths) + { + if(paths.empty()) return ""; + if(paths.size() == 1) return paths[0]; + + std::string path = paths[0]; + + for(unsigned int i=1; i paths(2); + paths[0] = a; + paths[1] = b; + return join_posix(paths); + } + + std::string join(const std::string & path1, const std::string & path2) + { +#ifdef WINDOWS + return join_nt(path1, path2); +#else + return join_posix(path1, path2); +#endif + } + + + std::string join(const std::vector< std::string > & paths) + { +#ifdef WINDOWS + return join_nt(paths); +#else + return join_posix(paths); +#endif + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + + + // Split a pathname. + // Return (head, tail) where tail is everything after the final slash. + // Either part may be empty + + void split_nt(std::string & head, std::string & tail, const std::string & path) + { + std::string d, p; + splitdrive_nt(d, p, path); + + // set i to index beyond p's last slash + int i = (int)p.size(); + + // walk back to find the index of the first slash from the end + while(i>0 && (p[i-1] != '\\') && (p[i-1] != '/')) + { + i = i - 1; + } + + head = pystring::slice(p,0,i); + tail = pystring::slice(p,i); // now tail has no slashes + + // remove trailing slashes from head, unless it's all slashes + std::string head2 = head; + while(!head2.empty() && ((pystring::slice(head2,-1) == "/") || + (pystring::slice(head2,-1) == "\\"))) + { + head2 = pystring::slice(head2,0,-1); + } + + if(!head2.empty()) head = head2; + head = d + head; + } + + + // Split a path in head (everything up to the last '/') and tail (the + // rest). If the path ends in '/', tail will be empty. If there is no + // '/' in the path, head will be empty. + // Trailing '/'es are stripped from head unless it is the root. + + void split_posix(std::string & head, std::string & tail, const std::string & p) + { + int i = pystring::rfind(p, "/") + 1; + + head = pystring::slice(p,0,i); + tail = pystring::slice(p,i); + + if(!head.empty() && (head != pystring::mul("/", (int) head.size()))) + { + head = pystring::rstrip(head, "/"); + } + } + + void split(std::string & head, std::string & tail, const std::string & path) + { +#ifdef WINDOWS + return split_nt(head, tail, path); +#else + return split_posix(head, tail, path); +#endif + } + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + + std::string basename_nt(const std::string & path) + { + std::string head, tail; + split_nt(head, tail, path); + return tail; + } + + std::string basename_posix(const std::string & path) + { + std::string head, tail; + split_posix(head, tail, path); + return tail; + } + + std::string basename(const std::string & path) + { +#ifdef WINDOWS + return basename_nt(path); +#else + return basename_posix(path); +#endif + } + + std::string dirname_nt(const std::string & path) + { + std::string head, tail; + split_nt(head, tail, path); + return head; + } + + std::string dirname_posix(const std::string & path) + { + std::string head, tail; + split_posix(head, tail, path); + return head; + } + + std::string dirname(const std::string & path) + { +#ifdef WINDOWS + return dirname_nt(path); +#else + return dirname_posix(path); +#endif + } + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + + // Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B. + std::string normpath_nt(const std::string & p) + { + std::string path = p; + path = pystring::replace(path, "/","\\"); + + std::string prefix; + splitdrive_nt(prefix, path, path); + + // We need to be careful here. If the prefix is empty, and the path starts + // with a backslash, it could either be an absolute path on the current + // drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It + // is therefore imperative NOT to collapse multiple backslashes blindly in + // that case. + // The code below preserves multiple backslashes when there is no drive + // letter. This means that the invalid filename \\\a\b is preserved + // unchanged, where a\\\b is normalised to a\b. It's not clear that there + // is any better behaviour for such edge cases. + + if(prefix.empty()) + { + // No drive letter - preserve initial backslashes + while(pystring::slice(path,0,1) == "\\") + { + prefix = prefix + "\\"; + path = pystring::slice(path,1); + } + } + else + { + // We have a drive letter - collapse initial backslashes + if(pystring::startswith(path, "\\")) + { + prefix = prefix + "\\"; + path = pystring::lstrip(path, "\\"); + } + } + + std::vector comps; + pystring::split(path, comps, "\\"); + + int i = 0; + + while(i<(int)comps.size()) + { + if(comps[i].empty() || comps[i] == ".") + { + comps.erase(comps.begin()+i); + } + else if(comps[i] == "..") + { + if(i>0 && comps[i-1] != "..") + { + comps.erase(comps.begin()+i-1, comps.begin()+i+1); + i -= 1; + } + else if(i == 0 && pystring::endswith(prefix, "\\")) + { + comps.erase(comps.begin()+i); + } + else + { + i += 1; + } + } + else + { + i += 1; + } + } + + // If the path is now empty, substitute '.' + if(prefix.empty() && comps.empty()) + { + comps.push_back("."); + } + + return prefix + pystring::join("\\", comps); + } + + // Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. + // It should be understood that this may change the meaning of the path + // if it contains symbolic links! + // Normalize path, eliminating double slashes, etc. + + std::string normpath_posix(const std::string & p) + { + if(p.empty()) return "."; + + std::string path = p; + + int initial_slashes = pystring::startswith(path,"/") ? 1 : 0; + + // POSIX allows one or two initial slashes, but treats three or more + // as single slash. + + if (initial_slashes && pystring::startswith(path,"//") + && !pystring::startswith(path,"///")) + initial_slashes = 2; + + std::vector comps, new_comps; + pystring::split(path, comps, "/"); + + for(unsigned int i=0; i 0) + path = pystring::mul("/",initial_slashes) + path; + + if(path.empty()) return "."; + return path; + } + + std::string normpath(const std::string & path) + { +#ifdef WINDOWS + return normpath_nt(path); +#else + return normpath_posix(path); +#endif + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// + + // Split the extension from a pathname. + // Extension is everything from the last dot to the end, ignoring + // leading dots. Returns "(root, ext)"; ext may be empty. + // It is always true that root + ext == p + + void splitext_generic(std::string & root, std::string & ext, + const std::string & p, + const std::string & sep, + const std::string & altsep, + const std::string & extsep) + { + int sepIndex = pystring::rfind(p, sep); + if(!altsep.empty()) + { + int altsepIndex = pystring::rfind(p, altsep); + sepIndex = std::max(sepIndex, altsepIndex); + } + + int dotIndex = pystring::rfind(p, extsep); + if(dotIndex > sepIndex) + { + // Skip all leading dots + int filenameIndex = sepIndex + 1; + + while(filenameIndex < dotIndex) + { + if(pystring::slice(p,filenameIndex) != extsep) + { + root = pystring::slice(p, 0, dotIndex); + ext = pystring::slice(p, dotIndex); + return; + } + + filenameIndex += 1; + } + } + + root = p; + ext = ""; + } + + void splitext_nt(std::string & root, std::string & ext, const std::string & path) + { + return splitext_generic(root, ext, path, + "\\", "/", "."); + } + + void splitext_posix(std::string & root, std::string & ext, const std::string & path) + { + return splitext_generic(root, ext, path, + "/", "", "."); + } + + void splitext(std::string & root, std::string & ext, const std::string & path) + { +#ifdef WINDOWS + return splitext_nt(root, ext, path); +#else + return splitext_posix(root, ext, path); +#endif + } + +} // namespace path +} // namespace os + + +}//namespace pystring + + diff --git a/hw_iface/code/pystring.h b/hw_iface/code/pystring.h new file mode 100644 index 0000000..45ffd9a --- /dev/null +++ b/hw_iface/code/pystring.h @@ -0,0 +1,429 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2008-2010, Sony Pictures Imageworks Inc +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// Neither the name of the organization Sony Pictures Imageworks nor the +// names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS +// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER +// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDED_PYSTRING_H +#define INCLUDED_PYSTRING_H + +#include +#include + +namespace pystring +{ + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @mainpage pystring + /// + /// This is a set of functions matching the interface and behaviors of python string methods + /// (as of python 2.3) using std::string. + /// + /// Overlapping functionality ( such as index and slice/substr ) of std::string is included + /// to match python interfaces. + /// + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @defgroup functions pystring + /// @{ + + + #define MAX_32BIT_INT 2147483647 + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string with only its first character capitalized. + /// + std::string capitalize( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return centered in a string of length width. Padding is done using spaces. + /// + std::string center( const std::string & str, int width ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return the number of occurrences of substring sub in string S[start:end]. Optional + /// arguments start and end are interpreted as in slice notation. + /// + int count( const std::string & str, const std::string & substr, int start = 0, int end = MAX_32BIT_INT); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return True if the string ends with the specified suffix, otherwise return False. With + /// optional start, test beginning at that position. With optional end, stop comparing at that position. + /// + bool endswith( const std::string & str, const std::string & suffix, int start = 0, int end = MAX_32BIT_INT ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string where all tab characters are expanded using spaces. If tabsize + /// is not given, a tab size of 8 characters is assumed. + /// + std::string expandtabs( const std::string & str, int tabsize = 8); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return the lowest index in the string where substring sub is found, such that sub is + /// contained in the range [start, end). Optional arguments start and end are interpreted as + /// in slice notation. Return -1 if sub is not found. + /// + int find( const std::string & str, const std::string & sub, int start = 0, int end = MAX_32BIT_INT ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Synonym of find right now. Python version throws exceptions. This one currently doesn't + /// + int index( const std::string & str, const std::string & sub, int start = 0, int end = MAX_32BIT_INT ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return true if all characters in the string are alphanumeric and there is at least one + /// character, false otherwise. + /// + bool isalnum( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return true if all characters in the string are alphabetic and there is at least one + /// character, false otherwise + /// + bool isalpha( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return true if all characters in the string are digits and there is at least one + /// character, false otherwise. + /// + bool isdigit( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return true if all cased characters in the string are lowercase and there is at least one + /// cased character, false otherwise. + /// + bool islower( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return true if there are only whitespace characters in the string and there is at least + /// one character, false otherwise. + /// + bool isspace( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return true if the string is a titlecased string and there is at least one character, + /// i.e. uppercase characters may only follow uncased characters and lowercase characters only + /// cased ones. Return false otherwise. + /// + bool istitle( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return true if all cased characters in the string are uppercase and there is at least one + /// cased character, false otherwise. + /// + bool isupper( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a string which is the concatenation of the strings in the sequence seq. + /// The separator between elements is the str argument + /// + std::string join( const std::string & str, const std::vector< std::string > & seq ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return the string left justified in a string of length width. Padding is done using + /// spaces. The original string is returned if width is less than str.size(). + /// + std::string ljust( const std::string & str, int width ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string converted to lowercase. + /// + std::string lower( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string with leading characters removed. If chars is omitted or None, + /// whitespace characters are removed. If given and not "", chars must be a string; the + /// characters in the string will be stripped from the beginning of the string this method + /// is called on (argument "str" ). + /// + std::string lstrip( const std::string & str, const std::string & chars = "" ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string, concatenated N times, together. + /// Corresponds to the __mul__ operator. + /// + std::string mul( const std::string & str, int n); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Split the string around first occurance of sep. + /// Three strings will always placed into result. If sep is found, the strings will + /// be the text before sep, sep itself, and the remaining text. If sep is + /// not found, the original string will be returned with two empty strings. + /// + void partition( const std::string & str, const std::string & sep, std::vector< std::string > & result ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string with all occurrences of substring old replaced by new. If + /// the optional argument count is given, only the first count occurrences are replaced. + /// + std::string replace( const std::string & str, const std::string & oldstr, const std::string & newstr, int count = -1); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return the highest index in the string where substring sub is found, such that sub is + /// contained within s[start,end]. Optional arguments start and end are interpreted as in + /// slice notation. Return -1 on failure. + /// + int rfind( const std::string & str, const std::string & sub, int start = 0, int end = MAX_32BIT_INT ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Currently a synonym of rfind. The python version raises exceptions. This one currently + /// does not + /// + int rindex( const std::string & str, const std::string & sub, int start = 0, int end = MAX_32BIT_INT ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return the string right justified in a string of length width. Padding is done using + /// spaces. The original string is returned if width is less than str.size(). + /// + std::string rjust( const std::string & str, int width); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Split the string around last occurance of sep. + /// Three strings will always placed into result. If sep is found, the strings will + /// be the text before sep, sep itself, and the remaining text. If sep is + /// not found, the original string will be returned with two empty strings. + /// + void rpartition( const std::string & str, const std::string & sep, std::vector< std::string > & result ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string with trailing characters removed. If chars is "", whitespace + /// characters are removed. If not "", the characters in the string will be stripped from the + /// end of the string this method is called on. + /// + std::string rstrip( const std::string & str, const std::string & chars = "" ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Fills the "result" list with the words in the string, using sep as the delimiter string. + /// If maxsplit is > -1, at most maxsplit splits are done. If sep is "", + /// any whitespace string is a separator. + /// + void split( const std::string & str, std::vector< std::string > & result, const std::string & sep = "", int maxsplit = -1); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Fills the "result" list with the words in the string, using sep as the delimiter string. + /// Does a number of splits starting at the end of the string, the result still has the + /// split strings in their original order. + /// If maxsplit is > -1, at most maxsplit splits are done. If sep is "", + /// any whitespace string is a separator. + /// + void rsplit( const std::string & str, std::vector< std::string > & result, const std::string & sep = "", int maxsplit = -1); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a list of the lines in the string, breaking at line boundaries. Line breaks + /// are not included in the resulting list unless keepends is given and true. + /// + void splitlines( const std::string & str, std::vector< std::string > & result, bool keepends = false ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return True if string starts with the prefix, otherwise return False. With optional start, + /// test string beginning at that position. With optional end, stop comparing string at that + /// position + /// + bool startswith( const std::string & str, const std::string & prefix, int start = 0, int end = MAX_32BIT_INT ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string with leading and trailing characters removed. If chars is "", + /// whitespace characters are removed. If given not "", the characters in the string will be + /// stripped from the both ends of the string this method is called on. + /// + std::string strip( const std::string & str, const std::string & chars = "" ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string with uppercase characters converted to lowercase and vice versa. + /// + std::string swapcase( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a titlecased version of the string: words start with uppercase characters, + /// all remaining cased characters are lowercase. + /// + std::string title( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string where all characters occurring in the optional argument + /// deletechars are removed, and the remaining characters have been mapped through the given + /// translation table, which must be a string of length 256. + /// + std::string translate( const std::string & str, const std::string & table, const std::string & deletechars = ""); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a copy of the string converted to uppercase. + /// + std::string upper( const std::string & str ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return the numeric string left filled with zeros in a string of length width. The original + /// string is returned if width is less than str.size(). + /// + std::string zfill( const std::string & str, int width ); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief function matching python's slice functionality. + /// + std::string slice( const std::string & str, int start = 0, int end = MAX_32BIT_INT); + + /// + /// @ } + /// + + +namespace os +{ +namespace path +{ + // All of the function below have three versions. + // Example: + // join(...) + // join_nt(...) + // join_posix(...) + // + // The regular function dispatches to the other versions - based on the OS + // at compile time - to match the result you'd get from the python + // interepreter on the same operating system + // + // Should you want to 'lock off' to a particular version of the string + // manipulation across *all* operating systems, use the version with the + // _OS you are interested in. I.e., you can use posix style path joining, + // even on Windows, with join_posix. + // + // The naming, (nt, posix) matches the cpython source implementation. + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @defgroup functions pystring::os::path + /// @{ + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return the base name of pathname path. This is the second half of the pair returned + /// by split(path). Note that the result of this function is different from the Unix basename + /// program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an + /// empty string (''). + + std::string basename(const std::string & path); + std::string basename_nt(const std::string & path); + std::string basename_posix(const std::string & path); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return the directory name of pathname path. This is the first half of the pair + /// returned by split(path). + + std::string dirname(const std::string & path); + std::string dirname_nt(const std::string & path); + std::string dirname_posix(const std::string & path); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return True if path is an absolute pathname. On Unix, that means it begins with a + /// slash, on Windows that it begins with a (back)slash after chopping off a potential drive + /// letter. + + bool isabs(const std::string & path); + bool isabs_nt(const std::string & path); + bool isabs_posix(const std::string & s); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Return a normalized absolutized version of the pathname path. + /// + /// NOTE: This differs from the interface of the python equivalent in that it requires you + /// to pass in the current working directory as an argument. + + std::string abspath(const std::string & path, const std::string & cwd); + std::string abspath_nt(const std::string & path, const std::string & cwd); + std::string abspath_posix(const std::string & path, const std::string & cwd); + + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Join one or more path components intelligently. If any component is an absolute + /// path, all previous components (on Windows, including the previous drive letter, if there + /// was one) are thrown away, and joining continues. The return value is the concatenation of + /// path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted + /// between components, unless path2 is empty. Note that on Windows, since there is a current + /// directory for each drive, os.path.join("c:", "foo") represents a path relative to the + /// current directory on drive C: (c:foo), not c:\foo. + + /// This dispatches based on the compilation OS + std::string join(const std::string & path1, const std::string & path2); + std::string join_nt(const std::string & path1, const std::string & path2); + std::string join_posix(const std::string & path1, const std::string & path2); + + std::string join(const std::vector< std::string > & paths); + std::string join_nt(const std::vector< std::string > & paths); + std::string join_posix(const std::vector< std::string > & paths); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Normalize a pathname. This collapses redundant separators and up-level references + /// so that A//B, A/B/, A/./B and A/foo/../B all become A/B. It does not normalize the case + /// (use normcase() for that). On Windows, it converts forward slashes to backward slashes. + /// It should be understood that this may change the meaning of the path if it contains + /// symbolic links! + + std::string normpath(const std::string & path); + std::string normpath_nt(const std::string & path); + std::string normpath_posix(const std::string & path); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Split the pathname path into a pair, (head, tail) where tail is the last pathname + /// component and head is everything leading up to that. The tail part will never contain a + /// slash; if path ends in a slash, tail will be empty. If there is no slash in path, head + /// will be empty. If path is empty, both head and tail are empty. Trailing slashes are + /// stripped from head unless it is the root (one or more slashes only). In all cases, + /// join(head, tail) returns a path to the same location as path (but the strings may + /// differ). + + void split(std::string & head, std::string & tail, const std::string & path); + void split_nt(std::string & head, std::string & tail, const std::string & path); + void split_posix(std::string & head, std::string & tail, const std::string & path); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Split the pathname path into a pair (drive, tail) where drive is either a drive + /// specification or the empty string. On systems which do not use drive specifications, + /// drive will always be the empty string. In all cases, drive + tail will be the same as + /// path. + + void splitdrive(std::string & drivespec, std::string & pathspec, const std::string & path); + void splitdrive_nt(std::string & drivespec, std::string & pathspec, const std::string & p); + void splitdrive_posix(std::string & drivespec, std::string & pathspec, const std::string & path); + + ////////////////////////////////////////////////////////////////////////////////////////////// + /// @brief Split the pathname path into a pair (root, ext) such that root + ext == path, and + /// ext is empty or begins with a period and contains at most one period. Leading periods on + /// the basename are ignored; splitext('.cshrc') returns ('.cshrc', ''). + + void splitext(std::string & root, std::string & ext, const std::string & path); + void splitext_nt(std::string & root, std::string & ext, const std::string & path); + void splitext_posix(std::string & root, std::string & ext, const std::string & path); + + /// + /// @ } + /// +} // namespace path +} // namespace os + +} // namespace pystring + +#endif diff --git a/hw_iface/code/test_serial_write.py b/hw_iface/code/test_serial_write.py new file mode 100644 index 0000000..d283f39 --- /dev/null +++ b/hw_iface/code/test_serial_write.py @@ -0,0 +1,38 @@ +#!/usr/bin/python + +import sys +import time +import serial +import random +import math +import time + +s = serial.Serial(sys.argv[1]) + +def gps_loop(): + + i = 0 + + while(1): + time.sleep(1) + i += 1 + try: + lat = 52.0 + .01 * math.sin(.1 * i) + lon = 21.0 + .01 * math.cos(.1 * i) + speed = 100.0 + 20.0 * math.cos(.1 * i) + sats = random.randrange(4,9) + + msg = 'gps::' + 'time=%s,lat=%f,lon=%f,alt=180000,altmsl=190000,sats=%d,speed=%f,heading=160000' % ( time.strftime("%H%M%S", time.gmtime()), lat, lon, sats, speed ) + print msg + s.write(msg + "\n") + except KeyboardInterrupt: + return + +def cycle_tabs(_dir): + msg = "tab::cycle=" + _dir + s.write(msg + "\n") + +if __name__ == "__main__": + gps_loop() + # cycle_tabs( sys.argv[2] ) + diff --git a/hw_iface/code/virtual_port.sh b/hw_iface/code/virtual_port.sh new file mode 100644 index 0000000..626de78 --- /dev/null +++ b/hw_iface/code/virtual_port.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +socat -d -d pty,raw,echo=0 pty,raw,echo=0 + diff --git a/hw_iface/code/websocket_session.cpp b/hw_iface/code/websocket_session.cpp new file mode 100644 index 0000000..61c2c83 --- /dev/null +++ b/hw_iface/code/websocket_session.cpp @@ -0,0 +1,99 @@ +#include "websocket_session.h" +#include "GLOBALS.h" + +namespace habboy_hw_iface +{ + +websocket_session::websocket_session( + tcp::socket socket, + std::shared_ptr p_ws_server ) + : ws_(std::move(socket)) +{ + p_ws_server_ = p_ws_server; +} + +websocket_session::~websocket_session() +{ + // Remove this session from the list of active sessions + // state_->leave(*this); + p_ws_server_->session_delete(*this); +} + +void websocket_session::fail(error_code ec, char const* what) +{ + if( ec == net::error::operation_aborted || + ec == boost::beast::websocket::error::closed) + return; + std::cerr << what << ": " << ec.message() << "\n"; +} + +void websocket_session::on_accept(error_code ec) +{ + if(ec) + return fail(ec, "accept"); + + p_ws_server_->session_add(*this); + + // Read a message + ws_.async_read( + buffer_, + [sp = shared_from_this()]( + error_code ec, std::size_t bytes) + { + sp->on_read(ec, bytes); + }); +} + +void websocket_session::on_read(error_code ec, std::size_t) +{ + if(ec) + return fail(ec, "read"); + + // GLOBALS::get().sessions_send( boost::beast::buffers_to_string(buffer_.data()) ); + p_ws_server_->sessions_send( boost::beast::buffers_to_string( buffer_.data()) ); + + std::string msg = boost::beast::buffers_to_string( buffer_.data() ); + std::cout<<"received message: "<on_read(ec, bytes); + }); +} + +void websocket_session::send(std::shared_ptr const& ss) +{ + queue_.push_back(ss); + if(queue_.size() > 1) + return; + + ws_.async_write( + net::buffer(*queue_.front()), + [sp = shared_from_this()](error_code ec, std::size_t bytes) + { + sp->on_write(ec, bytes); + }); +} + +void websocket_session::on_write(error_code ec, std::size_t) +{ + if(ec) + return fail(ec, "write"); + + queue_.erase(queue_.begin()); + + if(! queue_.empty()) + ws_.async_write( + net::buffer(*queue_.front()), + [sp = shared_from_this()](error_code ec, std::size_t bytes) + { + sp->on_write(ec, bytes); + }); +} + +} // ns \ No newline at end of file diff --git a/hw_iface/code/websocket_session.h b/hw_iface/code/websocket_session.h new file mode 100644 index 0000000..1d0ea0f --- /dev/null +++ b/hw_iface/code/websocket_session.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +#include "ws_server.h" + +namespace habboy_hw_iface +{ + +namespace net = boost::asio; // namespace asio +using tcp = net::ip::tcp; // from +using error_code = boost::system::error_code; // from + +class websocket_session : public std::enable_shared_from_this +{ + boost::beast::flat_buffer buffer_; + boost::beast::websocket::stream ws_; + std::vector> queue_; + std::shared_ptr p_ws_server_; + + void fail(error_code ec, char const* what); + void on_accept(error_code ec); + void on_read(error_code ec, std::size_t bytes_transferred); + void on_write(error_code ec, std::size_t bytes_transferred); + +public: + websocket_session(tcp::socket socket, std::shared_ptr p_ws_server); + ~websocket_session(); + + template + void run(boost::beast::http::request> req); + + void send(std::shared_ptr const& i_msg); +}; + +template +void websocket_session::run(boost::beast::http::request> req) +{ + ws_.async_accept( + req, + std::bind( + &websocket_session::on_accept, + shared_from_this(), + std::placeholders::_1)); +} + + +} //ns \ No newline at end of file diff --git a/hw_iface/code/ws_server.cpp b/hw_iface/code/ws_server.cpp new file mode 100644 index 0000000..b4f2122 --- /dev/null +++ b/hw_iface/code/ws_server.cpp @@ -0,0 +1,37 @@ +#include "ws_server.h" +#include "listener.h" +#include "websocket_session.h" + +namespace habboy_hw_iface +{ + + +void WebsocketServer::operator()() +{ + using namespace std; + using tcp = boost::asio::ip::tcp; + + auto const address = boost::asio::ip::make_address( host_ ); + auto const port = static_cast( port_ ); + + make_shared( + ioc_, + tcp::endpoint{address, port}, + *this + )->run(); + + ioc_.run(); +} + +void WebsocketServer::sessions_send (std::string message) +{ + auto const ss = std::make_shared(std::move(message)); + { + std::lock_guard lock(sessions_mtx_); + for(auto session : sessions_) + session->send(ss); + } +} + + +} //ns \ No newline at end of file diff --git a/hw_iface/code/ws_server.h b/hw_iface/code/ws_server.h new file mode 100644 index 0000000..8abdefa --- /dev/null +++ b/hw_iface/code/ws_server.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +// #include "websocket_session.h" + + +/* +using boost::asio::ip::tcp; +namespace beast = boost::beast; +namespace websocket = boost::beast::websocket; +*/ + +namespace habboy_hw_iface +{ + +class websocket_session; + +class WebsocketServer : public std::enable_shared_from_this +{ + +public: + WebsocketServer() = delete; + WebsocketServer(const WebsocketServer&) = delete; + WebsocketServer& operator=(const WebsocketServer&) = delete; + + WebsocketServer(std::string host, unsigned int port) : host_(host), port_(port) {} + + void operator()(); + + // sessions + void session_add (habboy_hw_iface::websocket_session& session) { sessions_.insert(&session); } + void session_delete (habboy_hw_iface::websocket_session& session) { sessions_.erase(&session); } + void sessions_send (std::string message); + +private: + std::string host_{"0.0.0.0"}; + unsigned int port_{5565}; + boost::asio::io_context ioc_{1}; + + // sessions + std::unordered_set sessions_; + std::mutex sessions_mtx_; +}; + +} //ns \ No newline at end of file diff --git a/hw_iface/js_test_client/index.html b/hw_iface/js_test_client/index.html new file mode 100644 index 0000000..e3e01bb --- /dev/null +++ b/hw_iface/js_test_client/index.html @@ -0,0 +1,36 @@ + + + + + + + + + + + + +
+
+ + + + + diff --git a/hw_iface/js_test_client/js/ws_client.js b/hw_iface/js_test_client/js/ws_client.js new file mode 100644 index 0000000..1f62d9f --- /dev/null +++ b/hw_iface/js_test_client/js/ws_client.js @@ -0,0 +1,110 @@ + +var G_HD_WEBSOCKET; +var G_HD_CONNECTED = 0; + + +function debug_print() +{ + console.debug(arguments); + document.getElementById("ws_client_debug").innerHTML = ""; + for (i = 0; i < arguments.length; i++) + document.getElementById("ws_client_debug").innerHTML += arguments[i] + " "; +} + + +function OpenConnection(endpoint) +{ + if(G_HD_CONNECTED) + return; + + var server = endpoint; + console.debug("Connecting to ", server, " ..."); + G_HD_WEBSOCKET = new WebSocket("ws://" + server); + G_HD_WEBSOCKET.binaryType = 'arraybuffer'; // or 'blob' + + G_HD_WEBSOCKET.onopen = function(evt) { ws_onOpen(evt) }; + G_HD_WEBSOCKET.onclose = function(evt) { ws_onClose(evt) }; + G_HD_WEBSOCKET.onmessage = function(evt) { ws_onMessage(evt) }; + G_HD_WEBSOCKET.onerror = function(evt) { ws_onError(evt) }; +} + + +function ws_onClose(evt) +{ + G_HD_CONNECTED = 0; + debug_print("DISCONNECTED"); + setTimeout(function () { OpenConnection(); }, 5000); +} + + +function ws_onError(evt) +{ + debug_print("ws_onError: ", evt.data); +} + + +function ws_onOpen(evt) +{ + G_HD_CONNECTED = 1; + debug_print("ws_onOpen: ", "Connected."); + + G_HD_WEBSOCKET.send("hi"); + SendCommand("info:gps"); + + console.debug("ws_onOpen: init refresh."); +} + + +function ws_onMessage(evt) +{ + if(!G_HD_CONNECTED) + { + debug_print("ws_onMessage: not connected."); + return; + } + + // console.debug("ON_MSG", evt); + + if(typeof evt.data === "string") + { + HandleMessage(evt.data) + } + else if(evt.data instanceof ArrayBuffer) + { + debug_print("got bin data"); + } + else + { + debug_print("ws_onMessage: unknown data type."); + return; + } +} + + +function SendCommand(i_cmd) +{ + if(!G_HD_CONNECTED) + { + debug_print("SendCommand: not connected."); + return; + } + var msg = "cmd::" + i_cmd; + // debug_print("SendCommand: ", msg); + G_HD_WEBSOCKET.send(msg); +} + + +function HandleMessage(i_data) +{ + if(!G_HD_CONNECTED) + { + debug_print("HandleMessage: not connected."); + return; + } + + if( !i_data.startsWith("cmd::info:liveprint") ) + debug_print("Received Message: ", i_data); + + return false; + +} diff --git a/tilemaker_config/README.md b/tilemaker_config/README.md new file mode 100644 index 0000000..1103bdc --- /dev/null +++ b/tilemaker_config/README.md @@ -0,0 +1,3 @@ +Example usage and config of tilemaker + +How to use tilemaker: https://github.com/ogre/tilemaker_config diff --git a/tilemaker_config/hab_admin.json b/tilemaker_config/hab_admin.json new file mode 100644 index 0000000..0d41a15 --- /dev/null +++ b/tilemaker_config/hab_admin.json @@ -0,0 +1,37 @@ +{ + "layers": { + "admin": { + "source": "../data/boundaries/export3.shp", + "source_columns": [ + "admin_level" + ], + "minzoom": 5, + "maxzoom": 10, + "simplify_below": 10, + "simplify_length": 100, + "simplify_level": 0.0035, + "simplify_ratio": 3 + } + }, + "settings": { + "minzoom": 5, + "maxzoom": 10, + "basezoom": 10, + "include_ids": false, + "name": "HAB", + "version": "1.0", + "description": "HAB", + "compress": "none", + "metadata": { + "json": { + "vector_layers": [ + { + "id": "admin", + "description": "admin", + "fields": {} + } + ] + } + } + } +} \ No newline at end of file diff --git a/tilemaker_config/hab_admin.lua b/tilemaker_config/hab_admin.lua new file mode 100644 index 0000000..8cdf438 --- /dev/null +++ b/tilemaker_config/hab_admin.lua @@ -0,0 +1,24 @@ + +node_keys = { +} + +function init_function() +end + +function exit_function() +end + +function node_function(node) +end + +function way_function(way) + -- something has to be written + -- local boundary = way:Find("boundary") + -- if boundary ~= nil and boundary == "administrative" then + -- local admin_level = way:Find("admin_level") + -- if admin_level ~= nil and admin_level ~= "" then + -- layer = "unused" + -- way:Layer(layer, false) + -- end -- admin level + -- end +end diff --git a/tilemaker_config/hab_aeroway.json b/tilemaker_config/hab_aeroway.json new file mode 100644 index 0000000..c4c03d6 --- /dev/null +++ b/tilemaker_config/hab_aeroway.json @@ -0,0 +1,39 @@ +{ + "layers": { + "aeroway": { + "minzoom": 9, + "maxzoom": 14, + "simplify_below": 13, + "simplify_length": 10, + "simplify_ratio": 3 + }, + "aeroway_other": { + "minzoom": 9, + "maxzoom": 14, + "simplify_below": 13, + "simplify_length": 10, + "simplify_ratio": 3 + } + }, + "settings": { + "minzoom": 8, + "maxzoom": 14, + "basezoom": 14, + "include_ids": false, + "name": "HAB", + "version": "1.0", + "description": "HAB", + "compress": "none", + "metadata": { + "json": { + "vector_layers": [ + { + "id": "aeroway", + "description": "aeroway", + "fields": {} + } + ] + } + } + } +} \ No newline at end of file diff --git a/tilemaker_config/hab_aeroway.lua b/tilemaker_config/hab_aeroway.lua new file mode 100644 index 0000000..1fc3c1f --- /dev/null +++ b/tilemaker_config/hab_aeroway.lua @@ -0,0 +1,83 @@ +node_keys = {} + +G_DEFAULT = 0 +G_COUNTS = {} + + +function zoom_tile_area(latitude_degrees, zoom_level) + earth_equatorial_circumference = 40075016.686 -- meters + latitude_radians = 3.14159265359 * latitude_degrees / 180.0 + tile_width = earth_equatorial_circumference * math.cos(latitude_radians) / (2^zoom_level) + return tile_width*tile_width +end + +-- store m2 area for one tile on each zoom level +ZOOM_TILES_AREA = {} + + +function init_function() + for i=1,16 do + ZOOM_TILES_AREA[i] = zoom_tile_area(52.0, i) + print(ZOOM_TILES_AREA[i]) + end +end + + +local function is_in (val, tab) + for index, value in ipairs(tab) do + if value == val then + return true + end + end + return false +end + + +function get_min_zoom(in_area) + local min_zoom = 1 + for _z=15,1,-1 do + if in_area < (0.01 * ZOOM_TILES_AREA[_z]) then + return _z + end + end + return min_zoom +end + + +function exit_function() + for _k,_v in pairs(G_COUNTS) + do + print("\n") + print(_k) + for k,v in pairs(_v) + do + print("\t", k, v) + end + end +end + + +function node_function(node) +end + + +function way_function(way) + local name = way:Find("name"); + -- aeroway + local aeroway = way:Find("aeroway") + if aeroway ~= nil and aeroway ~= "" then + local class = aeroway + + if G_COUNTS["aeroway"] == nil then G_COUNTS["aeroway"] = {} end + if G_COUNTS["aeroway"][aeroway] == nil then G_COUNTS["aeroway"][aeroway] = 0 end + G_COUNTS["aeroway"][aeroway] = G_COUNTS["aeroway"][aeroway] + 1 + + if is_in( aeroway, { "aerodrome", "apron", "heliport", "runway", "terminal", "hangar"} )then + layer = "aeroway" + way:Layer(layer, way:IsClosed()) + way:Attribute("class", aeroway) + way:MinZoom( get_min_zoom(way:Area()) ) + if name ~= nil and name ~= "" then way:Attribute("name",name) end + end + end +end \ No newline at end of file diff --git a/tilemaker_config/hab_buildings.json b/tilemaker_config/hab_buildings.json new file mode 100644 index 0000000..363ee62 --- /dev/null +++ b/tilemaker_config/hab_buildings.json @@ -0,0 +1,29 @@ +{ + "layers": { + "building": { + "minzoom": 15, + "maxzoom": 15 + } + }, + "settings": { + "minzoom": 15, + "maxzoom": 15, + "basezoom": 15, + "include_ids": false, + "name": "HAB", + "version": "1.0", + "description": "HAB", + "compress": "none", + "metadata": { + "json": { + "vector_layers": [ + { + "id": "building", + "description": "building", + "fields": {} + } + ] + } + } + } +} \ No newline at end of file diff --git a/tilemaker_config/hab_buildings.lua b/tilemaker_config/hab_buildings.lua new file mode 100644 index 0000000..c60699a --- /dev/null +++ b/tilemaker_config/hab_buildings.lua @@ -0,0 +1,85 @@ +node_keys = {} + +G_DEFAULT = 0 +G_COUNTS = {} + + +function zoom_tile_area(latitude_degrees, zoom_level) + earth_equatorial_circumference = 40075016.686 -- meters + latitude_radians = 3.14159265359 * latitude_degrees / 180.0 + tile_width = earth_equatorial_circumference * math.cos(latitude_radians) / (2^zoom_level) + return tile_width*tile_width +end + +-- store m2 area for one tile on each zoom level +ZOOM_TILES_AREA = {} + + +function init_function() + for i=1,16 do + ZOOM_TILES_AREA[i] = zoom_tile_area(52.0, i) + print(ZOOM_TILES_AREA[i]) + end +end + + +local function is_in (val, tab) + for index, value in ipairs(tab) do + if value == val then + return true + end + end + return false +end + + +function get_min_zoom(in_area) + local min_zoom = 1 + for _z=15,1,-1 do + if in_area < (0.01 * ZOOM_TILES_AREA[_z]) then + return _z + end + end + return min_zoom +end + + +function exit_function() + for _k,_v in pairs(G_COUNTS) + do + print("\n") + print(_k) + for k,v in pairs(_v) + do + print("\t", k, v) + end + end +end + + +function node_function(node) +end + + +function way_function(way) + local name = way:Find("name"); + + -- building + local building = way:Find("building") + if building ~= nil and building ~= "" then + if G_COUNTS["building"] == nil then G_COUNTS["building"] = {} end + if G_COUNTS["building"][building] == nil then G_COUNTS["building"][building] = 0 end + G_COUNTS["building"][building] = G_COUNTS["building"][building] + 1 + + local layer = "building" + way:Layer(layer, true) + way:Attribute("class", building) + if name ~= nil and name ~= "" then way:Attribute("name",name) end + + local height = way:Find("height"); + if height ~= nil and height ~= "" then way:Attribute("height",height) end + local min_height = way:Find("min_height"); + if min_height ~= nil and min_height ~= "" then way:Attribute("min_height",min_height) end + + end +end \ No newline at end of file diff --git a/tilemaker_config/hab_labels.json b/tilemaker_config/hab_labels.json new file mode 100644 index 0000000..0a30dd5 --- /dev/null +++ b/tilemaker_config/hab_labels.json @@ -0,0 +1,33 @@ +{ + "layers": { + "place_label": { + "minzoom": 6, + "maxzoom": 15 + }, + "road_label": { + "minzoom": 6, + "maxzoom": 15 + } + }, + "settings": { + "minzoom": 5, + "maxzoom": 15, + "basezoom": 15, + "include_ids": false, + "name": "HAB", + "version": "1.0", + "description": "HAB", + "compress": "none", + "metadata": { + "json": { + "vector_layers": [ + { + "id": "labels", + "description": "labels", + "fields": {} + } + ] + } + } + } +} \ No newline at end of file diff --git a/tilemaker_config/hab_labels.lua b/tilemaker_config/hab_labels.lua new file mode 100644 index 0000000..d23abb8 --- /dev/null +++ b/tilemaker_config/hab_labels.lua @@ -0,0 +1,140 @@ +-- https://taginfo.openstreetmap.org/keys + +node_keys = { + -- "Aerialway", + -- "Aeroway", + -- "Amenity", + -- "Barrier", + -- "Boundary", + -- "building", + -- "Craft", + -- "Emergency", + -- "Geological", + -- "Highway", + -- "Historic", + -- "Common Landuse Key Values", + -- "Other Landuse Key Values", + -- "Leisure", + -- "Man_made", + -- "Military", + -- "natural", + -- "Office", + "place", + -- "Power", + -- "Public Transport", + -- "Railway", + -- "Route", + -- "Shop", + -- "Sport", + -- "Telecom", + -- "Tourism", + -- "Waterway" +} + +G_DEFAULT = 0 +G_COUNTS = {} + + +function init_function() +end + + +local function is_in (val, tab) + for index, value in ipairs(tab) do + if value == val then + return true + end + end + return false +end + + +function exit_function() + for _k,_v in pairs(G_COUNTS) + do + print("\n") + print(_k) + for k,v in pairs(_v) + do + print("\t", k, v) + end + end +end + + +function node_function(node) + + local place = node:Find("place") + local capital = node:Find("capital") + local admin_level = node:Find("admin_level") + local name = node:Find("name") + local aeroway = node:Find("aeroway") + -- local shop = node:Find("shop") + -- local amenity = node:Find("amenity") + + -- place + if place ~= nil and place ~= "" then + node:Layer("place_label", false) + node:Attribute("name",name) + -- the main field for styling labels for different kinds of places is type. + -- possible values: 'city','town','village','hamlet','suburb','neighbourhood' + node:Attribute("type",place) + --The capital field allows distinct styling of labels or icons for the capitals of countries, regions, or states & provinces. + -- 2=National capital, 3=Regional capital (uncommon), 4=State/provincial capital + if capital ~="" then + if admin_level == 2 then + node:AttributeNumeric("capital",2) + end + if admin_level == 4 then + node:AttributeNumeric("capital",4) + end + end + -- The value number from 0 through 9, where 0 is the large end of the scale (eg New York City). + -- All places other than large cities will have a scalerank of null. + if place == "village" then + node:AttributeNumeric("scalerank",3) + end + if place == "town" then + node:AttributeNumeric("scalerank",5) + end + if place == "suburb" then + node:AttributeNumeric("scalerank",7) + end + if place == "city" then + node:AttributeNumeric("scalerank",9) + end + -- Therefore to reduce the label density to 4 labels per tile, you can add the filter [localrank=1]. + node:AttributeNumeric("localrank",1) + -- The ldir field can be used as a hint for label offset directions at lower zoom levels. + node:Attribute("ldir","N") + end +end + + +function way_function(way) + local name = way:Find("name"); + -- road_label layer + local highway = way:Find("highway") + if highway ~= nil and highway ~= "" and name ~= "" then + way:Layer("road_label", false) + way:Attribute("name",name) + local ref = way:Find("ref") + if ref ~= "" then + way:Attribute("ref", ref) + way:AttributeNumeric( "reflen", string.len(ref) ) + end + way:AttributeNumeric("osm_id",tonumber(way:Id())) + way:Attribute("shield","default") + way:AttributeNumeric("len", 100) + way:AttributeNumeric("localrank", 3) + --"class","len","localrank","name","name_de","name_en","name_es","name_fr","name_ru","name_zh","osm_id","ref","reflen","shield" + --way:AttributeBoolean("oneway": "false") + if highway=="residential" then way:Attribute("class","street") end + if highway=="primary" or highway=="secondary" or highway=="tertiary" then + way:Attribute("class","main") + end + if highway=="primary_link" or highway=="secondary_link" then + way:Attribute("class","street") + end + end +end \ No newline at end of file diff --git a/tilemaker_config/hab_landuse.json b/tilemaker_config/hab_landuse.json new file mode 100644 index 0000000..4b8f59d --- /dev/null +++ b/tilemaker_config/hab_landuse.json @@ -0,0 +1,39 @@ +{ + "layers": { + "landuse": { + "minzoom": 9, + "maxzoom": 14, + "simplify_below": 13, + "simplify_length": 10, + "simplify_ratio": 3 + }, + "natural": { + "minzoom": 9, + "maxzoom": 14, + "simplify_below": 13, + "simplify_length": 10, + "simplify_ratio": 3 + } + }, + "settings": { + "minzoom": 9, + "maxzoom": 14, + "basezoom": 14, + "include_ids": false, + "name": "HAB", + "version": "1.0", + "description": "HAB", + "compress": "none", + "metadata": { + "json": { + "vector_layers": [ + { + "id": "roads", + "description": "roads", + "fields": {} + } + ] + } + } + } +} \ No newline at end of file diff --git a/tilemaker_config/hab_landuse.lua b/tilemaker_config/hab_landuse.lua new file mode 100644 index 0000000..2f14390 --- /dev/null +++ b/tilemaker_config/hab_landuse.lua @@ -0,0 +1,96 @@ +node_keys = {} + +G_DEFAULT = 0 +G_COUNTS = {} + + +function zoom_tile_area(latitude_degrees, zoom_level) + earth_equatorial_circumference = 40075016.686 -- meters + latitude_radians = 3.14159265359 * latitude_degrees / 180.0 + tile_width = earth_equatorial_circumference * math.cos(latitude_radians) / (2^zoom_level) + return tile_width*tile_width +end + +-- store m2 area for one tile on each zoom level +ZOOM_TILES_AREA = {} + + +function init_function() + for i=1,16 do + ZOOM_TILES_AREA[i] = zoom_tile_area(52.0, i) + print(ZOOM_TILES_AREA[i]) + end +end + + +local function is_in (val, tab) + for index, value in ipairs(tab) do + if value == val then + return true + end + end + return false +end + + +function get_min_zoom(in_area) + local min_zoom = 1 + for _z=15,1,-1 do + if in_area < (0.01 * ZOOM_TILES_AREA[_z]) then + return _z + end + end + return min_zoom +end + + +function exit_function() + for _k,_v in pairs(G_COUNTS) + do + print("\n") + print(_k) + for k,v in pairs(_v) + do + print("\t", k, v) + end + end +end + + +function node_function(node) +end + + +function way_function(way) + local name = way:Find("name"); + + -- Landuse + local landuse = way:Find("landuse") + if landuse ~= nil and landuse ~= "" then + if G_COUNTS["landuse"] == nil then G_COUNTS["landuse"] = {} end + if G_COUNTS["landuse"][landuse] == nil then G_COUNTS["landuse"][landuse] = 0 end + G_COUNTS["landuse"][landuse] = G_COUNTS["landuse"][landuse] + 1 + + local layer = "landuse" + way:Layer(layer, way:IsClosed()) + way:Attribute("class", landuse) + way:MinZoom( get_min_zoom(way:Area()) ) + if name ~= nil and name ~= "" then way:Attribute("name",name) end + end + + -- Natural + local natural = way:Find("natural") + if natural ~= nil and natural ~= "" then + if G_COUNTS["natural"] == nil then G_COUNTS["natural"] = {} end + if G_COUNTS["natural"][natural] == nil then G_COUNTS["natural"][natural] = 0 end + G_COUNTS["natural"][natural] = G_COUNTS["natural"][natural] + 1 + + if is_in( natural, { "wood", "forest", "scrub", "heath", "grassland", "fell", "bare_rock", "scree", "shingle", "sand", "meadow" } ) then + local layer = "natural" + way:Layer(layer, way:IsClosed()) + way:Attribute("class", natural) + way:MinZoom( get_min_zoom(way:Area()) ) + if name ~= nil and name ~= "" then way:Attribute("name",name) end + end + end +end \ No newline at end of file diff --git a/tilemaker_config/hab_roads.json b/tilemaker_config/hab_roads.json new file mode 100644 index 0000000..17d9aab --- /dev/null +++ b/tilemaker_config/hab_roads.json @@ -0,0 +1,39 @@ +{ + "layers": { + "roads": { + "minzoom": 5, + "maxzoom": 14, + "simplify_below": 12, + "simplify_level": 0.001, + "simplify_ratio": 2 + }, + "railways": { + "minzoom": 13, + "maxzoom": 14, + "simplify_below": 13, + "simplify_level": 0.001, + "simplify_ratio": 2 + } + }, + "settings": { + "minzoom": 5, + "maxzoom": 14, + "basezoom": 14, + "include_ids": false, + "name": "HAB", + "version": "1.0", + "description": "HAB", + "compress": "none", + "metadata": { + "json": { + "vector_layers": [ + { + "id": "roads", + "description": "roads", + "fields": {} + } + ] + } + } + } +} \ No newline at end of file diff --git a/tilemaker_config/hab_roads.lua b/tilemaker_config/hab_roads.lua new file mode 100644 index 0000000..3b8b572 --- /dev/null +++ b/tilemaker_config/hab_roads.lua @@ -0,0 +1,144 @@ +-- https://taginfo.openstreetmap.org/keys + +node_keys = {} + +G_DEFAULT = 0 +G_COUNTS = {} + + +function init_function() +end + + +function exit_function() + for _k,_v in pairs(G_COUNTS) + do + print("\n") + print(_k) + for k,v in pairs(_v) + do + print("\t", k, v) + end + end +end + + +function node_function(node) +end + + +function Set(list) + local set = {} + for _, l in ipairs(list) do set[l] = true end + return set +end + + +local function is_in (val, tab) + for index, value in ipairs(tab) do + if value == val then + return true + end + end + return false +end + + +function SetBrunnelAttributes(obj) + if obj:Find("bridge") == "yes" then obj:Attribute("brunnel", "bridge") + elseif obj:Find("tunnel") == "yes" then obj:Attribute("brunnel", "tunnel") + elseif obj:Find("ford") == "yes" then obj:Attribute("brunnel", "ford") + end +end + + +linkValues = Set { "motorway_link", "trunk_link", "primary_link", "secondary_link", "tertiary_link" } + + +-- https://stackoverflow.com/a/7615129/4288232 +function split(inputstr, sep) + if sep == nil then + sep = "%s" + end + local t={} ; i=1 + for str in string.gmatch(inputstr, "([^"..sep.."]+)") do + t[i] = str + i = i + 1 + end + return t +end + + +function way_function(way) + if way:Find("disused") == "yes" then return end + + local name = way:Find("name"); + + -- highway + local highway = way:Find("highway") + if highway ~= nil and highway ~= "" then + if highway == "proposed" then return end + + if G_COUNTS["highway"] == nil then G_COUNTS["highway"] = {} end + if G_COUNTS["highway"][highway] == nil then G_COUNTS["highway"][highway] = 0 end + G_COUNTS["highway"][highway] = G_COUNTS["highway"][highway] + 1 + + + local road_type = "unknown" + local road_min_zoom = 0; + if is_in( highway, { "motorway", "trunk", "primary" } ) then + road_type = "road_main" + end + + if is_in( highway, { "motorway_link", "trunk_link", "primary_link", "secondary", "secondary_link" } ) then + road_type = "road_secondary" + road_min_zoom = 6 + end + + if is_in( highway, { "tertiary", "tertiary_link", "unclassified" } ) + then + road_type = "road_tertiary" + road_min_zoom = 10 + end + + if is_in( highway, { "track", "road", "living_street", "residential", "footway" } ) + then + road_type = "other" + road_min_zoom = 14 + end + + + if road_type == "unknown" then + return + end + + + way:Layer("roads", false) + way:Attribute("class", highway) + -- way:Attribute("class", road_type) + if name ~= nil and name ~= "" then way:Attribute("name",name) end + if road_min_zoom then way:MinZoom(road_min_zoom) end + SetBrunnelAttributes(way) + -- Links (ramp) + if linkValues[highway] then + splitHighway = split(highway, "_") + highway = splitHighway[1] + way:AttributeNumeric("ramp",1) + end + end + + -- railway + local railway = way:Find("railway") + if railway ~= nil and railway == "rail" then + if G_COUNTS["railway"] == nil then G_COUNTS["railway"] = {} end + if G_COUNTS["railway"][railway] == nil then G_COUNTS["railway"][railway] = 0 end + G_COUNTS["railway"][railway] = G_COUNTS["railway"][railway] + 1 + + local layer = "railways" + way:Layer(layer, false) + way:Attribute("class", railway) + if name ~= nil and name ~= "" then + way:Attribute("name",name) + end + end +end \ No newline at end of file diff --git a/tilemaker_config/hab_water.json b/tilemaker_config/hab_water.json new file mode 100644 index 0000000..f77ed7a --- /dev/null +++ b/tilemaker_config/hab_water.json @@ -0,0 +1,39 @@ +{ + "layers": { + "river": { + "minzoom": 5, + "maxzoom": 14, + "simplify_below": 11, + "simplify_level": 0.0015, + "simplify_ratio": 2 + }, + "water": { + "minzoom": 5, + "maxzoom": 14, + "simplify_below": 13, + "simplify_length": 10, + "simplify_ratio": 3 + } + }, + "settings": { + "minzoom": 5, + "maxzoom": 14, + "basezoom": 16, + "include_ids": false, + "name": "HAB", + "version": "1.0", + "description": "HAB", + "compress": "none", + "metadata": { + "json": { + "vector_layers": [ + { + "id": "water", + "description": "water", + "fields": {} + } + ] + } + } + } +} \ No newline at end of file diff --git a/tilemaker_config/hab_water.lua b/tilemaker_config/hab_water.lua new file mode 100644 index 0000000..e9c6275 --- /dev/null +++ b/tilemaker_config/hab_water.lua @@ -0,0 +1,108 @@ +node_keys = {} + +G_DEFAULT = 0 +G_COUNTS = {} + + +function zoom_tile_area(latitude_degrees, zoom_level) + earth_equatorial_circumference = 40075016.686 -- meters + latitude_radians = 3.14159265359 * latitude_degrees / 180.0 + tile_width = earth_equatorial_circumference * math.cos(latitude_radians) / (2^zoom_level) + return tile_width*tile_width +end + +-- store m2 area for one tile on each zoom level +ZOOM_TILES_AREA = {} + + +function init_function() + for i=1,16 do + ZOOM_TILES_AREA[i] = zoom_tile_area(52.0, i) + print(ZOOM_TILES_AREA[i]) + end +end + + +local function is_in (val, tab) + for index, value in ipairs(tab) do + if value == val then + return true + end + end + return false +end + + +function get_min_zoom(in_area) + local min_zoom = 1 + for _z=15,1,-1 do + if in_area < (0.01 * ZOOM_TILES_AREA[_z]) then + return _z + end + end + return min_zoom +end + + +function exit_function() + for _k,_v in pairs(G_COUNTS) + do + print("\n") + print(_k) + for k,v in pairs(_v) + do + print("\t", k, v) + end + end +end + + +function node_function(node) +end + + +function way_function(way) + local name = way:Find("name"); + + -- Water + local natural = way:Find("natural") + if natural ~= nil and natural ~= "" and way:IsClosed() ~= false then + if G_COUNTS["natural"] == nil then G_COUNTS["natural"] = {} end + if G_COUNTS["natural"][natural] == nil then G_COUNTS["natural"][natural] = 0 end + G_COUNTS["natural"][natural] = G_COUNTS["natural"][natural] + 1 + + if is_in( natural, { "water", "wetland", "bay", "mud" } ) then + local layer = "water" + if layer ~= "" then + way:Layer(layer, way:IsClosed()) + way:Attribute("class", natural) + way:MinZoom( get_min_zoom(way:Area()) ) + if name ~= nil and name ~= "" then way:Attribute("name",name) end + end + end + end + + -- waterway + local waterway = way:Find("waterway") + if waterway ~= nil and waterway ~= "" then + if G_COUNTS["waterway"] == nil then G_COUNTS["waterway"] = {} end + if G_COUNTS["waterway"][waterway] == nil then G_COUNTS["waterway"][waterway] = 0 end + G_COUNTS["waterway"][waterway] = G_COUNTS["waterway"][waterway] + 1 + + -- if is_in( class, { "yes", "water", "river", "riverbank", "stream", "reservoir", "moat", "pond", "canal" } ) + if is_in( waterway, { "yes", "water", "riverbank", "reservoir", "moat", "pond", "canal" } ) then + layer = "water" + way:Layer(layer, way:IsClosed()) + way:Attribute("class", waterway) + -- way:MinZoom( get_min_zoom(way:Area()) ) + if name ~= nil and name ~= "" then way:Attribute("name",name) end + elseif is_in( waterway, { "river", "stream", "canal" } ) then + layer = "river" + way:Layer(layer, way:IsClosed()) + way:Attribute("class", waterway) + -- way:MinZoom( get_min_zoom(way:Area()) ) + if name ~= nil and name ~= "" then way:Attribute("name",name) end + end + end + +end \ No newline at end of file diff --git a/tilemaker_config/update.sh b/tilemaker_config/update.sh new file mode 100644 index 0000000..c412e17 --- /dev/null +++ b/tilemaker_config/update.sh @@ -0,0 +1,15 @@ +#!/bin/sh + +## +# $1 is path to PBF file +# $2 is output dir +# /usr/bin/time -v is used to report execution time and memory usage + +mkdir $2 +/usr/bin/time -v ./tilemaker $1 --output $2/aeroway --config ./hab_aeroway.json --process ./hab_aeroway.lua +/usr/bin/time -v ./tilemaker $1 --output $2/buildings --config ./hab_buildings.json --process ./hab_buildings.lua +/usr/bin/time -v ./tilemaker $1 --output $2/landuse --config ./hab_landuse.json --process ./hab_landuse.lua +/usr/bin/time -v ./tilemaker $1 --output $2/roads --config ./hab_roads.json --process ./hab_roads.lua +/usr/bin/time -v ./tilemaker $1 --output $2/water --config ./hab_water.json --process ./hab_water.lua +/usr/bin/time -v ./tilemaker $1 --output $2/labels --config ./hab_labels.json --process ./hab_labels.lua +/usr/bin/time -v ./tilemaker $1 --output $2/admin --config ./hab_admin.json --process ./hab_admin.lua diff --git a/webUI/README.md b/webUI/README.md new file mode 100644 index 0000000..cb1162f --- /dev/null +++ b/webUI/README.md @@ -0,0 +1,148 @@ +# webUI + +![HabBoy](../docs/HabBoy_Habdec.jpg) + +```webUI``` is a HabBoy GUI in a web browser: +* connects to ```data_server``` for payload telemetry +* displays any nuber HabDec interfaces +* displays OSM map with payload and HabBoy location +* displays google map with navigation route +* displays graphs and gauges with telemetry using [highcharts.js](https://www.highcharts.com/) +* Displays Habitat SSDV + +# Installation +```webUI``` should be server with any web server, ie. apache. +Opening ```index.html``` directly from disk might not work due to CORS restrictions. + +For testing, you can start simple python server: +``` +cd webUI/code +python -m http.server 80 +``` +Then open browser and go to http://localhost + +For example, if you use apache: +```ln -s ~/habboy/webUI/code /var/www/html/habboy``` + +Web UI is then available under URL ```http://habboy/habboy``` + +# User Interface +User Interface is divided in two parts. At the bottom is ```status bar```. +Rest of the UI area is many tabs(Habdec, maps, etc.) that can be switched with buttons at right side of screen. + +## Status Bar +```status bar``` is located at the bottom of the screen. + +First line displays payload information: + +* callsign +* altitude [max altitude] +* ascent rate m/s +* horizontal speed km/h +* GPS fix age (time since last GPS fix) +* last payload sentence age + +Color of the payload line has meaning: +* green - 0-60 seconds age +* orange - 60-120 seconds age +* red - more than 120 seconds age + +Second line displays information about HabBoy device: + +* distance to payload +* payload elevation +* azimuth to payload +* HabBoy vehuicle speed km/h +* GPS fix age +* GPS packet age + + +## Tabs +Right side of screen is a column of buttons. Each button is a tab. +Custom tabs can be added by editing ```HABBOY.js``` file. + +## Tab - HabDec +HabBoy can display multiple HabDec interfaces, one per radio/connection. +Each instance will have it's own TAB named ```Radio XXX```, where XXX is last octed of HabDec IP address. + +To install HabDec into HabBoy, create symlink (or copy): +``` +cd ./habboy_sw/webUI +ln -s ~/habdec/code/webClient ./habdec_gui +``` + +To add new habBoy TAB, open URL: +```http://habboy:8888/habboy/api/v1/habdec/add/192.168.1.100:5555``` +Where 192.168.1.100:5555 is addr:port oh running habdec websocketServer. + +## Tab - Map +```Tab Map``` is OpenStreetMap vetor tiles map with location of payload, HabBoy device and predicted land spot. + +To work correctly you must: +* install cusf and wind data as described in [data_server](../data_server/README.md) +* prepare and install vector tiles as described [here](../docs/VECTOR_TILES.md) + +## Tab - Google Maps + +To enable, edit ```webUI\code\js\HB_google_map.js``` file and fill your google API key in ```GMAPS_API_KEY``` variable. + +You can uncomment ```HG_GoogleMap_NavigationUpdate()``` function call to enable google navigation. This needs more work however and is a mere experiment now. + +## Tab - Control +Various HabBoy settings. + +### Nav +Copy payload lat,lon to clipboard + +### Chase Car +Upload HabBoy GPS position to Habitat (as chasecar) + +### Payloads... +Select payload to track. These are payloads saved in ```data_server``` DB. + +### Device -> habdec_start / habdec_stop +start/stop HabDec daemon + +### Device -> spy_start / spy_stop +start/stop SpyServer daemon + +### Device -> restart +restart all daemons (habboy and habdec) + +### Device -> reboot +reboot computer + +### Device -> halt +stop computer + +## Directory Structure +Below is a dir structure of ```/var/www/html``` + +``` +~ www tree -d -l -L 4 . +. +└── html + ├── habboy -> /home/pi/share/dev/habboy/habboy_sw/webUI/code + │   ├── css + │   ├── habdec_gui -> /home/pi/share/dev/habdec/habdec/code/webClient + │   │   ├── css + │   │   └── js + │   ├── img + │   └── js + │   └── highcharts + ├── osm + │   ├── font -> /home/pi/share/data/osm/font/klokantech/font + │   │   ├── Klokantech Noto Sans Bold + │   │   ├── ... + │   │   └── Roboto Thin-Italic + │   └── tiles -> /home/pi/share/data/osm/poland_layered/3 + │   ├── admin + │   ├── aeroway + │   ├── buildings + │   ├── labels + │   ├── landuse + │   ├── roads + │   └── water + └── ssdv + └── gallery +``` \ No newline at end of file diff --git a/webUI/code/css/HABBOY.css b/webUI/code/css/HABBOY.css new file mode 100644 index 0000000..aab237e --- /dev/null +++ b/webUI/code/css/HABBOY.css @@ -0,0 +1,110 @@ + + +body, html { + width: 100%; + /* height: 90vh; */ + margin: 0; + padding: 0; + font-family: 'Open Sans', sans-serif; + background-color: #000; +} + + +.HABBOY_MAIN_DIV { + /* height: 100%; */ +} + + +/* single TAB container */ +.HB_TAB_DIV { + display: flex; + width: 100%; + height: 100%; +} + +/* dov created in tab builder functions */ +.HB_TAB_CONTENT_DIV { + display: flex; + width: 100%; + height: 100%; +} + +/* bottom */ +.HB_STATUS_BAR_DIV { + /* display: flex; */ + background-color: var(--HB_tab_button); + color: var(--HB_text); +} + + +/* top TABS buttons */ +.HB_TAB_BUTTON { + background-color: var(--HB_tab_button); + color: var(--HB_text); + margin: 1px; + border: solid; + border-color: var(--HB_tab_button_border); + border-radius: 10px; + cursor: pointer; + font-size: 22px; +} + +button { + flex: auto; + background-color: var(--HB_button); + color: var(--HB_text); + border: solid; + border-color: var(--HB_button_border); + border-radius: 10px; + cursor: pointer; + font-size: 22px; +} + +img { + width: 100%; + object-fit: contain; +} + + +.HB_modal_submenu_bg { + position: fixed; + left: 0; + top: 0; + width: 100%; + height: 100%; + /* overflow: auto; */ + /* z-index: 1; */ + background-color: var(--HB_bg); +} + + +.HB_modal_submenu_div { + position: fixed; + left: 10%; + top: 10%; + width: 80%; + height: 80%; +} + +table, th, td { + border: 1px solid var(--HB_button_border); + border-collapse: collapse; + /* width: 70%; */ + margin-left: auto; + margin-right: auto; +} + +p { + color: var(--HB_text); + text-align: center; + margin: 5px; + font-size: 20px; + +} + +th > p, td > p { + color: var(--HB_text); + text-align: center; + margin: 5px; + font-size: 25px; +} \ No newline at end of file diff --git a/webUI/code/css/HABBOY_colors_basic.css b/webUI/code/css/HABBOY_colors_basic.css new file mode 100644 index 0000000..00462f3 --- /dev/null +++ b/webUI/code/css/HABBOY_colors_basic.css @@ -0,0 +1,20 @@ + +:root { + --HB_bg: hsl(210, 15%, 14%); + --HB_text: #eee; + --HB_text_highlight: hsl(32, 93%, 45%); + + --HB_tab_button:rgb(31, 62, 93); + --HB_tab_button_active:#bb0; + --HB_tab_button_text:#eee; + --HB_tab_button_active_text:#000; + --HB_tab_button_border:rgb(31, 62, 93); + --HB_tab_button_border_highlight:#b80; + + --HB_button:rgb(31, 62, 93); + --HB_button_active:#990; + --HB_button_text:#ccc; + --HB_button_active_text:#000; + --HB_button_border:#000; +} + diff --git a/webUI/code/css/mapbox-gl.css b/webUI/code/css/mapbox-gl.css new file mode 100644 index 0000000..0221a0d --- /dev/null +++ b/webUI/code/css/mapbox-gl.css @@ -0,0 +1 @@ +.mapboxgl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgba(0,0,0,0)}.mapboxgl-canvas{position:absolute;left:0;top:0}.mapboxgl-map:-webkit-full-screen{width:100%;height:100%}.mapboxgl-canary{background-color:salmon}.mapboxgl-canvas-container.mapboxgl-interactive,.mapboxgl-ctrl-group button.mapboxgl-ctrl-compass{cursor:-webkit-grab;cursor:-moz-grab;cursor:grab;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none}.mapboxgl-canvas-container.mapboxgl-interactive.mapboxgl-track-pointer{cursor:pointer}.mapboxgl-canvas-container.mapboxgl-interactive:active,.mapboxgl-ctrl-group button.mapboxgl-ctrl-compass:active{cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate,.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate .mapboxgl-canvas{touch-action:pan-x pan-y}.mapboxgl-canvas-container.mapboxgl-touch-drag-pan,.mapboxgl-canvas-container.mapboxgl-touch-drag-pan .mapboxgl-canvas{touch-action:pinch-zoom}.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate.mapboxgl-touch-drag-pan,.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate.mapboxgl-touch-drag-pan .mapboxgl-canvas{touch-action:none}.mapboxgl-ctrl-bottom-left,.mapboxgl-ctrl-bottom-right,.mapboxgl-ctrl-top-left,.mapboxgl-ctrl-top-right{position:absolute;pointer-events:none;z-index:2}.mapboxgl-ctrl-top-left{top:0;left:0}.mapboxgl-ctrl-top-right{top:0;right:0}.mapboxgl-ctrl-bottom-left{bottom:0;left:0}.mapboxgl-ctrl-bottom-right{right:0;bottom:0}.mapboxgl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.mapboxgl-ctrl-top-left .mapboxgl-ctrl{margin:10px 0 0 10px;float:left}.mapboxgl-ctrl-top-right .mapboxgl-ctrl{margin:10px 10px 0 0;float:right}.mapboxgl-ctrl-bottom-left .mapboxgl-ctrl{margin:0 0 10px 10px;float:left}.mapboxgl-ctrl-bottom-right .mapboxgl-ctrl{margin:0 10px 10px 0;float:right}.mapboxgl-ctrl-group{border-radius:4px;background:#fff}.mapboxgl-ctrl-group:not(:empty){-moz-box-shadow:0 0 2px rgba(0,0,0,.1);-webkit-box-shadow:0 0 2px rgba(0,0,0,.1);box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (-ms-high-contrast:active){.mapboxgl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.mapboxgl-ctrl-group button{width:29px;height:29px;display:block;padding:0;outline:none;border:0;box-sizing:border-box;background-color:transparent;cursor:pointer}.mapboxgl-ctrl-group button+button{border-top:1px solid #ddd}.mapboxgl-ctrl button .mapboxgl-ctrl-icon{display:block;width:100%;height:100%;background-repeat:no-repeat;background-position:50%}@media (-ms-high-contrast:active){.mapboxgl-ctrl-icon{background-color:transparent}.mapboxgl-ctrl-group button+button{border-top:1px solid ButtonText}}.mapboxgl-ctrl button::-moz-focus-inner{border:0;padding:0}.mapboxgl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.mapboxgl-ctrl button:disabled{cursor:not-allowed}.mapboxgl-ctrl button:disabled .mapboxgl-ctrl-icon{opacity:.25}.mapboxgl-ctrl button:not(:disabled):hover{background-color:rgba(0,0,0,.05)}.mapboxgl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.mapboxgl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.mapboxgl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.mapboxgl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.mapboxgl-ctrl-group button:focus:only-child{border-radius:inherit}.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-out .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-9z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-in .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5z'/%3E%3C/svg%3E")}@media (-ms-high-contrast:active){.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-out .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-9z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-in .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5z'/%3E%3C/svg%3E")}}@media (-ms-high-contrast:black-on-white){.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-out .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-9z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-zoom-in .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5z'/%3E%3C/svg%3E")}}.mapboxgl-ctrl button.mapboxgl-ctrl-fullscreen .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3h1zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16h1zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5H13zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1V7.5z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-shrink .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1h-5.5zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1v-5.5zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1v5.5zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1h5.5z'/%3E%3C/svg%3E")}@media (-ms-high-contrast:active){.mapboxgl-ctrl button.mapboxgl-ctrl-fullscreen .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3h1zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16h1zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5H13zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1V7.5z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-shrink .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1h-5.5zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1v-5.5zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1v5.5zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1h5.5z'/%3E%3C/svg%3E")}}@media (-ms-high-contrast:black-on-white){.mapboxgl-ctrl button.mapboxgl-ctrl-fullscreen .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3h1zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16h1zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5H13zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1V7.5z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-shrink .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1h-5.5zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1v-5.5zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1v5.5zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1h5.5z'/%3E%3C/svg%3E")}}.mapboxgl-ctrl button.mapboxgl-ctrl-compass .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M10.5 14l4-8 4 8h-8z'/%3E%3Cpath d='M10.5 16l4 8 4-8h-8z' fill='%23ccc'/%3E%3C/svg%3E")}@media (-ms-high-contrast:active){.mapboxgl-ctrl button.mapboxgl-ctrl-compass .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M10.5 14l4-8 4 8h-8z'/%3E%3Cpath d='M10.5 16l4 8 4-8h-8z' fill='%23999'/%3E%3C/svg%3E")}}@media (-ms-high-contrast:black-on-white){.mapboxgl-ctrl button.mapboxgl-ctrl-compass .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 29 29' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M10.5 14l4-8 4 8h-8z'/%3E%3Cpath d='M10.5 16l4 8 4-8h-8z' fill='%23ccc'/%3E%3C/svg%3E")}}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23333'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate:disabled .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23aaa'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath d='M14 5l1 1-9 9-1-1 9-9z' fill='red'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%2333b5e5'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active-error .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23e58978'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%2333b5e5'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background-error .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23e54e33'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-waiting .mapboxgl-ctrl-icon{-webkit-animation:mapboxgl-spin 2s linear infinite;-moz-animation:mapboxgl-spin 2s infinite linear;-o-animation:mapboxgl-spin 2s infinite linear;-ms-animation:mapboxgl-spin 2s infinite linear;animation:mapboxgl-spin 2s linear infinite}@media (-ms-high-contrast:active){.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23fff'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate:disabled .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23999'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath d='M14 5l1 1-9 9-1-1 9-9z' fill='red'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%2333b5e5'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-active-error .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23e58978'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%2333b5e5'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate.mapboxgl-ctrl-geolocate-background-error .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23e54e33'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3C/svg%3E")}}@media (-ms-high-contrast:black-on-white){.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.mapboxgl-ctrl button.mapboxgl-ctrl-geolocate:disabled .mapboxgl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='29' height='29' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill='%23666'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 005.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 009 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 003.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0011 5.1V5s0-1-1-1zm0 2.5a3.5 3.5 0 110 7 3.5 3.5 0 110-7z'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath d='M14 5l1 1-9 9-1-1 9-9z' fill='red'/%3E%3C/svg%3E")}}@-webkit-keyframes mapboxgl-spin{0%{-webkit-transform:rotate(0deg)}to{-webkit-transform:rotate(1turn)}}@-moz-keyframes mapboxgl-spin{0%{-moz-transform:rotate(0deg)}to{-moz-transform:rotate(1turn)}}@-o-keyframes mapboxgl-spin{0%{-o-transform:rotate(0deg)}to{-o-transform:rotate(1turn)}}@-ms-keyframes mapboxgl-spin{0%{-ms-transform:rotate(0deg)}to{-ms-transform:rotate(1turn)}}@keyframes mapboxgl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.mapboxgl-ctrl-logo{width:88px;height:23px;margin:0 0 -4px -4px;display:block;background-repeat:no-repeat;cursor:pointer;overflow:hidden;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='88' height='23' viewBox='0 0 88 23' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' fill-rule='evenodd'%3E%3Cdefs%3E%3Cpath id='a' d='M11.5 2.25c5.105 0 9.25 4.145 9.25 9.25s-4.145 9.25-9.25 9.25-9.25-4.145-9.25-9.25 4.145-9.25 9.25-9.25zM6.997 15.983c-.051-.338-.828-5.802 2.233-8.873a4.395 4.395 0 013.13-1.28c1.27 0 2.49.51 3.39 1.42.91.9 1.42 2.12 1.42 3.39 0 1.18-.449 2.301-1.28 3.13C12.72 16.93 7 16 7 16l-.003-.017zM15.3 10.5l-2 .8-.8 2-.8-2-2-.8 2-.8.8-2 .8 2 2 .8z'/%3E%3Cpath id='b' d='M50.63 8c.13 0 .23.1.23.23V9c.7-.76 1.7-1.18 2.73-1.18 2.17 0 3.95 1.85 3.95 4.17s-1.77 4.19-3.94 4.19c-1.04 0-2.03-.43-2.74-1.18v3.77c0 .13-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V8.23c0-.12.1-.23.23-.23h1.4zm-3.86.01c.01 0 .01 0 .01-.01.13 0 .22.1.22.22v7.55c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V15c-.7.76-1.69 1.19-2.73 1.19-2.17 0-3.94-1.87-3.94-4.19 0-2.32 1.77-4.19 3.94-4.19 1.03 0 2.02.43 2.73 1.18v-.75c0-.12.1-.23.23-.23h1.4zm26.375-.19a4.24 4.24 0 00-4.16 3.29c-.13.59-.13 1.19 0 1.77a4.233 4.233 0 004.17 3.3c2.35 0 4.26-1.87 4.26-4.19 0-2.32-1.9-4.17-4.27-4.17zM60.63 5c.13 0 .23.1.23.23v3.76c.7-.76 1.7-1.18 2.73-1.18 1.88 0 3.45 1.4 3.84 3.28.13.59.13 1.2 0 1.8-.39 1.88-1.96 3.29-3.84 3.29-1.03 0-2.02-.43-2.73-1.18v.77c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V5.23c0-.12.1-.23.23-.23h1.4zm-34 11h-1.4c-.13 0-.23-.11-.23-.23V8.22c.01-.13.1-.22.23-.22h1.4c.13 0 .22.11.23.22v.68c.5-.68 1.3-1.09 2.16-1.1h.03c1.09 0 2.09.6 2.6 1.55.45-.95 1.4-1.55 2.44-1.56 1.62 0 2.93 1.25 2.9 2.78l.03 5.2c0 .13-.1.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.8 0-1.46.7-1.59 1.62l.01 4.68c0 .13-.11.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.85 0-1.54.79-1.6 1.8v4.5c0 .13-.1.23-.23.23zm53.615 0h-1.61c-.04 0-.08-.01-.12-.03-.09-.06-.13-.19-.06-.28l2.43-3.71-2.39-3.65a.213.213 0 01-.03-.12c0-.12.09-.21.21-.21h1.61c.13 0 .24.06.3.17l1.41 2.37 1.4-2.37a.34.34 0 01.3-.17h1.6c.04 0 .08.01.12.03.09.06.13.19.06.28l-2.37 3.65 2.43 3.7c0 .05.01.09.01.13 0 .12-.09.21-.21.21h-1.61c-.13 0-.24-.06-.3-.17l-1.44-2.42-1.44 2.42a.34.34 0 01-.3.17zm-7.12-1.49c-1.33 0-2.42-1.12-2.42-2.51 0-1.39 1.08-2.52 2.42-2.52 1.33 0 2.42 1.12 2.42 2.51 0 1.39-1.08 2.51-2.42 2.52zm-19.865 0c-1.32 0-2.39-1.11-2.42-2.48v-.07c.02-1.38 1.09-2.49 2.4-2.49 1.32 0 2.41 1.12 2.41 2.51 0 1.39-1.07 2.52-2.39 2.53zm-8.11-2.48c-.01 1.37-1.09 2.47-2.41 2.47s-2.42-1.12-2.42-2.51c0-1.39 1.08-2.52 2.4-2.52 1.33 0 2.39 1.11 2.41 2.48l.02.08zm18.12 2.47c-1.32 0-2.39-1.11-2.41-2.48v-.06c.02-1.38 1.09-2.48 2.41-2.48s2.42 1.12 2.42 2.51c0 1.39-1.09 2.51-2.42 2.51z'/%3E%3C/defs%3E%3Cmask id='c'%3E%3Crect width='100%25' height='100%25' fill='%23fff'/%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/mask%3E%3Cg opacity='.3' stroke='%23000' stroke-width='3'%3E%3Ccircle mask='url(%23c)' cx='11.5' cy='11.5' r='9.25'/%3E%3Cuse xlink:href='%23b' mask='url(%23c)'/%3E%3C/g%3E%3Cg opacity='.9' fill='%23fff'%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/g%3E%3C/svg%3E")}a.mapboxgl-ctrl-logo.mapboxgl-compact{width:23px}@media (-ms-high-contrast:active){a.mapboxgl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='88' height='23' viewBox='0 0 88 23' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' fill-rule='evenodd'%3E%3Cdefs%3E%3Cpath id='a' d='M11.5 2.25c5.105 0 9.25 4.145 9.25 9.25s-4.145 9.25-9.25 9.25-9.25-4.145-9.25-9.25 4.145-9.25 9.25-9.25zM6.997 15.983c-.051-.338-.828-5.802 2.233-8.873a4.395 4.395 0 013.13-1.28c1.27 0 2.49.51 3.39 1.42.91.9 1.42 2.12 1.42 3.39 0 1.18-.449 2.301-1.28 3.13C12.72 16.93 7 16 7 16l-.003-.017zM15.3 10.5l-2 .8-.8 2-.8-2-2-.8 2-.8.8-2 .8 2 2 .8z'/%3E%3Cpath id='b' d='M50.63 8c.13 0 .23.1.23.23V9c.7-.76 1.7-1.18 2.73-1.18 2.17 0 3.95 1.85 3.95 4.17s-1.77 4.19-3.94 4.19c-1.04 0-2.03-.43-2.74-1.18v3.77c0 .13-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V8.23c0-.12.1-.23.23-.23h1.4zm-3.86.01c.01 0 .01 0 .01-.01.13 0 .22.1.22.22v7.55c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V15c-.7.76-1.69 1.19-2.73 1.19-2.17 0-3.94-1.87-3.94-4.19 0-2.32 1.77-4.19 3.94-4.19 1.03 0 2.02.43 2.73 1.18v-.75c0-.12.1-.23.23-.23h1.4zm26.375-.19a4.24 4.24 0 00-4.16 3.29c-.13.59-.13 1.19 0 1.77a4.233 4.233 0 004.17 3.3c2.35 0 4.26-1.87 4.26-4.19 0-2.32-1.9-4.17-4.27-4.17zM60.63 5c.13 0 .23.1.23.23v3.76c.7-.76 1.7-1.18 2.73-1.18 1.88 0 3.45 1.4 3.84 3.28.13.59.13 1.2 0 1.8-.39 1.88-1.96 3.29-3.84 3.29-1.03 0-2.02-.43-2.73-1.18v.77c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V5.23c0-.12.1-.23.23-.23h1.4zm-34 11h-1.4c-.13 0-.23-.11-.23-.23V8.22c.01-.13.1-.22.23-.22h1.4c.13 0 .22.11.23.22v.68c.5-.68 1.3-1.09 2.16-1.1h.03c1.09 0 2.09.6 2.6 1.55.45-.95 1.4-1.55 2.44-1.56 1.62 0 2.93 1.25 2.9 2.78l.03 5.2c0 .13-.1.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.8 0-1.46.7-1.59 1.62l.01 4.68c0 .13-.11.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.85 0-1.54.79-1.6 1.8v4.5c0 .13-.1.23-.23.23zm53.615 0h-1.61c-.04 0-.08-.01-.12-.03-.09-.06-.13-.19-.06-.28l2.43-3.71-2.39-3.65a.213.213 0 01-.03-.12c0-.12.09-.21.21-.21h1.61c.13 0 .24.06.3.17l1.41 2.37 1.4-2.37a.34.34 0 01.3-.17h1.6c.04 0 .08.01.12.03.09.06.13.19.06.28l-2.37 3.65 2.43 3.7c0 .05.01.09.01.13 0 .12-.09.21-.21.21h-1.61c-.13 0-.24-.06-.3-.17l-1.44-2.42-1.44 2.42a.34.34 0 01-.3.17zm-7.12-1.49c-1.33 0-2.42-1.12-2.42-2.51 0-1.39 1.08-2.52 2.42-2.52 1.33 0 2.42 1.12 2.42 2.51 0 1.39-1.08 2.51-2.42 2.52zm-19.865 0c-1.32 0-2.39-1.11-2.42-2.48v-.07c.02-1.38 1.09-2.49 2.4-2.49 1.32 0 2.41 1.12 2.41 2.51 0 1.39-1.07 2.52-2.39 2.53zm-8.11-2.48c-.01 1.37-1.09 2.47-2.41 2.47s-2.42-1.12-2.42-2.51c0-1.39 1.08-2.52 2.4-2.52 1.33 0 2.39 1.11 2.41 2.48l.02.08zm18.12 2.47c-1.32 0-2.39-1.11-2.41-2.48v-.06c.02-1.38 1.09-2.48 2.41-2.48s2.42 1.12 2.42 2.51c0 1.39-1.09 2.51-2.42 2.51z'/%3E%3C/defs%3E%3Cmask id='c'%3E%3Crect width='100%25' height='100%25' fill='%23fff'/%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/mask%3E%3Cg stroke='%23000' stroke-width='3'%3E%3Ccircle mask='url(%23c)' cx='11.5' cy='11.5' r='9.25'/%3E%3Cuse xlink:href='%23b' mask='url(%23c)'/%3E%3C/g%3E%3Cg fill='%23fff'%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/g%3E%3C/svg%3E")}}@media (-ms-high-contrast:black-on-white){a.mapboxgl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='88' height='23' viewBox='0 0 88 23' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' fill-rule='evenodd'%3E%3Cdefs%3E%3Cpath id='a' d='M11.5 2.25c5.105 0 9.25 4.145 9.25 9.25s-4.145 9.25-9.25 9.25-9.25-4.145-9.25-9.25 4.145-9.25 9.25-9.25zM6.997 15.983c-.051-.338-.828-5.802 2.233-8.873a4.395 4.395 0 013.13-1.28c1.27 0 2.49.51 3.39 1.42.91.9 1.42 2.12 1.42 3.39 0 1.18-.449 2.301-1.28 3.13C12.72 16.93 7 16 7 16l-.003-.017zM15.3 10.5l-2 .8-.8 2-.8-2-2-.8 2-.8.8-2 .8 2 2 .8z'/%3E%3Cpath id='b' d='M50.63 8c.13 0 .23.1.23.23V9c.7-.76 1.7-1.18 2.73-1.18 2.17 0 3.95 1.85 3.95 4.17s-1.77 4.19-3.94 4.19c-1.04 0-2.03-.43-2.74-1.18v3.77c0 .13-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V8.23c0-.12.1-.23.23-.23h1.4zm-3.86.01c.01 0 .01 0 .01-.01.13 0 .22.1.22.22v7.55c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V15c-.7.76-1.69 1.19-2.73 1.19-2.17 0-3.94-1.87-3.94-4.19 0-2.32 1.77-4.19 3.94-4.19 1.03 0 2.02.43 2.73 1.18v-.75c0-.12.1-.23.23-.23h1.4zm26.375-.19a4.24 4.24 0 00-4.16 3.29c-.13.59-.13 1.19 0 1.77a4.233 4.233 0 004.17 3.3c2.35 0 4.26-1.87 4.26-4.19 0-2.32-1.9-4.17-4.27-4.17zM60.63 5c.13 0 .23.1.23.23v3.76c.7-.76 1.7-1.18 2.73-1.18 1.88 0 3.45 1.4 3.84 3.28.13.59.13 1.2 0 1.8-.39 1.88-1.96 3.29-3.84 3.29-1.03 0-2.02-.43-2.73-1.18v.77c0 .12-.1.23-.23.23h-1.4c-.13 0-.23-.1-.23-.23V5.23c0-.12.1-.23.23-.23h1.4zm-34 11h-1.4c-.13 0-.23-.11-.23-.23V8.22c.01-.13.1-.22.23-.22h1.4c.13 0 .22.11.23.22v.68c.5-.68 1.3-1.09 2.16-1.1h.03c1.09 0 2.09.6 2.6 1.55.45-.95 1.4-1.55 2.44-1.56 1.62 0 2.93 1.25 2.9 2.78l.03 5.2c0 .13-.1.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.8 0-1.46.7-1.59 1.62l.01 4.68c0 .13-.11.23-.23.23h-1.41c-.13 0-.23-.11-.23-.23v-4.59c0-.98-.74-1.71-1.62-1.71-.85 0-1.54.79-1.6 1.8v4.5c0 .13-.1.23-.23.23zm53.615 0h-1.61c-.04 0-.08-.01-.12-.03-.09-.06-.13-.19-.06-.28l2.43-3.71-2.39-3.65a.213.213 0 01-.03-.12c0-.12.09-.21.21-.21h1.61c.13 0 .24.06.3.17l1.41 2.37 1.4-2.37a.34.34 0 01.3-.17h1.6c.04 0 .08.01.12.03.09.06.13.19.06.28l-2.37 3.65 2.43 3.7c0 .05.01.09.01.13 0 .12-.09.21-.21.21h-1.61c-.13 0-.24-.06-.3-.17l-1.44-2.42-1.44 2.42a.34.34 0 01-.3.17zm-7.12-1.49c-1.33 0-2.42-1.12-2.42-2.51 0-1.39 1.08-2.52 2.42-2.52 1.33 0 2.42 1.12 2.42 2.51 0 1.39-1.08 2.51-2.42 2.52zm-19.865 0c-1.32 0-2.39-1.11-2.42-2.48v-.07c.02-1.38 1.09-2.49 2.4-2.49 1.32 0 2.41 1.12 2.41 2.51 0 1.39-1.07 2.52-2.39 2.53zm-8.11-2.48c-.01 1.37-1.09 2.47-2.41 2.47s-2.42-1.12-2.42-2.51c0-1.39 1.08-2.52 2.4-2.52 1.33 0 2.39 1.11 2.41 2.48l.02.08zm18.12 2.47c-1.32 0-2.39-1.11-2.41-2.48v-.06c.02-1.38 1.09-2.48 2.41-2.48s2.42 1.12 2.42 2.51c0 1.39-1.09 2.51-2.42 2.51z'/%3E%3C/defs%3E%3Cmask id='c'%3E%3Crect width='100%25' height='100%25' fill='%23fff'/%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/mask%3E%3Cg stroke='%23fff' stroke-width='3' fill='%23fff'%3E%3Ccircle mask='url(%23c)' cx='11.5' cy='11.5' r='9.25'/%3E%3Cuse xlink:href='%23b' mask='url(%23c)'/%3E%3C/g%3E%3Cuse xlink:href='%23a'/%3E%3Cuse xlink:href='%23b'/%3E%3C/svg%3E")}}.mapboxgl-ctrl.mapboxgl-ctrl-attrib{padding:0 5px;background-color:hsla(0,0%,100%,.5);margin:0}@media screen{.mapboxgl-ctrl-attrib.mapboxgl-compact{min-height:20px;padding:0;margin:10px;position:relative;background-color:#fff;border-radius:3px 12px 12px 3px}.mapboxgl-ctrl-attrib.mapboxgl-compact:hover{padding:2px 24px 2px 4px;visibility:visible;margin-top:6px}.mapboxgl-ctrl-bottom-left>.mapboxgl-ctrl-attrib.mapboxgl-compact:hover,.mapboxgl-ctrl-top-left>.mapboxgl-ctrl-attrib.mapboxgl-compact:hover{padding:2px 4px 2px 24px;border-radius:12px 3px 3px 12px}.mapboxgl-ctrl-attrib.mapboxgl-compact .mapboxgl-ctrl-attrib-inner{display:none}.mapboxgl-ctrl-attrib.mapboxgl-compact:hover .mapboxgl-ctrl-attrib-inner{display:block}.mapboxgl-ctrl-attrib.mapboxgl-compact:after{content:"";cursor:pointer;position:absolute;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='24' height='24' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill-rule='evenodd'%3E%3Cpath d='M4 10a6 6 0 1012 0 6 6 0 10-12 0m5-3a1 1 0 102 0 1 1 0 10-2 0m0 3a1 1 0 112 0v3a1 1 0 11-2 0'/%3E%3C/svg%3E");background-color:hsla(0,0%,100%,.5);width:24px;height:24px;box-sizing:border-box;border-radius:12px}.mapboxgl-ctrl-bottom-right>.mapboxgl-ctrl-attrib.mapboxgl-compact:after{bottom:0;right:0}.mapboxgl-ctrl-top-right>.mapboxgl-ctrl-attrib.mapboxgl-compact:after{top:0;right:0}.mapboxgl-ctrl-top-left>.mapboxgl-ctrl-attrib.mapboxgl-compact:after{top:0;left:0}.mapboxgl-ctrl-bottom-left>.mapboxgl-ctrl-attrib.mapboxgl-compact:after{bottom:0;left:0}}@media screen and (-ms-high-contrast:active){.mapboxgl-ctrl-attrib.mapboxgl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='24' height='24' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill-rule='evenodd' fill='%23fff'%3E%3Cpath d='M4 10a6 6 0 1012 0 6 6 0 10-12 0m5-3a1 1 0 102 0 1 1 0 10-2 0m0 3a1 1 0 112 0v3a1 1 0 11-2 0'/%3E%3C/svg%3E")}}@media screen and (-ms-high-contrast:black-on-white){.mapboxgl-ctrl-attrib.mapboxgl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg width='24' height='24' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg' fill-rule='evenodd'%3E%3Cpath d='M4 10a6 6 0 1012 0 6 6 0 10-12 0m5-3a1 1 0 102 0 1 1 0 10-2 0m0 3a1 1 0 112 0v3a1 1 0 11-2 0'/%3E%3C/svg%3E")}}.mapboxgl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.mapboxgl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.mapboxgl-ctrl-attrib .mapbox-improve-map{font-weight:700;margin-left:2px}.mapboxgl-attrib-empty{display:none}.mapboxgl-ctrl-scale{background-color:hsla(0,0%,100%,.75);font-size:10px;border:2px solid #333;border-top:#333;padding:0 5px;color:#333;box-sizing:border-box}.mapboxgl-popup{position:absolute;top:0;left:0;display:-webkit-flex;display:flex;will-change:transform;pointer-events:none}.mapboxgl-popup-anchor-top,.mapboxgl-popup-anchor-top-left,.mapboxgl-popup-anchor-top-right{-webkit-flex-direction:column;flex-direction:column}.mapboxgl-popup-anchor-bottom,.mapboxgl-popup-anchor-bottom-left,.mapboxgl-popup-anchor-bottom-right{-webkit-flex-direction:column-reverse;flex-direction:column-reverse}.mapboxgl-popup-anchor-left{-webkit-flex-direction:row;flex-direction:row}.mapboxgl-popup-anchor-right{-webkit-flex-direction:row-reverse;flex-direction:row-reverse}.mapboxgl-popup-tip{width:0;height:0;border:10px solid transparent;z-index:1}.mapboxgl-popup-anchor-top .mapboxgl-popup-tip{-webkit-align-self:center;align-self:center;border-top:none;border-bottom-color:#fff}.mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip{-webkit-align-self:flex-start;align-self:flex-start;border-top:none;border-left:none;border-bottom-color:#fff}.mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip{-webkit-align-self:flex-end;align-self:flex-end;border-top:none;border-right:none;border-bottom-color:#fff}.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip{-webkit-align-self:center;align-self:center;border-bottom:none;border-top-color:#fff}.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip{-webkit-align-self:flex-start;align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip{-webkit-align-self:flex-end;align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.mapboxgl-popup-anchor-left .mapboxgl-popup-tip{-webkit-align-self:center;align-self:center;border-left:none;border-right-color:#fff}.mapboxgl-popup-anchor-right .mapboxgl-popup-tip{-webkit-align-self:center;align-self:center;border-right:none;border-left-color:#fff}.mapboxgl-popup-close-button{position:absolute;right:0;top:0;border:0;border-radius:0 3px 0 0;cursor:pointer;background-color:transparent}.mapboxgl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.mapboxgl-popup-content{position:relative;background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:10px 10px 15px;pointer-events:auto}.mapboxgl-popup-anchor-top-left .mapboxgl-popup-content{border-top-left-radius:0}.mapboxgl-popup-anchor-top-right .mapboxgl-popup-content{border-top-right-radius:0}.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-content{border-bottom-left-radius:0}.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-content{border-bottom-right-radius:0}.mapboxgl-popup-track-pointer{display:none}.mapboxgl-popup-track-pointer *{pointer-events:none;user-select:none}.mapboxgl-map:hover .mapboxgl-popup-track-pointer{display:flex}.mapboxgl-map:active .mapboxgl-popup-track-pointer{display:none}.mapboxgl-marker{position:absolute;top:0;left:0;will-change:transform}.mapboxgl-user-location-dot,.mapboxgl-user-location-dot:before{background-color:#1da1f2;width:15px;height:15px;border-radius:50%}.mapboxgl-user-location-dot:before{content:"";position:absolute;-webkit-animation:mapboxgl-user-location-dot-pulse 2s infinite;-moz-animation:mapboxgl-user-location-dot-pulse 2s infinite;-ms-animation:mapboxgl-user-location-dot-pulse 2s infinite;animation:mapboxgl-user-location-dot-pulse 2s infinite}.mapboxgl-user-location-dot:after{border-radius:50%;border:2px solid #fff;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px;box-sizing:border-box;box-shadow:0 0 3px rgba(0,0,0,.35)}@-webkit-keyframes mapboxgl-user-location-dot-pulse{0%{-webkit-transform:scale(1);opacity:1}70%{-webkit-transform:scale(3);opacity:0}to{-webkit-transform:scale(1);opacity:0}}@-ms-keyframes mapboxgl-user-location-dot-pulse{0%{-ms-transform:scale(1);opacity:1}70%{-ms-transform:scale(3);opacity:0}to{-ms-transform:scale(1);opacity:0}}@keyframes mapboxgl-user-location-dot-pulse{0%{transform:scale(1);opacity:1}70%{transform:scale(3);opacity:0}to{transform:scale(1);opacity:0}}.mapboxgl-user-location-dot-stale{background-color:#aaa}.mapboxgl-user-location-dot-stale:after{display:none}.mapboxgl-user-location-accuracy-circle{background-color:rgba(29,161,242,.2);width:1px;height:1px;border-radius:100%}.mapboxgl-crosshair,.mapboxgl-crosshair .mapboxgl-interactive,.mapboxgl-crosshair .mapboxgl-interactive:active{cursor:crosshair}.mapboxgl-boxzoom{position:absolute;top:0;left:0;width:0;height:0;background:#fff;border:2px dotted #202020;opacity:.5}@media print{.mapbox-improve-map{display:none}} \ No newline at end of file diff --git a/webUI/code/dummyButtonsServer.py b/webUI/code/dummyButtonsServer.py new file mode 100644 index 0000000..e7d977c --- /dev/null +++ b/webUI/code/dummyButtonsServer.py @@ -0,0 +1,5 @@ +#!/usr/bin/python + +import sys + +print(sys.argv) \ No newline at end of file diff --git a/webUI/code/img/balloon.png b/webUI/code/img/balloon.png new file mode 100644 index 0000000..19f4010 Binary files /dev/null and b/webUI/code/img/balloon.png differ diff --git a/webUI/code/img/car.png b/webUI/code/img/car.png new file mode 100644 index 0000000..95429b1 Binary files /dev/null and b/webUI/code/img/car.png differ diff --git a/webUI/code/img/test.jpg b/webUI/code/img/test.jpg new file mode 100644 index 0000000..1043916 Binary files /dev/null and b/webUI/code/img/test.jpg differ diff --git a/webUI/code/img/test2.jpg b/webUI/code/img/test2.jpg new file mode 100644 index 0000000..f7bce64 Binary files /dev/null and b/webUI/code/img/test2.jpg differ diff --git a/webUI/code/index.html b/webUI/code/index.html new file mode 100644 index 0000000..6a73503 --- /dev/null +++ b/webUI/code/index.html @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + HABBOY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + \ No newline at end of file diff --git a/webUI/code/js/HABBOY.js b/webUI/code/js/HABBOY.js new file mode 100644 index 0000000..eed47cc --- /dev/null +++ b/webUI/code/js/HABBOY.js @@ -0,0 +1,1165 @@ +// var HABBOY_URL = window.location.hostname; +// var HABBOY_DATA_URL = "https://" + HABBOY_URL + ":8888"; +var HABBOY_URL = window.location.origin; +if(HABBOY_URL == 'null') + HABBOY_URL = 'http://localhost'; +var HABBOY_HOST = window.location.hostname; + +var HABBOY_DATA_URL = new URL(HABBOY_URL); +HABBOY_DATA_URL.port = '8888'; +HABBOY_DATA_URL = HABBOY_DATA_URL.toString(); +HABBOY_DATA_URL = HABBOY_DATA_URL.substr(0, HABBOY_DATA_URL.length-1); + +console.debug('HABBOY_URL ', HABBOY_URL); +console.debug('HABBOY_HOST ', HABBOY_HOST); +console.debug('HABBOY_DATA_URL ', HABBOY_DATA_URL); + +var HABBOY_PARAMS = {}; // parameters from data server +var HABBOY_PAYLOAD_ID = "NO_PAYLOAD"; // this will be set on HABBOY_INIT(), by query to DATA server +var HABBOY_PAYLOAD_CALLSIGN = ""; + +var HB_VEHICLES_TELEMETRY = {}; +var HB_VEHICLES_TELEMETRY_LAST = {}; // from last update - all values since "HB_VEHICLES_TELEMETRY_Update_LastTime" +var HB_VEHICLES_TELEMETRY_UpdateCallbacks = []; // funs to call on each telemetry update. parameter is payload's telemetry +var HB_VEHICLES_GPS_LAST = {}; //for payloads +var HB_VEHICLES_SENTENCE_LAST = {}; +var HB_VEHICLES_PREDICT = {}; // predicted path +var HB_VEHICLES_PREDICT_HABITAT = {}; // predicted path from HABITAT + +var HB_HABBOY_TIME_DIFF_mSECS = 0; // if negative, HabBoy server has lagging clock relative to here +var HB_HABBOY_INFO = {}; // various info on habboy status and health + +var HB_DEVICE_GPS_LAST = { + "HABBOY": { + 'time': '1970-01-01 12:00:00+00:00', + "latitude": 52.1, + "longitude": 21, + "altitude": 100, + 'ground_speed_mps': 0, // kmph + 'heading': 0, + 'sats': 0, + 'parse_timestamp': 0, // only for serial GPS from HabBoy + 'ascent_mps': 0, // m/s - calculated in HB_VEHICLES_TELEMETRY_Update + 'fix_age': 0, // seconds since last valid NMEA message received + 'data_age': 0 // seconds since last any NMEA message received + } +}; +HB_DEVICE_GPS_LAST["DEVICE"] = HB_DEVICE_GPS_LAST["HABBOY"]; + +var HB_TAB_BUILDERS_ARR = []; // FUNCTIONS - each build a new tab content +var HB_TAB_BUTTONS = []; +var HB_TAB_BUTTON_CURRENT = ""; +var HB_TAB_BUTTONS_WIDGET_NAV = {}; // indexed with tab_names (HB_TAB_BUTTON_CURRENT). keeps list of children widgets and it's nav info +var HABBOY_HABDEC_IFRAMES = []; + + +function toggleFullscreen() +{ + var elem = document.documentElement; + if (!document.fullscreenElement && !document.mozFullScreenElement && + !document.webkitFullscreenElement && !document.msFullscreenElement) + { + if (elem.requestFullscreen) { + elem.requestFullscreen(); + } else if (elem.msRequestFullscreen) { + elem.msRequestFullscreen(); + } else if (elem.mozRequestFullScreen) { + elem.mozRequestFullScreen(); + } else if (elem.webkitRequestFullscreen) { + elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); + } + } + else + { + if (document.exitFullscreen) { + document.exitFullscreen(); + } else if (document.msExitFullscreen) { + document.msExitFullscreen(); + } else if (document.mozCancelFullScreen) { + document.mozCancelFullScreen(); + } else if (document.webkitExitFullscreen) { + document.webkitExitFullscreen(); + } + } +} + +function HB_get_css_val(i_css) { + let root = document.querySelector(':root'); + let rootStyles = getComputedStyle(root); + return rootStyles.getPropertyValue(i_css); +} + +function HB_modal_submenu_fun(elements_list, parent_div) +{ + var button_onclick = function() { + var modal_bg = document.createElement("div"); + modal_bg.classList.add("HB_modal_submenu_bg"); + modal_bg.style.display = "flex"; + + var grid = document.createElement('div'); + grid.classList.add("HB_modal_submenu_div"); + grid.style.display = 'grid'; + grid.style.gridTemplateColumns = "auto auto auto auto "; + modal_bg.appendChild(grid); + + for(i in elements_list) + grid.appendChild( elements_list[i] ); + + var close_b = document.createElement("button"); + close_b.innerHTML = "X"; + close_b.onclick = function () { + modal_bg.innerHTML = ''; + modal_bg.parentElement.removeChild(modal_bg); + } + grid.appendChild( close_b ); + + parent_div.appendChild(modal_bg); + } + + return button_onclick; +} + + +function SentenceAge(i_sentence_time) { // isoformat 1970-01-01T12:00:00.0+00:00 + var sentence_time = Date.parse(i_sentence_time); + var now = new Date(Date.now()); + var t_diff_secs = (now-(sentence_time-HB_HABBOY_TIME_DIFF_mSECS)) / 1e3; + return t_diff_secs; +} + + +function bearing_to_dir_str(i_bear) { + var bearing_dir_name = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N']; + var bearing_dir_arrow = [8593, 8599, 8594, 8600, 8595, 8601, 8592, 8598, 8593]; + var a = i_bear + if (a < 0) + a += 360; + a = a % 360; + i = 1.0 * a / 360.0; + i = Math.round( i * (bearing_dir_name.length-1) ); + return bearing_dir_name[i] + String.fromCharCode(bearing_dir_arrow[i]); +} + + + +function CalcGpsDistance(lat1, lon1, alt1, lat2, lon2, alt2) +{ + /* + Calculate and return information from 2 (lat, lon, alt) points + Input and output latitudes, longitudes, angles, bearings and elevations are + in degrees, and input altitudes and output distances are in meters. + */ + + var radius = 6371000.0; // Earth radius in meters + var M_PI = Math.PI; + + // to radians + lat1 *= M_PI / 180.0; + lat2 *= M_PI / 180.0; + lon1 *= M_PI / 180.0; + lon2 *= M_PI / 180.0; + + // Calculate the bearing, the angle at the centre, and the great circle + // distance using Vincenty's_formulae with f = 0 (a sphere). See + // http://en.wikipedia.org/wiki/Great_circle_distance#Formulas and + // http://en.wikipedia.org/wiki/Great-circle_navigation and + // http://en.wikipedia.org/wiki/Vincenty%27s_formulae + var d_lon = lon2 - lon1; + var sa = Math.cos(lat2) * Math.sin(d_lon); + var sb = (Math.cos(lat1) * Math.sin(lat2)) - (Math.sin(lat1) * Math.cos(lat2) * Math.cos(d_lon)); + var bearing = Math.atan2(sa, sb); + var aa = Math.sqrt((sa*sa) + (sb*sb)); + var ab = (Math.sin(lat1) * Math.sin(lat2)) + (Math.cos(lat1) * Math.cos(lat2) * Math.cos(d_lon)); + var angle_at_centre = Math.atan2(aa, ab); + var great_circle_distance = angle_at_centre * radius; + + // Armed with the angle at the centre, calculating the remaining items + // is a simple 2D triangley circley problem: + + // Use the triangle with sides (r + alt1), (r + alt2), distance in a + // straight line. The angle between (r + alt1) and (r + alt2) is the + // angle at the centre. The angle between distance in a straight line and + // (r + alt1) is the elevation plus pi/2. + + // Use sum of angle in a triangle to express the third angle in terms + // of the other two. Use sine rule on sides (r + alt1) and (r + alt2), + // expand with compound angle formulae and solve for tan elevation by + // dividing both sides by cos elevation + var ta = radius + alt1; + var tb = radius + alt2; + var ea = (Math.cos(angle_at_centre) * tb) - ta; + var eb = Math.sin(angle_at_centre) * tb; + var elevation = Math.atan2(ea, eb); + + // Use cosine rule to find unknown side. + var line_distance = Math.sqrt((ta*ta) + (tb*tb) - 2 * tb * ta * Math.cos(angle_at_centre)); + + // Give a bearing in range 0 <= b < 2pi + if (bearing < 0) + bearing += 2 * M_PI; + + + var res = { + dist_line_: line_distance, + dist_circle_: great_circle_distance, + dist_radians_: angle_at_centre, + elevation_: elevation / ( M_PI / 180.0 ), + bearing_: bearing / ( M_PI / 180.0 ) + } + return res; + +} + +////////////////////////////////////////// +////////////////////////////////////////// +// // +// PROCEDURES TO BUILD CONTENT OF TABS // +// // +////////////////////////////////////////// +////////////////////////////////////////// + + +function HB_BuildStatusBar(status_bar_div) { + var payload_div = document.createElement("div"); + payload_div.id = "HB_StatusBar_payload_div" + payload_div.style.fontSize = "4.0vh"; + var habboy_div = document.createElement("div"); + habboy_div.id = "HB_StatusBar_habboy_div" + habboy_div.style.fontSize = "4.0vh"; + + status_bar_div.appendChild(payload_div); + status_bar_div.appendChild(habboy_div); + + HB_UpdateStatusBar(payload_div, habboy_div); +} + +function HB_UpdateStatusBar(payload_div, habboy_div) { + var sentence_age = 0; + var now = new Date(Date.now()); + + var payload_info = "No Telemetry - " + HABBOY_PAYLOAD_CALLSIGN + " - " + now + ""; + if(HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID] != undefined) + { + payload_info = '[' + HABBOY_PAYLOAD_CALLSIGN + "] "; + // payload_info += HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]["latitude"].toFixed(6) + " "; + // payload_info += HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]["longitude"].toFixed(6) + " "; + payload_info += HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]["altitude"].toFixed(0) + "m"; + + var _s = HB_VEHICLES_TELEMETRY_LAST[HABBOY_PAYLOAD_ID]['altitude']['values'].length; + payload_info += " (" + HB_VEHICLES_TELEMETRY_LAST[HABBOY_PAYLOAD_ID]['altitude']['max'][_s-1].toFixed(0) + "m)"; + + // ascent rate computed by habboy - based on incomming GPS altitudes + var ascent_rate = HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]['ascent_mps']; + var ascend_arrow = "↑" + if(ascent_rate<0) + ascend_arrow = "↓" + payload_info += " " + ascend_arrow + ascent_rate.toFixed(1); + + // ARY specific. display payload-computed ascentrate + try { + var payload_ascent_rate = HB_VEHICLES_TELEMETRY_LAST[HABBOY_PAYLOAD_ID]['ascentrate']['values'][_s-1]; + payload_info += "(" + payload_ascent_rate.toFixed(1) + ")"; + } catch(err) {} + payload_info += " m/s"; + + var speed_mps = HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]['ground_speed_mps']; + var speed_kmph = 3.6 * speed_mps; + payload_info += " →" + speed_kmph.toFixed(0) + " km/h"; + + // ARY Specific + try{ + var state = HB_VEHICLES_TELEMETRY_LAST[HABBOY_PAYLOAD_ID]['state']['values'][_s-1]; + payload_info += " S:" + state; + } catch(err) {} + + sentence_age = SentenceAge( HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]['time'] ); + sentence_age_str = Math.floor(sentence_age); + if(sentence_age>60) + sentence_age_str = new Date(1000 * sentence_age).toISOString().substr(11,8); + payload_info += " gps=" + sentence_age_str + "s"; + + var sentence_reception_timestamp = Date.parse( HB_VEHICLES_SENTENCE_LAST[HABBOY_PAYLOAD_ID]['_INSERT_TIME'] ); + var sentence_reception_age = (now - (sentence_reception_timestamp-HB_HABBOY_TIME_DIFF_mSECS)) / 1e3; + sentence_reception_age_str = Math.floor(sentence_reception_age); + if(sentence_reception_age>60) + sentence_reception_age_str = new Date(1000 * sentence_reception_age).toISOString().substr(11,8); + payload_info += " packet=" + sentence_reception_age_str + "s"; + } + + var habboy_info = "[HabBoy] "; + var habboy_fix_age = 0; + var habboy_data_age = 0; + if(HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID] != undefined) { + var payload_dist = CalcGpsDistance( HB_DEVICE_GPS_LAST['HABBOY']['latitude'], + HB_DEVICE_GPS_LAST['HABBOY']['longitude'], + HB_DEVICE_GPS_LAST['HABBOY']['altitude'], + HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]['latitude'], + HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]['longitude'], + HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]['altitude'] ); + var payload_dist_str = Math.round(payload_dist.dist_circle_) + "m"; + if(payload_dist.dist_circle_ > 1000) + payload_dist_str = (0.001 * payload_dist.dist_circle_).toFixed(1) + "km"; + habboy_info += " Dist: " + payload_dist_str; + habboy_info += " ∠: " + Math.round(payload_dist.elevation_).toFixed(0) + String.fromCharCode(176); + var heading = Math.round(payload_dist.bearing_).toFixed(); //HB_DEVICE_GPS_LAST['HABBOY']['heading'].toFixed(1); + if(heading > 180) + heading -= 360; + habboy_info += " Azimuth: " + heading + String.fromCharCode(176) + "" + bearing_to_dir_str(heading); + } + + habboy_info += " Speed: " + Math.round(3.6 * HB_DEVICE_GPS_LAST['HABBOY']['ground_speed_mps']).toFixed(0) + "km/h "; + habboy_fix_age = Math.round(HB_DEVICE_GPS_LAST['HABBOY']['fix_age']).toFixed(0); + habboy_fix_age_str = Math.floor(habboy_fix_age); + if(habboy_fix_age>60) + habboy_fix_age_str = new Date(1000 * habboy_fix_age).toISOString().substr(11,8); + + habboy_data_age = Math.round(HB_DEVICE_GPS_LAST['HABBOY']['data_age']).toFixed(0); + habboy_data_age_str = Math.floor(habboy_data_age); + if(habboy_data_age>60) + habboy_data_age_str = new Date(1000 * habboy_data_age).toISOString().substr(11,8); + + habboy_info += " gps=" + habboy_fix_age_str + "s packet=" + habboy_data_age_str; + + if(sentence_age > 120) + payload_div.innerHTML = '' + payload_info + ''; + else if(sentence_age > 60) + payload_div.innerHTML = '' + payload_info + ''; + else + payload_div.innerHTML = '' + payload_info + ''; + + if(habboy_fix_age > 5 || habboy_data_age > 5) + habboy_div.innerHTML = '' + habboy_info + ''; + else + habboy_div.innerHTML = '' + habboy_info + ''; + + setTimeout(() => { + HB_UpdateStatusBar(payload_div, habboy_div); + }, 1000); +} + + + + +function ExampleTabBuilder_img(parent_div, img_src) { + var img = document.createElement("img"); + img.src = img_src; + parent_div.appendChild(img); + +} + + +function HB_Habitat_SSDV(parent_div) { + var filter = ""; + // + var container = document.createElement("div"); + container.classList.add ("HB_TAB_CONTENT_DIV"); + container.innerHTML = ''; + parent_div.appendChild(container); + // return "SSDV"; + return {"tab_name": "SSDV-G", "tab_nav": []}; + +} + + +function HB_Local_SSDV(parent_div) { + var filter = ""; + var container = document.createElement("div"); + container.classList.add ("HB_TAB_CONTENT_DIV"); + console.debug(HABBOY_HOST); + container.innerHTML = ''; + parent_div.appendChild(container); + // return "SSDV"; + return {"tab_name": "SSDV-L", "tab_nav": []}; + +} + + +function HB_Habitat_SSDV_Last(parent_div) { + var filter = HABBOY_PAYLOAD_ID; + var img = document.createElement("img"); + img.src = "https://ssdv.habhub.org/" + filter + "/latest.jpeg"; + img.style.width = "100%"; + img.style.height = "100%"; + parent_div.appendChild(img); + // return "Last"; + return {"tab_name": "Photo", "tab_nav": []}; + +} + + +function HB_Habitat_Tracker(parent_div) { + var filter = ""; + // + var container = document.createElement("div"); + container.classList.add ("HB_TAB_CONTENT_DIV"); + + var iframe = document.createElement("iframe"); + iframe.src = "https://tracker.habhub.org/index.html?embed=1&hidelist=0&hidegraph=0&expandgraph=0&filter=!RS_*;"; + iframe.style.width = "100%"; + iframe.style.height = "100%"; + container.appendChild(iframe); + + parent_div.appendChild(container); + // return "HabHub"; + return {"tab_name": "HabHub", "tab_nav": []}; +} + +function NiceRadioName(radio_addr) { + if(radio_addr.toLowerCase().startsWith('ws://')) + radio_addr = radio_addr.substr(5, radio_addr.length); + radio_addr = radio_addr.split(":")[0]; + let tokens = radio_addr.split("."); + if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(radio_addr)) + return tokens[tokens.length-1]; + else + return tokens[0]; +} + + +function HB_BuildHabdec(parent_div, habdec_addr) { + + if( habdec_addr.toLowerCase().startsWith("ws://") ) + habdec_addr = habdec_addr.substr(5, habdec_addr.length); + + // construct name for this tab. + // check existing names to prevent duplicates + if( typeof HB_BuildHabdec.existing_radio_names == 'undefined' ) + HB_BuildHabdec.existing_radio_names = []; + + var radio_name_proposed = NiceRadioName(habdec_addr); + var radio_name_new = radio_name_proposed; + if( HB_BuildHabdec.existing_radio_names.includes(radio_name_new) ) + radio_name_new = radio_name_proposed + '_' + habdec_addr.substr( habdec_addr.indexOf(':')+1, habdec_addr.length ); + + HB_BuildHabdec.existing_radio_names.push(radio_name_new); + + var container = document.createElement("div"); + container.classList.add ("HB_TAB_CONTENT_DIV"); + + var iframe = document.createElement("iframe"); + iframe.id = "HB_HABDEC_IFRAME_" + radio_name_new; + iframe.radio_name = radio_name_new; + iframe.style.width = "100%"; + iframe.style.height = "100%"; + + let iframe_src = location.origin + "/" + location.pathname + "/habdec_gui"; + iframe.src = iframe_src; + + iframe.onload = () => { + iframe.contentWindow.postMessage("cmd::setServer:addr=" + habdec_addr); + } + HABBOY_HABDEC_IFRAMES.push(iframe); + + container.appendChild(iframe); + + parent_div.appendChild(container); + + // return "Radio"; + return {"tab_name": "Radio " + radio_name_new, "tab_nav": []}; +} + + +function HB_ReplaceColorScheme_CB(color_name) { + + /* + var cssLinkIndex = 1; + + var oldlink = document.getElementsByTagName("link").item(cssLinkIndex); + var newlink = document.createElement("link"); + + console.debug(oldlink, newlink); + + newlink.setAttribute("rel", "stylesheet"); + newlink.setAttribute("type", "text/css"); + newlink.setAttribute("href", cssFile); + + document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink); + */ + + /*Highcharts.theme = HB_highcharts_theme(); + Highcharts.setOptions(Highcharts.theme);*/ + + HB_ApplyColorScheme( color_name, HB_COLOR_SCHEMES[color_name] ); + + HB_TabButtonsUpdateState(); + + // inform habdec + for(let i in HABBOY_HABDEC_IFRAMES) + { + var habdec_window = HABBOY_HABDEC_IFRAMES[i].contentWindow; + habdec_window.postMessage('cmd::setColorScheme' + + ':name=' + color_name + + ':config=' + JSON.stringify(HB_COLOR_SCHEMES[color_name]['HABDEC']) + ); + } +} + + +function HB_UpdateInfo(info_div) { + try{ + if( Object.keys(HB_HABBOY_INFO).length ) { + var content = ""; + + // globals stats + content +='

GLOBALS

'; + + try { + var global_stats = Object.keys(HB_HABBOY_INFO['global']); + content += '

'; + for(var i in global_stats) + content += ""; + content += ''; + for(var i in global_stats) + content += ''; + content += '

" + global_stats[i] + "

' + Math.round(HB_HABBOY_INFO['global'][global_stats[i]]) + '

'; + } catch(err) { + console.debug("Error in habboy info.", err); + } + + // processes + content += '

Process

'; + var procs_arr = Object.keys(HB_HABBOY_INFO['proc']); + var stats_arr = Object.keys(HB_HABBOY_INFO['proc'][procs_arr[0]]); + content += ''; + content += "\n"; + for(var i in stats_arr) + content += ""; + content += ""; + + for (const [proc, stats] of Object.entries(HB_HABBOY_INFO['proc'])) { + content += ''; + content += '"; + for ([key, value] of Object.entries(HB_HABBOY_INFO['proc'][proc])) { + if(key == 'runtime') + value = new Date(1000 * value).toISOString().substr(11,8); + else + value = Math.round(value); + content += ''; + } + content += ''; + } + content += '

Process

" + stats_arr[i] + "

' + proc + "

' + value + '

'; + + // telemetry + content += '

Telemetry

'; + content += ''; + + var habhubs = Object.keys(HB_HABBOY_INFO['telemetry']['habhub']); + if(habhubs.length) { + var stats_arr = Object.keys(HB_HABBOY_INFO['telemetry']['habhub'][habhubs[0]]); + content += "\n"; + for(var i in stats_arr) + content += ""; + + for(var i in habhubs) { + var hh = habhubs[i]; + content += ''; + content += ''; + for ([key, value] of Object.entries(HB_HABBOY_INFO['telemetry']['habhub'][hh])) { + if(key == 'connection_age' || key == 'sentence_age') + value = new Date(1000 * value).toISOString().substr(11,8); + else + value = Math.round(value); + content += ''; + } + content += ''; + } + } + + var habdecs = Object.keys(HB_HABBOY_INFO['telemetry']['habdec']); + if(habdecs.length) { + for(var i in habdecs) { + var hd = habdecs[i]; + content += ''; + content += '"; + for ([key, value] of Object.entries(HB_HABBOY_INFO['telemetry']['habdec'][hd])) { + if(key == 'connection_age' || key == 'sentence_age') + value = new Date(1000 * value).toISOString().substr(11,8); + else + value = Math.round(value); + content += ''; + } + content += ''; + } + } + + content += '

Source

" + stats_arr[i] + "

Habitat ' + hh + '

' + value + '

' + hd + "

' + value + '

'; + + // last sentence + if(HB_VEHICLES_SENTENCE_LAST[HABBOY_PAYLOAD_ID]) + content += '

Last Sentence

' + HB_VEHICLES_SENTENCE_LAST[HABBOY_PAYLOAD_ID]['_SENTENCE'] + '

' + + info_div.innerHTML = content; + info_div.style.backgroundColor = HB_get_css_val("--HB_bg"); + } + } + catch(err) { + console.debug("HB_UpdateInfo error", err); + } + + setTimeout(() => { + HB_UpdateInfo(info_div) + }, 1000); +} + + +function HB_BuildInfo(parent_div) { + var info_div = document.createElement('div'); + info_div.id = "info_cnt_div"; + info_div.flex = "auto"; + info_div.style.width = '100%'; + info_div.style.backgroundColor = HB_get_css_val("--HB_bg"); + HB_UpdateInfo(info_div); + parent_div.appendChild(info_div); + return {"tab_name": "Info", "tab_nav": []}; + +} + + +function copy_text_to_clipboard(i_text){ + const el = document.createElement('textarea'); + el.value = i_text; + document.body.appendChild(el); + el.select(); + document.execCommand('copy'); +document.body.removeChild(el); +}; + + +function HB_BuildConfig(parent_div) { + + var nav_info = []; + + var grid = document.createElement('div'); + grid.flex = "auto"; + grid.style.width = '100%'; + grid.style.display = 'grid'; + grid.style.gridTemplateColumns = "auto auto auto auto "; + parent_div.appendChild(grid); + + var b; + + b = document.createElement("button"); + b.innerHTML = "Full Screen"; + b.onclick = toggleFullscreen; + grid.appendChild(b); + nav_info.push( {"widget": b, "click": 1} ); + + b = document.createElement("button"); + b.innerHTML = "Toggle Layout"; + b.onclick = function () { HB_MENU_LAYOUT_TOP = !HB_MENU_LAYOUT_TOP; HB_SetMenuLayout(); }; + grid.appendChild(b); + nav_info.push( {"widget": b, "click": 1} ); + + b = document.createElement("button"); + b.innerHTML = "Refresh"; + b.onclick = function(){location.reload()}; + grid.appendChild(b); + nav_info.push( {"widget": b, "click": 1} ); + + b = document.createElement("button"); + b.innerHTML = "Nav"; + b.onclick = function () { + // var loc_url = "http://www.google.com/maps/place/" + + copy_text_to_clipboard( HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]['latitude'] + ', ' + + HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]['longitude'] ); + var loc_url = "geo:" + + HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]["latitude"] + "," +HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]["longitude"]; + window.open(loc_url, '_blank'); + }; + grid.appendChild(b); + nav_info.push( {"widget": b, "click": 1} ); + + let chasecar_b = document.createElement("button"); + chasecar_b.innerHTML = "Chase Car"; + chasecar_b.onclick = () => { + HABBOY_UPLOAD_CHASE_CAR = !HABBOY_UPLOAD_CHASE_CAR; + if(HABBOY_UPLOAD_CHASE_CAR) + chasecar_b.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + chasecar_b.style.backgroundColor = HB_get_css_val('--HB_button'); + } + grid.appendChild(chasecar_b); + nav_info.push( {"widget": chasecar_b, "click": 1} ); + + // device control + // + var ctrl_cmds_buttons = new Array(); + var CTRL_CMDS = ['habdec_stop', 'habdec_start', + 'spy_stop', 'spy_start', + 'restart', 'reboot', 'halt', + ]; + for(let cc in CTRL_CMDS) + { + b = document.createElement("button"); + b.innerHTML = CTRL_CMDS[cc].toUpperCase(); + b.onclick = function () { + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/ctrl/" + CTRL_CMDS[cc]); + xhr.send(); + // setTimeout(() => { location.reload() }, 1000); + }; + ctrl_cmds_buttons.push(b); + } + + b = document.createElement("button"); + b.innerHTML = 'Device...'; + b.onclick = HB_modal_submenu_fun(ctrl_cmds_buttons, parent_div); + grid.appendChild(b); + nav_info.push( {"widget": b, "click": 1} ); + + // color schemes + // + var color_buttons = new Array(); + for(let color_scheme in HB_COLOR_SCHEMES) + { + b = document.createElement("button"); + b.innerHTML = color_scheme; + b.onclick = function () { HB_ReplaceColorScheme_CB(color_scheme); }; + color_buttons.push(b); + } + + b = document.createElement("button"); + b.innerHTML = 'Color...'; + b.onclick = HB_modal_submenu_fun(color_buttons, parent_div); + grid.appendChild(b); + nav_info.push( {"widget": b, "click": 1} ); + + // payloads + // + var payloads_buttons = new Array(); + for(let i in HABBOY_PARAMS['payloads']) + { + let pid_and_callsign = HABBOY_PARAMS['payloads'][i]; + var b = document.createElement("button"); + b.innerHTML = pid_and_callsign[1] + ', ' + pid_and_callsign[0]; + b.onclick = function(){HB_ReplacePayloadId(pid_and_callsign)}; + payloads_buttons.push(b); + } + + b = document.createElement("button"); + b.innerHTML = 'Payloads...'; + b.onclick = HB_modal_submenu_fun(payloads_buttons, parent_div); + grid.appendChild(b); + nav_info.push( {"widget": b, "click": 1} ); + + // test - add radio + /* + b = document.createElement("button"); + b.innerHTML = "Add Radio"; + b.onclick = function () { + let buttons_div = document.getElementById("HB_BUTTONS_DIV"); + let tabs_div = document.getElementById("HB_TABS_DIV"); + HB_BuildTab( + (parent_div)=> { + return HB_BuildHabdec( parent_div, "127.0.0.1:5555" ); + }, + buttons_div, tabs_div ); + }; + grid.appendChild(b); + nav_info.push( {"widget": b, "click": 1} ); + */ + + // return "Config"; + return {"tab_name": "Control", "tab_nav": nav_info}; +} + + +////////////////////////////////////////// +////////////////////////////////////////// +// // +// GUI PROCEDURES // +// // +////////////////////////////////////////// +////////////////////////////////////////// + + +function HB_TabButtonsUpdateState() { + // MANUALLY SET LIGHT-UP, BECAUSE THERE ARE OTHER BUTTONS THAT CAN BE CLICKED + // + + // colors of tab buttons + var root = document.querySelector(':root'); + var rootStyles = getComputedStyle(root); + var color_tab_button = rootStyles.getPropertyValue('--HB_tab_button'); + var color_tab_button_active = rootStyles.getPropertyValue('--HB_tab_button_active'); + var color_tab_button_text = rootStyles.getPropertyValue('--HB_tab_button_text'); + var color_tab_button_active_text = rootStyles.getPropertyValue('--HB_tab_button_active_text'); + + // un-light all buttons + var tab_divs_arr = document.getElementsByClassName("HB_TAB_DIV"); + var buttons = document.getElementsByClassName("HB_TAB_BUTTON"); + for (i = 0; i < tab_divs_arr.length; i++) { + buttons[i].style.backgroundColor = color_tab_button; + buttons[i].style.color = color_tab_button_text; + } + // light up selected button + var button = document.getElementById("HB_TAB_BUTTON_" + HB_TAB_BUTTON_CURRENT) + button.style.backgroundColor = color_tab_button_active; + button.style.color = color_tab_button_active_text; + +} + + +function HB_TabButton_onclick_CB(tab_name) { + HB_TAB_BUTTON_CURRENT = tab_name; + + // Hide all tabs + var i, tab_divs_arr, tab_buttons; + tab_divs_arr = document.getElementsByClassName("HB_TAB_DIV"); + for (i = 0; i < tab_divs_arr.length; i++) + tab_divs_arr[i].style.display = "none"; + + // Show the specific tab content + var clicked_tab = document.getElementById("HB_TAB_DIV_" + tab_name); + clicked_tab.style.display = "flex"; + + HB_TabButtonsUpdateState(); + + window.dispatchEvent(new Event('resize')); +} + + +function HB_BuildTab(builder_function, tab_buttons_parent_div, tabs_parent_div) { + // tab button + var tab_button = document.createElement("button"); + tab_button.classList.add("HB_TAB_BUTTON"); + tab_button.style.flex = "auto"; + tab_buttons_parent_div.appendChild(tab_button); + HB_TAB_BUTTONS.push(tab_button); + + // tab div + var tab_div = document.createElement("div"); + tab_div.classList.add("HB_TAB_DIV"); + tabs_parent_div.appendChild(tab_div); + + // content + // var tab_name = builder_function(tab_div); + var tab_result = builder_function(tab_div); + var tab_name = tab_result.tab_name; + var tab_nav = tab_result.tab_nav; + HB_TAB_BUTTONS_WIDGET_NAV[tab_name] = tab_nav; + + tab_button.innerHTML = tab_name; + tab_button.id = "HB_TAB_BUTTON_" + tab_name; + tab_button.HB_tab_name = tab_name; + tab_button.onclick = function () { HB_TabButton_onclick_CB(tab_name); }; + + tab_div.id = "HB_TAB_DIV_" + tab_name; + + return tab_name; +} + + +var HB_MENU_LAYOUT_TOP = 0; +function HB_SetMenuLayout() +{ + var buttons_div = document.getElementById("HB_BUTTONS_DIV"); + var tabs_div = document.getElementById("HB_TABS_DIV"); + var buttons_plus_tabs_div = document.getElementById("HB_TABS_AND_BUTTONS_DIV"); + + if(HB_MENU_LAYOUT_TOP) { + buttons_plus_tabs_div.style.flexDirection = "column"; + buttons_div.style.flexDirection = "row"; + buttons_div.style.width = ""; + buttons_div.style.height = "10vh"; + tabs_div.style.width = ""; + tabs_div.style.height = "80vh"; + + while (buttons_plus_tabs_div.firstChild) + buttons_plus_tabs_div.removeChild(buttons_plus_tabs_div.firstChild); + buttons_plus_tabs_div.appendChild(buttons_div); + buttons_plus_tabs_div.appendChild(tabs_div); + } + else { + buttons_plus_tabs_div.style.flexDirection = "row"; + buttons_div.style.flexDirection = "column"; + buttons_div.style.width = "13vw"; + buttons_div.style.height = ""; + tabs_div.style.width = "87vw"; + tabs_div.style.height = "90vh"; + + while (buttons_plus_tabs_div.firstChild) + buttons_plus_tabs_div.removeChild(buttons_plus_tabs_div.firstChild); + buttons_plus_tabs_div.appendChild(tabs_div); + buttons_plus_tabs_div.appendChild(buttons_div); + } + + // window.dispatchEvent(new Event('resize')); + +} + + + +/////////////////////////////////////////////////// +/////////////////////////////////////////////////// +// // +// PROCEDURES TO NAVIGATE TABS AND ITS CHILDREN // +// // +/////////////////////////////////////////////////// +/////////////////////////////////////////////////// + +// Changes selected tab +// this is supposed to be initiated by a hardware switch +// +var last_tab_highlighted = 0; +function HB_CycleTabs(i_jump) { + + last_tab_highlighted += i_jump; + last_tab_highlighted = last_tab_highlighted % (HB_TAB_BUTTONS.length); + while(last_tab_highlighted < 0) + last_tab_highlighted += HB_TAB_BUTTONS.length; + + if(HB_TAB_BUTTONS[last_tab_highlighted] != undefined) + HB_TAB_BUTTONS[last_tab_highlighted].click(); + + var tab_name = HB_TAB_BUTTONS[last_tab_highlighted].HB_tab_name; + console.debug( tab_name ); + console.debug( HB_TAB_BUTTONS_WIDGET_NAV[tab_name] ); +} + + + +function HB_BuildGui(habboy_main_div) { + + while (habboy_main_div.firstChild) + habboy_main_div.removeChild(habboy_main_div.firstChild); + + // BUILD TABS + // + var tabs_div = document.createElement("div"); + tabs_div.id = "HB_TABS_DIV"; + tabs_div.style.display = "flex"; + var buttons_div = document.createElement("div"); + buttons_div.id = "HB_BUTTONS_DIV"; + buttons_div.style.display = "flex"; + + for (var i in HB_TAB_BUILDERS_ARR) { + HB_BuildTab( HB_TAB_BUILDERS_ARR[i], buttons_div, tabs_div ); + } + + // PUT TABS AND BUTTONS INTO DIV + // + var buttons_plus_tabs_div = document.createElement("div"); + buttons_plus_tabs_div.id = "HB_TABS_AND_BUTTONS_DIV"; + buttons_plus_tabs_div.style.display = "flex"; + buttons_plus_tabs_div.flex = "auto"; + buttons_plus_tabs_div.appendChild(buttons_div); + buttons_plus_tabs_div.appendChild(tabs_div); + + // bottom status bar + var status_bar_div = document.createElement("div"); + status_bar_div.classList.add("HB_STATUS_BAR_DIV"); + status_bar_div.style.height = "10vh"; + + HB_BuildStatusBar(status_bar_div); + + habboy_main_div.appendChild(buttons_plus_tabs_div); + habboy_main_div.appendChild(status_bar_div); + + window.onload = + setTimeout( + function () { + var tab_divs_arr = document.getElementsByClassName("HB_TAB_DIV"); + // hide all but first tab + for (i = 1; i < tab_divs_arr.length; i++) + tab_divs_arr[i].style.display = "none"; + window.dispatchEvent(new Event('resize')); + HB_SetMenuLayout(); + } + , 100); + +} + + +// this requires httpS ... +function HB_DeviceLocationGPS() { + navigator.geolocation.getCurrentPosition( + (loc) => { // success function + HB_DEVICE_GPS_LAST["DEVICE"] = { + "time": (new Date()).toISOString(), + "latitude": loc.coords.latitude, + "longitude": loc.coords.longitude, + "altitude": loc.coords.altitude || 0, + "ground_speed_mps": loc.coords.speed || 0, + "heading": loc.coords.heading || 0, + "sats": loc.coords.sats || 0 }; + }, + (err) => { // error function + console.debug("HB_DeviceLocationGPS failed. Use HABBOY position. ", err); + HB_DEVICE_GPS_LAST["DEVICE"] = HB_DEVICE_GPS_LAST["HABBOY"]; + } + ); + setTimeout( HB_DeviceLocationGPS, 1000 ); +} + + +///////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////// + +function HB_HabBoyTimeOffset() { + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/utcnow"); + xhr.onload = function () { + if (xhr.status == 200) + { + var now = new Date().getTime(); + var habboy_utcnow = Date.parse( xhr.responseText ); + HB_HABBOY_TIME_DIFF_mSECS = habboy_utcnow - now; + console.debug("HB_HABBOY_TIME_DIFF_mSECS", HB_HABBOY_TIME_DIFF_mSECS); + } + setTimeout( () => { HB_HabBoyTimeOffset(HB_HabBoyTimeOffset) }, 15000); + }; + xhr.onerror = () => { setTimeout(() => { HB_HabBoyTimeOffset(HB_HabBoyTimeOffset) }, 15000); }; + xhr.send(); +} + + +function HB_HABBOY_INFO_Update() { + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/info"); + xhr.onload = function () { + if (xhr.status == 200) { + try { + HB_HABBOY_INFO = JSON.parse(xhr.responseText); + } catch(e) {} + } + setTimeout( HB_HABBOY_INFO_Update, 5000); + }; + xhr.onerror = () => { setTimeout(HB_HABBOY_INFO_Update, 5000); }; + xhr.send(); +} + + +function HB_ReplacePayloadId(pid_and_callsign) { + let xhr = new XMLHttpRequest(); + xhr.open('PUT', HABBOY_DATA_URL + "/habboy/api/v1/params/payload_id"); + xhr.setRequestHeader('Content-type','application/json; charset=utf-8'); + xhr.onload = function () { + if (xhr.status == 200) { + location.reload(); + } + }; + xhr.onerror = () => { console.debug("HB_ReplacePayloadId Failed.") }; + xhr.send( JSON.stringify( {'payload_id': pid_and_callsign[0], 'callsign': pid_and_callsign[1]} ) ); +} + + +function WatchForNewHabdecs( current_habdec_clients ) { + + function eqSet(as, bs) { + if (as.size !== bs.size) return false; + for (var a of as) if (!bs.has(a)) return false; + return true; + } + + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/params"); + xhr.onload = function () { + if (xhr.status == 200) + { + let new_habdec_clients = new Set( JSON.parse(xhr.responseText)['habdec_clients'] ); + if( !eqSet(new_habdec_clients, current_habdec_clients) ) + location.reload(); + setTimeout(() => { WatchForNewHabdecs( current_habdec_clients ) }, 3000); + } + }; + xhr.onerror = () => { setTimeout(() => { WatchForNewHabdecs( current_habdec_clients ) }, 3000); }; + xhr.send(); +} + +///////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////// + +function HB_BuildAll(habboy_main_div) { + + Highcharts.theme = HB_highcharts_theme(); + Highcharts.setOptions(Highcharts.theme); + + // main TABs + // + for(let i in HABBOY_PARAMS['habdec_clients']) + { + HB_TAB_BUILDERS_ARR.push( + (parent_div)=> { + return HB_BuildHabdec( parent_div, HABBOY_PARAMS['habdec_clients'][i] ); + } + ); + } + HB_TAB_BUILDERS_ARR.push(HB_BuildMap); + HB_TAB_BUILDERS_ARR.push(HB_BuildGoogleMap); + HB_TAB_BUILDERS_ARR.push(HB_BuildCharts); + HB_TAB_BUILDERS_ARR.push(HB_BuildGauges); + // HB_TAB_BUILDERS_ARR.push(HB_Habitat_Tracker); // seems it doesn't work without https + HB_TAB_BUILDERS_ARR.push(HB_Habitat_SSDV); + HB_TAB_BUILDERS_ARR.push(HB_Local_SSDV); + // HB_TAB_BUILDERS_ARR.push(HB_Habitat_SSDV_Last); + // HB_TAB_BUILDERS_ARR.push(function name(parent_div) { ExampleTabBuilder_img(parent_div, "img/test2.jpg"); return {"tab_name": "Stat", "tab_nav": []}; }); + HB_TAB_BUILDERS_ARR.push(HB_BuildRcvStats); + // HB_TAB_BUILDERS_ARR.push(function name(parent_div) { ExampleTabBuilder_img(parent_div, "img/test2.jpg"); return "Diagnosics"; }); + HB_TAB_BUILDERS_ARR.push(HB_BuildInfo); + HB_TAB_BUILDERS_ARR.push(HB_BuildConfig); + + HB_BuildGui(habboy_main_div); + + setTimeout(() => { + WatchForNewHabdecs( new Set(HABBOY_PARAMS['habdec_clients']) ) + }, 3000); + + + HB_HabBoyTimeOffset(); + UpdateVehicleLastSentence(); + HB_VEHICLES_TELEMETRY_Update(); + HB_VEHICLES_PREDICT_Update(); + HB_VEHICLES_PREDICT_HABITAT_Update(); + HB_HABBOY_GPS_Update(); + HB_HABBOY_INFO_Update(); + HB_SendChaseCar(); + + /*var use_geolocation = false; + if(use_geolocation) + HB_DeviceLocationGPS(); // this requires https ... + else + HB_hw_iface("ws://" + HABBOY_HOST + ":5565");*/ + + // CycleTabs(); + + setTimeout(() => { + window.dispatchEvent(new Event('resize')); + }, 500); + +} + +function HABBOY_INIT(habboy_main_div) { + + Highcharts.setOptions({ + global: + { + // getTimezoneOffset:undefined + // timezone:undefined + // timezoneOffset:undefined + useUTC:false + // VMLRadialGradientURL:http://code.highcharts.com/{version}/gfx/vml-radial-gradient.png + } + }); + + + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/params"); + xhr.onload = function () { + if (xhr.status == 200) + { + HABBOY_PARAMS = JSON.parse(xhr.responseText); + HABBOY_PAYLOAD_ID = HABBOY_PARAMS["payload_id"]; + HABBOY_PAYLOAD_CALLSIGN = HABBOY_PARAMS["callsign"]; + console.debug("HABBOY_PARAMS ", HABBOY_PARAMS); + HB_BuildAll(habboy_main_div); + } + else + { + HABBOY_INIT(habboy_main_div); + } + }; + xhr.onerror = () => { setTimeout(() => { HABBOY_INIT(habboy_main_div) }, 3000); }; + xhr.send(); +} \ No newline at end of file diff --git a/webUI/code/js/HB_charts.js b/webUI/code/js/HB_charts.js new file mode 100644 index 0000000..9c9b4b3 --- /dev/null +++ b/webUI/code/js/HB_charts.js @@ -0,0 +1,187 @@ + + +function SentenceTimeToEpoch(i_str) { // isoformat 1970-01-01T12:00:00.0+00:00 + var result = Date.parse(i_str); + return result; +} + + +function hashCode(str) // java String#hashCode +{ + var hash = 5381; + for (var i = 0; i < str.length; i++) { + hash = str.charCodeAt(i) + ((hash << 5) - hash); + } + return hash; +} + +function stringToRGB(i) +{ + var hash = hashCode(i); + var r = (hash & 0xFF0000) >> 16; + var g = (hash & 0x00FF00) >> 8; + var b = hash & 0x0000FF; + return [r,g,b]; +} + +function HB_SensorColor(i_sensor_name, i_brightness) { + var RGB = [50,50,50]; + if(i_sensor_name == "altitude") RGB = [0,200,0]; + else if(i_sensor_name == "altitude") RGB = [0,100,0]; + else if(i_sensor_name == "temperature_internal") RGB = [150,50,50]; + else if(i_sensor_name == "temperature_external") RGB = [0,25,125]; + else if(i_sensor_name == "pressure") RGB = [150,25,7]; + else { + RGB = stringToRGB( i_sensor_name ); + // fix minimum brightbess + RGB[0] = 55 + Math.floor(.77*RGB[0]); + RGB[1] = 55 + Math.floor(.77*RGB[1]); + RGB[2] = 55 + Math.floor(.77*RGB[2]); + } + + RGB[0] *= i_brightness; + RGB[1] *= i_brightness; + RGB[2] *= i_brightness; + + return "rgb(" + RGB[0] + "," + RGB[1] + "," + RGB[2] + ")"; +} + +function HB_GenericGraph_UpdateSeries_New(sensor, chart, data) { + if(!(sensor in data)) + return; + + var _now = new Date().getTime(); + // console.debug( data[sensor]['times'][data[sensor]['times'].length-1] ); + // console.debug( SentenceTimeToEpoch(data[sensor]['times'][data[sensor]['times'].length-1]) ); + // console.debug( _now ); + var time_samples = []; // array of [time,value] pairs + var time_samples_dVdT = []; // array of [time,delta_value] pairs + var hour_as_milisecs = 3600 * 1000; + for(var i=0; i 15e3 ) { // add every 15 seconds + chart.series[0].addPoint( time_samples[_last_i] ); + chart.series[1].addPoint( time_samples_dVdT[_last_i] ); + } + } +} + +function HB_BuildSensorChart_GenericGraph(sensor) { + var chart_div = document.createElement('div'); + + var chart = new Highcharts.Chart({ + chart: { + renderTo: chart_div, + type: 'line', + zoomType: 'x', + animation: false, + }, + title: { + text: sensor, + style: { fontFamily: 'monospace', color: "hsl(32, 93%, 45%)" } + }, + xAxis: { + type: 'datetime', + }, + yAxis: [ { title: {text: sensor} }, // values + { title: {text: sensor + " / dT"}, opposite: true }], // values / dT + plotOptions: { + series: { + animation: false + } + }, + series: [] + }); + + return [chart_div, chart]; +} + + +function HB_BuildCharts_AllSensors(parent_div) { + let payload_id = HABBOY_PAYLOAD_ID; + + if( !(payload_id in HB_VEHICLES_TELEMETRY) ) + { + console.debug("HB_BuildCharts_AllSensors - No telemetry for " + payload_id); + setTimeout(() => { + HB_BuildCharts_AllSensors(parent_div) + }, 1000); + return; + } + + var grid = document.createElement("div"); + grid.style.display = "grid"; + grid.style.gridTemplateColumns = "auto auto auto"; + grid.style.width = "100%"; + grid.style.height = "100%"; + parent_div.appendChild(grid); + + for (let sensor in HB_VEHICLES_TELEMETRY[payload_id]) { + if( sensor == "latitude" + || sensor == "longitude" + || sensor == "time" + || sensor == "sentence_id" + || ! HB_VEHICLES_TELEMETRY[payload_id][sensor]["is_numeric"] + ) + continue; + + let _t = HB_BuildSensorChart_GenericGraph(sensor); + let chart_container = _t[0]; + let chart = _t[1]; + grid.appendChild(chart_container); + + // initialize with data + HB_GenericGraph_UpdateSeries_New(sensor, chart, HB_VEHICLES_TELEMETRY[payload_id]); + + // update chart on each telemetry update + console.debug("Register telemetry callback for chart ", sensor); + HB_VEHICLES_TELEMETRY_UpdateCallbacks.push( + (sensor_update_data) => { + HB_GenericGraph_UpdateSeries_New(sensor, chart, sensor_update_data); + } + ) + } +} + +function HB_BuildCharts(parent_div) { + var charts_div = document.createElement("div"); + charts_div.id = "HB_CHARTS"; + charts_div.style.width = '100%'; + charts_div.style.height = '100%'; + parent_div.appendChild(charts_div); + + HB_BuildCharts_AllSensors(charts_div); + + return {"tab_name": "Graphs", "tab_nav": []}; +} diff --git a/webUI/code/js/HB_color_schemes.js b/webUI/code/js/HB_color_schemes.js new file mode 100644 index 0000000..c7271f6 --- /dev/null +++ b/webUI/code/js/HB_color_schemes.js @@ -0,0 +1,302 @@ + + var HB_COLOR_SCHEME; + var HB_COLOR_SCHEMES = {}; + +HB_COLOR_SCHEMES["DEFAULT"] = { + HABDEC: { + CSS: { + HD_bg: "hsl(210, 15%, 15%)", + HD_fg: "hsl(210, 15%, 25%)", + HD_button: "hsl(210, 15%, 25%)", + HD_button_border: "hsl(210, 15%, 15%)", + HD_button_text: "hsl(0, 0%, 55%)", + HD_label: "hsl(32, 93%, 45%)", + HD_highlight: "hsl(210, 80%, 45%)", + HD_enabled: "hsl(50, 100%, 40%)", + HD_sentence: "hsl(0, 100%, 33%)" + }, + SPECTRUM: { + HIGH: "hsl(30, 30%, 100%)", + MID: "hsl(30, 80%, 75%)", + LOW: "hsl(30, 100%, 30%)", + FILTER: "hsla(200, 50%, 30%, .5)" + } + }, + HABBOY: { + CSS: { + HB_bg: 'hsl(210, 15%, 14%)', + HB_text: '#eee', + HB_text_highlight: 'hsl(32, 93%, 45%)', + HB_tab_button: 'rgb(31, 62, 93)', + HB_tab_button_active: '#bb0', + HB_tab_button_text: '#eee', + HB_tab_button_active_text: '#000', + HB_tab_button_border: 'rgb(31, 62, 93)', + HB_tab_button_border_highlight: '#b80', + HB_button: 'rgb(31, 62, 93)', + HB_button_active: '#990', + HB_button_text: '#ccc', + HB_button_active_text: '#000', + HB_button_border: '#000' + } + } +}; + + +HB_COLOR_SCHEMES["RED"] = { + HABDEC: { + CSS: { + HD_bg: "hsl(0, 0%, 0%)", + HD_fg: "hsl(0, 50%, 10%)", + HD_button: "hsl(0, 100%, 5%)", + HD_button_border: "hsl(0, 100%, 20%)", + HD_button_text: "hsl(0, 100%, 60%)", + HD_label: "hsl(0, 100%, 45%)", + HD_highlight: "hsl(0, 80%, 45%)", + HD_enabled: "hsl(0, 100%, 30%)", + HD_sentence: "hsl(0, 100%, 33%)" + }, + SPECTRUM: { + HIGH: "hsl(0, 30%, 100%)", + MID: "hsl(0, 80%, 55%)", + LOW: "hsl(0, 100%, 10%)", + FILTER: "hsla(0, 50%, 30%, .5)" + } + }, + HABBOY: { + CSS: { + HB_bg: "hsl(0, 0%, 0%)", + HB_text: "hsl(0, 100%, 60%)", + HB_text_highlight: "hsl(0, 80%, 45%)", + HB_tab_button: "hsl(0, 100%, 5%)", + HB_tab_button_active: "hsl(0, 100%, 25%)", + HB_tab_button_text: "hsl(0, 100%, 60%)", + HB_tab_button_active_text: "hsl(0, 100%, 80%)", + HB_tab_button_border: "hsl(0, 100%, 40%)", + HB_tab_button_border_highlight: "hsl(0, 60%, 0%)", + HB_button: "hsl(0, 20%, 5%)", + HB_button_active: "hsl(0, 100%, 25%)", + HB_button_text: "hsl(0, 100%, 60%)", + HB_button_active_text: "hsl(0, 100%, 80%)", + HB_button_border: "hsl(0, 100%, 30%)", + } + } +}; + +HB_COLOR_SCHEMES["GREEN"] = { + HABDEC: { + CSS: { + HD_bg: "hsl(120, 0%, 0%)", + HD_fg: "hsl(120, 50%, 10%)", + HD_button: "hsl(120, 100%, 2%)", + HD_button_border: "hsl(120, 100%, 15%)", + HD_button_text: "hsl(120, 100%, 30%)", + HD_label: "hsl(120, 100%, 30%)", + HD_highlight: "hsl(120, 80%, 35%)", + HD_enabled: "hsl(120, 100%, 20%)", + HD_sentence: "hsl(120, 100%, 33%)" + }, + SPECTRUM: { + HIGH: "hsl(120, 30%, 100%)", + MID: "hsl(120, 80%, 55%)", + LOW: "hsl(120, 100%, 10%)", + FILTER: "hsla(120, 50%, 30%, .5)" + } + }, + HABBOY: { + CSS: { + HB_bg: "hsl(120, 0%, 0%)", + HB_text: "hsl(120, 100%, 60%)", + HB_text_highlight: "hsl(120, 80%, 45%)", + HB_tab_button: "hsl(120, 100%, 5%)", + HB_tab_button_active: "hsl(120, 100%, 20%)", + HB_tab_button_text: "hsl(120, 100%, 60%)", + HB_tab_button_active_text: "hsl(120, 100%, 70%)", + HB_tab_button_border: "hsl(120, 100%, 40%)", + HB_tab_button_border_highlight: "hsl(120, 60%, 0%)", + HB_button: "hsl(120, 20%, 5%)", + HB_button_active: "hsl(120, 100%, 20%)", + HB_button_text: "hsl(120, 100%, 60%)", + HB_button_active_text: "hsl(120, 100%, 80%)", + HB_button_border: "hsl(120, 100%, 30%)", + } + } +}; + +HB_COLOR_SCHEMES["BLUE"] = { + HABDEC: { + CSS: { + HD_bg: "hsl(210, 0%, 0%)", + HD_fg: "hsl(210, 50%, 20%)", + HD_button: "hsl(210, 100%, 4%)", + HD_button_border: "hsl(210, 100%, 30%)", + HD_button_text: "hsl(210, 100%, 60%)", + HD_label: "hsl(210, 100%, 60%)", + HD_highlight: "hsl(210, 80%, 30%)", + HD_enabled: "hsl(210, 100%, 40%)", + HD_sentence: "hsl(210, 100%, 75%)" + }, + SPECTRUM: { + HIGH: "hsl(210, 30%, 100%)", + MID: "hsl(210, 80%, 75%)", + LOW: "hsl(210, 100%, 20%)", + FILTER: "hsla(210, 50%, 30%, .5)" + } + }, + HABBOY: { + CSS: { + HB_bg: "hsl(210, 0%, 0%)", + HB_text: "hsl(210, 100%, 60%)", + HB_text_highlight: "hsl(210, 80%, 45%)", + HB_tab_button: "hsl(210, 100%, 5%)", + HB_tab_button_active: "hsl(210, 100%, 20%)", + HB_tab_button_text: "hsl(210, 100%, 60%)", + HB_tab_button_active_text: "hsl(210, 100%, 70%)", + HB_tab_button_border: "hsl(210, 100%, 40%)", + HB_tab_button_border_highlight: "hsl(210, 60%, 0%)", + HB_button: "hsl(210, 20%, 5%)", + HB_button_active: "hsl(210, 100%, 20%)", + HB_button_text: "hsl(210, 100%, 60%)", + HB_button_active_text: "hsl(210, 100%, 80%)", + HB_button_border: "hsl(210, 100%, 30%)", + } + } +}; + +HB_COLOR_SCHEMES["GOLD"] = { + HABDEC: { + CSS: { + HD_bg: "hsl(40, 0%, 0%)", + HD_fg: "hsl(40, 50%, 20%)", + HD_button: "hsl(40, 100%, 4%)", + HD_button_border: "hsl(40, 100%, 30%)", + HD_button_text: "hsl(40, 100%, 60%)", + HD_label: "hsl(40, 100%, 60%)", + HD_highlight: "hsl(40, 80%, 30%)", + HD_enabled: "hsl(40, 100%, 40%)", + HD_sentence: "hsl(40, 100%, 75%)" + }, + SPECTRUM: { + HIGH: "hsl(40, 30%, 100%)", + MID: "hsl(40, 80%, 75%)", + LOW: "hsl(40, 100%, 20%)", + FILTER: "hsla(40, 50%, 30%, .5)" + } + }, + HABBOY: { + CSS: { + HB_bg: "hsl(40, 0%, 0%)", + HB_text: "hsl(40, 100%, 60%)", + HB_text_highlight: "hsl(40, 80%, 45%)", + HB_tab_button: "hsl(40, 100%, 5%)", + HB_tab_button_active: "hsl(40, 100%, 20%)", + HB_tab_button_text: "hsl(40, 100%, 60%)", + HB_tab_button_active_text: "hsl(40, 100%, 70%)", + HB_tab_button_border: "hsl(40, 100%, 40%)", + HB_tab_button_border_highlight: "hsl(40, 60%, 0%)", + HB_button: "hsl(40, 20%, 5%)", + HB_button_active: "hsl(40, 100%, 20%)", + HB_button_text: "hsl(40, 100%, 60%)", + HB_button_active_text: "hsl(40, 100%, 80%)", + HB_button_border: "hsl(40, 100%, 30%)", + } + } +}; + +HB_COLOR_SCHEMES["PLUM"] = { + HABDEC: { + CSS: { + HD_bg: "hsl(300, 0%, 0%)", + HD_fg: "hsl(300, 50%, 20%)", + HD_button: "hsl(300, 100%, 4%)", + HD_button_border: "hsl(300, 100%, 30%)", + HD_button_text: "hsl(300, 100%, 60%)", + HD_label: "hsl(300, 100%, 60%)", + HD_highlight: "hsl(300, 80%, 30%)", + HD_enabled: "hsl(300, 100%, 40%)", + HD_sentence: "hsl(300, 100%, 75%)" + }, + SPECTRUM: { + HIGH: "hsl(300, 30%, 100%)", + MID: "hsl(300, 80%, 75%)", + LOW: "hsl(300, 100%, 20%)", + FILTER: "hsla(300, 50%, 30%, .5)" + } + }, + HABBOY: { + CSS: { + HB_bg: "hsl(300, 0%, 0%)", + HB_text: "hsl(300, 100%, 60%)", + HB_text_highlight: "hsl(300, 80%, 45%)", + HB_tab_button: "hsl(300, 100%, 5%)", + HB_tab_button_active: "hsl(300, 100%, 20%)", + HB_tab_button_text: "hsl(300, 100%, 60%)", + HB_tab_button_active_text: "hsl(300, 100%, 70%)", + HB_tab_button_border: "hsl(300, 100%, 40%)", + HB_tab_button_border_highlight: "hsl(300, 60%, 0%)", + HB_button: "hsl(300, 20%, 5%)", + HB_button_active: "hsl(300, 100%, 20%)", + HB_button_text: "hsl(300, 100%, 60%)", + HB_button_active_text: "hsl(300, 100%, 80%)", + HB_button_border: "hsl(300, 100%, 30%)", + } + } +}; + + +HB_COLOR_SCHEMES["WHITE"] = { + HABDEC: { + CSS: { + HD_bg: "hsl(0, 0%, 100%)", + HD_fg: "hsl(0, 50%,0%)", + HD_button: "hsl(0, 0%, 80%)", + HD_button_border: "hsl(0, 0%, 10%)", + HD_button_text: "hsl(0, 0%, 0%)", + HD_label: "hsl(0, 0%, 0%)", + HD_highlight: "hsl(0, 0%, 30%)", + HD_enabled: "hsl(0, 0%, 20%)", + HD_sentence: "hsl(0, 0%, 75%)" + }, + SPECTRUM: { + HIGH: "hsl(0, 0%, 100%)", + MID: "hsl(0, 0%, 25%)", + LOW: "hsl(0, 0%, 0%)", + FILTER: "hsla(0, 0%, 30%, .5)" + } + }, + HABBOY: { + CSS: { + HB_bg: "hsl(0, 0%, 100%)", + HB_text: "hsl(0, 0%, 0%)", + HB_text_highlight: "hsl(0, 0%, 30%)", + HB_tab_button: "hsl(0, 0%, 100%)", + HB_tab_button_active: "hsl(0, 0%, 20%)", + HB_tab_button_text: "hsl(0, 0%, 0%)", + HB_tab_button_active_text: "hsl(0, 0%, 80%)", + HB_tab_button_border: "hsl(0, 0%, 70%)", + HB_tab_button_border_highlight: "hsl(0, 0%, 10%)", + HB_button: "hsl(0, 0%, 100%)", + HB_button_active: "hsl(0, 0%, 20%)", + HB_button_text: "hsl(0, 0%, 0%)", + HB_button_active_text: "hsl(0, 0%, 0%)", + HB_button_border: "hsl(0, 0%, 70%)", + } + } +}; + + +function HB_ApplyColorScheme(i_scheme_name, i_color_scheme) { + console.debug('i_scheme_name', i_scheme_name); + HB_COLOR_SCHEME = i_color_scheme; + let root = document.documentElement; + for(prop in i_color_scheme['HABBOY']['CSS']) + root.style.setProperty( '--' + prop, i_color_scheme['HABBOY']['CSS'][prop] ); + + try { + HB_GoogleMap.set('styles', HB_GMAP_COLOR_SCHEMES[i_scheme_name]); + } + catch(error) { + console.debug(error); + false; + } +} \ No newline at end of file diff --git a/webUI/code/js/HB_gauge.js b/webUI/code/js/HB_gauge.js new file mode 100644 index 0000000..b8b32a5 --- /dev/null +++ b/webUI/code/js/HB_gauge.js @@ -0,0 +1,166 @@ + +function HB_Gauge_UpdateSeries_New(sensor, chart, data) { + var _l = data[sensor]['values'].length; + var val = data[sensor]['values'][_l-1]; + chart.series[0].points[0].update( [0, val] ); // time is not important, only life is +} + + +function HB_BuildSensorGauge(sensor) { + var HB_bg = HB_get_css_val('--HB_bg'); + var HB_text_highlight = HB_get_css_val('--HB_text_highlight'); + var HB_tab_button = HB_get_css_val('--HB_tab_button'); + + var chart_div = document.createElement('div'); + + var y_axis = { + min: -100, + max: 100, + minorTickLength: 7, + tickLength: 13 + } + + if (sensor == "elev") { + y_axis.min = 0; + y_axis.max = 500; + } + else if (sensor == "altitude") { + y_axis.min = 0; + y_axis.max = 50000; + y_axis.plotBands = [{ + from: 0, + to: 10000, + color: '#008811' // green + }, { + from: 10000, + to: 30000, + color: '#aaaa00' // yellow + }, { + from: 30000, + to: 40000, + color: '#aa0000' // red + }, { + from: 40000, + to: 50000, + color: '#8800bb' // purple + } + + ] + } + + var chart = new Highcharts.Chart({ + chart: { + renderTo: chart_div, + type: 'gauge', + animation: false, + plotBackgroundColor: null, + plotBackgroundImage: null, + plotBorderWidth: 0, + plotShadow: false, + }, + title: { + text: sensor, + style: { fontFamily: 'monospace', color: "hsl(32, 93%, 45%)" } + }, + pane: { + startAngle: -150, + endAngle: 150, + background: [{ + backgroundColor: null, + borderColor: HB_tab_button, + borderWidth: 3, + outerRadius: '109%', + }] + }, + yAxis: y_axis, + plotOptions: { + gauge: { + pivot: { + radius: 5, + backgroundColor: "hsl(32, 93%, 40%)" + } + }, + series: { + dial: { + backgroundColor: "hsl(32, 93%, 25%)", + radius: '80%', + baseWidth: 12, + baseLength: '5%', + rearWidth: 1, + rearLength: '0%', + }, + dataLabels: { + enabled: true, + borderWidth: 0, + style: { + "color": HB_text_highlight, + "fontSize": "20px", + "fontWeight": "bold", + "textOutline": "0px" + } + } + } + }, + series: [{ + name: sensor, + data: [0] + }] + }); + + return [chart_div, chart]; +} + + +function HB_BuildGauges_AllSensors(parent_div) { + let payload_id = HABBOY_PAYLOAD_ID; + + if(HB_VEHICLES_TELEMETRY[payload_id] == undefined) + { + setTimeout(() => { + HB_BuildGauges_AllSensors(parent_div) + }, 1000); + return; + } + + var grid = document.createElement("div"); + grid.style.display = "grid"; + grid.style.gridTemplateColumns = "auto auto auto"; + grid.style.width = "100%"; + grid.style.height = "100%"; + parent_div.appendChild(grid); + + for (let sensor in HB_VEHICLES_TELEMETRY[payload_id]) { + if (sensor == "latitude" + || sensor == "longitude" + || sensor == "time" + || sensor == "sentence_id" + || ! HB_VEHICLES_TELEMETRY[payload_id][sensor]["is_numeric"] + ) + continue; + + let _t = HB_BuildSensorGauge(sensor); + let chart_container = _t[0]; + let chart = _t[1]; + grid.appendChild(chart_container); + + // update chart on each telemetry update + console.debug("Register telemetry callback for gauge ", sensor); + HB_VEHICLES_TELEMETRY_UpdateCallbacks.push( + (sensor_update_data) => { + HB_Gauge_UpdateSeries_New(sensor, chart, sensor_update_data); + } + ) + } +} + + +function HB_BuildGauges(parent_div) { + var charts_div = document.createElement("div"); + charts_div.id = "HB_GAUGES"; + parent_div.appendChild(charts_div); + + HB_BuildGauges_AllSensors(charts_div); + + return {"tab_name": "Gauge", "tab_nav": []}; + +} diff --git a/webUI/code/js/HB_google_map.js b/webUI/code/js/HB_google_map.js new file mode 100644 index 0000000..999e7cc --- /dev/null +++ b/webUI/code/js/HB_google_map.js @@ -0,0 +1,324 @@ +var HB_GoogleMap; +var HB_GoogleMap_Marker_Payload; +var HB_GoogleMap_Marker_Landing; +var HB_GoogleMap_Marker_Habboy; +var HB_GoogleMap_directionsService; +var HB_GoogleMap_directionsDisplay; +var GMAPS_API_KEY = "YOUR GOOGLE MAPS API KEYS"; + + +function HB_loadScript(url, callback){ + + try { + console.debug("HB_loadScript:", url, callback); + var script = document.createElement("script") + script.type = "text/javascript"; + script.onload = function(){ + console.debug("HB_loadScript callback:", url, callback); + callback(); + }; + script.src = url; + document.getElementsByTagName("head")[0].appendChild(script); + } + catch (e) { + console.debug("HB_loadScript error:", url, callback, e); + setTimeout(() => { + HB_loadScript(url, callback) + }, 5000); + } +} + + +function throttle_events(event) +{ + var now = window.performance.now(); + var distance = Math.sqrt(Math.pow(event.clientX - mthrottle_last.x, 2) + Math.pow(event.clientY - mthrottle_last.y, 2)); + var time = now - mthrottle_last.time; + if (distance * time < mthrottle_space * mthrottle_period) { //event arrived too soon or mouse moved too little or both + if (event.stopPropagation) { // W3C/addEventListener() + event.stopPropagation(); + } else { // Older IE. + event.cancelBubble = true; + } + } else { + mthrottle_last.time = now; + mthrottle_last.x = event.clientX; + mthrottle_last.y = event.clientY; + } +} + + +function HB_BuildGoogleMap(parent_div) { + setTimeout(() => { + HB_BuildGoogleMap_TryLoad(parent_div) + }, 1); + + return { "tab_name": "GMap", "tab_nav": [] }; +} + + +function HB_BuildGoogleMap_TryLoad(parent_div) { + try { + const script = document.createElement('script'); + document.body.appendChild(script); + script.onload = () => { + HB_BuildGoogleMap_DoIt(parent_div) + }; + script.onerror = () => { + // console.debug("HB_BuildGoogleMap_TryLoad fail."); + setTimeout(() => { + HB_BuildGoogleMap_TryLoad(parent_div) + }, 10000); + } + script.async = false; + script.src = 'https://maps.googleapis.com/maps/api/js?key=' + GMAPS_API_KEY; + } + catch(e) { + // console.debug("HB_BuildGoogleMap_TryLoad fail.", e); + setTimeout(() => { + HB_BuildGoogleMap_TryLoad(parent_div) + }, 10000); + } +} + + +function HB_BuildGoogleMap_DoIt(parent_div) { + + var map_div = document.createElement("div"); + map_div.id = "googlemap"; + map_div.style.display = "flex"; + map_div.style.flexGrow = "1"; + + parent_div.appendChild(map_div); + + google.maps.visualRefresh = true; + + var mapOptions = { + center: new google.maps.LatLng(52, 21), + zoom: 13, + mapTypeControl: true, + mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }, + mapTypeIds: [ + google.maps.MapTypeId.ROADMAP, + google.maps.MapTypeId.TERRAIN + ], + zoomControl: true, + zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE }, + //styles: map_style_browns, //map_style_mc map_style_blue + key: GMAPS_API_KEY + }; + + + // if(window.performance && window.performance.now && window.navigator.userAgent.indexOf("Firefox") != -1) map_div.addEventListener("mousemove", throttle_events, true); + + HB_GoogleMap = new google.maps.Map(map_div, mapOptions); + google.maps.event.addListenerOnce( HB_GoogleMap, 'idle', function() {google.maps.event.trigger(HB_GoogleMap, 'resize');} ); + google.maps.event.trigger(HB_GoogleMap, 'resize'); + + HB_GoogleMap_Marker_Habboy = new google.maps.Marker( + { position: new google.maps.LatLng(52, 21), + map: HB_GoogleMap, + //labelContent: PAYLOAD_NAME, + ////labelAnchor: initPos, + // labelAnchor: new google.maps.Point(-15, 35), + labelClass: 'labels', // the CSS class for the label + labelInBackground: false, + icon: { + path: google.maps.SymbolPath.CIRCLE, + scale: 10, + fillColor: "rgb(0,255,0)", + fillOpacity: 1, + strokeWeight: 1 + }, + /* + icon: { + url: 'img/balloon.png', + scaledSize: new google.maps.Size(64,64), + size: new google.maps.Size(64,64), + anchor: new google.maps.Point(32,32), + //anchor: new google.maps.Point(23, 42), + //anchor: new google.maps.Point(23, 105), + }, + */ + } + ); + + HB_GoogleMap_Marker_Landing = new google.maps.Marker( + { position: new google.maps.LatLng(52.1, 21.1), + map: HB_GoogleMap, + //labelContent: PAYLOAD_NAME, + ////labelAnchor: initPos, + // labelAnchor: new google.maps.Point(-15, 35), + labelClass: 'labels', // the CSS class for the label + labelInBackground: false, + icon: { + path: google.maps.SymbolPath.CIRCLE, + fillColor: "rgb(255,255,0)", + // url: 'img/balloon.png', + scale: 10, + fillOpacity: 1, + strokeWeight: 1 + } + } + ); + + HB_GoogleMap_Marker_Payload = new google.maps.Marker( + { position: new google.maps.LatLng(52.1, 21), + map: HB_GoogleMap, + //labelContent: PAYLOAD_NAME, + ////labelAnchor: initPos, + // labelAnchor: new google.maps.Point(-15, 35), + labelClass: 'labels', // the CSS class for the label + labelInBackground: false, + icon: { + path: google.maps.SymbolPath.CIRCLE, + fillColor: "rgb(255,80,0)", + // url: 'img/balloon.png', + scale: 10, + fillOpacity: 1, + strokeWeight: 1 + } + } + ); + + HB_GoogleMap_directionsService = new google.maps.DirectionsService; + HB_GoogleMap_directionsDisplay = new google.maps.DirectionsRenderer({ + preserveViewport: true, + polylineOptions: {strokeColor: "rgb(255, 120,0)"}, + markerOptions: {visible: false} + }); + HB_GoogleMap_directionsDisplay.setMap(HB_GoogleMap); + + // HB_GoogleMap.set('styles', HB_GMAP_style_red); + + // HB_Map_BuildFollowButtons(parent_div); + + HB_GoogleMap_AutoZoom(); + HB_GoogleMap_PayloadPos(); + // HG_GoogleMap_NavigationUpdate(); + + return { "tab_name": "GMap", "tab_nav": [] }; + +} + + +// updates DEVICE and payload markers position +function HB_GoogleMap_PayloadPos() { + if(HABBOY_PAYLOAD_ID in HB_VEHICLES_GPS_LAST) + { + var current_pos = new google.maps.LatLng( HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]["latitude"], HB_VEHICLES_GPS_LAST[HABBOY_PAYLOAD_ID]["longitude"] ); + + HB_GoogleMap_Marker_Payload.setPosition( current_pos ); + //marker.labelContent = PAYLOAD_NAME + '\n' + alt; + //marker.label.setStyles(); + HB_GoogleMap_Marker_Payload.setShape(); + //marker.label.draw(); + } + + // if( HB_DEVICE_GPS_LAST['DEVICE']["latitude"] ) + // { + // var device_pos = new google.maps.LatLng( HB_DEVICE_GPS_LAST['DEVICE']["latitude"], HB_DEVICE_GPS_LAST['DEVICE']["longitude"] ); + // HB_GoogleMap_Marker_Device.setPosition( device_pos ); + // HB_GoogleMap_Marker_Device.setShape(); + // } + + if( HB_DEVICE_GPS_LAST['HABBOY']["latitude"] ) + { + var habboy_pos = new google.maps.LatLng( HB_DEVICE_GPS_LAST['HABBOY']["latitude"], HB_DEVICE_GPS_LAST['HABBOY']["longitude"] ); + HB_GoogleMap_Marker_Habboy.setPosition( habboy_pos ); + HB_GoogleMap_Marker_Habboy.setShape(); + } + + if( HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID] && HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID].length>1 ) { + var last = HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID].length; + var landing_lat_lon = new google.maps.LatLng( [HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID][last-1][1], + HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID][last-1][2]] ); + HB_GoogleMap_Marker_Landing.setPosition( landing_lat_lon ); + HB_GoogleMap_Marker_Landing.setShape(); + } + + setTimeout(HB_GoogleMap_PayloadPos, 3000); +} + + +function HG_GoogleMap_NavigationUpdate() +{ + console.debug('HG_GoogleMap_NavigationUpdate'); + if( HB_VEHICLES_PREDICT && HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID] ) + { + let origin = [ HB_DEVICE_GPS_LAST["HABBOY"]["latitude"], HB_DEVICE_GPS_LAST["HABBOY"]["longitude"] ]; + var last = HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID].length; + var landing_lat_lon = [ HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID][last-1][1], + HB_VEHICLES_PREDICT[HABBOY_PAYLOAD_ID][last-1][2] ]; + let destination = landing_lat_lon; + + console.debug('google nav'); + HB_GoogleMap_directionsService.route({ + origin: origin[0] + ',' + origin[1], + destination: destination[0] + ',' + destination[1], + travelMode: 'DRIVING' + }, function(response, status) { + if (status === 'OK') { + console.debug(response); + HB_GoogleMap_directionsDisplay.setDirections(response); + setTimeout(HG_GoogleMap_NavigationUpdate, 60 * 1000); + } else { + console.debug('HG_GoogleMap_NavigationUpdate failed: ' + status); + setTimeout(HG_GoogleMap_NavigationUpdate, 30 * 1000); + } + } + ); + + setTimeout(HG_GoogleMap_NavigationUpdate, 60 * 1000); + + } + else{ + console.debug('google nav - no HB_VEHICLES_PREDICT'); + setTimeout(HG_GoogleMap_NavigationUpdate, 10 * 1000); + } + +} + + +function HB_GoogleMap_AutoZoom() { + if (HB_Map_FollowPayloads || HB_Map_FollowDevice || HB_Map_FollowHabBoy) { + try { + if( G_HB_Map_TrackBounds['_sw']["lat"] == G_HB_Map_TrackBounds['_ne']["lat"] + && G_HB_Map_TrackBounds['_sw']['lng'] == G_HB_Map_TrackBounds['_ne']['lng'] ) + { // center + HB_GoogleMap.setCenter( new google.maps.LatLng(G_HB_Map_TrackBounds['_sw']["lat"], G_HB_Map_TrackBounds['_sw']['lng']) ); + } + else + { // fit + var bounds = new google.maps.LatLngBounds(); + bounds.extend( new google.maps.LatLng(G_HB_Map_TrackBounds['_sw']["lat"], G_HB_Map_TrackBounds['_sw']['lng']) ); + bounds.extend( new google.maps.LatLng(G_HB_Map_TrackBounds['_ne']["lat"], G_HB_Map_TrackBounds['_ne']['lng']) ); + HB_GoogleMap.fitBounds(bounds); + } + } + catch (e) { + console.debug('HB_GoogleMap_AutoZoom err: ', e); + } + } + else { + } + setTimeout(HB_GoogleMap_AutoZoom, 3000); +} + + +var HB_GMAP_style_blue = [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#193341"}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#2c5a71"}]},{"featureType":"road","elementType":"geometry","stylers":[{"color":"#29768a"},{"lightness":-37}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#406d80"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#406d80"}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#3e606f"},{"weight":2},{"gamma":0.84}]},{"elementType":"labels.text.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"administrative","elementType":"geometry","stylers":[{"weight":0.6},{"color":"#1a3541"}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#2c5a71"}]}]; +var HB_GMAP_style_mc = [{"featureType":"all","elementType":"labels.text.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"all","elementType":"labels.text.stroke","stylers":[{"color":"#000000"},{"lightness":13}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#000000"}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#144b53"},{"lightness":14},{"weight":1.4}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#08304b"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#0c4152"},{"lightness":5}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#000000"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#0b434f"},{"lightness":25}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#000000"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"color":"#0b3d51"},{"lightness":16}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#000000"}]},{"featureType":"transit","elementType":"all","stylers":[{"color":"#146474"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#021019"}]}]; +var HB_GMAP_style_browns = [{"elementType":"geometry","stylers":[{"hue":"#ff4400"},{"saturation":-68},{"lightness":-4},{"gamma":0.72}]},{"featureType":"road","elementType":"labels.icon"},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"hue":"#0077ff"},{"gamma":3.1}]},{"featureType":"water","stylers":[{"hue":"#00ccff"},{"gamma":0.44},{"saturation":-33}]},{"featureType":"poi.park","stylers":[{"hue":"#44ff00"},{"saturation":-23}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"hue":"#007fff"},{"gamma":0.77},{"saturation":65},{"lightness":99}]},{"featureType":"water","elementType":"labels.text.stroke","stylers":[{"gamma":0.11},{"weight":5.6},{"saturation":99},{"hue":"#0091ff"},{"lightness":-86}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"lightness":-48},{"hue":"#ff5e00"},{"gamma":1.2},{"saturation":-23}]},{"featureType":"transit","elementType":"labels.text.stroke","stylers":[{"saturation":-64},{"hue":"#ff9100"},{"lightness":16},{"gamma":0.47},{"weight":2.7}]}]; +var HB_GMAP_style_red = [{"featureType":"all","elementType":"labels.text.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"all","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"all","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#c9323b"}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#c9323b"},{"weight":1.2}]},{"featureType":"administrative.locality","elementType":"geometry.fill","stylers":[{"lightness":"-1"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.fill","stylers":[{"lightness":"0"},{"saturation":"0"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.stroke","stylers":[{"weight":"0.01"}]},{"featureType":"administrative.land_parcel","elementType":"labels.text.stroke","stylers":[{"weight":"0.01"}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#c9323b"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#99282f"}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#99282f"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.stroke","stylers":[{"color":"#99282f"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#99282f"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#99282f"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#99282f"}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#090228"}]}]; +var HB_GMAP_style_red2 = [{"featureType":"all","elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#000000"},{"lightness":40}]},{"featureType":"all","elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#000000"},{"lightness":16}]},{"featureType":"all","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#000000"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#000000"},{"lightness":17},{"weight":1.2}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":20}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":21}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#000000"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#000000"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":16}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#000000"},{"lightness":19}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#952d2d"},{"lightness":17}]}]; +var HB_GMAP_style_hopper = [{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#165c64"},{"saturation":34},{"lightness":-69},{"visibility":"on"}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"hue":"#b7caaa"},{"saturation":-14},{"lightness":-18},{"visibility":"on"}]},{"featureType":"landscape.man_made","elementType":"all","stylers":[{"hue":"#cbdac1"},{"saturation":-6},{"lightness":-9},{"visibility":"on"}]},{"featureType":"road","elementType":"geometry","stylers":[{"hue":"#8d9b83"},{"saturation":-89},{"lightness":-12},{"visibility":"on"}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"hue":"#d4dad0"},{"saturation":-88},{"lightness":54},{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"hue":"#bdc5b6"},{"saturation":-89},{"lightness":-3},{"visibility":"simplified"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"hue":"#bdc5b6"},{"saturation":-89},{"lightness":-26},{"visibility":"on"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"hue":"#c17118"},{"saturation":61},{"lightness":-45},{"visibility":"on"}]},{"featureType":"poi.park","elementType":"all","stylers":[{"hue":"#8ba975"},{"saturation":-46},{"lightness":-28},{"visibility":"on"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"hue":"#a43218"},{"saturation":74},{"lightness":-51},{"visibility":"simplified"}]},{"featureType":"administrative.province","elementType":"all","stylers":[{"hue":"#ffffff"},{"saturation":0},{"lightness":100},{"visibility":"simplified"}]},{"featureType":"administrative.neighborhood","elementType":"all","stylers":[{"hue":"#ffffff"},{"saturation":0},{"lightness":100},{"visibility":"off"}]},{"featureType":"administrative.locality","elementType":"labels","stylers":[{"hue":"#ffffff"},{"saturation":0},{"lightness":100},{"visibility":"off"}]},{"featureType":"administrative.land_parcel","elementType":"all","stylers":[{"hue":"#ffffff"},{"saturation":0},{"lightness":100},{"visibility":"off"}]},{"featureType":"administrative","elementType":"all","stylers":[{"hue":"#3a3935"},{"saturation":5},{"lightness":-57},{"visibility":"off"}]},{"featureType":"poi.medical","elementType":"geometry","stylers":[{"hue":"#cba923"},{"saturation":50},{"lightness":-46},{"visibility":"on"}]}] + +var HB_GMAP_COLOR_SCHEMES = { + 'BLUE': HB_GMAP_style_blue, + 'RED': HB_GMAP_style_red2, + 'GREEN': HB_GMAP_style_hopper, + 'GOLD': HB_GMAP_style_browns, + 'PLUM': HB_GMAP_style_mc +} + + diff --git a/webUI/code/js/HB_hw_iface.js b/webUI/code/js/HB_hw_iface.js new file mode 100644 index 0000000..eafe5d7 --- /dev/null +++ b/webUI/code/js/HB_hw_iface.js @@ -0,0 +1,96 @@ + +var HB_hw_iface_websocket; + + +function HB_HandleHwMessage(msg) +{ + msg = msg.replace('\r', ''); + msg = msg.replace('\n', ''); + + // console.debug('HB_HandleHwMessage: ', msg); + + var msg_parts = msg.split("::"); + + if(msg_parts[0] == "gps") + { + gps_result = { + 'time': '1970-01-01 12:00:00', + "latitude": 0, + "longitude": 0, + "altitude": 0, + 'speed': 0, // kmph + 'heading': 0, + 'sats': 0, + 'ground_speed_mps': 0, // m/s + 'ascent_mps': 0 // m/s + }; + + var kv = msg_parts[1].split(","); + for(i in kv) + { + var tokens = kv[i].split("="); + // console.debug(tokens[0], tokens[1]); + if(tokens[0] == "time") gps_result['time'] = tokens[1]; + if(tokens[0] == "lat") gps_result['latitude'] = parseFloat( tokens[1] ) * 1e-7; + if(tokens[0] == "lon") gps_result['longitude'] = parseFloat( tokens[1] ) * 1e-7; + if(tokens[0] == "alt") gps_result['altitude'] = parseFloat( tokens[1] ); + if(tokens[0] == "speed") gps_result['speed'] = parseFloat( tokens[1] ); + if(tokens[0] == "heading") gps_result['heading'] = parseFloat( tokens[1] ); + if(tokens[0] == "sats") gps_result['sats'] = parseInt( tokens[1] ); + } + HB_DEVICE_GPS_LAST["HABBOY"] = gps_result; + } + else if(msg_parts[0] == "tab") + { + var tokens = msg_parts[1].split("="); + if(tokens[0] == "cycle") HB_CycleTabs(parseInt(tokens[1])); + } + else if(msg_parts[0] == "rot") + { + HB_CycleTabs( parseInt(msg_parts[1]) ); + } +} + +function HB_hw_iface_open(endpoint) +{ + HB_hw_iface_websocket = new WebSocket(endpoint); + // console.debug("HB_hw_iface_open: ", HB_hw_iface_websocket); + + if(HB_hw_iface_websocket === undefined) + { + setTimeout(function () { HB_hw_iface_open(endpoint); }, 1000); + return; + } + + HB_hw_iface_websocket.onopen = function (ev) { + console.debug("Hardware interface connection opened"); + }; + + HB_hw_iface_websocket.onclose = function (ev) { + HB_hw_iface_websocket = undefined; + console.debug("Hardware interface connection closed"); + HB_hw_iface_open(endpoint); + }; + + HB_hw_iface_websocket.onmessage = function (ev) { + var msg = ev.data; + HB_DEVICE_GPS_LAST["HABBOY"] = ["000000", [52 + .001*Math.random(),21 + .001*Math.random(),80, 150, 350, 11]]; + HB_HandleHwMessage(msg); + }; + + HB_hw_iface_websocket.onerror = function (ev) { + console.debug("Hardware interface error"); + console.log(ev); + // HB_hw_iface_open(endpoint); + }; +} + +function HB_hw_iface(endpoint) +{ + HB_hw_iface_open(endpoint); + + /*HB_DEVICE_GPS_LAST = ["000000", [52 + .001*Math.random(),21 + .001*Math.random(),80, 150, 350, 11]]; + setTimeout(() => { + UpdateHabboyGps(); + }, 500);*/ +} \ No newline at end of file diff --git a/webUI/code/js/HB_map.js b/webUI/code/js/HB_map.js new file mode 100644 index 0000000..3a347f4 --- /dev/null +++ b/webUI/code/js/HB_map.js @@ -0,0 +1,803 @@ + +var HB_MAP; +var HB_Map_FollowDevice = 0; // autozoom to show this device on map +var HB_Map_FollowHabBoy = 0; // autozoom to show habboy server +var HB_Map_FollowPayloads = 0; // autozoom to show all vehicles on map +var HB_Map_FollowLanding = 0; // autozoom to show this device on map +var HB_Map_Bearing = false; // rotate map to match HabBoy GPS bearing + +function CreateRadioHorizon(lat, lon, alt, points) { + if(!points) points = 64; + + var coords = { + latitude: lat, + longitude: lon + }; + + var km = Math.sqrt(12.756 * alt); // horizon in kilometers + + var ret = []; + var distanceX = km/(111.320*Math.cos(coords.latitude*Math.PI/180)); + var distanceY = km/110.574; + + var theta, x, y; + for(var i=0; i + HB_Map_PayloadPathUpdate(HABBOY_PAYLOAD_ID, telemetry_data) + ); + // HB_Map_PayloadPathUpdate(HABBOY_PAYLOAD_ID, HB_VEHICLES_TELEMETRY[HABBOY_PAYLOAD_ID]); + + HB_VEHICLES_TELEMETRY_UpdateCallbacks.push(HB_Map_PayloadPredictUpdate); + + // return "MAP"; + return { "tab_name": "MAP", "tab_nav": nav_info }; + } + + + function HB_Map_BuildFollowButtons(parent_div/*, HB_MAP*/) { + + // device + // let's not use DEVICE locations as this requires working over HTTPS + /* + var device_button = document.createElement("button"); + device_button.innerHTML = "Me"; + device_button.style.position = "absolute"; + device_button.style.bottom = "35vh"; + device_button.style.left = "0"; + device_button.style.height = "13%"; + device_button.style.width = "13%"; + if (HB_Map_FollowDevice) + device_button.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + device_button.style.backgroundColor = HB_get_css_val('--HB_button'); + device_button.onclick = function () { + HB_Map_FollowDevice = !HB_Map_FollowDevice; + if (HB_Map_FollowDevice) + device_button.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + device_button.style.backgroundColor = HB_get_css_val('--HB_button'); + }; + parent_div.appendChild(device_button); + */ + + // HABBOY + var habboy_button = document.createElement("button"); + habboy_button.innerHTML = "HabBoy"; + habboy_button.style.position = "absolute"; + habboy_button.style.bottom = "30vh"; + habboy_button.style.left = "0"; + habboy_button.style.height = "13%"; + habboy_button.style.width = "13%"; + if (HB_Map_FollowHabBoy) + habboy_button.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + habboy_button.style.backgroundColor = HB_get_css_val('--HB_button'); + habboy_button.onclick = function () { + HB_Map_FollowHabBoy = !HB_Map_FollowHabBoy; + if (HB_Map_FollowHabBoy) + habboy_button.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + habboy_button.style.backgroundColor = HB_get_css_val('--HB_button'); + }; + parent_div.appendChild(habboy_button); + + // payload + var payload_button = document.createElement("button"); + payload_button.innerHTML = "Payload"; + payload_button.style.position = "absolute"; + payload_button.style.bottom = "45vh"; + payload_button.style.left = "0"; + payload_button.style.height = "13%"; + payload_button.style.width = "13%"; + if (HB_Map_FollowPayloads) + payload_button.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + payload_button.style.backgroundColor = HB_get_css_val('--HB_button'); + payload_button.onclick = function () { + HB_Map_FollowPayloads = !HB_Map_FollowPayloads; + if (HB_Map_FollowPayloads) + payload_button.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + payload_button.style.backgroundColor = HB_get_css_val('--HB_button'); + }; + parent_div.appendChild(payload_button); + + // landing spot + // payload + var landing_button = document.createElement("button"); + landing_button.innerHTML = "Land Spot"; + landing_button.style.position = "absolute"; + landing_button.style.bottom = "60vh"; + landing_button.style.left = "0"; + landing_button.style.height = "13%"; + landing_button.style.width = "13%"; + if (HB_Map_FollowLanding) + landing_button.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + landing_button.style.backgroundColor = HB_get_css_val('--HB_button'); + landing_button.onclick = function () { + HB_Map_FollowLanding = !HB_Map_FollowLanding; + if (HB_Map_FollowLanding) + landing_button.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + landing_button.style.backgroundColor = HB_get_css_val('--HB_button'); + }; + parent_div.appendChild(landing_button); + + // orient map button + // + var map_orient_bt = document.createElement("button"); + // map_orient_bt.innerHTML = String.fromCharCode(0x2b99); + // map_orient_bt.innerHTML = '^'; + map_orient_bt.innerHTML = '^'; // compass symbol "🧭" + map_orient_bt.style.position = "absolute"; + map_orient_bt.style.bottom = "75vh"; + map_orient_bt.style.left = "0"; + map_orient_bt.style.height = "13%"; + map_orient_bt.style.width = "13%"; + map_orient_bt.onclick = function () { + HB_Map_Bearing = ! HB_Map_Bearing; + if(HB_Map_Bearing) + map_orient_bt.style.backgroundColor = HB_get_css_val('--HB_button_active'); + else + map_orient_bt.style.backgroundColor = HB_get_css_val('--HB_button'); + } + parent_div.appendChild(map_orient_bt); + + // return [device_button, payload_button, habboy_button]; + return [payload_button, habboy_button, landing_button, map_orient_bt]; + + } + + + function HB_Map_BuildLayersMenu(parent_div, map) { + + // menu content + // + var grid_div = document.createElement("div"); + grid_div.id = "HG_MapLayersGrid" + grid_div.style.display = "none"; + grid_div.style.gridTemplateColumns = "auto auto auto auto"; + grid_div.style.width = "70%"; + grid_div.style.height = "50%"; + grid_div.style.position = "absolute"; + grid_div.style.bottom = "20vh"; + grid_div.style.left = "15%"; + // grid_div.style.zIndex = "-1"; + + // menu button + // + var menu_button = document.createElement("button"); + menu_button.innerHTML = "Layers"; + menu_button.style.position = "absolute"; + menu_button.style.bottom = "15vh"; + menu_button.style.left = "0"; + menu_button.style.height = "13%"; + menu_button.style.width = "13%"; + menu_button.onclick = function () { + if (grid_div.style.display === "grid") + grid_div.style.display = "none"; + else if (grid_div.style.display === "none") + grid_div.style.display = "grid"; + } + + // colors of buttons + var color_button = HB_get_css_val('--HB_button'); + menu_button.style.background = color_button; + + + + var display_groups = { + "green": [ + "landuse_forest", + "wood", + "landuse_park", + "landuse_grass", + "bush", + "natural_other", + ], + "farm": [ + "landuse_farmland", + "country", + "soil", + ], + "water": [ + "water", + "wetland", + "mud", + "river", + ], + "other": [ + "landuse_residential", + "landuse_com", + "landuse_other", + ], + "air": [ + "aeroway", + "aeroway_other", + ], + "road": [ + "road_main", + "road_secondary", + "road_tertiary", + "road_other", + "railway", + // "river", + ], + "buildings": [ + "building", + ], + "admin": [ + "admin", + "road_label", + "place_city", + "place_other" + ] + // "background", + }; + + var layer_buttons = []; + + // for (let display_group of Object.keys(display_groups)) { + var style = HB_map_style_bright(); + for (let display_group of style.layers) { + var b = document.createElement('button'); + // b.innerHTML = display_group; + b.innerHTML = display_group.id; + b.style.opacity = .75; + b.style.background = color_button; + // b.onclick = function (e) { HB_Map_ToggleDisplayGrp(e, map, display_groups[display_group]); } + b.onclick = function (e) { HB_Map_ToggleDisplayGrp(e, map, [display_group.id]); } + grid_div.appendChild(b); + + layer_buttons.push(b); + } + + parent_div.appendChild(grid_div); + parent_div.appendChild(menu_button); + + return [menu_button, layer_buttons]; + + } + + + function HB_Map_ToggleDisplayGrp(e, map, layers_arr) { + e.preventDefault(); + e.stopPropagation(); + + for (var j = 0; j < layers_arr.length; j++) { + var layer = layers_arr[j]; + var visibility = map.getLayoutProperty(layer, 'visibility'); + if (visibility === 'visible') + map.setLayoutProperty(layer, 'visibility', 'none'); + else + map.setLayoutProperty(layer, 'visibility', 'visible'); + } + } + + + + // PAYLOADS + // + + var G_HB_Map_PayloadPos = {}; // position for all tracked payloads + var G_HB_Map_TrackBounds = new mapboxgl.LngLatBounds(); + + // updates DEVICE and payload markers position + function HB_Map_PayloadPos(payload_id) { + + var data_arr = []; + G_HB_Map_TrackBounds = new mapboxgl.LngLatBounds(); + + var vehicles = HB_VEHICLES_GPS_LAST; + for (v in vehicles) { + if (!(v in G_HB_Map_PayloadPos)) { + G_HB_Map_PayloadPos[v] = { + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [21, 52] + }, + "properties": { + "title": v + } + } + } + + data_arr.push(G_HB_Map_PayloadPos[v]); + + if (vehicles[v] != undefined) { + var lat = vehicles[v]["latitude"]; + var lon = vehicles[v]["longitude"]; + + if (HB_Map_FollowPayloads && lat && lon) + G_HB_Map_TrackBounds.extend(new mapboxgl.LngLat(lon, lat)); + + G_HB_Map_PayloadPos[v].geometry.coordinates = [lon, lat]; + G_HB_Map_PayloadPos[v].properties.title = v + " " + vehicles[v]["altitude"].toString(); + } + + } // for (v in vehicles) + + if (HB_Map_FollowDevice) { + var lat = HB_DEVICE_GPS_LAST["DEVICE"]["latitude"]; + var lon = HB_DEVICE_GPS_LAST["DEVICE"]["longitude"]; + if (lat && lon) + G_HB_Map_TrackBounds.extend(new mapboxgl.LngLat(lon, lat)); + } + + if (HB_Map_FollowHabBoy) { + var lat = HB_DEVICE_GPS_LAST["HABBOY"]["latitude"]; + var lon = HB_DEVICE_GPS_LAST["HABBOY"]["longitude"]; + if (lat && lon) + G_HB_Map_TrackBounds.extend(new mapboxgl.LngLat(lon, lat)); + } + + if (HB_Map_FollowLanding) { + // local predict + if(HB_VEHICLES_PREDICT[payload_id]) { + var sz = HB_VEHICLES_PREDICT[payload_id].length; + if(sz) { + var landing_lon_lat = [ HB_VEHICLES_PREDICT[payload_id][sz-1][2], HB_VEHICLES_PREDICT[payload_id][sz-1][1] ]; + if (landing_lon_lat[0] && landing_lon_lat[1]) + G_HB_Map_TrackBounds.extend(new mapboxgl.LngLat(landing_lon_lat[0], landing_lon_lat[1])); + } + } + // habitat predict + if(HB_VEHICLES_PREDICT_HABITAT[payload_id]) { + var sz = HB_VEHICLES_PREDICT_HABITAT[payload_id].length; + if(sz) { + var landing_lon_lat = [ parseFloat(HB_VEHICLES_PREDICT_HABITAT[payload_id][sz-1]['lon']), + parseFloat(HB_VEHICLES_PREDICT_HABITAT[payload_id][sz-1]['lat']) ]; + if (landing_lon_lat[0] && landing_lon_lat[1]) + G_HB_Map_TrackBounds.extend(new mapboxgl.LngLat(landing_lon_lat[0], landing_lon_lat[1])); + } + } + } + + + HB_MAP.getSource('payloads').setData({ "type": "FeatureCollection", "features": data_arr }); + // HB_MAP.getSource('DEVICE').setData({ "type": "Point", "coordinates": [HB_DEVICE_GPS_LAST['DEVICE']["longitude"], HB_DEVICE_GPS_LAST['DEVICE']["latitude"]] }); + HB_MAP.getSource('HABBOY').setData({ "type": "Point", "coordinates": [HB_DEVICE_GPS_LAST['HABBOY']["longitude"], HB_DEVICE_GPS_LAST['HABBOY']["latitude"]] }); + + setTimeout( ()=>{HB_Map_PayloadPos(payload_id)}, 500); + } + + + function HB_Map_AutoZoomAndBearing() { + var goals_num = HB_Map_FollowPayloads + HB_Map_FollowDevice + HB_Map_FollowHabBoy + HB_Map_FollowLanding; + if (goals_num) { + try { + if(goals_num > 1) { + HB_MAP.fitBounds(G_HB_Map_TrackBounds, { + padding: { top: 130, bottom: 130, left: 130, right: 130 }, + maxZoom: HB_MAP.getZoom() + }); + } + else if(goals_num == 1){ + HB_MAP.easeTo({ + center: G_HB_Map_TrackBounds.getCenter(), + bearing: HB_Map_Bearing * HB_DEVICE_GPS_LAST['HABBOY']['heading'], + }); + } + } + catch (e) { + console.debug('HB_Map_AutoZoomAndBearing err: ', e); + } + } + else { + } + + setTimeout(HB_Map_AutoZoomAndBearing, 3000); + } + + + var G_HB_Map_PayloadsPathGeoJson = {}; // mapbox paths for payload_id's + function HB_Map_PayloadPathUpdate(payload_id, data) { + // console.debug("HB_Map_PayloadPathUpdate ", data); + + if(!data) + return; + + if (!(payload_id in G_HB_Map_PayloadsPathGeoJson)) { + G_HB_Map_PayloadsPathGeoJson[payload_id] = { + "type": "FeatureCollection", + "features": [{ + "type": "Feature", + "geometry": { + "type": "LineString", + "coordinates": [ + ] + } + }] + }; + } + + for (var i in data['latitude']["values"]) { + G_HB_Map_PayloadsPathGeoJson[payload_id]["features"][0]["geometry"]["coordinates"].push( + [ data['longitude']["values"][i], + data['latitude']["values"][i] ] + ); + } + + if( HB_MAP.getSource('payloads_path') ) { + HB_MAP.getSource('payloads_path').setData( + G_HB_Map_PayloadsPathGeoJson[payload_id] + ); + // console.debug(G_HB_Map_PayloadsPathGeoJson[payload_id]["features"][0]["geometry"]["coordinates"]); + } + + if( HB_MAP.getSource('horizon') ) { + HB_MAP.getSource('horizon').setData( + CreateRadioHorizon( + data['latitude']["values"][0], + data['longitude']["values"][0], + data['altitude']["values"][0] + , 64 ) + ); + } + + } + + + function HB_Map_PayloadPredictUpdate() { + + // predict path + let payload_id = HABBOY_PAYLOAD_ID; + var pred_path_data = { + "type": "FeatureCollection", + "features": [{ + "type": "Feature", + "geometry": { + "type": "LineString", + "coordinates": [ + ] + } + }] + }; + + var pred_path_data_hab = { + "type": "FeatureCollection", + "features": [{ + "type": "Feature", + "geometry": { + "type": "LineString", + "coordinates": [ + ] + } + }] + };; + + for (var i in HB_VEHICLES_PREDICT[payload_id]) { + pred_path_data["features"][0]["geometry"]["coordinates"].push( + [ HB_VEHICLES_PREDICT[payload_id][i][2], + HB_VEHICLES_PREDICT[payload_id][i][1] ] + ); + } + + for (var i in HB_VEHICLES_PREDICT_HABITAT[payload_id]) { + pred_path_data_hab["features"][0]["geometry"]["coordinates"].push( + [ parseFloat(HB_VEHICLES_PREDICT_HABITAT[payload_id][i]['lon']), + parseFloat(HB_VEHICLES_PREDICT_HABITAT[payload_id][i]['lat']) ] + ); + } + + if( HB_MAP.getSource('payloads_predict') ) { + HB_MAP.getSource('payloads_predict').setData(pred_path_data); + } + + if( HB_MAP.getSource('payloads_predict_habitat') ) { + HB_MAP.getSource('payloads_predict_habitat').setData(pred_path_data_hab); + } + + // landing spot + var src_land = HB_MAP.getSource('Landing'); + if(HB_VEHICLES_PREDICT[payload_id]) { + var sz = HB_VEHICLES_PREDICT[payload_id].length; + if(sz && src_land) { + var landing_lon_lat = [ HB_VEHICLES_PREDICT[payload_id][sz-1][2], HB_VEHICLES_PREDICT[payload_id][sz-1][1] ]; + src_land.setData( { "type": "Point", "coordinates": landing_lon_lat } ); + } + } + + // landing spot - habitat + var src_land_habitat = HB_MAP.getSource('LandingHabitat'); + if(HB_VEHICLES_PREDICT_HABITAT[payload_id]) { + var sz = HB_VEHICLES_PREDICT_HABITAT[payload_id].length; + if(sz && src_land_habitat) { + var landing_h_lon_lat = [ + parseFloat(HB_VEHICLES_PREDICT_HABITAT[payload_id][sz-1]['lon']), + parseFloat(HB_VEHICLES_PREDICT_HABITAT[payload_id][sz-1]['lat']) ]; + src_land_habitat.setData( { "type": "Point", "coordinates": landing_h_lon_lat } ); + } + } + + } diff --git a/webUI/code/js/HB_map_style_bright.js b/webUI/code/js/HB_map_style_bright.js new file mode 100644 index 0000000..07969fa --- /dev/null +++ b/webUI/code/js/HB_map_style_bright.js @@ -0,0 +1,595 @@ + +function HB_map_style_bright() { + var land_type_min_zoom = 9; + + // var data_root = location.origin + "/habboy/open_street_map/vector_tiles/poland/"; + // var fonts = location.origin + "/habboy/open_street_map/font/{fontstack}/{range}.pbf"; + + // var data_root = "http://" + HABBOY_URL + "/osm/poland_layered"; + // var fonts = "http://" + HABBOY_URL + "/osm/font/{fontstack}/{range}.pbf"; + + var data_root = HABBOY_URL + "/osm/tiles"; + var fonts = HABBOY_URL + "/osm/font/{fontstack}/{range}.pbf"; + + var data_path_template = "{z}/{x}/{y}.pbf"; + + var green_opacity = .5; + var farm_opacity = .5; + var water_opacity = .65; + + var style = + { + // "id": "g61ohl2cd", + "version": 8, + "name": "hab", + "metadata": { + "mapbox:autocomposite": true, + "mapbox:type": "template" + }, + + "glyphs": fonts, + + // minzoom / maxzoom must be the same as in .json + "sources": { + "landuse": { + "type": "vector", + "tiles": [data_root + "/landuse/" + data_path_template], + "minzoom": 9, "maxzoom": 14 + }, + "water": { + "type": "vector", + "tiles": [data_root + "/water/" + data_path_template], + "minzoom": 5, "maxzoom": 14 + }, + "aeroway": { + "type": "vector", + "tiles": [data_root + "/aeroway/" + data_path_template], + "minzoom": 9, "maxzoom": 14 + }, + "roads": { + "type": "vector", + "tiles": [data_root + "/roads/" + data_path_template], + "minzoom": 5, "maxzoom": 14 + }, + "buildings": { + "type": "vector", + "tiles": [data_root + "/buildings/" + data_path_template], + "minzoom": 15, "maxzoom": 15 + }, + "labels": { + "type": "vector", + "tiles": [data_root + "/labels/" + data_path_template], + "minzoom": 6, "maxzoom": 15 + }, + "admin": { + "type": "vector", + "tiles": [data_root + "/admin/" + data_path_template], + "minzoom": 5, "maxzoom": 10 + } + }, + + + // layers order determines drawing order + "layers": [ + { + "id": "background", + "type": "background", + "paint": { + "background-color": "hsl(0, 0%, 100%)" + } + }, + + { + "id": "natural_other", + "type": "fill", + "source": "landuse", + "source-layer": "natural", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(60, .8, .75)", + "fill-opacity": green_opacity + }, + }, + + { + "id": "land_other", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(25, .85, .75)", + "fill-opacity": .25 + }, + "filter": [ + "!in", + "class", + "wood", "forest", "national_park", "reservoir", + "park", "grass", "bush", + "soil", "farmland", "farmyard", + "residential", "commercial", "construction", "industrial", "retail", + ], + }, + + { + "id": "woods", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(90, 1.0, .75)", + "fill-opacity": green_opacity + }, + "filter": [ + "in", + "class", + "wood", "forest", "national_park", "reservoir" + ], + }, + + { + "id": "park", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(100, .85, .85)", + "fill-opacity": green_opacity + }, + "filter": [ + "in", + "class", + "park", "grass", "bush" + ], + }, + + { + "id": "farm", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(45, 0.85, 0.75)", + "fill-opacity": farm_opacity + }, + "filter": [ + "in", + "class", + "soil", "farmland", "farmyard" + ], + }, + + { + "id": "civil", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(20, .0, .85)", + }, + "filter": [ + "in", + "class", + "residential", "commercial", "construction", "industrial", "retail" + ], + }, + + + { + "id": "river", + "type": "line", + "source": "water", + "source-layer": "river", + "minzoom": 9, + "paint": { + "line-color": "rgb(0,50,150)", + "line-opacity": water_opacity, + "line-width": { + "base": 2, + "stops": [ + [9, 2], + [10, 5] + ] + } + }, + "filter": [ + "all", + [ + "==", + "$type", + "LineString" + ], + [ + "in", + "class", + "river", + "canal", + // "stream" + ] + ], + }, + + { + "id": "water", + "type": "fill", + "source": "water", + "source-layer": "water", + "minzoom": 9, + "paint": { + "fill-color": "hsl(225, .35, .45)", + "fill-opacity": water_opacity + }, + "filter": [ + "in", + "class", + "riverbank", "water" + ] + }, + + { + "id": "wetland", + "type": "fill", + "source": "water", + "source-layer": "water", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(205, .3, .37)", + "fill-opacity": water_opacity + }, + "filter": [ + "==", + "class", + "wetland" + ] + }, + + { + "id": "mud", + "type": "fill", + "source": "water", + "source-layer": "water", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "rgb(80,50,20)", + "fill-opacity": water_opacity + }, + "filter": [ + "==", + "class", + "mud" + ] + }, + + { + "id": "admin", + "type": "line", + "source": "admin", + "source-layer": "admin", + "filter": [ + "all", + [ + "==", + "$type", + "Polygon" + ], + ], + "paint": { + "line-color": "rgb(0,110,0)", + "line-width": 3 + } + }, + + { + "id": "aeroway", + "type": "fill", + "source": "aeroway", + "source-layer": "aeroway", + "minzoom": 8, + "filter": [ + "!in", "class", "terminal", "hangar" + ], + "paint": { + "fill-color": "rgb(255,90,0)", + "fill-opacity": 0.5 + }, + }, + + { + "id": "aeroway_buildings", + "type": "fill", + "source": "aeroway", + "source-layer": "aeroway", + "minzoom": 14, + "filter": [ + "in", "class", "terminal", "hangar" + ], + "paint": { + "fill-color": "rgb(180,20,0)" + }, + }, + + { + "id": "road_other", + "type": "line", + "source": "roads", + "source-layer": "roads", + "minzoom": 14, // one less than buildings + "filter": [ + "in", + "class", + "track", "road", "living_street", "residential", "footway" + ], + "paint": { + "line-color": "rgb(110,90,80)", + // "line-width": 3 + "line-width": { + "base": 2, + "stops": [ + [10, 0.25], + [14, 1.5] + ] + } + } + }, + + { + "id": "road_tertiary", + "type": "line", + "source": "roads", + "source-layer": "roads", + "minzoom": 10, + "filter": [ + "in", + "class", + "tertiary", "tertiary_link", "unclassified" + ], + "paint": { + "line-color": "rgb(145,120,110)", + "line-width": { + "base": 2, + "stops": [ + [10, 0.8], + [14, 3] + ] + } + } + }, + + { + "id": "road_secondary", + "type": "line", + "source": "roads", + "source-layer": "roads", + "filter": [ + "in", + "class", + "motorway_link", + "trunk_link", + "primary_link", + "secondary", + "secondary_link", + ], + "paint": { + "line-color": "rgb(200,133,66)", + "line-width": { + "base": 2, + "stops": [ + [8, 2], + [11, 4] + ] + } + }, + "layout": { + "line-cap": "round", + "line-join": "miter" + } + }, + + { + "id": "road_main", + "type": "line", + "source": "roads", + "source-layer": "roads", + "filter": [ + "in", + "class", + "motorway", + "trunk", + "primary", + ], + "paint": { + "line-color": "rgb(200,0,0)", + "line-width": { + "base": 2, + "stops": [ + [5, 3], + [9, 6.5] + ] + } + }, + "layout": { + "line-cap": "round", + "line-join": "round" + } + }, + + { + "id": "railways", + "type": "line", + "source": "roads", + "source-layer": "railways", + "minzoom": 13, + "paint": { + "line-color": "rgb(80,80,80)", + "line-width": 2, + "line-dasharray": [6, 3] + } + }, + + { + "id": "building", + "type": "fill", + "source": "buildings", + "source-layer": "building", + "paint": { + "fill-color": "hsl(220, .15, .8)", + // "fill-opacity": .15 + } + }, + + { + "id": "place_city", + "type": "symbol", + "source": "labels", + "source-layer": "place_label", + "filter": [ + "all", + [ + "==", + "$type", + "Point" + ], + [ + "in", + "type", + "capital", + "city", + "town" + ], + [ + ">=", + "scalerank", + 5 + ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-max-width": 6, + "text-size": { + "stops": [ + [10,20], + [15,30] + ] + } + }, + "paint": { + // "text-color": "hsl(220, 0.4, 1)", + "text-color": "rgb(80,255,255)", + "text-halo-color": "rgba(0,0,0,1)", + "text-halo-width": 2, + "text-halo-blur": 1 + } + }, + + { + "id": "place_other", + "type": "symbol", + "source": "labels", + "source-layer": "place_label", + "minzoom": 12, + "filter": [ + "all", + [ + "==", + "$type", + "Point" + ], + [ + "!in", + "type", + "capital", + "city", + "town" + ], + // [ + // "<", + // "scalerank", + // 7 + // ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-max-width": 6, + "text-size": { + "stops": [ + // [6,12], + // [12,16] + [10,10], + [15,15] + ] + } + }, + "paint": { + // "text-color": "hsl(220,0.4,.8)", + "text-color": "rgb(80,255,255)", + "text-halo-color": "rgba(0,0,0,1)", + "text-halo-width": 2, + "text-halo-blur": 1 + } + }, + + { + "id": "road_label", + "type": "symbol", + "source": "labels", + "source-layer": "road_label", + "filter": [ + "all", + [ + "==", + "$type", + "LineString" + ], + ], + "layout": { + "symbol-placement": "line", + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-transform": "uppercase", + "text-letter-spacing": 0.1, + "text-size": { + // "base": 1.4, + "base": 2, + "stops": [ + // [10,8], + // [20,14] + [10,10], + [15,15] + ] + } + }, + "paint": { + "text-color": "rgb(0,0,0)", + "text-halo-color": "rgba(255,255,255,1)", + "text-halo-width": 2, + "text-halo-blur": 1 + } + }, + + ] // layers + }; // STYLE + + + + return style; +} diff --git a/webUI/code/js/HB_map_style_default.js b/webUI/code/js/HB_map_style_default.js new file mode 100644 index 0000000..ce9fa3c --- /dev/null +++ b/webUI/code/js/HB_map_style_default.js @@ -0,0 +1,658 @@ + +function HB_map_style_default() { + var land_type_min_zoom = 9; + + // var data_root = location.origin + "/habboy/open_street_map/vector_tiles/poland/"; + // var fonts = location.origin + "/habboy/open_street_map/font/{fontstack}/{range}.pbf"; + + // var data_root = "http://" + HABBOY_URL + "/osm/poland_layered"; + // var fonts = "http://" + HABBOY_URL + "/osm/font/{fontstack}/{range}.pbf"; + + var data_root = HABBOY_URL + "/osm/tiles"; + var fonts = HABBOY_URL + "/osm/font/{fontstack}/{range}.pbf"; + + var data_path_template = "{z}/{x}/{y}.pbf"; + + var green_opacity = .35; + var farm_opacity = .35; + var water_opacity = .65; + + var style = + { + // "id": "g61ohl2cd", + "version": 8, + "name": "hab", + "metadata": { + "mapbox:autocomposite": true, + "mapbox:type": "template" + }, + + "glyphs": fonts, + + // minzoom / maxzoom must be the same as in .json + "sources": { + "aeroway": { + "type": "vector", + "tiles": [data_root + "/aeroway/" + data_path_template], + "minzoom": 5, "maxzoom": 15 + }, + "buildings": { + "type": "vector", + "tiles": [data_root + "/buildings/" + data_path_template], + "minzoom": 14, "maxzoom": 15 + }, + "labels": { + "type": "vector", + "tiles": [data_root + "/labels/" + data_path_template], + "minzoom": 5, "maxzoom": 15 + }, + "landuse": { + "type": "vector", + "tiles": [data_root + "/landuse/" + data_path_template], + "minzoom": 5, "maxzoom": 15 + }, + "roads": { + "type": "vector", + "tiles": [data_root + "/roads/" + data_path_template], + "minzoom": 5, "maxzoom": 15 + }, + "water": { + "type": "vector", + "tiles": [data_root + "/water/" + data_path_template], + "minzoom": 5, "maxzoom": 15 + }, + "admin": { + "type": "vector", + "tiles": [data_root + "/admin/" + data_path_template], + "minzoom": 5, "maxzoom": 15 + } + }, + + + "layers": [ + + { + "id": "background", + "type": "background", + "paint": { + "background-color": "hsl(47, 2%, 10%)" + } + }, + + { + "id": "natural_other", + "type": "fill", + "source": "landuse", + "source-layer": "natural_other", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(20,50,20)", + "fill-opacity": green_opacity + }, + }, + + { + "id": "soil", + "type": "fill", + "source": "landuse", + "source-layer": "soil", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(70,40,35)", + "fill-opacity": farm_opacity + }, + }, + + { + "id": "landuse_other", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(20,20,20)", + "fill-opacity": .75 + }, + "filter": [ + "!in", + "class", + "forest", "national_park", "reservoir", "park", "grass", "farmland", "farmyard", "residential", + "commercial", "construction", "industrial", "retail" + ], + }, + + { + "id": "landuse_forest", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(0,80,0)", + "fill-opacity": green_opacity + }, + "filter": [ + "in", + "class", + "forest", "national_park", "reservoir" + ], + }, + + { + "id": "landuse_park", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(0,120,0)", + "fill-opacity": green_opacity + }, + "filter": [ + "==", + "class", + "park" + ], + }, + + { + "id": "landuse_grass", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(30,120,30)", + "fill-opacity": green_opacity + }, + "filter": [ + "==", + "class", + "grass" + ], + }, + + { + "id": "landuse_farmland", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": 10, + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "hsl(45, 0.35, 0.333)", + "fill-opacity": farm_opacity + }, + "filter": [ + "in", + "class", + "farmland", "farmyard" + ], + }, + + { + "id": "landuse_residential", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(30,30,30)", + "fill-opacity": 1 + }, + "filter": [ + "==", + "class", + "residential" + ], + }, + + { + "id": "landuse_com", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(30,30,30)", + "fill-opacity": 1 + }, + "filter": [ + "in", + "class", + "commercial", "construction", "industrial", "retail" + ], + }, + + { + "id": "wood", + "type": "fill", + "source": "landuse", + "source-layer": "wood", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(0,80,60)", + "fill-opacity": green_opacity + } + }, + + { + "id": "bush", + "type": "fill", + "source": "landuse", + "source-layer": "bush", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(0,120,90)", + "fill-opacity": green_opacity + } + }, + + { + "id": "river", + "type": "line", + "source": "water", + "source-layer": "river", + "maxzoom": 15, + "paint": { + "line-color": "rgb(0,50,150)", + "line-width": 1.5 + }, + "filter": [ + "all", + [ + "==", + "$type", + "LineString" + ], + [ + "in", + "class", + "river", + "canal", + // "stream" + ] + ], + }, + + { + "id": "water", + "type": "fill", + "source": "water", + "source-layer": "water", + "minzoom": 9, + "paint": { + "fill-color": "hsl(225, .35, .45)", + "fill-opacity": water_opacity + }, + "filter": [ + "in", + "class", + "riverbank", "water" + ] + }, + + { + "id": "wetland", + "type": "fill", + "source": "water", + "source-layer": "water", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "hsl(205, .3, .37)", + "fill-opacity": water_opacity + }, + "filter": [ + "==", + "class", + "wetland" + ] + }, + + { + "id": "mud", + "type": "fill", + "source": "water", + "source-layer": "mud", + "minzoom": land_type_min_zoom, + "paint": { + "fill-color": "rgb(80,50,20)", + "fill-opacity": water_opacity + }, + }, + + { + "id": "admin", + "type": "line", + "source": "admin", + "source-layer": "admin", + "filter": [ + "all", + [ + "==", + "$type", + "Polygon" + ], + // [ + // "==", + // "admin_level", + // 4 + // ] + ], + "paint": { + "line-color": "rgb(0,150,0)", + "line-width": 1 + } + }, + + { + "id": "aeroway", + "type": "fill", + "source": "aeroway", + "source-layer": "aeroway", + "minzoom": 9, + "paint": { + "fill-color": "rgb(180,130,0)" + }, + }, + + { + "id": "aeroway_other", + "type": "fill", + "source": "aeroway", + "source-layer": "aeroway_other", + "minzoom": 9, + "paint": { + "fill-color": "rgb(180,0,0)" + }, + // "filter": [ "==", "$type", "Polygon" ] + }, + + { + "id": "road_other", + "type": "line", + "source": "roads", + "source-layer": "road_other", + "paint": { + "line-color": "rgb(110,90,80)", + "line-width": { + "base": 1.8, + "stops": [ + [ + 4, + 0.25 + ], + [ + 20, + 30 + ] + ] + } + } + }, + + { + "id": "road_tertiary", + "type": "line", + "source": "roads", + "source-layer": "road_tertiary", + "paint": { + "line-color": "rgb(150,100,50)", + "line-width": { + "base": 1.55, + "stops": [ + [ + 4, + 0.25 + ], + [ + 20, + 30 + ] + ] + } + } + }, + + { + "id": "road_secondary", + "type": "line", + "source": "roads", + "source-layer": "road_secondary", + "paint": { + "line-color": "rgb(150,100,50)", + "line-width": { + "base": 1.4, + "stops": [ + [ + 6, + 0.5 + ], + [ + 20, + 30 + ] + ] + } + } + }, + + { + "id": "road_main", + "type": "line", + "source": "roads", + "source-layer": "road_main", + "paint": { + "line-color": "rgb(150,30,0)", + "line-width": 2, + // { + // "base": 1.5, + // "stops": [ + // [ + // 6, + // 0.5 + // ], + // [ + // 20, + // 30 + // ] + // ] + // } + } + }, + + { + "id": "railway", + "type": "line", + "source": "roads", + "source-layer": "railway", + "paint": { + "line-color": "rgb(80,80,80)", + "line-width": { + "base": 2.5, + "stops": [ + [ + 6, + 0.5 + ], + [ + 20, + 30 + ] + ] + }, + "line-dasharray": [ + 6, + 3 + ] + } + }, + + { + "id": "building", + "type": "fill", + "source": "buildings", + "source-layer": "building", + "paint": { + // "fill-color": "rgb(110,95,95)", + "fill-color": "rgb(45,47,55)", + // "fill-opacity": .15 + } + // ,"filter": ["==", "$type", "Polygon"] + }, + + { + "id": "place_city", + "type": "symbol", + "source": "labels", + "source-layer": "place_label", + "filter": [ + "all", + [ + "==", + "$type", + "Point" + ], + [ + "in", + "type", + "capital", + "city", + "town" + ], + [ + ">=", + "scalerank", + 5 + ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-max-width": 6, + "text-size": { + "stops": [ + [ + 6, + 12 + ], + [ + 12, + 16 + ] + ] + } + }, + "paint": { + // "text-color": "rgb(120,150,200)", + "text-color": "hsl(220,0.4,0.8)", + "text-halo-color": "rgba(0,0,0,0.75)", + "text-halo-width": 1, + "text-halo-blur": 1 + } + }, + + { + "id": "place_other", + "type": "symbol", + "source": "labels", + "source-layer": "place_label", + "minzoom": 12, + "filter": [ + "all", + [ + "==", + "$type", + "Point" + ], + [ + "!in", + "type", + "capital", + "city", + "town" + ], + // [ + // "<", + // "scalerank", + // 7 + // ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-max-width": 6, + "text-size": { + "stops": [ + [ + 6, + 12 + ], + [ + 12, + 16 + ] + ] + } + }, + "paint": { + // "text-color": "rgb(120,150,200)", + "text-color": "hsl(220,0.4,0.8)", + "text-halo-color": "rgba(0,0,0,0.75)", + "text-halo-width": 1, + "text-halo-blur": 1 + } + }, + + { + "id": "road_label", + "type": "symbol", + "source": "labels", + "source-layer": "road_label", + "filter": [ + "all", + [ + "==", + "$type", + "LineString" + ], + ], + "layout": { + "symbol-placement": "line", + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-transform": "uppercase", + "text-letter-spacing": 0.1, + "text-size": { + "base": 1.4, + "stops": [ + [ + 10, + 8 + ], + [ + 20, + 14 + ] + ] + } + }, + "paint": { + // "text-color": "rgb(120,150,200)", + "text-color": "hsl(220,0.4,0.8)", + "text-halo-color": "rgba(0,0,0,0.75)", + "text-halo-width": 1, + "text-halo-blur": 1 + } + }, + ] // layers + }; + + return style; +} diff --git a/webUI/code/js/HB_map_style_simplified.js b/webUI/code/js/HB_map_style_simplified.js new file mode 100644 index 0000000..2f42ebf --- /dev/null +++ b/webUI/code/js/HB_map_style_simplified.js @@ -0,0 +1,594 @@ + +function HB_map_style_simplified() { + var land_type_min_zoom = 9; + + // var data_root = location.origin + "/habboy/open_street_map/vector_tiles/poland/"; + // var fonts = location.origin + "/habboy/open_street_map/font/{fontstack}/{range}.pbf"; + + // var data_root = "http://" + HABBOY_URL + "/osm/poland_layered"; + // var fonts = "http://" + HABBOY_URL + "/osm/font/{fontstack}/{range}.pbf"; + + var data_root = HABBOY_URL + "/osm/tiles"; + var fonts = HABBOY_URL + "/osm/font/{fontstack}/{range}.pbf"; + + var data_path_template = "{z}/{x}/{y}.pbf"; + + var green_opacity = .35; + var farm_opacity = .35; + var water_opacity = .65; + + var style = + { + // "id": "g61ohl2cd", + "version": 8, + "name": "hab", + "metadata": { + "mapbox:autocomposite": true, + "mapbox:type": "template" + }, + + "glyphs": fonts, + + // minzoom / maxzoom must be the same as in .json + "sources": { + "landuse": { + "type": "vector", + "tiles": [data_root + "/landuse/" + data_path_template], + "minzoom": 9, "maxzoom": 14 + }, + "water": { + "type": "vector", + "tiles": [data_root + "/water/" + data_path_template], + "minzoom": 5, "maxzoom": 14 + }, + "aeroway": { + "type": "vector", + "tiles": [data_root + "/aeroway/" + data_path_template], + "minzoom": 9, "maxzoom": 14 + }, + "roads": { + "type": "vector", + "tiles": [data_root + "/roads/" + data_path_template], + "minzoom": 5, "maxzoom": 14 + }, + "buildings": { + "type": "vector", + "tiles": [data_root + "/buildings/" + data_path_template], + "minzoom": 15, "maxzoom": 15 + }, + "labels": { + "type": "vector", + "tiles": [data_root + "/labels/" + data_path_template], + "minzoom": 6, "maxzoom": 15 + }, + "admin": { + "type": "vector", + "tiles": [data_root + "/admin/" + data_path_template], + "minzoom": 5, "maxzoom": 10 + } + }, + + + // layers order determines drawing order + "layers": [ + { + "id": "background", + "type": "background", + "paint": { + "background-color": "hsl(47, 2%, 10%)" + } + }, + + { + "id": "natural_other", + "type": "fill", + "source": "landuse", + "source-layer": "natural", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(90, .3, .5)", + "fill-opacity": green_opacity + }, + }, + + { + "id": "land_other", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "rgb(40,40,60)", + "fill-opacity": .25 + }, + "filter": [ + "!in", + "class", + "wood", "forest", "national_park", "reservoir", + "park", "grass", "bush", + "soil", "farmland", "farmyard", + "residential", "commercial", "construction", "industrial", "retail", + ], + }, + + { + "id": "woods", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(90, .3, .5)", + "fill-opacity": green_opacity + }, + "filter": [ + "in", + "class", + "wood", "forest", "national_park", "reservoir" + ], + }, + + { + "id": "park", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(120, .75, .75)", + "fill-opacity": green_opacity + }, + "filter": [ + "in", + "class", + "park", "grass", "bush" + ], + }, + + { + "id": "farm", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(45, 0.65, 0.5)", + "fill-opacity": farm_opacity + }, + "filter": [ + "in", + "class", + "soil", "farmland", "farmyard" + ], + }, + + { + "id": "civil", + "type": "fill", + "source": "landuse", + "source-layer": "landuse", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(220, .1, .2)", + }, + "filter": [ + "in", + "class", + "residential", "commercial", "construction", "industrial", "retail" + ], + }, + + + { + "id": "river", + "type": "line", + "source": "water", + "source-layer": "river", + "minzoom": 9, + "paint": { + "line-color": "rgb(0,50,150)", + "line-opacity": water_opacity, + "line-width": { + "base": 2, + "stops": [ + [9, 2], + [10, 5] + ] + } + }, + "filter": [ + "all", + [ + "==", + "$type", + "LineString" + ], + [ + "in", + "class", + "river", + "canal", + // "stream" + ] + ], + }, + + { + "id": "water", + "type": "fill", + "source": "water", + "source-layer": "water", + "minzoom": 9, + "paint": { + "fill-color": "hsl(225, .35, .45)", + "fill-opacity": water_opacity + }, + "filter": [ + "in", + "class", + "riverbank", "water" + ] + }, + + { + "id": "wetland", + "type": "fill", + "source": "water", + "source-layer": "water", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "hsl(205, .3, .37)", + "fill-opacity": water_opacity + }, + "filter": [ + "==", + "class", + "wetland" + ] + }, + + { + "id": "mud", + "type": "fill", + "source": "water", + "source-layer": "water", + "minzoom": land_type_min_zoom, + // "maxzoom": land_type_max_zoom, + "paint": { + "fill-color": "rgb(80,50,20)", + "fill-opacity": water_opacity + }, + "filter": [ + "==", + "class", + "mud" + ] + }, + + { + "id": "admin", + "type": "line", + "source": "admin", + "source-layer": "admin", + "filter": [ + "all", + [ + "==", + "$type", + "Polygon" + ], + ], + "paint": { + "line-color": "rgb(0,110,0)", + "line-width": 3 + } + }, + + { + "id": "aeroway", + "type": "fill", + "source": "aeroway", + "source-layer": "aeroway", + "minzoom": 8, + "filter": [ + "!in", "class", "terminal", "hangar" + ], + "paint": { + "fill-color": "rgb(120,80,0)" + }, + }, + + { + "id": "aeroway_buildings", + "type": "fill", + "source": "aeroway", + "source-layer": "aeroway", + "minzoom": 14, + "filter": [ + "in", "class", "terminal", "hangar" + ], + "paint": { + "fill-color": "rgb(180,20,0)" + }, + }, + + { + "id": "road_other", + "type": "line", + "source": "roads", + "source-layer": "roads", + "minzoom": 14, // one less than buildings + "filter": [ + "in", + "class", + "track", "road", "living_street", "residential", "footway" + ], + "paint": { + "line-color": "rgb(110,90,80)", + // "line-width": 3 + "line-width": { + "base": 2, + "stops": [ + [10, 0.25], + [14, 1.5] + ] + } + } + }, + + { + "id": "road_tertiary", + "type": "line", + "source": "roads", + "source-layer": "roads", + "minzoom": 10, + "filter": [ + "in", + "class", + "tertiary", "tertiary_link", "unclassified" + ], + "paint": { + "line-color": "rgb(145,120,110)", + "line-width": { + "base": 2, + "stops": [ + [10, 0.8], + [14, 3] + ] + } + } + }, + + { + "id": "road_secondary", + "type": "line", + "source": "roads", + "source-layer": "roads", + "filter": [ + "in", + "class", + "motorway_link", + "trunk_link", + "primary_link", + "secondary", + "secondary_link", + ], + "paint": { + "line-color": "rgb(200,133,66)", + "line-width": { + "base": 2, + "stops": [ + [8, 2], + [11, 4] + ] + } + }, + "layout": { + "line-cap": "round", + "line-join": "miter" + } + }, + + { + "id": "road_main", + "type": "line", + "source": "roads", + "source-layer": "roads", + "filter": [ + "in", + "class", + "motorway", + "trunk", + "primary", + ], + "paint": { + "line-color": "rgb(200,0,0)", + "line-width": { + "base": 2, + "stops": [ + [5, 3], + [9, 6.5] + ] + } + }, + "layout": { + "line-cap": "round", + "line-join": "round" + } + }, + + { + "id": "railways", + "type": "line", + "source": "roads", + "source-layer": "railways", + "minzoom": 13, + "paint": { + "line-color": "rgb(80,80,80)", + "line-width": 2, + "line-dasharray": [6, 3] + } + }, + + { + "id": "building", + "type": "fill", + "source": "buildings", + "source-layer": "building", + "paint": { + "fill-color": "hsl(220, .15, .4)", + // "fill-opacity": .15 + } + }, + + { + "id": "place_city", + "type": "symbol", + "source": "labels", + "source-layer": "place_label", + "filter": [ + "all", + [ + "==", + "$type", + "Point" + ], + [ + "in", + "type", + "capital", + "city", + "town" + ], + [ + ">=", + "scalerank", + 5 + ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-max-width": 6, + "text-size": { + "stops": [ + [10,20], + [15,30] + ] + } + }, + "paint": { + // "text-color": "rgb(120,150,200)", + "text-color": "hsl(220, 0.4, 1)", + "text-halo-color": "rgba(0,0,0,0.75)", + "text-halo-width": 1, + "text-halo-blur": 1 + } + }, + + { + "id": "place_other", + "type": "symbol", + "source": "labels", + "source-layer": "place_label", + "minzoom": 12, + "filter": [ + "all", + [ + "==", + "$type", + "Point" + ], + [ + "!in", + "type", + "capital", + "city", + "town" + ], + // [ + // "<", + // "scalerank", + // 7 + // ] + ], + "layout": { + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-max-width": 6, + "text-size": { + "stops": [ + // [6,12], + // [12,16] + [10,10], + [15,15] + ] + } + }, + "paint": { + // "text-color": "rgb(120,150,200)", + "text-color": "hsl(220,0.4,.8)", + "text-halo-color": "rgba(0,0,0,0.75)", + "text-halo-width": 1, + "text-halo-blur": 1 + } + }, + + { + "id": "road_label", + "type": "symbol", + "source": "labels", + "source-layer": "road_label", + "filter": [ + "all", + [ + "==", + "$type", + "LineString" + ], + ], + "layout": { + "symbol-placement": "line", + "text-field": "{name}", + "text-font": [ + "Open Sans Semibold" + ], + "text-transform": "uppercase", + "text-letter-spacing": 0.1, + "text-size": { + // "base": 1.4, + "base": 2, + "stops": [ + // [10,8], + // [20,14] + [10,10], + [15,15] + ] + } + }, + "paint": { + "text-color": "hsl(220,0.4,1)", + "text-halo-color": "rgba(0,0,0,0.75)", + "text-halo-width": 1, + "text-halo-blur": 1 + } + }, + + ] // layers + }; // STYLE + + + + return style; +} diff --git a/webUI/code/js/HB_receiversStats.js b/webUI/code/js/HB_receiversStats.js new file mode 100644 index 0000000..5df2c54 --- /dev/null +++ b/webUI/code/js/HB_receiversStats.js @@ -0,0 +1,114 @@ + +function HB_RcvStats_UpdateSeries(chart) { + let payload_id = HABBOY_PAYLOAD_ID; + + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/receiver_stats"); + xhr.onload = function () { + if (xhr.status == 200) + { + var data = JSON.parse(xhr.responseText); + var series_data = []; + for(receiver in data) + series_data.push( [receiver, data[receiver]] ); + chart.series[0].update( {data: series_data}, true); + + setTimeout(() => { + HB_RcvStats_UpdateSeries(chart) + }, 3000); + } + else + { + console.debug("HB_RcvStats_UpdateSeries failed. Status:", xhr.status); + console.debug("HB_RcvStats_UpdateSeries failed URL: ", HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/receiver_stats"); + setTimeout(() => { + HB_RcvStats_UpdateSeries(chart) + }, 3000); + } + }; + xhr.onerror = () => { setTimeout(() => { + console.debug("HB_RcvStats_UpdateSeries failed. Status:", xhr.status); + console.debug("HB_RcvStats_UpdateSeries failed URL: ", HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/receiver_stats"); + setTimeout(() => { + HB_RcvStats_UpdateSeries(chart) + }, 3000); + }, 3000); }; + xhr.send(); +} + + +function HB_BuildRcvStatsChart() { + var HB_bg = HB_get_css_val('--HB_bg'); + var HB_text_highlight = HB_get_css_val('--HB_text_highlight'); + var HB_tab_button = HB_get_css_val('--HB_tab_button'); + + var chart_div = document.createElement('div'); + + var chart = new Highcharts.Chart({ + chart: { + renderTo: chart_div, + type: 'pie', + animation: false, + plotBackgroundColor: null, + plotBackgroundImage: null, + plotBorderWidth: 0, + plotShadow: false, + }, + title: { + text: "Receivers Stats", + align: 'center', + verticalAlign: 'middle', + style: { fontFamily: 'monospace', color: HB_text_highlight }, + y: 85 + }, + plotOptions: { + pie: { + dataLabels: { + enabled: true, + // distance: -50, + style: { + fontSize: "20px", + color: "#0EA", + textOutline: "0px", + fontWeight: 'bold', + }, + format: '{point.name}: {point.y}' + }, + startAngle: -90, + endAngle: 90, + center: ['50%', '75%'], + size: '110%' + } + }, + series: [{ + innerSize: '50%', + type: 'pie', + name: 'Receivers Stats', + // data: [ ['xxx', 23], ['yyy', 23], ['zzz', 54] ] + }] + }); + + HB_RcvStats_UpdateSeries(chart); + + return chart_div; +} + + +function HB_BuildRcvStats(parent_div) { + var charts_div = document.createElement("div"); + charts_div.id = "HB_RcvStats"; + parent_div.appendChild(charts_div); + + var grid = document.createElement("div"); + grid.style.display = "grid"; + grid.style.gridTemplateColumns = "auto auto auto"; + grid.style.width = "100%"; + grid.style.height = "100%"; + charts_div.appendChild(grid); + + var graph_container = HB_BuildRcvStatsChart(); + grid.appendChild(graph_container); + + return {"tab_name": "RcvStats", "tab_nav": []}; + +} diff --git a/webUI/code/js/HB_vehicles.js b/webUI/code/js/HB_vehicles.js new file mode 100644 index 0000000..40c1cd0 --- /dev/null +++ b/webUI/code/js/HB_vehicles.js @@ -0,0 +1,306 @@ + +// var HB_VEHICLES_TELEMETRY_Update_LastTime = "1970-01-01 12:00:00"; +var HB_VEHICLES_TELEMETRY_Update_LastTime = "1970-01-01T00:00:00.0+00:00"; + +function calc_gps_speed(gps_prev, gps_new) // https://stackoverflow.com/questions/14560999/using-the-haversine-formula-in-javascript +{ + //gps for payloads: ['2019-10-12 12:34:56', [lat,lon,alt], ground speed m/s, ascend rate m/s] + + var result = gps_new; + // while( result.length < 4) result.push(0); + + if( gps_prev == undefined || gps_new == undefined ) + return result; + + var dT = -( SentenceAge(gps_new['time']) - SentenceAge(gps_prev['time']) ); + + if( !dT && (gps_prev['time'] == gps_new['time'] )) + { + // reuse previously computed speed and ascent + result['ground_speed_mps'] = gps_prev['ground_speed_mps']; + result['ascent_mps'] = gps_prev['ascent_mps']; + return result; + } + + var dAlt = gps_new["altitude"] - gps_prev["altitude"]; + + Number.prototype.toRad = function() { + return this * Math.PI / 180; + } + + var R = 6371000; // meters + //has a problem with the .toRad() method below. + var x1 = gps_new["latitude"] - gps_prev["latitude"]; + var dLat = x1.toRad(); + var x2 = gps_new["longitude"] - gps_prev["longitude"]; + var dLon = x2.toRad(); + var a = Math.sin(dLat/2.0) * Math.sin(dLat/2.0) + + Math.cos(gps_prev["latitude"].toRad()) * Math.cos(gps_new["latitude"].toRad()) * + Math.sin(dLon/2) * Math.sin(dLon/2); + var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + var dP = R * c; + + result['ground_speed_mps'] = dP/dT; // ground speed m/s + result['ascent_mps'] = dAlt/dT; // ascend rate m/s + // console.debug(result); + return result; +} + + +function HB_VEHICLES_TELEMETRY_Update(/*payload_id*/) +{ + let payload_id = HABBOY_PAYLOAD_ID; + + var xhr = new XMLHttpRequest(); + xhr.open( + 'GET', + // HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/sensors/*?time=" + HB_VEHICLES_TELEMETRY_Update_LastTime + HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/sensors/*?time=" + + encodeURIComponent(HB_VEHICLES_TELEMETRY_Update_LastTime) + ); + xhr.setRequestHeader("Content-Type", "application/json"); //;charset=UTF-8 + xhr.onload = function () { + if (xhr.status == 200) + { + var telemetry = JSON.parse(xhr.responseText); + if("latitude" in telemetry) + { + HB_VEHICLES_TELEMETRY_LAST[payload_id] = telemetry; + if( !(payload_id in HB_VEHICLES_TELEMETRY) ) + { + HB_VEHICLES_TELEMETRY[payload_id] = telemetry; + } + else // append + { + for(sensor in telemetry) { + if(sensor in HB_VEHICLES_TELEMETRY[payload_id]) { + for(key in HB_VEHICLES_TELEMETRY[payload_id][sensor]) { + if(key != "is_numeric") + HB_VEHICLES_TELEMETRY[payload_id][sensor][key].push(...telemetry[sensor][key]); // array + // console.debug( "new data points ", key, telemetry[sensor][key].length ); + // console.debug( "ALL data points ", sensor, HB_VEHICLES_TELEMETRY[payload_id][sensor][key].length ); + } + } + } + } + + // update HB_VEHICLES_GPS_LAST + let batch_size = telemetry["latitude"]["values"].length; + var gps_now = { + "time": telemetry["latitude"]["times"][batch_size-1], + "latitude": telemetry["latitude"]["values"][batch_size-1], + "longitude": telemetry["longitude"]["values"][batch_size-1], + "altitude": telemetry["altitude"]["values"][batch_size-1], + "ground_speed_mps": 0, + "ascent_mps": 0 + } + gps_now = calc_gps_speed( HB_VEHICLES_GPS_LAST[payload_id], gps_now ); + HB_VEHICLES_GPS_LAST[payload_id] = gps_now; + // console.debug(HB_VEHICLES_GPS_LAST); + + // instead of utcnow - use last timestamp from received data + // this way we won't receive the same data next time + // HB_VEHICLES_TELEMETRY_Update_LastTime = new Date().toJSON().slice(0,19).replace(/T/g,' '); + HB_VEHICLES_TELEMETRY_Update_LastTime = telemetry["latitude"]["times"][ telemetry["latitude"]["times"].length - 1 ]; + + // callbacks for updated telemetry + for(cb in HB_VEHICLES_TELEMETRY_UpdateCallbacks) + { + try { + HB_VEHICLES_TELEMETRY_UpdateCallbacks[cb](telemetry); + } + catch (e) { + console.debug("HB_VEHICLES_TELEMETRY_UpdateCallbacks error:", e); + } + } + } + else + { + console.debug("HB_VEHICLES_TELEMETRY_Update failed -- no LATITUDE"); + } + + setTimeout(() => { HB_VEHICLES_TELEMETRY_Update(payload_id); }, 3000); + } + else + { + console.debug("HB_VEHICLES_TELEMETRY_Update failed. Status:", xhr.status); + console.debug(HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/sensors/*"); + setTimeout(() => { HB_VEHICLES_TELEMETRY_Update(payload_id); }, 6000); + } + }; + xhr.onerror = () => { + console.debug("HB_VEHICLES_TELEMETRY_Update failed. Status:"); + setTimeout(() => { HB_VEHICLES_TELEMETRY_Update(payload_id); }, 6000); + }; + xhr.send(); +} + + +function HB_HABBOY_GPS_Update() +{ + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/gps"); + xhr.onload = function () { + if (xhr.status == 200) { + var gps = JSON.parse(xhr.responseText); + HB_DEVICE_GPS_LAST["HABBOY"] = gps; + setTimeout( HB_HABBOY_GPS_Update, 1000 ); // currently GPS hardware is updated each 1 second + } + else { + console.debug("HB_HABBOY_GPS_Update Failed. Status: ", xhr.status); + setTimeout( HB_HABBOY_GPS_Update, 5000 ); + } + } + xhr.onerror = function () { + console.debug("HB_HABBOY_GPS_Update Failed."); + setTimeout( HB_HABBOY_GPS_Update, 5000 ); + } + xhr.send(); +} + +function UpdateVehicleLastSentence(/*payload_id*/) +{ + let payload_id = HABBOY_PAYLOAD_ID; + + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/sentences/lastdata"); + xhr.onload = function () { + if (xhr.status == 200) { + // HB_VEHICLES_SENTENCE_LAST[payload_id] = xhr.response; //text, not json + HB_VEHICLES_SENTENCE_LAST[payload_id] = JSON.parse(xhr.responseText); //JSON + setTimeout(() => { + UpdateVehicleLastSentence(payload_id) + }, 30000); + } + else { + console.debug("UpdateVehicleLastSentence failed. Status: ", xhr.status); + console.debug(HABBOY_DATA_URL + "/" + "habboy/api/v1/payloads/" + payload_id + "/sentences/lastdata"); + setTimeout(() => { + UpdateVehicleLastSentence(payload_id) + }, 30000); + } + } + xhr.onerror = function () { + console.debug("UpdateVehicleLastSentence Failed."); + setTimeout(() => { + UpdateVehicleLastSentence(payload_id) + }, 30000); + } + xhr.send(); + +} + + +function HB_VEHICLES_PREDICT_Update(/*payload_id*/) +{ + let payload_id = HABBOY_PAYLOAD_ID; + + var xhr = new XMLHttpRequest(); + xhr.open('GET', HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/predict"); + xhr.onload = function () { + if (xhr.status == 200) { + HB_VEHICLES_PREDICT[payload_id] = JSON.parse(xhr.responseText); + setTimeout(() => { + HB_VEHICLES_PREDICT_Update(); + }, 60 * 1000); // predict takes 12 seconds on Odroid-XU4 + } + else { + console.debug("HB_VEHICLES_PREDICT_Update failed. Status: ", xhr.status); + console.debug(HABBOY_DATA_URL + "/habboy/api/v1/payloads/" + payload_id + "/predict"); + setTimeout(() => { + HB_VEHICLES_PREDICT_Update() + }, 5000); + } + } + xhr.onerror = function () { + console.debug("HB_VEHICLES_PREDICT_Update failed."); + console.debug(HABBOY_DATA_URL + "/habboy/api/v1/payloads/predict"); + setTimeout(() => { + HB_VEHICLES_PREDICT_Update(); + }, 5000); + } + xhr.send(); +} + + +function HB_VEHICLES_PREDICT_HABITAT_Update(/*payload_id*/) +{ + console.debug('HB_VEHICLES_PREDICT_HABITAT_Update'); + + // https://legacy-snus.habhub.org/tracker/get_predictions.php?vehicles=AIRCOR-3 + let payload_id = HABBOY_PAYLOAD_ID; + let payload_callsign = HABBOY_PAYLOAD_CALLSIGN; + + var xhr = new XMLHttpRequest(); + xhr.open('GET', "https://legacy-snus.habhub.org/tracker/get_predictions.php?vehicles=" + payload_callsign); + xhr.onload = function () { + if (xhr.status == 200) { + let temp = JSON.parse(xhr.responseText); + if(temp && temp[0]) { + HB_VEHICLES_PREDICT_HABITAT[payload_id] = JSON.parse(temp[0].data); // [{'alt','lat','lon','time_1597935524'}] + // console.debug('HB_VEHICLES_PREDICT_HABITAT[payload_id]', HB_VEHICLES_PREDICT_HABITAT[payload_id]) + } + setTimeout(() => { + HB_VEHICLES_PREDICT_HABITAT_Update(); + }, 60 * 1000); + } + else { + console.debug("HB_VEHICLES_PREDICT_HABITAT_Update failed. Status: ", xhr.status); + setTimeout(() => { + HB_VEHICLES_PREDICT_HABITAT_Update() + }, 10 * 1000); + } + } + xhr.onerror = function () { + console.debug("HB_VEHICLES_PREDICT_HABITAT_Update failed."); + setTimeout(() => { + HB_VEHICLES_PREDICT_HABITAT_Update(); + }, 5000); + } + xhr.send(); +} + + +var HABBOY_UPLOAD_CHASE_CAR = 0; +function HB_SendChaseCar() +{ + if(!HABBOY_UPLOAD_CHASE_CAR) { + setTimeout(() => { + HB_SendChaseCar(); + }, 5000); + return; + } + + var chasecar_data = { + "latitude": HB_DEVICE_GPS_LAST["HABBOY"]["latitude"], + "longitude": HB_DEVICE_GPS_LAST["HABBOY"]["longitude"], + "altitude": HB_DEVICE_GPS_LAST["HABBOY"]["altitude"], + "ground_speed_mps": HB_DEVICE_GPS_LAST["HABBOY"]["ground_speed_mps"], + "heading": HB_DEVICE_GPS_LAST["HABBOY"]["heading"] + }; + + var xhr = new XMLHttpRequest(); + xhr.open('POST', HABBOY_DATA_URL + "/habboy/api/v1/chasecar/habboy_chase"); + // xhr.setRequestHeader("Content-Type", "application/json"); + xhr.onload = function () { + if (xhr.status == 200) { + console.debug("HB_SendChaseCar OK. ", JSON.parse(xhr.responseText) ); + setTimeout(() => { + HB_SendChaseCar(); + }, 30000); + } + else { + console.debug("HB_SendChaseCar failed. Status: ", xhr.status); + setTimeout(() => { + HB_SendChaseCar(); + }, 30000); + } + } + xhr.onerror = function () { + console.debug("HB_SendChaseCar failed."); + setTimeout(() => { + HB_SendChaseCar(); + }, 30000); + } + xhr.send( JSON.stringify(chasecar_data) ); +} \ No newline at end of file diff --git a/webUI/code/js/highcharts/HB_highcharts_theme_monokai.js b/webUI/code/js/highcharts/HB_highcharts_theme_monokai.js new file mode 100644 index 0000000..037a958 --- /dev/null +++ b/webUI/code/js/highcharts/HB_highcharts_theme_monokai.js @@ -0,0 +1,60 @@ +function HB_highcharts_theme() { + + var HB_bg = HB_get_css_val('--HB_bg'); + var HB_text = HB_get_css_val('--HB_text'); + var HB_text_highlight = HB_get_css_val('--HB_text_highlight'); + + // based on monokai + // http://jkunst.com/highcharts-themes-collection/ + + var res = + { + "colors": ["#F92672", "#66D9EF", "#A6E22E", "#A6E22E"], + "chart": { + "backgroundColor": HB_bg, + "style": { + // "fontFamily": "Inconsolata", + "color": HB_text_highlight + } + }, + "title": { + "style": { + "color": "#A2A39C" + }, + "align": "left" + }, + "subtitle": { + "style": { + "color": "#A2A39C" + }, + "align": "left" + }, + "legend": { + "align": "right", + "verticalAlign": "bottom", + "itemStyle": { + "fontWeight": "normal", + "color": "#A2A39C" + } + }, + "xAxis": { + "gridLineDashStyle": "Dot", + "gridLineWidth": 1, + "gridLineColor": "#A2A39C", + "lineColor": "#A2A39C", + "minorGridLineColor": "#A2A39C", + "tickColor": "#A2A39C", + "tickWidth": 1 + }, + "yAxis": { + "gridLineDashStyle": "Dot", + "gridLineColor": "#A2A39C", + "lineColor": "#A2A39C", + "minorGridLineColor": "#A2A39C", + "tickColor": HB_text_highlight, + "tickWidth": 1 + } + } + + return res; +} \ No newline at end of file diff --git a/webUI/code/js/highcharts/highcharts-more.js b/webUI/code/js/highcharts/highcharts-more.js new file mode 100644 index 0000000..be17b7a --- /dev/null +++ b/webUI/code/js/highcharts/highcharts-more.js @@ -0,0 +1,168 @@ +/* + Highcharts JS v8.1.0 (2020-05-05) + + (c) 2009-2018 Torstein Honsi + + License: www.highcharts.com/license +*/ +(function(c){"object"===typeof module&&module.exports?(c["default"]=c,module.exports=c):"function"===typeof define&&define.amd?define("highcharts/highcharts-more",["highcharts"],function(B){c(B);c.Highcharts=B;return c}):c("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(c){function B(l,a,d,b){l.hasOwnProperty(a)||(l[a]=b.apply(null,d))}c=c?c._modules:{};B(c,"parts-more/Pane.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(l,a){function d(g,b,a){return Math.sqrt(Math.pow(g- +a[0],2)+Math.pow(b-a[1],2))e?0:e,this.center[2]/2)-this.offset)};b.postTranslate=function(e,h){var f=this.chart,p=this.center;e=this.startAngleRad+e;return{x:f.plotLeft+p[0]+Math.cos(e)*h,y:f.plotTop+p[1]+Math.sin(e)*h}};b.getPlotBandPath= +function(e,h,f){var p=this.center,w=this.startAngleRad,v=p[2]/2,n=[u(f.outerRadius,"100%"),f.innerRadius,u(f.thickness,10)],g=Math.min(this.offset,0),b=/%$/;var a=this.isCircular;if("polygon"===this.options.gridLineInterpolation)n=this.getPlotLinePath({value:e}).concat(this.getPlotLinePath({value:h,reverse:!0}));else{e=Math.max(e,this.min);h=Math.min(h,this.max);a||(n[0]=this.translate(e),n[1]=this.translate(h));n=n.map(function(f){b.test(f)&&(f=m(f,10)*v/100);return f});if("circle"!==f.shape&&a)e= +w+this.translate(e),h=w+this.translate(h);else{e=-Math.PI/2;h=1.5*Math.PI;var k=!0}n[0]-=g;n[2]-=g;n=this.chart.renderer.symbols.arc(this.left+p[0],this.top+p[1],n[0],n[0],{start:Math.min(e,h),end:Math.max(e,h),innerR:u(n[1],n[0]-n[2]),open:k});a&&(a=(h+e)/2,g=this.left+p[0]+p[2]/2*Math.cos(a),n.xBounds=a>-Math.PI/2&&a-Math.PI&&0>a||a>Math.PI?-10:10)}return n};b.getCrosshairPosition=function(e,h, +f){var p=e.value,w=this.pane.center;if(this.isCircular){if(y(p))e.point&&(v=e.point.shapeArgs||{},v.start&&(p=this.chart.inverted?this.translate(e.point.rectPlotY,!0):e.point.x));else{var v=e.chartX||0;var n=e.chartY||0;p=this.translate(Math.atan2(n-f,v-h)-this.startAngleRad,!0)}e=this.getPosition(p);v=e.x;n=e.y}else y(p)||(v=e.chartX,n=e.chartY),y(v)&&y(n)&&(f=w[1]+this.chart.plotTop,p=this.translate(Math.min(Math.sqrt(Math.pow(v-h,2)+Math.pow(n-f,2)),w[2]/2)-w[3]/2,!0));return[p,v||0,n||0]};b.getPlotLinePath= +function(e){var h=this,f=h.pane.center,p=h.chart,w=p.inverted,v=e.value,n=e.reverse,g=h.getPosition(v),b=h.pane.options.background?h.pane.options.background[0]||h.pane.options.background:{},a=b.innerRadius||"0%",k=b.outerRadius||"100%";b=f[0]+p.plotLeft;var m=f[1]+p.plotTop,q=g.x,d=g.y,u=h.height;g=f[3]/2;var A;e.isCrosshair&&(d=this.getCrosshairPosition(e,b,m),v=d[0],q=d[1],d=d[2]);if(h.isCircular)v=Math.sqrt(Math.pow(q-b,2)+Math.pow(d-m,2)),n="string"===typeof a?C(a,1):a/v,p="string"===typeof k? +C(k,1):k/v,f&&g&&(v=g/v,nv||v>u)&&(v=0),"circle"===h.options.gridLineInterpolation)f=h.getLinePath(0,v,g);else if(f=[],p[w?"yAxis":"xAxis"].forEach(function(f){f.pane===h.pane&&(A=f)}),A)for(b=A.tickPositions,A.autoConnect&&(b=b.concat([b[0]])),n&&(b=b.slice().reverse()),v&&(v+=g),q=0;qk?k+360:k,d=q,A=0,r=0,t=null===w.y?.3*-p.height:0;if(h.isRadial){var l=h.getPosition(this.pos,h.center[2]/2+C(u(w.distance,-25),h.center[2]/2,-h.center[2]/2));"auto"===w.rotation?f.attr({rotation:a}):null===b&&(b=h.chart.renderer.fontMetrics(f.styles&&f.styles.fontSize).b-p.height/2);null===g&&(h.isCircular?(p.width>h.len*h.tickInterval/(h.max-h.min)&&(n=0),g=a>n&& +a<180-n?"left":a>180+n&&a<360-n?"right":"center"):g="center",f.attr({align:g}));if("auto"===g&&2===h.tickPositions.length&&h.isCircular){90q?q=180-q:270=q&&(q=540-q);180=d&&(d=360-d);if(h.pane.options.startAngle===k||h.pane.options.startAngle===k+360||h.pane.options.startAngle===k-360)m="start";g=-90<=k&&90>=k||-360<=k&&-270>=k||270<=k&&360>=k?"start"===m?"right":"left":"start"===m?"left":"right";70d&&(g="center");15>q||180<=q&&195>q?A=.3*p.height:15<=q&&35>=q?A="start"=== +m?0:.75*p.height:195<=q&&215>=q?A="start"===m?.75*p.height:0:35=q?A="start"===m?.25*-p.height:p.height:215=q&&(A="start"===m?p.height:.25*-p.height);15>d?r="start"===m?.15*-p.height:.15*p.height:165=d&&(r="start"===m?.15*p.height:.15*-p.height);f.attr({align:g});f.translate(r,A+t)}e.pos.x=l.x+w.x;e.pos.y=l.y+b}}});k(m.prototype,"getMarkPath",function(e,h,f,p,g,b,n){var w=this.axis;w.isRadial?(e=w.getPosition(this.pos,w.center[2]/2+p),h=["M",h,f,"L",e.x,e.y]):h=e.call(this,h, +f,p,g,b,n);return h})};b.defaultCircularOptions={gridLineWidth:1,labels:{align:null,distance:15,x:0,y:null,style:{textOverflow:"none"}},maxPadding:0,minPadding:0,showLastLabel:!1,tickLength:0};b.defaultRadialGaugeOptions={labels:{align:"center",x:0,y:null},minorGridLineWidth:0,minorTickInterval:"auto",minorTickLength:10,minorTickPosition:"inside",minorTickWidth:1,tickLength:10,tickPosition:"inside",tickWidth:2,title:{rotation:0},zIndex:2};b.defaultRadialOptions={gridLineInterpolation:"circle",gridLineWidth:1, +labels:{align:"right",x:-3,y:-2},showLastLabel:!1,title:{x:4,text:null,rotation:90}};return b}();b.compose(l,a);return b});B(c,"parts-more/AreaRangeSeries.js",[c["parts/Globals.js"],c["parts/Point.js"],c["parts/Utilities.js"]],function(l,a,d){var b=d.defined,r=d.extend,t=d.isArray,y=d.isNumber,c=d.pick;d=d.seriesType;var x=l.seriesTypes,g=l.Series.prototype,u=a.prototype;d("arearange","area",{lineWidth:1,threshold:null,tooltip:{pointFormat:'\u25cf {series.name}: {point.low} - {point.high}
'}, +trackByArea:!0,dataLabels:{align:null,verticalAlign:null,xLow:0,xHigh:0,yLow:0,yHigh:0}},{pointArrayMap:["low","high"],pointValKey:"low",deferTranslatePolar:!0,toYData:function(g){return[g.low,g.high]},highToXY:function(g){var b=this.chart,a=this.xAxis.postTranslate(g.rectPlotX,this.yAxis.len-g.plotHigh);g.plotHighX=a.x-b.plotLeft;g.plotHigh=a.y-b.plotTop;g.plotLowX=g.plotX},translate:function(){var g=this,b=g.yAxis,a=!!g.modifyValue;x.area.prototype.translate.apply(g);g.points.forEach(function(k){var d= +k.high,q=k.plotY;k.isNull?k.plotY=null:(k.plotLow=q,k.plotHigh=b.translate(a?g.modifyValue(d,k):d,0,1,0,1),a&&(k.yBottom=k.plotHigh))});this.chart.polar&&this.points.forEach(function(b){g.highToXY(b);b.tooltipPos=[(b.plotHighX+b.plotLowX)/2,(b.plotHigh+b.plotLow)/2]})},getGraphPath:function(g){var b=[],a=[],d,m=x.area.prototype.getGraphPath;var q=this.options;var e=this.chart.polar&&!1!==q.connectEnds,h=q.connectNulls,f=q.step;g=g||this.points;for(d=g.length;d--;){var p=g[d];p.isNull||e||h||g[d+1]&& +!g[d+1].isNull||a.push({plotX:p.plotX,plotY:p.plotY,doCurve:!1});var w={polarPlotY:p.polarPlotY,rectPlotX:p.rectPlotX,yBottom:p.yBottom,plotX:c(p.plotHighX,p.plotX),plotY:p.plotHigh,isNull:p.isNull};a.push(w);b.push(w);p.isNull||e||h||g[d-1]&&!g[d-1].isNull||a.push({plotX:p.plotX,plotY:p.plotY,doCurve:!1})}g=m.call(this,g);f&&(!0===f&&(f="left"),q.step={left:"right",center:"center",right:"left"}[f]);b=m.call(this,b);a=m.call(this,a);q.step=f;q=[].concat(g,b);!this.chart.polar&&a[0]&&"M"===a[0][0]&& +(a[0]=["L",a[0][1],a[0][2]]);this.graphPath=q;this.areaPath=g.concat(a);q.isArea=!0;q.xMap=g.xMap;this.areaPath.xMap=g.xMap;return q},drawDataLabels:function(){var b=this.points,a=b.length,k,d=[],u=this.options.dataLabels,q,e=this.chart.inverted;if(t(u))if(1q.plotLow; +q.y=q.high;q._plotY=q.plotY;q.plotY=q.plotHigh;d[k]=q.dataLabel;q.dataLabel=q.dataLabelUpper;q.below=p;e?h.align||(h.align=p?"right":"left"):h.verticalAlign||(h.verticalAlign=p?"top":"bottom")}this.options.dataLabels=h;g.drawDataLabels&&g.drawDataLabels.apply(this,arguments);for(k=a;k--;)if(q=b[k])q.dataLabelUpper=q.dataLabel,q.dataLabel=d[k],delete q.dataLabels,q.y=q.low,q.plotY=q._plotY}if(f.enabled||this._hasPointLabels){for(k=a;k--;)if(q=b[k])p=f.inside?q.plotHighq.plotLow, +q.below=!p,e?f.align||(f.align=p?"left":"right"):f.verticalAlign||(f.verticalAlign=p?"bottom":"top");this.options.dataLabels=f;g.drawDataLabels&&g.drawDataLabels.apply(this,arguments)}if(h.enabled)for(k=a;k--;)if(q=b[k])q.dataLabels=[q.dataLabelUpper,q.dataLabel].filter(function(f){return!!f});this.options.dataLabels=u},alignDataLabel:function(){x.column.prototype.alignDataLabel.apply(this,arguments)},drawPoints:function(){var a=this.points.length,d;g.drawPoints.apply(this,arguments);for(d=0;dw&&(w*=-1,p-=w);l?(t=e.barX+m,e.shapeType="arc",e.shapeArgs=b.polarArc(p+w,p,t,t+e.pointWidth)):(h.height=w,h.y=p,e.tooltipPos=k.inverted?[g.len+g.pos-k.plotLeft-p-w/2,a.len+a.pos-k.plotTop- +h.x-h.width/2,w]:[a.left-k.plotLeft+h.x+h.width/2,g.pos-k.plotTop+p+w/2,w])})},directTouch:!0,trackerGroups:["group","dataLabelsGroup"],drawGraph:y,getSymbol:y,crispCol:function(){return c.crispCol.apply(this,arguments)},drawPoints:function(){return c.drawPoints.apply(this,arguments)},drawTracker:function(){return c.drawTracker.apply(this,arguments)},getColumnMetrics:function(){return c.getColumnMetrics.apply(this,arguments)},pointAttribs:function(){return c.pointAttribs.apply(this,arguments)},animate:function(){return c.animate.apply(this, +arguments)},polarArc:function(){return c.polarArc.apply(this,arguments)},translate3dPoints:function(){return c.translate3dPoints.apply(this,arguments)},translate3dShapes:function(){return c.translate3dShapes.apply(this,arguments)}},{setState:c.pointClass.prototype.setState});""});B(c,"parts-more/ColumnPyramidSeries.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(l,a){var d=a.clamp,b=a.pick;a=a.seriesType;var r=l.seriesTypes.column.prototype;a("columnpyramid","column",{},{translate:function(){var a= +this,l=a.chart,c=a.options,x=a.dense=2>a.closestPointRange*a.xAxis.transA;x=a.borderWidth=b(c.borderWidth,x?0:1);var g=a.yAxis,u=c.threshold,m=a.translatedThreshold=g.getThreshold(u),C=b(c.minPointLength,5),k=a.getColumnMetrics(),z=k.width,A=a.barW=Math.max(z,1+2*x),q=a.pointXOffset=k.offset;l.inverted&&(m-=.5);c.pointPadding&&(A=Math.ceil(A));r.translate.apply(a);a.points.forEach(function(e){var h=b(e.yBottom,m),f=999+Math.abs(h),p=d(e.plotY,-f,g.len+f);f=e.plotX+q;var w=A/2,v=Math.min(p,h);h=Math.max(p, +h)-v;var n;e.barX=f;e.pointWidth=z;e.tooltipPos=l.inverted?[g.len+g.pos-l.plotLeft-p,a.xAxis.len-f-w,h]:[f+w,p+g.pos-l.plotTop,h];p=u+(e.total||e.y);"percent"===c.stacking&&(p=u+(0>e.y)?-100:100);p=g.toPixels(p,!0);var E=(n=l.plotHeight-p-(l.plotHeight-m))?w*(v-p)/n:0;var k=n?w*(v+h-p)/n:0;n=f-E+w;E=f+E+w;var r=f+k+w;k=f-k+w;var H=v-C;var t=v+h;0>e.y&&(H=v,t=v+h+C);l.inverted&&(r=l.plotWidth-v,n=p-(l.plotWidth-m),E=w*(p-r)/n,k=w*(p-(r-h))/n,n=f+w+E,E=n-2*E,r=f-k+w,k=f+k+w,H=v,t=v+h-C,0>e.y&&(t=v+ +h+C));e.shapeType="path";e.shapeArgs={x:n,y:H,width:E-n,height:h,d:[["M",n,H],["L",E,H],["L",r,t],["L",k,t],["Z"]]}})}});""});B(c,"parts-more/GaugeSeries.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(l,a){var d=a.clamp,b=a.isNumber,r=a.merge,t=a.pick,c=a.pInt;a=a.seriesType;var D=l.Series,x=l.TrackerMixin;a("gauge","line",{dataLabels:{borderColor:"#cccccc",borderRadius:3,borderWidth:1,crop:!1,defer:!1,enabled:!0,verticalAlign:"top",y:15,zIndex:2},dial:{},pivot:{},tooltip:{headerFormat:""}, +showInLegend:!1},{angular:!0,directTouch:!0,drawGraph:l.noop,fixedBox:!0,forceDL:!0,noSharedTooltip:!0,trackerGroups:["group","dataLabelsGroup"],translate:function(){var g=this.yAxis,a=this.options,m=g.center;this.generatePoints();this.points.forEach(function(u){var k=r(a.dial,u.dial),l=c(t(k.radius,"80%"))*m[2]/200,A=c(t(k.baseLength,"70%"))*l/100,q=c(t(k.rearLength,"10%"))*l/100,e=k.baseWidth||3,h=k.topWidth||1,f=a.overshoot,p=g.startAngleRad+g.translate(u.y,null,null,null,!0);if(b(f)||!1===a.wrap)f= +b(f)?f/180*Math.PI:0,p=d(p,g.startAngleRad-f,g.endAngleRad+f);p=180*p/Math.PI;u.shapeType="path";u.shapeArgs={d:k.path||[["M",-q,-e/2],["L",A,-e/2],["L",l,-h/2],["L",l,h/2],["L",A,e/2],["L",-q,e/2],["Z"]],translateX:m[0],translateY:m[1],rotation:p};u.plotX=m[0];u.plotY=m[1]})},drawPoints:function(){var g=this,b=g.chart,a=g.yAxis.center,d=g.pivot,k=g.options,l=k.pivot,A=b.renderer;g.points.forEach(function(a){var e=a.graphic,h=a.shapeArgs,f=h.d,p=r(k.dial,a.dial);e?(e.animate(h),h.d=f):a.graphic=A[a.shapeType](h).attr({rotation:h.rotation, +zIndex:1}).addClass("highcharts-dial").add(g.group);if(!b.styledMode)a.graphic[e?"animate":"attr"]({stroke:p.borderColor||"none","stroke-width":p.borderWidth||0,fill:p.backgroundColor||"#000000"})});d?d.animate({translateX:a[0],translateY:a[1]}):(g.pivot=A.circle(0,0,t(l.radius,5)).attr({zIndex:2}).addClass("highcharts-pivot").translate(a[0],a[1]).add(g.group),b.styledMode||g.pivot.attr({"stroke-width":l.borderWidth||0,stroke:l.borderColor||"#cccccc",fill:l.backgroundColor||"#000000"}))},animate:function(a){var b= +this;a||b.points.forEach(function(a){var g=a.graphic;g&&(g.attr({rotation:180*b.yAxis.startAngleRad/Math.PI}),g.animate({rotation:a.shapeArgs.rotation},b.options.animation))})},render:function(){this.group=this.plotGroup("group","series",this.visible?"visible":"hidden",this.options.zIndex,this.chart.seriesGroup);D.prototype.render.call(this);this.group.clip(this.chart.clipRect)},setData:function(a,b){D.prototype.setData.call(this,a,!1);this.processData();this.generatePoints();t(b,!0)&&this.chart.redraw()}, +hasData:function(){return!!this.points.length},drawTracker:x&&x.drawTrackerPoint},{setState:function(a){this.state=a}});""});B(c,"parts-more/BoxPlotSeries.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(l,a){var d=a.pick;a=a.seriesType;var b=l.noop,r=l.seriesTypes;a("boxplot","column",{threshold:null,tooltip:{pointFormat:'\u25cf {series.name}
Maximum: {point.high}
Upper quartile: {point.q3}
Median: {point.median}
Lower quartile: {point.q1}
Minimum: {point.low}
'}, +whiskerLength:"50%",fillColor:"#ffffff",lineWidth:1,medianWidth:2,whiskerWidth:2},{pointArrayMap:["low","q1","median","q3","high"],toYData:function(a){return[a.low,a.q1,a.median,a.q3,a.high]},pointValKey:"high",pointAttribs:function(){return{}},drawDataLabels:b,translate:function(){var a=this.yAxis,b=this.pointArrayMap;r.column.prototype.translate.apply(this);this.points.forEach(function(d){b.forEach(function(b){null!==d[b]&&(d[b+"Plot"]=a.translate(d[b],0,1,0,1))});d.plotHigh=d.highPlot})},drawPoints:function(){var a= +this,b=a.options,r=a.chart,l=r.renderer,g,u,m,c,k,z,A=0,q,e,h,f,p=!1!==a.doQuartiles,w,v=a.options.whiskerLength;a.points.forEach(function(n){var E=n.graphic,I=E?"animate":"attr",L=n.shapeArgs,H={},J={},t={},K={},G=n.color||a.color;"undefined"!==typeof n.plotY&&(q=Math.round(L.width),e=Math.floor(L.x),h=e+q,f=Math.round(q/2),g=Math.floor(p?n.q1Plot:n.lowPlot),u=Math.floor(p?n.q3Plot:n.lowPlot),m=Math.floor(n.highPlot),c=Math.floor(n.lowPlot),E||(n.graphic=E=l.g("point").add(a.group),n.stem=l.path().addClass("highcharts-boxplot-stem").add(E), +v&&(n.whiskers=l.path().addClass("highcharts-boxplot-whisker").add(E)),p&&(n.box=l.path(void 0).addClass("highcharts-boxplot-box").add(E)),n.medianShape=l.path(void 0).addClass("highcharts-boxplot-median").add(E)),r.styledMode||(J.stroke=n.stemColor||b.stemColor||G,J["stroke-width"]=d(n.stemWidth,b.stemWidth,b.lineWidth),J.dashstyle=n.stemDashStyle||b.stemDashStyle||b.dashStyle,n.stem.attr(J),v&&(t.stroke=n.whiskerColor||b.whiskerColor||G,t["stroke-width"]=d(n.whiskerWidth,b.whiskerWidth,b.lineWidth), +t.dashstyle=n.whiskerDashStyle||b.whiskerDashStyle||b.dashStyle,n.whiskers.attr(t)),p&&(H.fill=n.fillColor||b.fillColor||G,H.stroke=b.lineColor||G,H["stroke-width"]=b.lineWidth||0,H.dashstyle=n.boxDashStyle||b.boxDashStyle||b.dashStyle,n.box.attr(H)),K.stroke=n.medianColor||b.medianColor||G,K["stroke-width"]=d(n.medianWidth,b.medianWidth,b.lineWidth),K.dashstyle=n.medianDashStyle||b.medianDashStyle||b.dashStyle,n.medianShape.attr(K)),z=n.stem.strokeWidth()%2/2,A=e+f+z,E=[["M",A,u],["L",A,m],["M", +A,g],["L",A,c]],n.stem[I]({d:E}),p&&(z=n.box.strokeWidth()%2/2,g=Math.floor(g)+z,u=Math.floor(u)+z,e+=z,h+=z,E=[["M",e,u],["L",e,g],["L",h,g],["L",h,u],["L",e,u],["Z"]],n.box[I]({d:E})),v&&(z=n.whiskers.strokeWidth()%2/2,m+=z,c+=z,w=/%$/.test(v)?f*parseFloat(v)/100:v/2,E=[["M",A-w,m],["L",A+w,m],["M",A-w,c],["L",A+w,c]],n.whiskers[I]({d:E})),k=Math.round(n.medianPlot),z=n.medianShape.strokeWidth()%2/2,k+=z,E=[["M",e,k],["L",h,k]],n.medianShape[I]({d:E}))})},setStackedPoints:b});""});B(c,"parts-more/ErrorBarSeries.js", +[c["parts/Globals.js"],c["parts/Utilities.js"]],function(l,a){a=a.seriesType;var d=l.noop,b=l.seriesTypes;a("errorbar","boxplot",{color:"#000000",grouping:!1,linkedTo:":previous",tooltip:{pointFormat:'\u25cf {series.name}: {point.low} - {point.high}
'},whiskerWidth:null},{type:"errorbar",pointArrayMap:["low","high"],toYData:function(b){return[b.low,b.high]},pointValKey:"high",doQuartiles:!1,drawDataLabels:b.arearange?function(){var a=this.pointValKey; +b.arearange.prototype.drawDataLabels.call(this);this.data.forEach(function(b){b.y=b[a]})}:d,getColumnMetrics:function(){return this.linkedParent&&this.linkedParent.columnMetrics||b.column.prototype.getColumnMetrics.call(this)}});""});B(c,"parts-more/WaterfallSeries.js",[c["parts/Globals.js"],c["parts/Point.js"],c["parts/Utilities.js"],c["parts/Stacking.js"]],function(l,a,d,b){var r=d.addEvent,c=d.arrayMax,y=d.arrayMin,D=d.correctFloat,x=d.isNumber,g=d.objectEach,u=d.pick;d=d.seriesType;var m=l.Axis, +C=l.Chart,k=l.Series,z=l.seriesTypes;r(m,"afterInit",function(){this.isXAxis||(this.waterfallStacks={changed:!1})});r(m,"afterBuildStacks",function(){this.waterfallStacks.changed=!1;delete this.waterfallStacks.alreadyChanged});r(C,"beforeRedraw",function(){for(var b=this.axes,a=this.series,e=a.length;e--;)a[e].options.stacking&&(b.forEach(function(h){h.isXAxis||(h.waterfallStacks.changed=!0)}),e=0)});r(m,"afterRender",function(){var b=this.options.stackLabels;b&&b.enabled&&this.waterfallStacks&&this.renderWaterfallStackTotals()}); +m.prototype.renderWaterfallStackTotals=function(){var a=this.waterfallStacks,d=this.stacking&&this.stacking.stackTotalGroup,e=new b(this,this.options.stackLabels,!1,0,void 0);this.dummyStackItem=e;g(a,function(h){g(h,function(f){e.total=f.stackTotal;f.label&&(e.label=f.label);b.prototype.render.call(e,d);f.label=e.label;delete e.label})});e.total=null};d("waterfall","column",{dataLabels:{inside:!0},lineWidth:1,lineColor:"#333333",dashStyle:"Dot",borderColor:"#333333",states:{hover:{lineWidthPlus:0}}}, +{pointValKey:"y",showLine:!0,generatePoints:function(){var b;z.column.prototype.generatePoints.apply(this);var a=0;for(b=this.points.length;am.height&&(m.y+=m.height,m.height*=-1);r.plotY=m.y=Math.round(m.y)-this.borderWidth%2/2;m.height=Math.max(Math.round(m.height),.001);r.yBottom= +m.y+m.height;m.height<=h&&!r.isNull?(m.height=h,m.y-=f,r.plotY=m.y,r.minPointLengthOffset=0>r.y?-f:f):(r.isNull&&(m.width=0),r.minPointLengthOffset=0);m=r.plotY+(r.negative?m.height:0);this.chart.inverted?r.tooltipPos[0]=a.len-m:r.tooltipPos[1]=m}},processData:function(a){var b=this.options,e=this.yData,h=b.data,f=e.length,p=b.threshold||0,g,v,n,d,m;for(m=v=g=n=d=0;mm.y&&!g||0d.indexOf(g)&&(c=!0);e[g]||(e[g]={});d=e[g];for(var l=0;l=f&&this.renderRange(a)},this);this.legendSymbol.add(this.legendItem);this.legendItem.add(this.legendGroup);this.hideOverlappingLabels()};a.prototype.renderRange=function(a){var f=this.options,b=f.labels,e=this.chart.renderer,h=this.symbols,g=h.labels,d=a.center,k=Math.abs(a.radius),c=f.connectorDistance||0,m=b.align,r=b.style.fontSize;c=this.legend.options.rtl||"left"===m?-c:c;b=f.connectorWidth;var l=this.ranges[0].radius|| +0,u=d-k-f.borderWidth/2+b/2;r=r/2-(this.fontMetrics.h-r)/2;var t=e.styledMode;"center"===m&&(c=0,f.connectorDistance=0,a.labelStyle.align="center");m=u+f.labels.y;var q=l+c+f.labels.x;h.bubbleItems.push(e.circle(l,d+((u%1?1:.5)-(b%2?0:.5)),k).attr(t?{}:a.bubbleStyle).addClass((t?"highcharts-color-"+this.options.seriesIndex+" ":"")+"highcharts-bubble-legend-symbol "+(f.className||"")).add(this.legendSymbol));h.connectors.push(e.path(e.crispLine([["M",l,u],["L",l+c,u]],f.connectorWidth)).attr(t?{}: +a.connectorStyle).addClass((t?"highcharts-color-"+this.options.seriesIndex+" ":"")+"highcharts-bubble-legend-connectors "+(f.connectorClassName||"")).add(this.legendSymbol));a=e.text(this.formatLabel(a),q,m+r).attr(t?{}:a.labelStyle).addClass("highcharts-bubble-legend-labels "+(f.labels.className||"")).add(this.legendSymbol);g.push(a);a.placed=!0;a.alignAttr={x:q,y:m+r}};a.prototype.getMaxLabelSize=function(){var a,f;this.symbols.labels.forEach(function(b){f=b.getBBox(!0);a=a?f.width>a.width?f:a: +f});return a||{}};a.prototype.formatLabel=function(a){var f=this.options,e=f.labels.formatter;f=f.labels.format;var h=this.chart.numberFormatter;return f?b.format(f,a):e?e.call(a):h(a.value,1)};a.prototype.hideOverlappingLabels=function(){var a=this.chart,f=this.symbols;!this.options.labels.allowOverlap&&f&&(a.hideOverlappingLabels(f.labels),f.labels.forEach(function(a,b){a.newOpacity?a.newOpacity!==a.oldOpacity&&f.connectors[b].show():f.connectors[b].hide()}))};a.prototype.getRanges=function(){var a= +this.legend.bubbleLegend,f=a.options.ranges,b,e=Number.MAX_VALUE,g=-Number.MAX_VALUE;a.chart.series.forEach(function(f){f.isBubble&&!f.ignoreSeries&&(b=f.zData.filter(D),b.length&&(e=u(f.options.zMin,Math.min(e,Math.max(y(b),!1===f.options.displayNegative?f.options.zThreshold:-Number.MAX_VALUE))),g=u(f.options.zMax,Math.max(g,l(b)))))});var n=e===g?[{value:g}]:[{value:e},{value:(e+g)/2},{value:g,autoRanges:!0}];f.length&&f[0].radius&&n.reverse();n.forEach(function(a,b){f&&f[b]&&(n[b]=x(!1,f[b],a))}); +return n};a.prototype.predictBubbleSizes=function(){var a=this.chart,f=this.fontMetrics,b=a.legend.options,e="horizontal"===b.layout,g=e?a.legend.lastLineHeight:0,n=a.plotSizeX,d=a.plotSizeY,k=a.series[this.options.seriesIndex];a=Math.ceil(k.minPxSize);var c=Math.ceil(k.maxPxSize);k=k.options.maxSize;var m=Math.min(d,n);if(b.floating||!/%$/.test(k))f=c;else if(k=parseFloat(k),f=(m+g-f.h/2)*k/100/(k/100+1),e&&d-f>=n||!e&&n-f>=d)f=c;return[a,Math.ceil(f)]};a.prototype.updateRanges=function(a,f){var b= +this.legend.options.bubbleLegend;b.minSize=a;b.maxSize=f;b.ranges=this.getRanges()};a.prototype.correctSizes=function(){var a=this.legend,f=this.chart.series[this.options.seriesIndex];1v.height&&(v.height=a[d].itemHeight);v.step=g}return b};d.prototype.retranslateItems=function(a){var b,f,e,g=this.options.rtl,d=0;this.allItems.forEach(function(h,p){b=h.legendGroup.translateX;f=h._legendItemPos[1];if((e=h.movementX)||g&&h.ranges)e=g?b-h.options.maxSize/2:b+e,h.legendGroup.attr({translateX:e});p>a[d].step&&d++;h.legendGroup.attr({translateY:Math.round(f+ +a[d].height/2)});h._legendItemPos[1]=f+a[d].height/2})};a(k,"legendItemClick",function(){var a=this.chart,b=this.visible,f=this.chart.legend;f&&f.bubbleLegend&&(this.visible=!b,this.ignoreSeries=b,a=0<=a.getVisibleBubbleSeriesIndex(),f.bubbleLegend.visible!==a&&(f.update({bubbleLegend:{enabled:a}}),f.bubbleLegend.visible=a),this.visible=b)});C(z.prototype,"drawChartBox",function(a,b,f){var e=this.legend,h=0<=this.getVisibleBubbleSeriesIndex();if(e&&e.options.enabled&&e.bubbleLegend&&e.options.bubbleLegend.autoRanges&& +h){var d=e.bubbleLegend.options;h=e.bubbleLegend.predictBubbleSizes();e.bubbleLegend.updateRanges(h[0],h[1]);d.placed||(e.group.placed=!1,e.allItems.forEach(function(a){a.legendGroup.translateY=null}));e.render();this.getMargins();this.axes.forEach(function(a){a.visible&&a.render();d.placed||(a.setScale(),a.updateNames(),g(a.ticks,function(a){a.isNew=!0;a.isNewLabel=!0}))});d.placed=!0;this.getMargins();a.call(this,b,f);e.bubbleLegend.correctSizes();e.retranslateItems(e.getLinesHeights())}else a.call(this, +b,f),e&&e.options.enabled&&e.bubbleLegend&&(e.render(),e.retranslateItems(e.getLinesHeights()))});c.BubbleLegend=q;return c.BubbleLegend});B(c,"parts-more/BubbleSeries.js",[c["parts/Globals.js"],c["parts/Color.js"],c["parts/Point.js"],c["parts/Utilities.js"]],function(c,a,d,b){var r=a.parse,l=b.arrayMax,y=b.arrayMin,D=b.clamp,x=b.extend,g=b.isNumber,u=b.pick,m=b.pInt;a=b.seriesType;b=c.Axis;var C=c.noop,k=c.Series,z=c.seriesTypes;a("bubble","scatter",{dataLabels:{formatter:function(){return this.point.z}, +inside:!0,verticalAlign:"middle"},animationLimit:250,marker:{lineColor:null,lineWidth:1,fillOpacity:.5,radius:null,states:{hover:{radiusPlus:0}},symbol:"circle"},minSize:8,maxSize:"20%",softThreshold:!1,states:{hover:{halo:{size:5}}},tooltip:{pointFormat:"({point.x}, {point.y}), Size: {point.z}"},turboThreshold:0,zThreshold:0,zoneAxis:"z"},{pointArrayMap:["y","z"],parallelArrays:["x","y","z"],trackerGroups:["group","dataLabelsGroup"],specialGroup:"group",bubblePadding:!0,zoneAxis:"z",directTouch:!0, +isBubble:!0,pointAttribs:function(a,b){var e=this.options.marker.fillOpacity;a=k.prototype.pointAttribs.call(this,a,b);1!==e&&(a.fill=r(a.fill).setOpacity(e).get("rgba"));return a},getRadii:function(a,b,e){var g=this.zData,f=this.yData,p=e.minPxSize,d=e.maxPxSize,v=[];var n=0;for(e=g.length;n=this.minPxSize/2?(h.marker=x(h.marker,{radius:f,width:2*f,height:2*f}),h.dlBox={x:h.plotX-f,y:h.plotY-f,width:2*f,height:2*f}):h.shapeArgs=h.plotY=h.dlBox=void 0}},alignDataLabel:z.column.prototype.alignDataLabel,buildKDTree:C,applyZones:C},{haloPath:function(a){return d.prototype.haloPath.call(this,0===a?0:(this.marker?this.marker.radius||0:0)+a)},ttBelow:!1});b.prototype.beforePadding= +function(){var a=this,b=this.len,e=this.chart,h=0,f=b,p=this.isXAxis,d=p?"xData":"yData",k=this.min,n={},c=Math.min(e.plotWidth,e.plotHeight),r=Number.MAX_VALUE,t=-Number.MAX_VALUE,C=this.max-k,x=b/C,z=[];this.series.forEach(function(f){var b=f.options;!f.bubblePadding||!f.visible&&e.options.chart.ignoreHiddenSeries||(a.allowZoomOutside=!0,z.push(f),p&&(["minSize","maxSize"].forEach(function(a){var f=b[a],e=/%$/.test(f);f=m(f);n[a]=e?c*f/100:f}),f.minPxSize=n.minSize,f.maxPxSize=Math.max(n.maxSize, +n.minSize),f=f.zData.filter(g),f.length&&(r=u(b.zMin,D(y(f),!1===b.displayNegative?b.zThreshold:-Number.MAX_VALUE,r)),t=u(b.zMax,Math.max(t,l(f))))))});z.forEach(function(b){var e=b[d],n=e.length;p&&b.getRadii(r,t,b);if(0a?1:0)},barycenter:function(){var a=this.options.gravitationalConstant,d=this.barycenter.xFactor,b=this.barycenter.yFactor;d=(d-(this.box.left+this.box.width)/2)*a;b=(b-(this.box.top+this.box.height)/2)*a;this.nodes.forEach(function(a){a.fixedPosition|| +(a.plotX-=d/a.mass/a.degree,a.plotY-=b/a.mass/a.degree)})},repulsive:function(a,d,b){d=d*this.diffTemperature/a.mass/a.degree;a.fixedPosition||(a.plotX+=b.x*d,a.plotY+=b.y*d)},attractive:function(a,d,b){var c=a.getMass(),l=-b.x*d*this.diffTemperature;d=-b.y*d*this.diffTemperature;a.fromNode.fixedPosition||(a.fromNode.plotX-=l*c.fromNode/a.fromNode.degree,a.fromNode.plotY-=d*c.fromNode/a.fromNode.degree);a.toNode.fixedPosition||(a.toNode.plotX+=l*c.toNode/a.toNode.degree,a.toNode.plotY+=d*c.toNode/ +a.toNode.degree)},integrate:function(a,d){var b=-a.options.friction,c=a.options.maxSpeed,l=(d.plotX+d.dispX-d.prevX)*b;b*=d.plotY+d.dispY-d.prevY;var y=Math.abs,D=y(l)/(l||1);y=y(b)/(b||1);l=D*Math.min(c,Math.abs(l));b=y*Math.min(c,Math.abs(b));d.prevX=d.plotX+d.dispX;d.prevY=d.plotY+d.dispY;d.plotX+=l;d.plotY+=b;d.temperature=a.vectorLength({x:l,y:b})},getK:function(a){return Math.pow(a.box.width*a.box.height/a.nodes.length,.5)}},euler:{attractiveForceFunction:function(a,d){return a*a/d},repulsiveForceFunction:function(a, +d){return d*d/a},barycenter:function(){var a=this.options.gravitationalConstant,d=this.barycenter.xFactor,b=this.barycenter.yFactor;this.nodes.forEach(function(c){if(!c.fixedPosition){var l=c.getDegree();l*=1+l/2;c.dispX+=(d-c.plotX)*a*l/c.degree;c.dispY+=(b-c.plotY)*a*l/c.degree}})},repulsive:function(a,d,b,c){a.dispX+=b.x/c*d/a.degree;a.dispY+=b.y/c*d/a.degree},attractive:function(a,d,b,c){var l=a.getMass(),r=b.x/c*d;d*=b.y/c;a.fromNode.fixedPosition||(a.fromNode.dispX-=r*l.fromNode/a.fromNode.degree, +a.fromNode.dispY-=d*l.fromNode/a.fromNode.degree);a.toNode.fixedPosition||(a.toNode.dispX+=r*l.toNode/a.toNode.degree,a.toNode.dispY+=d*l.toNode/a.toNode.degree)},integrate:function(a,d){d.dispX+=d.dispX*a.options.friction;d.dispY+=d.dispY*a.options.friction;var b=d.temperature=a.vectorLength({x:d.dispX,y:d.dispY});0!==b&&(d.plotX+=d.dispX/b*Math.min(Math.abs(d.dispX),a.temperature),d.plotY+=d.dispY/b*Math.min(Math.abs(d.dispY),a.temperature))},getK:function(a){return Math.pow(a.box.width*a.box.height/ +a.nodes.length,.3)}}}});B(c,"modules/networkgraph/QuadTree.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(c,a){a=a.extend;var d=c.QuadTreeNode=function(a){this.box=a;this.boxSize=Math.min(a.width,a.height);this.nodes=[];this.body=this.isInternal=!1;this.isEmpty=!0};a(d.prototype,{insert:function(a,c){this.isInternal?this.nodes[this.getBoxPosition(a)].insert(a,c-1):(this.isEmpty=!1,this.body?c?(this.isInternal=!0,this.divideBox(),!0!==this.body&&(this.nodes[this.getBoxPosition(this.body)].insert(this.body, +c-1),this.body=!0),this.nodes[this.getBoxPosition(a)].insert(a,c-1)):(c=new d({top:a.plotX,left:a.plotY,width:.1,height:.1}),c.body=a,c.isInternal=!1,this.nodes.push(c)):(this.isInternal=!1,this.body=a))},updateMassAndCenter:function(){var a=0,d=0,c=0;this.isInternal?(this.nodes.forEach(function(b){b.isEmpty||(a+=b.mass,d+=b.plotX*b.mass,c+=b.plotY*b.mass)}),d/=a,c/=a):this.body&&(a=this.body.mass,d=this.body.plotX,c=this.body.plotY);this.mass=a;this.plotX=d;this.plotY=c},divideBox:function(){var a= +this.box.width/2,c=this.box.height/2;this.nodes[0]=new d({left:this.box.left,top:this.box.top,width:a,height:c});this.nodes[1]=new d({left:this.box.left+a,top:this.box.top,width:a,height:c});this.nodes[2]=new d({left:this.box.left+a,top:this.box.top+c,width:a,height:c});this.nodes[3]=new d({left:this.box.left,top:this.box.top+c,width:a,height:c})},getBoxPosition:function(a){var b=a.plotYMath.abs(this.systemTemperature-this.prevSystemTemperature)||0>=this.temperature},getSystemTemperature:function(){return this.nodes.reduce(function(a,b){return a+b.temperature},0)},vectorLength:function(a){return Math.sqrt(a.x*a.x+a.y*a.y)},getDistR:function(a,b){a=this.getDistXY(a,b);return this.vectorLength(a)}, +getDistXY:function(a,b){var d=a.plotX-b.plotX;a=a.plotY-b.plotY;return{x:d,y:a,absX:Math.abs(d),absY:Math.abs(a)}}});d(a,"predraw",function(){this.graphLayoutsLookup&&this.graphLayoutsLookup.forEach(function(a){a.stop()})});d(a,"render",function(){function a(a){a.maxIterations--&&isFinite(a.temperature)&&!a.isStable()&&!a.enableSimulation&&(a.beforeStep&&a.beforeStep(),a.step(),d=!1,b=!0)}var b=!1;if(this.graphLayoutsLookup){x(!1,this);for(this.graphLayoutsLookup.forEach(function(a){a.start()});!d;){var d= +!0;this.graphLayoutsLookup.forEach(a)}b&&this.series.forEach(function(a){a&&a.layout&&a.render()})}});d(a,"beforePrint",function(){this.graphLayoutsLookup.forEach(function(a){a.updateSimulation(!1)});this.redraw()});d(a,"afterPrint",function(){this.graphLayoutsLookup.forEach(function(a){a.updateSimulation()});this.redraw()})});B(c,"modules/networkgraph/draggable-nodes.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(c,a){var d=a.addEvent;a=c.Chart;c.dragNodesMixin={onMouseDown:function(a, +d){d=this.chart.pointer.normalize(d);a.fixedPosition={chartX:d.chartX,chartY:d.chartY,plotX:a.plotX,plotY:a.plotY};a.inDragMode=!0},onMouseMove:function(a,d){if(a.fixedPosition&&a.inDragMode){var b=this.chart,c=b.pointer.normalize(d);d=a.fixedPosition.chartX-c.chartX;c=a.fixedPosition.chartY-c.chartY;if(5e&&(f.degree+=.01,f.neighbours++,b=a.repulsiveForce(-e/Math.sqrt(f.neighbours),a.k, +f,d)),a.force("repulsive",f,b*d.mass,c,d,e))})})},applyLimitBox:function(a){if(this.options.splitSeries&&!a.isParentNode&&this.options.parentNodeLimit){var f=this.getDistXY(a,a.series.parentNode);var b=a.series.parentNodeRadius-a.marker.radius-this.vectorLength(f);0>b&&b>-2*a.marker.radius&&(a.plotX-=.01*f.x,a.plotY-=.01*f.y)}q.prototype.applyLimitBox.apply(this,arguments)}});b("packedbubble","bubble",{minSize:"10%",maxSize:"50%",sizeBy:"area",zoneAxis:"y",crisp:!1,tooltip:{pointFormat:"Value: {point.value}"}, +draggable:!0,useSimulation:!0,dataLabels:{formatter:function(){return this.point.value},parentNodeFormatter:function(){return this.name},parentNodeTextPath:{enabled:!0},padding:0,style:{transition:"opacity 2000ms"}},layoutAlgorithm:{initialPositions:"circle",initialPositionRadius:20,bubblePadding:5,parentNodeLimit:!1,seriesInteraction:!0,dragBetweenSeries:!1,parentNodeOptions:{maxIterations:400,gravitationalConstant:.03,maxSpeed:50,initialPositionRadius:100,seriesInteraction:!0,marker:{fillColor:null, +fillOpacity:1,lineWidth:1,lineColor:null,symbol:"circle"}},enableSimulation:!0,type:"packedbubble",integration:"packedbubble",maxIterations:1E3,splitSeries:!1,maxSpeed:5,gravitationalConstant:.01,friction:-.981}},{hasDraggableNodes:!0,forces:["barycenter","repulsive"],pointArrayMap:["value"],pointValKey:"value",isCartesian:!1,requireSorting:!1,directTouch:!0,axisTypes:[],noSharedTooltip:!0,searchPoint:c.noop,accumulateAllPoints:function(a){var f=a.chart,b=[],e,c;for(e=0;eMath.sqrt(f*f+e*e)-Math.abs(a[2]+b[2])},positionBubble:function(a,b,e){var f=Math.sqrt,c=Math.asin,d=Math.acos,h=Math.pow,g=Math.abs;f=f(h(a[0]-b[0],2)+h(a[1]-b[1],2));d=d((h(f,2)+h(e[2]+b[2],2)-h(e[2]+a[2],2))/(2*(e[2]+b[2])*f));c=c(g(a[0]-b[0])/f); +a=(0>a[1]-b[1]?0:Math.PI)+d+c*(0>(a[0]-b[0])*(a[1]-b[1])?1:-1);return[b[0]+(b[2]+e[2])*Math.sin(a),b[1]-(b[2]+e[2])*Math.cos(a),e[2],e[3],e[4]]},placeBubbles:function(a){var b=this.checkOverlap,f=this.positionBubble,e=[],c=1,d=0,h=0;var g=[];var k;a=a.sort(function(a,b){return b[2]-a[2]});if(a.length){e.push([[0,0,a[0][2],a[0][3],a[0][4]]]);if(1c&&(c=a),ae&&(f.series.addPoint(C(a.options,{plotX:a.plotX,plotY:a.plotY}),!1),c.removeElementFromCollection(a,c.nodes),a.remove()))}); +h.onMouseUp.apply(this,arguments)}},destroy:function(){this.chart.graphLayoutsLookup&&this.chart.graphLayoutsLookup.forEach(function(a){a.removeElementFromCollection(this,a.series)},this);this.parentNode&&(this.parentNodeLayout.removeElementFromCollection(this.parentNode,this.parentNodeLayout.nodes),this.parentNode.dataLabel&&(this.parentNode.dataLabel=this.parentNode.dataLabel.destroy()));c.Series.prototype.destroy.apply(this,arguments)},alignDataLabel:c.Series.prototype.alignDataLabel},{destroy:function(){this.series.layout&& +this.series.layout.removeElementFromCollection(this,this.series.layout.nodes);return d.prototype.destroy.apply(this,arguments)}});t(A,"beforeRedraw",function(){this.allDataPoints&&delete this.allDataPoints});""});B(c,"parts-more/Polar.js",[c["parts/Globals.js"],c["parts/Utilities.js"],c["parts-more/Pane.js"]],function(c,a,d){var b=a.addEvent,l=a.animObject,t=a.defined,y=a.find,D=a.isNumber,x=a.pick,g=a.splat,u=a.uniqueKey,m=a.wrap,C=c.Series,k=c.seriesTypes,z=C.prototype,A=c.Pointer.prototype;z.searchPointByAngle= +function(a){var b=this.chart,e=this.xAxis.pane.center;return this.searchKDTree({clientX:180+-180/Math.PI*Math.atan2(a.chartX-e[0]-b.plotLeft,a.chartY-e[1]-b.plotTop)})};z.getConnectors=function(a,b,c,d){var e=d?1:0;var f=0<=b&&b<=a.length-1?b:0>b?a.length-1+b:0;b=0>f-1?a.length-(1+e):f-1;e=f+1>a.length-1?e:f+1;var h=a[b];e=a[e];var g=h.plotX;h=h.plotY;var k=e.plotX;var p=e.plotY;e=a[f].plotX;f=a[f].plotY;g=(1.5*e+g)/2.5;h=(1.5*f+h)/2.5;k=(1.5*e+k)/2.5;var l=(1.5*f+p)/2.5;p=Math.sqrt(Math.pow(g-e, +2)+Math.pow(h-f,2));var m=Math.sqrt(Math.pow(k-e,2)+Math.pow(l-f,2));g=Math.atan2(h-f,g-e);l=Math.PI/2+(g+Math.atan2(l-f,k-e))/2;Math.abs(g-l)>Math.PI/2&&(l-=Math.PI);g=e+Math.cos(l)*p;h=f+Math.sin(l)*p;k=e+Math.cos(Math.PI+l)*m;l=f+Math.sin(Math.PI+l)*m;e={rightContX:k,rightContY:l,leftContX:g,leftContY:h,plotX:e,plotY:f};c&&(e.prevPointCont=this.getConnectors(a,b,!1,d));return e};z.toXY=function(a){var b=this.chart,e=this.xAxis;var c=this.yAxis;var d=a.plotX,g=a.plotY,k=a.series,l=b.inverted,m= +a.y,q=l?d:c.len-g;l&&k&&!k.isRadialBar&&(a.plotY=g="number"===typeof m?c.translate(m)||0:0);a.rectPlotX=d;a.rectPlotY=g;c.center&&(q+=c.center[3]/2);c=l?c.postTranslate(g,q):e.postTranslate(d,q);a.plotX=a.polarPlotX=c.x-b.plotLeft;a.plotY=a.polarPlotY=c.y-b.plotTop;this.kdByAngle?(b=(d/Math.PI*180+e.pane.options.startAngle)%360,0>b&&(b+=360),a.clientX=b):a.clientX=a.plotX};k.spline&&(m(k.spline.prototype,"getPointSpline",function(a,b,c,d){this.chart.polar?d?(a=this.getConnectors(b,d,!0,this.connectEnds), +a=["C",a.prevPointCont.rightContX,a.prevPointCont.rightContY,a.leftContX,a.leftContY,a.plotX,a.plotY]):a=["M",c.plotX,c.plotY]:a=a.call(this,b,c,d);return a}),k.areasplinerange&&(k.areasplinerange.prototype.getPointSpline=k.spline.prototype.getPointSpline));b(C,"afterTranslate",function(){var a=this.chart;if(a.polar&&this.xAxis){(this.kdByAngle=a.tooltip&&a.tooltip.shared)?this.searchPoint=this.searchPointByAngle:this.options.findNearestPointBy="xy";if(!this.preventPostTranslate)for(var d=this.points, +f=d.length;f--;)this.toXY(d[f]),!a.hasParallelCoordinates&&!this.yAxis.reversed&&d[f].yb&&(b=h),0>a&&(a=h));return{x:e[0],y:e[1],r:b,innerR:a,start:c,end:d}},m(k,"animate",q),m(k,"translate",function(b){var c=this.options,e=c.stacking,d=this.chart,g=this.xAxis,k=this.yAxis,l=k.reversed,m=k.center,q=g.startAngleRad, +r=g.endAngleRad-q;this.preventPostTranslate=!0;b.call(this);if(g.isRadial){b=this.points;g=b.length;var u=k.translate(k.min);var z=k.translate(k.max);c=c.threshold||0;if(d.inverted&&D(c)){var y=k.translate(c);t(y)&&(0>y?y=0:y>r&&(y=r),this.translatedThreshold=y+q)}for(;g--;){c=b[g];var x=c.barX;var A=c.x;var C=c.y;c.shapeType="arc";if(d.inverted){c.plotY=k.translate(C);if(e&&k.stacking){if(C=k.stacking.stacks[(0>C?"-":"")+this.stackKey],this.visible&&C&&C[A]&&!c.isNull){var B=C[A].points[this.getStackIndicator(void 0, +A,this.index).key];var F=k.translate(B[0]);B=k.translate(B[1]);t(F)&&(F=a.clamp(F,0,r))}}else F=y,B=c.plotY;F>B&&(B=[F,F=B][0]);if(!l)if(Fz)B=z;else{if(Bz)F=B=0}else if(B>u)B=u;else if(Fu||Bk.max&&(F=B=l?r:0);F+=q;B+=q;m&&(c.barX=x+=m[3]/2);A=Math.max(x,0);C=Math.max(x+c.pointWidth,0);c.shapeArgs={x:m&&m[0],y:m&&m[1],r:C,innerR:A,start:F,end:B};c.opacity=F===B?0:void 0;c.plotY=(t(this.translatedThreshold)&&(Fm[1])}}}),k.findAlignments=function(a,b){null===b.align&&(b.align=20a?"left":200a?"right":"center");null===b.verticalAlign&&(b.verticalAlign=45>a||315a?"top":"middle");return b},C&&(C.findAlignments=k.findAlignments),m(k,"alignDataLabel", +function(a,b,c,d,g,k){var e=this.chart,f=x(d.inside,!!this.options.stacking);e.polar?(a=b.rectPlotX/Math.PI*180,e.inverted?(this.forceDL=e.isInsidePlot(b.plotX,Math.round(b.plotY),!1),f&&b.shapeArgs?(g=b.shapeArgs,g=this.yAxis.postTranslate((g.start+g.end)/2-this.xAxis.startAngleRad,b.barX+b.pointWidth/2),g={x:g.x-e.plotLeft,y:g.y-e.plotTop}):b.tooltipPos&&(g={x:b.tooltipPos[0],y:b.tooltipPos[1]}),d.align=x(d.align,"center"),d.verticalAlign=x(d.verticalAlign,"middle")):this.findAlignments&&(d=this.findAlignments(a, +d)),z.alignDataLabel.call(this,b,c,d,g,k),this.isRadialBar&&b.shapeArgs&&b.shapeArgs.start===b.shapeArgs.end&&c.hide(!0)):a.call(this,b,c,d,g,k)}));m(A,"getCoordinates",function(a,b){var c=this.chart,e={xAxis:[],yAxis:[]};c.polar?c.axes.forEach(function(a){var d=a.isXAxis,f=a.center;if("colorAxis"!==a.coll){var g=b.chartX-f[0]-c.plotLeft;f=b.chartY-f[1]-c.plotTop;e[d?"xAxis":"yAxis"].push({axis:a,value:a.translate(d?Math.PI-Math.atan2(g,f):Math.sqrt(Math.pow(g,2)+Math.pow(f,2)),!0)})}}):e=a.call(this, +b);return e});c.SVGRenderer.prototype.clipCircle=function(a,b,c,d){var e=u(),f=this.createElement("clipPath").attr({id:e}).add(this.defs);a=d?this.arc(a,b,c,d,0,2*Math.PI).add(f):this.circle(a,b,c).add(f);a.id=e;a.clipPath=f;return a};b(c.Chart,"getAxes",function(){this.pane||(this.pane=[]);g(this.options.pane).forEach(function(a){new d(a,this)},this)});b(c.Chart,"afterDrawChartBox",function(){this.pane.forEach(function(a){a.render()})});b(c.Series,"afterInit",function(){var a=this.chart;a.inverted&& +a.polar&&(this.isRadialSeries=!0,this.is("column")&&(this.isRadialBar=!0))});m(c.Chart.prototype,"get",function(a,b){return y(this.pane,function(a){return a.options.id===b})||a.call(this,b)})});B(c,"masters/highcharts-more.src.js",[],function(){})}); +//# sourceMappingURL=highcharts-more.js.map \ No newline at end of file diff --git a/webUI/code/js/highcharts/highcharts.js b/webUI/code/js/highcharts/highcharts.js new file mode 100644 index 0000000..9d39bac --- /dev/null +++ b/webUI/code/js/highcharts/highcharts.js @@ -0,0 +1,522 @@ +/* + Highcharts JS v8.1.0 (2020-05-05) + + (c) 2009-2018 Torstein Honsi + + License: www.highcharts.com/license +*/ +(function(X,Q){"object"===typeof module&&module.exports?(Q["default"]=Q,module.exports=X.document?Q(X):Q):"function"===typeof define&&define.amd?define("highcharts/highcharts",function(){return Q(X)}):(X.Highcharts&&X.Highcharts.error(16,!0),X.Highcharts=Q(X))})("undefined"!==typeof window?window:this,function(X){function Q(d,f,E,q){d.hasOwnProperty(f)||(d[f]=q.apply(null,E))}var A={};Q(A,"parts/Globals.js",[],function(){var d="undefined"!==typeof X?X:"undefined"!==typeof window?window:{},f=d.document, +E=d.navigator&&d.navigator.userAgent||"",q=f&&f.createElementNS&&!!f.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect,M=/(edge|msie|trident)/i.test(E)&&!d.opera,K=-1!==E.indexOf("Firefox"),J=-1!==E.indexOf("Chrome"),L=K&&4>parseInt(E.split("Firefox/")[1],10);return{product:"Highcharts",version:"8.1.0",deg2rad:2*Math.PI/360,doc:f,hasBidiBug:L,hasTouch:!!d.TouchEvent,isMS:M,isWebKit:-1!==E.indexOf("AppleWebKit"),isFirefox:K,isChrome:J,isSafari:!J&&-1!==E.indexOf("Safari"),isTouchDevice:/(Mobile|Android|Windows Phone)/.test(E), +SVG_NS:"http://www.w3.org/2000/svg",chartCount:0,seriesTypes:{},symbolSizes:{},svg:q,win:d,marginNames:["plotTop","marginRight","marginBottom","plotLeft"],noop:function(){},charts:[],dateFormats:{}}});Q(A,"parts/Utilities.js",[A["parts/Globals.js"]],function(d){function f(){var a,c=arguments,k={},r=function(a,c){"object"!==typeof a&&(a={});Z(c,function(k,e){!E(k,!0)||t(k)||n(k)?a[e]=c[e]:a[e]=r(a[e]||{},k)});return a};!0===c[0]&&(k=c[1],c=Array.prototype.slice.call(c,2));var e=c.length;for(a=0;a< +e;a++)k=r(k,c[a]);return k}function E(a,c){return!!a&&"object"===typeof a&&(!c||!w(a))}function q(a,c,k){var r;D(c)?b(k)?a.setAttribute(c,k):a&&a.getAttribute&&((r=a.getAttribute(c))||"class"!==c||(r=a.getAttribute(c+"Name"))):Z(c,function(c,k){a.setAttribute(k,c)});return r}function M(){for(var a=arguments,c=a.length,k=0;kr)for(var e=0;e=z+this.startTime){this.now=this.end;this.pos=1;this.update();var l=b[this.prop]=!0;Z(b,function(a){!0!==a&&(l=!1)});l&&e&&e.call(r);a=!1}else this.pos=k.easing((c- +this.startTime)/z),this.now=this.start+(this.end-this.start)*this.pos,this.update(),a=!0;return a};a.prototype.initPath=function(a,c,k){function r(a,c){for(;a.lengtha&&-Infinity=k&&(c=[1/k])));for(r=0;r=a||!e&&b<=(c[r]+(c[r+1]||c[r]))/2);r++);return z=P(z*k,-Math.round(Math.log(.001)/Math.LN10))},c=d.stableSort=function(a,c){var k=a.length,r,e;for(e=0;ek&&(k=a[c]);return k},r=d.destroyObjectProperties=function(a,c){Z(a,function(k,r){k&&k!==c&&k.destroy&&k.destroy();delete a[r]})},z=d.discardElement=function(a){var c=d.garbageBin;c||(c=l("div"));a&&c.appendChild(a);c.innerHTML=""},P=d.correctFloat=function(a,c){return parseFloat(a.toPrecision(c||14))},U=d.setAnimation=function(a,c){c.renderer.globalAnimation=M(a,c.options.chart.animation,!0)},W=d.animObject=function(a){return E(a)?f(a): +{duration:a?500:0}},Y=d.timeUnits={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5,month:24192E5,year:314496E5},T=d.numberFormat=function(a,c,k,r){a=+a||0;c=+c;var e=d.defaultOptions.lang,z=(a.toString().split(".")[1]||"").split("e")[0].length,b=a.toString().split("e");if(-1===c)c=Math.min(z,20);else if(!N(c))c=2;else if(c&&b[1]&&0>b[1]){var l=c+ +b[1];0<=l?(b[0]=(+b[0]).toExponential(l).split("e")[0],c=l):(b[0]=b[0].split(".")[0]||0,a=20>c?(b[0]*Math.pow(10,b[1])).toFixed(c): +0,b[1]=0)}var g=(Math.abs(b[1]?b[0]:a)+Math.pow(10,-Math.max(c,z)-1)).toFixed(c);z=String(C(g));l=3a?"-":"")+(l?z.substr(0,l)+r:"");a+=z.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+r);c&&(a+=k+g.slice(-c));b[1]&&0!==+a&&(a+="e"+b[1]);return a};Math.easeInOutSine=function(a){return-.5*(Math.cos(Math.PI*a)-1)};var ca=d.getStyle=function(a,c,k){if("width"===c)return c=Math.min(a.offsetWidth,a.scrollWidth),k=a.getBoundingClientRect&& +a.getBoundingClientRect().width,k=c-1&&(c=Math.floor(k)),Math.max(0,c-d.getStyle(a,"padding-left")-d.getStyle(a,"padding-right"));if("height"===c)return Math.max(0,Math.min(a.offsetHeight,a.scrollHeight)-d.getStyle(a,"padding-top")-d.getStyle(a,"padding-bottom"));x.getComputedStyle||F(27,!0);if(a=x.getComputedStyle(a,void 0))a=a.getPropertyValue(c),M(k,"opacity"!==c)&&(a=C(a));return a},aa=d.inArray=function(a,c,k){return c.indexOf(a,k)},O=d.find=Array.prototype.find?function(a,c){return a.find(c)}: +function(a,c){var k,r=a.length;for(k=0;kc?a>16,(f&65280)>>8,f&255,1]:4===F&&(q=[(f&3840)>>4|(f&3840)>>8,(f&240)>>4|f&240,(f&15)<<4|f&15,1])}if(!q)for(x=this.parsers.length;x--&&!q;){var H=this.parsers[x];(F=H.regex.exec(f))&&(q=H.parse(F))}}this.rgba=q||[]};d.prototype.get= +function(d){var f=this.input,x=this.rgba;if("undefined"!==typeof this.stops){var F=q(f);F.stops=[].concat(F.stops);this.stops.forEach(function(f,x){F.stops[x]=[F.stops[x][0],f.get(d)]})}else F=x&&E(x[0])?"rgb"===d||!d&&1===x[3]?"rgb("+x[0]+","+x[1]+","+x[2]+")":"a"===d?x[3]:"rgba("+x.join(",")+")":f;return F};d.prototype.brighten=function(d){var f,x=this.rgba;if(this.stops)this.stops.forEach(function(f){f.brighten(d)});else if(E(d)&&0!==d)for(f=0;3>f;f++)x[f]+=M(255*d),0>x[f]&&(x[f]=0),255k.width)k={width:0,height:0}}else k=this.htmlGetBBox();r.isSVG&& +(c=k.width,r=k.height,u&&(k.height=r={"11px,17":14,"13px,20":16}[l&&l.fontSize+","+Math.round(r)]||r),a&&(l=a*q,k.width=Math.abs(r*Math.sin(l))+Math.abs(c*Math.cos(l)),k.height=Math.abs(r*Math.cos(l))+Math.abs(c*Math.sin(l))));if(v&&0]*>/g,"").replace(/</g,"<").replace(/>/g,">")))};B.prototype.toFront=function(){var c=this.element;c.parentNode.appendChild(c);return this};B.prototype.translate=function(c,a){return this.attr({translateX:c,translateY:a})};B.prototype.updateShadows=function(c,a,k){var r=this.shadows; +if(r)for(var e=r.length;e--;)k.call(r[e],"height"===c?Math.max(a-(r[e].cutHeight||0),0):"d"===c?this.d:a,c,r[e])};B.prototype.updateTransform=function(){var c=this.translateX||0,a=this.translateY||0,k=this.scaleX,r=this.scaleY,e=this.inverted,b=this.rotation,l=this.matrix,g=this.element;e&&(c+=this.width,a+=this.height);c=["translate("+c+","+a+")"];N(l)&&c.push("matrix("+l.join(",")+")");e?c.push("rotate(90) scale(-1,1)"):b&&c.push("rotate("+b+" "+y(this.rotationOriginX,g.getAttribute("x"),0)+" "+ +y(this.rotationOriginY,g.getAttribute("y")||0)+")");(N(k)||N(r))&&c.push("scale("+y(k,1)+" "+y(r,1)+")");c.length&&g.setAttribute("transform",c.join(" "))};B.prototype.visibilitySetter=function(c,a,k){"inherit"===c?k.removeAttribute(a):this[a]!==c&&k.setAttribute(a,c);this[a]=c};B.prototype.xGetter=function(c){"circle"===this.element.nodeName&&("x"===c?c="cx":"y"===c&&(c="cy"));return this._defaultGetter(c)};B.prototype.zIndexSetter=function(c,a){var k=this.renderer,r=this.parentGroup,e=(r||k).element|| +k.box,b=this.element,l=!1;k=e===k.box;var g=this.added;var h;N(c)?(b.setAttribute("data-z-index",c),c=+c,this[a]===c&&(g=!1)):N(this[a])&&b.removeAttribute("data-z-index");this[a]=c;if(g){(c=this.zIndex)&&r&&(r.handleZ=!0);a=e.childNodes;for(h=a.length-1;0<=h&&!l;h--){r=a[h];g=r.getAttribute("data-z-index");var p=!N(g);if(r!==b)if(0>c&&p&&!k&&!h)e.insertBefore(b,a[h]),l=!0;else if(G(g)<=c||p&&(!N(c)||0<=c))e.insertBefore(b,a[h+1]||null),l=!0}l||(e.insertBefore(b,a[k?3:0]||null),l=!0)}return l};return B}(); +E.prototype["stroke-widthSetter"]=E.prototype.strokeSetter;E.prototype.yGetter=E.prototype.xGetter;E.prototype.matrixSetter=E.prototype.rotationOriginXSetter=E.prototype.rotationOriginYSetter=E.prototype.rotationSetter=E.prototype.scaleXSetter=E.prototype.scaleYSetter=E.prototype.translateXSetter=E.prototype.translateYSetter=E.prototype.verticalAlignSetter=function(e,c){this[c]=e;this.doTransform=!0};f.SVGElement=E;return f.SVGElement});Q(A,"parts/SvgRenderer.js",[A["parts/Color.js"],A["parts/Globals.js"], +A["parts/SVGElement.js"],A["parts/Utilities.js"]],function(d,f,E,q){var M=d.parse,K=q.addEvent,J=q.attr,L=q.createElement,x=q.css,F=q.defined,H=q.destroyObjectProperties,C=q.extend,D=q.isArray,w=q.isNumber,n=q.isObject,t=q.isString,N=q.merge,m=q.objectEach,b=q.pick,g=q.pInt,v=q.removeEvent,h=q.splat,e=q.uniqueKey,p=f.charts,l=f.deg2rad,I=f.doc,u=f.isFirefox,y=f.isMS,G=f.isWebKit;q=f.noop;var S=f.svg,R=f.SVG_NS,B=f.symbolSizes,c=f.win;d=f.SVGRenderer=function(){this.init.apply(this,arguments)};C(d.prototype, +{Element:E,SVG_NS:R,init:function(a,k,r,e,b,l,g){var z=this.createElement("svg").attr({version:"1.1","class":"highcharts-root"});g||z.css(this.getStyle(e));e=z.element;a.appendChild(e);J(a,"dir","ltr");-1===a.innerHTML.indexOf("xmlns")&&J(e,"xmlns",this.SVG_NS);this.isSVG=!0;this.box=e;this.boxWrapper=z;this.alignedObjects=[];this.url=(u||G)&&I.getElementsByTagName("base").length?c.location.href.split("#")[0].replace(/<[^>]*>/g,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(I.createTextNode("Created with Highcharts 8.1.0")); +this.defs=this.createElement("defs").add();this.allowHTML=l;this.forExport=b;this.styledMode=g;this.gradients={};this.cache={};this.cacheKeys=[];this.imgCount=0;this.setSize(k,r,!1);var h;u&&a.getBoundingClientRect&&(k=function(){x(a,{left:0,top:0});h=a.getBoundingClientRect();x(a,{left:Math.ceil(h.left)-h.left+"px",top:Math.ceil(h.top)-h.top+"px"})},k(),this.unSubPixelFix=K(c,"resize",k))},definition:function(a){function c(a,k){var e;h(a).forEach(function(a){var b=r.createElement(a.tagName),l={}; +m(a,function(a,c){"tagName"!==c&&"children"!==c&&"textContent"!==c&&(l[c]=a)});b.attr(l);b.add(k||r.defs);a.textContent&&b.element.appendChild(I.createTextNode(a.textContent));c(a.children||[],b);e=b});return e}var r=this;return c(a)},getStyle:function(a){return this.style=C({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},a)},setStyle:function(a){this.boxWrapper.css(this.getStyle(a))},isHidden:function(){return!this.boxWrapper.getBBox().width},destroy:function(){var a= +this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();H(this.gradients||{});this.gradients=null;a&&(this.defs=a.destroy());this.unSubPixelFix&&this.unSubPixelFix();return this.alignedObjects=null},createElement:function(a){var c=new this.Element;c.init(this,a);return c},draw:q,getRadialAttr:function(a,c){return{cx:a[0]-a[2]/2+c.cx*a[2],cy:a[1]-a[2]/2+c.cy*a[2],r:c.r*a[2]}},truncate:function(a,c,r,e,b,l,g){var k=this,z=a.rotation,h,p=e?1:0,u=(r||e).length,P=u,m=[],v=function(a){c.firstChild&& +c.removeChild(c.firstChild);a&&c.appendChild(I.createTextNode(a))},y=function(l,z){z=z||l;if("undefined"===typeof m[z])if(c.getSubStringLength)try{m[z]=b+c.getSubStringLength(0,e?z+1:z)}catch(fa){""}else k.getSpanWidth&&(v(g(r||e,l)),m[z]=b+k.getSpanWidth(a,c));return m[z]},n;a.rotation=0;var U=y(c.textContent.length);if(n=b+U>l){for(;p<=u;)P=Math.ceil((p+u)/2),e&&(h=g(e,P)),U=y(P,h&&h.length-1),p===u?p=u+1:U>l?u=P-1:p=P;0===u?v(""):r&&u===r.length-1||v(h||g(r||e,P))}e&&e.splice(0,P);a.actualWidth= +U;a.rotation=z;return n},escapes:{"&":"&","<":"<",">":">","'":"'",'"':"""},buildText:function(a){var c=a.element,r=this,e=r.forExport,l=b(a.textStr,"").toString(),h=-1!==l.indexOf("<"),p=c.childNodes,u,v=J(c,"x"),y=a.styles,n=a.textWidth,O=y&&y.lineHeight,V=y&&y.textOutline,t=y&&"ellipsis"===y.textOverflow,G=y&&"nowrap"===y.whiteSpace,d=y&&y.fontSize,w,B=p.length;y=n&&!a.added&&this.box;var f=function(a){var k;r.styledMode||(k=/(px|em)$/.test(a&&a.style.fontSize)?a.style.fontSize: +d||r.style.fontSize||12);return O?g(O):r.fontMetrics(k,a.getAttribute("style")?a:c).h},N=function(a,c){m(r.escapes,function(k,r){c&&-1!==c.indexOf(k)||(a=a.toString().replace(new RegExp(k,"g"),r))});return a},C=function(a,c){var k=a.indexOf("<");a=a.substring(k,a.indexOf(">")-k);k=a.indexOf(c+"=");if(-1!==k&&(k=k+c.length+1,c=a.charAt(k),'"'===c||"'"===c))return a=a.substring(k+1),a.substring(0,a.indexOf(c))},D=//g;var q=[l,t,G,O,V,d,n].join();if(q!==a.textCache){for(a.textCache=q;B--;)c.removeChild(p[B]); +h||V||t||n||-1!==l.indexOf(" ")&&(!G||D.test(l))?(y&&y.appendChild(c),h?(l=r.styledMode?l.replace(/<(b|strong)>/g,'').replace(/<(i|em)>/g,''):l.replace(/<(b|strong)>/g,'').replace(/<(i|em)>/g,''),l=l.replace(//g,"").split(D)):l=[l],l=l.filter(function(a){return""!==a}),l.forEach(function(k,b){var l=0,g=0;k=k.replace(/^\s+|\s+$/g, +"").replace(//g,"|||");var z=k.split("|||");z.forEach(function(k){if(""!==k||1===z.length){var h={},p=I.createElementNS(r.SVG_NS,"tspan"),m,P;(m=C(k,"class"))&&J(p,"class",m);if(m=C(k,"style"))m=m.replace(/(;| |^)color([ :])/,"$1fill$2"),J(p,"style",m);(P=C(k,"href"))&&!e&&(J(p,"onclick",'location.href="'+P+'"'),J(p,"class","highcharts-anchor"),r.styledMode||x(p,{cursor:"pointer"}));k=N(k.replace(/<[a-zA-Z\/](.|\n)*?>/g,"")||" ");if(" "!==k){p.appendChild(I.createTextNode(k)); +l?h.dx=0:b&&null!==v&&(h.x=v);J(p,h);c.appendChild(p);!l&&w&&(!S&&e&&x(p,{display:"block"}),J(p,"dy",f(p)));if(n){var O=k.replace(/([^\^])-/g,"$1- ").split(" ");h=!G&&(1Math.abs(l.end-l.start-2*Math.PI));var z=Math.cos(k),u=Math.sin(k),m=Math.cos(p);p=Math.sin(p);k=b(l.longArc,.001>l.end-k-Math.PI?0:1);g=[["M",a+g*z,c+h*u],["A",g,h,0,k,b(l.clockwise,1),a+g*m,c+h*p]];F(r)&&g.push(e?["M",a+r*m,c+r*p]:["L",a+r*m,c+r*p],["A",r,r,0,k,F(l.clockwise)?1-l.clockwise:0,a+r*z,c+r*u]);e||g.push(["Z"]);return g},callout:function(a,c,r,e,b){var k=Math.min(b&&b.r||0,r,e),l=k+6,g= +b&&b.anchorX;b=b&&b.anchorY;var h=[["M",a+k,c],["L",a+r-k,c],["C",a+r,c,a+r,c,a+r,c+k],["L",a+r,c+e-k],["C",a+r,c+e,a+r,c+e,a+r-k,c+e],["L",a+k,c+e],["C",a,c+e,a,c+e,a,c+e-k],["L",a,c+k],["C",a,c,a,c,a+k,c]];g&&g>r?b>c+l&&bg?b>c+l&&be&&g>a+l&&gb&&g>a+l&&ga?a+3:Math.round(1.2*a);return{h:k, +b:Math.round(.8*k),f:a}},rotCorr:function(a,c,e){var k=a;c&&e&&(k=Math.max(k*Math.cos(c*l),4));return{x:-a/3*Math.sin(c*l),y:k}},pathToSegments:function(a){for(var c=[],e=[],b={A:8,C:7,H:2,L:3,M:3,Q:5,S:5,T:3,V:2},l=0;lthis.oldTextWidth)&&((u=this.textPxLength)||(M(t,{width:"",whiteSpace:p||"nowrap"}),u=t.offsetWidth),u=u>l);u&&(/[ \-]/.test(t.textContent||t.innerText)||"ellipsis"===t.style.textOverflow)?(M(t,{width:l+"px",display:"block",whiteSpace:p||"normal"}),this.oldTextWidth=l,this.hasBoxWidthChanged=!0):this.hasBoxWidthChanged=!1;I!==this.cTT&& +(p=n.fontMetrics(t.style.fontSize,t).b,!K(e)||e===(this.oldRotation||0)&&v===this.oldAlign||this.setSpanRotation(e,h,p),this.getSpanCorrection(!K(e)&&this.textPxLength||t.offsetWidth,p,h,e,v));M(t,{left:b+(this.xCorr||0)+"px",top:g+(this.yCorr||0)+"px"});this.cTT=I;this.oldRotation=e;this.oldAlign=v}}else this.alignOnAdd=!0},setSpanRotation:function(n,t,d){var m={},b=this.renderer.getTransformKey();m[b]=m.transform="rotate("+n+"deg)";m[b+(F?"Origin":"-origin")]=m.transformOrigin=100*t+"% "+d+"px"; +M(this.element,m)},getSpanCorrection:function(n,t,d){this.xCorr=-n*d;this.yCorr=-t}});J(f.prototype,{getTransformKey:function(){return H&&!/Edge/.test(w.navigator.userAgent)?"-ms-transform":C?"-webkit-transform":F?"MozTransform":w.opera?"-o-transform":""},html:function(n,t,d){var m=this.createElement("span"),b=m.element,g=m.renderer,v=g.isSVG,h=function(e,b){["opacity","visibility"].forEach(function(l){e[l+"Setter"]=function(g,h,p){var u=e.div?e.div.style:b;D.prototype[l+"Setter"].call(this,g,h,p); +u&&(u[h]=g)}});e.addedSetters=!0};m.textSetter=function(e){e!==b.innerHTML&&(delete this.bBox,delete this.oldTextWidth);this.textStr=e;b.innerHTML=L(e,"");m.doTransform=!0};v&&h(m,m.element.style);m.xSetter=m.ySetter=m.alignSetter=m.rotationSetter=function(e,b){"align"===b&&(b="textAlign");m[b]=e;m.doTransform=!0};m.afterSetters=function(){this.doTransform&&(this.htmlUpdateTransform(),this.doTransform=!1)};m.attr({text:n,x:Math.round(t),y:Math.round(d)}).css({position:"absolute"});g.styledMode||m.css({fontFamily:this.style.fontFamily, +fontSize:this.style.fontSize});b.style.whiteSpace="nowrap";m.css=m.htmlCss;v&&(m.add=function(e){var p=g.box.parentNode,l=[];if(this.parentGroup=e){var v=e.div;if(!v){for(;e;)l.push(e),e=e.parentGroup;l.reverse().forEach(function(e){function b(b,l){e[l]=b;"translateX"===l?u.left=b+"px":u.top=b+"px";e.doTransform=!0}var g=E(e.element,"class");v=e.div=e.div||q("div",g?{className:g}:void 0,{position:"absolute",left:(e.translateX||0)+"px",top:(e.translateY||0)+"px",display:e.display,opacity:e.opacity, +pointerEvents:e.styles&&e.styles.pointerEvents},v||p);var u=v.style;J(e,{classSetter:function(e){return function(b){this.element.setAttribute("class",b);e.className=b}}(v),on:function(){l[0].div&&m.on.apply({element:l[0].div},arguments);return e},translateXSetter:b,translateYSetter:b});e.addedSetters||h(e)})}}else v=p;v.appendChild(b);m.added=!0;m.alignOnAdd&&m.htmlUpdateTransform();return m});return m}})});Q(A,"parts/Tick.js",[A["parts/Globals.js"],A["parts/Utilities.js"]],function(d,f){var E=f.clamp, +q=f.correctFloat,M=f.defined,K=f.destroyObjectProperties,J=f.extend,L=f.fireEvent,x=f.isNumber,F=f.merge,H=f.objectEach,C=f.pick,D=d.deg2rad;f=function(){function d(n,t,d,m,b){this.isNewLabel=this.isNew=!0;this.axis=n;this.pos=t;this.type=d||"";this.parameters=b||{};this.tickmarkOffset=this.parameters.tickmarkOffset;this.options=this.parameters.options;L(this,"init");d||m||this.addLabel()}d.prototype.addLabel=function(){var n=this,t=n.axis,d=t.options,m=t.chart,b=t.categories,g=t.logarithmic,v=t.names, +h=n.pos,e=C(n.options&&n.options.labels,d.labels),p=t.tickPositions,l=h===p[0],I=h===p[p.length-1];v=this.parameters.category||(b?C(b[h],v[h],h):h);var u=n.label;b=(!e.step||1===e.step)&&1===t.tickInterval;p=p.info;var y,G;if(t.dateTime&&p){var f=m.time.resolveDTLFormat(d.dateTimeLabelFormats[!d.grid&&p.higherRanks[h]||p.unitName]);var w=f.main}n.isFirst=l;n.isLast=I;n.formatCtx={axis:t,chart:m,isFirst:l,isLast:I,dateTimeLabelFormat:w,tickPositionInfo:p,value:g?q(g.lin2log(v)):v,pos:h};d=t.labelFormatter.call(n.formatCtx, +this.formatCtx);if(G=f&&f.list)n.shortenLabel=function(){for(y=0;ye&&m-p*lg&&(G=Math.round((b-m)/Math.cos(e* +D)));else if(b=m+(1-p)*l,m-p*lg&&(u=g-n.x+u*p,y=-1),u=Math.min(I,u),uu||d.autoRotation&&(h.styles||{}).width)G=u;G&&(this.shortenLabel?this.shortenLabel():(w.width=Math.floor(G)+"px",(f.style||{}).textOverflow||(w.textOverflow="ellipsis"),h.css(w)))};d.prototype.moveLabel=function(n,d){var t=this,m=t.label,b=!1,g=t.axis,v=g.reversed,h=g.chart.inverted;m&&m.textStr===n?(t.movedLabel=m,b=!0,delete t.label):H(g.ticks, +function(e){b||e.isNew||e===t||!e.label||e.label.textStr!==n||(t.movedLabel=e.label,b=!0,e.labelPos=t.movedLabel.xy,delete e.label)});if(!b&&(t.labelPos||m)){var e=t.labelPos||m.xy;m=h?e.x:v?0:g.width+g.left;g=h?v?g.width+g.left:0:e.y;t.movedLabel=t.createLabel({x:m,y:g},n,d);t.movedLabel&&t.movedLabel.attr({opacity:0})}};d.prototype.render=function(n,d,f){var m=this.axis,b=m.horiz,g=this.pos,v=C(this.tickmarkOffset,m.tickmarkOffset);g=this.getPosition(b,g,v,d);v=g.x;var h=g.y;m=b&&v===m.pos+m.len|| +!b&&h===m.pos?-1:1;f=C(f,1);this.isActive=!0;this.renderGridLine(d,f,m);this.renderMark(g,f,m);this.renderLabel(g,d,f,n);this.isNew=!1;L(this,"afterRender")};d.prototype.renderGridLine=function(n,d,f){var m=this.axis,b=m.options,g=this.gridLine,v={},h=this.pos,e=this.type,p=C(this.tickmarkOffset,m.tickmarkOffset),l=m.chart.renderer,I=e?e+"Grid":"grid",u=b[I+"LineWidth"],y=b[I+"LineColor"];b=b[I+"LineDashStyle"];g||(m.chart.styledMode||(v.stroke=y,v["stroke-width"]=u,b&&(v.dashstyle=b)),e||(v.zIndex= +1),n&&(d=0),this.gridLine=g=l.path().attr(v).addClass("highcharts-"+(e?e+"-":"")+"grid-line").add(m.gridGroup));if(g&&(f=m.getPlotLinePath({value:h+p,lineWidth:g.strokeWidth()*f,force:"pass",old:n})))g[n||this.isNew?"attr":"animate"]({d:f,opacity:d})};d.prototype.renderMark=function(n,d,f){var m=this.axis,b=m.options,g=m.chart.renderer,v=this.type,h=v?v+"Tick":"tick",e=m.tickSize(h),p=this.mark,l=!p,I=n.x;n=n.y;var u=C(b[h+"Width"],!v&&m.isXAxis?1:0);b=b[h+"Color"];e&&(m.opposite&&(e[0]=-e[0]),l&& +(this.mark=p=g.path().addClass("highcharts-"+(v?v+"-":"")+"tick").add(m.axisGroup),m.chart.styledMode||p.attr({stroke:b,"stroke-width":u})),p[l?"attr":"animate"]({d:this.getMarkPath(I,n,e[0],p.strokeWidth()*f,m.horiz,g),opacity:d}))};d.prototype.renderLabel=function(n,d,f,m){var b=this.axis,g=b.horiz,v=b.options,h=this.label,e=v.labels,p=e.step;b=C(this.tickmarkOffset,b.tickmarkOffset);var l=!0,I=n.x;n=n.y;h&&x(I)&&(h.xy=n=this.getLabelPosition(I,n,h,g,e,b,m,p),this.isFirst&&!this.isLast&&!C(v.showFirstLabel, +1)||this.isLast&&!this.isFirst&&!C(v.showLastLabel,1)?l=!1:!g||e.step||e.rotation||d||0===f||this.handleOverflow(n),p&&m%p&&(l=!1),l&&x(n.y)?(n.opacity=f,h[this.isNewLabel?"attr":"animate"](n),this.isNewLabel=!1):(h.attr("y",-9999),this.isNewLabel=!0))};d.prototype.replaceMovedLabel=function(){var n=this.label,d=this.axis,f=d.reversed,m=this.axis.chart.inverted;if(n&&!this.isNew){var b=m?n.xy.x:f?d.left:d.width+d.left;f=m?f?d.width+d.top:d.top:n.xy.y;n.animate({x:b,y:f,opacity:0},void 0,n.destroy); +delete this.label}d.isDirty=!0;this.label=this.movedLabel;delete this.movedLabel};return d}();d.Tick=f;return d.Tick});Q(A,"parts/Time.js",[A["parts/Globals.js"],A["parts/Utilities.js"]],function(d,f){var E=f.defined,q=f.error,M=f.extend,K=f.isObject,J=f.merge,L=f.objectEach,x=f.pad,F=f.pick,H=f.splat,C=f.timeUnits,D=d.win;f=function(){function f(d){this.options={};this.variableTimezone=this.useUTC=!1;this.Date=D.Date;this.getTimezoneOffset=this.timezoneOffsetFunction();this.update(d)}f.prototype.get= +function(d,t){if(this.variableTimezone||this.timezoneOffset){var n=t.getTime(),m=n-this.getTimezoneOffset(t);t.setTime(m);d=t["getUTC"+d]();t.setTime(n);return d}return this.useUTC?t["getUTC"+d]():t["get"+d]()};f.prototype.set=function(d,t,f){if(this.variableTimezone||this.timezoneOffset){if("Milliseconds"===d||"Seconds"===d||"Minutes"===d)return t["setUTC"+d](f);var m=this.getTimezoneOffset(t);m=t.getTime()-m;t.setTime(m);t["setUTC"+d](f);d=this.getTimezoneOffset(t);m=t.getTime()+d;return t.setTime(m)}return this.useUTC? +t["setUTC"+d](f):t["set"+d](f)};f.prototype.update=function(d){var n=F(d&&d.useUTC,!0);this.options=d=J(!0,this.options||{},d);this.Date=d.Date||D.Date||Date;this.timezoneOffset=(this.useUTC=n)&&d.timezoneOffset;this.getTimezoneOffset=this.timezoneOffsetFunction();this.variableTimezone=!(n&&!d.getTimezoneOffset&&!d.timezone)};f.prototype.makeTime=function(n,f,w,m,b,g){if(this.useUTC){var v=this.Date.UTC.apply(0,arguments);var h=this.getTimezoneOffset(v);v+=h;var e=this.getTimezoneOffset(v);h!==e? +v+=e-h:h-36E5!==this.getTimezoneOffset(v-36E5)||d.isSafari||(v-=36E5)}else v=(new this.Date(n,f,F(w,1),F(m,0),F(b,0),F(g,0))).getTime();return v};f.prototype.timezoneOffsetFunction=function(){var d=this,f=this.options,w=D.moment;if(!this.useUTC)return function(m){return 6E4*(new Date(m.toString())).getTimezoneOffset()};if(f.timezone){if(w)return function(m){return 6E4*-w.tz(m,f.timezone).utcOffset()};q(25)}return this.useUTC&&f.getTimezoneOffset?function(m){return 6E4*f.getTimezoneOffset(m.valueOf())}: +function(){return 6E4*(d.timezoneOffset||0)}};f.prototype.dateFormat=function(n,f,w){var m;if(!E(f)||isNaN(f))return(null===(m=d.defaultOptions.lang)||void 0===m?void 0:m.invalidDate)||"";n=F(n,"%Y-%m-%d %H:%M:%S");var b=this;m=new this.Date(f);var g=this.get("Hours",m),v=this.get("Day",m),h=this.get("Date",m),e=this.get("Month",m),p=this.get("FullYear",m),l=d.defaultOptions.lang,I=null===l||void 0===l?void 0:l.weekdays,u=null===l||void 0===l?void 0:l.shortWeekdays;m=M({a:u?u[v]:I[v].substr(0,3), +A:I[v],d:x(h),e:x(h,2," "),w:v,b:l.shortMonths[e],B:l.months[e],m:x(e+1),o:e+1,y:p.toString().substr(2,2),Y:p,H:x(g),k:g,I:x(g%12||12),l:g%12||12,M:x(this.get("Minutes",m)),p:12>g?"AM":"PM",P:12>g?"am":"pm",S:x(m.getSeconds()),L:x(Math.floor(f%1E3),3)},d.dateFormats);L(m,function(e,l){for(;-1!==n.indexOf("%"+l);)n=n.replace("%"+l,"function"===typeof e?e.call(b,f):e)});return w?n.substr(0,1).toUpperCase()+n.substr(1):n};f.prototype.resolveDTLFormat=function(d){return K(d,!0)?d:(d=H(d),{main:d[0],from:d[1], +to:d[2]})};f.prototype.getTimeTicks=function(d,f,w,m){var b=this,g=[],v={};var h=new b.Date(f);var e=d.unitRange,p=d.count||1,l;m=F(m,1);if(E(f)){b.set("Milliseconds",h,e>=C.second?0:p*Math.floor(b.get("Milliseconds",h)/p));e>=C.second&&b.set("Seconds",h,e>=C.minute?0:p*Math.floor(b.get("Seconds",h)/p));e>=C.minute&&b.set("Minutes",h,e>=C.hour?0:p*Math.floor(b.get("Minutes",h)/p));e>=C.hour&&b.set("Hours",h,e>=C.day?0:p*Math.floor(b.get("Hours",h)/p));e>=C.day&&b.set("Date",h,e>=C.month?1:Math.max(1, +p*Math.floor(b.get("Date",h)/p)));if(e>=C.month){b.set("Month",h,e>=C.year?0:p*Math.floor(b.get("Month",h)/p));var n=b.get("FullYear",h)}e>=C.year&&b.set("FullYear",h,n-n%p);e===C.week&&(n=b.get("Day",h),b.set("Date",h,b.get("Date",h)-n+m+(n4*C.month||b.getTimezoneOffset(f)!==b.getTimezoneOffset(w));f=h.getTime();for(h=1;fg.length&&g.forEach(function(e){0===e%18E5&&"000000000"===b.dateFormat("%H%M%S%L",e)&&(v[e]="day")})}g.info=M(d,{higherRanks:v,totalRange:e*p});return g};f.defaultOptions={Date:void 0,getTimezoneOffset:void 0,timezone:void 0,timezoneOffset:0,useUTC:!0};return f}();d.Time=f;return d.Time});Q(A,"parts/Options.js",[A["parts/Globals.js"], +A["parts/Time.js"],A["parts/Color.js"],A["parts/Utilities.js"]],function(d,f,E,q){E=E.parse;var M=q.merge;d.defaultOptions={colors:"#7cb5ec #434348 #90ed7d #f7a35c #8085e9 #f15c80 #e4d354 #2b908f #f45b5b #91e8e1".split(" "),symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January February March April May June July August September October November December".split(" "),shortMonths:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),weekdays:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), +decimalPoint:".",numericSymbols:"kMGTPE".split(""),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:" "},global:{},time:f.defaultOptions,chart:{styledMode:!1,borderRadius:0,colorCount:10,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacing:[10,10,15,10],resetZoomButton:{theme:{zIndex:6},position:{align:"right",x:-10,y:10}},width:null,height:null,borderColor:"#335cad",backgroundColor:"#ffffff",plotBorderColor:"#cccccc"},title:{text:"Chart title",align:"center",margin:15, +widthAdjust:-44},subtitle:{text:"",align:"center",widthAdjust:-44},caption:{margin:15,text:"",align:"left",verticalAlign:"bottom"},plotOptions:{},labels:{style:{position:"absolute",color:"#333333"}},legend:{enabled:!0,align:"center",alignColumns:!0,layout:"horizontal",labelFormatter:function(){return this.name},borderColor:"#999999",borderRadius:0,navigation:{activeColor:"#003399",inactiveColor:"#cccccc"},itemStyle:{color:"#333333",cursor:"pointer",fontSize:"12px",fontWeight:"bold",textOverflow:"ellipsis"}, +itemHoverStyle:{color:"#000000"},itemHiddenStyle:{color:"#cccccc"},shadow:!1,itemCheckboxStyle:{position:"absolute",width:"13px",height:"13px"},squareSymbol:!0,symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold",position:"relative",top:"45%"},style:{position:"absolute",backgroundColor:"#ffffff",opacity:.5,textAlign:"center"}},tooltip:{enabled:!0,animation:d.svg,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L", +second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M",day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y",month:"%B %Y",year:"%Y"},footerFormat:"",padding:8,snap:d.isTouchDevice?25:10,headerFormat:'{point.key}
',pointFormat:'\u25cf {series.name}: {point.y}
',backgroundColor:E("#f7f7f7").setOpacity(.85).get(),borderWidth:1,shadow:!0,style:{color:"#333333",cursor:"default",fontSize:"12px", +whiteSpace:"nowrap"}},credits:{enabled:!0,href:"https://www.highcharts.com?credits",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer",color:"#999999",fontSize:"9px"},text:"Highcharts.com"}};d.setOptions=function(f){d.defaultOptions=M(!0,d.defaultOptions,f);(f.time||f.global)&&d.time.update(M(d.defaultOptions.global,d.defaultOptions.time,f.global,f.time));return d.defaultOptions};d.getOptions=function(){return d.defaultOptions};d.defaultPlotOptions=d.defaultOptions.plotOptions; +d.time=new f(M(d.defaultOptions.global,d.defaultOptions.time));d.dateFormat=function(f,q,L){return d.time.dateFormat(f,q,L)};""});Q(A,"parts/Axis.js",[A["parts/Color.js"],A["parts/Globals.js"],A["parts/Tick.js"],A["parts/Utilities.js"]],function(d,f,E,q){var M=q.addEvent,K=q.animObject,J=q.arrayMax,L=q.arrayMin,x=q.clamp,F=q.correctFloat,H=q.defined,C=q.destroyObjectProperties,D=q.error,w=q.extend,n=q.fireEvent,t=q.format,N=q.getMagnitude,m=q.isArray,b=q.isFunction,g=q.isNumber,v=q.isString,h=q.merge, +e=q.normalizeTickInterval,p=q.objectEach,l=q.pick,I=q.relativeLength,u=q.removeEvent,y=q.splat,G=q.syncTimeout,S=f.defaultOptions,R=f.deg2rad;q=function(){function B(c,a){this.zoomEnabled=this.width=this.visible=this.userOptions=this.translationSlope=this.transB=this.transA=this.top=this.ticks=this.tickRotCorr=this.tickPositions=this.tickmarkOffset=this.tickInterval=this.tickAmount=this.side=this.series=this.right=this.positiveValuesOnly=this.pos=this.pointRangePadding=this.pointRange=this.plotLinesAndBandsGroups= +this.plotLinesAndBands=this.paddedTicks=this.overlap=this.options=this.oldMin=this.oldMax=this.offset=this.names=this.minPixelPadding=this.minorTicks=this.minorTickInterval=this.min=this.maxLabelLength=this.max=this.len=this.left=this.labelFormatter=this.labelEdge=this.isLinked=this.height=this.hasVisibleSeries=this.hasNames=this.coll=this.closestPointRange=this.chart=this.categories=this.bottom=this.alternateBands=void 0;this.init(c,a)}B.prototype.init=function(c,a){var k=a.isX,e=this;e.chart=c; +e.horiz=c.inverted&&!e.isZAxis?!k:k;e.isXAxis=k;e.coll=e.coll||(k?"xAxis":"yAxis");n(this,"init",{userOptions:a});e.opposite=a.opposite;e.side=a.side||(e.horiz?e.opposite?0:2:e.opposite?1:3);e.setOptions(a);var g=this.options,h=g.type;e.labelFormatter=g.labels.formatter||e.defaultLabelFormatter;e.userOptions=a;e.minPixelPadding=0;e.reversed=g.reversed;e.visible=!1!==g.visible;e.zoomEnabled=!1!==g.zoomEnabled;e.hasNames="category"===h||!0===g.categories;e.categories=g.categories||e.hasNames;e.names|| +(e.names=[],e.names.keys={});e.plotLinesAndBandsGroups={};e.positiveValuesOnly=!(!e.logarithmic||g.allowNegativeLog);e.isLinked=H(g.linkedTo);e.ticks={};e.labelEdge=[];e.minorTicks={};e.plotLinesAndBands=[];e.alternateBands={};e.len=0;e.minRange=e.userMinRange=g.minRange||g.maxZoom;e.range=g.range;e.offset=g.offset||0;e.max=null;e.min=null;e.crosshair=l(g.crosshair,y(c.options.tooltip.crosshairs)[k?0:1],!1);a=e.options.events;-1===c.axes.indexOf(e)&&(k?c.axes.splice(c.xAxis.length,0,e):c.axes.push(e), +c[e.coll].push(e));e.series=e.series||[];c.inverted&&!e.isZAxis&&k&&"undefined"===typeof e.reversed&&(e.reversed=!0);e.labelRotation=e.options.labels.rotation;p(a,function(a,c){b(a)&&M(e,c,a)});n(this,"afterInit")};B.prototype.setOptions=function(c){this.options=h(B.defaultOptions,"yAxis"===this.coll&&B.defaultYAxisOptions,[B.defaultTopAxisOptions,B.defaultRightAxisOptions,B.defaultBottomAxisOptions,B.defaultLeftAxisOptions][this.side],h(S[this.coll],c));n(this,"afterSetOptions",{userOptions:c})}; +B.prototype.defaultLabelFormatter=function(){var c=this.axis,a=this.value,k=c.chart.time,e=c.categories,b=this.dateTimeLabelFormat,l=S.lang,g=l.numericSymbols;l=l.numericSymbolMagnitude||1E3;var h=g&&g.length,p=c.options.labels.format;c=c.logarithmic?Math.abs(a):c.tickInterval;var m=this.chart,u=m.numberFormatter;if(p)var v=t(p,this,m);else if(e)v=a;else if(b)v=k.dateFormat(b,a);else if(h&&1E3<=c)for(;h--&&"undefined"===typeof v;)k=Math.pow(l,h+1),c>=k&&0===10*a%k&&null!==g[h]&&0!==a&&(v=u(a/k,-1)+ +g[h]);"undefined"===typeof v&&(v=1E4<=Math.abs(a)?u(a,-1):u(a,-1,void 0,""));return v};B.prototype.getSeriesExtremes=function(){var c=this,a=c.chart,k;n(this,"getSeriesExtremes",null,function(){c.hasVisibleSeries=!1;c.dataMin=c.dataMax=c.threshold=null;c.softThreshold=!c.isXAxis;c.stacking&&c.stacking.buildStacks();c.series.forEach(function(e){if(e.visible||!a.options.chart.ignoreHiddenSeries){var b=e.options,r=b.threshold;c.hasVisibleSeries=!0;c.positiveValuesOnly&&0>=r&&(r=null);if(c.isXAxis){if(b= +e.xData,b.length){k=e.getXExtremes(b);var h=k.min;var p=k.max;g(h)||h instanceof Date||(b=b.filter(g),k=e.getXExtremes(b),h=k.min,p=k.max);b.length&&(c.dataMin=Math.min(l(c.dataMin,h),h),c.dataMax=Math.max(l(c.dataMax,p),p))}}else if(e=e.applyExtremes(),g(e.dataMin)&&(h=e.dataMin,c.dataMin=Math.min(l(c.dataMin,h),h)),g(e.dataMax)&&(p=e.dataMax,c.dataMax=Math.max(l(c.dataMax,p),p)),H(r)&&(c.threshold=r),!b.softThreshold||c.positiveValuesOnly)c.softThreshold=!1}})});n(this,"afterGetSeriesExtremes")}; +B.prototype.translate=function(c,a,k,e,b,l){var r=this.linkedParent||this,h=1,p=0,z=e?r.oldTransA:r.transA;e=e?r.oldMin:r.min;var m=r.minPixelPadding;b=(r.isOrdinal||r.brokenAxis&&r.brokenAxis.hasBreaks||r.logarithmic&&b)&&r.lin2val;z||(z=r.transA);k&&(h*=-1,p=r.len);r.reversed&&(h*=-1,p-=h*(r.sector||r.len));a?(c=(c*h+p-m)/z+e,b&&(c=r.lin2val(c))):(b&&(c=r.val2lin(c)),c=g(e)?h*(c-e)*z+p+h*m+(g(l)?z*l:0):void 0);return c};B.prototype.toPixels=function(c,a){return this.translate(c,!1,!this.horiz,null, +!0)+(a?0:this.pos)};B.prototype.toValue=function(c,a){return this.translate(c-(a?0:this.pos),!0,!this.horiz,null,!0)};B.prototype.getPlotLinePath=function(c){function a(a,c,k){if("pass"!==d&&ak)d?a=x(a,c,k):B=!0;return a}var k=this,e=k.chart,b=k.left,h=k.top,p=c.old,m=c.value,u=c.translatedValue,v=c.lineWidth,d=c.force,y,O,f,I,G=p&&e.oldChartHeight||e.chartHeight,t=p&&e.oldChartWidth||e.chartWidth,B,w=k.transB;c={value:m,lineWidth:v,old:p,force:d,acrossPanes:c.acrossPanes,translatedValue:u}; +n(this,"getPlotLinePath",c,function(c){u=l(u,k.translate(m,null,null,p));u=x(u,-1E5,1E5);y=f=Math.round(u+w);O=I=Math.round(G-u-w);g(u)?k.horiz?(O=h,I=G-k.bottom,y=f=a(y,b,b+k.width)):(y=b,f=t-k.right,O=I=a(O,h,h+k.height)):(B=!0,d=!1);c.path=B&&!d?null:e.renderer.crispLine([["M",y,O],["L",f,I]],v||1)});return c.path};B.prototype.getLinearTickPositions=function(c,a,k){var e=F(Math.floor(a/c)*c);k=F(Math.ceil(k/c)*c);var b=[],l;F(e+c)===e&&(l=20);if(this.single)return[a];for(a=e;a<=k;){b.push(a);a= +F(a+c,l);if(a===g)break;var g=a}return b};B.prototype.getMinorTickInterval=function(){var c=this.options;return!0===c.minorTicks?l(c.minorTickInterval,"auto"):!1===c.minorTicks?null:c.minorTickInterval};B.prototype.getMinorTickPositions=function(){var c=this.options,a=this.tickPositions,k=this.minorTickInterval,e=[],b=this.pointRangePadding||0,l=this.min-b;b=this.max+b;var g=b-l;if(g&&g/k=this.minRange;var v=this.minRange;var d=(v-k+a)/2;d=[a-d,l(c.min,a-d)];m&&(d[2]=this.logarithmic?this.logarithmic.log2lin(this.dataMin):this.dataMin);a=J(d);k=[a+v,l(c.max,a+v)];m&&(k[2]=e?e.log2lin(this.dataMax):this.dataMax);k=L(k);k-a=O)B=O,v=0;else if(a.dataMax<=O){var w=O;u=0}a.min= +l(G,B,a.dataMin);a.max=l(t,w,a.dataMax)}b&&(a.positiveValuesOnly&&!c&&0>=Math.min(a.min,l(a.dataMin,a.min))&&D(10,1,k),a.min=F(b.log2lin(a.min),16),a.max=F(b.log2lin(a.max),16));a.range&&H(a.max)&&(a.userMin=a.min=G=Math.max(a.dataMin,a.minFromRange()),a.userMax=t=a.max,a.range=null);n(a,"foundExtremes");a.beforePadding&&a.beforePadding();a.adjustForMinRange();!(f||a.axisPointRange||a.stacking&&a.stacking.usePercentage||m)&&H(a.min)&&H(a.max)&&(k=a.max-a.min)&&(!H(G)&&v&&(a.min-=k*v),!H(t)&&u&&(a.max+= +k*u));g(a.userMin)||(g(h.softMin)&&h.softMina.max&&(a.max=t=h.softMax),g(h.ceiling)&&(a.max=Math.min(a.max,h.ceiling)));I&&H(a.dataMin)&&(O=O||0,!H(G)&&a.min=O?a.min=a.options.minRange?Math.min(O,a.max-a.minRange):O:!H(t)&&a.max>O&&a.dataMax<=O&&(a.max=a.options.minRange?Math.max(O,a.min+a.minRange):O));a.tickInterval=a.min===a.max||"undefined"===typeof a.min||"undefined"=== +typeof a.max?1:m&&!d&&y===a.linkedParent.options.tickPixelInterval?d=a.linkedParent.tickInterval:l(d,this.tickAmount?(a.max-a.min)/Math.max(this.tickAmount-1,1):void 0,f?1:(a.max-a.min)*y/Math.max(a.len,y));p&&!c&&a.series.forEach(function(c){c.processData(a.min!==a.oldMin||a.max!==a.oldMax)});a.setAxisTranslation(!0);a.beforeSetTickPositions&&a.beforeSetTickPositions();a.ordinal&&(a.tickInterval=a.ordinal.postProcessTickInterval(a.tickInterval));a.pointRange&&!d&&(a.tickInterval=Math.max(a.pointRange, +a.tickInterval));c=l(h.minTickInterval,a.dateTime&&a.closestPointRange);!d&&a.tickIntervala.tickInterval||void 0!==this.tickAmount),!!this.tickAmount));this.tickAmount||(a.tickInterval=a.unsquish());this.setTickPositions()};B.prototype.setTickPositions=function(){var c=this.options,a=c.tickPositions;var e=this.getMinorTickInterval();var b=c.tickPositioner,l=this.hasVerticalPanning(), +g="colorAxis"===this.coll,h=(g||!l)&&c.startOnTick;l=(g||!l)&&c.endOnTick;this.tickmarkOffset=this.categories&&"between"===c.tickmarkPlacement&&1===this.tickInterval?.5:0;this.minorTickInterval="auto"===e&&this.tickInterval?this.tickInterval/5:e;this.single=this.min===this.max&&H(this.min)&&!this.tickAmount&&(parseInt(this.min,10)===this.min||!1!==c.allowDecimals);this.tickPositions=e=a&&a.slice();!e&&(this.ordinal&&this.ordinal.positions||!((this.max-this.min)/this.tickInterval>Math.max(2*this.len, +200))?e=this.dateTime?this.getTimeTicks(this.dateTime.normalizeTimeTickInterval(this.tickInterval,c.units),this.min,this.max,c.startOfWeek,this.ordinal&&this.ordinal.positions,this.closestPointRange,!0):this.logarithmic?this.logarithmic.getLogTickPositions(this.tickInterval,this.min,this.max):this.getLinearTickPositions(this.tickInterval,this.min,this.max):(e=[this.min,this.max],D(19,!1,this.chart)),e.length>this.len&&(e=[e[0],e.pop()],e[0]===e[1]&&(e.length=1)),this.tickPositions=e,b&&(b=b.apply(this, +[this.min,this.max])))&&(this.tickPositions=e=b);this.paddedTicks=e.slice(0);this.trimTicks(e,h,l);this.isLinked||(this.single&&2>e.length&&!this.categories&&!this.series.some(function(a){return a.is("heatmap")&&"between"===a.options.pointPlacement})&&(this.min-=.5,this.max+=.5),a||b||this.adjustTickAmount());n(this,"afterSetTickPositions")};B.prototype.trimTicks=function(c,a,e){var k=c[0],b=c[c.length-1],l=!this.isOrdinal&&this.minPointOffset||0;n(this,"trimTicks");if(!this.isLinked){if(a&&-Infinity!== +k)this.min=k;else for(;this.min-l>c[0];)c.shift();if(e)this.max=b;else for(;this.max+la&&(this.finalTickAmt=a,a=5);this.tickAmount=a};B.prototype.adjustTickAmount=function(){var c=this.options,a=this.tickInterval,e=this.tickPositions,b=this.tickAmount,g=this.finalTickAmt,h=e&&e.length,p=l(this.threshold,this.softThreshold? +0:null),m;if(this.hasData()){if(hb&&(this.tickInterval*=2,this.setTickPositions());if(H(g)){for(a=c=e.length;a--;)(3===g&&1===a%2||2>=g&&0m&&(c=m)),H(g)&&(km&&(k=m))),e.displayBtn="undefined"!==typeof c||"undefined"!==typeof k,e.setExtremes(c,k,!1,void 0,{trigger:"zoom"});a.zoomed=!0});return c.zoomed};B.prototype.setAxisSize=function(){var c=this.chart,a=this.options,e=a.offsets||[0,0,0,0],b=this.horiz,g=this.width=Math.round(I(l(a.width, +c.plotWidth-e[3]+e[1]),c.plotWidth)),h=this.height=Math.round(I(l(a.height,c.plotHeight-e[0]+e[2]),c.plotHeight)),p=this.top=Math.round(I(l(a.top,c.plotTop+e[0]),c.plotHeight,c.plotTop));a=this.left=Math.round(I(l(a.left,c.plotLeft+e[3]),c.plotWidth,c.plotLeft));this.bottom=c.chartHeight-h-p;this.right=c.chartWidth-g-a;this.len=Math.max(b?g:h,0);this.pos=b?a:p};B.prototype.getExtremes=function(){var c=this.logarithmic;return{min:c?F(c.lin2log(this.min)):this.min,max:c?F(c.lin2log(this.max)):this.max, +dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}};B.prototype.getThreshold=function(c){var a=this.logarithmic,e=a?a.lin2log(this.min):this.min;a=a?a.lin2log(this.max):this.max;null===c||-Infinity===c?c=e:Infinity===c?c=a:e>c?c=e:aa?c.align="right":195a&&(c.align="left")}); +return c.align};B.prototype.tickSize=function(c){var a=this.options,e=a["tick"===c?"tickLength":"minorTickLength"],b=l(a["tick"===c?"tickWidth":"minorTickWidth"],"tick"===c&&this.isXAxis&&!this.categories?1:0);if(b&&e){"inside"===a[c+"Position"]&&(e=-e);var g=[e,b]}c={tickSize:g};n(this,"afterTickSize",c);return c.tickSize};B.prototype.labelMetrics=function(){var c=this.tickPositions&&this.tickPositions[0]||0;return this.chart.renderer.fontMetrics(this.options.labels.style&&this.options.labels.style.fontSize, +this.ticks[c]&&this.ticks[c].label)};B.prototype.unsquish=function(){var c=this.options.labels,a=this.horiz,e=this.tickInterval,b=e,g=this.len/(((this.categories?1:0)+this.max-this.min)/e),h,p=c.rotation,m=this.labelMetrics(),u,v=Number.MAX_VALUE,d,y=this.max-this.min,f=function(a){var c=a/(g||1);c=1y&&Infinity!==a&&Infinity!==g&&y&&(c=Math.ceil(y/e));return F(c*e)};a?(d=!c.staggerLines&&!c.step&&(H(p)?[p]:g=a){u=f(Math.abs(m.h/Math.sin(R*a)));var c=u+Math.abs(a/360);c(l.step||0))return l.rotation?0:(this.staggerLines||1)*this.len/h;if(!b){c=null===(a=null===l||void 0===l?void 0: +l.style)||void 0===a?void 0:a.width;if(void 0!==c)return parseInt(c,10);if(p)return p-e.spacing[3]}return.33*e.chartWidth};B.prototype.renderUnsquish=function(){var c=this.chart,a=c.renderer,e=this.tickPositions,b=this.ticks,l=this.options.labels,g=l&&l.style||{},h=this.horiz,p=this.getSlotWidth(),m=Math.max(1,Math.round(p-2*(l.padding||5))),u={},d=this.labelMetrics(),y=l.style&&l.style.textOverflow,f=0;v(l.rotation)||(u.rotation=l.rotation||0);e.forEach(function(a){a=b[a];a.movedLabel&&a.replaceMovedLabel(); +a&&a.label&&a.label.textPxLength>f&&(f=a.label.textPxLength)});this.maxLabelLength=f;if(this.autoRotation)f>m&&f>d.h?u.rotation=this.labelRotation:this.labelRotation=0;else if(p){var n=m;if(!y){var I="clip";for(m=e.length;!h&&m--;){var G=e[m];if(G=b[G].label)G.styles&&"ellipsis"===G.styles.textOverflow?G.css({textOverflow:"clip"}):G.textPxLength>p&&G.css({width:p+"px"}),G.getBBox().height>this.len/e.length-(d.h-d.f)&&(G.specificTextOverflow="ellipsis")}}}u.rotation&&(n=f>.5*c.chartHeight?.33*c.chartHeight: +f,y||(I="ellipsis"));if(this.labelAlign=l.align||this.autoLabelAlign(this.labelRotation))u.align=this.labelAlign;e.forEach(function(a){var c=(a=b[a])&&a.label,e=g.width,k={};c&&(c.attr(u),a.shortenLabel?a.shortenLabel():n&&!e&&"nowrap"!==g.whiteSpace&&(n=this.min&&c<=this.max)b[c]||(b[c]=new E(this,c)),l&&b[c].isNew&&b[c].render(a,!0,-1),b[c].render(a)};B.prototype.render=function(){var c=this,a=c.chart,e=c.logarithmic,b=c.options,l=c.isLinked,h=c.tickPositions,m=c.axisTitle,u=c.ticks,d=c.minorTicks,v=c.alternateBands,y=b.stackLabels,I=b.alternateGridColor, +O=c.tickmarkOffset,t=c.axisLine,B=c.showAxis,w=K(a.renderer.globalAnimation),S,R;c.labelEdge.length=0;c.overlap=!1;[u,d,v].forEach(function(a){p(a,function(a){a.isActive=!1})});if(c.hasData()||l)c.minorTickInterval&&!c.categories&&c.getMinorTickPositions().forEach(function(a){c.renderMinorTick(a)}),h.length&&(h.forEach(function(a,e){c.renderTick(a,e)}),O&&(0===c.min||c.single)&&(u[-1]||(u[-1]=new E(c,-1,null,!0)),u[-1].render(-1))),I&&h.forEach(function(k,b){R="undefined"!==typeof h[b+1]?h[b+1]+O: +c.max-O;0===b%2&&kf&&(!C||v<=H)&&"undefined"!==typeof v&&t.push(v);v>H&&(m=!0);var v=g}}}else f=this.lin2log(f),H=this.lin2log(H),d=C?x.getMinorTickInterval():n.tickInterval,d=K("auto"===d?null:d,this.minorAutoInterval,n.tickPixelInterval/(C?5:1)*(H-f)/((C?w/x.tickPositions.length:w)||1)),d=M(d,void 0,q(d)),t=x.getLinearTickPositions(d,f,H).map(this.log2lin), +C||(this.minorAutoInterval=d/5);C||(x.tickInterval=d);return t};d.prototype.lin2log=function(d){return Math.pow(10,d)};d.prototype.log2lin=function(d){return Math.log(d)/Math.LN10};return d}();f=function(){function d(){}d.compose=function(d){d.keepProps.push("logarithmic");var f=d.prototype,x=J.prototype;f.log2lin=x.log2lin;f.lin2log=x.lin2log;E(d,"init",function(d){var f=this.logarithmic;"logarithmic"!==d.userOptions.type?this.logarithmic=void 0:(f||(f=this.logarithmic=new J(this)),this.log2lin!== +f.log2lin&&(f.log2lin=this.log2lin.bind(this)),this.lin2log!==f.lin2log&&(f.lin2log=this.lin2log.bind(this)))});E(d,"afterInit",function(){var d=this.logarithmic;d&&(this.lin2val=function(f){return d.lin2log(f)},this.val2lin=function(f){return d.log2lin(f)})})};return d}();f.compose(d);return f});Q(A,"parts/PlotLineOrBand.js",[A["parts/Globals.js"],A["parts/Axis.js"],A["parts/Utilities.js"]],function(d,f,E){var q=E.arrayMax,M=E.arrayMin,K=E.defined,J=E.destroyObjectProperties,L=E.erase,x=E.extend, +F=E.merge,H=E.objectEach,C=E.pick,D=function(){function f(d,f){this.axis=d;f&&(this.options=f,this.id=f.id)}f.prototype.render=function(){d.fireEvent(this,"render");var f=this,t=f.axis,w=t.horiz,m=t.logarithmic,b=f.options,g=b.label,v=f.label,h=b.to,e=b.from,p=b.value,l=K(e)&&K(h),I=K(p),u=f.svgElem,y=!u,G=[],S=b.color,R=C(b.zIndex,0),B=b.events;G={"class":"highcharts-plot-"+(l?"band ":"line ")+(b.className||"")};var c={},a=t.chart.renderer,k=l?"bands":"lines";m&&(e=m.log2lin(e),h=m.log2lin(h),p= +m.log2lin(p));t.chart.styledMode||(I?(G.stroke=S||"#999999",G["stroke-width"]=C(b.width,1),b.dashStyle&&(G.dashstyle=b.dashStyle)):l&&(G.fill=S||"#e6ebf5",b.borderWidth&&(G.stroke=b.borderColor,G["stroke-width"]=b.borderWidth)));c.zIndex=R;k+="-"+R;(m=t.plotLinesAndBandsGroups[k])||(t.plotLinesAndBandsGroups[k]=m=a.g("plot-"+k).attr(c).add());y&&(f.svgElem=u=a.path().attr(G).add(m));if(I)G=t.getPlotLinePath({value:p,lineWidth:u.strokeWidth(),acrossPanes:b.acrossPanes});else if(l)G=t.getPlotBandPath(e, +h,b);else return;(y||!u.d)&&G&&G.length?(u.attr({d:G}),B&&H(B,function(a,c){u.on(c,function(a){B[c].apply(f,[a])})})):u&&(G?(u.show(!0),u.animate({d:G})):u.d&&(u.hide(),v&&(f.label=v=v.destroy())));g&&(K(g.text)||K(g.formatter))&&G&&G.length&&0this.max&&f>this.max;if(w&&n){if(d){var v=w.toString()===n.toString();g=0}for(d=0;db){f=u;break}if(m[f]&&l.substr(m[f])!=="01-01 00:00:00.000".substr(m[f]))break;"week"!==f&&(u=f)}if(f)var v=g.resolveDTLFormat(e[f]).main;return v};b.prototype.getLabel=function(){var b,m,h=this,e=this.chart.renderer,p=this.chart.styledMode,l=this.options,f="tooltip"+(M(l.className)?" "+l.className:""),u=(null===(b=l.style)||void 0===b?void 0:b.pointerEvents)||(!this.followPointer&& +l.stickOnContact?"auto":"none"),y;b=function(){h.inContact=!0};var G=function(){var e=h.chart.hoverSeries;h.inContact=!1;if(e&&e.onMouseOut)e.onMouseOut()};if(!this.label){this.outside&&(this.container=y=d.doc.createElement("div"),y.className="highcharts-tooltip-container",q(y,{position:"absolute",top:"1px",pointerEvents:u,zIndex:3}),d.doc.body.appendChild(y),this.renderer=e=new d.Renderer(y,0,0,null===(m=this.chart.options.chart)||void 0===m?void 0:m.style,void 0,void 0,e.styledMode));this.split? +this.label=e.g(f):(this.label=e.label("",0,0,l.shape||"callout",null,null,l.useHTML,null,f).attr({padding:l.padding,r:l.borderRadius}),p||this.label.attr({fill:l.backgroundColor,"stroke-width":l.borderWidth}).css(l.style).css({pointerEvents:u}).shadow(l.shadow));p&&(this.applyFilter(),this.label.addClass("highcharts-tooltip-"+this.chart.index));if(h.outside&&!h.split){var n={x:this.label.xSetter,y:this.label.ySetter};this.label.xSetter=function(e,b){n[b].call(this.label,h.distance);y.style.left=e+ +"px"};this.label.ySetter=function(e,b){n[b].call(this.label,h.distance);y.style.top=e+"px"}}this.label.on("mouseenter",b).on("mouseleave",G).attr({zIndex:8}).add()}return this.label};b.prototype.getPosition=function(b,d,h){var e=this.chart,g=this.distance,l={},m=e.inverted&&h.h||0,u,f=this.outside,v=f?N.documentElement.clientWidth-2*g:e.chartWidth,n=f?Math.max(N.body.scrollHeight,N.documentElement.scrollHeight,N.body.offsetHeight,N.documentElement.offsetHeight,N.documentElement.clientHeight):e.chartHeight, +t=e.pointer.getChartPosition(),B=e.containerScaling,c=function(a){return B?a*B.scaleX:a},a=function(a){return B?a*B.scaleY:a},k=function(k){var l="x"===k;return[k,l?v:n,l?b:d].concat(f?[l?c(b):a(d),l?t.left-g+c(h.plotX+e.plotLeft):t.top-g+a(h.plotY+e.plotTop),0,l?v:n]:[l?b:d,l?h.plotX+e.plotLeft:h.plotY+e.plotTop,l?e.plotLeft:e.plotTop,l?e.plotLeft+e.plotWidth:e.plotTop+e.plotHeight])},r=k("y"),z=k("x"),w=!this.followPointer&&D(h.ttBelow,!e.inverted===!!h.negative),x=function(e,b,k,h,p,r,d){var u= +"y"===e?a(g):c(g),f=(k-h)/2,v=hz-m?z:z-m);else if(y)l[e]=Math.max(r,p+m+k>b?p:p+m);else return!1},C=function(a,c,e,b,k){var h;kc-g?h=!1:l[a]=kc-b/2?c-b-2:k-e/2;return h},q=function(a){var c=r;r=z;z=c;u=a},T=function(){!1!==x.apply(0,r)?!1!==C.apply(0,z)||u||(q(!0),T()):u?l.x=l.y=0:(q(!0),T())};(e.inverted||1=a+v&&O.pos+G<=a+v+f-B&&(I=O.pos+G);n=E(n,x.left-r,x.right+r);"number"===typeof I?(y=y.height+1,G=P?P.call(e,d,y,l):g(n,I,h,d),c.push({align:P?0:void 0,anchorX:n,anchorY:I,boxWidth:d,point:l,rank:D(G.rank,h?1:0),size:y,target:G.y,tt:b,x:G.x})):b.isActive=!1}return c},[]);!P&&b.some(function(a){return a.xh[0]?Math.max(Math.abs(h[0]),p.width-h[0]):Math.max(Math.abs(h[0]),p.width);e.height=0>h[1]?Math.max(Math.abs(h[1]),p.height-Math.abs(h[1])):Math.max(Math.abs(h[1]),p.height);this.tracker?this.tracker.attr(e): +(this.tracker=d.renderer.rect(e).addClass("highcharts-tracker").add(d),b.styledMode||this.tracker.attr({fill:"rgba(0,0,0,0)"}))}}};b.prototype.styledModeFormat=function(b){return b.replace('style="font-size: 10px"','class="highcharts-header"').replace(/style="color:{(point|series)\.color}"/g,'class="highcharts-color-{$1.colorIndex}"')};b.prototype.tooltipFooterHeaderFormatter=function(b,d){var h=d?"footer":"header",e=b.series,g=e.tooltipOptions,l=g.xDateFormat,m=e.xAxis,u=m&&"datetime"===m.options.type&& +F(b.key),f=g[h+"Format"];d={isFooter:d,labelConfig:b};L(this,"headerFormatter",d,function(h){u&&!l&&(l=this.getXDateFormat(b,g,m));u&&l&&(b.point&&b.point.tooltipDateKeys||["key"]).forEach(function(e){f=f.replace("{point."+e+"}","{point."+e+":"+l+"}")});e.chart.styledMode&&(f=this.styledModeFormat(f));h.text=x(f,{point:b,series:e},this.chart)});return d.text};b.prototype.update=function(b){this.destroy();C(!0,this.chart.options.tooltip.userOptions,b);this.init(this.chart,C(!0,this.options,b))};b.prototype.updatePosition= +function(b){var g=this.chart,h=g.pointer,e=this.getLabel(),d=b.plotX+g.plotLeft,l=b.plotY+g.plotTop;h=h.getChartPosition();b=(this.options.positioner||this.getPosition).call(this,e.width,e.height,b);if(this.outside){var m=(this.options.borderWidth||0)+2*this.distance;this.renderer.setSize(e.width+m,e.height+m,!1);if(g=g.containerScaling)q(this.container,{transform:"scale("+g.scaleX+", "+g.scaleY+")"}),d*=g.scaleX,l*=g.scaleY;d+=h.left-b.x;l+=h.top-b.y}this.move(Math.round(b.x),Math.round(b.y||0), +d,l)};return b}();d.Tooltip=m;return d.Tooltip});Q(A,"parts/Pointer.js",[A["parts/Globals.js"],A["parts/Utilities.js"],A["parts/Tooltip.js"],A["parts/Color.js"]],function(d,f,E,q){var M=f.addEvent,K=f.attr,J=f.css,L=f.defined,x=f.extend,F=f.find,H=f.fireEvent,C=f.isNumber,D=f.isObject,w=f.objectEach,n=f.offset,t=f.pick,N=f.splat,m=q.parse,b=d.charts,g=d.noop;f=function(){function f(b,e){this.lastValidTouch={};this.pinchDown=[];this.runChartClick=!1;this.chart=b;this.hasDragged=!1;this.options=e;this.unbindContainerMouseLeave= +function(){};this.init(b,e)}f.prototype.applyInactiveState=function(b){var e=[],h;(b||[]).forEach(function(b){h=b.series;e.push(h);h.linkedParent&&e.push(h.linkedParent);h.linkedSeries&&(e=e.concat(h.linkedSeries));h.navigatorSeries&&e.push(h.navigatorSeries)});this.chart.series.forEach(function(b){-1===e.indexOf(b)?b.setState("inactive",!0):b.options.inactiveOtherPoints&&b.setAllPointsToState("inactive")})};f.prototype.destroy=function(){var b=this;"undefined"!==typeof b.unDocMouseMove&&b.unDocMouseMove(); +this.unbindContainerMouseLeave();d.chartCount||(d.unbindDocumentMouseUp&&(d.unbindDocumentMouseUp=d.unbindDocumentMouseUp()),d.unbindDocumentTouchEnd&&(d.unbindDocumentTouchEnd=d.unbindDocumentTouchEnd()));clearInterval(b.tooltipTimeout);w(b,function(e,h){b[h]=null})};f.prototype.drag=function(b){var e=this.chart,h=e.options.chart,l=b.chartX,g=b.chartY,d=this.zoomHor,f=this.zoomVert,v=e.plotLeft,n=e.plotTop,t=e.plotWidth,B=e.plotHeight,c=this.selectionMarker,a=this.mouseDownX||0,k=this.mouseDownY|| +0,r=D(h.panning)?h.panning&&h.panning.enabled:h.panning,z=h.panKey&&b[h.panKey+"Key"];if(!c||!c.touch)if(lv+t&&(l=v+t),gn+B&&(g=n+B),this.hasDragged=Math.sqrt(Math.pow(a-l,2)+Math.pow(k-g,2)),10b.options.findNearestPointBy.indexOf("y");b=b.searchPoint(g,l);if((l=D(b,!0))&&!(l=!D(d,!0))){l=d.distX-b.distX;var h=d.dist-b.dist,p=(b.series.group&& +b.series.group.zIndex)-(d.series.group&&d.series.group.zIndex);l=0<(0!==l&&e?l:0!==h?h:0!==p?p:d.series.index>b.series.index?-1:1)}l&&(d=b)});return d};f.prototype.getChartCoordinatesFromPoint=function(b,e){var h=b.series,l=h.xAxis;h=h.yAxis;var g=t(b.clientX,b.plotX),d=b.shapeArgs;if(l&&h)return e?{chartX:l.len+l.pos-g,chartY:h.len+h.pos-b.plotY}:{chartX:g+l.pos,chartY:b.plotY+h.pos};if(d&&d.x&&d.y)return{chartX:d.x,chartY:d.y}};f.prototype.getChartPosition=function(){return this.chartPosition|| +(this.chartPosition=n(this.chart.container))};f.prototype.getCoordinates=function(b){var e={xAxis:[],yAxis:[]};this.chart.axes.forEach(function(h){e[h.isXAxis?"xAxis":"yAxis"].push({axis:h,value:h.toValue(b[h.horiz?"chartX":"chartY"])})});return e};f.prototype.getHoverData=function(b,e,g,l,d,m){var h,p=[];l=!(!l||!b);var f=e&&!e.stickyTracking,u={chartX:m?m.chartX:void 0,chartY:m?m.chartY:void 0,shared:d};H(this,"beforeGetHoverData",u);f=f?[e]:g.filter(function(e){return u.filter?u.filter(e):e.visible&& +!(!d&&e.directTouch)&&t(e.options.enableMouseTracking,!0)&&e.stickyTracking});e=(h=l||!m?b:this.findNearestKDPoint(f,d,m))&&h.series;h&&(d&&!e.noSharedTooltip?(f=g.filter(function(e){return u.filter?u.filter(e):e.visible&&!(!d&&e.directTouch)&&t(e.options.enableMouseTracking,!0)&&!e.noSharedTooltip}),f.forEach(function(e){var c=F(e.points,function(a){return a.x===h.x&&!a.isNull});D(c)&&(e.chart.isBoosting&&(c=e.getPoint(c)),p.push(c))})):p.push(h));u={hoverPoint:h};H(this,"afterGetHoverData",u);return{hoverPoint:u.hoverPoint, +hoverSeries:e,hoverPoints:p}};f.prototype.getPointFromEvent=function(b){b=b.target;for(var e;b&&!e;)e=b.point,b=b.parentNode;return e};f.prototype.onTrackerMouseOut=function(b){b=b.relatedTarget||b.toElement;var e=this.chart.hoverSeries;this.isDirectTouch=!1;if(!(!e||!b||e.stickyTracking||this.inClass(b,"highcharts-tooltip")||this.inClass(b,"highcharts-series-"+e.index)&&this.inClass(b,"highcharts-tracker")))e.onMouseOut()};f.prototype.inClass=function(b,e){for(var g;b;){if(g=K(b,"class")){if(-1!== +g.indexOf(e))return!0;if(-1!==g.indexOf("highcharts-container"))return!1}b=b.parentNode}};f.prototype.init=function(b,e){this.options=e;this.chart=b;this.runChartClick=e.chart.events&&!!e.chart.events.click;this.pinchDown=[];this.lastValidTouch={};E&&(b.tooltip=new E(b,e.tooltip),this.followTouchMove=t(e.tooltip.followTouchMove,!0));this.setDOMEvents()};f.prototype.normalize=function(b,e){var g=b.touches,l=g?g.length?g.item(0):g.changedTouches[0]:b;e||(e=this.getChartPosition());g=l.pageX-e.left; +e=l.pageY-e.top;if(l=this.chart.containerScaling)g/=l.scaleX,e/=l.scaleY;return x(b,{chartX:Math.round(g),chartY:Math.round(e)})};f.prototype.onContainerClick=function(b){var e=this.chart,g=e.hoverPoint;b=this.normalize(b);var l=e.plotLeft,h=e.plotTop;e.cancelClick||(g&&this.inClass(b.target,"highcharts-tracker")?(H(g.series,"click",x(b,{point:g})),e.hoverPoint&&g.firePointEvent("click",b)):(x(b,this.getCoordinates(b)),e.isInsidePlot(b.chartX-l,b.chartY-h)&&H(e,"click",b)))};f.prototype.onContainerMouseDown= +function(b){b=this.normalize(b);if(d.isFirefox&&0!==b.button)this.onContainerMouseMove(b);if("undefined"===typeof b.button||1===((b.buttons||b.button)&1))this.zoomOption(b),this.dragStart(b)};f.prototype.onContainerMouseLeave=function(g){var e=b[t(d.hoverChartIndex,-1)],h=this.chart.tooltip;g=this.normalize(g);e&&(g.relatedTarget||g.toElement)&&(e.pointer.reset(),e.pointer.chartPosition=void 0);h&&!h.isHidden&&this.reset()};f.prototype.onContainerMouseMove=function(b){var e=this.chart;b=this.normalize(b); +this.setHoverChartIndex();b.preventDefault||(b.returnValue=!1);"mousedown"===e.mouseIsDown&&this.drag(b);e.openMenu||!this.inClass(b.target,"highcharts-tracker")&&!e.isInsidePlot(b.chartX-e.plotLeft,b.chartY-e.plotTop)||this.runPointActions(b)};f.prototype.onDocumentTouchEnd=function(g){b[d.hoverChartIndex]&&b[d.hoverChartIndex].pointer.drop(g)};f.prototype.onContainerTouchMove=function(b){this.touch(b)};f.prototype.onContainerTouchStart=function(b){this.zoomOption(b);this.touch(b,!0)};f.prototype.onDocumentMouseMove= +function(b){var e=this.chart,g=this.chartPosition;b=this.normalize(b,g);var l=e.tooltip;!g||l&&l.isStickyOnContact()||e.isInsidePlot(b.chartX-e.plotLeft,b.chartY-e.plotTop)||this.inClass(b.target,"highcharts-tracker")||this.reset()};f.prototype.onDocumentMouseUp=function(g){var e=b[t(d.hoverChartIndex,-1)];e&&e.pointer.drop(g)};f.prototype.pinch=function(b){var e=this,h=e.chart,l=e.pinchDown,d=b.touches||[],m=d.length,f=e.lastValidTouch,v=e.hasZoom,n=e.selectionMarker,w={},B=1===m&&(e.inClass(b.target, +"highcharts-tracker")&&h.runTrackerClick||e.runChartClick),c={};1G.max&&(e=G.max-r,V=!0);V?(I-=.8*(I-f[p][0]),"number"===typeof O&&(O-=.8*(O-f[p][1])),g()):f[p]=[I,O];n||(m[p]=z-k,m[a]=r);m=n?1/y:y;d[a]=r;d[p]=e;l[n?b?"scaleY":"scaleX":"scale"+u]=y;l["translate"+u]=m*k+(I-m*w)};f.prototype.reset=function(b,e){var g=this.chart,l=g.hoverSeries,d=g.hoverPoint,h=g.hoverPoints,m=g.tooltip,f=m&&m.shared?h:d;b&&f&&N(f).forEach(function(e){e.series.isCartesian&&"undefined"===typeof e.plotX&&(b=!1)});if(b)m&&f&&N(f).length&&(m.refresh(f),m.shared&&h?h.forEach(function(e){e.setState(e.state, +!0);e.series.isCartesian&&(e.series.xAxis.crosshair&&e.series.xAxis.drawCrosshair(null,e),e.series.yAxis.crosshair&&e.series.yAxis.drawCrosshair(null,e))}):d&&(d.setState(d.state,!0),g.axes.forEach(function(e){e.crosshair&&d.series[e.coll]===e&&e.drawCrosshair(null,d)})));else{if(d)d.onMouseOut();h&&h.forEach(function(e){e.setState()});if(l)l.onMouseOut();m&&m.hide(e);this.unDocMouseMove&&(this.unDocMouseMove=this.unDocMouseMove());g.axes.forEach(function(e){e.hideCrosshair()});this.hoverX=g.hoverPoints= +g.hoverPoint=null}};f.prototype.runPointActions=function(g,e){var h=this.chart,l=h.tooltip&&h.tooltip.options.enabled?h.tooltip:void 0,m=l?l.shared:!1,f=e||h.hoverPoint,y=f&&f.series||h.hoverSeries;y=this.getHoverData(f,y,h.series,(!g||"touchmove"!==g.type)&&(!!e||y&&y.directTouch&&this.isDirectTouch),m,g);f=y.hoverPoint;var v=y.hoverPoints;e=(y=y.hoverSeries)&&y.tooltipOptions.followPointer;m=m&&y&&!y.noSharedTooltip;if(f&&(f!==h.hoverPoint||l&&l.isHidden)){(h.hoverPoints||[]).forEach(function(e){-1=== +v.indexOf(e)&&e.setState()});if(h.hoverSeries!==y)y.onMouseOver();this.applyInactiveState(v);(v||[]).forEach(function(e){e.setState("hover")});h.hoverPoint&&h.hoverPoint.firePointEvent("mouseOut");if(!f.series)return;f.firePointEvent("mouseOver");h.hoverPoints=v;h.hoverPoint=f;l&&l.refresh(m?v:f,g)}else e&&l&&!l.isHidden&&(f=l.getAnchor([{}],g),l.updatePosition({plotX:f[0],plotY:f[1]}));this.unDocMouseMove||(this.unDocMouseMove=M(h.container.ownerDocument,"mousemove",function(e){var l=b[d.hoverChartIndex]; +if(l)l.pointer.onDocumentMouseMove(e)}));h.axes.forEach(function(e){var b=t((e.crosshair||{}).snap,!0),l;b&&((l=h.hoverPoint)&&l.series[e.coll]===e||(l=F(v,function(c){return c.series[e.coll]===e})));l||!b?e.drawCrosshair(g,l):e.hideCrosshair()})};f.prototype.scaleGroups=function(b,e){var g=this.chart,l;g.series.forEach(function(d){l=b||d.getPlotBox();d.xAxis&&d.xAxis.zoomEnabled&&d.group&&(d.group.attr(l),d.markerGroup&&(d.markerGroup.attr(l),d.markerGroup.clip(e?g.clipRect:null)),d.dataLabelsGroup&& +d.dataLabelsGroup.attr(l))});g.clipRect.attr(e||g.clipBox)};f.prototype.setDOMEvents=function(){var b=this.chart.container,e=b.ownerDocument;b.onmousedown=this.onContainerMouseDown.bind(this);b.onmousemove=this.onContainerMouseMove.bind(this);b.onclick=this.onContainerClick.bind(this);this.unbindContainerMouseLeave=M(b,"mouseleave",this.onContainerMouseLeave.bind(this));d.unbindDocumentMouseUp||(d.unbindDocumentMouseUp=M(e,"mouseup",this.onDocumentMouseUp.bind(this)));d.hasTouch&&(M(b,"touchstart", +this.onContainerTouchStart.bind(this)),M(b,"touchmove",this.onContainerTouchMove.bind(this)),d.unbindDocumentTouchEnd||(d.unbindDocumentTouchEnd=M(e,"touchend",this.onDocumentTouchEnd.bind(this))))};f.prototype.setHoverChartIndex=function(){var b=this.chart,e=d.charts[t(d.hoverChartIndex,-1)];if(e&&e!==b)e.pointer.onContainerMouseLeave({relatedTarget:!0});e&&e.mouseIsDown||(d.hoverChartIndex=b.index)};f.prototype.touch=function(b,e){var g=this.chart,l;this.setHoverChartIndex();if(1===b.touches.length)if(b= +this.normalize(b),(l=g.isInsidePlot(b.chartX-g.plotLeft,b.chartY-g.plotTop))&&!g.openMenu){e&&this.runPointActions(b);if("touchmove"===b.type){e=this.pinchDown;var d=e[0]?4<=Math.sqrt(Math.pow(e[0].chartX-b.chartX,2)+Math.pow(e[0].chartY-b.chartY,2)):!1}t(d,!0)&&this.pinch(b)}else e&&this.reset();else 2===b.touches.length&&this.pinch(b)};f.prototype.zoomOption=function(b){var e=this.chart,g=e.options.chart,l=g.zoomType||"";e=e.inverted;/touch/.test(b.type)&&(l=t(g.pinchType,l));this.zoomX=b=/x/.test(l); +this.zoomY=l=/y/.test(l);this.zoomHor=b&&!e||l&&e;this.zoomVert=l&&!e||b&&e;this.hasZoom=b||l};return f}();d.Pointer=f;return d.Pointer});Q(A,"parts/MSPointer.js",[A["parts/Globals.js"],A["parts/Pointer.js"],A["parts/Utilities.js"]],function(d,f,E){function q(){var d=[];d.item=function(d){return this[d]};x(w,function(f){d.push({pageX:f.pageX,pageY:f.pageY,target:f.target})});return d}function M(f,n,m,b){"touch"!==f.pointerType&&f.pointerType!==f.MSPOINTER_TYPE_TOUCH||!H[d.hoverChartIndex]||(b(f), +b=H[d.hoverChartIndex].pointer,b[n]({type:m,target:f.currentTarget,preventDefault:D,touches:q()}))}var K=this&&this.__extends||function(){var d=function(f,m){d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,g){b.__proto__=g}||function(b,g){for(var d in g)g.hasOwnProperty(d)&&(b[d]=g[d])};return d(f,m)};return function(f,m){function b(){this.constructor=f}d(f,m);f.prototype=null===m?Object.create(m):(b.prototype=m.prototype,new b)}}(),J=E.addEvent,L=E.css,x=E.objectEach,F=E.removeEvent, +H=d.charts,C=d.doc,D=d.noop,w={},n=!!d.win.PointerEvent;return function(d){function f(){return null!==d&&d.apply(this,arguments)||this}K(f,d);f.prototype.batchMSEvents=function(d){d(this.chart.container,n?"pointerdown":"MSPointerDown",this.onContainerPointerDown);d(this.chart.container,n?"pointermove":"MSPointerMove",this.onContainerPointerMove);d(C,n?"pointerup":"MSPointerUp",this.onDocumentPointerUp)};f.prototype.destroy=function(){this.batchMSEvents(F);d.prototype.destroy.call(this)};f.prototype.init= +function(m,b){d.prototype.init.call(this,m,b);this.hasZoom&&L(m.container,{"-ms-touch-action":"none","touch-action":"none"})};f.prototype.onContainerPointerDown=function(d){M(d,"onContainerTouchStart","touchstart",function(b){w[b.pointerId]={pageX:b.pageX,pageY:b.pageY,target:b.currentTarget}})};f.prototype.onContainerPointerMove=function(d){M(d,"onContainerTouchMove","touchmove",function(b){w[b.pointerId]={pageX:b.pageX,pageY:b.pageY};w[b.pointerId].target||(w[b.pointerId].target=b.currentTarget)})}; +f.prototype.onDocumentPointerUp=function(d){M(d,"onDocumentTouchEnd","touchend",function(b){delete w[b.pointerId]})};f.prototype.setDOMEvents=function(){d.prototype.setDOMEvents.call(this);(this.hasZoom||this.followTouchMove)&&this.batchMSEvents(J)};return f}(f)});Q(A,"parts/Legend.js",[A["parts/Globals.js"],A["parts/Utilities.js"]],function(d,f){var E=f.addEvent,q=f.animObject,M=f.css,K=f.defined,J=f.discardElement,L=f.find,x=f.fireEvent,F=f.format,H=f.isNumber,C=f.merge,D=f.pick,w=f.relativeLength, +n=f.setAnimation,t=f.stableSort,N=f.syncTimeout;f=f.wrap;var m=d.isFirefox,b=d.marginNames,g=d.win,v=function(){function g(e,b){this.allItems=[];this.contentGroup=this.box=void 0;this.display=!1;this.group=void 0;this.offsetWidth=this.maxLegendWidth=this.maxItemWidth=this.legendWidth=this.legendHeight=this.lastLineHeight=this.lastItemY=this.itemY=this.itemX=this.itemMarginTop=this.itemMarginBottom=this.itemHeight=this.initialItemY=0;this.options={};this.padding=0;this.pages=[];this.proximate=!1;this.scrollGroup= +void 0;this.widthOption=this.totalItemWidth=this.titleHeight=this.symbolWidth=this.symbolHeight=0;this.chart=e;this.init(e,b)}g.prototype.init=function(e,b){this.chart=e;this.setOptions(b);b.enabled&&(this.render(),E(this.chart,"endResize",function(){this.legend.positionCheckboxes()}),this.proximate?this.unchartrender=E(this.chart,"render",function(){this.legend.proximatePositions();this.legend.positionItems()}):this.unchartrender&&this.unchartrender())};g.prototype.setOptions=function(e){var b=D(e.padding, +8);this.options=e;this.chart.styledMode||(this.itemStyle=e.itemStyle,this.itemHiddenStyle=C(this.itemStyle,e.itemHiddenStyle));this.itemMarginTop=e.itemMarginTop||0;this.itemMarginBottom=e.itemMarginBottom||0;this.padding=b;this.initialItemY=b-5;this.symbolWidth=D(e.symbolWidth,16);this.pages=[];this.proximate="proximate"===e.layout&&!this.chart.inverted;this.baseline=void 0};g.prototype.update=function(e,b){var g=this.chart;this.setOptions(C(!0,this.options,e));this.destroy();g.isDirtyLegend=g.isDirtyBox= +!0;D(b,!0)&&g.redraw();x(this,"afterUpdate")};g.prototype.colorizeItem=function(e,b){e.legendGroup[b?"removeClass":"addClass"]("highcharts-legend-item-hidden");if(!this.chart.styledMode){var g=this.options,d=e.legendItem,h=e.legendLine,m=e.legendSymbol,f=this.itemHiddenStyle.color;g=b?g.itemStyle.color:f;var p=b?e.color||f:f,v=e.options&&e.options.marker,n={fill:p};d&&d.css({fill:g,color:g});h&&h.attr({stroke:p});m&&(v&&m.isMarker&&(n=e.pointAttribs(),b||(n.stroke=n.fill=f)),m.attr(n))}x(this,"afterColorizeItem", +{item:e,visible:b})};g.prototype.positionItems=function(){this.allItems.forEach(this.positionItem,this);this.chart.isResizing||this.positionCheckboxes()};g.prototype.positionItem=function(e){var b=this.options,g=b.symbolPadding;b=!b.rtl;var d=e._legendItemPos,h=d[0];d=d[1];var m=e.checkbox;if((e=e.legendGroup)&&e.element)e[K(e.translateY)?"animate":"attr"]({translateX:b?h:this.legendWidth-h-2*g-4,translateY:d});m&&(m.x=h,m.y=d)};g.prototype.destroyItem=function(e){var b=e.checkbox;["legendItem","legendLine", +"legendSymbol","legendGroup"].forEach(function(b){e[b]&&(e[b]=e[b].destroy())});b&&J(e.checkbox)};g.prototype.destroy=function(){function b(b){this[b]&&(this[b]=this[b].destroy())}this.getAllItems().forEach(function(e){["legendItem","legendGroup"].forEach(b,e)});"clipRect up down pager nav box title group".split(" ").forEach(b,this);this.display=null};g.prototype.positionCheckboxes=function(){var b=this.group&&this.group.alignAttr,g=this.clipHeight||this.legendHeight,l=this.titleHeight;if(b){var d= +b.translateY;this.allItems.forEach(function(e){var h=e.checkbox;if(h){var m=d+l+h.y+(this.scrollOffset||0)+3;M(h,{left:b.translateX+e.checkboxOffset+h.x-20+"px",top:m+"px",display:this.proximate||m>d-6&&mn?this.maxItemWidth:b.itemWidth;d&&this.itemX-g+e>n&&(this.itemX=g,this.lastLineHeight&&(this.itemY+=f+this.lastLineHeight+m),this.lastLineHeight=0);this.lastItemY=f+this.itemY+m;this.lastLineHeight=Math.max(h,this.lastLineHeight);b._legendItemPos=[this.itemX,this.itemY];d?this.itemX+=e:(this.itemY+=f+h+m,this.lastLineHeight=h);this.offsetWidth=this.widthOption||Math.max((d?this.itemX-g-(b.checkbox?0:v):e)+g,this.offsetWidth)};g.prototype.getAllItems= +function(){var b=[];this.chart.series.forEach(function(e){var g=e&&e.options;e&&D(g.showInLegend,K(g.linkedTo)?!1:void 0,!0)&&(b=b.concat(e.legendItems||("point"===g.legendType?e.data:e)))});x(this,"afterGetAllItems",{allItems:b});return b};g.prototype.getAlignment=function(){var b=this.options;return this.proximate?b.align.charAt(0)+"tv":b.floating?"":b.align.charAt(0)+b.verticalAlign.charAt(0)+b.layout.charAt(0)};g.prototype.adjustMargins=function(e,g){var l=this.chart,d=this.options,h=this.getAlignment(); +h&&[/(lth|ct|rth)/,/(rtv|rm|rbv)/,/(rbh|cb|lbh)/,/(lbv|lm|ltv)/].forEach(function(m,f){m.test(h)&&!K(e[f])&&(l[b[f]]=Math.max(l[b[f]],l.legend[(f+1)%2?"legendHeight":"legendWidth"]+[1,-1,-1,1][f]*d[f%2?"x":"y"]+D(d.margin,12)+g[f]+(l.titleOffset[f]||0)))})};g.prototype.proximatePositions=function(){var b=this.chart,g=[],l="left"===this.options.align;this.allItems.forEach(function(e){var d=l;if(e.yAxis&&e.points){e.xAxis.options.reversed&&(d=!d);var h=L(d?e.points:e.points.slice(0).reverse(),function(b){return H(b.plotY)}); +d=this.itemMarginTop+e.legendItem.getBBox().height+this.itemMarginBottom;var m=e.yAxis.top-b.plotTop;e.visible?(h=h?h.plotY:e.yAxis.height,h+=m-.3*d):h=m+e.yAxis.height;g.push({target:h,size:d,item:e})}},this);d.distribute(g,b.plotHeight);g.forEach(function(e){e.item._legendItemPos[1]=b.plotTop-b.spacing[0]+e.pos})};g.prototype.render=function(){var b=this.chart,g=b.renderer,l=this.group,d=this.box,h=this.options,m=this.padding;this.itemX=m;this.itemY=this.initialItemY;this.lastItemY=this.offsetWidth= +0;this.widthOption=w(h.width,b.spacingBox.width-m);var f=b.spacingBox.width-2*m-h.x;-1<["rm","lm"].indexOf(this.getAlignment().substring(0,2))&&(f/=2);this.maxLegendWidth=this.widthOption||f;l||(this.group=l=g.g("legend").attr({zIndex:7}).add(),this.contentGroup=g.g().attr({zIndex:1}).add(l),this.scrollGroup=g.g().add(this.contentGroup));this.renderTitle();var v=this.getAllItems();t(v,function(b,c){return(b.options&&b.options.legendIndex||0)-(c.options&&c.options.legendIndex||0)});h.reversed&&v.reverse(); +this.allItems=v;this.display=f=!!v.length;this.itemHeight=this.totalItemWidth=this.maxItemWidth=this.lastLineHeight=0;v.forEach(this.renderItem,this);v.forEach(this.layoutItem,this);v=(this.widthOption||this.offsetWidth)+m;var n=this.lastItemY+this.lastLineHeight+this.titleHeight;n=this.handleOverflow(n);n+=m;d||(this.box=d=g.rect().addClass("highcharts-legend-box").attr({r:h.borderRadius}).add(l),d.isNew=!0);b.styledMode||d.attr({stroke:h.borderColor,"stroke-width":h.borderWidth||0,fill:h.backgroundColor|| +"none"}).shadow(h.shadow);0m&&!1!==c.enabled?(this.clipHeight= +n=Math.max(m-20-this.titleHeight-f,0),this.currentPage=D(this.currentPage,1),this.fullHeight=b,x.forEach(function(a,c){var b=a._legendItemPos[1],e=Math.round(a.legendItem.getBBox().height),k=z.length;if(!k||b-z[k-1]>n&&(t||b)!==z[k-1])z.push(t||b),k++;a.pageIx=k-1;t&&(x[c-1].pageIx=k-1);c===x.length-1&&b+e-z[k-1]>n&&b!==t&&(z.push(b),a.pageIx=k);b!==t&&(t=b)}),w||(w=e.clipRect=d.clipRect(0,f,9999,0),e.contentGroup.clip(w)),q(n),r||(this.nav=r=d.g().attr({zIndex:1}).add(this.group),this.up=d.symbol("triangle", +0,0,k,k).add(r),C("upTracker").on("click",function(){e.scroll(-1,a)}),this.pager=d.text("",15,10).addClass("highcharts-legend-navigation"),g.styledMode||this.pager.css(c.style),this.pager.add(r),this.down=d.symbol("triangle-down",0,0,k,k).add(r),C("downTracker").on("click",function(){e.scroll(1,a)})),e.scroll(0),b=m):r&&(q(),this.nav=r.destroy(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0);return b};g.prototype.scroll=function(b,g){var e=this,d=this.chart,h=this.pages,m=h.length,f=this.currentPage+ +b;b=this.clipHeight;var p=this.options.navigation,v=this.pager,w=this.padding;f>m&&(f=m);0=f.value;)f=b[++g];this.nonZonedColor||(this.nonZonedColor=this.color);this.color=f&&f.color&&!this.options.color?f.color:this.nonZonedColor;return f};d.prototype.hasNewShapeType=function(){return(this.graphic&&(this.graphic.symbolName||this.graphic.element.nodeName))!==this.shapeType};d.prototype.init=function(d,b,g){this.series=d;this.applyOptions(b,g);this.id=q(this.id)?this.id:t();this.resolveColor();d.chart.pointCount++;J(this,"afterInit");return this};d.prototype.optionsToObject= +function(f){var b={},g=this.series,m=g.options.keys,h=m||g.pointArrayMap||["y"],e=h.length,p=0,l=0;if(H(f)||null===f)b[h[0]]=f;else if(F(f))for(!m&&f.length>e&&(g=typeof f[0],"string"===g?b.name=f[0]:"number"===g&&(b.x=f[0]),p++);l=p(a[b].options.index,a[b]._i)){a.splice(b+1,0,this);break}-1===b&&a.unshift(this);b+=1}else a.push(this);return p(b,a.length-1)},bindAxes:function(){var a=this,c=a.options,b=a.chart,e;t(this,"bindAxes",null,function(){(a.axisTypes||[]).forEach(function(d){b[d].forEach(function(b){e=b.options;if(c[d]===e.index||"undefined"!==typeof c[d]&&c[d]===e.id||"undefined"===typeof c[d]&&0===e.index)a.insert(b.series), +a[d]=b,b.isDirty=!0});a[d]||a.optionalAxis===d||D(18,!0,b)})});t(this,"afterBindAxes")},updateParallelArrays:function(a,c){var b=a.series,e=arguments,d=g(c)?function(e){var d="y"===e&&b.toYData?b.toYData(a):a[e];b[e+"Data"][c]=d}:function(a){Array.prototype[c].apply(b[a+"Data"],Array.prototype.slice.call(e,2))};b.parallelArrays.forEach(d)},hasData:function(){return this.visible&&"undefined"!==typeof this.dataMax&&"undefined"!==typeof this.dataMin||this.visible&&this.yData&&0=this.cropStart?m-this.cropStart:m);!k&&d[m]&&d[m].touched&&(m=void 0);return m},drawLegendSymbol:d.drawLineMarker,updateData:function(a,c){var b=this.options,e=b.dataSorting,d=this.points,k=[],l,f,h,m=this.requireSorting,u=a.length===d.length, +p=!0;this.xIncrement=null;a.forEach(function(a,c){var f=H(a)&&this.pointClass.prototype.optionsToObject.call({series:this},a)||{};var r=f.x;if(f.id||g(r)){if(r=this.findPointIndex(f,h),-1===r||"undefined"===typeof r?k.push(a):d[r]&&a!==b.data[r]?(d[r].update(a,!1,null,!1),d[r].touched=!0,m&&(h=r+1)):d[r]&&(d[r].touched=!0),!u||c!==r||e&&e.enabled||this.hasDerivedData)l=!0}else k.push(a)},this);if(l)for(a=d.length;a--;)(f=d[a])&&!f.touched&&f.remove&&f.remove(!1,c);else!u||e&&e.enabled?p=!1:(a.forEach(function(a, +c){d[c].update&&a!==d[c].y&&d[c].update(a,!1,null,!1)}),k.length=0);d.forEach(function(a){a&&(a.touched=!1)});if(!p)return!1;k.forEach(function(a){this.addPoint(a,!1,null,null,!1)},this);null===this.xIncrement&&this.xData&&this.xData.length&&(this.xIncrement=J(this.xData),this.autoIncrement());return!0},setData:function(a,c,b,e){var d=this,k=d.points,l=k&&k.length||0,f,h=d.options,r=d.chart,u=h.dataSorting,n=null,z=d.xAxis;n=h.turboThreshold;var y=this.xData,w=this.yData,t=(f=d.pointArrayMap)&&f.length, +B=h.keys,G=0,q=1,x;a=a||[];f=a.length;c=p(c,!0);u&&u.enabled&&(a=this.sortData(a));!1!==e&&f&&l&&!d.cropped&&!d.hasGroupedData&&d.visible&&!d.isSeriesBoosting&&(x=this.updateData(a,b));if(!x){d.xIncrement=null;d.colorCounter=0;this.parallelArrays.forEach(function(a){d[a+"Data"].length=0});if(n&&f>n)if(n=d.getFirstValidPoint(a),g(n))for(b=0;ba?1:0}).forEach(function(a,c){a.x=c},this);c.linkedSeries&&c.linkedSeries.forEach(function(c){var b=c.options,d=b.data;b.dataSorting&&b.dataSorting.enabled||!d||(d.forEach(function(b,k){d[k]=e(c,b);a[k]&&(d[k].x=a[k].x,d[k].index= +k)}),c.setData(d,!1))});return a},getProcessedData:function(a){var c=this.xData,b=this.yData,e=c.length;var d=0;var g=this.xAxis,f=this.options;var l=f.cropThreshold;var h=a||this.getExtremesFromAll||f.getExtremesFromAll,m=this.isCartesian;a=g&&g.val2lin;f=!(!g||!g.logarithmic);var u=this.requireSorting;if(g){g=g.getExtremes();var p=g.min;var n=g.max}if(m&&this.sorted&&!h&&(!l||e>l||this.forceCrop))if(c[e-1]n)c=[],b=[];else if(this.yData&&(c[0]n)){d=this.cropData(this.xData,this.yData, +p,n);c=d.xData;b=d.yData;d=d.start;var v=!0}for(l=c.length||1;--l;)if(e=f?a(c[l])-a(c[l-1]):c[l]-c[l-1],0e&&u&&(D(15,!1,this.chart),u=!1);return{xData:c,yData:b,cropped:v,cropStart:d,closestPointRange:y}},processData:function(a){var c=this.xAxis;if(this.isCartesian&&!this.isDirty&&!c.isDirty&&!this.yAxis.isDirty&&!a)return!1;a=this.getProcessedData();this.cropped=a.cropped;this.cropStart=a.cropStart;this.processedXData=a.xData;this.processedYData=a.yData; +this.closestPointRange=this.basePointRange=a.closestPointRange},cropData:function(a,c,b,e,d){var g=a.length,k=0,l=g,f;d=p(d,this.cropShoulder);for(f=0;f=b){k=Math.max(0,f-d);break}for(b=f;be){l=b+d;break}return{xData:a.slice(k,l),yData:c.slice(k,l),start:k,end:l}},generatePoints:function(){var a=this.options,c=a.data,b=this.data,e,d=this.processedXData,g=this.processedYData,f=this.pointClass,l=d.length,h=this.cropStart||0,m=this.hasGroupedData;a=a.keys;var p=[],n;b|| +m||(b=[],b.length=c.length,b=this.data=b);a&&m&&(this.options.keys=!1);for(n=0;n=f&&(d[p-u]||v)<=h;if(w&&v)if(w=y.length)for(;w--;)g(y[w])&&(k[l++]=y[w]);else k[l++]=y}a={dataMin:L(k),dataMax:J(k)};t(this,"afterGetExtremes",{dataExtremes:a});return a},applyExtremes:function(){var a=this.getExtremes();this.dataMin=a.dataMin;this.dataMax=a.dataMax;return a},getFirstValidPoint:function(a){for(var c=null,b=a.length,e=0;null===c&&e=R&&(C.isNull=!0);C.plotX=G=F(x(b.translate(D,0,0,0,1,v,"flags"=== +this.type),-1E5,1E5));if(c&&this.visible&&A&&A[D]){var E=this.getStackIndicator(E,D,this.index);if(!C.isNull){var N=A[D];var L=N.points[E.key]}}m(L)&&(S=L[0],R=L[1],S===B&&E.key===A[D].base&&(S=p(g(w)&&w,l.min)),l.positiveValuesOnly&&0>=S&&(S=null),C.total=C.stackTotal=N.total,C.percentage=N.total&&C.y/N.total*100,C.stackY=R,this.irregularWidths||N.setOffset(this.pointXOffset||0,this.barW||0));C.yBottom=H(S)?x(l.translate(S,0,1,0,1),-1E5,1E5):null;u&&(R=this.modifyValue(R,C));C.plotY="number"===typeof R&& +Infinity!==R?x(l.translate(R,0,1,0,1),-1E5,1E5):void 0;C.isInside=this.isPointInside(C);C.clientX=y?F(b.translate(D,0,0,0,1,v)):G;C.negative=C[q]<(a[q+"Threshold"]||w||0);C.category=e&&"undefined"!==typeof e[C.x]?e[C.x]:C.x;if(!C.isNull&&!1!==C.visible){"undefined"!==typeof J&&(I=Math.min(I,Math.abs(G-J)));var J=G}C.zone=this.zones.length&&C.getZone();!C.graphic&&this.group&&d&&(C.isNew=!0)}this.closestPointRangePx=I;t(this,"afterTranslate")},getValidPoints:function(a,c,b){var e=this.chart;return(a|| +this.points||[]).filter(function(a){return c&&!e.isInsidePlot(a.plotX,a.plotY,e.inverted)?!1:!1!==a.visible&&(b||!a.isNull)})},getClipBox:function(a,c){var b=this.options,e=this.chart,d=e.inverted,g=this.xAxis,k=g&&this.yAxis;a&&!1===b.clip&&k?a=d?{y:-e.chartWidth+k.len+k.pos,height:e.chartWidth,width:e.chartHeight,x:-e.chartHeight+g.len+g.pos}:{y:-k.pos,height:e.chartHeight,width:e.chartWidth,x:-g.pos}:(a=this.clipBox||e.clipBox,c&&(a.width=e.plotSizeX,a.x=0));return c?{width:a.width,x:a.x}:a},setClip:function(a){var c= +this.chart,b=this.options,e=c.renderer,d=c.inverted,g=this.clipBox,l=this.getClipBox(a),f=this.sharedClipKey||["_sharedClip",a&&a.duration,a&&a.easing,l.height,b.xAxis,b.yAxis].join(),h=c[f],m=c[f+"m"];a&&(l.width=0,d&&(l.x=c.plotHeight+(!1!==b.clip?0:c.plotTop)));h?c.hasLoaded||h.attr(l):(a&&(c[f+"m"]=m=e.clipRect(d?c.plotSizeX+99:-99,d?-c.plotLeft:-c.plotTop,99,d?c.chartWidth:c.chartHeight)),c[f]=h=e.clipRect(l),h.count={length:0});a&&!h.count[this.index]&&(h.count[this.index]=!0,h.count.length+= +1);if(!1!==b.clip||a)this.group.clip(a||g?h:c.clipRect),this.markerGroup.clip(m),this.sharedClipKey=f;a||(h.count[this.index]&&(delete h.count[this.index],--h.count.length),0===h.count.length&&f&&c[f]&&(g||(c[f]=c[f].destroy()),c[f+"m"]&&(c[f+"m"]=c[f+"m"].destroy())))},animate:function(a){var c=this.chart,b=K(this.options.animation);if(!c.hasRendered)if(a)this.setClip(b);else{var e=this.sharedClipKey;a=c[e];var d=this.getClipBox(b,!0);a&&a.animate(d,b);c[e+"m"]&&c[e+"m"].animate({width:d.width+99, +x:d.x-(c.inverted?0:99)},b)}},afterAnimate:function(){this.setClip();t(this,"afterAnimate");this.finishedAnimating=!0},drawPoints:function(){var a=this.points,c=this.chart,b,e,d=this.options.marker,g=this[this.specialGroup]||this.markerGroup,f=this.xAxis,l=p(d.enabled,!f||f.isRadial?!0:null,this.closestPointRangePx>=d.enabledThreshold*d.radius);if(!1!==d.enabled||this._hasPointMarkers)for(b=0;bg&&c.shadow));f&&(f.startX=b.xMap,f.isArea=b.isArea)})},getZonesGraphs:function(a){this.zones.forEach(function(c, +b){b=["zone-graph-"+b,"highcharts-graph highcharts-zone-graph-"+b+" "+(c.className||"")];this.chart.styledMode||b.push(c.color||this.color,c.dashStyle||this.options.dashStyle);a.push(b)},this);return a},applyZones:function(){var a=this,c=this.chart,b=c.renderer,e=this.zones,d,g,f=this.clips||[],l,h=this.graph,m=this.area,u=Math.max(c.chartWidth,c.chartHeight),n=this[(this.zoneAxis||"y")+"Axis"],v=c.inverted,y,w,t,B=!1,G,q;if(e.length&&(h||m)&&n&&"undefined"!==typeof n.min){var C=n.reversed;var I= +n.horiz;h&&!this.showLine&&h.hide();m&&m.hide();var D=n.getExtremes();e.forEach(function(e,k){d=C?I?c.plotWidth:0:I?0:n.toPixels(D.min)||0;d=x(p(g,d),0,u);g=x(Math.round(n.toPixels(p(e.value,D.max),!0)||0),0,u);B&&(d=g=n.toPixels(D.max));y=Math.abs(d-g);w=Math.min(d,g);t=Math.max(d,g);n.isXAxis?(l={x:v?t:w,y:0,width:y,height:u},I||(l.x=c.plotHeight-l.x)):(l={x:0,y:v?t:w,width:u,height:y},I&&(l.y=c.plotWidth-l.y));v&&b.isVML&&(l=n.isXAxis?{x:0,y:C?w:t,height:l.width,width:c.chartWidth}:{x:l.y-c.plotLeft- +c.spacingBox.x,y:0,width:l.height,height:c.chartHeight});f[k]?f[k].animate(l):f[k]=b.clipRect(l);G=a["zone-area-"+k];q=a["zone-graph-"+k];h&&q&&q.clip(f[k]);m&&G&&G.clip(f[k]);B=e.value>D.max;a.resetZones&&0===g&&(g=void 0)});this.clips=f}else a.visible&&(h&&h.show(!0),m&&m.show(!0))},invertGroups:function(a){function c(){["group","markerGroup"].forEach(function(c){b[c]&&(e.renderer.isVML&&b[c].attr({width:b.yAxis.len,height:b.xAxis.len}),b[c].width=b.yAxis.len,b[c].height=b.xAxis.len,b[c].invert(b.isRadialSeries? +!1:a))})}var b=this,e=b.chart;b.xAxis&&(b.eventsToUnbind.push(E(e,"resize",c)),c(),b.invertGroups=c)},plotGroup:function(a,c,b,e,d){var g=this[a],k=!g;k&&(this[a]=g=this.chart.renderer.g().attr({zIndex:e||.1}).add(d));g.addClass("highcharts-"+c+" highcharts-series-"+this.index+" highcharts-"+this.type+"-series "+(H(this.colorIndex)?"highcharts-color-"+this.colorIndex+" ":"")+(this.options.className||"")+(g.hasClass("highcharts-tracker")?" highcharts-tracker":""),!0);g.attr({visibility:b})[k?"attr": +"animate"](this.getPlotBox());return g},getPlotBox:function(){var a=this.chart,c=this.xAxis,b=this.yAxis;a.inverted&&(c=b,b=this.xAxis);return{translateX:c?c.left:a.plotLeft,translateY:b?b.top:a.plotTop,scaleX:1,scaleY:1}},removeEvents:function(a){a?this.eventsToUnbind.length&&(this.eventsToUnbind.forEach(function(a){a()}),this.eventsToUnbind.length=0):l(this)},render:function(){var a=this,c=a.chart,b=a.options,e=!a.finishedAnimating&&c.renderer.isSVG&&K(b.animation).duration,d=a.visible?"inherit": +"hidden",g=b.zIndex,f=a.hasRendered,l=c.seriesGroup,h=c.inverted;t(this,"render");var m=a.plotGroup("group","series",d,g,l);a.markerGroup=a.plotGroup("markerGroup","markers",d,g,l);e&&a.animate&&a.animate(!0);m.inverted=a.isCartesian||a.invertable?h:!1;a.drawGraph&&(a.drawGraph(),a.applyZones());a.visible&&a.drawPoints();a.drawDataLabels&&a.drawDataLabels();a.redrawPoints&&a.redrawPoints();a.drawTracker&&!1!==a.options.enableMouseTracking&&a.drawTracker();a.invertGroups(h);!1===b.clip||a.sharedClipKey|| +f||m.clip(c.clipRect);e&&a.animate&&a.animate();f||(a.animationTimeout=y(function(){a.afterAnimate()},e||0));a.isDirty=!1;a.hasRendered=!0;t(a,"afterRender")},redraw:function(){var a=this.chart,c=this.isDirty||this.isDirtyData,b=this.group,e=this.xAxis,d=this.yAxis;b&&(a.inverted&&b.attr({width:a.plotWidth,height:a.plotHeight}),b.animate({translateX:p(e&&e.left,a.plotLeft),translateY:p(d&&d.top,a.plotTop)}));this.translate();this.render();c&&delete this.kdTree},kdAxisArray:["clientX","plotY"],searchPoint:function(a, +c){var b=this.xAxis,e=this.yAxis,d=this.chart.inverted;return this.searchKDTree({clientX:d?b.len-a.chartY+b.pos:a.chartX-b.pos,plotY:d?e.len-a.chartX+e.pos:a.chartY-e.pos},c,a)},buildKDTree:function(a){function c(a,e,d){var g;if(g=a&&a.length){var k=b.kdAxisArray[e%d];a.sort(function(a,c){return a[k]-c[k]});g=Math.floor(g/2);return{point:a[g],left:c(a.slice(0,g),e+1,d),right:c(a.slice(g+1),e+1,d)}}}this.buildingKdTree=!0;var b=this,e=-1m?"left":"right";n=0>m?"right":"left";c[p]&&(p=e(a,c[p],b+1, +l),u=p[f]v;)y--;this.updateParallelArrays(p,"splice",y,0,0);this.updateParallelArrays(p,y);k&&p.name&&(k[v]=p.name);m.splice(y,0,b);n&&(this.data.splice(y,0,null),this.processData());"point"===h.legendType&&this.generatePoints();d&&(c[0]&&c[0].remove?c[0].remove(!1):(c.shift(),this.updateParallelArrays(p,"shift"),m.shift()));!1!==l&&D(this,"addPoint",{point:p});this.isDirtyData=this.isDirty=!0;e&&a.redraw(f)},removePoint:function(b, +e,d){var f=this,l=f.data,m=l[b],c=f.points,a=f.chart,k=function(){c&&c.length===l.length&&c.splice(b,1);l.splice(b,1);f.options.data.splice(b,1);f.updateParallelArrays(m||{series:f},"splice",b,1);m&&m.destroy();f.isDirty=!0;f.isDirtyData=!0;e&&a.redraw()};h(d,a);e=g(e,!0);m?m.firePointEvent("remove",null,k):k()},remove:function(b,e,d,f){function l(){h.destroy(f);h.remove=null;c.isDirtyLegend=c.isDirtyBox=!0;c.linkSeries();g(b,!0)&&c.redraw(e)}var h=this,c=h.chart;!1!==d?D(h,"remove",null,l):l()}, +update:function(b,e){b=d.cleanRecursively(b,this.userOptions);D(this,"update",{options:b});var f=this,l=f.chart,h=f.userOptions,n=f.initialType||f.type,c=b.type||h.type||l.options.chart.type,a=!(this.hasDerivedData||b.dataGrouping||c&&c!==this.type||"undefined"!==typeof b.pointStart||b.pointInterval||b.pointIntervalUnit||b.keys),k=I[n].prototype,p,u=["group","markerGroup","dataLabelsGroup","transformGroup"],v=["eventOptions","navigatorSeries","baseSeries"],y=f.finishedAnimating&&{animation:!1},t= +{};a&&(v.push("data","isDirtyData","points","processedXData","processedYData","xIncrement","_hasPointMarkers","_hasPointLabels","mapMap","mapData","minY","maxY","minX","maxX"),!1!==b.visible&&v.push("area","graph"),f.parallelArrays.forEach(function(a){v.push(a+"Data")}),b.data&&(b.dataSorting&&C(f.options.dataSorting,b.dataSorting),this.setData(b.data,!1)));b=m(h,y,{index:"undefined"===typeof h.index?f.index:h.index,pointStart:g(h.pointStart,f.xData[0])},!a&&{data:f.options.data},b);a&&b.data&&(b.data= +f.options.data);v=u.concat(v);v.forEach(function(a){v[a]=f[a];delete f[a]});f.remove(!1,null,!1,!0);for(p in k)f[p]=void 0;I[c||n]?C(f,I[c||n].prototype):H(17,!0,l,{missingModuleFor:c||n});v.forEach(function(a){f[a]=v[a]});f.init(l,b);if(a&&this.points){var w=f.options;!1===w.visible?(t.graphic=1,t.dataLabel=1):f._hasPointLabels||(c=w.marker,k=w.dataLabels,c&&(!1===c.enabled||"symbol"in c)&&(t.graphic=1),k&&!1===k.enabled&&(t.dataLabel=1));this.points.forEach(function(a){a&&a.series&&(a.resolveColor(), +Object.keys(t).length&&a.destroyElements(t),!1===w.showInLegend&&a.legendItem&&l.legend.destroyItem(a))},this)}b.zIndex!==h.zIndex&&u.forEach(function(a){f[a]&&f[a].attr({zIndex:b.zIndex})});f.initialType=n;l.linkSeries();D(this,"afterUpdate");g(e,!0)&&l.redraw(a?void 0:!1)},setName:function(b){this.name=this.options.name=this.userOptions.name=b;this.chart.isDirtyLegend=!0}});C(p.prototype,{update:function(e,d){var f=this.chart,l=e&&e.events||{};e=m(this.userOptions,e);f.options[this.coll].indexOf&& +(f.options[this.coll][f.options[this.coll].indexOf(this.userOptions)]=e);b(f.options[this.coll].events,function(b,e){"undefined"===typeof l[e]&&(l[e]=void 0)});this.destroy(!0);this.init(f,C(e,{events:l}));f.isDirtyBox=!0;g(d,!0)&&f.redraw()},remove:function(b){for(var e=this.chart,d=this.coll,f=this.series,l=f.length;l--;)f[l]&&f[l].remove(!1);F(e.axes,this);F(e[d],this);w(e.options[d])?e.options[d].splice(this.options.index,1):delete e.options[d];e[d].forEach(function(b,c){b.options.index=b.userOptions.index= +c});this.destroy();e.isDirtyBox=!0;g(b,!0)&&e.redraw()},setTitle:function(b,e){this.update({title:b},e)},setCategories:function(b,e){this.update({categories:b},e)}})});Q(A,"parts/AreaSeries.js",[A["parts/Globals.js"],A["parts/Color.js"],A["mixins/legend-symbol.js"],A["parts/Utilities.js"]],function(d,f,A,q){var E=f.parse,K=q.objectEach,J=q.pick;f=q.seriesType;var L=d.Series;f("area","line",{softThreshold:!1,threshold:0},{singleStacks:!1,getStackPoints:function(d){var f=[],q=[],x=this.xAxis,D=this.yAxis, +w=D.stacking.stacks[this.stackKey],n={},t=this.index,A=D.series,m=A.length,b=J(D.options.reversedStacks,!0)?1:-1,g;d=d||this.points;if(this.options.stacking){for(g=0;gd&&C>J?(C=Math.max(d,J),D=2*J-C):CA&&D>J?(D=Math.max(A,J),C=2*J-D):D=Math.abs(f)&&.5d.closestPointRange*d.xAxis.transA;q=d.borderWidth=C(t.borderWidth,q?0:1);var m=d.xAxis,b=d.yAxis,g=t.threshold,v=d.translatedThreshold=b.getThreshold(g),h=C(t.minPointLength,5),e=d.getColumnMetrics(),p=e.width,l=d.barW=Math.max(p,1+2*q),I=d.pointXOffset=e.offset,u=d.dataMin, +y=d.dataMax;f.inverted&&(v-=.5);t.pointPadding&&(l=Math.ceil(l));D.prototype.translate.apply(d);d.points.forEach(function(e){var n=C(e.yBottom,v),t=999+Math.abs(n),q=p,c=e.plotX;t=J(e.plotY,-t,b.len+t);var a=e.plotX+I,k=l,r=Math.min(t,n),w=Math.max(t,n)-r;if(h&&Math.abs(w)h?n-h:v-(x?h:0)}L(e.options.pointWidth)&&(q=k=Math.ceil(e.options.pointWidth),a-=Math.round((q- +p)/2));e.barX=a;e.pointWidth=q;e.tooltipPos=f.inverted?[b.len+b.pos-f.plotLeft-t,m.len+m.pos-f.plotTop-(c||0)-I-k/2,w]:[a+k/2,t+b.pos-f.plotTop,w];e.shapeType=d.pointClass.prototype.shapeType||"rect";e.shapeArgs=d.crispCol.apply(d,e.isNull?[a,v,k,0]:[a,r,k,w])})},getSymbol:d.noop,drawLegendSymbol:A.drawRectangle,drawGraph:function(){this.group[this.dense?"addClass":"removeClass"]("highcharts-dense-data")},pointAttribs:function(d,f){var n=this.options,q=this.pointAttrToOptions||{};var m=q.stroke|| +"borderColor";var b=q["stroke-width"]||"borderWidth",g=d&&d.color||this.color,v=d&&d[m]||n[m]||this.color||g,h=d&&d[b]||n[b]||this[b]||0;q=d&&d.options.dashStyle||n.dashStyle;var e=C(d&&d.opacity,n.opacity,1);if(d&&this.zones.length){var p=d.getZone();g=d.options.color||p&&(p.color||d.nonZonedColor)||this.color;p&&(v=p.borderColor||v,q=p.dashStyle||q,h=p.borderWidth||h)}f&&d&&(d=H(n.states[f],d.options.states&&d.options.states[f]||{}),f=d.brightness,g=d.color||"undefined"!==typeof f&&E(g).brighten(d.brightness).get()|| +g,v=d[m]||v,h=d[b]||h,q=d.dashStyle||q,e=C(d.opacity,e));m={fill:g,stroke:v,"stroke-width":h,opacity:e};q&&(m.dashstyle=q);return m},drawPoints:function(){var d=this,f=this.chart,q=d.options,x=f.renderer,m=q.animationLimit||250,b;d.points.forEach(function(g){var n=g.graphic,h=!!n,e=n&&f.pointCount\u25cf
{series.name}
',pointFormat:"x: {point.x}
y: {point.y}
"}},{sorted:!1,requireSorting:!1,noSharedTooltip:!0,trackerGroups:["group", +"markerGroup","dataLabelsGroup"],takeOrdinalPosition:!1,drawGraph:function(){this.options.lineWidth&&q.prototype.drawGraph.call(this)},applyJitter:function(){var d=this,f=this.options.jitter,q=this.points.length;f&&this.points.forEach(function(A,x){["x","y"].forEach(function(E,H){var C="plot"+E.toUpperCase();if(f[E]&&!A.isNull){var D=d[E+"Axis"];var w=f[E]*D.transA;if(D&&!D.isLog){var n=Math.max(0,A[C]-w);D=Math.min(D.len,A[C]+w);H=1E4*Math.sin(x+H*q);A[C]=n+(D-n)*(H-Math.floor(H));"x"===E&&(A.clientX= +A.plotX)}}})})}});A(q,"afterTranslate",function(){this.applyJitter&&this.applyJitter()});""});Q(A,"mixins/centered-series.js",[A["parts/Globals.js"],A["parts/Utilities.js"]],function(d,f){var A=f.isNumber,q=f.pick,M=f.relativeLength,K=d.deg2rad;d.CenteredSeriesMixin={getCenter:function(){var d=this.options,f=this.chart,x=2*(d.slicedOffset||0),A=f.plotWidth-2*x,E=f.plotHeight-2*x,C=d.center,D=Math.min(A,E),w=d.size,n=d.innerSize||0;"string"===typeof w&&(w=parseFloat(w));"string"===typeof n&&(n=parseFloat(n)); +d=[q(C[0],"50%"),q(C[1],"50%"),q(w&&0>w?void 0:d.size,"100%"),q(n&&0>n?void 0:d.innerSize||0,"0%")];f.angular&&(d[3]=0);for(C=0;4>C;++C)w=d[C],f=2>C||2===C&&/%$/.test(w),d[C]=M(w,[A,E,D,d[2]][C])+(f?x:0);d[3]>d[2]&&(d[3]=d[2]);return d},getStartAndEndRadians:function(d,f){d=A(d)?d:0;f=A(f)&&f>d&&360>f-d?f:d+360;return{start:K*(d+-90),end:K*(f+-90)}}}});Q(A,"parts/PieSeries.js",[A["parts/Globals.js"],A["mixins/legend-symbol.js"],A["parts/Point.js"],A["parts/Utilities.js"]],function(d,f,A,q){var E= +q.addEvent,K=q.clamp,J=q.defined,L=q.fireEvent,x=q.isNumber,F=q.merge,H=q.pick,C=q.relativeLength,D=q.seriesType,w=q.setAnimation;q=d.CenteredSeriesMixin;var n=q.getStartAndEndRadians,t=d.noop,N=d.Series;D("pie","line",{center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{allowOverlap:!0,connectorPadding:5,connectorShape:"fixedOffset",crookDistance:"70%",distance:30,enabled:!0,formatter:function(){return this.point.isNull?void 0:this.point.name},softConnector:!0,x:0},fillColor:void 0,ignoreHiddenPoint:!0, +inactiveOtherPoints:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,stickyTracking:!1,tooltip:{followPointer:!0},borderColor:"#ffffff",borderWidth:1,lineWidth:void 0,states:{hover:{brightness:.1}}},{isCartesian:!1,requireSorting:!1,directTouch:!0,noSharedTooltip:!0,trackerGroups:["group","dataLabelsGroup"],axisTypes:[],pointAttribs:d.seriesTypes.column.prototype.pointAttribs,animate:function(d){var b=this,f=b.points,m=b.startAngleRad;d||f.forEach(function(d){var e=d.graphic, +f=d.shapeArgs;e&&f&&(e.attr({r:H(d.startR,b.center&&b.center[3]/2),start:m,end:m}),e.animate({r:f.r,start:f.start,end:f.end},b.options.animation))})},hasData:function(){return!!this.processedXData.length},updateTotals:function(){var d,b=0,f=this.points,n=f.length,h=this.options.ignoreHiddenPoint;for(d=0;d1.5*Math.PI? +x-=2*Math.PI:x<-Math.PI/2&&(x+=2*Math.PI);t.slicedTranslation={translateX:Math.round(Math.cos(x)*m),translateY:Math.round(Math.sin(x)*m)};var B=Math.cos(x)*d[2]/2;var c=Math.sin(x)*d[2]/2;t.tooltipPos=[d[0]+.7*B,d[1]+.7*c];t.half=x<-Math.PI/2||x>Math.PI/2?1:0;t.angle=x;w=Math.min(h,t.labelDistance/5);t.labelPosition={natural:{x:d[0]+B+Math.cos(x)*t.labelDistance,y:d[1]+c+Math.sin(x)*t.labelDistance},"final":{},alignment:0>t.labelDistance?"center":t.half?"right":"left",connectorPosition:{breakAt:{x:d[0]+ +B+Math.cos(x)*w,y:d[1]+c+Math.sin(x)*w},touchingSliceAt:{x:d[0]+B,y:d[1]+c}}}}L(this,"afterTranslate")},drawEmpty:function(){var d=this.options;if(0===this.total){var b=this.center[0];var f=this.center[1];this.graph||(this.graph=this.chart.renderer.circle(b,f,0).addClass("highcharts-graph").add(this.group));this.graph.animate({"stroke-width":d.borderWidth,cx:b,cy:f,r:this.center[2]/2,fill:d.fillColor||"none",stroke:d.color||"#cccccc"},this.options.animation)}else this.graph&&(this.graph=this.graph.destroy())}, +redrawPoints:function(){var d=this,b=d.chart,f=b.renderer,n,h,e,p,l=d.options.shadow;this.drawEmpty();!l||d.shadowGroup||b.styledMode||(d.shadowGroup=f.g("shadow").attr({zIndex:-1}).add(d.group));d.points.forEach(function(g){var m={};h=g.graphic;if(!g.isNull&&h){p=g.shapeArgs;n=g.getTranslate();if(!b.styledMode){var v=g.shadowGroup;l&&!v&&(v=g.shadowGroup=f.g("shadow").add(d.shadowGroup));v&&v.attr(n);e=d.pointAttribs(g,g.selected&&"select")}g.delayedRendering?(h.setRadialReference(d.center).attr(p).attr(n), +b.styledMode||h.attr(e).attr({"stroke-linejoin":"round"}).shadow(l,v),g.delayedRendering=!1):(h.setRadialReference(d.center),b.styledMode||F(!0,m,e),F(!0,m,p,n),h.animate(m));h.attr({visibility:g.visible?"inherit":"hidden"});h.addClass(g.getClassName())}else h&&(g.graphic=h.destroy())})},drawPoints:function(){var d=this.chart.renderer;this.points.forEach(function(b){b.graphic&&b.hasNewShapeType()&&(b.graphic=b.graphic.destroy());b.graphic||(b.graphic=d[b.shapeType](b.shapeArgs).add(b.series.group), +b.delayedRendering=!0)})},searchPoint:t,sortByAngle:function(d,b){d.sort(function(d,f){return"undefined"!==typeof d.angle&&(f.angle-d.angle)*b})},drawLegendSymbol:f.drawRectangle,getCenter:q.getCenter,getSymbol:t,drawGraph:null},{init:function(){A.prototype.init.apply(this,arguments);var d=this;d.name=H(d.name,"Slice");var b=function(b){d.slice("select"===b.type)};E(d,"select",b);E(d,"unselect",b);return d},isValid:function(){return x(this.y)&&0<=this.y},setVisible:function(d,b){var f=this,m=f.series, +h=m.chart,e=m.options.ignoreHiddenPoint;b=H(b,e);d!==f.visible&&(f.visible=f.options.visible=d="undefined"===typeof d?!f.visible:d,m.options.data[m.data.indexOf(f)]=f.options,["graphic","dataLabel","connector","shadowGroup"].forEach(function(b){if(f[b])f[b][d?"show":"hide"](!0)}),f.legendItem&&h.legend.colorizeItem(f,d),d||"hover"!==f.state||f.setState(""),e&&(m.isDirty=!0),b&&h.redraw())},slice:function(d,b,f){var g=this.series;w(f,g.chart);H(b,!0);this.sliced=this.options.sliced=J(d)?d:!this.sliced; +g.options.data[g.data.indexOf(this)]=this.options;this.graphic&&this.graphic.animate(this.getTranslate());this.shadowGroup&&this.shadowGroup.animate(this.getTranslate())},getTranslate:function(){return this.sliced?this.slicedTranslation:{translateX:0,translateY:0}},haloPath:function(d){var b=this.shapeArgs;return this.sliced||!this.visible?[]:this.series.chart.renderer.symbols.arc(b.x,b.y,b.r+d,b.r+d,{innerR:b.r-1,start:b.start,end:b.end})},connectorShapes:{fixedOffset:function(d,b,f){var g=b.breakAt; +b=b.touchingSliceAt;return[["M",d.x,d.y],f.softConnector?["C",d.x+("left"===d.alignment?-5:5),d.y,2*g.x-b.x,2*g.y-b.y,g.x,g.y]:["L",g.x,g.y],["L",b.x,b.y]]},straight:function(d,b){b=b.touchingSliceAt;return[["M",d.x,d.y],["L",b.x,b.y]]},crookedLine:function(d,b,f){b=b.touchingSliceAt;var g=this.series,h=g.center[0],e=g.chart.plotWidth,m=g.chart.plotLeft;g=d.alignment;var l=this.shapeArgs.r;f=C(f.crookDistance,1);e="left"===g?h+l+(e+m-h-l)*(1-f):m+(h-l)*f;f=["L",e,d.y];h=!0;if("left"===g?e>d.x||e< +b.x:eb.x)h=!1;d=[["M",d.x,d.y]];h&&d.push(f);d.push(["L",b.x,b.y]);return d}},getConnectorPath:function(){var d=this.labelPosition,b=this.series.options.dataLabels,f=b.connectorShape,n=this.connectorShapes;n[f]&&(f=n[f]);return f.call(this,{x:d.final.x,y:d.final.y,alignment:d.alignment},d.connectorPosition,b)}});""});Q(A,"parts/DataLabels.js",[A["parts/Globals.js"],A["parts/Utilities.js"]],function(d,f){var A=f.animObject,q=f.arrayMax,M=f.clamp,K=f.defined,J=f.extend,L=f.fireEvent,x=f.format, +F=f.isArray,H=f.merge,C=f.objectEach,D=f.pick,w=f.relativeLength,n=f.splat,t=f.stableSort;f=d.noop;var N=d.Series,m=d.seriesTypes;d.distribute=function(b,f,m){function g(b,e){return b.target-e.target}var e,n=!0,l=b,v=[];var u=0;var q=l.reducedLen||f;for(e=b.length;e--;)u+=b[e].size;if(u>q){t(b,function(b,e){return(e.rank||0)-(b.rank||0)});for(u=e=0;u<=q;)u+=b[e].size,e++;v=b.splice(e-1,b.length)}t(b,g);for(b=b.map(function(b){return{size:b.size,targets:[b.target],align:D(b.align,.5)}});n;){for(e= +b.length;e--;)n=b[e],u=(Math.min.apply(0,n.targets)+Math.max.apply(0,n.targets))/2,n.pos=M(u-n.size*n.align,0,f-n.size);e=b.length;for(n=!1;e--;)0b[e].pos&&(b[e-1].size+=b[e].size,b[e-1].targets=b[e-1].targets.concat(b[e].targets),b[e-1].align=.5,b[e-1].pos+b[e-1].size>f&&(b[e-1].pos=f-b[e-1].size),b.splice(e,1),n=!0)}l.push.apply(l,v);e=0;b.some(function(b){var g=0;if(b.targets.some(function(){l[e].pos=b.pos+g;if("undefined"!==typeof m&&Math.abs(l[e].pos-l[e].target)>m)return l.slice(0, +e+1).forEach(function(b){delete b.pos}),l.reducedLen=(l.reducedLen||f)-.1*f,l.reducedLen>.1*f&&d.distribute(l,f,m),!0;g+=l[e].size;e++}))return!0});t(l,g)};N.prototype.drawDataLabels=function(){function b(c,a){var b=a.filter;return b?(a=b.operator,c=c[b.property],b=b.value,">"===a&&c>b||"<"===a&&c="===a&&c>=b||"<="===a&&c<=b||"=="===a&&c==b||"==="===a&&c===b?!0:!1):!0}function d(c,a){var b=[],e;if(F(c)&&!F(a))b=c.map(function(c){return H(c,a)});else if(F(a)&&!F(c))b=a.map(function(a){return H(c, +a)});else if(F(c)||F(a))for(e=Math.max(c.length,a.length);e--;)b[e]=H(c[e],a[e]);else b=H(c,a);return b}var f=this,h=f.chart,e=f.options,m=e.dataLabels,l=f.points,q,u=f.hasRendered||0,t=A(e.animation).duration,w=Math.min(t,200),E=!h.renderer.forExport&&D(m.defer,0m||e.stacking?c.contrastColor:"#000000"):delete c.contrastColor,e.cursor&&(u.cursor=e.cursor));var q={r:a.borderRadius|| +0,rotation:v,padding:a.padding,zIndex:1};h.styledMode||(q.fill=a.backgroundColor,q.stroke=a.borderColor,q["stroke-width"]=a.borderWidth);C(q,function(a,c){"undefined"===typeof a&&delete q[c]})}!l||g&&K(p)?g&&K(p)&&(l?q.text=p:(c.dataLabels=c.dataLabels||[],l=c.dataLabels[d]=v?J.text(p,0,-9999,a.useHTML).addClass("highcharts-data-label"):J.label(p,0,-9999,a.shape,null,null,a.useHTML,null,"data-label"),d||(c.dataLabel=l),l.addClass(" highcharts-data-label-color-"+c.colorIndex+" "+(a.className||"")+ +(a.useHTML?" highcharts-tracker":""))),l.options=a,l.attr(q),h.styledMode||l.css(u).shadow(a.shadow),l.added||l.add(B),a.textPath&&!a.useHTML&&(l.setTextPath(c.getDataLabelPath&&c.getDataLabelPath(l)||c.graphic,a.textPath),c.dataLabelPath&&!a.textPath.enabled&&(c.dataLabelPath=c.dataLabelPath.destroy())),f.alignDataLabel(c,l,a,null,n)):(c.dataLabel=c.dataLabel&&c.dataLabel.destroy(),c.dataLabels&&(1===c.dataLabels.length?delete c.dataLabels:delete c.dataLabels[d]),d||delete c.dataLabel,k&&(c.connector= +c.connector.destroy(),c.connectors&&(1===c.connectors.length?delete c.connectors:delete c.connectors[d])))})})}L(this,"afterDrawDataLabels")};N.prototype.alignDataLabel=function(b,d,f,h,e){var g=this,l=this.chart,m=this.isCartesian&&l.inverted,n=this.enabledDataSorting,q=D(b.dlBox&&b.dlBox.centerX,b.plotX,-9999),v=D(b.plotY,-9999),t=d.getBBox(),w=f.rotation,x=f.align,c=l.isInsidePlot(q,Math.round(v),m),a="justify"===D(f.overflow,n?"none":"justify"),k=this.visible&&!1!==b.visible&&(b.series.forceDL|| +n&&!a||c||f.inside&&h&&l.isInsidePlot(q,m?h.x+1:h.y+h.height-1,m));var r=function(f){n&&g.xAxis&&!a&&g.setDataLabelStartPos(b,d,e,c,f)};if(k){var z=l.renderer.fontMetrics(l.styledMode?void 0:f.style.fontSize,d).b;h=J({x:m?this.yAxis.len-v:q,y:Math.round(m?this.xAxis.len-q:v),width:0,height:0},h);J(f,{width:t.width,height:t.height});w?(a=!1,q=l.renderer.rotCorr(z,w),q={x:h.x+f.x+h.width/2+q.x,y:h.y+f.y+{top:0,middle:.5,bottom:1}[f.verticalAlign]*h.height},r(q),d[e?"attr":"animate"](q).attr({align:x}), +r=(w+720)%360,r=180r,"left"===x?q.y-=r?t.height:0:"center"===x?(q.x-=t.width/2,q.y-=t.height/2):"right"===x&&(q.x-=t.width,q.y-=r?0:t.height),d.placed=!0,d.alignAttr=q):(r(h),d.align(f,null,h),q=d.alignAttr);a&&0<=h.height?this.justifyDataLabel(d,f,q,t,h,e):D(f.crop,!0)&&(k=l.isInsidePlot(q.x,q.y)&&l.isInsidePlot(q.x+t.width,q.y+t.height));if(f.shape&&!w)d[e?"attr":"animate"]({anchorX:m?l.plotWidth-b.plotY:b.plotX,anchorY:m?l.plotHeight-b.plotX:b.plotY})}e&&n&&(d.placed=!1);k||n&&!a||(d.hide(!0), +d.placed=!1)};N.prototype.setDataLabelStartPos=function(b,d,f,h,e){var g=this.chart,l=g.inverted,m=this.xAxis,n=m.reversed,q=l?d.height/2:d.width/2;b=(b=b.pointWidth)?b/2:0;m=l?e.x:n?-q-b:m.width-q+b;e=l?n?this.yAxis.height-q+b:-q-b:e.y;d.startXPos=m;d.startYPos=e;h?"hidden"===d.visibility&&(d.show(),d.attr({opacity:0}).animate({opacity:1})):d.attr({opacity:1}).animate({opacity:0},void 0,d.hide);g.hasRendered&&(f&&d.attr({x:d.startXPos,y:d.startYPos}),d.placed=!0)};N.prototype.justifyDataLabel=function(b, +d,f,h,e,m){var g=this.chart,n=d.align,p=d.verticalAlign,q=b.box?0:b.padding||0;var v=f.x+q;if(0>v){"right"===n?(d.align="left",d.inside=!0):d.x=-v;var t=!0}v=f.x+h.width-q;v>g.plotWidth&&("left"===n?(d.align="right",d.inside=!0):d.x=g.plotWidth-v,t=!0);v=f.y+q;0>v&&("bottom"===p?(d.verticalAlign="top",d.inside=!0):d.y=-v,t=!0);v=f.y+h.height-q;v>g.plotHeight&&("top"===p?(d.verticalAlign="bottom",d.inside=!0):d.y=g.plotHeight-v,t=!0);t&&(b.placed=!m,b.align(d,null,e));return t};m.pie&&(m.pie.prototype.dataLabelPositioners= +{radialDistributionY:function(b){return b.top+b.distributeBox.pos},radialDistributionX:function(b,d,f,h){return b.getX(fd.bottom-2?h:f,d.half,d)},justify:function(b,d,f){return f[0]+(b.half?-1:1)*(d+b.labelDistance)},alignToPlotEdges:function(b,d,f,h){b=b.getBBox().width;return d?b+h:f-b-h},alignToConnectors:function(b,d,f,h){var e=0,g;b.forEach(function(b){g=b.dataLabel.getBBox().width;g>e&&(e=g)});return d?e+h:f-e-h}},m.pie.prototype.drawDataLabels=function(){var b=this,f=b.data,m,h= +b.chart,e=b.options.dataLabels||{},n=e.connectorPadding,l,t=h.plotWidth,u=h.plotHeight,y=h.plotLeft,w=Math.round(h.chartWidth/3),x,C=b.center,B=C[2]/2,c=C[1],a,k,r,z,A=[[],[]],E,F,L,J,M=[0,0,0,0],Q=b.dataLabelPositioners,O;b.visible&&(e.enabled||b._hasPointLabels)&&(f.forEach(function(a){a.dataLabel&&a.visible&&a.dataLabel.shortened&&(a.dataLabel.attr({width:"auto"}).css({width:"auto",textOverflow:"clip"}),a.dataLabel.shortened=!1)}),N.prototype.drawDataLabels.apply(b),f.forEach(function(a){a.dataLabel&& +(a.visible?(A[a.half].push(a),a.dataLabel._pos=null,!K(e.style.width)&&!K(a.options.dataLabels&&a.options.dataLabels.style&&a.options.dataLabels.style.width)&&a.dataLabel.getBBox().width>w&&(a.dataLabel.css({width:Math.round(.7*w)+"px"}),a.dataLabel.shortened=!0)):(a.dataLabel=a.dataLabel.destroy(),a.dataLabels&&1===a.dataLabels.length&&delete a.dataLabels))}),A.forEach(function(f,g){var l=f.length,p=[],q;if(l){b.sortByAngle(f,g-.5);if(0t-n&&0===g&&(v=Math.round(E+k-t+n),M[1]=Math.max(v,M[1])),0>F-z/2?M[0]=Math.max(Math.round(-F+z/2),M[0]):F+z/2>u&&(M[2]=Math.max(Math.round(F+z/2-u),M[2])),a.sideOverflow=v)}}}),0===q(M)||this.verifyDataLabelOverflow(M))&&(this.placeDataLabels(),this.points.forEach(function(c){O=H(e,c.options.dataLabels);if(l=D(O.connectorWidth,1)){var d;x=c.connector;if((a=c.dataLabel)&&a._pos&&c.visible&&0D(this.translatedThreshold,l.yAxis.len)),q= +D(f.inside,!!this.options.stacking);m&&(h=H(m),0>h.y&&(h.height+=h.y,h.y=0),m=h.y+h.height-l.yAxis.len,0J.x+J.width||m.x+m.widthJ.y+J.height||m.y+m.height=a&&l<=k||h||!L(l))m=!0;f[h?"zoomX":"zoomY"]&&m&&(e=c.zoom(b.min,b.max),c.displayBtn&&(g=!0))});var h=d.resetZoomButton;g&&!h? +d.showResetZoom():!g&&w(h)&&(d.resetZoomButton=h.destroy());e&&d.redraw(N(d.options.chart.animation,b&&b.animation,100>d.pointCount))},pan:function(b,e){var f=this,g=f.hoverPoints,l=f.options.chart,h=f.options.mapNavigation&&f.options.mapNavigation.enabled,m;e="object"===typeof e?e:{enabled:e,type:"x"};l&&l.panning&&(l.panning=e);var n=e.type;F(this,"pan",{originalEvent:b},function(){g&&g.forEach(function(a){a.setState()});var c=[1];"xy"===n?c=[1,0]:"y"===n&&(c=[0]);c.forEach(function(a){var c=f[a? +"xAxis":"yAxis"][0],e=c.options,g=c.horiz,l=b[g?"chartX":"chartY"];g=g?"mouseDownX":"mouseDownY";var p=f[g],q=(c.pointRange||0)/2,u=c.reversed&&!f.inverted||!c.reversed&&f.inverted?-1:1,t=c.getExtremes(),v=c.toValue(p-l,!0)+q*u;u=c.toValue(p+c.len-l,!0)-q*u;var w=u=u&&v<=q)c.setExtremes(p, +v,!1,!1,{trigger:"pan"}),f.resetZoomButton||h||!n.match("y")||(f.showResetZoom(),c.displayBtn=!1),m=!0;f[g]=l}});m&&f.redraw(!1);J(f.container,{cursor:"move"})})}});x(A.prototype,{select:function(b,d){var e=this,f=e.series,g=f.chart;this.selectedStaging=b=N(b,!e.selected);e.firePointEvent(b?"select":"unselect",{accumulate:d},function(){e.selected=e.options.selected=b;f.options.data[f.data.indexOf(e)]=e.options;e.setState(b&&"select");d||g.getSelectedPoints().forEach(function(b){var d=b.series;b.selected&& +b!==e&&(b.selected=b.options.selected=!1,d.options.data[d.data.indexOf(b)]=b.options,b.setState(g.hoverPoints&&d.options.inactiveOtherPoints?"inactive":""),b.firePointEvent("unselect"))})});delete this.selectedStaging},onMouseOver:function(b){var d=this.series.chart,e=d.pointer;b=b?e.normalize(b):e.getChartCoordinatesFromPoint(this,d.inverted);e.runPointActions(b,this)},onMouseOut:function(){var b=this.series.chart;this.firePointEvent("mouseOut");this.series.options.inactiveOtherPoints||(b.hoverPoints|| +[]).forEach(function(b){b.setState()});b.hoverPoints=b.hoverPoint=null},importEvents:function(){if(!this.hasImportedEvents){var b=this,d=n(b.series.options.point,b.options).events;b.events=d;t(d,function(d,e){C(d)&&E(b,e,d)});this.hasImportedEvents=!0}},setState:function(d,e){var f=this.series,g=this.state,l=f.options.states[d||"normal"]||{},h=b[f.type].marker&&f.options.marker,m=h&&!1===h.enabled,n=h&&h.states&&h.states[d||"normal"]||{},c=!1===n.enabled,a=f.stateMarkerGraphic,k=this.marker||{},p= +f.chart,q=f.halo,t,v=h&&f.markerAttribs;d=d||"";if(!(d===this.state&&!e||this.selected&&"select"!==d||!1===l.enabled||d&&(c||m&&!1===n.enabled)||d&&k.states&&k.states[d]&&!1===k.states[d].enabled)){this.state=d;v&&(t=f.markerAttribs(this,d));if(this.graphic){g&&this.graphic.removeClass("highcharts-point-"+g);d&&this.graphic.addClass("highcharts-point-"+d);if(!p.styledMode){var w=f.pointAttribs(this,d);var A=N(p.options.chart.animation,l.animation);f.options.inactiveOtherPoints&&w.opacity&&((this.dataLabels|| +[]).forEach(function(a){a&&a.animate({opacity:w.opacity},A)}),this.connector&&this.connector.animate({opacity:w.opacity},A));this.graphic.animate(w,A)}t&&this.graphic.animate(t,N(p.options.chart.animation,n.animation,h.animation));a&&a.hide()}else{if(d&&n){g=k.symbol||f.symbol;a&&a.currentSymbol!==g&&(a=a.destroy());if(t)if(a)a[e?"animate":"attr"]({x:t.x,y:t.y});else g&&(f.stateMarkerGraphic=a=p.renderer.symbol(g,t.x,t.y,t.width,t.height).add(f.markerGroup),a.currentSymbol=g);!p.styledMode&&a&&a.attr(f.pointAttribs(this, +d))}a&&(a[d&&this.isInside?"show":"hide"](),a.element.point=this)}d=l.halo;l=(a=this.graphic||a)&&a.visibility||"inherit";d&&d.size&&a&&"hidden"!==l&&!this.isCluster?(q||(f.halo=q=p.renderer.path().add(a.parentGroup)),q.show()[e?"animate":"attr"]({d:this.haloPath(d.size)}),q.attr({"class":"highcharts-halo highcharts-color-"+N(this.colorIndex,f.colorIndex)+(this.className?" "+this.className:""),visibility:l,zIndex:-1}),q.point=this,p.styledMode||q.attr(x({fill:this.color||f.color,"fill-opacity":d.opacity}, +d.attributes))):q&&q.point&&q.point.haloPath&&q.animate({d:q.point.haloPath(0)},null,q.hide);F(this,"afterSetState")}},haloPath:function(b){return this.series.chart.renderer.symbols.circle(Math.floor(this.plotX)-b,this.plotY-b,2*b,2*b)}});x(v.prototype,{onMouseOver:function(){var b=this.chart,d=b.hoverSeries;b.pointer.setHoverChartIndex();if(d&&d!==this)d.onMouseOut();this.options.events.mouseOver&&F(this,"mouseOver");this.setState("hover");b.hoverSeries=this},onMouseOut:function(){var b=this.options, +d=this.chart,e=d.tooltip,f=d.hoverPoint;d.hoverSeries=null;if(f)f.onMouseOut();this&&b.events.mouseOut&&F(this,"mouseOut");!e||this.stickyTracking||e.shared&&!this.noSharedTooltip||e.hide();d.series.forEach(function(b){b.setState("",!0)})},setState:function(b,d){var e=this,f=e.options,g=e.graph,l=f.inactiveOtherPoints,h=f.states,m=f.lineWidth,c=f.opacity,a=N(h[b||"normal"]&&h[b||"normal"].animation,e.chart.options.chart.animation);f=0;b=b||"";if(e.state!==b&&([e.group,e.markerGroup,e.dataLabelsGroup].forEach(function(a){a&& +(e.state&&a.removeClass("highcharts-series-"+e.state),b&&a.addClass("highcharts-series-"+b))}),e.state=b,!e.chart.styledMode)){if(h[b]&&!1===h[b].enabled)return;b&&(m=h[b].lineWidth||m+(h[b].lineWidthPlus||0),c=N(h[b].opacity,c));if(g&&!g.dashstyle)for(h={"stroke-width":m},g.animate(h,a);e["zone-graph-"+f];)e["zone-graph-"+f].attr(h),f+=1;l||[e.group,e.markerGroup,e.dataLabelsGroup,e.labelBySeries].forEach(function(b){b&&b.animate({opacity:c},a)})}d&&l&&e.points&&e.setAllPointsToState(b)},setAllPointsToState:function(b){this.points.forEach(function(d){d.setState&& +d.setState(b)})},setVisible:function(b,d){var e=this,f=e.chart,g=e.legendItem,h=f.options.chart.ignoreHiddenSeries,l=e.visible;var m=(e.visible=b=e.options.visible=e.userOptions.visible="undefined"===typeof b?!l:b)?"show":"hide";["group","dataLabelsGroup","markerGroup","tracker","tt"].forEach(function(b){if(e[b])e[b][m]()});if(f.hoverSeries===e||(f.hoverPoint&&f.hoverPoint.series)===e)e.onMouseOut();g&&f.legend.colorizeItem(e,b);e.isDirty=!0;e.options.stacking&&f.series.forEach(function(b){b.options.stacking&& +b.visible&&(b.isDirty=!0)});e.linkedSeries.forEach(function(c){c.setVisible(b,!1)});h&&(f.isDirtyBox=!0);F(e,m);!1!==d&&f.redraw()},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},select:function(b){this.selected=b=this.options.selected="undefined"===typeof b?!this.selected:b;this.checkbox&&(this.checkbox.checked=b);F(this,b?"select":"unselect")},drawTracker:p.drawTrackerGraph})});Q(A,"parts/Responsive.js",[A["parts/Globals.js"],A["parts/Utilities.js"]],function(d,f){var A= +f.find,q=f.isArray,M=f.isObject,K=f.merge,J=f.objectEach,L=f.pick,x=f.splat,F=f.uniqueKey;d=d.Chart;d.prototype.setResponsive=function(d,f){var q=this.options.responsive,w=[],n=this.currentResponsive;!f&&q&&q.rules&&q.rules.forEach(function(d){"undefined"===typeof d._id&&(d._id=F());this.matchResponsiveRule(d,w)},this);f=K.apply(0,w.map(function(d){return A(q.rules,function(f){return f._id===d}).chartOptions}));f.isResponsiveOptions=!0;w=w.toString()||void 0;w!==(n&&n.ruleIds)&&(n&&this.update(n.undoOptions, +d,!0),w?(n=this.currentOptions(f),n.isResponsiveOptions=!0,this.currentResponsive={ruleIds:w,mergedOptions:f,undoOptions:n},this.update(f,d,!0)):this.currentResponsive=void 0)};d.prototype.matchResponsiveRule=function(d,f){var q=d.condition;(q.callback||function(){return this.chartWidth<=L(q.maxWidth,Number.MAX_VALUE)&&this.chartHeight<=L(q.maxHeight,Number.MAX_VALUE)&&this.chartWidth>=L(q.minWidth,0)&&this.chartHeight>=L(q.minHeight,0)}).call(this)&&f.push(d._id)};d.prototype.currentOptions=function(d){function f(d, +t,w,m){var b;J(d,function(d,n){if(!m&&-1(n=1))return n;for(;ra?r=i:n=i,i=.5*(n-r)+r;}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))};var i=a;function a(t,e){this.x=t,this.y=e;}function o(t,e,n,i){var a=new r(t,e,n,i);return function(t){return a.solve(t)}}a.prototype={clone:function(){return new a(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},a.convert=function(t){return t instanceof a?t:Array.isArray(t)?new a(t[0],t[1]):t};var s=o(.25,.1,.25,1);function u(t,e,r){return Math.min(r,Math.max(e,t))}function l(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function p(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n>e/4).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,t)}()}function y(t){return !!t&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)}function d(t,e){t.forEach((function(t){e[t]&&(e[t]=e[t].bind(e));}));}function m(t,e){return -1!==t.indexOf(e,t.length-e.length)}function v(t,e,r){var n={};for(var i in t)n[i]=e.call(r||this,t[i],i,t);return n}function g(t,e,r){var n={};for(var i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function x(t){return Array.isArray(t)?t.map(x):"object"==typeof t&&t?v(t,x):t}var b={};function w(t){b[t]||("undefined"!=typeof console&&console.warn(t),b[t]=!0);}function _(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function A(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""})),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r;}return e}var I=null;function z(t){if(null==I){var e=t.navigator?t.navigator.userAgent:null;I=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return I}function C(t){try{var e=self[t];return e.setItem("_mapbox_test_",1),e.removeItem("_mapbox_test_"),!0}catch(t){return !1}}var M,E,T,P,B=self.performance&&self.performance.now?self.performance.now.bind(self.performance):Date.now.bind(Date),V=self.requestAnimationFrame||self.mozRequestAnimationFrame||self.webkitRequestAnimationFrame||self.msRequestAnimationFrame,F=self.cancelAnimationFrame||self.mozCancelAnimationFrame||self.webkitCancelAnimationFrame||self.msCancelAnimationFrame,D={now:B,frame:function(t){var e=V(t);return {cancel:function(){return F(e)}}},getImageData:function(t,e){void 0===e&&(e=0);var r=self.document.createElement("canvas"),n=r.getContext("2d");if(!n)throw new Error("failed to create canvas 2d context");return r.width=t.width,r.height=t.height,n.drawImage(t,0,0,t.width,t.height),n.getImageData(-e,-e,t.width+2*e,t.height+2*e)},resolveURL:function(t){return M||(M=self.document.createElement("a")),M.href=t,M.href},hardwareConcurrency:self.navigator.hardwareConcurrency||4,get devicePixelRatio(){return self.devicePixelRatio},get prefersReducedMotion(){return !!self.matchMedia&&(null==E&&(E=self.matchMedia("(prefers-reduced-motion: reduce)")),E.matches)}},L={API_URL:"https://api.mapbox.com",get EVENTS_URL(){return this.API_URL?0===this.API_URL.indexOf("https://api.mapbox.cn")?"https://events.mapbox.cn/events/v2":0===this.API_URL.indexOf("https://api.mapbox.com")?"https://events.mapbox.com/events/v2":null:null},FEEDBACK_URL:"https://apps.mapbox.com/feedback",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,MAX_PARALLEL_IMAGE_REQUESTS:16},R={supported:!1,testSupport:function(t){!O&&P&&(U?j(t):T=t);}},O=!1,U=!1;function j(t){var e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);try{if(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,P),t.isContextLost())return;R.supported=!0;}catch(t){}t.deleteTexture(e),O=!0;}self.document&&((P=self.document.createElement("img")).onload=function(){T&&j(T),T=null,U=!0;},P.onerror=function(){O=!0,T=null;},P.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");var q="01",N=function(t,e){this._transformRequestFn=t,this._customAccessToken=e,this._createSkuToken();};function K(t){return 0===t.indexOf("mapbox:")}N.prototype._createSkuToken=function(){var t=function(){for(var t="",e=0;e<10;e++)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return {token:["1",q,t].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=t.token,this._skuTokenExpiresAt=t.tokenExpiresAt;},N.prototype._isSkuTokenExpired=function(){return Date.now()>this._skuTokenExpiresAt},N.prototype.transformRequest=function(t,e){return this._transformRequestFn&&this._transformRequestFn(t,e)||{url:t}},N.prototype.normalizeStyleURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/styles/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeGlyphsURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/fonts/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeSourceURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeSpriteURL=function(t,e,r,n){var i=J(t);return K(t)?(i.path="/styles/v1"+i.path+"/sprite"+e+r,this._makeAPIURL(i,this._customAccessToken||n)):(i.path+=""+e+r,H(i))},N.prototype.normalizeTileURL=function(t,e){if(this._isSkuTokenExpired()&&this._createSkuToken(),t&&!K(t))return t;var r=J(t);r.path=r.path.replace(/(\.(png|jpg)\d*)(?=$)/,(D.devicePixelRatio>=2||512===e?"@2x":"")+(R.supported?".webp":"$1")),r.path=r.path.replace(/^.+\/v4\//,"/"),r.path="/v4"+r.path;var n=this._customAccessToken||function(t){for(var e=0,r=t;e=1&&self.localStorage.setItem(e,JSON.stringify(this.eventData));}catch(t){w("Unable to write to LocalStorage");}},$.prototype.processRequests=function(t){},$.prototype.postEvent=function(t,e,r,n){var i=this;if(L.EVENTS_URL){var a=J(L.EVENTS_URL);a.params.push("access_token="+(n||L.ACCESS_TOKEN||""));var o={event:this.type,created:new Date(t).toISOString(),sdkIdentifier:"mapbox-gl-js",sdkVersion:"1.10.1",skuId:q,userId:this.anonId},s=e?p(o,e):o,u={url:H(a),headers:{"Content-Type":"text/plain"},body:JSON.stringify([s])};this.pendingRequest=xt(u,(function(t){i.pendingRequest=null,r(t),i.saveEventData(),i.processRequests(n);}));}},$.prototype.queueRequest=function(t,e){this.queue.push(t),this.processRequests(e);};var W,Q,tt=function(t){function e(){t.call(this,"map.load"),this.success={},this.skuToken="";}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.postMapLoadEvent=function(t,e,r,n){this.skuToken=r,(L.EVENTS_URL&&n||L.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return K(t)||Z(t)})))&&this.queueRequest({id:e,timestamp:Date.now()},n);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){var r=this.queue.shift(),n=r.id,i=r.timestamp;n&&this.success[n]||(this.anonId||this.fetchEventData(),y(this.anonId)||(this.anonId=f()),this.postEvent(i,{skuToken:this.skuToken},(function(t){t||n&&(e.success[n]=!0);}),t));}},e}($),et=new(function(t){function e(e){t.call(this,"appUserTurnstile"),this._customAccessToken=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.postTurnstileEvent=function(t,e){L.EVENTS_URL&&L.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return K(t)||Z(t)}))&&this.queueRequest(Date.now(),e);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){this.anonId&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();var r=Y(L.ACCESS_TOKEN),n=r?r.u:L.ACCESS_TOKEN,i=n!==this.eventData.tokenU;y(this.anonId)||(this.anonId=f(),i=!0);var a=this.queue.shift();if(this.eventData.lastSuccess){var o=new Date(this.eventData.lastSuccess),s=new Date(a),u=(a-this.eventData.lastSuccess)/864e5;i=i||u>=1||u<-1||o.getDate()!==s.getDate();}else i=!0;if(!i)return this.processRequests();this.postEvent(a,{"enabled.telemetry":!1},(function(t){t||(e.eventData.lastSuccess=a,e.eventData.tokenU=n);}),t);}},e}($)),rt=et.postTurnstileEvent.bind(et),nt=new tt,it=nt.postMapLoadEvent.bind(nt),at=500,ot=50;function st(){self.caches&&!W&&(W=self.caches.open("mapbox-tiles"));}function ut(t){var e=t.indexOf("?");return e<0?t:t.slice(0,e)}var lt,pt=1/0;function ct(){return null==lt&&(lt=self.OffscreenCanvas&&new self.OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof self.createImageBitmap),lt}var ht={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};"function"==typeof Object.freeze&&Object.freeze(ht);var ft=function(t){function e(e,r,n){401===r&&Z(n)&&(e+=": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes"),t.call(this,e),this.status=r,this.url=n,this.name=this.constructor.name,this.message=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.toString=function(){return this.name+": "+this.message+" ("+this.status+"): "+this.url},e}(Error),yt=S()?function(){return self.worker&&self.worker.referrer}:function(){return ("blob:"===self.location.protocol?self.parent:self).location.href};var dt,mt,vt=function(t,e){if(!(/^file:/.test(r=t.url)||/^file:/.test(yt())&&!/^\w+:/.test(r))){if(self.fetch&&self.Request&&self.AbortController&&self.Request.prototype.hasOwnProperty("signal"))return function(t,e){var r,n=new self.AbortController,i=new self.Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,referrer:yt(),signal:n.signal}),a=!1,o=!1,s=(r=i.url).indexOf("sku=")>0&&Z(r);"json"===t.type&&i.headers.set("Accept","application/json");var u=function(r,n,a){if(!o){if(r&&"SecurityError"!==r.message&&w(r),n&&a)return l(n);var u=Date.now();self.fetch(i).then((function(r){if(r.ok){var n=s?r.clone():null;return l(r,n,u)}return e(new ft(r.statusText,r.status,t.url))})).catch((function(t){20!==t.code&&e(new Error(t.message));}));}},l=function(r,n,s){("arrayBuffer"===t.type?r.arrayBuffer():"json"===t.type?r.json():r.text()).then((function(t){o||(n&&s&&function(t,e,r){if(st(),W){var n={status:e.status,statusText:e.statusText,headers:new self.Headers};e.headers.forEach((function(t,e){return n.headers.set(e,t)}));var i=k(e.headers.get("Cache-Control")||"");i["no-store"]||(i["max-age"]&&n.headers.set("Expires",new Date(r+1e3*i["max-age"]).toUTCString()),new Date(n.headers.get("Expires")).getTime()-r<42e4||function(t,e){if(void 0===Q)try{new Response(new ReadableStream),Q=!0;}catch(t){Q=!1;}Q?e(t.body):t.blob().then(e);}(e,(function(e){var r=new self.Response(e,n);st(),W&&W.then((function(e){return e.put(ut(t.url),r)})).catch((function(t){return w(t.message)}));})));}}(i,n,s),a=!0,e(null,t,r.headers.get("Cache-Control"),r.headers.get("Expires")));})).catch((function(t){o||e(new Error(t.message));}));};return s?function(t,e){if(st(),!W)return e(null);var r=ut(t.url);W.then((function(t){t.match(r).then((function(n){var i=function(t){if(!t)return !1;var e=new Date(t.headers.get("Expires")||0),r=k(t.headers.get("Cache-Control")||"");return e>Date.now()&&!r["no-cache"]}(n);t.delete(r),i&&t.put(r,n.clone()),e(null,n,i);})).catch(e);})).catch(e);}(i,u):u(null,null),{cancel:function(){o=!0,a||n.abort();}}}(t,e);if(S()&&self.worker&&self.worker.actor)return self.worker.actor.send("getResource",t,e,void 0,!0)}var r;return function(t,e){var r=new self.XMLHttpRequest;for(var n in r.open(t.method||"GET",t.url,!0),"arrayBuffer"===t.type&&(r.responseType="arraybuffer"),t.headers)r.setRequestHeader(n,t.headers[n]);return "json"===t.type&&(r.responseType="text",r.setRequestHeader("Accept","application/json")),r.withCredentials="include"===t.credentials,r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){if((r.status>=200&&r.status<300||0===r.status)&&null!==r.response){var n=r.response;if("json"===t.type)try{n=JSON.parse(r.response);}catch(t){return e(t)}e(null,n,r.getResponseHeader("Cache-Control"),r.getResponseHeader("Expires"));}else e(new ft(r.statusText,r.status,t.url));},r.send(t.body),{cancel:function(){return r.abort()}}}(t,e)},gt=function(t,e){return vt(p(t,{type:"arrayBuffer"}),e)},xt=function(t,e){return vt(p(t,{method:"POST"}),e)};dt=[],mt=0;var bt=function(t,e){if(R.supported&&(t.headers||(t.headers={}),t.headers.accept="image/webp,*/*"),mt>=L.MAX_PARALLEL_IMAGE_REQUESTS){var r={requestParameters:t,callback:e,cancelled:!1,cancel:function(){this.cancelled=!0;}};return dt.push(r),r}mt++;var n=!1,i=function(){if(!n)for(n=!0,mt--;dt.length&&mt0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},kt.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this};var It={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{}},default:"mapbox"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{},within:{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},in:{group:"Lookup"},"index-of":{group:"Lookup"},slice:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},"interpolate-hcl":{group:"Ramps, scales, curves"},"interpolate-lab":{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},collator:{group:"Types"},format:{group:"Types"},image:{group:"Types"},"number-format":{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"feature-state":{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"line-progress":{group:"Feature data"},accumulated:{group:"Feature data"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},round:{group:"Math"},abs:{group:"Math"},ceil:{group:"Math"},floor:{group:"Math"},distance:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},within:{group:"Decision"},"is-supported-script":{group:"String"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"},"resolved-locale":{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}},zt=function(t,e,r,n){this.message=(t?t+": ":"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__);};function Ct(t){var e=t.value;return e?[new zt(t.key,e,"constants have been deprecated as of v8")]:[]}function Mt(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var Zt=[Vt,Ft,Dt,Lt,Rt,qt,Ot,Kt(Ut),Nt];function Xt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Xt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(var r=0,n=Zt;r255?255:t}function i(t){return n("%"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function a(t){return (e="%"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))<0?0:e>1?1:e;var e;}function o(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{e.parseCSSColor=function(t){var e,s=t.replace(/ /g,"").toLowerCase();if(s in r)return r[s].slice();if("#"===s[0])return 4===s.length?(e=parseInt(s.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===s.length&&(e=parseInt(s.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var u=s.indexOf("("),l=s.indexOf(")");if(-1!==u&&l+1===s.length){var p=s.substr(0,u),c=s.substr(u+1,l-(u+1)).split(","),h=1;switch(p){case"rgba":if(4!==c.length)return null;h=a(c.pop());case"rgb":return 3!==c.length?null:[i(c[0]),i(c[1]),i(c[2]),h];case"hsla":if(4!==c.length)return null;h=a(c.pop());case"hsl":if(3!==c.length)return null;var f=(parseFloat(c[0])%360+360)%360/360,y=a(c[1]),d=a(c[2]),m=d<=.5?d*(y+1):d+y-d*y,v=2*d-m;return [n(255*o(v,m,f+1/3)),n(255*o(v,m,f)),n(255*o(v,m,f-1/3)),h];default:return null}}return null};}catch(t){}})).parseCSSColor,$t=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n;};$t.parse=function(t){if(t){if(t instanceof $t)return t;if("string"==typeof t){var e=Yt(t);if(e)return new $t(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},$t.prototype.toString=function(){var t=this.toArray(),e=t[1],r=t[2],n=t[3];return "rgba("+Math.round(t[0])+","+Math.round(e)+","+Math.round(r)+","+n+")"},$t.prototype.toArray=function(){var t=this.a;return 0===t?[0,0,0,0]:[255*this.r/t,255*this.g/t,255*this.b/t,t]},$t.black=new $t(0,0,0,1),$t.white=new $t(1,1,1,1),$t.transparent=new $t(0,0,0,0),$t.red=new $t(1,0,0,1);var Wt=function(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});};Wt.prototype.compare=function(t,e){return this.collator.compare(t,e)},Wt.prototype.resolvedLocale=function(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale};var Qt=function(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;},te=function(t){this.sections=t;};te.fromString=function(t){return new te([new Qt(t,null,null,null,null)])},te.prototype.isEmpty=function(){return 0===this.sections.length||!this.sections.some((function(t){return 0!==t.text.length||t.image&&0!==t.image.name.length}))},te.factory=function(t){return t instanceof te?t:te.fromString(t)},te.prototype.toString=function(){return 0===this.sections.length?"":this.sections.map((function(t){return t.text})).join("")},te.prototype.serialize=function(){for(var t=["format"],e=0,r=this.sections;e=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."}function ne(t){if(null===t)return !0;if("string"==typeof t)return !0;if("boolean"==typeof t)return !0;if("number"==typeof t)return !0;if(t instanceof $t)return !0;if(t instanceof Wt)return !0;if(t instanceof te)return !0;if(t instanceof ee)return !0;if(Array.isArray(t)){for(var e=0,r=t;e2){var s=t[1];if("string"!=typeof s||!(s in ue)||"object"===s)return e.error('The item type argument of "array" must be one of string, number, boolean',1);a=ue[s],n++;}else a=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);o=t[2],n++;}r=Kt(a,o);}else r=ue[i];for(var u=[];n1)&&e.push(n);}}return e.concat(this.args.map((function(t){return t.serialize()})))};var pe=function(t){this.type=qt,this.sections=t;};pe.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");for(var n=[],i=!1,a=1;a<=t.length-1;++a){var o=t[a];if(i&&"object"==typeof o&&!Array.isArray(o)){i=!1;var s=null;if(o["font-scale"]&&!(s=e.parse(o["font-scale"],1,Ft)))return null;var u=null;if(o["text-font"]&&!(u=e.parse(o["text-font"],1,Kt(Dt))))return null;var l=null;if(o["text-color"]&&!(l=e.parse(o["text-color"],1,Rt)))return null;var p=n[n.length-1];p.scale=s,p.font=u,p.textColor=l;}else {var c=e.parse(t[a],1,Ut);if(!c)return null;var h=c.type.kind;if("string"!==h&&"value"!==h&&"null"!==h&&"resolvedImage"!==h)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:c,scale:null,font:null,textColor:null});}}return new pe(n)},pe.prototype.evaluate=function(t){return new te(this.sections.map((function(e){var r=e.content.evaluate(t);return ie(r)===Nt?new Qt("",r,null,null,null):new Qt(ae(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))},pe.prototype.eachChild=function(t){for(var e=0,r=this.sections;e-1),r},ce.prototype.eachChild=function(t){t(this.input);},ce.prototype.outputDefined=function(){return !1},ce.prototype.serialize=function(){return ["image",this.input.serialize()]};var he={"to-boolean":Lt,"to-color":Rt,"to-number":Ft,"to-string":Dt},fe=function(t,e){this.type=t,this.args=e;};fe.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[0];if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");for(var n=he[r],i=[],a=1;a4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":re(e[0],e[1],e[2],e[3])))return new $t(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new se(r||"Could not parse color from value '"+("string"==typeof e?e:String(JSON.stringify(e)))+"'")}if("number"===this.type.kind){for(var o=null,s=0,u=this.args;s=e[2]||t[1]<=e[1]||t[3]>=e[3])}function be(t,e){var r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*8192),Math.round(n*i*8192)]}function we(t,e,r){return e[1]>t[1]!=r[1]>t[1]&&t[0]<(r[0]-e[0])*(t[1]-e[1])/(r[1]-e[1])+e[0]}function _e(t,e){for(var r,n,i,a,o,s,u,l=!1,p=0,c=e.length;p0&&s<0||o<0&&s>0}function ke(t,e,r){for(var n=0,i=r;nr[2]){var i=.5*n,a=t[0]-r[0]>i?-n:r[0]-t[0]>i?n:0;0===a&&(a=t[0]-r[2]>i?-n:r[2]-t[0]>i?n:0),t[0]+=a;}ge(e,t);}function Te(t,e,r,n){for(var i=8192*Math.pow(2,n.z),a=[8192*n.x,8192*n.y],o=[],s=0,u=t;s=0)return !1;var r=!0;return t.eachChild((function(t){r&&!De(t,e)&&(r=!1);})),r}Be.parse=function(t,e){if(2!==t.length)return e.error("'within' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(ne(t[1])){var r=t[1];if("FeatureCollection"===r.type)for(var n=0;ne))throw new se("Input is not a number.");a=o-1;}return 0}Re.prototype.parse=function(t,e,r,n,i){return void 0===i&&(i={}),e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)},Re.prototype._parse=function(t,e){function r(t,e,r){return "assert"===r?new le(e,[t]):"coerce"===r?new fe(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var n=t[0];if("string"!=typeof n)return this.error("Expression name must be a string, but found "+typeof n+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var i=this.registry[n];if(i){var a=i.parse(t,this);if(!a)return null;if(this.expectedType){var o=this.expectedType,s=a.type;if("string"!==o.kind&&"number"!==o.kind&&"boolean"!==o.kind&&"object"!==o.kind&&"array"!==o.kind||"value"!==s.kind)if("color"!==o.kind&&"formatted"!==o.kind&&"resolvedImage"!==o.kind||"value"!==s.kind&&"string"!==s.kind){if(this.checkSubtype(o,s))return null}else a=r(a,o,e.typeAnnotation||"coerce");else a=r(a,o,e.typeAnnotation||"assert");}if(!(a instanceof oe)&&"resolvedImage"!==a.type.kind&&function t(e){if(e instanceof Le)return t(e.boundExpression);if(e instanceof me&&"error"===e.name)return !1;if(e instanceof ve)return !1;if(e instanceof Be)return !1;var r=e instanceof fe||e instanceof le,n=!0;return e.eachChild((function(e){n=r?n&&t(e):n&&e instanceof oe;})),!!n&&Ve(e)&&De(e,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}(a)){var u=new de;try{a=new oe(a.type,a.evaluate(u));}catch(t){return this.error(t.message),null}}return a}return this.error('Unknown expression "'+n+'". If you wanted a literal array, use ["literal", [...]].',0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':"Expected an array, but found "+typeof t+" instead.")},Re.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Re(this.registry,n,e||null,i,this.errors)},Re.prototype.error=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=""+this.key+e.map((function(t){return "["+t+"]"})).join("");this.errors.push(new Pt(n,t));},Re.prototype.checkSubtype=function(t,e){var r=Xt(t,e);return r&&this.error(r),r};var Ue=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n=o)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',u);var p=e.parse(s,l,i);if(!p)return null;i=i||p.type,n.push([o,p]);}return new Ue(i,r,n)},Ue.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[Oe(e,n)].evaluate(t)},Ue.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t};var qe=Object.freeze({__proto__:null,number:je,color:function(t,e,r){return new $t(je(t.r,e.r,r),je(t.g,e.g,r),je(t.b,e.b,r),je(t.a,e.a,r))},array:function(t,e,r){return t.map((function(t,n){return je(t,e[n],r)}))}}),Ne=6/29*3*(6/29),Ke=Math.PI/180,Ge=180/Math.PI;function Ze(t){return t>.008856451679035631?Math.pow(t,1/3):t/Ne+4/29}function Xe(t){return t>6/29?t*t*t:Ne*(t-4/29)}function Je(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function He(t){return (t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ye(t){var e=He(t.r),r=He(t.g),n=He(t.b),i=Ze((.4124564*e+.3575761*r+.1804375*n)/.95047),a=Ze((.2126729*e+.7151522*r+.072175*n)/1);return {l:116*a-16,a:500*(i-a),b:200*(a-Ze((.0193339*e+.119192*r+.9503041*n)/1.08883)),alpha:t.a}}function $e(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=1*Xe(e),r=.95047*Xe(r),n=1.08883*Xe(n),new $t(Je(3.2404542*r-1.5371385*e-.4985314*n),Je(-.969266*r+1.8760108*e+.041556*n),Je(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}function We(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}var Qe={forward:Ye,reverse:$e,interpolate:function(t,e,r){return {l:je(t.l,e.l,r),a:je(t.a,e.a,r),b:je(t.b,e.b,r),alpha:je(t.alpha,e.alpha,r)}}},tr={forward:function(t){var e=Ye(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*Ge;return {h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*Ke,r=t.c;return $e({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return {h:We(t.h,e.h,r),c:je(t.c,e.c,r),l:je(t.l,e.l,r),alpha:je(t.alpha,e.alpha,r)}}},er=Object.freeze({__proto__:null,lab:Qe,hcl:tr}),rr=function(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(var a=0,o=i;a1})))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:s};}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(i=e.parse(i,2,Ft)))return null;var u=[],l=null;"interpolate-hcl"===r||"interpolate-lab"===r?l=Rt:e.expectedType&&"value"!==e.expectedType.kind&&(l=e.expectedType);for(var p=0;p=c)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',f);var d=e.parse(h,y,l);if(!d)return null;l=l||d.type,u.push([c,d]);}return "number"===l.kind||"color"===l.kind||"array"===l.kind&&"number"===l.itemType.kind&&"number"==typeof l.N?new rr(l,r,n,i,u):e.error("Type "+Gt(l)+" is not interpolatable.")},rr.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var a=Oe(e,n),o=rr.interpolationFactor(this.interpolation,n,e[a],e[a+1]),s=r[a].evaluate(t),u=r[a+1].evaluate(t);return "interpolate"===this.operator?qe[this.type.kind.toLowerCase()](s,u,o):"interpolate-hcl"===this.operator?tr.reverse(tr.interpolate(tr.forward(s),tr.forward(u),o)):Qe.reverse(Qe.interpolate(Qe.forward(s),Qe.forward(u),o))},rr.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e=r.length)throw new se("Array index out of bounds: "+e+" > "+(r.length-1)+".");if(e!==Math.floor(e))throw new se("Array index must be an integer, but found "+e+" instead.");return r[e]},or.prototype.eachChild=function(t){t(this.index),t(this.input);},or.prototype.outputDefined=function(){return !1},or.prototype.serialize=function(){return ["at",this.index.serialize(),this.input.serialize()]};var sr=function(t,e){this.type=Lt,this.needle=t,this.haystack=e;};sr.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Jt(r.type,[Lt,Dt,Ft,Vt,Ut])?new sr(r,n):e.error("Expected first argument to be of type boolean, string, number or null, but found "+Gt(r.type)+" instead"):null},sr.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!Ht(e,["boolean","string","number","null"]))throw new se("Expected first argument to be of type boolean, string, number or null, but found "+Gt(ie(e))+" instead.");if(!Ht(r,["string","array"]))throw new se("Expected second argument to be of type array or string, but found "+Gt(ie(r))+" instead.");return r.indexOf(e)>=0},sr.prototype.eachChild=function(t){t(this.needle),t(this.haystack);},sr.prototype.outputDefined=function(){return !0},sr.prototype.serialize=function(){return ["in",this.needle.serialize(),this.haystack.serialize()]};var ur=function(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;};ur.parse=function(t,e){if(t.length<=2||t.length>=5)return e.error("Expected 3 or 4 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Jt(r.type,[Lt,Dt,Ft,Vt,Ut]))return e.error("Expected first argument to be of type boolean, string, number or null, but found "+Gt(r.type)+" instead");if(4===t.length){var i=e.parse(t[3],3,Ft);return i?new ur(r,n,i):null}return new ur(r,n)},ur.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!Ht(e,["boolean","string","number","null"]))throw new se("Expected first argument to be of type boolean, string, number or null, but found "+Gt(ie(e))+" instead.");if(!Ht(r,["string","array"]))throw new se("Expected second argument to be of type array or string, but found "+Gt(ie(r))+" instead.");if(this.fromIndex){var n=this.fromIndex.evaluate(t);return r.indexOf(e,n)}return r.indexOf(e)},ur.prototype.eachChild=function(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);},ur.prototype.outputDefined=function(){return !1},ur.prototype.serialize=function(){if(null!=this.fromIndex&&void 0!==this.fromIndex){var t=this.fromIndex.serialize();return ["index-of",this.needle.serialize(),this.haystack.serialize(),t]}return ["index-of",this.needle.serialize(),this.haystack.serialize()]};var lr=function(t,e,r,n,i,a){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=a;};lr.parse=function(t,e){if(t.length<5)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if(t.length%2!=1)return e.error("Expected an even number of arguments.");var r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);for(var i={},a=[],o=2;oNumber.MAX_SAFE_INTEGER)return l.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof h&&Math.floor(h)!==h)return l.error("Numeric branch labels must be integer values.");if(r){if(l.checkSubtype(r,ie(h)))return null}else r=ie(h);if(void 0!==i[String(h)])return l.error("Branch labels must be unique.");i[String(h)]=a.length;}var f=e.parse(u,o,n);if(!f)return null;n=n||f.type,a.push(f);}var y=e.parse(t[1],1,Ut);if(!y)return null;var d=e.parse(t[t.length-1],t.length-1,n);return d?"value"!==y.type.kind&&e.concat(1).checkSubtype(r,y.type)?null:new lr(r,n,y,i,a,d):null},lr.prototype.evaluate=function(t){var e=this.input.evaluate(t);return (ie(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},lr.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);},lr.prototype.outputDefined=function(){return this.outputs.every((function(t){return t.outputDefined()}))&&this.otherwise.outputDefined()},lr.prototype.serialize=function(){for(var t=this,e=["match",this.input.serialize()],r=[],n={},i=0,a=Object.keys(this.cases).sort();i=5)return e.error("Expected 3 or 4 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Jt(r.type,[Kt(Ut),Dt,Ut]))return e.error("Expected first argument to be of type array or string, but found "+Gt(r.type)+" instead");if(4===t.length){var i=e.parse(t[3],3,Ft);return i?new cr(r.type,r,n,i):null}return new cr(r.type,r,n)},cr.prototype.evaluate=function(t){var e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);if(!Ht(e,["string","array"]))throw new se("Expected first argument to be of type array or string, but found "+Gt(ie(e))+" instead.");if(this.endIndex){var n=this.endIndex.evaluate(t);return e.slice(r,n)}return e.slice(r)},cr.prototype.eachChild=function(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);},cr.prototype.outputDefined=function(){return !1},cr.prototype.serialize=function(){if(null!=this.endIndex&&void 0!==this.endIndex){var t=this.endIndex.serialize();return ["slice",this.input.serialize(),this.beginIndex.serialize(),t]}return ["slice",this.input.serialize(),this.beginIndex.serialize()]};var dr=yr("==",(function(t,e,r){return e===r}),fr),mr=yr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !fr(0,e,r,n)})),vr=yr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),xr=yr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),br=yr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0})),wr=function(t,e,r,n,i){this.type=Dt,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;};wr.parse=function(t,e){if(3!==t.length)return e.error("Expected two arguments.");var r=e.parse(t[1],1,Ft);if(!r)return null;var n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");var i=null;if(n.locale&&!(i=e.parse(n.locale,1,Dt)))return null;var a=null;if(n.currency&&!(a=e.parse(n.currency,1,Dt)))return null;var o=null;if(n["min-fraction-digits"]&&!(o=e.parse(n["min-fraction-digits"],1,Ft)))return null;var s=null;return n["max-fraction-digits"]&&!(s=e.parse(n["max-fraction-digits"],1,Ft))?null:new wr(r,i,a,o,s)},wr.prototype.evaluate=function(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))},wr.prototype.eachChild=function(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);},wr.prototype.outputDefined=function(){return !1},wr.prototype.serialize=function(){var t={};return this.locale&&(t.locale=this.locale.serialize()),this.currency&&(t.currency=this.currency.serialize()),this.minFractionDigits&&(t["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(t["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),t]};var _r=function(t){this.type=Ft,this.input=t;};_r.parse=function(t,e){if(2!==t.length)return e.error("Expected 1 argument, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error("Expected argument of type string or array, but found "+Gt(r.type)+" instead."):new _r(r):null},_r.prototype.evaluate=function(t){var e=this.input.evaluate(t);if("string"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new se("Expected value to be of type string or array, but found "+Gt(ie(e))+" instead.")},_r.prototype.eachChild=function(t){t(this.input);},_r.prototype.outputDefined=function(){return !1},_r.prototype.serialize=function(){var t=["length"];return this.eachChild((function(e){t.push(e.serialize());})),t};var Ar={"==":dr,"!=":mr,">":gr,"<":vr,">=":br,"<=":xr,array:le,at:or,boolean:le,case:pr,coalesce:ir,collator:ve,format:pe,image:ce,in:sr,"index-of":ur,interpolate:rr,"interpolate-hcl":rr,"interpolate-lab":rr,length:_r,let:ar,literal:oe,match:lr,number:le,"number-format":wr,object:le,slice:cr,step:Ue,string:le,"to-boolean":fe,"to-color":fe,"to-number":fe,"to-string":fe,var:Le,within:Be};function Sr(t,e){var r=e[0],n=e[1],i=e[2],a=e[3];r=r.evaluate(t),n=n.evaluate(t),i=i.evaluate(t);var o=a?a.evaluate(t):1,s=re(r,n,i,o);if(s)throw new se(s);return new $t(r/255*o,n/255*o,i/255*o,o)}function kr(t,e){return t in e}function Ir(t,e){var r=e[t];return void 0===r?null:r}function zr(t){return {type:t}}function Cr(t){return {result:"success",value:t}}function Mr(t){return {result:"error",value:t}}function Er(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Tr(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Pr(t){return !!t.expression&&t.expression.interpolated}function Br(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Vr(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)}function Fr(t){return t}function Dr(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Lr(t,e,r,n,i){return Dr(typeof r===i?n[r]:void 0,t.default,e.default)}function Rr(t,e,r){if("number"!==Br(r))return Dr(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var i=Oe(t.stops.map((function(t){return t[0]})),r);return t.stops[i][1]}function Or(t,e,r){var n=void 0!==t.base?t.base:1;if("number"!==Br(r))return Dr(t.default,e.default);var i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];var a=Oe(t.stops.map((function(t){return t[0]})),r),o=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[a][0],t.stops[a+1][0]),s=t.stops[a][1],u=t.stops[a+1][1],l=qe[e.type]||Fr;if(t.colorSpace&&"rgb"!==t.colorSpace){var p=er[t.colorSpace];l=function(t,e){return p.reverse(p.interpolate(p.forward(t),p.forward(e),o))};}return "function"==typeof s.evaluate?{evaluate:function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var r=s.evaluate.apply(void 0,t),n=u.evaluate.apply(void 0,t);if(void 0!==r&&void 0!==n)return l(r,n,o)}}:l(s,u,o)}function Ur(t,e,r){return "color"===e.type?r=$t.parse(r):"formatted"===e.type?r=te.fromString(r.toString()):"resolvedImage"===e.type?r=ee.fromString(r.toString()):Br(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),Dr(r,t.default,e.default)}me.register(Ar,{error:[{kind:"error"},[Dt],function(t,e){throw new se(e[0].evaluate(t))}],typeof:[Dt,[Ut],function(t,e){return Gt(ie(e[0].evaluate(t)))}],"to-rgba":[Kt(Ft,4),[Rt],function(t,e){return e[0].evaluate(t).toArray()}],rgb:[Rt,[Ft,Ft,Ft],Sr],rgba:[Rt,[Ft,Ft,Ft,Ft],Sr],has:{type:Lt,overloads:[[[Dt],function(t,e){return kr(e[0].evaluate(t),t.properties())}],[[Dt,Ot],function(t,e){var r=e[1];return kr(e[0].evaluate(t),r.evaluate(t))}]]},get:{type:Ut,overloads:[[[Dt],function(t,e){return Ir(e[0].evaluate(t),t.properties())}],[[Dt,Ot],function(t,e){var r=e[1];return Ir(e[0].evaluate(t),r.evaluate(t))}]]},"feature-state":[Ut,[Dt],function(t,e){return Ir(e[0].evaluate(t),t.featureState||{})}],properties:[Ot,[],function(t){return t.properties()}],"geometry-type":[Dt,[],function(t){return t.geometryType()}],id:[Ut,[],function(t){return t.id()}],zoom:[Ft,[],function(t){return t.globals.zoom}],"heatmap-density":[Ft,[],function(t){return t.globals.heatmapDensity||0}],"line-progress":[Ft,[],function(t){return t.globals.lineProgress||0}],accumulated:[Ut,[],function(t){return void 0===t.globals.accumulated?null:t.globals.accumulated}],"+":[Ft,zr(Ft),function(t,e){for(var r=0,n=0,i=e;n":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[Lt,[Ut],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[Lt,[],function(t){return null!==t.id()&&void 0!==t.id()}],"filter-type-in":[Lt,[Kt(Dt)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[Lt,[Kt(Ut)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[Lt,[Dt,Kt(Ut)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[Lt,[Dt,Kt(Ut)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[r.value],n.value,0,n.value.length-1)}],all:{type:Lt,overloads:[[[Lt,Lt],function(t,e){var r=e[1];return e[0].evaluate(t)&&r.evaluate(t)}],[zr(Lt),function(t,e){for(var r=0,n=e;r0&&"string"==typeof t[0]&&t[0]in Ar}function Nr(t,e){var r=new Re(Ar,[],e?function(t){var e={color:Rt,string:Dt,number:Ft,enum:Dt,boolean:Lt,formatted:qt,resolvedImage:Nt};return "array"===t.type?Kt(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),n=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return n?Cr(new jr(n,e)):Mr(r.errors)}jr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a,this.expression.evaluate(this._evaluator)},jr.prototype.evaluate=function(t,e,r,n,i,a){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a||null;try{var o=this.expression.evaluate(this._evaluator);if(null==o||"number"==typeof o&&o!=o)return this._defaultValue;if(this._enumValues&&!(o in this._enumValues))throw new se("Expected value to be one of "+Object.keys(this._enumValues).map((function(t){return JSON.stringify(t)})).join(", ")+", but found "+JSON.stringify(o)+" instead.");return o}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}};var Kr=function(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Fe(e.expression);};Kr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,a)},Kr.prototype.evaluate=function(t,e,r,n,i,a){return this._styleExpression.evaluate(t,e,r,n,i,a)};var Gr=function(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Fe(e.expression),this.interpolationType=n;};function Zr(t,e){if("error"===(t=Nr(t,e)).result)return t;var r=t.value.expression,n=Ve(r);if(!n&&!Er(e))return Mr([new Pt("","data expressions not supported")]);var i=De(r,["zoom"]);if(!i&&!Tr(e))return Mr([new Pt("","zoom expressions not supported")]);var a=function t(e){var r=null;if(e instanceof ar)r=t(e.result);else if(e instanceof ir)for(var n=0,i=e.args;nn.maximum?[new zt(e,r,r+" is greater than the maximum value "+n.maximum)]:[]}function $r(t){var e,r,n,i=t.valueSpec,a=Et(t.value.type),o={},s="categorical"!==a&&void 0===t.value.property,u=!s,l="array"===Br(t.value.stops)&&"array"===Br(t.value.stops[0])&&"object"===Br(t.value.stops[0][0]),p=Jr({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===a)return [new zt(t.key,t.value,'identity function may not have a "stops" property')];var e=[],r=t.value;return e=e.concat(Hr({key:t.key,value:r,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:c})),"array"===Br(r)&&0===r.length&&e.push(new zt(t.key,r,"array must have at least one stop")),e},default:function(t){return bn({key:t.key,value:t.value,valueSpec:i,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===a&&s&&p.push(new zt(t.key,t.value,'missing required property "property"')),"identity"===a||t.value.stops||p.push(new zt(t.key,t.value,'missing required property "stops"')),"exponential"===a&&t.valueSpec.expression&&!Pr(t.valueSpec)&&p.push(new zt(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(u&&!Er(t.valueSpec)?p.push(new zt(t.key,t.value,"property functions not supported")):s&&!Tr(t.valueSpec)&&p.push(new zt(t.key,t.value,"zoom functions not supported"))),"categorical"!==a&&!l||void 0!==t.value.property||p.push(new zt(t.key,t.value,'"property" property is required')),p;function c(t){var e=[],a=t.value,s=t.key;if("array"!==Br(a))return [new zt(s,a,"array expected, "+Br(a)+" found")];if(2!==a.length)return [new zt(s,a,"array length 2 expected, length "+a.length+" found")];if(l){if("object"!==Br(a[0]))return [new zt(s,a,"object expected, "+Br(a[0])+" found")];if(void 0===a[0].zoom)return [new zt(s,a,"object stop key must have zoom")];if(void 0===a[0].value)return [new zt(s,a,"object stop key must have value")];if(n&&n>Et(a[0].zoom))return [new zt(s,a[0].zoom,"stop zoom values must appear in ascending order")];Et(a[0].zoom)!==n&&(n=Et(a[0].zoom),r=void 0,o={}),e=e.concat(Jr({key:s+"[0]",value:a[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Yr,value:h}}));}else e=e.concat(h({key:s+"[0]",value:a[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},a));return qr(Tt(a[1]))?e.concat([new zt(s+"[1]",a[1],"expressions are not allowed in function stops.")]):e.concat(bn({key:s+"[1]",value:a[1],valueSpec:i,style:t.style,styleSpec:t.styleSpec}))}function h(t,n){var s=Br(t.value),u=Et(t.value),l=null!==t.value?t.value:n;if(e){if(s!==e)return [new zt(t.key,l,s+" stop domain type must match previous stop domain type "+e)]}else e=s;if("number"!==s&&"string"!==s&&"boolean"!==s)return [new zt(t.key,l,"stop domain value must be a number, string, or boolean")];if("number"!==s&&"categorical"!==a){var p="number expected, "+s+" found";return Er(i)&&void 0===a&&(p+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new zt(t.key,l,p)]}return "categorical"!==a||"number"!==s||isFinite(u)&&Math.floor(u)===u?"categorical"!==a&&"number"===s&&void 0!==r&&u=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return !1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(var e=0,r=t.slice(1);ee?1:0}function an(t){if(!t)return !0;var e,r=t[0];return t.length<=1?"any"!==r:"=="===r?on(t[1],t[2],"=="):"!="===r?ln(on(t[1],t[2],"==")):"<"===r||">"===r||"<="===r||">="===r?on(t[1],t[2],r):"any"===r?(e=t.slice(1),["any"].concat(e.map(an))):"all"===r?["all"].concat(t.slice(1).map(an)):"none"===r?["all"].concat(t.slice(1).map(an).map(ln)):"in"===r?sn(t[1],t.slice(2)):"!in"===r?ln(sn(t[1],t.slice(2))):"has"===r?un(t[1]):"!has"===r?ln(un(t[1])):"within"!==r||t}function on(t,e,r){switch(t){case"$type":return ["filter-type-"+r,e];case"$id":return ["filter-id-"+r,e];default:return ["filter-"+r,t,e]}}function sn(t,e){if(0===e.length)return !1;switch(t){case"$type":return ["filter-type-in",["literal",e]];case"$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((function(t){return typeof t!=typeof e[0]}))?["filter-in-large",t,["literal",e.sort(nn)]]:["filter-in-small",t,["literal",e]]}}function un(t){switch(t){case"$type":return !0;case"$id":return ["filter-has-id"];default:return ["filter-has",t]}}function ln(t){return ["!",t]}function pn(t){return tn(Tt(t.value))?Wr(Mt({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):function t(e){var r=e.value,n=e.key;if("array"!==Br(r))return [new zt(n,r,"array expected, "+Br(r)+" found")];var i,a=e.styleSpec,o=[];if(r.length<1)return [new zt(n,r,"filter array must have at least 1 element")];switch(o=o.concat(Qr({key:n+"[0]",value:r[0],valueSpec:a.filter_operator,style:e.style,styleSpec:e.styleSpec})),Et(r[0])){case"<":case"<=":case">":case">=":r.length>=2&&"$type"===Et(r[1])&&o.push(new zt(n,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&o.push(new zt(n,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(i=Br(r[1]))&&o.push(new zt(n+"[1]",r[1],"string expected, "+i+" found"));for(var s=2;s=p[f+0]&&n>=p[f+1])?(o[h]=!0,a.push(l[h])):o[h]=!1;}}},Tn.prototype._forEachCell=function(t,e,r,n,i,a,o,s){for(var u=this._convertToCellCoord(t),l=this._convertToCellCoord(e),p=this._convertToCellCoord(r),c=this._convertToCellCoord(n),h=u;h<=p;h++)for(var f=l;f<=c;f++){var y=this.d*f+h;if((!s||s(this._convertFromCellCoord(h),this._convertFromCellCoord(f),this._convertFromCellCoord(h+1),this._convertFromCellCoord(f+1)))&&i.call(this,t,e,r,n,y,a,o,s))return}},Tn.prototype._convertFromCellCoord=function(t){return (t-this.padding)/this.scale},Tn.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},Tn.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=3+this.cells.length+1+1,r=0,n=0;n=0)){var p=t[l];u[l]=Vn[s].shallow.indexOf(l)>=0?p:On(p,e);}t instanceof Error&&(u.message=t.message);}if(u.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==s&&(u.$name=s),u}throw new Error("can't serialize object of type "+typeof t)}function Un(t){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||Ln(t)||Rn(t)||ArrayBuffer.isView(t)||t instanceof Pn)return t;if(Array.isArray(t))return t.map(Un);if("object"==typeof t){var e=t.$name||"Object",r=Vn[e].klass;if(!r)throw new Error("can't deserialize unregistered class "+e);if(r.deserialize)return r.deserialize(t);for(var n=Object.create(r.prototype),i=0,a=Object.keys(t);i=0?s:Un(s);}}return n}throw new Error("can't deserialize object of type "+typeof t)}var jn=function(){this.first=!0;};jn.prototype.update=function(t,e){var r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},Khmer:function(t){return t>=6016&&t<=6143},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}};function Nn(t){for(var e=0,r=t;e=65097&&t<=65103)||qn["CJK Compatibility Ideographs"](t)||qn["CJK Compatibility"](t)||qn["CJK Radicals Supplement"](t)||qn["CJK Strokes"](t)||!(!qn["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||qn["CJK Unified Ideographs Extension A"](t)||qn["CJK Unified Ideographs"](t)||qn["Enclosed CJK Letters and Months"](t)||qn["Hangul Compatibility Jamo"](t)||qn["Hangul Jamo Extended-A"](t)||qn["Hangul Jamo Extended-B"](t)||qn["Hangul Jamo"](t)||qn["Hangul Syllables"](t)||qn.Hiragana(t)||qn["Ideographic Description Characters"](t)||qn.Kanbun(t)||qn["Kangxi Radicals"](t)||qn["Katakana Phonetic Extensions"](t)||qn.Katakana(t)&&12540!==t||!(!qn["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!qn["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||qn["Unified Canadian Aboriginal Syllabics"](t)||qn["Unified Canadian Aboriginal Syllabics Extended"](t)||qn["Vertical Forms"](t)||qn["Yijing Hexagram Symbols"](t)||qn["Yi Syllables"](t)||qn["Yi Radicals"](t))))}function Gn(t){return !(Kn(t)||function(t){return !!(qn["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||qn["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||qn["Letterlike Symbols"](t)||qn["Number Forms"](t)||qn["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||qn["Control Pictures"](t)&&9251!==t||qn["Optical Character Recognition"](t)||qn["Enclosed Alphanumerics"](t)||qn["Geometric Shapes"](t)||qn["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||qn["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||qn["CJK Symbols and Punctuation"](t)||qn.Katakana(t)||qn["Private Use Area"](t)||qn["CJK Compatibility Forms"](t)||qn["Small Form Variants"](t)||qn["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}function Zn(t){return t>=1424&&t<=2303||qn["Arabic Presentation Forms-A"](t)||qn["Arabic Presentation Forms-B"](t)}function Xn(t,e){return !(!e&&Zn(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||qn.Khmer(t))}function Jn(t){for(var e=0,r=t;e-1&&(Yn="error"),Hn&&Hn(t);};function Qn(){ti.fire(new At("pluginStateChange",{pluginStatus:Yn,pluginURL:$n}));}var ti=new kt,ei=function(){return Yn},ri=function(){if("deferred"!==Yn||!$n)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Yn="loading",Qn(),$n&>({url:$n},(function(t){t?Wn(t):(Yn="loaded",Qn());}));},ni={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:function(){return "loaded"===Yn||null!=ni.applyArabicShaping},isLoading:function(){return "loading"===Yn},setState:function(t){Yn=t.pluginStatus,$n=t.pluginURL;},isParsed:function(){return null!=ni.applyArabicShaping&&null!=ni.processBidirectionalText&&null!=ni.processStyledBidirectionalText},getPluginURL:function(){return $n}},ii=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new jn,this.transition={});};ii.prototype.isSupportedScript=function(t){return function(t,e){for(var r=0,n=t;rthis.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}};var ai=function(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(Vr(t))return new Xr(t,e);if(qr(t)){var r=Zr(t,e);if("error"===r.result)throw new Error(r.value.map((function(t){return t.key+": "+t.message})).join(", "));return r.value}var n=t;return "string"==typeof t&&"color"===e.type&&(n=$t.parse(t)),{kind:"constant",evaluate:function(){return n}}}(void 0===e?t.specification.default:e,t.specification);};ai.prototype.isDataDriven=function(){return "source"===this.expression.kind||"composite"===this.expression.kind},ai.prototype.possiblyEvaluate=function(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)};var oi=function(t){this.property=t,this.value=new ai(t,void 0);};oi.prototype.transitioned=function(t,e){return new ui(this.property,this.value,e,p({},t.transition,this.transition),t.now)},oi.prototype.untransitioned=function(){return new ui(this.property,this.value,null,{},0)};var si=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);};si.prototype.getValue=function(t){return x(this._values[t].value.value)},si.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new oi(this._values[t].property)),this._values[t].value=new ai(this._values[t].property,null===e?void 0:x(e));},si.prototype.getTransition=function(t){return x(this._values[t].transition)},si.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new oi(this._values[t].property)),this._values[t].transition=x(e)||void 0;},si.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);ethis.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(n=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(o))}return i};var li=function(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues);};li.prototype.possiblyEvaluate=function(t,e,r){for(var n=new hi(this._properties),i=0,a=Object.keys(this._values);in.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},e.prototype.interpolate=function(t){return t},e}(yi),mi=function(t){this.specification=t;};mi.prototype.possiblyEvaluate=function(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){var i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new ii(Math.floor(e.zoom-1),e)),t.expression.evaluate(new ii(Math.floor(e.zoom),e)),t.expression.evaluate(new ii(Math.floor(e.zoom+1),e)),e)}},mi.prototype._calculate=function(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},mi.prototype.interpolate=function(t){return t};var vi=function(t){this.specification=t;};vi.prototype.possiblyEvaluate=function(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)},vi.prototype.interpolate=function(){return !1};var gi=function(t){for(var e in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[],t){var r=t[e];r.specification.overridable&&this.overridableProperties.push(e);var n=this.defaultPropertyValues[e]=new ai(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new oi(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}};Fn("DataDrivenProperty",yi),Fn("DataConstantProperty",fi),Fn("CrossFadedDataDrivenProperty",di),Fn("CrossFadedProperty",mi),Fn("ColorRampProperty",vi);var xi=function(t){function e(e,r){if(t.call(this),this.id=e.id,this.type=e.type,this._featureFilter={filter:function(){return !0},needGeometry:!1},"custom"!==e.type&&(this.metadata=(e=e).metadata,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,"background"!==e.type&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter),r.layout&&(this._unevaluatedLayout=new pi(r.layout)),r.paint)){for(var n in this._transitionablePaint=new si(r.paint),e.paint)this.setPaintProperty(n,e.paint[n],{validate:!1});for(var i in e.layout)this.setLayoutProperty(i,e.layout[i],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new hi(r.paint);}}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getCrossfadeParameters=function(){return this._crossfadeParameters},e.prototype.getLayoutProperty=function(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)},e.prototype.setLayoutProperty=function(t,e,r){void 0===r&&(r={}),null!=e&&this._validate(Cn,"layers."+this.id+".layout."+t,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);},e.prototype.getPaintProperty=function(t){return m(t,"-transition")?this._transitionablePaint.getTransition(t.slice(0,-"-transition".length)):this._transitionablePaint.getValue(t)},e.prototype.setPaintProperty=function(t,e,r){if(void 0===r&&(r={}),null!=e&&this._validate(zn,"layers."+this.id+".paint."+t,t,e,r))return !1;if(m(t,"-transition"))return this._transitionablePaint.setTransition(t.slice(0,-"-transition".length),e||void 0),!1;var n=this._transitionablePaint._values[t],i="cross-faded-data-driven"===n.property.specification["property-type"],a=n.value.isDataDriven(),o=n.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);var s=this._transitionablePaint._values[t].value;return s.isDataDriven()||a||i||this._handleOverridablePaintPropertyUpdate(t,o,s)},e.prototype._handleSpecialPaintPropertyUpdate=function(t){},e.prototype._handleOverridablePaintPropertyUpdate=function(t,e,r){return !1},e.prototype.isHidden=function(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),g(t,(function(t,e){return !(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)}))},e.prototype._validate=function(t,e,r,n,i){return void 0===i&&(i={}),(!i||!1!==i.validate)&&Mn(this,t.call(kn,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:It,style:{glyphs:!0,sprite:!0}}))},e.prototype.is3D=function(){return !1},e.prototype.isTileClipped=function(){return !1},e.prototype.hasOffscreenPass=function(){return !1},e.prototype.resize=function(){},e.prototype.isStateDependent=function(){for(var t in this.paint._values){var e=this.paint.get(t);if(e instanceof ci&&Er(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1},e}(kt),bi={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},wi=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;},_i=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0);};function Ai(t,e){void 0===e&&(e=1);var r=0,n=0;return {members:t.map((function(t){var i=bi[t.type].BYTES_PER_ELEMENT,a=r=Si(r,Math.max(e,i)),o=t.components||1;return n=Math.max(n,i),r+=i*o,{name:t.name,type:t.type,components:o,offset:a}})),size:Si(r,Math.max(n,e)),alignment:e}}function Si(t,e){return Math.ceil(t/e)*e}_i.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},_i.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},_i.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());},_i.prototype.clear=function(){this.length=0;},_i.prototype.resize=function(t){this.reserve(t),this.length=t;},_i.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}},_i.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")};var ki=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t},e}(_i);ki.prototype.bytesPerElement=4,Fn("StructArrayLayout2i4",ki);var Ii=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.int16[a+2]=n,this.int16[a+3]=i,t},e}(_i);Ii.prototype.bytesPerElement=8,Fn("StructArrayLayout4i8",Ii);var zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(_i);zi.prototype.bytesPerElement=12,Fn("StructArrayLayout2i4i12",zi);var Ci=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=4*t,u=8*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.uint8[u+4]=n,this.uint8[u+5]=i,this.uint8[u+6]=a,this.uint8[u+7]=o,t},e}(_i);Ci.prototype.bytesPerElement=8,Fn("StructArrayLayout2i4ub8",Ci);var Mi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l){var p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,a,o,s,u,l)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p){var c=9*t,h=18*t;return this.uint16[c+0]=e,this.uint16[c+1]=r,this.uint16[c+2]=n,this.uint16[c+3]=i,this.uint16[c+4]=a,this.uint16[c+5]=o,this.uint16[c+6]=s,this.uint16[c+7]=u,this.uint8[h+16]=l,this.uint8[h+17]=p,t},e}(_i);Mi.prototype.bytesPerElement=18,Fn("StructArrayLayout8ui2ub18",Mi);var Ei=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c){var h=this.length;return this.resize(h+1),this.emplace(h,t,e,r,n,i,a,o,s,u,l,p,c)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h){var f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=a,this.uint16[f+5]=o,this.uint16[f+6]=s,this.uint16[f+7]=u,this.int16[f+8]=l,this.int16[f+9]=p,this.int16[f+10]=c,this.int16[f+11]=h,t},e}(_i);Ei.prototype.bytesPerElement=24,Fn("StructArrayLayout4i4ui4i24",Ei);var Ti=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t},e}(_i);Ti.prototype.bytesPerElement=12,Fn("StructArrayLayout3f12",Ti);var Pi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.uint32[1*t+0]=e,t},e}(_i);Pi.prototype.bytesPerElement=4,Fn("StructArrayLayout1ul4",Pi);var Bi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u){var l=this.length;return this.resize(l+1),this.emplace(l,t,e,r,n,i,a,o,s,u)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l){var p=10*t,c=5*t;return this.int16[p+0]=e,this.int16[p+1]=r,this.int16[p+2]=n,this.int16[p+3]=i,this.int16[p+4]=a,this.int16[p+5]=o,this.uint32[c+3]=s,this.uint16[p+8]=u,this.uint16[p+9]=l,t},e}(_i);Bi.prototype.bytesPerElement=20,Fn("StructArrayLayout6i1ul2ui20",Bi);var Vi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(_i);Vi.prototype.bytesPerElement=12,Fn("StructArrayLayout2i2i2i12",Vi);var Fi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i){var a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i)},e.prototype.emplace=function(t,e,r,n,i,a){var o=4*t,s=8*t;return this.float32[o+0]=e,this.float32[o+1]=r,this.float32[o+2]=n,this.int16[s+6]=i,this.int16[s+7]=a,t},e}(_i);Fi.prototype.bytesPerElement=16,Fn("StructArrayLayout2f1f2i16",Fi);var Di=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=12*t,o=3*t;return this.uint8[a+0]=e,this.uint8[a+1]=r,this.float32[o+1]=n,this.float32[o+2]=i,t},e}(_i);Di.prototype.bytesPerElement=12,Fn("StructArrayLayout2ub2f12",Di);var Li=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t},e}(_i);Li.prototype.bytesPerElement=6,Fn("StructArrayLayout3ui6",Li);var Ri=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m){var v=this.length;return this.resize(v+1),this.emplace(v,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v){var g=24*t,x=12*t,b=48*t;return this.int16[g+0]=e,this.int16[g+1]=r,this.uint16[g+2]=n,this.uint16[g+3]=i,this.uint32[x+2]=a,this.uint32[x+3]=o,this.uint32[x+4]=s,this.uint16[g+10]=u,this.uint16[g+11]=l,this.uint16[g+12]=p,this.float32[x+7]=c,this.float32[x+8]=h,this.uint8[b+36]=f,this.uint8[b+37]=y,this.uint8[b+38]=d,this.uint32[x+10]=m,this.int16[g+22]=v,t},e}(_i);Ri.prototype.bytesPerElement=48,Fn("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Ri);var Oi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z){var C=this.length;return this.resize(C+1),this.emplace(C,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z,C){var M=34*t,E=17*t;return this.int16[M+0]=e,this.int16[M+1]=r,this.int16[M+2]=n,this.int16[M+3]=i,this.int16[M+4]=a,this.int16[M+5]=o,this.int16[M+6]=s,this.int16[M+7]=u,this.uint16[M+8]=l,this.uint16[M+9]=p,this.uint16[M+10]=c,this.uint16[M+11]=h,this.uint16[M+12]=f,this.uint16[M+13]=y,this.uint16[M+14]=d,this.uint16[M+15]=m,this.uint16[M+16]=v,this.uint16[M+17]=g,this.uint16[M+18]=x,this.uint16[M+19]=b,this.uint16[M+20]=w,this.uint16[M+21]=_,this.uint16[M+22]=A,this.uint32[E+12]=S,this.float32[E+13]=k,this.float32[E+14]=I,this.float32[E+15]=z,this.float32[E+16]=C,t},e}(_i);Oi.prototype.bytesPerElement=68,Fn("StructArrayLayout8i15ui1ul4f68",Oi);var Ui=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.float32[1*t+0]=e,t},e}(_i);Ui.prototype.bytesPerElement=4,Fn("StructArrayLayout1f4",Ui);var ji=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t},e}(_i);ji.prototype.bytesPerElement=6,Fn("StructArrayLayout3i6",ji);var qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t},e}(_i);qi.prototype.bytesPerElement=8,Fn("StructArrayLayout1ul2ui8",qi);var Ni=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t},e}(_i);Ni.prototype.bytesPerElement=4,Fn("StructArrayLayout2ui4",Ni);var Ki=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.uint16[1*t+0]=e,t},e}(_i);Ki.prototype.bytesPerElement=2,Fn("StructArrayLayout1ui2",Ki);var Gi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t},e}(_i);Gi.prototype.bytesPerElement=8,Fn("StructArrayLayout2f8",Gi);var Zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.float32[a+3]=i,t},e}(_i);Zi.prototype.bytesPerElement=16,Fn("StructArrayLayout4f16",Zi);var Xi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorPointX:{configurable:!0},anchorPointY:{configurable:!0},x1:{configurable:!0},y1:{configurable:!0},x2:{configurable:!0},y2:{configurable:!0},featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0},anchorPoint:{configurable:!0}};return r.anchorPointX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorPointY.get=function(){return this._structArray.int16[this._pos2+1]},r.x1.get=function(){return this._structArray.int16[this._pos2+2]},r.y1.get=function(){return this._structArray.int16[this._pos2+3]},r.x2.get=function(){return this._structArray.int16[this._pos2+4]},r.y2.get=function(){return this._structArray.int16[this._pos2+5]},r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+8]},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.anchorPoint.get=function(){return new i(this.anchorPointX,this.anchorPointY)},Object.defineProperties(e.prototype,r),e}(wi);Xi.prototype.size=20;var Ji=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Xi(this,t)},e}(Bi);Fn("CollisionBoxArray",Ji);var Hi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},glyphStartIndex:{configurable:!0},numGlyphs:{configurable:!0},vertexStartIndex:{configurable:!0},lineStartIndex:{configurable:!0},lineLength:{configurable:!0},segment:{configurable:!0},lowerSize:{configurable:!0},upperSize:{configurable:!0},lineOffsetX:{configurable:!0},lineOffsetY:{configurable:!0},writingMode:{configurable:!0},placedOrientation:{configurable:!0},hidden:{configurable:!0},crossTileID:{configurable:!0},associatedIconIndex:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.glyphStartIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.numGlyphs.get=function(){return this._structArray.uint16[this._pos2+3]},r.vertexStartIndex.get=function(){return this._structArray.uint32[this._pos4+2]},r.lineStartIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.lineLength.get=function(){return this._structArray.uint32[this._pos4+4]},r.segment.get=function(){return this._structArray.uint16[this._pos2+10]},r.lowerSize.get=function(){return this._structArray.uint16[this._pos2+11]},r.upperSize.get=function(){return this._structArray.uint16[this._pos2+12]},r.lineOffsetX.get=function(){return this._structArray.float32[this._pos4+7]},r.lineOffsetY.get=function(){return this._structArray.float32[this._pos4+8]},r.writingMode.get=function(){return this._structArray.uint8[this._pos1+36]},r.placedOrientation.get=function(){return this._structArray.uint8[this._pos1+37]},r.placedOrientation.set=function(t){this._structArray.uint8[this._pos1+37]=t;},r.hidden.get=function(){return this._structArray.uint8[this._pos1+38]},r.hidden.set=function(t){this._structArray.uint8[this._pos1+38]=t;},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+10]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+10]=t;},r.associatedIconIndex.get=function(){return this._structArray.int16[this._pos2+22]},Object.defineProperties(e.prototype,r),e}(wi);Hi.prototype.size=48;var Yi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Hi(this,t)},e}(Ri);Fn("PlacedSymbolArray",Yi);var $i=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},rightJustifiedTextSymbolIndex:{configurable:!0},centerJustifiedTextSymbolIndex:{configurable:!0},leftJustifiedTextSymbolIndex:{configurable:!0},verticalPlacedTextSymbolIndex:{configurable:!0},placedIconSymbolIndex:{configurable:!0},verticalPlacedIconSymbolIndex:{configurable:!0},key:{configurable:!0},textBoxStartIndex:{configurable:!0},textBoxEndIndex:{configurable:!0},verticalTextBoxStartIndex:{configurable:!0},verticalTextBoxEndIndex:{configurable:!0},iconBoxStartIndex:{configurable:!0},iconBoxEndIndex:{configurable:!0},verticalIconBoxStartIndex:{configurable:!0},verticalIconBoxEndIndex:{configurable:!0},featureIndex:{configurable:!0},numHorizontalGlyphVertices:{configurable:!0},numVerticalGlyphVertices:{configurable:!0},numIconVertices:{configurable:!0},numVerticalIconVertices:{configurable:!0},useRuntimeCollisionCircles:{configurable:!0},crossTileID:{configurable:!0},textBoxScale:{configurable:!0},textOffset0:{configurable:!0},textOffset1:{configurable:!0},collisionCircleDiameter:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.rightJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+2]},r.centerJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+3]},r.leftJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+4]},r.verticalPlacedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+5]},r.placedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+6]},r.verticalPlacedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+7]},r.key.get=function(){return this._structArray.uint16[this._pos2+8]},r.textBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.textBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+10]},r.verticalTextBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+11]},r.verticalTextBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+12]},r.iconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+13]},r.iconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+14]},r.verticalIconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+15]},r.verticalIconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+16]},r.featureIndex.get=function(){return this._structArray.uint16[this._pos2+17]},r.numHorizontalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+18]},r.numVerticalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+19]},r.numIconVertices.get=function(){return this._structArray.uint16[this._pos2+20]},r.numVerticalIconVertices.get=function(){return this._structArray.uint16[this._pos2+21]},r.useRuntimeCollisionCircles.get=function(){return this._structArray.uint16[this._pos2+22]},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+12]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+12]=t;},r.textBoxScale.get=function(){return this._structArray.float32[this._pos4+13]},r.textOffset0.get=function(){return this._structArray.float32[this._pos4+14]},r.textOffset1.get=function(){return this._structArray.float32[this._pos4+15]},r.collisionCircleDiameter.get=function(){return this._structArray.float32[this._pos4+16]},Object.defineProperties(e.prototype,r),e}(wi);$i.prototype.size=68;var Wi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new $i(this,t)},e}(Oi);Fn("SymbolInstanceArray",Wi);var Qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getoffsetX=function(t){return this.float32[1*t+0]},e}(Ui);Fn("GlyphOffsetArray",Qi);var ta=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getx=function(t){return this.int16[3*t+0]},e.prototype.gety=function(t){return this.int16[3*t+1]},e.prototype.gettileUnitDistanceFromAnchor=function(t){return this.int16[3*t+2]},e}(ji);Fn("SymbolLineVertexArray",ta);var ea=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0}};return r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+0]},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+3]},Object.defineProperties(e.prototype,r),e}(wi);ea.prototype.size=8;var ra=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new ea(this,t)},e}(qi);Fn("FeatureIndexArray",ra);var na=Ai([{name:"a_pos",components:2,type:"Int16"}],4).members,ia=function(t){void 0===t&&(t=[]),this.segments=t;};function aa(t,e){return 256*(t=u(Math.floor(t),0,255))+u(Math.floor(e),0,255)}ia.prototype.prepareSegment=function(t,e,r,n){var i=this.segments[this.segments.length-1];return t>ia.MAX_VERTEX_ARRAY_LENGTH&&w("Max vertices per segment is "+ia.MAX_VERTEX_ARRAY_LENGTH+": bucket requested "+t),(!i||i.vertexLength+t>ia.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n)&&(i={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},void 0!==n&&(i.sortKey=n),this.segments.push(i)),i},ia.prototype.get=function(){return this.segments},ia.prototype.destroy=function(){for(var t=0,e=this.segments;t>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(a>>>16)&65535)<<16);switch(u=0,r){case 3:u^=(255&t.charCodeAt(l+2))<<16;case 2:u^=(255&t.charCodeAt(l+1))<<8;case 1:i^=u=(65535&(u=(u=(65535&(u^=255&t.charCodeAt(l)))*o+(((u>>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0};})),ua=e((function(t){t.exports=function(t,e){for(var r,n=t.length,i=e^n,a=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(a)|(255&t.charCodeAt(++a))<<8|(255&t.charCodeAt(++a))<<16|(255&t.charCodeAt(++a))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++a;switch(n){case 3:i^=(255&t.charCodeAt(a+2))<<16;case 2:i^=(255&t.charCodeAt(a+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(a)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0};})),la=sa,pa=ua;la.murmur3=sa,la.murmur2=pa;var ca=function(){this.ids=[],this.positions=[],this.indexed=!1;};ca.prototype.add=function(t,e,r,n){this.ids.push(fa(t)),this.positions.push(e,r,n);},ca.prototype.getPositions=function(t){for(var e=fa(t),r=0,n=this.ids.length-1;r>1;this.ids[i]>=e?n=i:r=i+1;}for(var a=[];this.ids[r]===e;)a.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return a},ca.serialize=function(t,e){var r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return function t(e,r,n,i){for(;n>1],o=n-1,s=i+1;;){do{o++;}while(e[o]a);if(o>=s)break;ya(e,o,s),ya(r,3*o,3*s),ya(r,3*o+1,3*s+1),ya(r,3*o+2,3*s+2);}s-nVa.max||o.yVa.max)&&(w("Geometry exceeds allowed extent, reduce your vector tile buffer size"),o.x=u(o.x,Va.min,Va.max),o.y=u(o.y,Va.min,Va.max));}return r}function Da(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}var La=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new ki,this.indexArray=new Li,this.segments=new ia,this.programConfigurations=new Ta(na,t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function Ra(t,e){for(var r=0;r1){if(qa(t,e))return !0;for(var n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Za(t,e){for(var r,n,i,a=!1,o=0;oe.y!=(i=r[u]).y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function Xa(t,e){for(var r=!1,n=0,i=t.length-1;ne.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r);}return r}function Ja(t,e,r){var n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;var a=_(t,e,r[0]);return a!==_(t,e,r[1])||a!==_(t,e,r[2])||a!==_(t,e,r[3])}function Ha(t,e,r){var n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function Ya(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function $a(t,e,r,n,a){if(!e[0]&&!e[1])return t;var o=i.convert(e)._mult(a);"viewport"===r&&o._rotate(-n);for(var s=[],u=0;u=8192||p<0||p>=8192)){var c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),h=c.vertexLength;Da(this.layoutVertexArray,l,p,-1,-1),Da(this.layoutVertexArray,l,p,1,-1),Da(this.layoutVertexArray,l,p,1,1),Da(this.layoutVertexArray,l,p,-1,1),this.indexArray.emplaceBack(h,h+1,h+2),this.indexArray.emplaceBack(h,h+3,h+2),c.vertexLength+=4,c.primitiveLength+=2;}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{},n);},Fn("CircleBucket",La,{omit:["layers"]});var Wa=new gi({"circle-sort-key":new yi(It.layout_circle["circle-sort-key"])}),Qa={paint:new gi({"circle-radius":new yi(It.paint_circle["circle-radius"]),"circle-color":new yi(It.paint_circle["circle-color"]),"circle-blur":new yi(It.paint_circle["circle-blur"]),"circle-opacity":new yi(It.paint_circle["circle-opacity"]),"circle-translate":new fi(It.paint_circle["circle-translate"]),"circle-translate-anchor":new fi(It.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new fi(It.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new fi(It.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new yi(It.paint_circle["circle-stroke-width"]),"circle-stroke-color":new yi(It.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new yi(It.paint_circle["circle-stroke-opacity"])}),layout:Wa},to="undefined"!=typeof Float32Array?Float32Array:Array;function eo(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function ro(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],d=e[12],m=e[13],v=e[14],g=e[15],x=r[0],b=r[1],w=r[2],_=r[3];return t[0]=x*n+b*s+w*c+_*d,t[1]=x*i+b*u+w*h+_*m,t[2]=x*a+b*l+w*f+_*v,t[3]=x*o+b*p+w*y+_*g,t[4]=(x=r[4])*n+(b=r[5])*s+(w=r[6])*c+(_=r[7])*d,t[5]=x*i+b*u+w*h+_*m,t[6]=x*a+b*l+w*f+_*v,t[7]=x*o+b*p+w*y+_*g,t[8]=(x=r[8])*n+(b=r[9])*s+(w=r[10])*c+(_=r[11])*d,t[9]=x*i+b*u+w*h+_*m,t[10]=x*a+b*l+w*f+_*v,t[11]=x*o+b*p+w*y+_*g,t[12]=(x=r[12])*n+(b=r[13])*s+(w=r[14])*c+(_=r[15])*d,t[13]=x*i+b*u+w*h+_*m,t[14]=x*a+b*l+w*f+_*v,t[15]=x*o+b*p+w*y+_*g,t}Math.hypot||(Math.hypot=function(){for(var t=arguments,e=0,r=arguments.length;r--;)e+=t[r]*t[r];return Math.sqrt(e)});var no,io=ro;function ao(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}no=new to(3),to!=Float32Array&&(no[0]=0,no[1]=0,no[2]=0),function(){var t=new to(4);to!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0);}();var oo=(function(){var t=new to(2);to!=Float32Array&&(t[0]=0,t[1]=0);}(),function(t){function e(e){t.call(this,e,Qa);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.createBucket=function(t){return new La(t)},e.prototype.queryRadius=function(t){var e=t;return Ha("circle-radius",this,e)+Ha("circle-stroke-width",this,e)+Ya(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o,s){for(var u=$a(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),a.angle,o),l=this.paint.get("circle-radius").evaluate(e,r)+this.paint.get("circle-stroke-width").evaluate(e,r),p="map"===this.paint.get("circle-pitch-alignment"),c=p?u:function(t,e){return t.map((function(t){return so(t,e)}))}(u,s),h=p?l*o:l,f=0,y=n;ft.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,u=0;u80*r){n=a=t[0],i=o=t[1];for(var y=r;ya&&(a=s),u>o&&(o=u);l=0!==(l=Math.max(a-n,o-i))?1/l:0;}return Io(h,f,r,n,i,l),f}function So(t,e,r,n,i){var a,o;if(i===Jo(t,e,r,n)>0)for(a=e;a=e;a-=n)o=Go(a,t[a],t[a+1],o);return o&&Oo(o,o.next)&&(Zo(o),o=o.next),o}function ko(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!Oo(n,n.next)&&0!==Ro(n.prev,n,n.next))n=n.next;else {if(Zo(n),(n=e=n.prev)===n.next)break;r=!0;}}while(r||n!==e);return e}function Io(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=Vo(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,u,l=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||u>0&&n;)0!==s&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,u--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n;}a.nextZ=null,l*=2;}while(o>1)}(i);}(t,n,i,a);for(var s,u,l=t;t.prev!==t.next;)if(s=t.prev,u=t.next,a?Co(t,n,i,a):zo(t))e.push(s.i/r),e.push(t.i/r),e.push(u.i/r),Zo(t),t=u.next,l=u.next;else if((t=u)===l){o?1===o?Io(t=Mo(ko(t),e,r),e,r,n,i,a,2):2===o&&Eo(t,e,r,n,i,a):Io(ko(t),e,r,n,i,a,1);break}}}function zo(t){var e=t.prev,r=t,n=t.next;if(Ro(e,r,n)>=0)return !1;for(var i=t.next.next;i!==t.prev;){if(Do(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Ro(i.prev,i,i.next)>=0)return !1;i=i.next;}return !0}function Co(t,e,r,n){var i=t.prev,a=t,o=t.next;if(Ro(i,a,o)>=0)return !1;for(var s=i.x>a.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,u=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,l=Vo(i.x=l&&h&&h.z<=p;){if(c!==t.prev&&c!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,c.x,c.y)&&Ro(c.prev,c,c.next)>=0)return !1;if(c=c.prevZ,h!==t.prev&&h!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,h.x,h.y)&&Ro(h.prev,h,h.next)>=0)return !1;h=h.nextZ;}for(;c&&c.z>=l;){if(c!==t.prev&&c!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,c.x,c.y)&&Ro(c.prev,c,c.next)>=0)return !1;c=c.prevZ;}for(;h&&h.z<=p;){if(h!==t.prev&&h!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,h.x,h.y)&&Ro(h.prev,h,h.next)>=0)return !1;h=h.nextZ;}return !0}function Mo(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!Oo(i,a)&&Uo(i,n,n.next,a)&&No(i,a)&&No(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),Zo(n),Zo(n.next),n=t=a),n=n.next;}while(n!==t);return ko(n)}function Eo(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&Lo(o,s)){var u=Ko(o,s);return o=ko(o,o.next),u=ko(u,u.next),Io(o,e,r,n,i,a),void Io(u,e,r,n,i,a)}s=s.next;}o=o.next;}while(o!==t)}function To(t,e){return t.x-e.x}function Po(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=p&&i!==n.x&&Do(ar.x||n.x===r.x&&Bo(r,n)))&&(r=n,h=u)),n=n.next;}while(n!==l);return r}(t,e)){var r=Ko(e,t);ko(e,e.next),ko(r,r.next);}}function Bo(t,e){return Ro(t.prev,t,e.prev)<0&&Ro(e.next,t,t.next)<0}function Vo(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Fo(t){var e=t,r=t;do{(e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function Lo(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Uo(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(No(t,e)&&No(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Ro(t.prev,t,e.prev)||Ro(t,e.prev,e))||Oo(t,e)&&Ro(t.prev,t,t.next)>0&&Ro(e.prev,e,e.next)>0)}function Ro(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Oo(t,e){return t.x===e.x&&t.y===e.y}function Uo(t,e,r,n){var i=qo(Ro(t,e,r)),a=qo(Ro(t,e,n)),o=qo(Ro(r,n,t)),s=qo(Ro(r,n,e));return i!==a&&o!==s||!(0!==i||!jo(t,r,e))||!(0!==a||!jo(t,n,e))||!(0!==o||!jo(r,t,n))||!(0!==s||!jo(r,e,n))}function jo(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function qo(t){return t>0?1:t<0?-1:0}function No(t,e){return Ro(t.prev,t,t.next)<0?Ro(t,e,t.next)>=0&&Ro(t,t.prev,e)>=0:Ro(t,e,t.prev)<0||Ro(t,t.next,e)<0}function Ko(t,e){var r=new Xo(t.i,t.x,t.y),n=new Xo(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function Go(t,e,r,n){var i=new Xo(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Zo(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function Xo(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function Jo(t,e,r,n){for(var i=0,a=e,o=r-n;an;){if(i-n>600){var o=i-n+1,s=r-n+1,u=Math.log(o),l=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*l*(o-l)/o)*(s-o/2<0?-1:1);t(e,r,Math.max(n,Math.floor(r-s*l/o+p)),Math.min(i,Math.floor(r+(o-s)*l/o+p)),a);}var c=e[r],h=n,f=i;for(Yo(e,n,r),a(e[i],c)>0&&Yo(e,n,i);h0;)f--;}0===a(e[n],c)?Yo(e,n,f):Yo(e,++f,i),f<=r&&(n=f+1),r<=f&&(i=f-1);}}(t,e,r||0,n||t.length-1,i||$o);}function Yo(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function $o(t,e){return te?1:0}function Wo(t,e){var r=t.length;if(r<=1)return [t];for(var n,i,a=[],o=0;o1)for(var u=0;u0&&r.holes.push(n+=t[i-1].length);}return r},wo.default=_o;var rs=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new ki,this.indexArray=new Li,this.indexArray2=new Ni,this.programConfigurations=new Ta(bo,t.layers,t.zoom),this.segments=new ia,this.segments2=new ia,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};rs.prototype.populate=function(t,e,r){this.hasPattern=ts("fill",this.layers,e);for(var n=this.layers[0].layout.get("fill-sort-key"),i=[],a=0,o=t;a>3;}if(a--,1===n||2===n)o+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&u.push(e),e=[]),e.push(new i(o,s));else {if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone());}}return e&&u.push(e),u},us.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,u=1/0,l=-1/0;t.pos>3;}if(n--,1===r||2===r)(i+=t.readSVarint())s&&(s=i),(a+=t.readSVarint())l&&(l=a);else if(7!==r)throw new Error("unknown command "+r)}return [o,u,s,l]},us.prototype.toGeoJSON=function(t,e,r){var n,i,a=this.extent*Math.pow(2,r),o=this.extent*t,s=this.extent*e,u=this.loadGeometry(),l=us.types[this.type];function p(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}function ys(t,e,r){if(3===t){var n=new cs(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}hs.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new ss(this._pbf,e,this.extent,this._keys,this._values)};var ds={VectorTile:function(t,e){this.layers=t.readFields(ys,{},e);},VectorTileFeature:ss,VectorTileLayer:cs},ms=ds.VectorTileFeature.types,vs=Math.pow(2,13);function gs(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,2*Math.floor(n*vs)+o,i*vs*2,a*vs*2,Math.round(s));}var xs=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new zi,this.indexArray=new Li,this.programConfigurations=new Ta(os,t.layers,t.zoom),this.segments=new ia,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function bs(t,e){return t.x===e.x&&(t.x<0||t.x>8192)||t.y===e.y&&(t.y<0||t.y>8192)}xs.prototype.populate=function(t,e,r){this.features=[],this.hasPattern=ts("fill-extrusion",this.layers,e);for(var n=0,i=t;n8192}))||P.every((function(t){return t.y<0}))||P.every((function(t){return t.y>8192}))))for(var d=0,m=0;m=1){var g=y[m-1];if(!bs(v,g)){c.vertexLength+4>ia.MAX_VERTEX_ARRAY_LENGTH&&(c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));var x=v.sub(g)._perp()._unit(),b=g.dist(v);d+b>32768&&(d=0),gs(this.layoutVertexArray,v.x,v.y,x.x,x.y,0,0,d),gs(this.layoutVertexArray,v.x,v.y,x.x,x.y,0,1,d),gs(this.layoutVertexArray,g.x,g.y,x.x,x.y,0,0,d+=b),gs(this.layoutVertexArray,g.x,g.y,x.x,x.y,0,1,d);var w=c.vertexLength;this.indexArray.emplaceBack(w,w+2,w+1),this.indexArray.emplaceBack(w+1,w+2,w+3),c.vertexLength+=4,c.primitiveLength+=2;}}}}if(c.vertexLength+u>ia.MAX_VERTEX_ARRAY_LENGTH&&(c=this.segments.prepareSegment(u,this.layoutVertexArray,this.indexArray)),"Polygon"===ms[t.type]){for(var _=[],A=[],S=c.vertexLength,k=0,I=s;k=2&&t[u-1].equals(t[u-2]);)u--;for(var l=0;l0;if(A&&v>l){var k=p.dist(f);if(k>2*c){var I=p.sub(p.sub(f)._mult(c/k)._round());this.updateDistance(f,I),this.addCurrentVertex(I,d,0,0,h),f=I;}}var z=f&&y,C=z?r:s?"butt":n;if(z&&"round"===C&&(wi&&(C="bevel"),"bevel"===C&&(w>2&&(C="flipbevel"),w100)g=m.mult(-1);else {var M=w*d.add(m).mag()/d.sub(m).mag();g._perp()._mult(M*(S?-1:1));}this.addCurrentVertex(p,g,0,0,h),this.addCurrentVertex(p,g.mult(-1),0,0,h);}else if("bevel"===C||"fakeround"===C){var E=-Math.sqrt(w*w-1),T=S?E:0,P=S?0:E;if(f&&this.addCurrentVertex(p,d,T,P,h),"fakeround"===C)for(var B=Math.round(180*_/Math.PI/20),V=1;V2*c){var U=p.add(y.sub(p)._mult(c/O)._round());this.updateDistance(p,U),this.addCurrentVertex(U,m,0,0,h),p=U;}}}}},Ms.prototype.addCurrentVertex=function(t,e,r,n,i,a){void 0===a&&(a=!1);var o=e.y*n-e.x,s=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,a,!1,r,i),this.addHalfVertex(t,o,s,a,!0,-n,i),this.distance>Cs/2&&0===this.totalDistance&&(this.distance=0,this.addCurrentVertex(t,e,r,n,i,a));},Ms.prototype.addHalfVertex=function(t,e,r,n,i,a,o){var s=.5*this.scaledDistance;this.layoutVertexArray.emplaceBack((t.x<<1)+(n?1:0),(t.y<<1)+(i?1:0),Math.round(63*e)+128,Math.round(63*r)+128,1+(0===a?0:a<0?-1:1)|(63&s)<<2,s>>6);var u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,u),o.primitiveLength++),i?this.e2=u:this.e1=u;},Ms.prototype.updateScaledDistance=function(){this.scaledDistance=this.totalDistance>0?(this.clipStart+(this.clipEnd-this.clipStart)*this.distance/this.totalDistance)*(Cs-1):this.distance;},Ms.prototype.updateDistance=function(t,e){this.distance+=t.dist(e),this.updateScaledDistance();},Fn("LineBucket",Ms,{omit:["layers","patternFeatures"]});var Es=new gi({"line-cap":new fi(It.layout_line["line-cap"]),"line-join":new yi(It.layout_line["line-join"]),"line-miter-limit":new fi(It.layout_line["line-miter-limit"]),"line-round-limit":new fi(It.layout_line["line-round-limit"]),"line-sort-key":new yi(It.layout_line["line-sort-key"])}),Ts={paint:new gi({"line-opacity":new yi(It.paint_line["line-opacity"]),"line-color":new yi(It.paint_line["line-color"]),"line-translate":new fi(It.paint_line["line-translate"]),"line-translate-anchor":new fi(It.paint_line["line-translate-anchor"]),"line-width":new yi(It.paint_line["line-width"]),"line-gap-width":new yi(It.paint_line["line-gap-width"]),"line-offset":new yi(It.paint_line["line-offset"]),"line-blur":new yi(It.paint_line["line-blur"]),"line-dasharray":new mi(It.paint_line["line-dasharray"]),"line-pattern":new di(It.paint_line["line-pattern"]),"line-gradient":new vi(It.paint_line["line-gradient"])}),layout:Es},Ps=new(function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new ii(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n,i){return r=p({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n,i)},e}(yi))(Ts.paint.properties["line-width"].specification);Ps.useIntegerZoom=!0;var Bs=function(t){function e(e){t.call(this,e,Ts);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._handleSpecialPaintPropertyUpdate=function(t){"line-gradient"===t&&this._updateGradient();},e.prototype._updateGradient=function(){this.gradient=mo(this._transitionablePaint._values["line-gradient"].value.expression,"lineProgress"),this.gradientTexture=null;},e.prototype.recalculate=function(e,r){t.prototype.recalculate.call(this,e,r),this.paint._values["line-floorwidth"]=Ps.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e);},e.prototype.createBucket=function(t){return new Ms(t)},e.prototype.queryRadius=function(t){var e=t,r=Vs(Ha("line-width",this,e),Ha("line-gap-width",this,e)),n=Ha("line-offset",this,e);return r/2+Math.abs(n)+Ya(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,a,o,s){var u=$a(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o.angle,s),l=s/2*Vs(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),p=this.paint.get("line-offset").evaluate(e,r);return p&&(n=function(t,e){for(var r=[],n=new i(0,0),a=0;a=3)for(var a=0;a0?e+2*t:t}var Fs=Ai([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Ds=Ai([{name:"a_projected_pos",components:3,type:"Float32"}],4),Ls=(Ai([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),Ai([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"}])),Rs=(Ai([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]),Ai([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4)),Os=Ai([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Us(t,e,r){return t.sections.forEach((function(t){t.text=function(t,e,r){var n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),ni.applyArabicShaping&&(t=ni.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ai([{name:"triangle",components:3,type:"Uint16"}]),Ai([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ai([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",components:2,name:"textOffset"},{type:"Float32",name:"collisionCircleDiameter"}]),Ai([{type:"Float32",name:"offsetX"}]),Ai([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);var js={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"},qs=function(t,e,r,n,i){var a,o,s=8*i-n-1,u=(1<>1,p=-7,c=r?i-1:0,h=r?-1:1,f=t[e+c];for(c+=h,a=f&(1<<-p)-1,f>>=-p,p+=s;p>0;a=256*a+t[e+c],c+=h,p-=8);for(o=a&(1<<-p)-1,a>>=-p,p+=n;p>0;o=256*o+t[e+c],c+=h,p-=8);if(0===a)a=1-l;else {if(a===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),a-=l;}return (f?-1:1)*o*Math.pow(2,a-n)},Ns=function(t,e,r,n,i,a){var o,s,u,l=8*a-i-1,p=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:a-1,y=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),(e+=o+c>=1?h/u:h*Math.pow(2,1-c))*u>=2&&(o++,u/=2),o+c>=p?(s=0,o=p):o+c>=1?(s=(e*u-1)*Math.pow(2,i),o+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),o=0));i>=8;t[r+f]=255&s,f+=y,s/=256,i-=8);for(o=o<0;t[r+f]=255&o,f+=y,o/=256,l-=8);t[r+f-y]|=128*d;},Ks=Gs;function Gs(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}Gs.Varint=0,Gs.Fixed64=1,Gs.Bytes=2,Gs.Fixed32=5;var Zs="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function Xs(t){return t.type===Gs.Bytes?t.readVarint()+t.pos:t.pos+1}function Js(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function Hs(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function Ys(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function su(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}function uu(t,e,r){1===t&&r.readMessage(lu,e);}function lu(t,e,r){if(3===t){var n=r.readMessage(pu,{}),i=n.width,a=n.height,o=n.left,s=n.top,u=n.advance;e.push({id:n.id,bitmap:new ho({width:i+6,height:a+6},n.bitmap),metrics:{width:i,height:a,left:o,top:s,advance:u}});}}function pu(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}function cu(t){for(var e=0,r=0,n=0,i=t;n=0;h--){var f=o[h];if(!(c.w>f.w||c.h>f.h)){if(c.x=f.x,c.y=f.y,u=Math.max(u,c.y+c.h),s=Math.max(s,c.x+c.w),c.w===f.w&&c.h===f.h){var y=o.pop();h>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=au(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=su(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=au(this.buf,this.pos)+4294967296*au(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=au(this.buf,this.pos)+4294967296*su(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=qs(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=qs(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,a=r.buf;if(n=(112&(i=a[r.pos++]))>>4,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<3,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<10,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<17,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<24,i<128)return Js(t,n,e);if(n|=(1&(i=a[r.pos++]))<<31,i<128)return Js(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&Zs?function(t,e,r){return Zs.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i239?4:u>223?3:u>191?2:1;if(i+p>r)break;1===p?u<128&&(l=u):2===p?128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)<=127&&(l=null):3===p?(o=t[i+2],128==(192&(a=t[i+1]))&&128==(192&o)&&((l=(15&u)<<12|(63&a)<<6|63&o)<=2047||l>=55296&&l<=57343)&&(l=null)):4===p&&(o=t[i+2],s=t[i+3],128==(192&(a=t[i+1]))&&128==(192&o)&&128==(192&s)&&((l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||l>=1114112)&&(l=null)),null===l?(l=65533,p=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=p;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==Gs.Bytes)return t.push(this.readVarint(e));var r=Xs(this);for(t=t||[];this.pos127;);else if(e===Gs.Bytes)this.pos=this.readVarint()+this.pos;else if(e===Gs.Fixed32)this.pos+=4;else {if(e!==Gs.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&Hs(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),Ns(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),Ns(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&Hs(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,Gs.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,Ys,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,$s,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,tu,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,Ws,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,Qs,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,eu,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,ru,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,nu,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,iu,e);},writeBytesField:function(t,e){this.writeTag(t,Gs.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,Gs.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,Gs.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,Gs.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var hu=function(t,e){var r=e.pixelRatio,n=e.version,i=e.stretchX,a=e.stretchY,o=e.content;this.paddedRect=t,this.pixelRatio=r,this.stretchX=i,this.stretchY=a,this.content=o,this.version=n;},fu={tl:{configurable:!0},br:{configurable:!0},tlbr:{configurable:!0},displaySize:{configurable:!0}};fu.tl.get=function(){return [this.paddedRect.x+1,this.paddedRect.y+1]},fu.br.get=function(){return [this.paddedRect.x+this.paddedRect.w-1,this.paddedRect.y+this.paddedRect.h-1]},fu.tlbr.get=function(){return this.tl.concat(this.br)},fu.displaySize.get=function(){return [(this.paddedRect.w-2)/this.pixelRatio,(this.paddedRect.h-2)/this.pixelRatio]},Object.defineProperties(hu.prototype,fu);var yu=function(t,e){var r={},n={};this.haveRenderCallbacks=[];var i=[];this.addImages(t,r,i),this.addImages(e,n,i);var a=cu(i),o=new fo({width:a.w||1,height:a.h||1});for(var s in t){var u=t[s],l=r[s].paddedRect;fo.copy(u.data,o,{x:0,y:0},{x:l.x+1,y:l.y+1},u.data);}for(var p in e){var c=e[p],h=n[p].paddedRect,f=h.x+1,y=h.y+1,d=c.data.width,m=c.data.height;fo.copy(c.data,o,{x:0,y:0},{x:f,y:y},c.data),fo.copy(c.data,o,{x:0,y:m-1},{x:f,y:y-1},{width:d,height:1}),fo.copy(c.data,o,{x:0,y:0},{x:f,y:y+m},{width:d,height:1}),fo.copy(c.data,o,{x:d-1,y:0},{x:f-1,y:y},{width:1,height:m}),fo.copy(c.data,o,{x:0,y:0},{x:f+d,y:y},{width:1,height:m});}this.image=o,this.iconPositions=r,this.patternPositions=n;};yu.prototype.addImages=function(t,e,r){for(var n in t){var i=t[n],a={x:0,y:0,w:i.data.width+2,h:i.data.height+2};r.push(a),e[n]=new hu(a,i),i.hasRenderCallback&&this.haveRenderCallbacks.push(n);}},yu.prototype.patchUpdatedImages=function(t,e){for(var r in t.dispatchRenderCallbacks(this.haveRenderCallbacks),t.updatedImages)this.patchUpdatedImage(this.iconPositions[r],t.getImage(r),e),this.patchUpdatedImage(this.patternPositions[r],t.getImage(r),e);},yu.prototype.patchUpdatedImage=function(t,e,r){if(t&&e&&t.version!==e.version){t.version=e.version;var n=t.tl;r.update(e.data,void 0,{x:n[0],y:n[1]});}},Fn("ImagePosition",hu),Fn("ImageAtlas",yu);var du={horizontal:1,vertical:2,horizontalOnly:3},mu=function(){this.scale=1,this.fontStack="",this.imageName=null;};mu.forText=function(t,e){var r=new mu;return r.scale=t||1,r.fontStack=e,r},mu.forImage=function(t){var e=new mu;return e.imageName=t,e};var vu=function(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null;};function gu(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d){var m,v=vu.fromFeature(t,i);c===du.vertical&&v.verticalizePunctuation();var g=ni.processBidirectionalText,x=ni.processStyledBidirectionalText;if(g&&1===v.sections.length){m=[];for(var b=0,w=g(v.toString(),ku(v,l,a,e,n,f,y));b0&&R>k&&(k=R);}else {var O=r[z.fontStack],U=O&&O[M];if(U&&U.rect)P=U.rect,T=U.metrics;else {var j=e[z.fontStack],q=j&&j[M];if(!q)continue;T=q.metrics;}E=24*(w-z.scale);}F?(t.verticalizable=!0,S.push({glyph:M,imageName:B,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:T,rect:P}),h+=V*z.scale+l):(S.push({glyph:M,imageName:B,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:T,rect:P}),h+=T.advance*z.scale+l);}0!==S.length&&(y=Math.max(h-l,y),zu(S,0,S.length-1,m,k)),h=0;var N=a*w+k;A.lineOffset=Math.max(k,_),f+=N,d=Math.max(N,d),++v;}else f+=a,++v;}var K,G=f- -17,Z=Iu(o),X=Z.horizontalAlign,J=Z.verticalAlign;(function(t,e,r,n,i,a,o,s,u){var l,p=(e-r)*i;l=a!==o?-s*n- -17:(-n*u+.5)*o;for(var c=0,h=t;c=0&&n>=t&&xu[this.text.charCodeAt(n)];n--)r--;this.text=this.text.substring(t,r),this.sectionIndex=this.sectionIndex.slice(t,r);},vu.prototype.substring=function(t,e){var r=new vu;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r},vu.prototype.toString=function(){return this.text},vu.prototype.getMaxScale=function(){var t=this;return this.sectionIndex.reduce((function(e,r){return Math.max(e,t.sections[r].scale)}),0)},vu.prototype.addTextSection=function(t,e){this.text+=t.text,this.sections.push(mu.forText(t.scale,t.fontStack||e));for(var r=this.sections.length-1,n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)};var xu={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},bu={};function wu(t,e,r,n,i,a){if(e.imageName){var o=n[e.imageName];return o?o.displaySize[0]*e.scale*24/a+i:0}var s=r[e.fontStack],u=s&&s[t];return u?u.metrics.advance*e.scale+i:0}function _u(t,e,r,n){var i=Math.pow(t-e,2);return n?t=0,c=0,h=0;h-r/2;){if(--o<0)return !1;s-=t[o].dist(a),a=t[o];}s+=t[o].dist(t[o+1]),o++;for(var u=[],l=0;sn;)l-=u.shift().angleDelta;if(l>i)return !1;o++,s+=p.dist(c);}return !0}function Fu(t){for(var e=0,r=0;rl){var y=(l-u)/f,d=je(c.x,h.x,y),m=je(c.y,h.y,y),v=new Mu(d,m,h.angleTo(c),p);return v._round(),!o||Vu(t,v,s,o,e)?v:void 0}u+=f;}}function Ou(t,e,r,n,i,a,o,s,u){var l=Du(n,a,o),p=Lu(n,i),c=p*o,h=0===t[0].x||t[0].x===u||0===t[0].y||t[0].y===u;return e-c=0&&w=0&&_=0&&f+p<=c){var A=new Mu(w,_,x,d);A._round(),i&&!Vu(e,A,o,i,a)||y.push(A);}}h+=g;}return u||y.length||s||(y=t(e,h/2,n,i,a,o,s,!0,l)),y}(t,h?e/2*s%e:(p/2+2*a)*o*s%e,e,l,r,c,h,!1,u)}function Uu(t,e,r,n,a){for(var o=[],s=0;s=n&&h.x>=n||(c.x>=n?c=new i(n,c.y+(n-c.x)/(h.x-c.x)*(h.y-c.y))._round():h.x>=n&&(h=new i(n,c.y+(n-c.x)/(h.x-c.x)*(h.y-c.y))._round()),c.y>=a&&h.y>=a||(c.y>=a?c=new i(c.x+(a-c.y)/(h.y-c.y)*(h.x-c.x),a)._round():h.y>=a&&(h=new i(c.x+(a-c.y)/(h.y-c.y)*(h.x-c.x),a)._round()),l&&c.equals(l[l.length-1])||o.push(l=[c]),l.push(h)))));}return o}function ju(t,e,r,n){var a=[],o=t.image,s=o.pixelRatio,u=o.paddedRect.w-2,l=o.paddedRect.h-2,p=t.right-t.left,c=t.bottom-t.top,h=o.stretchX||[[0,u]],f=o.stretchY||[[0,l]],y=function(t,e){return t+e[1]-e[0]},d=h.reduce(y,0),m=f.reduce(y,0),v=u-d,g=l-m,x=0,b=d,w=0,_=m,A=0,S=v,k=0,I=g;if(o.content&&n){var z=o.content;x=qu(h,0,z[0]),w=qu(f,0,z[1]),b=qu(h,z[0],z[2]),_=qu(f,z[1],z[3]),A=z[0]-x,k=z[1]-w,S=z[2]-z[0]-b,I=z[3]-z[1]-_;}var C=function(n,a,u,l){var h=Ku(n.stretch-x,b,p,t.left),f=Gu(n.fixed-A,S,n.stretch,d),y=Ku(a.stretch-w,_,c,t.top),v=Gu(a.fixed-k,I,a.stretch,m),g=Ku(u.stretch-x,b,p,t.left),z=Gu(u.fixed-A,S,u.stretch,d),C=Ku(l.stretch-w,_,c,t.top),M=Gu(l.fixed-k,I,l.stretch,m),E=new i(h,y),T=new i(g,y),P=new i(g,C),B=new i(h,C),V=new i(f/s,v/s),F=new i(z/s,M/s),D=e*Math.PI/180;if(D){var L=Math.sin(D),R=Math.cos(D),O=[R,-L,L,R];E._matMult(O),T._matMult(O),B._matMult(O),P._matMult(O);}var U=n.stretch+n.fixed,j=a.stretch+a.fixed;return {tl:E,tr:T,bl:B,br:P,tex:{x:o.paddedRect.x+1+U,y:o.paddedRect.y+1+j,w:u.stretch+u.fixed-U,h:l.stretch+l.fixed-j},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:V,pixelOffsetBR:F,minFontScaleX:S/s/p,minFontScaleY:I/s/c,isSDF:r}};if(n&&(o.stretchX||o.stretchY))for(var M=Nu(h,v,d),E=Nu(f,g,m),T=0;T0&&(y=Math.max(10,y),this.circleDiameter=y);}else {var d=o.top*s-u,m=o.bottom*s+u,v=o.left*s-u,g=o.right*s+u,x=o.collisionPadding;if(x&&(v-=x[0]*s,d-=x[1]*s,g+=x[2]*s,m+=x[3]*s),p){var b=new i(v,d),w=new i(g,d),_=new i(v,m),A=new i(g,m),S=p*Math.PI/180;b._rotate(S),w._rotate(S),_._rotate(S),A._rotate(S),v=Math.min(b.x,w.x,_.x,A.x),g=Math.max(b.x,w.x,_.x,A.x),d=Math.min(b.y,w.y,_.y,A.y),m=Math.max(b.y,w.y,_.y,A.y);}t.emplaceBack(e.x,e.y,v,d,g,m,r,n,a);}this.boxEndIndex=t.length;},Xu=function(t,e){if(void 0===t&&(t=[]),void 0===e&&(e=Ju),this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r);};function Ju(t,e){return te?1:0}function Hu(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var n=1/0,a=1/0,o=-1/0,s=-1/0,u=t[0],l=0;lo)&&(o=p.x),(!l||p.y>s)&&(s=p.y);}var c=Math.min(o-n,s-a),h=c/2,f=new Xu([],Yu);if(0===c)return new i(n,a);for(var y=n;ym.d||!m.d)&&(m=g,r&&console.log("found best %d after %d probes",Math.round(1e4*g.d)/1e4,v)),g.max-m.d<=e||(f.push(new $u(g.p.x-(h=g.h/2),g.p.y-h,h,t)),f.push(new $u(g.p.x+h,g.p.y-h,h,t)),f.push(new $u(g.p.x-h,g.p.y+h,h,t)),f.push(new $u(g.p.x+h,g.p.y+h,h,t)),v+=4);}return r&&(console.log("num probes: "+v),console.log("best distance: "+m.d)),m.p}function Yu(t,e){return e.max-t.max}function $u(t,e,r,n){this.p=new i(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;it.y!=p.y>t.y&&t.x<(p.x-l.x)*(t.y-l.y)/(p.y-l.y)+l.x&&(r=!r),n=Math.min(n,Ga(t,l,p));}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}Xu.prototype.push=function(t){this.data.push(t),this.length++,this._up(this.length-1);},Xu.prototype.pop=function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}},Xu.prototype.peek=function(){return this.data[0]},Xu.prototype._up=function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i;}e[t]=n;},Xu.prototype._down=function(t){for(var e=this.data,r=this.compare,n=this.length>>1,i=e[t];t=0)break;e[t]=o,t=a;}e[t]=i;};var Wu=Number.POSITIVE_INFINITY;function Qu(t,e){return e[1]!==Wu?function(t,e,r){var n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-7;break;case"bottom-right":case"bottom-left":case"bottom":i=7-r;}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){var r=0,n=0;e<0&&(e=0);var i=e/Math.sqrt(2);switch(t){case"top-right":case"top-left":n=i-7;break;case"bottom-right":case"bottom-left":n=7-i;break;case"bottom":n=7-e;break;case"top":n=e-7;}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e;}return [r,n]}(t,e[0])}function tl(t){switch(t){case"right":case"top-right":case"bottom-right":return "right";case"left":case"top-left":case"bottom-left":return "left"}return "center"}function el(t,e,r,n,a,o,s,u,l,p,c,h,f,y,d){var m=function(t,e,r,n,a,o,s,u){for(var l=n.layout.get("text-rotate").evaluate(o,{})*Math.PI/180,p=[],c=0,h=e.positionedLines;c32640&&w(t.layerIds[0]+': Value for "text-size" is >= 255. Reduce your "text-size".'):"composite"===v.kind&&((g=[128*y.compositeTextSizes[0].evaluate(s,{},d),128*y.compositeTextSizes[1].evaluate(s,{},d)])[0]>32640||g[1]>32640)&&w(t.layerIds[0]+': Value for "text-size" is >= 255. Reduce your "text-size".'),t.addSymbols(t.text,m,g,u,o,s,p,e,l.lineStartIndex,l.lineLength,f,d);for(var x=0,b=c;x=0;o--)if(n.dist(a[o])0)&&("constant"!==a.value.kind||a.value.value.length>0),l="constant"!==s.value.kind||!!s.value.value||Object.keys(s.parameters).length>0,p=i.get("symbol-sort-key");if(this.features=[],u||l){for(var c=e.iconDependencies,h=e.glyphDependencies,f=e.availableImages,y=new ii(this.zoom),d=0,m=t;d=0;for(var B=0,V=S.sections;B=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var u=0;u0},cl.prototype.hasIconData=function(){return this.icon.segments.get().length>0},cl.prototype.hasDebugData=function(){return this.textCollisionBox&&this.iconCollisionBox},cl.prototype.hasTextCollisionBoxData=function(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0},cl.prototype.hasIconCollisionBoxData=function(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0},cl.prototype.addIndicesForPlacedSymbol=function(t,e){for(var r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs,i=r.vertexStartIndex;i1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(var r=0,n=this.symbolInstanceIndexes;r=0&&n.indexOf(t)===r&&e.addIndicesForPlacedSymbol(e.text,t);})),i.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,i.verticalPlacedTextSymbolIndex),i.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,i.placedIconSymbolIndex),i.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,i.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}},Fn("SymbolBucket",cl,{omit:["layers","collisionBoxArray","features","compareText"]}),cl.MAX_GLYPHS=65535,cl.addDynamicAttributes=sl;var hl=new gi({"symbol-placement":new fi(It.layout_symbol["symbol-placement"]),"symbol-spacing":new fi(It.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new fi(It.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new yi(It.layout_symbol["symbol-sort-key"]),"symbol-z-order":new fi(It.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new fi(It.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new fi(It.layout_symbol["icon-ignore-placement"]),"icon-optional":new fi(It.layout_symbol["icon-optional"]),"icon-rotation-alignment":new fi(It.layout_symbol["icon-rotation-alignment"]),"icon-size":new yi(It.layout_symbol["icon-size"]),"icon-text-fit":new fi(It.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new fi(It.layout_symbol["icon-text-fit-padding"]),"icon-image":new yi(It.layout_symbol["icon-image"]),"icon-rotate":new yi(It.layout_symbol["icon-rotate"]),"icon-padding":new fi(It.layout_symbol["icon-padding"]),"icon-keep-upright":new fi(It.layout_symbol["icon-keep-upright"]),"icon-offset":new yi(It.layout_symbol["icon-offset"]),"icon-anchor":new yi(It.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new fi(It.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new fi(It.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new fi(It.layout_symbol["text-rotation-alignment"]),"text-field":new yi(It.layout_symbol["text-field"]),"text-font":new yi(It.layout_symbol["text-font"]),"text-size":new yi(It.layout_symbol["text-size"]),"text-max-width":new yi(It.layout_symbol["text-max-width"]),"text-line-height":new fi(It.layout_symbol["text-line-height"]),"text-letter-spacing":new yi(It.layout_symbol["text-letter-spacing"]),"text-justify":new yi(It.layout_symbol["text-justify"]),"text-radial-offset":new yi(It.layout_symbol["text-radial-offset"]),"text-variable-anchor":new fi(It.layout_symbol["text-variable-anchor"]),"text-anchor":new yi(It.layout_symbol["text-anchor"]),"text-max-angle":new fi(It.layout_symbol["text-max-angle"]),"text-writing-mode":new fi(It.layout_symbol["text-writing-mode"]),"text-rotate":new yi(It.layout_symbol["text-rotate"]),"text-padding":new fi(It.layout_symbol["text-padding"]),"text-keep-upright":new fi(It.layout_symbol["text-keep-upright"]),"text-transform":new yi(It.layout_symbol["text-transform"]),"text-offset":new yi(It.layout_symbol["text-offset"]),"text-allow-overlap":new fi(It.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new fi(It.layout_symbol["text-ignore-placement"]),"text-optional":new fi(It.layout_symbol["text-optional"])}),fl={paint:new gi({"icon-opacity":new yi(It.paint_symbol["icon-opacity"]),"icon-color":new yi(It.paint_symbol["icon-color"]),"icon-halo-color":new yi(It.paint_symbol["icon-halo-color"]),"icon-halo-width":new yi(It.paint_symbol["icon-halo-width"]),"icon-halo-blur":new yi(It.paint_symbol["icon-halo-blur"]),"icon-translate":new fi(It.paint_symbol["icon-translate"]),"icon-translate-anchor":new fi(It.paint_symbol["icon-translate-anchor"]),"text-opacity":new yi(It.paint_symbol["text-opacity"]),"text-color":new yi(It.paint_symbol["text-color"],{runtimeType:Rt,getOverride:function(t){return t.textColor},hasOverride:function(t){return !!t.textColor}}),"text-halo-color":new yi(It.paint_symbol["text-halo-color"]),"text-halo-width":new yi(It.paint_symbol["text-halo-width"]),"text-halo-blur":new yi(It.paint_symbol["text-halo-blur"]),"text-translate":new fi(It.paint_symbol["text-translate"]),"text-translate-anchor":new fi(It.paint_symbol["text-translate-anchor"])}),layout:hl},yl=function(t){this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;};yl.prototype.evaluate=function(t){if(t.formattedSection){var e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default},yl.prototype.eachChild=function(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);},yl.prototype.outputDefined=function(){return !1},yl.prototype.serialize=function(){return null},Fn("FormatSectionOverride",yl,{omit:["defaultValue"]});var dl=function(t){function e(e){t.call(this,e,fl);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.recalculate=function(e,r){if(t.prototype.recalculate.call(this,e,r),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){var n=this.layout.get("text-writing-mode");if(n){for(var i=[],a=0,o=n;a",targetMapId:n,sourceMapId:a.mapId});}}},Ml.prototype.receive=function(t){var e=t.data,r=e.id;if(r&&(!e.targetMapId||this.mapId===e.targetMapId))if(""===e.type){delete this.tasks[r];var n=this.cancelCallbacks[r];delete this.cancelCallbacks[r],n&&n();}else S()||e.mustQueue?(this.tasks[r]=e,this.taskQueue.push(r),this.invoker.trigger()):this.processTask(r,e);},Ml.prototype.process=function(){if(this.taskQueue.length){var t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length&&this.invoker.trigger(),e&&this.processTask(t,e);}},Ml.prototype.processTask=function(t,e){var r=this;if(""===e.type){var n=this.callbacks[t];delete this.callbacks[t],n&&(e.error?n(Un(e.error)):n(null,Un(e.data)));}else {var i=!1,a=z(this.globalScope)?void 0:[],o=e.hasCallback?function(e,n){i=!0,delete r.cancelCallbacks[t],r.target.postMessage({id:t,type:"",sourceMapId:r.mapId,error:e?On(e):null,data:On(n,a)},a);}:function(t){i=!0;},s=null,u=Un(e.data);if(this.parent[e.type])s=this.parent[e.type](e.sourceMapId,u,o);else if(this.parent.getWorkerSource){var l=e.type.split(".");s=this.parent.getWorkerSource(e.sourceMapId,l[0],u.source)[l[1]](u,o);}else o(new Error("Could not find function "+e.type));!i&&s&&s.cancel&&(this.cancelCallbacks[t]=s.cancel);}},Ml.prototype.remove=function(){this.invoker.remove(),this.target.removeEventListener("message",this.receive,!1);};var Tl=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]));};Tl.prototype.setNorthEast=function(t){return this._ne=t instanceof Pl?new Pl(t.lng,t.lat):Pl.convert(t),this},Tl.prototype.setSouthWest=function(t){return this._sw=t instanceof Pl?new Pl(t.lng,t.lat):Pl.convert(t),this},Tl.prototype.extend=function(t){var e,r,n=this._sw,i=this._ne;if(t instanceof Pl)e=t,r=t;else {if(!(t instanceof Tl))return Array.isArray(t)?4===t.length||t.every(Array.isArray)?this.extend(Tl.convert(t)):this.extend(Pl.convert(t)):this;if(r=t._ne,!(e=t._sw)||!r)return this}return n||i?(n.lng=Math.min(e.lng,n.lng),n.lat=Math.min(e.lat,n.lat),i.lng=Math.max(r.lng,i.lng),i.lat=Math.max(r.lat,i.lat)):(this._sw=new Pl(e.lng,e.lat),this._ne=new Pl(r.lng,r.lat)),this},Tl.prototype.getCenter=function(){return new Pl((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},Tl.prototype.getSouthWest=function(){return this._sw},Tl.prototype.getNorthEast=function(){return this._ne},Tl.prototype.getNorthWest=function(){return new Pl(this.getWest(),this.getNorth())},Tl.prototype.getSouthEast=function(){return new Pl(this.getEast(),this.getSouth())},Tl.prototype.getWest=function(){return this._sw.lng},Tl.prototype.getSouth=function(){return this._sw.lat},Tl.prototype.getEast=function(){return this._ne.lng},Tl.prototype.getNorth=function(){return this._ne.lat},Tl.prototype.toArray=function(){return [this._sw.toArray(),this._ne.toArray()]},Tl.prototype.toString=function(){return "LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},Tl.prototype.isEmpty=function(){return !(this._sw&&this._ne)},Tl.prototype.contains=function(t){var e=Pl.convert(t),r=e.lng,n=e.lat,i=this._sw.lng<=r&&r<=this._ne.lng;return this._sw.lng>this._ne.lng&&(i=this._sw.lng>=r&&r>=this._ne.lng),this._sw.lat<=n&&n<=this._ne.lat&&i},Tl.convert=function(t){return !t||t instanceof Tl?t:new Tl(t)};var Pl=function(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};Pl.prototype.wrap=function(){return new Pl(l(this.lng,-180,180),this.lat)},Pl.prototype.toArray=function(){return [this.lng,this.lat]},Pl.prototype.toString=function(){return "LngLat("+this.lng+", "+this.lat+")"},Pl.prototype.distanceTo=function(t){var e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return 6371008.8*Math.acos(Math.min(i,1))},Pl.prototype.toBounds=function(t){void 0===t&&(t=0);var e=360*t/40075017,r=e/Math.cos(Math.PI/180*this.lat);return new Tl(new Pl(this.lng-r,this.lat-e),new Pl(this.lng+r,this.lat+e))},Pl.convert=function(t){if(t instanceof Pl)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Pl(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Pl(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")};var Bl=2*Math.PI*6371008.8;function Vl(t){return Bl*Math.cos(t*Math.PI/180)}function Fl(t){return (180+t)/360}function Dl(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Ll(t,e){return t/Vl(e)}function Rl(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}var Ol=function(t,e,r){void 0===r&&(r=0),this.x=+t,this.y=+e,this.z=+r;};Ol.fromLngLat=function(t,e){void 0===e&&(e=0);var r=Pl.convert(t);return new Ol(Fl(r.lng),Dl(r.lat),Ll(e,r.lat))},Ol.prototype.toLngLat=function(){return new Pl(360*this.x-180,Rl(this.y))},Ol.prototype.toAltitude=function(){return this.z*Vl(Rl(this.y))},Ol.prototype.meterInMercatorCoordinateUnits=function(){return 1/Bl*(t=Rl(this.y),1/Math.cos(t*Math.PI/180));var t;};var Ul=function(t,e,r){this.z=t,this.x=e,this.y=r,this.key=Nl(0,t,t,e,r);};Ul.prototype.equals=function(t){return this.z===t.z&&this.x===t.x&&this.y===t.y},Ul.prototype.url=function(t,e){var r,n,i,a,o,s=(n=this.y,i=this.z,a=El(256*(r=this.x),256*(n=Math.pow(2,i)-n-1),i),o=El(256*(r+1),256*(n+1),i),a[0]+","+a[1]+","+o[0]+","+o[1]),u=function(t,e,r){for(var n,i="",a=t;a>0;a--)i+=(e&(n=1<this.canonical.z?new ql(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new ql(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},ql.prototype.calculateScaledKey=function(t,e){var r=this.canonical.z-t;return t>this.canonical.z?Nl(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Nl(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)},ql.prototype.isChildOf=function(t){if(t.wrap!==this.wrap)return !1;var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e},ql.prototype.children=function(t){if(this.overscaledZ>=t)return [new ql(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new ql(e,this.wrap,e,r,n),new ql(e,this.wrap,e,r+1,n),new ql(e,this.wrap,e,r,n+1),new ql(e,this.wrap,e,r+1,n+1)]},ql.prototype.isLessThan=function(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)},Kl.prototype._unpackMapbox=function(t,e,r){return (256*t*256+256*e+r)/10-1e4},Kl.prototype._unpackTerrarium=function(t,e,r){return 256*t+e+r/256-32768},Kl.prototype.getPixels=function(){return new fo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))},Kl.prototype.backfillBorder=function(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");var n=e*this.dim,i=e*this.dim+this.dim,a=r*this.dim,o=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:a=o-1;break;case 1:o=a+1;}for(var s=-e*this.dim,u=-r*this.dim,l=a;l=0&&p[3]>=0&&s.insert(o,p[0],p[1],p[2],p[3]);}},Hl.prototype.loadVTLayers=function(){return this.vtLayers||(this.vtLayers=new ds.VectorTile(new Ks(this.rawTileData)).layers,this.sourceLayerCoder=new Gl(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers},Hl.prototype.query=function(t,e,r,n){var a=this;this.loadVTLayers();for(var o=t.params||{},s=8192/t.tileSize/t.scale,u=rn(o.filter),l=t.queryGeometry,p=t.queryPadding*s,c=$l(l),h=this.grid.query(c.minX-p,c.minY-p,c.maxX+p,c.maxY+p),f=$l(t.cameraQueryGeometry),y=this.grid3D.query(f.minX-p,f.minY-p,f.maxX+p,f.maxY+p,(function(e,r,n,a){return function(t,e,r,n,a){for(var o=0,s=t;o=u.x&&a>=u.y)return !0}var l=[new i(e,r),new i(e,a),new i(n,a),new i(n,r)];if(t.length>2)for(var p=0,c=l;p=0)return !0;return !1}(a,c)){var h=this.sourceLayerCoder.decode(r),f=this.vtLayers[h].feature(n);if(i.filter(new ii(this.tileID.overscaledZ),f))for(var y=this.getId(f,h),d=0;dn)i=!1;else if(e)if(this.expirationTimeot&&(t.getActor().send("enforceCacheSizeLimit",at),pt=0);},t.clamp=u,t.clearTileCache=function(t){var e=self.caches.delete("mapbox-tiles");t&&e.catch(t).then((function(){return t()}));},t.clipLine=Uu,t.clone=function(t){var e=new to(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.clone$1=x,t.clone$2=function(t){var e=new to(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.collisionCircleLayout=Os,t.config=L,t.create=function(){var t=new to(16);return to!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.create$1=function(){var t=new to(9);return to!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t},t.create$2=function(){var t=new to(4);return to!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t},t.createCommonjsModule=e,t.createExpression=Nr,t.createLayout=Ai,t.createStyleLayer=function(t){return "custom"===t.type?new bl(t):new wl[t.type](t)},t.cross=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],u=r[2];return t[0]=i*u-a*s,t[1]=a*o-n*u,t[2]=n*s-i*o,t},t.deepEqual=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(var n=0;n0&&(a=1/Math.sqrt(a)),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a,t},t.number=je,t.offscreenCanvasSupported=ct,t.ortho=function(t,e,r,n,i,a,o){var s=1/(e-r),u=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*u,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*u,t[14]=(o+a)*l,t[15]=1,t},t.parseGlyphPBF=function(t){return new Ks(t).readFields(uu,[])},t.pbf=Ks,t.performSymbolLayout=function(t,e,r,n,i,a,o){t.createArrays(),t.tilePixelRatio=8192/(512*t.overscaling),t.compareText={},t.iconsNeedLinear=!1;var s=t.layers[0].layout,u=t.layers[0]._unevaluatedLayout._values,l={};if("composite"===t.textSizeData.kind){var p=t.textSizeData,c=p.maxZoom;l.compositeTextSizes=[u["text-size"].possiblyEvaluate(new ii(p.minZoom),o),u["text-size"].possiblyEvaluate(new ii(c),o)];}if("composite"===t.iconSizeData.kind){var h=t.iconSizeData,f=h.maxZoom;l.compositeIconSizes=[u["icon-size"].possiblyEvaluate(new ii(h.minZoom),o),u["icon-size"].possiblyEvaluate(new ii(f),o)];}l.layoutTextSize=u["text-size"].possiblyEvaluate(new ii(t.zoom+1),o),l.layoutIconSize=u["icon-size"].possiblyEvaluate(new ii(t.zoom+1),o),l.textMaxSize=u["text-size"].possiblyEvaluate(new ii(18));for(var y=24*s.get("text-line-height"),d="map"===s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement"),m=s.get("text-keep-upright"),v=s.get("text-size"),g=function(){var a=b[x],u=s.get("text-font").evaluate(a,{},o).join(","),p=v.evaluate(a,{},o),c=l.layoutTextSize.evaluate(a,{},o),h=l.layoutIconSize.evaluate(a,{},o),f={horizontal:{},vertical:void 0},g=a.text,_=[0,0];if(g){var A=g.toString(),S=24*s.get("text-letter-spacing").evaluate(a,{},o),k=function(t){for(var e=0,r=t;e=8192||c.y<0||c.y>=8192||function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,_,A,S,k){var I,z,C,M,E,T=t.addToLineVertexArray(e,r),P=0,B=0,V=0,F=0,D=-1,L=-1,R={},O=la(""),U=0,j=0;if(void 0===s._unevaluatedLayout.getValue("text-radial-offset")?(U=(I=s.layout.get("text-offset").evaluate(b,{},S).map((function(t){return 24*t})))[0],j=I[1]):(U=24*s.layout.get("text-radial-offset").evaluate(b,{},S),j=Wu),t.allowVerticalPlacement&&n.vertical){var q=s.layout.get("text-rotate").evaluate(b,{},S)+90;M=new Zu(u,e,l,p,c,n.vertical,h,f,y,q),o&&(E=new Zu(u,e,l,p,c,o,m,v,y,q));}if(i){var N=s.layout.get("icon-rotate").evaluate(b,{}),K="none"!==s.layout.get("icon-text-fit"),G=ju(i,N,A,K),Z=o?ju(o,N,A,K):void 0;C=new Zu(u,e,l,p,c,i,m,v,!1,N),P=4*G.length;var X=t.iconSizeData,J=null;"source"===X.kind?(J=[128*s.layout.get("icon-size").evaluate(b,{})])[0]>32640&&w(t.layerIds[0]+': Value for "icon-size" is >= 255. Reduce your "icon-size".'):"composite"===X.kind&&((J=[128*_.compositeIconSizes[0].evaluate(b,{},S),128*_.compositeIconSizes[1].evaluate(b,{},S)])[0]>32640||J[1]>32640)&&w(t.layerIds[0]+': Value for "icon-size" is >= 255. Reduce your "icon-size".'),t.addSymbols(t.icon,G,J,x,g,b,!1,e,T.lineStartIndex,T.lineLength,-1,S),D=t.icon.placedSymbolArray.length-1,Z&&(B=4*Z.length,t.addSymbols(t.icon,Z,J,x,g,b,du.vertical,e,T.lineStartIndex,T.lineLength,-1,S),L=t.icon.placedSymbolArray.length-1);}for(var H in n.horizontal){var Y=n.horizontal[H];if(!z){O=la(Y.text);var $=s.layout.get("text-rotate").evaluate(b,{},S);z=new Zu(u,e,l,p,c,Y,h,f,y,$);}var W=1===Y.positionedLines.length;if(V+=el(t,e,Y,a,s,y,b,d,T,n.vertical?du.horizontal:du.horizontalOnly,W?Object.keys(n.horizontal):[H],R,D,_,S),W)break}n.vertical&&(F+=el(t,e,n.vertical,a,s,y,b,d,T,du.vertical,["vertical"],R,L,_,S));var Q=z?z.boxStartIndex:t.collisionBoxArray.length,tt=z?z.boxEndIndex:t.collisionBoxArray.length,et=M?M.boxStartIndex:t.collisionBoxArray.length,rt=M?M.boxEndIndex:t.collisionBoxArray.length,nt=C?C.boxStartIndex:t.collisionBoxArray.length,it=C?C.boxEndIndex:t.collisionBoxArray.length,at=E?E.boxStartIndex:t.collisionBoxArray.length,ot=E?E.boxEndIndex:t.collisionBoxArray.length,st=-1,ut=function(t,e){return t&&t.circleDiameter?Math.max(t.circleDiameter,e):e};st=ut(z,st),st=ut(M,st),st=ut(C,st);var lt=(st=ut(E,st))>-1?1:0;lt&&(st*=k/24),t.glyphOffsetArray.length>=cl.MAX_GLYPHS&&w("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==b.sortKey&&t.addToSortKeyRanges(t.symbolInstances.length,b.sortKey),t.symbolInstances.emplaceBack(e.x,e.y,R.right>=0?R.right:-1,R.center>=0?R.center:-1,R.left>=0?R.left:-1,R.vertical||-1,D,L,O,Q,tt,et,rt,nt,it,at,ot,l,V,F,P,B,lt,0,h,U,j,st);}(t,c,s,r,n,i,h,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,v,_,k,u,x,A,I,y,e,a,l,p,o);};if("line"===z)for(var T=0,P=Uu(e.geometry,0,0,8192,8192);T1){var U=Ru(O,S,r.vertical||d,n,24,g);U&&E(O,U);}}else if("Polygon"===e.type)for(var j=0,q=Wo(e.geometry,0);j=T.maxzoom||"none"!==T.visibility&&(s(P,this.zoom,i),(g[T.id]=T.createBucket({index:h.bucketLayerIDs.length,layers:P,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:w,sourceID:this.source})).populate(S,v,this.tileID.canonical),h.bucketLayerIDs.push(P.map((function(e){return e.id}))));}}}var C=e.mapObject(v.glyphDependencies,(function(e){return Object.keys(e).map(Number)}));Object.keys(C).length?n.send("getGlyphs",{uid:this.uid,stacks:C},(function(e,t){c||(c=e,p=t,O.call(l));})):p={};var D=Object.keys(v.iconDependencies);D.length?n.send("getImages",{icons:D,source:this.source,tileID:this.tileID,type:"icons"},(function(e,t){c||(c=e,f=t,O.call(l));})):f={};var L=Object.keys(v.patternDependencies);function O(){if(c)return a(c);if(p&&f&&d){var t=new o(p),r=new e.ImageAtlas(f,d);for(var n in g){var l=g[n];l instanceof e.SymbolBucket?(s(l.layers,this.zoom,i),e.performSymbolLayout(l,p,t.positions,f,r.iconPositions,this.showCollisionBoxes,this.tileID.canonical)):l.hasPattern&&(l instanceof e.LineBucket||l instanceof e.FillBucket||l instanceof e.FillExtrusionBucket)&&(s(l.layers,this.zoom,i),l.addFeatures(v,this.tileID.canonical,r.patternPositions));}this.status="done",a(null,{buckets:e.values(g).filter((function(e){return !e.isEmpty()})),featureIndex:h,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:t.image,imageAtlas:r,glyphMap:this.returnDependencies?p:null,iconMap:this.returnDependencies?f:null,glyphPositions:this.returnDependencies?t.positions:null});}}L.length?n.send("getImages",{icons:L,source:this.source,tileID:this.tileID,type:"patterns"},(function(e,t){c||(c=e,d=t,O.call(l));})):d={},O.call(this);};var l=function(e,t,r,i){this.actor=e,this.layerIndex=t,this.availableImages=r,this.loadVectorData=i||a,this.loading={},this.loaded={};};l.prototype.loadTile=function(t,r){var i=this,o=t.uid;this.loading||(this.loading={});var s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.RequestPerformance(t.request),a=this.loading[o]=new n(t);a.abort=this.loadVectorData(t,(function(t,n){if(delete i.loading[o],t||!n)return a.status="done",i.loaded[o]=a,r(t);var l=n.rawData,u={};n.expires&&(u.expires=n.expires),n.cacheControl&&(u.cacheControl=n.cacheControl);var h={};if(s){var c=s.finish();c&&(h.resourceTiming=JSON.parse(JSON.stringify(c)));}a.vectorTile=n.vectorTile,a.parse(n.vectorTile,i.layerIndex,i.availableImages,i.actor,(function(t,i){if(t||!i)return r(t);r(null,e.extend({rawTileData:l.slice(0)},i,u,h));})),i.loaded=i.loaded||{},i.loaded[o]=a;}));},l.prototype.reloadTile=function(e,t){var r=this,i=this.loaded,o=e.uid,n=this;if(i&&i[o]){var s=i[o];s.showCollisionBoxes=e.showCollisionBoxes;var a=function(e,i){var o=s.reloadCallback;o&&(delete s.reloadCallback,s.parse(s.vectorTile,n.layerIndex,r.availableImages,n.actor,o)),t(e,i);};"parsing"===s.status?s.reloadCallback=a:"done"===s.status&&(s.vectorTile?s.parse(s.vectorTile,this.layerIndex,this.availableImages,this.actor,a):a());}},l.prototype.abortTile=function(e,t){var r=this.loading,i=e.uid;r&&r[i]&&r[i].abort&&(r[i].abort(),delete r[i]),t();},l.prototype.removeTile=function(e,t){var r=this.loaded,i=e.uid;r&&r[i]&&delete r[i],t();};var u=e.window.ImageBitmap,h=function(){this.loaded={};};function c(e,t){if(0!==e.length){p(e[0],t);for(var r=1;r=0!=!!t&&e.reverse();}h.prototype.loadTile=function(t,r){var i=t.uid,o=t.encoding,n=t.rawImageData,s=u&&n instanceof u?this.getImageData(n):n,a=new e.DEMData(i,s,o);this.loaded=this.loaded||{},this.loaded[i]=a,r(null,a);},h.prototype.getImageData=function(t){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(t.width,t.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d")),this.offscreenCanvas.width=t.width,this.offscreenCanvas.height=t.height,this.offscreenCanvasContext.drawImage(t,0,0,t.width,t.height);var r=this.offscreenCanvasContext.getImageData(-1,-1,t.width+2,t.height+2);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),new e.RGBAImage({width:r.width,height:r.height},r.data)},h.prototype.removeTile=function(e){var t=this.loaded,r=e.uid;t&&t[r]&&delete t[r];};var f=e.vectorTile.VectorTileFeature.prototype.toGeoJSON,d=function(t){this._feature=t,this.extent=e.EXTENT,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10));};d.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],r=0,i=this._feature.geometry;r>31}function T(e,t){for(var r=e.loadGeometry(),i=e.type,o=0,n=0,s=r.length,a=0;a>1;!function e(t,r,i,o,n,s){for(;n>o;){if(n-o>600){var a=n-o+1,l=i-o+1,u=Math.log(a),h=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*h*(a-h)/a)*(l-a/2<0?-1:1);e(t,r,i,Math.max(o,Math.floor(i-l*h/a+c)),Math.min(n,Math.floor(i+(a-l)*h/a+c)),s);}var p=r[2*i+s],f=o,d=n;for(D(t,r,o,i),r[2*n+s]>p&&D(t,r,o,n);fp;)d--;}r[2*o+s]===p?D(t,r,o,d):D(t,r,++d,n),d<=i&&(o=d+1),i<=d&&(n=d-1);}}(t,r,a,o,n,s%2),e(t,r,i,o,a-1,s+1),e(t,r,i,a+1,n,s+1);}}(s,a,i,0,s.length-1,0);};F.prototype.range=function(e,t,r,i){return function(e,t,r,i,o,n,s){for(var a,l,u=[0,e.length-1,0],h=[];u.length;){var c=u.pop(),p=u.pop(),f=u.pop();if(p-f<=s)for(var d=f;d<=p;d++)l=t[2*d+1],(a=t[2*d])>=r&&a<=o&&l>=i&&l<=n&&h.push(e[d]);else {var g=Math.floor((f+p)/2);l=t[2*g+1],(a=t[2*g])>=r&&a<=o&&l>=i&&l<=n&&h.push(e[g]);var v=(c+1)%2;(0===c?r<=a:i<=l)&&(u.push(f),u.push(g-1),u.push(v)),(0===c?o>=a:n>=l)&&(u.push(g+1),u.push(p),u.push(v));}}return h}(this.ids,this.coords,e,t,r,i,this.nodeSize)},F.prototype.within=function(e,t,r){return function(e,t,r,i,o,n){for(var s=[0,e.length-1,0],a=[],l=o*o;s.length;){var u=s.pop(),h=s.pop(),c=s.pop();if(h-c<=n)for(var p=c;p<=h;p++)O(t[2*p],t[2*p+1],r,i)<=l&&a.push(e[p]);else {var f=Math.floor((c+h)/2),d=t[2*f],g=t[2*f+1];O(d,g,r,i)<=l&&a.push(e[f]);var v=(u+1)%2;(0===u?r-o<=d:i-o<=g)&&(s.push(c),s.push(f-1),s.push(v)),(0===u?r+o>=d:i+o>=g)&&(s.push(f+1),s.push(h),s.push(v));}}return a}(this.ids,this.coords,e,t,r,this.nodeSize)};var N={minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:function(e){return e}},J=function(e){this.options=V(Object.create(N),e),this.trees=new Array(this.options.maxZoom+1);};function Z(e,t,r,i,o){return {x:e,y:t,zoom:1/0,id:r,parentId:-1,numPoints:i,properties:o}}function A(e,t){var r=e.geometry.coordinates,i=r[1];return {x:Y(r[0]),y:j(i),zoom:1/0,index:t,parentId:-1}}function B(e){return {type:"Feature",id:e.id,properties:G(e),geometry:{type:"Point",coordinates:[(i=e.x,360*(i-.5)),(t=e.y,r=(180-360*t)*Math.PI/180,360*Math.atan(Math.exp(r))/Math.PI-90)]}};var t,r,i;}function G(e){var t=e.numPoints,r=t>=1e4?Math.round(t/1e3)+"k":t>=1e3?Math.round(t/100)/10+"k":t;return V(V({},e.properties),{cluster:!0,cluster_id:e.id,point_count:t,point_count_abbreviated:r})}function Y(e){return e/360+.5}function j(e){var t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function V(e,t){for(var r in t)e[r]=t[r];return e}function X(e){return e.x}function W(e){return e.y}function R(e,t,r,i,o,n){var s=o-r,a=n-i;if(0!==s||0!==a){var l=((e-r)*s+(t-i)*a)/(s*s+a*a);l>1?(r=o,i=n):l>0&&(r+=s*l,i+=a*l);}return (s=e-r)*s+(a=t-i)*a}function q(e,t,r,i){var o={id:void 0===e?null:e,type:t,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(e){var t=e.geometry,r=e.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)U(e,t);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i0&&(s+=i?(o*u-l*n)/2:Math.sqrt(Math.pow(l-o,2)+Math.pow(u-n,2))),o=l,n=u;}var h=t.length-3;t[2]=1,function e(t,r,i,o){for(var n,s=o,a=i-r>>1,l=i-r,u=t[r],h=t[r+1],c=t[i],p=t[i+1],f=r+3;fs)n=f,s=d;else if(d===s){var g=Math.abs(f-a);go&&(n-r>3&&e(t,r,n,o),t[n+2]=s,i-n>3&&e(t,n,i,o));}(t,0,h,r),t[h+2]=1,t.size=Math.abs(s),t.start=0,t.end=t.size;}function Q(e,t,r,i){for(var o=0;o1?1:r}function re(e,t,r,i,o,n,s,a){if(i/=t,n>=(r/=t)&&s=i)return null;for(var l=[],u=0;u=r&&d=i)){var g=[];if("Point"===p||"MultiPoint"===p)ie(c,g,r,i,o);else if("LineString"===p)oe(c,g,r,i,o,!1,a.lineMetrics);else if("MultiLineString"===p)se(c,g,r,i,o,!1);else if("Polygon"===p)se(c,g,r,i,o,!0);else if("MultiPolygon"===p)for(var v=0;v=r&&s<=i&&(t.push(e[n]),t.push(e[n+1]),t.push(e[n+2]));}}function oe(e,t,r,i,o,n,s){for(var a,l,u=ne(e),h=0===o?le:ue,c=e.start,p=0;pr&&(l=h(u,f,d,v,m,r),s&&(u.start=c+a*l)):y>i?x=r&&(l=h(u,f,d,v,m,r),w=!0),x>i&&y<=i&&(l=h(u,f,d,v,m,i),w=!0),!n&&w&&(s&&(u.end=c+a*l),t.push(u),u=ne(e)),s&&(c+=a);}var S=e.length-3;f=e[S],d=e[S+1],g=e[S+2],(y=0===o?f:d)>=r&&y<=i&&ae(u,f,d,g),S=u.length-3,n&&S>=3&&(u[S]!==u[0]||u[S+1]!==u[1])&&ae(u,u[0],u[1],u[2]),u.length&&t.push(u);}function ne(e){var t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function se(e,t,r,i,o,n){for(var s=0;ss.maxX&&(s.maxX=h),c>s.maxY&&(s.maxY=c);}return s}function ge(e,t,r,i){var o=t.geometry,n=t.type,s=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a0&&t.size<(o?s:i))r.numPoints+=t.length/3;else {for(var a=[],l=0;ls)&&(r.numSimplified++,a.push(t[l]),a.push(t[l+1])),r.numPoints++;o&&function(e,t){for(var r=0,i=0,o=e.length,n=o-2;i0===t)for(i=0,o=e.length;i24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");var i=function(e,t){var r=[];if("FeatureCollection"===e.type)for(var i=0;i=i;u--){var h=+Date.now();a=this._cluster(a,u),this.trees[u]=new F(a,X,W,n,Float32Array),r&&console.log("z%d: %d clusters in %dms",u,a.length,+Date.now()-h);}return r&&console.timeEnd("total time"),this},J.prototype.getClusters=function(e,t){var r=((e[0]+180)%360+360)%360-180,i=Math.max(-90,Math.min(90,e[1])),o=180===e[2]?180:((e[2]+180)%360+360)%360-180,n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)r=-180,o=180;else if(r>o){var s=this.getClusters([r,i,180,n],t),a=this.getClusters([-180,i,o,n],t);return s.concat(a)}for(var l=this.trees[this._limitZoom(t)],u=[],h=0,c=l.range(Y(r),j(n),Y(o),j(i));h1?this._map(a,!0):null,d=(s<<5)+(t+1)+this.points.length,g=0,v=u;g>5},J.prototype._getOriginZoom=function(e){return (e-this.points.length)%32},J.prototype._map=function(e,t){if(e.numPoints)return t?V({},e.properties):e.properties;var r=this.points[e.index].properties,i=this.options.map(r);return t&&i===r?V({},i):i},me.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0},me.prototype.splitTile=function(e,t,r,i,o,n,s){for(var a=[e,t,r,i],l=this.options,u=l.debug;a.length;){i=a.pop(),r=a.pop(),t=a.pop(),e=a.pop();var h=1<1&&console.time("creation"),p=this.tiles[c]=de(e,t,r,i,l),this.tileCoords.push({z:t,x:r,y:i}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,r,i,p.numFeatures,p.numPoints,p.numSimplified),console.timeEnd("creation"));var f="z"+t;this.stats[f]=(this.stats[f]||0)+1,this.total++;}if(p.source=e,o){if(t===l.maxZoom||t===o)continue;var d=1<1&&console.time("clipping");var g,v,m,y,x,w,S=.5*l.buffer/l.extent,I=.5-S,M=.5+S,b=1+S;g=v=m=y=null,x=re(e,h,r-S,r+M,0,p.minX,p.maxX,l),w=re(e,h,r+I,r+b,0,p.minX,p.maxX,l),e=null,x&&(g=re(x,h,i-S,i+M,1,p.minY,p.maxY,l),v=re(x,h,i+I,i+b,1,p.minY,p.maxY,l),x=null),w&&(m=re(w,h,i-S,i+M,1,p.minY,p.maxY,l),y=re(w,h,i+I,i+b,1,p.minY,p.maxY,l),w=null),u>1&&console.timeEnd("clipping"),a.push(g||[],t+1,2*r,2*i),a.push(v||[],t+1,2*r,2*i+1),a.push(m||[],t+1,2*r+1,2*i),a.push(y||[],t+1,2*r+1,2*i+1);}}},me.prototype.getTile=function(e,t,r){var i=this.options,o=i.extent,n=i.debug;if(e<0||e>24)return null;var s=1<1&&console.log("drilling down to z%d-%d-%d",e,t,r);for(var l,u=e,h=t,c=r;!l&&u>0;)u--,h=Math.floor(h/2),c=Math.floor(c/2),l=this.tiles[ye(u,h,c)];return l&&l.source?(n>1&&console.log("found parent tile z%d-%d-%d",u,h,c),n>1&&console.time("drilling down"),this.splitTile(l.source,u,h,c,e,t,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?pe(this.tiles[a],o):null):null};var we=function(t){function r(e,r,i,o){t.call(this,e,r,i,xe),o&&(this.loadGeoJSON=o);}return t&&(r.__proto__=t),(r.prototype=Object.create(t&&t.prototype)).constructor=r,r.prototype.loadData=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),this._pendingCallback=t,this._pendingLoadDataParams=e,this._state&&"Idle"!==this._state?this._state="NeedsLoadData":(this._state="Coalescing",this._loadData());},r.prototype._loadData=function(){var t=this;if(this._pendingCallback&&this._pendingLoadDataParams){var r=this._pendingCallback,i=this._pendingLoadDataParams;delete this._pendingCallback,delete this._pendingLoadDataParams;var o=!!(i&&i.request&&i.request.collectResourceTiming)&&new e.RequestPerformance(i.request);this.loadGeoJSON(i,(function(n,s){if(n||!s)return r(n);if("object"!=typeof s)return r(new Error("Input data given to '"+i.source+"' is not a valid GeoJSON object."));!function e(t,r){var i,o=t&&t.type;if("FeatureCollection"===o)for(i=0;i=0?0:e.button},i.remove=function(t){t.parentNode&&t.parentNode.removeChild(t);};var p=function(e){function i(){e.call(this),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.RGBAImage({width:1,height:1}),this.dirty=!0;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.isLoaded=function(){return this.loaded},i.prototype.setLoaded=function(t){if(this.loaded!==t&&(this.loaded=t,t)){for(var e=0,i=this.requestors;e=0?1.2:1));}function g(t,e,i,o,r,a,n){for(var s=0;s65535)e(new Error("glyphs > 65535 not supported"));else if(a.ranges[s])e(null,{stack:i,id:r,glyph:n});else {var l=a.requests[s];l||(l=a.requests[s]=[],y.loadGlyphRange(i,s,o.url,o.requestManager,(function(t,e){if(e){for(var i in e)o._doesCharSupportLocalGlyph(+i)||(a.glyphs[+i]=e[+i]);a.ranges[s]=!0;}for(var r=0,n=l;r1&&(s=t[++n]);var c=Math.abs(l-s.left),u=Math.abs(l-s.right),h=Math.min(c,u),p=void 0,d=r/i*(o+1);if(s.isDash){var _=o-Math.abs(d);p=Math.sqrt(h*h+_*_);}else p=o-Math.sqrt(h*h+d*d);this.data[a+l]=Math.max(0,Math.min(255,p+128));}},T.prototype.addRegularDash=function(t){for(var e=t.length-1;e>=0;--e){var i=t[e],o=t[e+1];i.zeroLength?t.splice(e,1):o&&o.isDash===i.isDash&&(o.left=i.left,t.splice(e,1));}var r=t[0],a=t[t.length-1];r.isDash===a.isDash&&(r.left=a.left-this.width,a.right=r.right+this.width);for(var n=this.width*this.nextRow,s=0,l=t[s],c=0;c1&&(l=t[++s]);var u=Math.abs(c-l.left),h=Math.abs(c-l.right),p=Math.min(u,h);this.data[n+c]=Math.max(0,Math.min(255,(l.isDash?p:-p)+128));}},T.prototype.addDash=function(e,i){var o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.warnOnce("LineAtlas out of space"),null;for(var a=0,n=0;n=o&&e.x=r&&e.y0&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y-1).key]={backfilled:!1}),i.y+10&&(o.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire(new t.Event("data",o));}}));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setData=function(e){var i=this;return this._data=e,this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData((function(e){if(e)i.fire(new t.ErrorEvent(e));else {var o={dataType:"source",sourceDataType:"content"};i._collectResourceTiming&&i._resourceTiming&&i._resourceTiming.length>0&&(o.resourceTiming=i._resourceTiming,i._resourceTiming=[]),i.fire(new t.Event("data",o));}})),this},i.prototype.getClusterExpansionZoom=function(t,e){return this.actor.send("geojson.getClusterExpansionZoom",{clusterId:t,source:this.id},e),this},i.prototype.getClusterChildren=function(t,e){return this.actor.send("geojson.getClusterChildren",{clusterId:t,source:this.id},e),this},i.prototype.getClusterLeaves=function(t,e,i,o){return this.actor.send("geojson.getClusterLeaves",{source:this.id,clusterId:t,limit:e,offset:i},o),this},i.prototype._updateWorkerData=function(e){var i=this;this._loaded=!1;var o=t.extend({},this.workerOptions),r=this._data;"string"==typeof r?(o.request=this.map._requestManager.transformRequest(t.browser.resolveURL(r),t.ResourceType.Source),o.request.collectResourceTiming=this._collectResourceTiming):o.data=JSON.stringify(r),this.actor.send(this.type+".loadData",o,(function(t,r){i._removed||r&&r.abandoned||(i._loaded=!0,r&&r.resourceTiming&&r.resourceTiming[i.id]&&(i._resourceTiming=r.resourceTiming[i.id].slice(0)),i.actor.send(i.type+".coalesce",{source:o.source},null),e(t));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.loadTile=function(e,i){var o=this,r=e.actor?"reloadTile":"loadTile";e.actor=this.actor,e.request=this.actor.send(r,{type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:t.browser.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId},(function(t,a){return delete e.request,e.unloadVectorData(),e.aborted?i(null):t?i(t):(e.loadVectorData(a,o.map.painter,"reloadTile"===r),i(null))}));},i.prototype.abortTile=function(t){t.request&&(t.request.cancel(),delete t.request),t.aborted=!0;},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.actor.send("removeTile",{uid:t.uid,type:this.type,source:this.id});},i.prototype.onRemove=function(){this._removed=!0,this.actor.send("removeSource",{type:this.type,source:this.id});},i.prototype.serialize=function(){return t.extend({},this._options,{type:this.type,data:this._data})},i.prototype.hasTransition=function(){return !1},i}(t.Evented),M=t.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]),L=function(e){function i(t,i,o,r){e.call(this),this.id=t,this.dispatcher=o,this.coordinates=i.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(r),this.options=i;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(e,i){var o=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,t.getImage(this.map._requestManager.transformRequest(this.url,t.ResourceType.Image),(function(r,a){o._loaded=!0,r?o.fire(new t.ErrorEvent(r)):a&&(o.image=a,e&&(o.coordinates=e),i&&i(),o._finishLoading());}));},i.prototype.loaded=function(){return this._loaded},i.prototype.updateImage=function(t){var e=this;return this.image&&t.url?(this.options.url=t.url,this.load(t.coordinates,(function(){e.texture=null;})),this):this},i.prototype._finishLoading=function(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setCoordinates=function(e){var i=this;this.coordinates=e;var o=e.map(t.MercatorCoordinate.fromLngLat);this.tileID=function(e){for(var i=1/0,o=1/0,r=-1/0,a=-1/0,n=0,s=e;ni.end(0)?this.fire(new t.ErrorEvent(new t.ValidationError("sources."+this.id,null,"Playback for this video can be set only between the "+i.start(0)+" and "+i.end(0)+"-second mark."))):this.video.currentTime=e;}},i.prototype.getVideo=function(){return this.video},i.prototype.onAdd=function(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));},i.prototype.prepare=function(){if(!(0===Object.keys(this.tiles).length||this.video.readyState<2)){var e=this.map.painter.context,i=e.gl;for(var o in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.Texture(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var r=this.tiles[o];"loaded"!==r.state&&(r.state="loaded",r.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"video",urls:this.urls,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this.video&&!this.video.paused},i}(L),R=function(e){function i(i,o,r,a){e.call(this,i,o,r,a),o.coordinates?Array.isArray(o.coordinates)&&4===o.coordinates.length&&!o.coordinates.some((function(t){return !Array.isArray(t)||2!==t.length||t.some((function(t){return "number"!=typeof t}))}))||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "coordinates"'))),o.animate&&"boolean"!=typeof o.animate&&this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'optional "animate" property must be a boolean value'))),o.canvas?"string"==typeof o.canvas||o.canvas instanceof t.window.HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "canvas"'))),this.options=o,this.animate=void 0===o.animate||o.animate;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof t.window.HTMLCanvasElement?this.options.canvas:t.window.document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());},i.prototype.getCanvas=function(){return this.canvas},i.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play();},i.prototype.onRemove=function(){this.pause();},i.prototype.prepare=function(){var e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var i=this.map.painter.context,o=i.gl;for(var r in this.boundsBuffer||(this.boundsBuffer=i.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.Texture(i,this.canvas,o.RGBA,{premultiply:!0}),this.tiles){var a=this.tiles[r];"loaded"!==a.state&&(a.state="loaded",a.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"canvas",coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this._playing},i.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];tthis.max){var n=this._getAndRemoveByKey(this.order[0]);n&&this.onRemove(n);}return this},U.prototype.has=function(t){return t.wrapped().key in this.data},U.prototype.getAndRemove=function(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null},U.prototype._getAndRemoveByKey=function(t){var e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value},U.prototype.getByKey=function(t){var e=this.data[t];return e?e[0].value:null},U.prototype.get=function(t){return this.has(t)?this.data[t.wrapped().key][0].value:null},U.prototype.remove=function(t,e){if(!this.has(t))return this;var i=t.wrapped().key,o=void 0===e?0:this.data[i].indexOf(e),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this},U.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this},U.prototype.filter=function(t){var e=[];for(var i in this.data)for(var o=0,r=this.data[i];o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,o),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)));}},i.prototype.getTile=function(t){return this.getTileByID(t.key)},i.prototype.getTileByID=function(t){return this._tiles[t]},i.prototype._retainLoadedChildren=function(t,e,i,o){for(var r in this._tiles){var a=this._tiles[r];if(!(o[r]||!a.hasData()||a.tileID.overscaledZ<=e||a.tileID.overscaledZ>i)){for(var n=a.tileID;a&&a.tileID.overscaledZ>e+1;){var s=a.tileID.scaledTo(a.tileID.overscaledZ-1);(a=this._tiles[s.key])&&a.hasData()&&(n=s);}for(var l=n;l.overscaledZ>e;)if(t[(l=l.scaledTo(l.overscaledZ-1)).key]){o[n.key]=n;break}}}},i.prototype.findLoadedParent=function(t,e){if(t.key in this._loadedParentTiles){var i=this._loadedParentTiles[t.key];return i&&i.tileID.overscaledZ>=e?i:null}for(var o=t.overscaledZ-1;o>=e;o--){var r=t.scaledTo(o),a=this._getLoadedTile(r);if(a)return a}},i.prototype._getLoadedTile=function(t){var e=this._tiles[t.key];return e&&e.hasData()?e:this._cache.getByKey(t.wrapped().key)},i.prototype.updateCacheSize=function(t){var e=Math.ceil(t.width/this._source.tileSize)+1,i=Math.ceil(t.height/this._source.tileSize)+1,o=Math.floor(e*i*5),r="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,o):o;this._cache.setMaxSize(r);},i.prototype.handleWrapJump=function(t){var e=Math.round((t-(void 0===this._prevLng?t:this._prevLng))/360);if(this._prevLng=t,e){var i={};for(var o in this._tiles){var r=this._tiles[o];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+e),i[r.tileID.key]=r;}for(var a in this._tiles=i,this._timers)clearTimeout(this._timers[a]),delete this._timers[a];for(var n in this._tiles)this._setTileReloadTimer(n,this._tiles[n]);}},i.prototype.update=function(e){var o=this;if(this.transform=e,this._sourceLoaded&&!this._paused){var r;this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((function(e){return new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)})):(r=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(r=r.filter((function(t){return o._source.hasTile(t)})))):r=[];var a=e.coveringZoomLevel(this._source),n=Math.max(a-i.maxOverzooming,this._source.minzoom),s=Math.max(a+i.maxUnderzooming,this._source.minzoom),l=this._updateRetainedTiles(r,a);if(Lt(this._source.type)){for(var c={},u={},h=0,p=Object.keys(l);hthis._source.maxzoom){var m=_.children(this._source.maxzoom)[0],g=this.getTile(m);if(g&&g.hasData()){o[m.key]=m;continue}}else {var v=_.children(this._source.maxzoom);if(o[v[0].key]&&o[v[1].key]&&o[v[2].key]&&o[v[3].key])continue}for(var y=f.wasRequested(),x=_.overscaledZ-1;x>=a;--x){var b=_.scaledTo(x);if(r[b.key])break;if(r[b.key]=!0,!(f=this.getTile(b))&&y&&(f=this._addTile(b)),f&&(o[b.key]=b,y=f.wasRequested(),f.hasData()))break}}}return o},i.prototype._updateLoadedParentTileCache=function(){for(var t in this._loadedParentTiles={},this._tiles){for(var e=[],i=void 0,o=this._tiles[t].tileID;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}e.push(o.key);var r=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(r))break;o=r;}for(var a=0,n=e;a0||(e.hasData()&&"reloading"!==e.state?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));},i.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._cache.reset();},i.prototype.tilesIn=function(e,i,o){var r=this,a=[],n=this.transform;if(!n)return a;for(var s=o?n.getCameraQueryGeometry(e):e,l=e.map((function(t){return n.pointCoordinate(t)})),c=s.map((function(t){return n.pointCoordinate(t)})),u=this.getIds(),h=1/0,p=1/0,d=-1/0,_=-1/0,f=0,m=c;f=0&&g[1].y+m>=0){var v=l.map((function(t){return s.getTilePoint(t)})),y=c.map((function(t){return s.getTilePoint(t)}));a.push({tile:o,tileID:s,queryGeometry:v,cameraQueryGeometry:y,scale:f});}}},y=0;y=t.browser.now())return !0}return !1},i.prototype.setFeatureState=function(t,e,i){this._state.updateState(t=t||"_geojsonTileLayer",e,i);},i.prototype.removeFeatureState=function(t,e,i){this._state.removeFeatureState(t=t||"_geojsonTileLayer",e,i);},i.prototype.getFeatureState=function(t,e){return this._state.getState(t=t||"_geojsonTileLayer",e)},i.prototype.setDependencies=function(t,e,i){var o=this._tiles[t];o&&o.setDependencies(e,i);},i.prototype.reloadTilesForDependencies=function(t,e){for(var i in this._tiles)this._tiles[i].hasDependency(t,e)&&this._reloadTile(i,"reloading");this._cache.filter((function(i){return !i.hasDependency(t,e)}));},i}(t.Evented);function Mt(t,e){var i=Math.abs(2*t.wrap)-+(t.wrap<0),o=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||o-i||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x}function Lt(t){return "raster"===t||"image"===t||"video"===t}function At(){return new t.window.Worker(Wr.workerUrl)}Dt.maxOverzooming=10,Dt.maxUnderzooming=3;var Rt="mapboxgl_preloaded_worker_pool",kt=function(){this.active={};};kt.prototype.acquire=function(t){if(!this.workers)for(this.workers=[];this.workers.length0?(r-n)/s:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))};var Yt=function(t,e,i){var o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(var a=0;a=-e[0]&&i<=e[0]&&o>=-e[1]&&o<=e[1]}function ie(e,i,o,r,a,n,s,l){var c=r?e.textSizeData:e.iconSizeData,u=t.evaluateSizeForZoom(c,o.transform.zoom),h=[256/o.width*2+1,256/o.height*2+1],p=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;p.clear();for(var d=e.lineVertexArray,_=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,f=o.transform.width/o.transform.height,m=!1,g=0;g<_.length;g++){var v=_.get(g);if(v.hidden||v.writingMode===t.WritingMode.vertical&&!m)ce(v.numGlyphs,p);else {m=!1;var y=[v.anchorX,v.anchorY,0,1];if(t.transformMat4(y,y,i),ee(y,h)){var x=te(o.transform.cameraToCenterDistance,y[3]),b=t.evaluateSizeForFeature(c,u,v),w=s?b/x:b*x,T=new t.Point(v.anchorX,v.anchorY),E=$t(T,a).point,I={},P=ae(v,w,!1,l,i,a,n,e.glyphOffsetArray,d,p,E,T,I,f);m=P.useVertical,(P.notEnoughRoom||m||P.needsFlipping&&ae(v,w,!0,l,i,a,n,e.glyphOffsetArray,d,p,E,T,I,f).notEnoughRoom)&&ce(v.numGlyphs,p);}else ce(v.numGlyphs,p);}}r?e.text.dynamicLayoutVertexBuffer.updateData(p):e.icon.dynamicLayoutVertexBuffer.updateData(p);}function oe(t,e,i,o,r,a,n,s,l,c,u){var h=s.glyphStartIndex+s.numGlyphs,p=s.lineStartIndex,d=s.lineStartIndex+s.lineLength,_=e.getoffsetX(s.glyphStartIndex),f=e.getoffsetX(h-1),m=se(t*_,i,o,r,a,n,s.segment,p,d,l,c,u);if(!m)return null;var g=se(t*f,i,o,r,a,n,s.segment,p,d,l,c,u);return g?{first:m,last:g}:null}function re(e,i,o,r){return e===t.WritingMode.horizontal&&Math.abs(o.y-i.y)>Math.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.WritingMode.vertical?i.yo.x)?{needsFlipping:!0}:null}function ae(e,i,o,r,a,n,s,l,c,u,h,p,d,_){var f,m=i/24,g=e.lineOffsetX*m,v=e.lineOffsetY*m;if(e.numGlyphs>1){var y=e.glyphStartIndex+e.numGlyphs,x=e.lineStartIndex,b=e.lineStartIndex+e.lineLength,w=oe(m,l,g,v,o,h,p,e,c,n,d);if(!w)return {notEnoughRoom:!0};var T=$t(w.first.point,s).point,E=$t(w.last.point,s).point;if(r&&!o){var I=re(e.writingMode,T,E,_);if(I)return I}f=[w.first];for(var P=e.glyphStartIndex+1;P0?D.point:ne(p,z,S,1,a),L=re(e.writingMode,S,M,_);if(L)return L}var A=se(m*l.getoffsetX(e.glyphStartIndex),g,v,o,h,p,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,c,n,d);if(!A)return {notEnoughRoom:!0};f=[A];}for(var R=0,k=f;R0?1:-1,f=0;r&&(_*=-1,f=Math.PI),_<0&&(f+=Math.PI);for(var m=_>0?l+s:l+s+1,g=a,v=a,y=0,x=0,b=Math.abs(d),w=[];y+x<=b;){if((m+=_)=c)return null;if(v=g,w.push(g),void 0===(g=p[m])){var T=new t.Point(u.getx(m),u.gety(m)),E=$t(T,h);if(E.signedDistanceFromCamera>0)g=p[m]=E.point;else {var I=m-_;g=ne(0===y?n:new t.Point(u.getx(I),u.gety(I)),T,v,b-y+1,h);}}y+=x,x=v.dist(g);}var P=(b-y)/x,S=g.sub(v),C=S.mult(P)._add(v);C._add(S._unit()._perp()._mult(o*_));var z=f+Math.atan2(g.y-v.y,g.x-v.x);return w.push(C),{point:C,angle:z,path:w}}Yt.prototype.keysLength=function(){return this.boxKeys.length+this.circleKeys.length},Yt.prototype.insert=function(t,e,i,o,r){this._forEachCell(e,i,o,r,this._insertBoxCell,this.boxUid++),this.boxKeys.push(t),this.bboxes.push(e),this.bboxes.push(i),this.bboxes.push(o),this.bboxes.push(r);},Yt.prototype.insertCircle=function(t,e,i,o){this._forEachCell(e-o,i-o,e+o,i+o,this._insertCircleCell,this.circleUid++),this.circleKeys.push(t),this.circles.push(e),this.circles.push(i),this.circles.push(o);},Yt.prototype._insertBoxCell=function(t,e,i,o,r,a){this.boxCells[r].push(a);},Yt.prototype._insertCircleCell=function(t,e,i,o,r,a){this.circleCells[r].push(a);},Yt.prototype._query=function(t,e,i,o,r,a){if(i<0||t>this.width||o<0||e>this.height)return !r&&[];var n=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=o){if(r)return !0;for(var s=0;s0:n},Yt.prototype._queryCircle=function(t,e,i,o,r){var a=t-i,n=t+i,s=e-i,l=e+i;if(n<0||a>this.width||l<0||s>this.height)return !o&&[];var c=[];return this._forEachCell(a,s,n,l,this._queryCellCircle,c,{hitTest:o,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}},r),o?c.length>0:c},Yt.prototype.query=function(t,e,i,o,r){return this._query(t,e,i,o,!1,r)},Yt.prototype.hitTest=function(t,e,i,o,r){return this._query(t,e,i,o,!0,r)},Yt.prototype.hitTestCircle=function(t,e,i,o){return this._queryCircle(t,e,i,!0,o)},Yt.prototype._queryCell=function(t,e,i,o,r,a,n,s){var l=n.seenUids,c=this.boxCells[r];if(null!==c)for(var u=this.bboxes,h=0,p=c;h=u[_+0]&&o>=u[_+1]&&(!s||s(this.boxKeys[d]))){if(n.hitTest)return a.push(!0),!0;a.push({key:this.boxKeys[d],x1:u[_],y1:u[_+1],x2:u[_+2],y2:u[_+3]});}}}var f=this.circleCells[r];if(null!==f)for(var m=this.circles,g=0,v=f;gn*n+s*s},Yt.prototype._circleAndRectCollide=function(t,e,i,o,r,a,n){var s=(a-o)/2,l=Math.abs(t-(o+s));if(l>s+i)return !1;var c=(n-r)/2,u=Math.abs(e-(r+c));if(u>c+i)return !1;if(l<=s||u<=c)return !0;var h=l-s,p=u-c;return h*h+p*p<=i*i};var le=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function ce(t,e){for(var i=0;i=1;M--)D.push(C.path[M]);for(var L=1;L0){for(var B=D[0].clone(),O=D[0].clone(),F=1;F=I.x&&O.x<=P.x&&B.y>=I.y&&O.y<=P.y?[D]:O.xP.x||O.yP.y?[]:t.clipLine([D],I.x,I.y,P.x,P.y);}for(var U=0,N=k;U=this.screenRightBoundary||o<100||e>this.screenBottomBoundary},he.prototype.isInsideGrid=function(t,e,i,o){return i>=0&&t=0&&e0?(this.prevPlacement&&this.prevPlacement.variableOffsets[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID].text&&(f=this.prevPlacement.variableOffsets[h.crossTileID].anchor),this.variableOffsets[h.crossTileID]={textOffset:m,width:i,height:o,anchor:t,textBoxScale:r,prevAnchor:f},this.markUsedJustification(p,t,h,d),p.allowVerticalPlacement&&(this.markUsedOrientation(p,d,h),this.placedOrientations[h.crossTileID]=d),{shift:g,placedGlyphBoxes:v}):void 0},be.prototype.placeLayerBucketPart=function(e,i,o){var r=this,a=e.parameters,n=a.bucket,s=a.layout,l=a.posMatrix,c=a.textLabelPlaneMatrix,u=a.labelToScreenMatrix,h=a.textPixelRatio,p=a.holdingForFade,d=a.collisionBoxArray,_=a.partiallyEvaluatedTextSize,f=a.collisionGroup,m=s.get("text-optional"),g=s.get("icon-optional"),v=s.get("text-allow-overlap"),y=s.get("icon-allow-overlap"),x="map"===s.get("text-rotation-alignment"),b="map"===s.get("text-pitch-alignment"),w="none"!==s.get("icon-text-fit"),T="viewport-y"===s.get("symbol-z-order"),E=v&&(y||!n.hasIconData()||g),I=y&&(v||!n.hasTextData()||m);!n.collisionArrays&&d&&n.deserializeCollisionBoxes(d);var P=function(e,a){if(!i[e.crossTileID])if(p)r.placements[e.crossTileID]=new fe(!1,!1,!1);else {var d,T=!1,P=!1,S=!0,C=null,z={box:null,offscreen:null},D={box:null,offscreen:null},M=null,L=null,A=0,R=0,k=0;a.textFeatureIndex?A=a.textFeatureIndex:e.useRuntimeCollisionCircles&&(A=e.featureIndex),a.verticalTextFeatureIndex&&(R=a.verticalTextFeatureIndex);var B=a.textBox;if(B){var O=function(i){var o=t.WritingMode.horizontal;if(n.allowVerticalPlacement&&!i&&r.prevPlacement){var a=r.prevPlacement.placedOrientations[e.crossTileID];a&&(r.placedOrientations[e.crossTileID]=a,r.markUsedOrientation(n,o=a,e));}return o},F=function(i,o){if(n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&a.verticalTextBox)for(var r=0,s=n.writingModes;r0&&(U=U.filter((function(t){return t!==N.anchor}))).unshift(N.anchor);}var Z=function(t,i,o){for(var a=t.x2-t.x1,s=t.y2-t.y1,c=e.textBoxScale,u=w&&!y?i:null,p={box:[],offscreen:!1},d=v?2*U.length:U.length,_=0;_=U.length,e,n,o,u);if(m&&(p=m.placedGlyphBoxes)&&p.box&&p.box.length){T=!0,C=m.shift;break}}return p};F((function(){return Z(B,a.iconBox,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&!(z&&z.box&&z.box.length)&&e.numVerticalGlyphVertices>0&&i?Z(i,a.verticalIconBox,t.WritingMode.vertical):{box:null,offscreen:null}})),z&&(T=z.box,S=z.offscreen);var j=O(z&&z.box);if(!T&&r.prevPlacement){var q=r.prevPlacement.variableOffsets[e.crossTileID];q&&(r.variableOffsets[e.crossTileID]=q,r.markUsedJustification(n,q.anchor,e,j));}}else {var V=function(t,i){var o=r.collisionIndex.placeCollisionBox(t,v,h,l,f.predicate);return o&&o.box&&o.box.length&&(r.markUsedOrientation(n,i,e),r.placedOrientations[e.crossTileID]=i),o};F((function(){return V(B,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?V(i,t.WritingMode.vertical):{box:null,offscreen:null}})),O(z&&z.box&&z.box.length);}}if(T=(d=z)&&d.box&&d.box.length>0,S=d&&d.offscreen,e.useRuntimeCollisionCircles){var G=n.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),W=t.evaluateSizeForFeature(n.textSizeData,_,G),X=s.get("text-padding");M=r.collisionIndex.placeCollisionCircles(v,G,n.lineVertexArray,n.glyphOffsetArray,W,l,c,u,o,b,f.predicate,e.collisionCircleDiameter,X),T=v||M.circles.length>0&&!M.collisionDetected,S=S&&M.offscreen;}if(a.iconFeatureIndex&&(k=a.iconFeatureIndex),a.iconBox){var H=function(t){var e=w&&C?xe(t,C.x,C.y,x,b,r.transform.angle):t;return r.collisionIndex.placeCollisionBox(e,y,h,l,f.predicate)};P=D&&D.box&&D.box.length&&a.verticalIconBox?(L=H(a.verticalIconBox)).box.length>0:(L=H(a.iconBox)).box.length>0,S=S&&L.offscreen;}var K=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,Y=g||0===e.numIconVertices;if(K||Y?Y?K||(P=P&&T):T=P&&T:P=T=P&&T,T&&d&&d.box&&r.collisionIndex.insertCollisionBox(d.box,s.get("text-ignore-placement"),n.bucketInstanceId,D&&D.box&&R?R:A,f.ID),P&&L&&r.collisionIndex.insertCollisionBox(L.box,s.get("icon-ignore-placement"),n.bucketInstanceId,k,f.ID),M&&(T&&r.collisionIndex.insertCollisionCircles(M.circles,s.get("text-ignore-placement"),n.bucketInstanceId,A,f.ID),o)){var J=n.bucketInstanceId,Q=r.collisionCircleArrays[J];void 0===Q&&(Q=r.collisionCircleArrays[J]=new me);for(var $=0;$=0;--C){var z=S[C];P(n.symbolInstances.get(z),n.collisionArrays[z]);}else for(var D=e.symbolInstanceStart;D=0&&(e.text.placedSymbolArray.get(l).crossTileID=a>=0&&l!==a?0:o.crossTileID);}},be.prototype.markUsedOrientation=function(e,i,o){for(var r=i===t.WritingMode.horizontal||i===t.WritingMode.horizontalOnly?i:0,a=i===t.WritingMode.vertical?i:0,n=0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];n0,v=r.placedOrientations[a.crossTileID],y=v===t.WritingMode.vertical,x=v===t.WritingMode.horizontal||v===t.WritingMode.horizontalOnly;if(s>0||l>0){var b=De(m.text);_(e.text,s,y?Me:b),_(e.text,l,x?Me:b);var w=m.text.isHidden();[a.rightJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.leftJustifiedTextSymbolIndex].forEach((function(t){t>=0&&(e.text.placedSymbolArray.get(t).hidden=w||y?1:0);})),a.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).hidden=w||x?1:0);var T=r.variableOffsets[a.crossTileID];T&&r.markUsedJustification(e,T.anchor,a,v);var E=r.placedOrientations[a.crossTileID];E&&(r.markUsedJustification(e,"left",a,E),r.markUsedOrientation(e,E,a));}if(g){var I=De(m.icon),P=!(p&&a.verticalPlacedIconSymbolIndex&&y);a.placedIconSymbolIndex>=0&&(_(e.icon,a.numIconVertices,P?I:Me),e.icon.placedSymbolArray.get(a.placedIconSymbolIndex).hidden=m.icon.isHidden()),a.verticalPlacedIconSymbolIndex>=0&&(_(e.icon,a.numVerticalIconVertices,P?Me:I),e.icon.placedSymbolArray.get(a.verticalPlacedIconSymbolIndex).hidden=m.icon.isHidden());}if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){var S=e.collisionArrays[o];if(S){var C=new t.Point(0,0);if(S.textBox||S.verticalTextBox){var z=!0;if(c){var D=r.variableOffsets[f];D?(C=ye(D.anchor,D.width,D.height,D.textOffset,D.textBoxScale),u&&C._rotate(h?r.transform.angle:-r.transform.angle)):z=!1;}S.textBox&&we(e.textCollisionBox.collisionVertexArray,m.text.placed,!z||y,C.x,C.y),S.verticalTextBox&&we(e.textCollisionBox.collisionVertexArray,m.text.placed,!z||x,C.x,C.y);}var M=Boolean(!x&&S.verticalIconBox);S.iconBox&&we(e.iconCollisionBox.collisionVertexArray,m.icon.placed,M,p?C.x:0,p?C.y:0),S.verticalIconBox&&we(e.iconCollisionBox.collisionVertexArray,m.icon.placed,!M,p?C.x:0,p?C.y:0);}}},m=0;mt},be.prototype.setStale=function(){this.stale=!0;};var Te=Math.pow(2,25),Ee=Math.pow(2,24),Ie=Math.pow(2,17),Pe=Math.pow(2,16),Se=Math.pow(2,9),Ce=Math.pow(2,8),ze=Math.pow(2,1);function De(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;var e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*Te+e*Ee+i*Ie+e*Pe+i*Se+e*Ce+i*ze+e}var Me=0,Le=function(t){this._sortAcrossTiles="viewport-y"!==t.layout.get("symbol-z-order")&&void 0!==t.layout.get("symbol-sort-key").constantOr(1),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];};Le.prototype.continuePlacement=function(t,e,i,o,r){for(var a=this._bucketParts;this._currentTileIndex2};this._currentPlacementIndex>=0;){var s=i[e[this._currentPlacementIndex]],l=this.placement.collisionIndex.transform.zoom;if("symbol"===s.type&&(!s.minzoom||s.minzoom<=l)&&(!s.maxzoom||s.maxzoom>l)){if(this._inProgressLayer||(this._inProgressLayer=new Le(s)),this._inProgressLayer.continuePlacement(o[s.source],this.placement,this._showCollisionBoxes,s,n))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;},Ae.prototype.commit=function(t){return this.placement.commit(t),this.placement};var Re=512/t.EXTENT/2,ke=function(t,e,i){this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=i;for(var o=0;ot.overscaledZ)for(var s in n){var l=n[s];l.tileID.isChildOf(t)&&l.findMatches(e.symbolInstances,t,r);}else {var c=n[t.scaledTo(Number(a)).key];c&&c.findMatches(e.symbolInstances,t,r);}}for(var u=0;u1?"@2x":"",l=t.getJSON(i.transformRequest(i.normalizeSpriteURL(e,s,".json"),t.ResourceType.SpriteJSON),(function(t,e){l=null,n||(n=t,r=e,u());})),c=t.getImage(i.transformRequest(i.normalizeSpriteURL(e,s,".png"),t.ResourceType.SpriteImage),(function(t,e){c=null,n||(n=t,a=e,u());}));function u(){if(n)o(n);else if(r&&a){var e=t.browser.getImageData(a),i={};for(var s in r){var l=r[s],c=l.width,u=l.height,h=l.x,p=l.y,d=l.sdf,_=l.pixelRatio,f=l.stretchX,m=l.stretchY,g=l.content,v=new t.RGBAImage({width:c,height:u});t.RGBAImage.copy(e,v,{x:h,y:p},{x:0,y:0},{width:c,height:u}),i[s]={data:v,pixelRatio:_,sdf:d,stretchX:f,stretchY:m,content:g};}o(null,i);}}return {cancel:function(){l&&(l.cancel(),l=null),c&&(c.cancel(),c=null);}}}(e,this.map._requestManager,(function(e,o){if(i._spriteRequest=null,e)i.fire(new t.ErrorEvent(e));else if(o)for(var r in o)i.imageManager.addImage(r,o[r]);i.imageManager.setLoaded(!0),i._availableImages=i.imageManager.listImages(),i.dispatcher.broadcast("setImages",i._availableImages),i.fire(new t.Event("data",{dataType:"style"}));}));},i.prototype._validateLayer=function(e){var i=this.sourceCaches[e.source];if(i){var o=e.sourceLayer;if(o){var r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.ErrorEvent(new Error('Source layer "'+o+'" does not exist on source "'+r.id+'" as specified by style layer "'+e.id+'"')));}}},i.prototype.loaded=function(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(var t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return !1;return !!this.imageManager.isLoaded()},i.prototype._serializeLayers=function(t){for(var e=[],i=0,o=t;i0)throw new Error("Unimplemented: "+r.map((function(t){return t.command})).join(", ")+".");return o.forEach((function(t){"setTransition"!==t.command&&i[t.command].apply(i,t.args);})),this.stylesheet=e,!0},i.prototype.addImage=function(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error("An image with this name already exists.")));this.imageManager.addImage(e,i),this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.updateImage=function(t,e){this.imageManager.updateImage(t,e);},i.prototype.getImage=function(t){return this.imageManager.getImage(t)},i.prototype.removeImage=function(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error("No image with this name exists.")));this.imageManager.removeImage(e),this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.listImages=function(){return this._checkLoaded(),this.imageManager.listImages()},i.prototype.addSource=function(e,i,o){var r=this;if(void 0===o&&(o={}),this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error("There is already a source with this ID");if(!i.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(i).join(", ")+".");if(!(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.validateStyle.source,"sources."+e,i,null,o))){this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);var a=this.sourceCaches[e]=new Dt(e,i,this.dispatcher);a.style=this,a.setEventedParent(this,(function(){return {isSourceLoaded:r.loaded(),source:a.serialize(),sourceId:e}})),a.onAdd(this.map),this._changed=!0;}},i.prototype.removeSource=function(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(var i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error('Source "'+e+'" cannot be removed while layer "'+i+'" is using it.')));var o=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],o.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),o.setEventedParent(null),o.clearTiles(),o.onRemove&&o.onRemove(this.map),this._changed=!0;},i.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0;},i.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},i.prototype.addLayer=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=e.id;if(this.getLayer(r))this.fire(new t.ErrorEvent(new Error('Layer with id "'+r+'" already exists on this map')));else {var a;if("custom"===e.type){if(Ue(this,t.validateCustomStyleLayer(e)))return;a=t.createStyleLayer(e);}else {if("object"==typeof e.source&&(this.addSource(r,e.source),e=t.clone$1(e),e=t.extend(e,{source:r})),this._validate(t.validateStyle.layer,"layers."+r,e,{arrayIndex:-1},o))return;a=t.createStyleLayer(e),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}}),this._serializedLayers[a.id]=a.serialize();}var n=i?this._order.indexOf(i):this._order.length;if(i&&-1===n)this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.')));else {if(this._order.splice(n,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){var s=this._removedLayers[r];delete this._removedLayers[r],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}},i.prototype.moveLayer=function(e,i){if(this._checkLoaded(),this._changed=!0,this._layers[e]){if(e!==i){var o=this._order.indexOf(e);this._order.splice(o,1);var r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.'))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be moved.")));},i.prototype.removeLayer=function(e){this._checkLoaded();var i=this._layers[e];if(i){i.setEventedParent(null);var o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be removed.")));},i.prototype.getLayer=function(t){return this._layers[t]},i.prototype.hasLayer=function(t){return t in this._layers},i.prototype.setLayerZoomRange=function(e,i,o){this._checkLoaded();var r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot have zoom extent.")));},i.prototype.setFilter=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=this.getLayer(e);if(r){if(!t.deepEqual(r.filter,i))return null==i?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(t.validateStyle.filter,"layers."+r.id+".filter",i,null,o)||(r.filter=t.clone$1(i),this._updateLayer(r)))}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be filtered.")));},i.prototype.getFilter=function(e){return t.clone$1(this.getLayer(e).filter)},i.prototype.setLayoutProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getLayoutProperty=function(e,i){var o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style.")));},i.prototype.setPaintProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getPaintProperty(i),o)||(a.setPaintProperty(i,o,r)&&this._updateLayer(a),this._changed=!0,this._updatedPaintProps[e]=!0):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},i.prototype.setFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0!==a){var n=a.getSource().type;"geojson"===n&&r?this.fire(new t.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==n||r?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.removeFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=this.sourceCaches[o];if(void 0!==r){var a=r.getSource().type,n="vector"===a?e.sourceLayer:void 0;"vector"!==a||n?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.ErrorEvent(new Error("A feature id is requred to remove its specific state property."))):r.removeFeatureState(n,e.id,i):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.getFeatureState=function(e){this._checkLoaded();var i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r){if("vector"!==r.getSource().type||o)return void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id);this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+i+"' does not exist in the map's style.")));},i.prototype.getTransition=function(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},i.prototype.serialize=function(){return t.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:t.mapObject(this.sourceCaches,(function(t){return t.serialize()})),layers:this._serializeLayers(this._order)},(function(t){return void 0!==t}))},i.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&"raster"!==this.sourceCaches[t.source].getSource().type&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0;},i.prototype._flattenAndSortRenderedFeatures=function(t){for(var e=this,i=function(t){return "fill-extrusion"===e._layers[t].type},o={},r=[],a=this._order.length-1;a>=0;a--){var n=this._order[a];if(i(n)){o[n]=a;for(var s=0,l=t;s=0;d--){var _=this._order[d];if(i(_))for(var f=r.length-1;f>=0;f--){var m=r[f].feature;if(o[m.layer.id] 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}","attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,0.0,1.0);gl_Position.xy+=(a_extrude+a_shift)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}"),$e=gi("varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}","attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),ti=gi("uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}","attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,0,1);}"),ei=gi("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}"),ii=gi("varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),oi=gi("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),ri=gi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),ai=gi("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),ni=gi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),si=gi("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform float u_maxzoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggeration=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/ pow(2.0,(u_zoom-u_maxzoom)*exaggeration+19.2562-u_zoom);gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),li=gi("uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}"),ci=gi("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),ui=gi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,vec2(v_lineprogress,0.5));gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define MAX_LINE_DISTANCE 32767.0\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_lineprogress=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0/MAX_LINE_DISTANCE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),hi=gi("uniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),pi=gi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),di=gi("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),_i=gi("uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0),0.0,1.0);v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;v_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));}"),fi=gi("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),mi=gi("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}");function gi(t,e){var i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o={};return {fragmentSource:t=t.replace(i,(function(t,e,i,r,a){return o[a]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nvarying "+i+" "+r+" "+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n"})),vertexSource:e=e.replace(i,(function(t,e,i,r,a){var n="float"===r?"vec2":"vec4",s=a.match(/color/)?"color":n;return o[a]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float u_"+a+"_t;\nattribute "+i+" "+n+" a_"+a+";\nvarying "+i+" "+r+" "+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"vec4"===s?"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = a_"+a+";\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = unpack_mix_"+s+"(a_"+a+", u_"+a+"_t);\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float u_"+a+"_t;\nattribute "+i+" "+n+" a_"+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"vec4"===s?"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = a_"+a+";\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = unpack_mix_"+s+"(a_"+a+", u_"+a+"_t);\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n"}))}}var vi=Object.freeze({__proto__:null,prelude:Ge,background:We,backgroundPattern:Xe,circle:He,clippingMask:Ke,heatmap:Ye,heatmapTexture:Je,collisionBox:Qe,collisionCircle:$e,debug:ti,fill:ei,fillOutline:ii,fillOutlinePattern:oi,fillPattern:ri,fillExtrusion:ai,fillExtrusionPattern:ni,hillshadePrepare:si,hillshade:li,line:ci,lineGradient:ui,linePattern:hi,lineSDF:pi,raster:di,symbolIcon:_i,symbolSDF:fi,symbolTextAndIcon:mi}),yi=function(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;};yi.prototype.bind=function(t,e,i,o,r,a,n,s){this.context=t;for(var l=this.boundPaintVertexBuffers.length!==o.length,c=0;!l&&c>16,s>>16],u_pixel_coord_lower:[65535&n,65535&s]}}xi.prototype.draw=function(t,e,i,o,r,a,n,s,l,c,u,h,p,d,_,f){var m,g=t.gl;if(!this.failedToCreate){for(var v in t.program.set(this.program),t.setDepthMode(i),t.setStencilMode(o),t.setColorMode(r),t.setCullFace(a),this.fixedUniforms)this.fixedUniforms[v].set(n[v]);d&&d.setUniforms(t,this.binderUniforms,h,{zoom:p});for(var y=(m={},m[g.LINES]=2,m[g.TRIANGLES]=3,m[g.LINE_STRIP]=1,m)[e],x=0,b=u.get();x0?1-1/(1.001-n):-n),u_contrast_factor:(a=r.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Zi(r.paint.get("raster-hue-rotate"))};var a,n;};function Zi(t){t*=Math.PI/180;var e=Math.sin(t),i=Math.cos(t);return [(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}var ji,qi=function(t,e,i,o,r,a,n,s,l,c){var u=r.transform;return {u_is_size_zoom_constant:+("constant"===t||"source"===t),u_is_size_feature_constant:+("constant"===t||"camera"===t),u_size_t:e?e.uSizeT:0,u_size:e?e.uSize:0,u_camera_to_center_distance:u.cameraToCenterDistance,u_pitch:u.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:u.width/u.height,u_fade_change:r.options.fadeDuration?r.symbolFadeChange:1,u_matrix:a,u_label_plane_matrix:n,u_coord_matrix:s,u_is_text:+l,u_pitch_with_map:+o,u_texsize:c,u_texture:0}},Vi=function(e,i,o,r,a,n,s,l,c,u,h){var p=a.transform;return t.extend(qi(e,i,o,r,a,n,s,l,c,u),{u_gamma_scale:r?Math.cos(p._pitch)*p.cameraToCenterDistance:1,u_device_pixel_ratio:t.browser.devicePixelRatio,u_is_halo:+h})},Gi=function(e,i,o,r,a,n,s,l,c,u){return t.extend(Vi(e,i,o,r,a,n,s,l,!0,c,!0),{u_texsize_icon:u,u_texture_icon:1})},Wi=function(t,e,i){return {u_matrix:t,u_opacity:e,u_color:i}},Xi=function(e,i,o,r,a,n){return t.extend(function(t,e,i,o){var r=i.imageManager.getPattern(t.from.toString()),a=i.imageManager.getPattern(t.to.toString()),n=i.imageManager.getPixelSize(),s=n.width,l=n.height,c=Math.pow(2,o.tileID.overscaledZ),u=o.tileSize*Math.pow(2,i.transform.tileZoom)/c,h=u*(o.tileID.canonical.x+o.tileID.wrap*c),p=u*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:r.tl,u_pattern_br_a:r.br,u_pattern_tl_b:a.tl,u_pattern_br_b:a.br,u_texsize:[s,l],u_mix:e.t,u_pattern_size_a:r.displaySize,u_pattern_size_b:a.displaySize,u_scale_a:e.fromScale,u_scale_b:e.toScale,u_tile_units_to_pixels:1/pe(o,1,i.transform.tileZoom),u_pixel_coord_upper:[h>>16,p>>16],u_pixel_coord_lower:[65535&h,65535&p]}}(r,n,o,a),{u_matrix:e,u_opacity:i})},Hi={fillExtrusion:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fillExtrusionPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_height_factor:new t.Uniform1f(e,i.u_height_factor),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fill:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},fillPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},fillOutline:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world)}},fillOutlinePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},circle:function(e,i){return {u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_scale_with_map:new t.Uniform1i(e,i.u_scale_with_map),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},collisionBox:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pixels_to_tile_units:new t.Uniform1f(e,i.u_pixels_to_tile_units),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_overscale_factor:new t.Uniform1f(e,i.u_overscale_factor)}},collisionCircle:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_inv_matrix:new t.UniformMatrix4f(e,i.u_inv_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_viewport_size:new t.Uniform2f(e,i.u_viewport_size)}},debug:function(e,i){return {u_color:new t.UniformColor(e,i.u_color),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_overlay:new t.Uniform1i(e,i.u_overlay),u_overlay_scale:new t.Uniform1f(e,i.u_overlay_scale)}},clippingMask:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmap:function(e,i){return {u_extrude_scale:new t.Uniform1f(e,i.u_extrude_scale),u_intensity:new t.Uniform1f(e,i.u_intensity),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmapTexture:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_color_ramp:new t.Uniform1i(e,i.u_color_ramp),u_opacity:new t.Uniform1f(e,i.u_opacity)}},hillshade:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_latrange:new t.Uniform2f(e,i.u_latrange),u_light:new t.Uniform2f(e,i.u_light),u_shadow:new t.UniformColor(e,i.u_shadow),u_highlight:new t.UniformColor(e,i.u_highlight),u_accent:new t.UniformColor(e,i.u_accent)}},hillshadePrepare:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_dimension:new t.Uniform2f(e,i.u_dimension),u_zoom:new t.Uniform1f(e,i.u_zoom),u_maxzoom:new t.Uniform1f(e,i.u_maxzoom),u_unpack:new t.Uniform4f(e,i.u_unpack)}},line:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels)}},lineGradient:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_image:new t.Uniform1i(e,i.u_image)}},linePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_texsize:new t.Uniform2f(e,i.u_texsize),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_image:new t.Uniform1i(e,i.u_image),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},lineSDF:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_patternscale_a:new t.Uniform2f(e,i.u_patternscale_a),u_patternscale_b:new t.Uniform2f(e,i.u_patternscale_b),u_sdfgamma:new t.Uniform1f(e,i.u_sdfgamma),u_image:new t.Uniform1i(e,i.u_image),u_tex_y_a:new t.Uniform1f(e,i.u_tex_y_a),u_tex_y_b:new t.Uniform1f(e,i.u_tex_y_b),u_mix:new t.Uniform1f(e,i.u_mix)}},raster:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_tl_parent:new t.Uniform2f(e,i.u_tl_parent),u_scale_parent:new t.Uniform1f(e,i.u_scale_parent),u_buffer_scale:new t.Uniform1f(e,i.u_buffer_scale),u_fade_t:new t.Uniform1f(e,i.u_fade_t),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image0:new t.Uniform1i(e,i.u_image0),u_image1:new t.Uniform1i(e,i.u_image1),u_brightness_low:new t.Uniform1f(e,i.u_brightness_low),u_brightness_high:new t.Uniform1f(e,i.u_brightness_high),u_saturation_factor:new t.Uniform1f(e,i.u_saturation_factor),u_contrast_factor:new t.Uniform1f(e,i.u_contrast_factor),u_spin_weights:new t.Uniform3f(e,i.u_spin_weights)}},symbolIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture)}},symbolSDF:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo)}},symbolTextAndIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texsize_icon:new t.Uniform2f(e,i.u_texsize_icon),u_texture:new t.Uniform1i(e,i.u_texture),u_texture_icon:new t.Uniform1i(e,i.u_texture_icon),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo)}},background:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_color:new t.UniformColor(e,i.u_color)}},backgroundPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image:new t.Uniform1i(e,i.u_image),u_pattern_tl_a:new t.Uniform2f(e,i.u_pattern_tl_a),u_pattern_br_a:new t.Uniform2f(e,i.u_pattern_br_a),u_pattern_tl_b:new t.Uniform2f(e,i.u_pattern_tl_b),u_pattern_br_b:new t.Uniform2f(e,i.u_pattern_br_b),u_texsize:new t.Uniform2f(e,i.u_texsize),u_mix:new t.Uniform1f(e,i.u_mix),u_pattern_size_a:new t.Uniform2f(e,i.u_pattern_size_a),u_pattern_size_b:new t.Uniform2f(e,i.u_pattern_size_b),u_scale_a:new t.Uniform1f(e,i.u_scale_a),u_scale_b:new t.Uniform1f(e,i.u_scale_b),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.Uniform1f(e,i.u_tile_units_to_pixels)}}};function Ki(e,i,o,r,a,n,s){for(var l=e.context,c=l.gl,u=e.useProgram("collisionBox"),h=[],p=0,d=0,_=0;_0){var b=t.create(),w=v;t.mul(b,g.placementInvProjMatrix,e.transform.glCoordMatrix),t.mul(b,b,g.placementViewportMatrix),h.push({circleArray:x,circleOffset:d,transform:w,invTransform:b}),d=p+=x.length/4;}y&&u.draw(l,c.LINES,It.disabled,Pt.disabled,e.colorModeForRenderPass(),Ct.disabled,zi(v,e.transform,m),o.id,y.layoutVertexBuffer,y.indexBuffer,y.segments,null,e.transform.zoom,null,null,y.collisionVertexBuffer);}}if(s&&h.length){var T=e.useProgram("collisionCircle"),E=new t.StructArrayLayout2f1f2i16;E.resize(4*p),E._trim();for(var I=0,P=0,S=h;P=0&&(f[g.associatedIconIndex]={shiftedAnchor:E,angle:I});}else ce(g.numGlyphs,d);}if(h){_.clear();for(var S=e.icon.placedSymbolArray,C=0;C0){var s=t.browser.now(),l=(s-e.timeAdded)/n,c=i?(s-i.timeAdded)/n:-1,u=o.getSource(),h=a.coveringZoomLevel({tileSize:u.tileSize,roundZoom:u.roundZoom}),p=!i||Math.abs(i.tileID.overscaledZ-h)>Math.abs(e.tileID.overscaledZ-h),d=p&&e.refreshedUponExpiration?1:t.clamp(p?l:1-c,0,1);return e.refreshedUponExpiration&&l>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return {opacity:1,mix:0}}var so=new t.Color(1,0,0,1),lo=new t.Color(0,1,0,1),co=new t.Color(0,0,1,1),uo=new t.Color(1,0,1,1),ho=new t.Color(0,1,1,1);function po(t,e,i,o){fo(t,0,e+i/2,t.transform.width,i,o);}function _o(t,e,i,o){fo(t,e-i/2,0,i,t.transform.height,o);}function fo(e,i,o,r,a,n){var s=e.context,l=s.gl;l.enable(l.SCISSOR_TEST),l.scissor(i*t.browser.devicePixelRatio,o*t.browser.devicePixelRatio,r*t.browser.devicePixelRatio,a*t.browser.devicePixelRatio),s.clear({color:n}),l.disable(l.SCISSOR_TEST);}function mo(e,i,o){var r=e.context,a=r.gl,n=o.posMatrix,s=e.useProgram("debug"),l=It.disabled,c=Pt.disabled,u=e.colorModeForRenderPass();r.activeTexture.set(a.TEXTURE0),e.emptyTexture.bind(a.LINEAR,a.CLAMP_TO_EDGE),s.draw(r,a.LINE_STRIP,l,c,u,Ct.disabled,Mi(n,t.Color.red),"$debug",e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);var h=i.getTileByID(o.key).latestRawTileData,p=Math.floor((h&&h.byteLength||0)/1024),d=i.getTile(o).tileSize,_=512/Math.min(d,512)*(o.overscaledZ/e.transform.zoom)*.5,f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=" => "+o.overscaledZ),function(t,e){t.initDebugOverlayCanvas();var i=t.debugOverlayCanvas,o=t.context.gl,r=t.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(e,5,5),r.strokeText(e,5,5),t.debugOverlayTexture.update(i),t.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,f+" "+p+"kb"),s.draw(r,a.TRIANGLES,l,c,St.alphaBlended,Ct.disabled,Mi(n,t.Color.transparent,_),"$debug",e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments);}var go={symbol:function(e,i,o,r,a){if("translucent"===e.renderPass){var n=Pt.disabled,s=e.colorModeForRenderPass();o.layout.get("text-variable-anchor")&&function(e,i,o,r,a,n,s){for(var l=i.transform,c="map"===a,u="map"===n,h=0,p=e;h256&&this.clearStencil(),i.setColorMode(St.disabled),i.setDepthMode(It.disabled);var r=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(var a=0,n=e;a256&&this.clearStencil();var t=this.nextStencilID++,e=this.context.gl;return new Pt({func:e.NOTEQUAL,mask:255},t,255,e.KEEP,e.KEEP,e.REPLACE)},vo.prototype.stencilModeForClipping=function(t){var e=this.context.gl;return new Pt({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)},vo.prototype.stencilConfigForOverlap=function(t){var e,i=this.context.gl,o=t.sort((function(t,e){return e.overscaledZ-t.overscaledZ})),r=o[o.length-1].overscaledZ,a=o[0].overscaledZ-r+1;if(a>1){this.currentStencilSource=void 0,this.nextStencilID+a>256&&this.clearStencil();for(var n={},s=0;s=0;this.currentLayer--){var x=this.style._layers[r[this.currentLayer]],b=a[x.source],w=u[x.source];this._renderTileClippingMasks(x,w),this.renderLayer(this,b,x,w);}for(this.renderPass="translucent",this.currentLayer=0;this.currentLayer0?e.pop():null},vo.prototype.isPatternMissing=function(t){if(!t)return !1;if(!t.from||!t.to)return !0;var e=this.imageManager.getPattern(t.from.toString()),i=this.imageManager.getPattern(t.to.toString());return !e||!i},vo.prototype.useProgram=function(t,e){this.cache=this.cache||{};var i=""+t+(e?e.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[i]||(this.cache[i]=new xi(this.context,vi[t],e,Hi[t],this._showOverdrawInspector)),this.cache[i]},vo.prototype.setCustomLayerDefaults=function(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();},vo.prototype.setBaseState=function(){var t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD);},vo.prototype.initDebugOverlayCanvas=function(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=t.window.document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.Texture(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));},vo.prototype.destroy=function(){this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy();};var yo=function(t,e){this.points=t,this.planes=e;};yo.fromInvProjectionMatrix=function(e,i,o){var r=Math.pow(2,o),a=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((function(i){return t.transformMat4([],i,e)})).map((function(e){return t.scale$1([],e,1/e[3]/i*r)})),n=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((function(e){var i=t.sub([],a[e[0]],a[e[1]]),o=t.sub([],a[e[2]],a[e[1]]),r=t.normalize([],t.cross([],i,o)),n=-t.dot(r,a[e[1]]);return r.concat(n)}));return new yo(a,n)};var xo=function(e,i){this.min=e,this.max=i,this.center=t.scale$2([],t.add([],this.min,this.max),.5);};xo.prototype.quadrant=function(e){for(var i=[e%2==0,e<2],o=t.clone$2(this.min),r=t.clone$2(this.max),a=0;a=0;if(0===n)return 0;n!==i.length&&(o=!1);}if(o)return 2;for(var l=0;l<3;l++){for(var c=Number.MAX_VALUE,u=-Number.MAX_VALUE,h=0;hthis.max[l]-this.min[l])return 0}return 1};var bo=function(t,e,i,o){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===o&&(o=0),isNaN(t)||t<0||isNaN(e)||e<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=t,this.bottom=e,this.left=i,this.right=o;};bo.prototype.interpolate=function(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.number(e.right,i.right,o)),this},bo.prototype.getCenter=function(e,i){var o=t.clamp((this.left+e-this.right)/2,0,e),r=t.clamp((this.top+i-this.bottom)/2,0,i);return new t.Point(o,r)},bo.prototype.equals=function(t){return this.top===t.top&&this.bottom===t.bottom&&this.left===t.left&&this.right===t.right},bo.prototype.clone=function(){return new bo(this.top,this.bottom,this.left,this.right)},bo.prototype.toJSON=function(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}};var wo=function(e,i,o,r,a){this.tileSize=512,this.maxValidLatitude=85.051129,this._renderWorldCopies=void 0===a||a,this._minZoom=e||0,this._maxZoom=i||22,this._minPitch=null==o?0:o,this._maxPitch=null==r?60:r,this.setMaxBounds(),this.width=0,this.height=0,this._center=new t.LngLat(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._edgeInsets=new bo,this._posMatrixCache={},this._alignedPosMatrixCache={};},To={minZoom:{configurable:!0},maxZoom:{configurable:!0},minPitch:{configurable:!0},maxPitch:{configurable:!0},renderWorldCopies:{configurable:!0},worldSize:{configurable:!0},centerOffset:{configurable:!0},size:{configurable:!0},bearing:{configurable:!0},pitch:{configurable:!0},fov:{configurable:!0},zoom:{configurable:!0},center:{configurable:!0},padding:{configurable:!0},centerPoint:{configurable:!0},unmodified:{configurable:!0},point:{configurable:!0}};wo.prototype.clone=function(){var t=new wo(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._edgeInsets=this._edgeInsets.clone(),t._calcMatrices(),t},To.minZoom.get=function(){return this._minZoom},To.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t));},To.maxZoom.get=function(){return this._maxZoom},To.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t));},To.minPitch.get=function(){return this._minPitch},To.minPitch.set=function(t){this._minPitch!==t&&(this._minPitch=t,this.pitch=Math.max(this.pitch,t));},To.maxPitch.get=function(){return this._maxPitch},To.maxPitch.set=function(t){this._maxPitch!==t&&(this._maxPitch=t,this.pitch=Math.min(this.pitch,t));},To.renderWorldCopies.get=function(){return this._renderWorldCopies},To.renderWorldCopies.set=function(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t;},To.worldSize.get=function(){return this.tileSize*this.scale},To.centerOffset.get=function(){return this.centerPoint._sub(this.size._div(2))},To.size.get=function(){return new t.Point(this.width,this.height)},To.bearing.get=function(){return -this.angle/Math.PI*180},To.bearing.set=function(e){var i=-t.wrap(e,-180,180)*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=t.create$2(),t.rotate(this.rotationMatrix,this.rotationMatrix,this.angle));},To.pitch.get=function(){return this._pitch/Math.PI*180},To.pitch.set=function(e){var i=t.clamp(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());},To.fov.get=function(){return this._fov/Math.PI*180},To.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices());},To.zoom.get=function(){return this._zoom},To.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices());},To.center.get=function(){return this._center},To.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices());},To.padding.get=function(){return this._edgeInsets.toJSON()},To.padding.set=function(t){this._edgeInsets.equals(t)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,t,1),this._calcMatrices());},To.centerPoint.get=function(){return this._edgeInsets.getCenter(this.width,this.height)},wo.prototype.isPaddingEqual=function(t){return this._edgeInsets.equals(t)},wo.prototype.interpolatePadding=function(t,e,i){this._unmodified=!1,this._edgeInsets.interpolate(t,e,i),this._constrain(),this._calcMatrices();},wo.prototype.coveringZoomLevel=function(t){var e=(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize));return Math.max(0,e)},wo.prototype.getVisibleUnwrappedCoordinates=function(e){var i=[new t.UnwrappedTileID(0,e)];if(this._renderWorldCopies)for(var o=this.pointCoordinate(new t.Point(0,0)),r=this.pointCoordinate(new t.Point(this.width,0)),a=this.pointCoordinate(new t.Point(this.width,this.height)),n=this.pointCoordinate(new t.Point(0,this.height)),s=Math.floor(Math.min(o.x,r.x,a.x,n.x)),l=Math.floor(Math.max(o.x,r.x,a.x,n.x)),c=s-1;c<=l+1;c++)0!==c&&i.push(new t.UnwrappedTileID(c,e));return i},wo.prototype.coveringTiles=function(e){var i=this.coveringZoomLevel(e),o=i;if(void 0!==e.minzoom&&ie.maxzoom&&(i=e.maxzoom);var r=t.MercatorCoordinate.fromLngLat(this.center),a=Math.pow(2,i),n=[a*r.x,a*r.y,0],s=yo.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,i),l=e.minzoom||0;this.pitch<=60&&this._edgeInsets.top<.1&&(l=i);var c=function(t){return {aabb:new xo([t*a,0,0],[(t+1)*a,a,0]),zoom:0,x:0,y:0,wrap:t,fullyVisible:!1}},u=[],h=[],p=i,d=e.reparseOverscaled?o:i;if(this._renderWorldCopies)for(var _=1;_<=3;_++)u.push(c(-_)),u.push(c(_));for(u.push(c(0));u.length>0;){var f=u.pop(),m=f.x,g=f.y,v=f.fullyVisible;if(!v){var y=f.aabb.intersects(s);if(0===y)continue;v=2===y;}var x=f.aabb.distanceX(n),b=f.aabb.distanceY(n),w=Math.max(Math.abs(x),Math.abs(b));if(f.zoom===p||w>3+(1<=l)h.push({tileID:new t.OverscaledTileID(f.zoom===p?d:f.zoom,f.wrap,f.zoom,m,g),distanceSq:t.sqrLen([n[0]-.5-m,n[1]-.5-g])});else for(var T=0;T<4;T++){var E=(m<<1)+T%2,I=(g<<1)+(T>>1);u.push({aabb:f.aabb.quadrant(T),zoom:f.zoom+1,x:E,y:I,wrap:f.wrap,fullyVisible:v});}}return h.sort((function(t,e){return t.distanceSq-e.distanceSq})).map((function(t){return t.tileID}))},wo.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices();},To.unmodified.get=function(){return this._unmodified},wo.prototype.zoomScale=function(t){return Math.pow(2,t)},wo.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},wo.prototype.project=function(e){var i=t.clamp(e.lat,-this.maxValidLatitude,this.maxValidLatitude);return new t.Point(t.mercatorXfromLng(e.lng)*this.worldSize,t.mercatorYfromLat(i)*this.worldSize)},wo.prototype.unproject=function(e){return new t.MercatorCoordinate(e.x/this.worldSize,e.y/this.worldSize).toLngLat()},To.point.get=function(){return this.project(this.center)},wo.prototype.setLocationAtPoint=function(e,i){var o=this.pointCoordinate(i),r=this.pointCoordinate(this.centerPoint),a=this.locationCoordinate(e),n=new t.MercatorCoordinate(a.x-(o.x-r.x),a.y-(o.y-r.y));this.center=this.coordinateLocation(n),this._renderWorldCopies&&(this.center=this.center.wrap());},wo.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},wo.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},wo.prototype.locationCoordinate=function(e){return t.MercatorCoordinate.fromLngLat(e)},wo.prototype.coordinateLocation=function(t){return t.toLngLat()},wo.prototype.pointCoordinate=function(e){var i=[e.x,e.y,0,1],o=[e.x,e.y,1,1];t.transformMat4(i,i,this.pixelMatrixInverse),t.transformMat4(o,o,this.pixelMatrixInverse);var r=i[3],a=o[3],n=i[1]/r,s=o[1]/a,l=i[2]/r,c=o[2]/a,u=l===c?0:(0-l)/(c-l);return new t.MercatorCoordinate(t.number(i[0]/r,o[0]/a,u)/this.worldSize,t.number(n,s,u)/this.worldSize)},wo.prototype.coordinatePoint=function(e){var i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix),new t.Point(i[0]/i[3],i[1]/i[3])},wo.prototype.getBounds=function(){return (new t.LngLatBounds).extend(this.pointLocation(new t.Point(0,0))).extend(this.pointLocation(new t.Point(this.width,0))).extend(this.pointLocation(new t.Point(this.width,this.height))).extend(this.pointLocation(new t.Point(0,this.height)))},wo.prototype.getMaxBounds=function(){return this.latRange&&2===this.latRange.length&&this.lngRange&&2===this.lngRange.length?new t.LngLatBounds([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]]):null},wo.prototype.setMaxBounds=function(t){t?(this.lngRange=[t.getWest(),t.getEast()],this.latRange=[t.getSouth(),t.getNorth()],this._constrain()):(this.lngRange=null,this.latRange=[-this.maxValidLatitude,this.maxValidLatitude]);},wo.prototype.calculatePosMatrix=function(e,i){void 0===i&&(i=!1);var o=e.key,r=i?this._alignedPosMatrixCache:this._posMatrixCache;if(r[o])return r[o];var a=e.canonical,n=this.worldSize/this.zoomScale(a.z),s=a.x+Math.pow(2,a.z)*e.wrap,l=t.identity(new Float64Array(16));return t.translate(l,l,[s*n,a.y*n,0]),t.scale(l,l,[n/t.EXTENT,n/t.EXTENT,1]),t.multiply(l,i?this.alignedProjMatrix:this.projMatrix,l),r[o]=new Float32Array(l),r[o]},wo.prototype.customLayerMatrix=function(){return this.mercatorMatrix.slice()},wo.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var e,i,o,r,a=-90,n=90,s=-180,l=180,c=this.size,u=this._unmodified;if(this.latRange){var h=this.latRange;a=t.mercatorYfromLat(h[1])*this.worldSize,e=(n=t.mercatorYfromLat(h[0])*this.worldSize)-an&&(r=n-m);}if(this.lngRange){var g=d.x,v=c.x/2;g-vl&&(o=l-v);}void 0===o&&void 0===r||(this.center=this.unproject(new t.Point(void 0!==o?o:d.x,void 0!==r?r:d.y))),this._unmodified=u,this._constraining=!1;}},wo.prototype._calcMatrices=function(){if(this.height){var e=this.centerOffset;this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var i=Math.PI/2+this._pitch,o=this._fov*(.5+e.y/this.height),r=Math.sin(o)*this.cameraToCenterDistance/Math.sin(t.clamp(Math.PI-i-o,.01,Math.PI-.01)),a=this.point,n=a.x,s=a.y,l=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),c=this.height/50,u=new Float64Array(16);t.perspective(u,this._fov,this.width/this.height,c,l),u[8]=2*-e.x/this.width,u[9]=2*e.y/this.height,t.scale(u,u,[1,-1,1]),t.translate(u,u,[0,0,-this.cameraToCenterDistance]),t.rotateX(u,u,this._pitch),t.rotateZ(u,u,this.angle),t.translate(u,u,[-n,-s,0]),this.mercatorMatrix=t.scale([],u,[this.worldSize,this.worldSize,this.worldSize]),t.scale(u,u,[1,1,t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize,1]),this.projMatrix=u,this.invProjMatrix=t.invert([],this.projMatrix);var h=this.width%2/2,p=this.height%2/2,d=Math.cos(this.angle),_=Math.sin(this.angle),f=n-Math.round(n)+d*h+_*p,m=s-Math.round(s)+d*p+_*h,g=new Float64Array(u);if(t.translate(g,g,[f>.5?f-1:f,m>.5?m-1:m,0]),this.alignedProjMatrix=g,u=t.create(),t.scale(u,u,[this.width/2,-this.height/2,1]),t.translate(u,u,[1,-1,0]),this.labelPlaneMatrix=u,u=t.create(),t.scale(u,u,[1,-1,1]),t.translate(u,u,[-1,-1,0]),t.scale(u,u,[2/this.width,2/this.height,1]),this.glCoordMatrix=u,this.pixelMatrix=t.multiply(new Float64Array(16),this.labelPlaneMatrix,this.projMatrix),!(u=t.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=u,this._posMatrixCache={},this._alignedPosMatrixCache={};}},wo.prototype.maxPitchScaleFactor=function(){if(!this.pixelMatrixInverse)return 1;var e=this.pointCoordinate(new t.Point(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix)[3]/this.cameraToCenterDistance},wo.prototype.getCameraPoint=function(){var e=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.Point(0,e))},wo.prototype.getCameraQueryGeometry=function(e){var i=this.getCameraPoint();if(1===e.length)return [e[0],i];for(var o=i.x,r=i.y,a=i.x,n=i.y,s=0,l=e;s=3&&!t.some((function(t){return isNaN(t)}))){var e=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(t[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:e,pitch:+(t[4]||0)}),!0}return !1},Eo.prototype._updateHashUnthrottled=function(){var e=this.getHashString();try{t.window.history.replaceState(t.window.history.state,"",e);}catch(t){}};var Io={linearity:.3,easing:t.bezier(0,0,.3,1)},Po=t.extend({deceleration:2500,maxSpeed:1400},Io),So=t.extend({deceleration:20,maxSpeed:1400},Io),Co=t.extend({deceleration:1e3,maxSpeed:360},Io),zo=t.extend({deceleration:1e3,maxSpeed:90},Io),Do=function(t){this._map=t,this.clear();};function Mo(t,e){(!t.duration||t.duration0&&i-e[0].time>160;)e.shift();},Do.prototype._onMoveEnd=function(e){if(this._drainInertiaBuffer(),!(this._inertiaBuffer.length<2)){for(var i={zoom:0,bearing:0,pitch:0,pan:new t.Point(0,0),pinchAround:void 0,around:void 0},o=0,r=this._inertiaBuffer;o=this._clickTolerance||this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.dblclick=function(t){return this._firePreventable(new Ao(t.type,this._map,t))},Bo.prototype.mouseover=function(t){this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.mouseout=function(t){this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.touchstart=function(t){return this._firePreventable(new Ro(t.type,this._map,t))},Bo.prototype.touchmove=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype.touchend=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype.touchcancel=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype._firePreventable=function(t){if(this._map.fire(t),t.defaultPrevented)return {}},Bo.prototype.isEnabled=function(){return !0},Bo.prototype.isActive=function(){return !1},Bo.prototype.enable=function(){},Bo.prototype.disable=function(){};var Oo=function(t){this._map=t;};Oo.prototype.reset=function(){this._delayContextMenu=!1,delete this._contextMenuEvent;},Oo.prototype.mousemove=function(t){this._map.fire(new Ao(t.type,this._map,t));},Oo.prototype.mousedown=function(){this._delayContextMenu=!0;},Oo.prototype.mouseup=function(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Ao("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);},Oo.prototype.contextmenu=function(t){this._delayContextMenu?this._contextMenuEvent=t:this._map.fire(new Ao(t.type,this._map,t)),this._map.listens("contextmenu")&&t.preventDefault();},Oo.prototype.isEnabled=function(){return !0},Oo.prototype.isActive=function(){return !1},Oo.prototype.enable=function(){},Oo.prototype.disable=function(){};var Fo=function(t,e){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),this._clickTolerance=e.clickTolerance||1;};function Uo(t,e){for(var i={},o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){for(var i=new t.Point(0,0),o=0,r=e;o30)&&(this.aborted=!0);}}},No.prototype.touchend=function(t,e,i){if((!this.centroid||t.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){var o=!this.aborted&&this.centroid;if(this.reset(),o)return o}};var Zo=function(t){this.singleTap=new No(t),this.numTaps=t.numTaps,this.reset();};Zo.prototype.reset=function(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();},Zo.prototype.touchstart=function(t,e,i){this.singleTap.touchstart(t,e,i);},Zo.prototype.touchmove=function(t,e,i){this.singleTap.touchmove(t,e,i);},Zo.prototype.touchend=function(t,e,i){var o=this.singleTap.touchend(t,e,i);if(o){var r=t.timeStamp-this.lastTime<500,a=!this.lastTap||this.lastTap.dist(o)<30;if(r&&a||this.reset(),this.count++,this.lastTime=t.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}};var jo=function(){this._zoomIn=new Zo({numTouches:1,numTaps:2}),this._zoomOut=new Zo({numTouches:2,numTaps:1}),this.reset();};jo.prototype.reset=function(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();},jo.prototype.touchstart=function(t,e,i){this._zoomIn.touchstart(t,e,i),this._zoomOut.touchstart(t,e,i);},jo.prototype.touchmove=function(t,e,i){this._zoomIn.touchmove(t,e,i),this._zoomOut.touchmove(t,e,i);},jo.prototype.touchend=function(t,e,i){var o=this,r=this._zoomIn.touchend(t,e,i),a=this._zoomOut.touchend(t,e,i);return r?(this._active=!0,t.preventDefault(),setTimeout((function(){return o.reset()}),0),{cameraAnimation:function(e){return e.easeTo({duration:300,zoom:e.getZoom()+1,around:e.unproject(r)},{originalEvent:t})}}):a?(this._active=!0,t.preventDefault(),setTimeout((function(){return o.reset()}),0),{cameraAnimation:function(e){return e.easeTo({duration:300,zoom:e.getZoom()-1,around:e.unproject(a)},{originalEvent:t})}}):void 0},jo.prototype.touchcancel=function(){this.reset();},jo.prototype.enable=function(){this._enabled=!0;},jo.prototype.disable=function(){this._enabled=!1,this.reset();},jo.prototype.isEnabled=function(){return this._enabled},jo.prototype.isActive=function(){return this._active};var qo=function(t){this.reset(),this._clickTolerance=t.clickTolerance||1;};qo.prototype.reset=function(){this._active=!1,this._moved=!1,delete this._lastPoint,delete this._eventButton;},qo.prototype._correctButton=function(t,e){return !1},qo.prototype._move=function(t,e){return {}},qo.prototype.mousedown=function(t,e){if(!this._lastPoint){var o=i.mouseButton(t);this._correctButton(t,o)&&(this._lastPoint=e,this._eventButton=o);}},qo.prototype.mousemoveWindow=function(t,e){var i=this._lastPoint;if(i&&(t.preventDefault(),this._moved||!(e.dist(i)0&&(this._active=!0);var r=Uo(o,i),a=new t.Point(0,0),n=new t.Point(0,0),s=0;for(var l in r){var c=r[l],u=this._touches[l];u&&(a._add(c),n._add(c.sub(u)),s++,r[l]=c);}if(this._touches=r,!(sMath.abs(t.x)}var er=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.reset=function(){t.prototype.reset.call(this),this._valid=void 0,delete this._firstMove,delete this._lastPoints;},e.prototype._start=function(t){this._lastPoints=t,tr(t[0].sub(t[1]))&&(this._valid=!1);},e.prototype._move=function(t,e,i){var o=t[0].sub(this._lastPoints[0]),r=t[1].sub(this._lastPoints[1]);if(this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid)return this._lastPoints=t,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}},e.prototype.gestureBeginsVertically=function(t,e,i){if(void 0!==this._valid)return this._valid;var o=t.mag()>=2,r=e.mag()>=2;if(o||r){if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;var a=t.y>0==e.y>0;return tr(t)&&tr(e)&&a}},e}(Ho),ir={panStep:100,bearingStep:15,pitchStep:10},or=function(){var t=ir;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep;};function rr(t){return t*(2-t)}or.prototype.reset=function(){this._active=!1;},or.prototype.keydown=function(t){var e=this;if(!(t.altKey||t.ctrlKey||t.metaKey)){var i=0,o=0,r=0,a=0,n=0;switch(t.keyCode){case 61:case 107:case 171:case 187:i=1;break;case 189:case 109:case 173:i=-1;break;case 37:t.shiftKey?o=-1:(t.preventDefault(),a=-1);break;case 39:t.shiftKey?o=1:(t.preventDefault(),a=1);break;case 38:t.shiftKey?r=1:(t.preventDefault(),n=-1);break;case 40:t.shiftKey?r=-1:(t.preventDefault(),n=1);break;default:return}return {cameraAnimation:function(s){var l=s.getZoom();s.easeTo({duration:300,easeId:"keyboardHandler",easing:rr,zoom:i?Math.round(l)+i*(t.shiftKey?2:1):l,bearing:s.getBearing()+o*e._bearingStep,pitch:s.getPitch()+r*e._pitchStep,offset:[-a*e._panStep,-n*e._panStep],center:s.getCenter()},{originalEvent:t});}}}},or.prototype.enable=function(){this._enabled=!0;},or.prototype.disable=function(){this._enabled=!1,this.reset();},or.prototype.isEnabled=function(){return this._enabled},or.prototype.isActive=function(){return this._active};var ar=function(e,i){this._map=e,this._el=e.getCanvasContainer(),this._handler=i,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=1/450,t.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this);};ar.prototype.setZoomRate=function(t){this._defaultZoomRate=t;},ar.prototype.setWheelZoomRate=function(t){this._wheelZoomRate=t;},ar.prototype.isEnabled=function(){return !!this._enabled},ar.prototype.isActive=function(){return !!this._active||void 0!==this._finishTimeout},ar.prototype.isZooming=function(){return !!this._zooming},ar.prototype.enable=function(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=t&&"center"===t.around);},ar.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},ar.prototype.wheel=function(e){if(this.isEnabled()){var i=e.deltaMode===t.window.WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,o=t.browser.now(),r=o-(this._lastWheelEventTime||0);this._lastWheelEventTime=o,0!==i&&i%4.000244140625==0?this._type="wheel":0!==i&&Math.abs(i)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=i,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*i)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,i+=this._lastValue)),e.shiftKey&&i&&(i/=4),this._type&&(this._lastWheelEvent=e,this._delta-=i,this._active||this._start(e)),e.preventDefault();}},ar.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(t);},ar.prototype._start=function(e){if(this._delta){this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);var o=i.mousePos(this._el,e);this._around=t.LngLat.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(o)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame());}},ar.prototype.renderFrame=function(){return this._onScrollFrame()},ar.prototype._onScrollFrame=function(){var e=this;if(this._frameId&&(this._frameId=null,this.isActive())){var i=this._map.transform;if(0!==this._delta){var o="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?this._wheelZoomRate:this._defaultZoomRate,r=2/(1+Math.exp(-Math.abs(this._delta*o)));this._delta<0&&0!==r&&(r=1/r);var a="number"==typeof this._targetZoom?i.zoomScale(this._targetZoom):i.scale;this._targetZoom=Math.min(i.maxZoom,Math.max(i.minZoom,i.scaleZoom(a*r))),"wheel"===this._type&&(this._startZoom=i.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}var n,s="number"==typeof this._targetZoom?this._targetZoom:i.zoom,l=this._startZoom,c=this._easing,u=!1;if("wheel"===this._type&&l&&c){var h=Math.min((t.browser.now()-this._lastWheelEventTime)/200,1),p=c(h);n=t.number(l,s,p),h<1?this._frameId||(this._frameId=!0):u=!0;}else n=s,u=!0;return this._active=!0,u&&(this._active=!1,this._finishTimeout=setTimeout((function(){e._zooming=!1,e._handler._triggerRenderFrame(),delete e._targetZoom,delete e._finishTimeout;}),200)),{noInertia:!0,needsRenderFrame:!u,zoomDelta:n-i.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}},ar.prototype._smoothOutEasing=function(e){var i=t.ease;if(this._prevEase){var o=this._prevEase,r=(t.browser.now()-o.start)/o.duration,a=o.easing(r+.01)-o.easing(r),n=.27/Math.sqrt(a*a+1e-4)*.01,s=Math.sqrt(.0729-n*n);i=t.bezier(n,s,.25,1);}return this._prevEase={start:t.browser.now(),duration:e,easing:i},i},ar.prototype.reset=function(){this._active=!1;};var nr=function(t,e){this._clickZoom=t,this._tapZoom=e;};nr.prototype.enable=function(){this._clickZoom.enable(),this._tapZoom.enable();},nr.prototype.disable=function(){this._clickZoom.disable(),this._tapZoom.disable();},nr.prototype.isEnabled=function(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()},nr.prototype.isActive=function(){return this._clickZoom.isActive()||this._tapZoom.isActive()};var sr=function(){this.reset();};sr.prototype.reset=function(){this._active=!1;},sr.prototype.dblclick=function(t,e){return t.preventDefault(),{cameraAnimation:function(i){i.easeTo({duration:300,zoom:i.getZoom()+(t.shiftKey?-1:1),around:i.unproject(e)},{originalEvent:t});}}},sr.prototype.enable=function(){this._enabled=!0;},sr.prototype.disable=function(){this._enabled=!1,this.reset();},sr.prototype.isEnabled=function(){return this._enabled},sr.prototype.isActive=function(){return this._active};var lr=function(){this._tap=new Zo({numTouches:1,numTaps:1}),this.reset();};lr.prototype.reset=function(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,this._tap.reset();},lr.prototype.touchstart=function(t,e,i){this._swipePoint||(this._tapTime&&t.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?i.length>0&&(this._swipePoint=e[0],this._swipeTouch=i[0].identifier):this._tap.touchstart(t,e,i));},lr.prototype.touchmove=function(t,e,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;var o=e[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,t.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(t,e,i);},lr.prototype.touchend=function(t,e,i){this._tapTime?this._swipePoint&&0===i.length&&this.reset():this._tap.touchend(t,e,i)&&(this._tapTime=t.timeStamp);},lr.prototype.touchcancel=function(){this.reset();},lr.prototype.enable=function(){this._enabled=!0;},lr.prototype.disable=function(){this._enabled=!1,this.reset();},lr.prototype.isEnabled=function(){return this._enabled},lr.prototype.isActive=function(){return this._active};var cr=function(t,e,i){this._el=t,this._mousePan=e,this._touchPan=i;};cr.prototype.enable=function(t){this._inertiaOptions=t||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan");},cr.prototype.disable=function(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan");},cr.prototype.isEnabled=function(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()},cr.prototype.isActive=function(){return this._mousePan.isActive()||this._touchPan.isActive()};var ur=function(t,e,i){this._pitchWithRotate=t.pitchWithRotate,this._mouseRotate=e,this._mousePitch=i;};ur.prototype.enable=function(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable();},ur.prototype.disable=function(){this._mouseRotate.disable(),this._mousePitch.disable();},ur.prototype.isEnabled=function(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())},ur.prototype.isActive=function(){return this._mouseRotate.isActive()||this._mousePitch.isActive()};var hr=function(t,e,i,o){this._el=t,this._touchZoom=e,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;};hr.prototype.enable=function(t){this._touchZoom.enable(t),this._rotationDisabled||this._touchRotate.enable(t),this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate");},hr.prototype.disable=function(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate");},hr.prototype.isEnabled=function(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()},hr.prototype.isActive=function(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()},hr.prototype.disableRotation=function(){this._rotationDisabled=!0,this._touchRotate.disable();},hr.prototype.enableRotation=function(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();};var pr=function(t){return t.zoom||t.drag||t.pitch||t.rotate},dr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(t.Event);function _r(t){return t.panDelta&&t.panDelta.mag()||t.zoomDelta||t.bearingDelta||t.pitchDelta}var fr=function(e,o){this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Do(e),this._bearingSnap=o.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(o),t.bindAll(["handleEvent","handleWindowEvent"],this);var r=this._el;this._listeners=[[r,"touchstart",{passive:!1}],[r,"touchmove",{passive:!1}],[r,"touchend",void 0],[r,"touchcancel",void 0],[r,"mousedown",void 0],[r,"mousemove",void 0],[r,"mouseup",void 0],[t.window.document,"mousemove",{capture:!0}],[t.window.document,"mouseup",void 0],[r,"mouseover",void 0],[r,"mouseout",void 0],[r,"dblclick",void 0],[r,"click",void 0],[r,"keydown",{capture:!1}],[r,"keyup",void 0],[r,"wheel",{passive:!1}],[r,"contextmenu",void 0],[t.window,"blur",void 0]];for(var a=0,n=this._listeners;aa?Math.min(2,b):Math.max(.5,b),w=Math.pow(m,1-e),T=r.unproject(y.add(x.mult(e*w)).mult(f));r.setLocationAtPoint(r.renderWorldCopies?T.wrap():T,_);}o._fireMoveEvents(i);}),(function(t){o._afterEase(i,t);}),e),this},i.prototype._prepareEase=function(e,i,o){void 0===o&&(o={}),this._moving=!0,i||o.moving||this.fire(new t.Event("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.Event("pitchstart",e));},i.prototype._fireMoveEvents=function(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e));},i.prototype._afterEase=function(e,i){if(!this._easeId||!i||this._easeId!==i){delete this._easeId;var o=this._zooming,r=this._rotating,a=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,o&&this.fire(new t.Event("zoomend",e)),r&&this.fire(new t.Event("rotateend",e)),a&&this.fire(new t.Event("pitchend",e)),this.fire(new t.Event("moveend",e));}},i.prototype.flyTo=function(e,i){var o=this;if(!e.essential&&t.browser.prefersReducedMotion){var r=t.pick(e,["center","zoom","bearing","pitch","around"]);return this.jumpTo(r,i)}this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.ease},e);var a=this.transform,n=this.getZoom(),s=this.getBearing(),l=this.getPitch(),c=this.getPadding(),u="zoom"in e?t.clamp(+e.zoom,a.minZoom,a.maxZoom):n,h="bearing"in e?this._normalizeBearing(e.bearing,s):s,p="pitch"in e?+e.pitch:l,d="padding"in e?e.padding:a.padding,_=a.zoomScale(u-n),f=t.Point.convert(e.offset),m=a.centerPoint.add(f),g=a.pointLocation(m),v=t.LngLat.convert(e.center||g);this._normalizeCenter(v);var y=a.project(g),x=a.project(v).sub(y),b=e.curve,w=Math.max(a.width,a.height),T=w/_,E=x.mag();if("minZoom"in e){var I=t.clamp(Math.min(e.minZoom,n,u),a.minZoom,a.maxZoom),P=w/a.zoomScale(I-n);b=Math.sqrt(P/E*2);}var S=b*b;function C(t){var e=(T*T-w*w+(t?-1:1)*S*S*E*E)/(2*(t?T:w)*S*E);return Math.log(Math.sqrt(e*e+1)-e)}function z(t){return (Math.exp(t)-Math.exp(-t))/2}function D(t){return (Math.exp(t)+Math.exp(-t))/2}var M=C(0),L=function(t){return D(M)/D(M+b*t)},A=function(t){return w*((D(M)*(z(e=M+b*t)/D(e))-z(M))/S)/E;var e;},R=(C(1)-M)/b;if(Math.abs(E)<1e-6||!isFinite(R)){if(Math.abs(w-T)<1e-6)return this.easeTo(e,i);var k=Te.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=s!==h,this._pitching=p!==l,this._padding=!a.isPaddingEqual(d),this._prepareEase(i,!1),this._ease((function(e){var r=e*R,_=1/L(r);a.zoom=1===e?u:n+a.scaleZoom(_),o._rotating&&(a.bearing=t.number(s,h,e)),o._pitching&&(a.pitch=t.number(l,p,e)),o._padding&&(a.interpolatePadding(c,d,e),m=a.centerPoint.add(f));var g=1===e?v:a.unproject(y.add(x.mult(A(r))).mult(_));a.setLocationAtPoint(a.renderWorldCopies?g.wrap():g,m),o._fireMoveEvents(i);}),(function(){return o._afterEase(i)}),e),this},i.prototype.isEasing=function(){return !!this._easeFrameId},i.prototype.stop=function(){return this._stop()},i.prototype._stop=function(t,e){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){var i=this._onEaseEnd;delete this._onEaseEnd,i.call(this,e);}if(!t){var o=this.handlers;o&&o.stop();}return this},i.prototype._ease=function(e,i,o){!1===o.animate||0===o.duration?(e(1),i()):(this._easeStart=t.browser.now(),this._easeOptions=o,this._onEaseFrame=e,this._onEaseEnd=i,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));},i.prototype._renderFrameCallback=function(){var e=Math.min((t.browser.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},i.prototype._normalizeBearing=function(e,i){e=t.wrap(e,-180,180);var o=Math.abs(e-i);return Math.abs(e-360-i)180?-360:i<-180?360:0;}},i}(t.Evented),gr=function(e){void 0===e&&(e={}),this.options=e,t.bindAll(["_updateEditLink","_updateData","_updateCompact"],this);};gr.prototype.getDefaultPosition=function(){return "bottom-right"},gr.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._innerContainer=i.create("div","mapboxgl-ctrl-attrib-inner",this._container),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},gr.prototype.onRemove=function(){i.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0;},gr.prototype._updateEditLink=function(){var e=this._editLink;e||(e=this._editLink=this._container.querySelector(".mapbox-improve-map"));var i=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||t.config.ACCESS_TOKEN}];if(e){var o=i.reduce((function(t,e,o){return e.value&&(t+=e.key+"="+e.value+(o=0)return !1;return !0}))).join(" | ");n!==this._attribHTML&&(this._attribHTML=n,t.length?(this._innerContainer.innerHTML=n,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null);}},gr.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact");};var vr=function(){t.bindAll(["_updateLogo"],this),t.bindAll(["_updateCompact"],this);};vr.prototype.onAdd=function(t){this._map=t,this._container=i.create("div","mapboxgl-ctrl");var e=i.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.rel="noopener nofollow",e.href="https://www.mapbox.com/",e.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),e.setAttribute("rel","noopener nofollow"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container},vr.prototype.onRemove=function(){i.remove(this._container),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact);},vr.prototype.getDefaultPosition=function(){return "bottom-left"},vr.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none");},vr.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return !0;return !1}},vr.prototype._updateCompact=function(){var t=this._container.children;if(t.length){var e=t[0];this._map.getCanvasContainer().offsetWidth<250?e.classList.add("mapboxgl-compact"):e.classList.remove("mapboxgl-compact");}};var yr=function(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;};yr.prototype.add=function(t){var e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e},yr.prototype.remove=function(t){for(var e=this._currentlyRunning,i=0,o=e?this._queue.concat(e):this._queue;ie.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=e.minPitch&&null!=e.maxPitch&&e.minPitch>e.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=e.minPitch&&e.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=e.maxPitch&&e.maxPitch>60)throw new Error("maxPitch must be less than or equal to 60");var r=new wo(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies);if(o.call(this,r,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._antialias=e.antialias,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossSourceCollisions=e.crossSourceCollisions,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming,this._renderTaskQueue=new yr,this._controls=[],this._mapId=t.uniqueId(),this._locale=t.extend({},xr,e.locale),this._requestManager=new t.RequestManager(e.transformRequest,e.accessToken),"string"==typeof e.container){if(this._container=t.window.document.getElementById(e.container),!this._container)throw new Error("Container '"+e.container+"' not found.")}else {if(!(e.container instanceof wr))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container;}if(e.maxBounds&&this.setMaxBounds(e.maxBounds),t.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),void 0===this.painter)throw new Error("Failed to initialize WebGL.");this.on("move",(function(){return i._update(!1)})),this.on("moveend",(function(){return i._update(!1)})),this.on("zoom",(function(){return i._update(!0)})),void 0!==t.window&&(t.window.addEventListener("online",this._onWindowOnline,!1),t.window.addEventListener("resize",this._onWindowResize,!1)),this.handlers=new fr(this,e),this._hash=e.hash&&new Eo("string"==typeof e.hash&&e.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),e.bounds&&(this.resize(),this.fitBounds(e.bounds,t.extend({},e.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=e.localIdeographFontFamily,e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new gr({customAttribution:e.customAttribution})),this.addControl(new vr,e.logoPosition),this.on("style.load",(function(){i.transform.unmodified&&i.jumpTo(i.style.stylesheet);})),this.on("data",(function(e){i._update("style"===e.dataType),i.fire(new t.Event(e.dataType+"data",e));})),this.on("dataloading",(function(e){i.fire(new t.Event(e.dataType+"dataloading",e));}));}o&&(r.__proto__=o),(r.prototype=Object.create(o&&o.prototype)).constructor=r;var a={showTileBoundaries:{configurable:!0},showPadding:{configurable:!0},showCollisionBoxes:{configurable:!0},showOverdrawInspector:{configurable:!0},repaint:{configurable:!0},vertices:{configurable:!0},version:{configurable:!0}};return r.prototype._getMapId=function(){return this._mapId},r.prototype.addControl=function(e,i){if(void 0===i&&e.getDefaultPosition&&(i=e.getDefaultPosition()),void 0===i&&(i="top-right"),!e||!e.onAdd)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));var o=e.onAdd(this);this._controls.push(e);var r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this},r.prototype.removeControl=function(e){if(!e||!e.onRemove)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));var i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this},r.prototype.resize=function(e){var i=this._containerDimensions(),o=i[0],r=i[1];this._resizeCanvas(o,r),this.transform.resize(o,r),this.painter.resize(o,r);var a=!this._moving;return a&&(this.stop(),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e))),this.fire(new t.Event("resize",e)),a&&this.fire(new t.Event("moveend",e)),this},r.prototype.getBounds=function(){return this.transform.getBounds()},r.prototype.getMaxBounds=function(){return this.transform.getMaxBounds()},r.prototype.setMaxBounds=function(e){return this.transform.setMaxBounds(t.LngLatBounds.convert(e)),this._update()},r.prototype.setMinZoom=function(t){if((t=null==t?-2:t)>=-2&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},r.prototype.getMaxZoom=function(){return this.transform.maxZoom},r.prototype.setMinPitch=function(t){if((t=null==t?0:t)<0)throw new Error("minPitch must be greater than or equal to 0");if(t>=0&&t<=this.transform.maxPitch)return this.transform.minPitch=t,this._update(),this.getPitch()60)throw new Error("maxPitch must be less than or equal to 60");if(t>=this.transform.minPitch)return this.transform.maxPitch=t,this._update(),this.getPitch()>t&&this.setPitch(t),this;throw new Error("maxPitch must be greater than the current minPitch")},r.prototype.getMaxPitch=function(){return this.transform.maxPitch},r.prototype.getRenderWorldCopies=function(){return this.transform.renderWorldCopies},r.prototype.setRenderWorldCopies=function(t){return this.transform.renderWorldCopies=t,this._update()},r.prototype.project=function(e){return this.transform.locationPoint(t.LngLat.convert(e))},r.prototype.unproject=function(e){return this.transform.pointLocation(t.Point.convert(e))},r.prototype.isMoving=function(){return this._moving||this.handlers.isMoving()},r.prototype.isZooming=function(){return this._zooming||this.handlers.isZooming()},r.prototype.isRotating=function(){return this._rotating||this.handlers.isRotating()},r.prototype._createDelegatedListener=function(t,e,i){var o,r=this;if("mouseenter"===t||"mouseover"===t){var a=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){var n=r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[];n.length?a||(a=!0,i.call(r,new Ao(t,r,o.originalEvent,{features:n}))):a=!1;},mouseout:function(){a=!1;}}}}if("mouseleave"===t||"mouseout"===t){var n=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){(r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[]).length?n=!0:n&&(n=!1,i.call(r,new Ao(t,r,o.originalEvent)));},mouseout:function(e){n&&(n=!1,i.call(r,new Ao(t,r,e.originalEvent)));}}}}return {layer:e,listener:i,delegates:(o={},o[t]=function(t){var o=r.getLayer(e)?r.queryRenderedFeatures(t.point,{layers:[e]}):[];o.length&&(t.features=o,i.call(r,t),delete t.features);},o)}},r.prototype.on=function(t,e,i){if(void 0===i)return o.prototype.on.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(r),r.delegates)this.on(a,r.delegates[a]);return this},r.prototype.once=function(t,e,i){if(void 0===i)return o.prototype.once.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in r.delegates)this.once(a,r.delegates[a]);return this},r.prototype.off=function(t,e,i){var r=this;return void 0===i?o.prototype.off.call(this,t,e):(this._delegatedListeners&&this._delegatedListeners[t]&&function(o){for(var a=o[t],n=0;n180;){var s=o.locationPoint(e);if(s.x>=0&&s.y>=0&&s.x<=o.width&&s.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e}zr.prototype.down=function(t,e){this.mouseRotate.mousedown(t,e),this.mousePitch&&this.mousePitch.mousedown(t,e),i.disableDrag();},zr.prototype.move=function(t,e){var i=this.map,o=this.mouseRotate.mousemoveWindow(t,e);if(o&&o.bearingDelta&&i.setBearing(i.getBearing()+o.bearingDelta),this.mousePitch){var r=this.mousePitch.mousemoveWindow(t,e);r&&r.pitchDelta&&i.setPitch(i.getPitch()+r.pitchDelta);}},zr.prototype.off=function(){var t=this.element;i.removeEventListener(t,"mousedown",this.mousedown),i.removeEventListener(t,"touchstart",this.touchstart,{passive:!1}),i.removeEventListener(t,"touchmove",this.touchmove),i.removeEventListener(t,"touchend",this.touchend),i.removeEventListener(t,"touchcancel",this.reset),this.offTemp();},zr.prototype.offTemp=function(){i.enableDrag(),i.removeEventListener(t.window,"mousemove",this.mousemove),i.removeEventListener(t.window,"mouseup",this.mouseup);},zr.prototype.mousedown=function(e){this.down(t.extend({},e,{ctrlKey:!0,preventDefault:function(){return e.preventDefault()}}),i.mousePos(this.element,e)),i.addEventListener(t.window,"mousemove",this.mousemove),i.addEventListener(t.window,"mouseup",this.mouseup);},zr.prototype.mousemove=function(t){this.move(t,i.mousePos(this.element,t));},zr.prototype.mouseup=function(t){this.mouseRotate.mouseupWindow(t),this.mousePitch&&this.mousePitch.mouseupWindow(t),this.offTemp();},zr.prototype.touchstart=function(t){1!==t.targetTouches.length?this.reset():(this._startPos=this._lastPos=i.touchPos(this.element,t.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:function(){return t.preventDefault()}},this._startPos));},zr.prototype.touchmove=function(t){1!==t.targetTouches.length?this.reset():(this._lastPos=i.touchPos(this.element,t.targetTouches)[0],this.move({preventDefault:function(){return t.preventDefault()}},this._lastPos));},zr.prototype.touchend=function(t){0===t.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)e.getEast()||i.latitudee.getNorth())},o.prototype._setErrorState=function(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");}},o.prototype._onSuccess=function(e){if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.Event("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();}},o.prototype._updateCamera=function(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.extend({bearing:r},this.options.fitBoundsOptions);this._map.fitBounds(i.toBounds(o),a,{geolocateSource:!0});},o.prototype._updateMarker=function(e){if(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},o.prototype._updateCircleRadius=function(){var t=this._map._container.clientHeight/2,e=this._map.unproject([0,t]),i=this._map.unproject([1,t]),o=e.distanceTo(i),r=Math.ceil(2*this._accuracy/o);this._circleElement.style.width=r+"px",this._circleElement.style.height=r+"px";},o.prototype._onZoom=function(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},o.prototype._onError=function(e){if(this._map){if(this.options.trackUserLocation)if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;var i=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=i,this._geolocateButton.setAttribute("aria-label",i),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Or)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();}},o.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},o.prototype._setupUI=function(e){var o=this;if(this._container.addEventListener("contextmenu",(function(t){return t.preventDefault()})),this._geolocateButton=i.create("button","mapboxgl-ctrl-geolocate",this._container),i.create("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden",!0),this._geolocateButton.type="button",!1===e){t.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");var r=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=r,this._geolocateButton.setAttribute("aria-label",r);}else {var a=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.title=a,this._geolocateButton.setAttribute("aria-label",a);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=i.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new Rr(this._dotElement),this._circleElement=i.create("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Rr({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(function(e){e.geolocateSource||"ACTIVE_LOCK"!==o._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(o._watchState="BACKGROUND",o._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),o._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),o.fire(new t.Event("trackuserlocationend")));}));},o.prototype.trigger=function(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":Br--,Or=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart"));}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){var e;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),++Br>1?(e={maximumAge:6e5,timeout:0},Or=!0):(e=this.options.positionOptions,Or=!1),this._geolocationWatchID=t.window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else t.window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0},o.prototype._clearWatch=function(){t.window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);},o}(t.Evented),Ur={maxWidth:100,unit:"metric"},Nr=function(e){this.options=t.extend({},Ur,e),t.bindAll(["_onMove","setUnit"],this);};function Zr(t,e,i){var o=i&&i.maxWidth||100,r=t._container.clientHeight/2,a=t.unproject([0,r]),n=t.unproject([o,r]),s=a.distanceTo(n);if(i&&"imperial"===i.unit){var l=3.2808*s;l>5280?jr(e,o,l/5280,t._getUIString("ScaleControl.Miles")):jr(e,o,l,t._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?jr(e,o,s/1852,t._getUIString("ScaleControl.NauticalMiles")):s>=1e3?jr(e,o,s/1e3,t._getUIString("ScaleControl.Kilometers")):jr(e,o,s,t._getUIString("ScaleControl.Meters"));}function jr(t,e,i,o){var r,a,n,s=(r=i,(a=Math.pow(10,(""+Math.floor(r)).length-1))*(n=(n=r/a)>=10?10:n>=5?5:n>=3?3:n>=2?2:n>=1?1:function(t){var e=Math.pow(10,Math.ceil(-Math.log(t)/Math.LN10));return Math.round(t*e)/e}(n)));t.style.width=e*(s/i)+"px",t.innerHTML=s+" "+o;}Nr.prototype.getDefaultPosition=function(){return "bottom-left"},Nr.prototype._onMove=function(){Zr(this._map,this._container,this.options);},Nr.prototype.onAdd=function(t){return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},Nr.prototype.onRemove=function(){i.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;},Nr.prototype.setUnit=function(t){this.options.unit=t,Zr(this._map,this._container,this.options);};var qr=function(e){this._fullscreen=!1,e&&e.container&&(e.container instanceof t.window.HTMLElement?this._container=e.container:t.warnOnce("Full screen control 'container' must be a DOM element.")),t.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in t.window.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in t.window.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in t.window.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in t.window.document&&(this._fullscreenchange="MSFullscreenChange");};qr.prototype.onAdd=function(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",t.warnOnce("This device does not support fullscreen mode.")),this._controlContainer},qr.prototype.onRemove=function(){i.remove(this._controlContainer),this._map=null,t.window.document.removeEventListener(this._fullscreenchange,this._changeIcon);},qr.prototype._checkFullscreenSupport=function(){return !!(t.window.document.fullscreenEnabled||t.window.document.mozFullScreenEnabled||t.window.document.msFullscreenEnabled||t.window.document.webkitFullscreenEnabled)},qr.prototype._setupUI=function(){var e=this._fullscreenButton=i.create("button","mapboxgl-ctrl-fullscreen",this._controlContainer);i.create("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden",!0),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),t.window.document.addEventListener(this._fullscreenchange,this._changeIcon);},qr.prototype._updateTitle=function(){var t=this._getTitle();this._fullscreenButton.setAttribute("aria-label",t),this._fullscreenButton.title=t;},qr.prototype._getTitle=function(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")},qr.prototype._isFullscreen=function(){return this._fullscreen},qr.prototype._changeIcon=function(){(t.window.document.fullscreenElement||t.window.document.mozFullScreenElement||t.window.document.webkitFullscreenElement||t.window.document.msFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle());},qr.prototype._onClickFullscreen=function(){this._isFullscreen()?t.window.document.exitFullscreen?t.window.document.exitFullscreen():t.window.document.mozCancelFullScreen?t.window.document.mozCancelFullScreen():t.window.document.msExitFullscreen?t.window.document.msExitFullscreen():t.window.document.webkitCancelFullScreen&&t.window.document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen();};var Vr={closeButton:!0,closeOnClick:!0,className:"",maxWidth:"240px"},Gr=function(e){function o(i){e.call(this),this.options=t.extend(Object.create(Vr),i),t.bindAll(["_update","_onClose","remove","_onMouseMove","_onMouseUp","_onDrag"],this);}return e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o,o.prototype.addTo=function(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")):this._map.on("move",this._update),this.fire(new t.Event("open")),this},o.prototype.isOpen=function(){return !!this._map},o.prototype.remove=function(){return this._content&&i.remove(this._content),this._container&&(i.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),delete this._map),this.fire(new t.Event("close")),this},o.prototype.getLngLat=function(){return this._lngLat},o.prototype.setLngLat=function(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.remove("mapboxgl-track-pointer")),this},o.prototype.trackPointer=function(){return this._trackPointer=!0,this._pos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")),this},o.prototype.getElement=function(){return this._container},o.prototype.setText=function(e){return this.setDOMContent(t.window.document.createTextNode(e))},o.prototype.setHTML=function(e){var i,o=t.window.document.createDocumentFragment(),r=t.window.document.createElement("body");for(r.innerHTML=e;i=r.firstChild;)o.appendChild(i);return this.setDOMContent(o)},o.prototype.getMaxWidth=function(){return this._container&&this._container.style.maxWidth},o.prototype.setMaxWidth=function(t){return this.options.maxWidth=t,this._update(),this},o.prototype.setDOMContent=function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},o.prototype.addClassName=function(t){this._container&&this._container.classList.add(t);},o.prototype.removeClassName=function(t){this._container&&this._container.classList.remove(t);},o.prototype.toggleClassName=function(t){if(this._container)return this._container.classList.toggle(t)},o.prototype._createContent=function(){this._content&&i.remove(this._content),this._content=i.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=i.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.setAttribute("aria-label","Close popup"),this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));},o.prototype._onMouseUp=function(t){this._update(t.point);},o.prototype._onMouseMove=function(t){this._update(t.point);},o.prototype._onDrag=function(t){this._update(t.point);},o.prototype._update=function(e){var o=this;if(this._map&&(this._lngLat||this._trackPointer)&&this._content&&(this._container||(this._container=i.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=i.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className&&this.options.className.split(" ").forEach((function(t){return o._container.classList.add(t)})),this._trackPointer&&this._container.classList.add("mapboxgl-popup-track-pointer")),this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._map.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=Dr(this._lngLat,this._pos,this._map.transform)),!this._trackPointer||e)){var r=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat),a=this.options.anchor,n=function e(i){if(i){if("number"==typeof i){var o=Math.round(Math.sqrt(.5*Math.pow(i,2)));return {center:new t.Point(0,0),top:new t.Point(0,i),"top-left":new t.Point(o,o),"top-right":new t.Point(-o,o),bottom:new t.Point(0,-i),"bottom-left":new t.Point(o,-o),"bottom-right":new t.Point(-o,-o),left:new t.Point(i,0),right:new t.Point(-i,0)}}if(i instanceof t.Point||Array.isArray(i)){var r=t.Point.convert(i);return {center:r,top:r,"top-left":r,"top-right":r,bottom:r,"bottom-left":r,"bottom-right":r,left:r,right:r}}return {center:t.Point.convert(i.center||[0,0]),top:t.Point.convert(i.top||[0,0]),"top-left":t.Point.convert(i["top-left"]||[0,0]),"top-right":t.Point.convert(i["top-right"]||[0,0]),bottom:t.Point.convert(i.bottom||[0,0]),"bottom-left":t.Point.convert(i["bottom-left"]||[0,0]),"bottom-right":t.Point.convert(i["bottom-right"]||[0,0]),left:t.Point.convert(i.left||[0,0]),right:t.Point.convert(i.right||[0,0])}}return e(new t.Point(0,0))}(this.options.offset);if(!a){var s,l=this._container.offsetWidth,c=this._container.offsetHeight;s=r.y+n.bottom.ythis._map.transform.height-c?["bottom"]:[],r.xthis._map.transform.width-l/2&&s.push("right"),a=0===s.length?"bottom":s.join("-");}var u=r.add(n[a]).round();i.setTransform(this._container,Mr[a]+" translate("+u.x+"px,"+u.y+"px)"),Lr(this._container,a,"popup");}},o.prototype._onClose=function(){this.remove();},o}(t.Evented),Wr={version:t.version,supported:e,setRTLTextPlugin:t.setRTLTextPlugin,getRTLTextPluginStatus:t.getRTLTextPluginStatus,Map:Ir,NavigationControl:Cr,GeolocateControl:Fr,AttributionControl:gr,ScaleControl:Nr,FullscreenControl:qr,Popup:Gr,Marker:Rr,Style:qe,LngLat:t.LngLat,LngLatBounds:t.LngLatBounds,Point:t.Point,MercatorCoordinate:t.MercatorCoordinate,Evented:t.Evented,config:t.config,prewarm:function(){Ft().acquire(Rt);},clearPrewarmedResources:function(){var t=Bt;t&&(t.isPreloaded()&&1===t.numActive()?(t.release(Rt),Bt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},get accessToken(){return t.config.ACCESS_TOKEN},set accessToken(e){t.config.ACCESS_TOKEN=e;},get baseApiUrl(){return t.config.API_URL},set baseApiUrl(e){t.config.API_URL=e;},get workerCount(){return kt.workerCount},set workerCount(t){kt.workerCount=t;},get maxParallelImageRequests(){return t.config.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(e){t.config.MAX_PARALLEL_IMAGE_REQUESTS=e;},clearStorage:function(e){t.clearTileCache(e);},workerUrl:""};return Wr})); + +// + +return mapboxgl; + +}))); +//# sourceMappingURL=mapbox-gl.js.map