[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "![Space Huggers - A JS13k Game by Frank Force](/screenshot.png)\n\nThe empire is spreading like a plague across the galaxy and building outposts on remote planets.\nYou are an elite rebel soldier tasked with wiping out those bases.\nExplore strange planets using your tools of destruction and eliminate the invaders!\nYou have only 10 clones left, 3 more will be replenished after each mission.\nGood luck, have fun, and give space a hug for me.\n\n## This game is only for learning purposes and not intended to be redistributed!\n\n# [PLAY SPACE HUGGERS!](https://www.newgrounds.com/portal/view/819609)\n# [OFFICIAL JS13K BUILD](https://js13kgames.com/entries/space-huggers)\n# [VIDEO DEMO](https://www.youtube.com/watch?v=6VXrnk18Z4s)\n\n# How To Play\n- Use WASD or D-Pad - Move, jump, and climb\n- Z or Left click - Shoot - Most things will break, some will burn\n- X or Middle click - Roll - brief invulnerability, does damage, gives a boost, puts out fire\n- C or Right click - Grenade - 3 per life, use wisely\n- You can also use a Xbox or SNES style controller, connect up to 4 for co-op play!\n- Kill all enemies to complete the level\n- A radar along the bottom of the screen shows nearby enemies\n- You start with 10 lives and get 3 more for completing each level\n- For an optimal play experience please use Chrome in full screen mode\n- There is no end, but for a challenge, try beating the first 5 levels\n\n# Gameplay Tips\n- Roll to put out fire!\n- Rolling also does melee damage to enemies\n- Keep your distance from the specialists (white), they roll and flip often!\n- You can hold down jump to climb up walls\n- Jump flip to get more vertical height (roll immediately after jumping)\n- To reach really high places try a grenade jump!\n- You can press R to restart the game\n\n# Game Features\n- Run and gun / roguelike hybrid gameplay\n- 2-4 player jump in local co-op mode\n- Procedural level generation of great variety and complexity\n- Levels are fully destructible with persistence\n- Fire propagation and explosion system\n- 5 enemy types with a larger variant\n- 7 different crate/barrel/rock types\n- 17 sprite textures using a 12 color palette\n- Checkpoints can be captured for players to respawn there\n- Multi layer procedurally generated parallax background\n- Starfield simulation with moving stars, planets, and suns\n- Particle systems for rain, snow, blood, explosions, weapons, water and more\n- Native resolution rendering up to 1920x1200\n- 11 different sound effects with [ZzFX](https://github.com/KilledByAPixel/ZzFX)\n- Up to 4 player co-op with 4 gamepads!\n\n# Engine Features\n- Custom game engine written during the compo is separate from game code\n- Super fast rendering system for up to 50,000 objects at 60 fps\n- Physics engine for axis aligned bounding box rigid body dynamics\n- Tile based rendering and collision system\n- Particle effects system\n- Input processing system for keyboard, mouse, gamepads, and touch\n- Math library with Vector2, Color and Timer utility classes\n- Audio with ZzFX has ability to attenuate sounds by distance\n- Debug visualization system not in JS13K build. (press ~ to enter debug mode)\n\n# Enemy Types\n- Recruit (Green) - A bit shorter, more hesitant, takes only 1 hit\n- Soldier (Blue) - Average height and ability, takes 2 hits\n- Captain (Red) - Can climb walls and jumps more often, takes 3 hits\n- Specialist (White) - Jumps and rolls often, they are ninjas, takes 4 hits\n- Demolitions Expert (Purple) - Throws grenades and can't catch fire, takes 5 hits\n- Small chance of a heavy weapons variation that has double health and fires full auto\n\n# Object Types\n- Plastic Crate (Brown) - Burns easily and breaks when fully burnt\n- Metal Crate & Barrel (Gray) - Is hard to destroy, can't burn\n- Water Barrel (Blue) - Puts out fires and pushes away objects\n- Explosive Crate & Barrel (Green) - Burns and explodes after a few seconds\n- High Explosive Barrel (Red) - Explodes quickly and much larger than normal explosives\n- Rock (Color Varies) - Heavy and very hard to destroy, can't burn, can crush enemies\n- Lava Rock (Glowing Red & Orange) - Anything that touches it is lit on fire\n\n# Tools Used\n- [Roadroller](https://github.com/lifthrasiir/roadroller)\n- [Google Closure Compiler](https://github.com/google/closure-compiler)\n- [UglifyJS](https://github.com/mishoo/UglifyJS)\n- [Imagemin](https://github.com/imagemin/imagemin)\n- [Efficient Compression Tool](https://github.com/fhanau/Efficient-Compression-Tool)\n- [Advzip](https://www.npmjs.com/package/advzip-bin)\n- [ZzFX](https://github.com/KilledByAPixel/ZzFX)\n\n# How to build the 13k Zip\n- Run engine\\build\\setupBuild.bat to install the necessary tools via npm\n- You will need: google-closure-compiler, uglify, roadroller, imagemin-cli, and advzip\n- Run engine\\build\\build.bat, to build app.zip which is the final result\n- It will also create a file called index.min.html you can use for testing\n- The zip size may vary by 20 bytes or so due to randomness of roadroller\n"
  },
  {
    "path": "app.js",
    "content": "/*\r\n    Javascript Space Game\r\n    By Frank Force 2021\r\n\r\n*/\r\n\r\n'use strict';\r\n\r\nconst clampCamera = !debug;\r\nconst lowGraphicsSettings = glOverlay = !window['chrome']; // only chromium uses high settings\r\nconst startCameraScale = 4*16;\r\nconst defaultCameraScale = 4*16;\r\nconst maxPlayers = 4;\r\n\r\nconst team_none = 0;\r\nconst team_player = 1;\r\nconst team_enemy = 2;\r\n\r\nlet updateWindowSize, renderWindowSize, gameplayWindowSize;\r\n\r\nengineInit(\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n()=> // appInit \r\n{\r\n    resetGame();\r\n    cameraScale = startCameraScale;\r\n},\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n()=> // appUpdate\r\n{\r\n    const cameraSize = vec2(mainCanvas.width, mainCanvas.height).scale(1/cameraScale);\r\n    renderWindowSize = cameraSize.add(vec2(5));\r\n\r\n    gameplayWindowSize = vec2(mainCanvas.width, mainCanvas.height).scale(1/defaultCameraScale);\r\n    updateWindowSize = gameplayWindowSize.add(vec2(30));\r\n    //debugRect(cameraPos, maxGameplayCameraSize);\r\n    //debugRect(cameraPos, updateWindowSize);\r\n\r\n    if (debug)\r\n    {\r\n        randSeeded(randSeeded(randSeeded(randSeed = Date.now()))); // set random seed for debug mode stuf\r\n        if (keyWasPressed(81))\r\n            new Enemy(mousePosWorld);\r\n\r\n        if (keyWasPressed(84))\r\n        {\r\n            //for(let i=30;i--;)\r\n                new Prop(mousePosWorld);\r\n        }\r\n\r\n        if (keyWasPressed(69))\r\n            explosion(mousePosWorld);\r\n\r\n        if (keyIsDown(89))\r\n        {\r\n            let e = new ParticleEmitter(mousePosWorld);\r\n\r\n            // test\r\n            e.collideTiles = 1;\r\n            //e.tileIndex=7;\r\n            e.emitSize = 2;\r\n            e.colorStartA = new Color(1,1,1,1);\r\n            e.colorStartB = new Color(0,1,1,1);\r\n            e.colorEndA = new Color(0,0,1,0);\r\n            e.colorEndB = new Color(0,.5,1,0);\r\n            e.emitConeAngle = .1;\r\n            e.particleTime = 1\r\n            e.speed = .3\r\n            e.elasticity = .1\r\n            e.gravityScale = 1;\r\n            //e.additive = 1;\r\n            e.angle = -PI;\r\n        }\r\n\r\n        if (mouseWheel) // mouse zoom\r\n            cameraScale = clamp(cameraScale*(1-mouseWheel/10), defaultTileSize.x*16, defaultTileSize.x/16);\r\n                    \r\n        //if (keyWasPressed(77))\r\n        //    playSong([[[,0,219,,,,,1.1,,-.1,-50,-.05,-.01,1],[2,0,84,,,.1,,.7,,,,.5,,6.7,1,.05]],[[[0,-1,1,0,5,0],[1,1,8,8,0,3]]],[0,0,0,0],90]) // music test\r\n\r\n        if (keyWasPressed(77))\r\n            players[0].pos = mousePosWorld;\r\n\r\n        /*if (keyWasPressed(32))\r\n        {\r\n            skyParticles && skyParticles.destroy();\r\n            tileLayer.destroy();\r\n            tileBackgroundLayer.destroy();\r\n            tileParallaxLayers.forEach((tileParallaxLayer)=>tileParallaxLayer.destroy());\r\n            randomizeLevelParams();\r\n            applyArtToLevel();\r\n        }*/\r\n        if (keyWasPressed(78))\r\n            nextLevel();\r\n    }\r\n\r\n    // restart if no lives left\r\n    let minDeadTime = 1e3;\r\n    for(const player of players)\r\n        minDeadTime = min(minDeadTime, player && player.isDead() ? player.deadTimer.get() : 0);\r\n\r\n    if (minDeadTime > 3 && (keyWasPressed(90) || keyWasPressed(32) || gamepadWasPressed(0)) || keyWasPressed(82))\r\n        resetGame();\r\n\r\n    if (levelEndTimer.get() > 3)\r\n        nextLevel();\r\n},\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n()=> // appUpdatePost\r\n{\r\n    if (players.length == 1)\r\n    {\r\n        const player = players[0];\r\n        if (!player.isDead())\r\n            cameraPos = cameraPos.lerp(player.pos, clamp(player.getAliveTime()/2));\r\n    }\r\n    else\r\n    {\r\n        // camera follows average pos of living players\r\n        let posTotal = vec2();\r\n        let playerCount = 0;\r\n        let cameraOffset = 1;\r\n        for(const player of players)\r\n        {\r\n            if (player && !player.isDead())\r\n            {\r\n                ++playerCount;\r\n                posTotal = posTotal.add(player.pos.add(vec2(0,cameraOffset)));\r\n            }\r\n        }\r\n\r\n        if (playerCount)\r\n            cameraPos = cameraPos.lerp(posTotal.scale(1/playerCount), .2);\r\n    }\r\n\r\n    // spawn players if they don't exist\r\n    for(let i = maxPlayers;i--;)\r\n    {\r\n        if (!players[i] && (gamepadWasPressed(0, i)||gamepadWasPressed(1, i)))\r\n        {\r\n            ++playerLives;\r\n            new Player(checkpointPos, i);\r\n        }\r\n    }\r\n    \r\n    // clamp to bottom and sides of level\r\n    if (clampCamera)\r\n    {\r\n        const w = mainCanvas.width/2/cameraScale+1;\r\n        const h = mainCanvas.height/2/cameraScale+2;\r\n        cameraPos.y = max(cameraPos.y, h);\r\n        if (w*2 < tileCollisionSize.x)\r\n            cameraPos.x = clamp(cameraPos.x, tileCollisionSize.x - w, w);\r\n    }\r\n\r\n    updateParallaxLayers();\r\n\r\n    updateSky();\r\n},\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n()=> // appRender\r\n{\r\n    const gradient = mainContext.createLinearGradient(0,0,0,mainCanvas.height);\r\n    gradient.addColorStop(0,levelSkyColor.rgba());\r\n    gradient.addColorStop(1,levelSkyHorizonColor.rgba());\r\n    mainContext.fillStyle = gradient;\r\n    //mainContext.fillStyle = levelSkyColor.rgba();\r\n    mainContext.fillRect(0,0,mainCanvas.width, mainCanvas.height);\r\n\r\n    drawStars();\r\n},\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n()=> // appRenderPost\r\n{\r\n    //let minAliveTime = 9;\r\n    //for(const player of players)\r\n    //    minAliveTime = min(minAliveTime, player.getAliveTime());\r\n\r\n    //const livesPercent = percent(minAliveTime, 5, 4)\r\n    //const s = 8;\r\n    //const offset = 100*livesPercent;\r\n    //mainContext.drawImage(tileImage, 32, 8, s, s, 32, mainCanvas.height-90, s*9, s*9);\r\n    mainContext.textAlign = 'center';\r\n    const p = percent(gameTimer.get(), 8, 10);\r\n\r\n    //mainContext.globalCompositeOperation = 'difference';\r\n    mainContext.fillStyle = new Color(0,0,0,p).rgba();\r\n    if (p > 0)\r\n    {\r\n        //mainContext.fillStyle = (new Color).setHSLA(time/3,1,.5,p).rgba();\r\n        mainContext.font = '1.5in impact';\r\n        mainContext.fillText('SPACE HUGGERS', mainCanvas.width/2, 140);\r\n    }\r\n\r\n    mainContext.font = '.5in impact';\r\n    p > 0 && mainContext.fillText('A JS13K Game by Frank Force',mainCanvas.width/2, 210);\r\n\r\n    // check if any enemies left\r\n    let enemiesCount = 0;\r\n    for (const o of engineCollideObjects)\r\n    {\r\n        if (o.isCharacter && o.team  == team_enemy)\r\n        {\r\n            ++enemiesCount;\r\n            const pos = vec2(mainCanvas.width/2 + (o.pos.x - cameraPos.x)*30,mainCanvas.height-20);\r\n            drawRectScreenSpace(pos, o.size.scale(20), o.color.scale(1,.6));\r\n        }\r\n    }\r\n\r\n    if (!enemiesCount && !levelEndTimer.isSet())\r\n        levelEndTimer.set();\r\n\r\n    mainContext.fillStyle = new Color(0,0,0).rgba();\r\n    mainContext.fillText('Level ' + level + '      Lives ' + playerLives + '      Enemies ' + enemiesCount, mainCanvas.width/2, mainCanvas.height-40);\r\n\r\n    // fade in level transition\r\n    const fade = levelEndTimer.isSet() ? percent(levelEndTimer.get(), 3, 1) : percent(levelTimer.get(), .5, 2);\r\n    drawRect(cameraPos, vec2(1e3), new Color(0,0,0,fade))\r\n});"
  },
  {
    "path": "appCharacters.js",
    "content": "/*\r\n    Javascript Space Game\r\n    By Frank Force 2021\r\n\r\n*/\r\n\r\n'use strict';\r\n\r\nconst aiEnable = 1;\r\nconst debugAI = 0;\r\nconst maxCharacterSpeed = .2;\r\n\r\nclass Character extends GameObject \r\n{\r\n    constructor(pos, sizeScale = 1) \r\n    { \r\n        super(pos, vec2(.6,.95).scale(sizeScale), 32);\r\n\r\n        this.health = this.healthMax = this.canBurn = this.isCharacter = 1;\r\n        this.sizeScale = sizeScale;\r\n        this.groundTimer = new Timer;\r\n        this.jumpTimer = new Timer;\r\n        this.pressedJumpTimer = new Timer;\r\n        this.preventJumpTimer = new Timer;\r\n        this.dodgeTimer = new Timer;\r\n        this.dodgeRechargeTimer = new Timer;\r\n        this.deadTimer = new Timer;\r\n        this.blinkTimer = new Timer;\r\n        this.moveInput = vec2();\r\n        this.extraAdditiveColor = new Color(0,0,0,0);\r\n        this.color = new Color;\r\n        this.eyeColor = new Color;\r\n        this.bodyTile = 3;\r\n        this.headTile = 2;\r\n        this.renderOrder = 10;\r\n        this.overkill = this.grenadeCount = this.walkCyclePercent = 0;\r\n        this.grendeThrowTimer = new Timer;\r\n        this.setCollision();\r\n    }\r\n    \r\n    update() \r\n    {\r\n        this.lastPos = this.pos.copy();\r\n        this.gravityScale = 1; // reset default gravity (incase climbing ladder)\r\n\r\n        if (this.isDead() || !this.inUpdateWindow() && !this.persistent)\r\n        {\r\n            super.update();\r\n            return; // ignore offscreen objects\r\n        }\r\n            \r\n        let moveInput = this.moveInput.copy();\r\n\r\n        // allow grabbing ladder at head or feet\r\n        let touchingLadder = 0;\r\n        for(let y=2;y--;)\r\n        {\r\n            const testPos = this.pos.add(vec2(0, y + .1*this.moveInput.y - this.size.y*.5));\r\n            const collisionData = getTileCollisionData(testPos);\r\n            touchingLadder |= collisionData == tileType_ladder;\r\n        }\r\n        if (!touchingLadder)\r\n            this.climbingLadder = 0;\r\n        else if (this.moveInput.y)\r\n            this.climbingLadder = 1;\r\n\r\n        if (this.dodgeTimer.active())\r\n        {\r\n            // update roll\r\n            this.angle = this.getMirrorSign(2*PI*this.dodgeTimer.getPercent());\r\n\r\n            if (this.groundObject)\r\n                this.velocity.x += this.getMirrorSign(.1);\r\n\r\n            // apply damage to enemies when rolling\r\n            forEachObject(this.pos, this.size, (o)=>\r\n            {\r\n                if (o.isCharacter && o.team != this.team && !o.isDead())\r\n                    o.damage(1, this);\r\n            });\r\n        }\r\n        else\r\n            this.angle = 0;\r\n\r\n        if (this.climbingLadder)\r\n        {\r\n            this.gravityScale = this.climbingWall = this.groundObject = 0;\r\n            this.jumpTimer.unset();\r\n            this.groundTimer.unset();\r\n            this.velocity = this.velocity.multiply(vec2(.85)).add(vec2(0,.02*moveInput.y));\r\n\r\n            const delta = (this.pos.x|0)+.5 - this.pos.x;\r\n            this.velocity.x += .02*delta*abs(moveInput.x ? 0:moveInput.y);\r\n            moveInput.x *= .2;\r\n\r\n            // exit ladder if ground is below\r\n            this.climbingLadder = moveInput.y >= 0 || getTileCollisionData(this.pos.subtract(vec2(0,1))) <= 0;\r\n        }\r\n        else\r\n        {\r\n            // update jumping and ground check\r\n            if (this.groundObject || this.climbingWall)\r\n                this.groundTimer.set(.1);\r\n\r\n            if (this.groundTimer.active() && !this.dodgeTimer.active())\r\n            {\r\n                // is on ground\r\n                if (this.pressedJumpTimer.active() \r\n                    && !this.jumpTimer.active() \r\n                    && !this.preventJumpTimer.active())\r\n                {\r\n                    // start jump\r\n                    if (this.climbingWall)\r\n                    {\r\n                        this.velocity.y = .25;\r\n                    }\r\n                    else\r\n                    {\r\n                        this.velocity.y = .15;\r\n                        this.jumpTimer.set(.2);\r\n                    }\r\n                    this.preventJumpTimer.set(.5);\r\n                    playSound(sound_jump, this.pos);\r\n                }\r\n            }\r\n\r\n            if (this.jumpTimer.active() && !this.climbingWall)\r\n            {\r\n                // update variable height jump\r\n                this.groundTimer.unset();\r\n                if (this.holdingJump && this.velocity.y > 0 && this.jumpTimer.active())\r\n                    this.velocity.y += .017;\r\n            }\r\n\r\n            if (!this.groundObject)\r\n            {\r\n                // air control\r\n                if (sign(moveInput.x) == sign(this.velocity.x))\r\n                    moveInput.x *= .1; // moving with velocity\r\n                else\r\n                    moveInput.x *= .2; // moving against velocity (stopping)\r\n                \r\n                // slight extra gravity when moving down\r\n                if (this.velocity.y < 0)\r\n                    this.velocity.y += gravity*.2;\r\n            }\r\n        }\r\n\r\n        if (this.pressedDodge && !this.dodgeTimer.active() && !this.dodgeRechargeTimer.active())\r\n        {\r\n            // start dodge\r\n            this.dodgeTimer.set(.4);\r\n            this.dodgeRechargeTimer.set(2);\r\n            this.jumpTimer.unset();\r\n            this.extinguish();\r\n            playSound(sound_dodge, this.pos);\r\n\r\n            if (!this.groundObject && this.getAliveTime() > .2)\r\n                this.velocity.y += .2;\r\n        }\r\n\r\n        // apply movement acceleration and clamp\r\n        this.velocity.x = clamp(this.velocity.x + moveInput.x * .042, maxCharacterSpeed, -maxCharacterSpeed);\r\n\r\n        // call parent, update physics\r\n        const oldVelocity = this.velocity.copy();\r\n        super.update();\r\n        if (!this.isPlayer && !this.dodgeTimer.active())\r\n        {\r\n            // apply collision damage\r\n            const deltaSpeedSquared = this.velocity.subtract(oldVelocity).lengthSquared();\r\n            deltaSpeedSquared > .1 && this.damage(10*deltaSpeedSquared);\r\n        }\r\n\r\n        if (this.climbingLadder || this.groundTimer.active() && !this.dodgeTimer.active())\r\n        {\r\n            const speed = this.velocity.length();\r\n            this.walkCyclePercent += speed * .5;\r\n            this.walkCyclePercent = speed > .01 ? mod(this.walkCyclePercent, 1) : 0;\r\n        }\r\n        else\r\n            this.walkCyclePercent = 0;\r\n\r\n        this.weapon.triggerIsDown = this.holdingShoot && !this.dodgeTimer.active();\r\n        if (!this.dodgeTimer.active())\r\n        {\r\n            if (this.grenadeCount > 0 && this.pressingThrow && !this.wasPressingThrow && !this.grendeThrowTimer.active())\r\n            {\r\n                // throw greande\r\n                --this.grenadeCount;\r\n                const grenade = new Grenade(this.pos);\r\n                grenade.velocity = this.velocity.add(vec2(this.getMirrorSign(),rand(.8,.7)).normalize(.25+rand(.02)));\r\n                grenade.angleVelocity = this.getMirrorSign() * rand(.8,.5);\r\n                playSound(sound_jump, this.pos);\r\n                this.grendeThrowTimer.set(1);\r\n            }\r\n            this.wasPressingThrow = this.pressingThrow;\r\n        }\r\n\r\n        // update mirror\r\n        if (this.moveInput.x && !this.dodgeTimer.active())\r\n            this.mirror = this.moveInput.x < 0;\r\n\r\n        // clamp x pos\r\n        this.pos.x = clamp(this.pos.x, levelSize.x-2, 2);\r\n\r\n        // randomly blink\r\n        rand() < .005 && this.blinkTimer.set(rand(.2,.1));\r\n    }\r\n       \r\n    render()\r\n    {\r\n        if (!isOverlapping(this.pos, this.size, cameraPos, renderWindowSize))\r\n            return;\r\n\r\n        // set tile to use\r\n        this.tileIndex = this.isDead() ? this.bodyTile : this.climbingLadder || this.groundTimer.active() ? this.bodyTile + 2*this.walkCyclePercent|0 : this.bodyTile+1;\r\n\r\n        let additive = this.additiveColor.add(this.extraAdditiveColor);\r\n        if (this.isPlayer && !this.isDead() && this.dodgeRechargeTimer.elapsed() && this.dodgeRechargeTimer.get() < .2)\r\n        {\r\n            const v = .6 - this.dodgeRechargeTimer.get()*3;\r\n            additive = additive.add(new Color(0,v,v,0)).clamp();\r\n        }\r\n\r\n        const sizeScale = this.sizeScale;\r\n        const color = this.color.scale(this.burnColorPercent(),1);\r\n        const eyeColor = this.eyeColor.scale(this.burnColorPercent(),1);\r\n\r\n        const bodyPos = this.pos.add(vec2(0,-.1+.06*Math.sin(this.walkCyclePercent*PI)).scale(sizeScale));\r\n        drawTile(bodyPos, vec2(sizeScale), this.tileIndex, this.tileSize, color, this.angle, this.mirror, additive);\r\n        drawTile(this.pos.add(vec2(this.getMirrorSign(.05),.46).scale(sizeScale).rotate(-this.angle)),vec2(sizeScale/2),this.headTile,vec2(8), color,this.angle,this.mirror, additive);\r\n\r\n        //for(let i = this.grenadeCount; i--;)\r\n        //    drawTile(bodyPos, vec2(.5), 5, vec2(8), new Color, this.angle, this.mirror, additive);\r\n\r\n        const blinkScale = this.canBlink ? this.isDead() ? .3: .5 + .5*Math.cos(this.blinkTimer.getPercent()*PI*2) : 1;\r\n            drawTile(this.pos.add(vec2(this.getMirrorSign(.05),.46).scale(sizeScale).rotate(-this.angle)),vec2(sizeScale/2, blinkScale*sizeScale/2),this.headTile+1,vec2(8), eyeColor, this.angle, this.mirror, this.additiveColor);\r\n    }\r\n\r\n    damage(damage, damagingObject)\r\n    {\r\n        if (this.destroyed)\r\n            return;\r\n\r\n        if (this.team == team_player)\r\n        {\r\n            // safety window after spawn\r\n            if (godMode || this.getAliveTime() < 2)\r\n                return;\r\n        }\r\n\r\n        if (this.isDead() && !this.persistent)\r\n        {\r\n            this.overkill += damage;\r\n            if (this.overkill > 5)\r\n            {\r\n                makeBlood(this.pos, 300);\r\n                this.destroy();\r\n            }\r\n        }\r\n\r\n        this.blinkTimer.set(rand(.5,.4));\r\n        makeBlood(damagingObject ? damagingObject.pos : this.pos);\r\n        super.damage(damage, damagingObject);\r\n    }\r\n\r\n    kill(damagingObject)                  \r\n    {\r\n        if (this.isDead())\r\n            return 0;\r\n\r\n        if (levelWarmup)\r\n        {\r\n            this.destroy();\r\n            return 1;\r\n        }\r\n        \r\n        this.deadTimer.set();\r\n        this.size = this.size.scale(.5);\r\n\r\n        makeBlood(this.pos, 300);\r\n        playSound(sound_die, this.pos);\r\n\r\n        this.team = team_none;\r\n        this.health = 0;\r\n        const fallDirection = damagingObject ? sign(damagingObject.velocity.x) : randSign();\r\n        this.angleVelocity = fallDirection*rand(.22,.14);\r\n        this.angleDamping = .9;\r\n        this.weapon && this.weapon.destroy();\r\n\r\n        // move to back layer\r\n        this.renderOrder = 1;\r\n    }\r\n    \r\n    collideWithTile(data, pos)\r\n    {\r\n        if (!data)\r\n            return;\r\n\r\n        if (data == tileType_ladder)\r\n        {\r\n            if (pos.y + 1 > this.lastPos.y - this.size.y*.5)\r\n                return;\r\n\r\n            if (getTileCollisionData(pos.add(vec2(0,1))) // above\r\n                && !(getTileCollisionData(pos.add(vec2(1,0))) // left\r\n                    && getTileCollisionData(pos.add(vec2(1,0)))) // right\r\n            )\r\n                return; // dont collide if something above it and nothing to left or right\r\n\r\n            // allow standing on top of ladders\r\n            return !this.climbingLadder;\r\n        }\r\n\r\n        // break blocks above\r\n        const d = pos.y - this.pos.y;\r\n        if (!this.climbingLadder && this.velocity.y > .1 && d > 0 && d < this.size.y*.5)\r\n        {\r\n            if (destroyTile(pos))\r\n            {\r\n                this.velocity.y = 0;\r\n                return;\r\n            }\r\n        }\r\n\r\n        return 1;\r\n    }\r\n\r\n    collideWithObject(o)\r\n    {\r\n        if (this.isDead())\r\n            return super.collideWithObject(o);\r\n\r\n        if (o.velocity.lengthSquared() > .04)\r\n        {\r\n            const v = o.velocity.subtract(this.velocity);\r\n            const  m = 25*o.mass * v.lengthSquared();\r\n            if (!o.groundObject && o.isCrushing && !this.persistent && o.velocity.y < 0 && this.pos.y < o.pos.y - o.size.y/2 && abs(o.pos.x - this.pos.x) < o.size.x*.5)\r\n            {\r\n                // crushing\r\n                this.damage(1e3, o);\r\n                if (this.isDead())\r\n                {\r\n                    makeBlood(this.pos, 300);\r\n                    this.destroy();\r\n                }\r\n            }\r\n            else if (m > 1)\r\n                this.damage(4*m|0, o)\r\n        }\r\n\r\n        return super.collideWithObject(o);\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nconst type_weak   = 0;\r\nconst type_normal = 1;\r\nconst type_strong = 2;\r\nconst type_elite  = 3;\r\nconst type_grenade= 4;\r\nconst type_count  = 5;\r\n\r\nfunction alertEnemies(pos, playerPos)\r\n{\r\n    const radius = 4;\r\n    forEachObject(pos, radius, (o)=>{o.team == team_enemy && o.alert && o.alert(playerPos)});\r\n    debugAI && debugCircle(pos, radius, '#0ff6');\r\n}\r\n\r\nclass Enemy extends Character\r\n{\r\n    constructor(pos) \r\n    { \r\n        super(pos);\r\n\r\n        this.team = team_enemy;\r\n        this.sawPlayerTimer = new Timer;\r\n        this.reactionTimer = new Timer;\r\n        this.facePlayerTimer = new Timer;\r\n        this.holdJumpTimer = new Timer;\r\n        this.shootTimer = new Timer;\r\n        this.maxVisionRange = 12;\r\n\r\n        this.type = randSeeded()**3*min(level+1,type_count)|0;\r\n\r\n        let health = 1 + this.type;\r\n        this.eyeColor = new Color(1,.5,0);\r\n        if (this.type == type_weak)\r\n        {\r\n            this.color = new Color(0,1,0);\r\n            this.size = this.size.scale(this.sizeScale = .9);\r\n        }\r\n        else if (this.type == type_normal)\r\n        {\r\n            this.color = new Color(0,.4,1);\r\n        }\r\n        else if (this.type == type_strong)\r\n        {\r\n            this.color = new Color(1,0,0);\r\n            this.eyeColor = new Color(1,1,0);\r\n        }\r\n        else if (this.type == type_elite)\r\n        {\r\n            this.color = new Color(1,1,1);\r\n            this.eyeColor = new Color(1,0,0);\r\n            this.maxVisionRange = 15;\r\n        }\r\n        else if (this.type == type_grenade)\r\n        {\r\n            this.color = new Color(.7,0,1);\r\n            this.eyeColor = new Color(0,0,0);\r\n            this.grenadeCount = 3;\r\n            this.canBurn = 0;\r\n        }\r\n\r\n        if (this.isBig = randSeeded() < .05)\r\n        {\r\n            // chance of large enemy with extra health\r\n            this.size = this.size.scale(this.sizeScale = 1.3);\r\n            health *= 2;\r\n            this.grenadeCount *= 10;\r\n            this.maxVisionRange = 15;\r\n            --levelEnemyCount;\r\n        }\r\n\r\n        this.health = this.healthMax = health;\r\n        this.color = this.color.mutate();\r\n        this.mirror = rand() < .5;\r\n\r\n        new Weapon(this.pos, this);\r\n         --levelEnemyCount;\r\n\r\n        this.sightCheckFrame = rand(9)|0;\r\n    }\r\n    \r\n    update()\r\n    {\r\n        if (!aiEnable || levelWarmup || this.isDead() || !this.inUpdateWindow())\r\n        {\r\n            if (this.weapon)\r\n                this.weapon.triggerIsDown = 0;\r\n            super.update();\r\n            return; // ignore offscreen objects\r\n        }\r\n\r\n        if (this.weapon)\r\n            this.weapon.localPos = this.weapon.localOffset.scale(this.sizeScale);\r\n\r\n        // update check if players are visible\r\n        const sightCheckFrames = 9;\r\n        ASSERT(this.sawPlayerPos || !this.sawPlayerTimer.isSet());\r\n        if (frame%sightCheckFrames == this.sightCheckFrame)\r\n        {\r\n            const sawRecently = this.sawPlayerTimer.isSet() && this.sawPlayerTimer.get() < 5;\r\n            const visionRangeSquared = (sawRecently ? this.maxVisionRange * 1.2 : this.maxVisionRange)**2;\r\n            debugAI && debugCircle(this.pos, visionRangeSquared**.5, '#f003', .1);\r\n            for(const player of players)\r\n            {\r\n                // check range\r\n                if (player && !player.isDead())\r\n                if (sawRecently || this.getMirrorSign() == sign(player.pos.x - this.pos.x))\r\n                if (sawRecently || abs(player.pos.x - this.pos.x) > abs(player.pos.y - this.pos.y) ) // 45 degree slope\r\n                if (this.pos.distanceSquared(player.pos) < visionRangeSquared)\r\n                {\r\n                    const raycastHit = tileCollisionRaycast(this.pos, player.pos);\r\n                    if (!raycastHit)\r\n                    {\r\n                        this.alert(player.pos, 1);\r\n                        debugAI && debugLine(this.pos, player.pos, '#0f0',.1)\r\n                        break;\r\n                    }\r\n                    debugAI && debugLine(this.pos, player.pos, '#f00',.1)\r\n                    debugAI && raycastHit && debugPoint(raycastHit, '#ff0',.1)\r\n                }\r\n            }\r\n\r\n            if (sawRecently)\r\n            {\r\n                // alert nearby enemies\r\n                alertEnemies(this.pos, this.sawPlayerPos);\r\n            }\r\n        }\r\n\r\n        this.pressedDodge = this.climbingWall = this.pressingThrow = 0;\r\n        \r\n        if (this.burnTimer.isSet())\r\n        {\r\n            // burning, run around\r\n            this.facePlayerTimer.unset();\r\n\r\n            // random jump\r\n            if (rand()< .005)\r\n            {\r\n                this.pressedJumpTimer.set(.05);\r\n                this.holdJumpTimer.set(rand(.05));\r\n            }\r\n            \r\n            // random movement\r\n            if (rand()<.05)\r\n                this.moveInput.x = randSign()*rand(.6, .3);\r\n            this.moveInput.y = 0;\r\n\r\n            // random dodge\r\n            if (this.type == type_elite)\r\n                this.pressedDodge = 1;\r\n            else if (this.groundObject)\r\n                this.pressedDodge = rand() < .005;\r\n        }\r\n        else if (this.sawPlayerTimer.isSet() && this.sawPlayerTimer.get() < 10)\r\n        {\r\n            debugAI && debugPoint(this.sawPlayerPos, '#f00');\r\n\r\n            // wall climb\r\n            if (this.type >= type_strong && this.moveInput.x && !this.velocity.x && this.velocity.y < 0)\r\n            {\r\n                this.velocity.y *=.8;\r\n                this.climbingWall = 1;\r\n                this.pressedJumpTimer.set(.1);\r\n                this.holdJumpTimer.set(rand(.2));\r\n            }\r\n            \r\n            const timeSinceSawPlayer = this.sawPlayerTimer.get();\r\n            this.weapon.localAngle *= .8;\r\n            if (this.reactionTimer.active())\r\n            {\r\n                // just saw player for first time, act surprised\r\n                this.moveInput.x = 0;\r\n            }\r\n            else if (timeSinceSawPlayer < 5)\r\n            {\r\n                debugAI && debugRect(this.pos, this.size, '#f00');\r\n                    \r\n                if (!this.dodgeTimer.active())\r\n                {\r\n                    const playerDirection = sign(this.sawPlayerPos.x - this.pos.x);\r\n                    if (this.type == type_grenade && rand() < .002 && this.getMirrorSign() == playerDirection)\r\n                        this.pressingThrow = 1;\r\n                        \r\n                    // actively fighting player\r\n                    if (rand()<.05)\r\n                        this.facePlayerTimer.set(rand(2,.5));\r\n\r\n                    // random jump\r\n                    if (rand()<(this.type < type_strong ? .0005 : .005))\r\n                    {\r\n                        this.pressedJumpTimer.set(.1);\r\n                        this.holdJumpTimer.set(rand(.2));\r\n                    }\r\n                    \r\n                    // random movement\r\n                    if (rand()<(this.isBig?.05:.02))\r\n                        this.moveInput.x = 0;\r\n                    else if (rand()<.01)\r\n                        this.moveInput.x = rand()<.6 ? playerDirection*rand(.5, .2) : -playerDirection*rand(.4, .2);\r\n                    if (rand()<.03)\r\n                        this.moveInput.y = rand()<.5 ? 0 : randSign()*rand(.4, .2);\r\n                \r\n                    // random shoot\r\n                    if (abs(this.sawPlayerPos.y - this.pos.y) < 4)\r\n                    if (!this.shootTimer.isSet() || this.shootTimer.get() > 1)\r\n                        rand() < (this.type > type_weak ? .02 : .01) && this.shootTimer.set(this.isBig ? rand(2,1) : .05);\r\n                }\r\n\r\n                // random dodge\r\n                if (this.type == type_elite)\r\n                    this.pressedDodge = rand() < .01 && timeSinceSawPlayer < .5;\r\n            }\r\n            else\r\n            {\r\n                // was fighting but lost player\r\n                debugAI && debugRect(this.pos, this.size, '#ff0');\r\n\r\n                if (rand()<.04)\r\n                    this.facePlayerTimer.set(rand(2,.5));\r\n\r\n                // random movement\r\n                if (rand()<.02)\r\n                    this.moveInput.x = 0;\r\n                else if (rand()<.01)\r\n                    this.moveInput.x = randSign()*rand(.4, .2);\r\n\r\n                // random jump\r\n                if (rand() < (this.sawPlayerPos.y > this.pos.y ? .002 : .001))\r\n                {\r\n                    this.pressedJumpTimer.set(.1);\r\n                    this.holdJumpTimer.set(rand(.2));\r\n                }\r\n                \r\n                // random shoot\r\n                if (!this.shootTimer.isSet() || this.shootTimer.get() > 5)\r\n                    rand() < .001 && this.shootTimer.set(rand(.2,.1));\r\n\r\n                // move up/down in dirction last player was seen\r\n                this.moveInput.y = clamp(this.sawPlayerPos.y - this.pos.y,.5,-.5);\r\n            }\r\n        }\r\n        else\r\n        {\r\n            // try to act normal\r\n            if (rand()<.03)\r\n                this.moveInput.x = 0;\r\n            else if (rand()<.005)\r\n                this.moveInput.x = randSign()*rand(.2, .1);\r\n            else if (rand()<.001)\r\n                this.moveInput.x = randSign()*1e-9; // hack: look in a direction\r\n\r\n            this.weapon.localAngle = lerp(.1, .7, this.weapon.localAngle);\r\n            this.reactionTimer.unset();\r\n        }\r\n\r\n        if (this.isBig && this.type != type_elite)\r\n        {\r\n            // big enemies cant jump\r\n            this.pressedJumpTimer.unset();\r\n            this.holdJumpTimer.unset();\r\n        }\r\n        this.holdingShoot = this.shootTimer.active();\r\n        this.holdingJump = this.holdJumpTimer.active();\r\n\r\n        super.update();\r\n\r\n        // override default mirror\r\n        if (this.facePlayerTimer.active() && !this.dodgeTimer.active() && !this.reactionTimer.active())\r\n            this.mirror = this.sawPlayerPos.x < this.pos.x;\r\n    }\r\n\r\n    alert(playerPos, resetSawPlayer)\r\n    {\r\n        if (resetSawPlayer || !this.sawPlayerTimer.isSet())\r\n        {\r\n            if (!this.reactionTimer.isSet())\r\n            {\r\n                this.reactionTimer.set(rand(1,.5)*(this.type == type_weak ? 2 : 1));\r\n                this.facePlayerTimer.set(rand(2,1));\r\n                if (this.groundObject && rand() < .2)\r\n                    this.velocity.y += .1; // random jump\r\n            }\r\n\r\n            this.sawPlayerTimer.set();\r\n            this.sawPlayerPos = playerPos;\r\n        }\r\n    }\r\n\r\n    damage(damage, damagingObject)\r\n    {\r\n        super.damage(damage, damagingObject);\r\n        if (!this.isDead())\r\n        {\r\n            this.alert(damagingObject ? damagingObject.pos.subtract(damagingObject.velocity.normalize()) : this.pos, 1);\r\n            this.reactionTimer.set(rand(1,.5));\r\n            this.shootTimer.unset();\r\n        }\r\n    }\r\n\r\n    kill(damagingObject)\r\n    {\r\n        if (this.isDead())\r\n            return 0;\r\n\r\n        super.kill(damagingObject);\r\n        levelWarmup || ++totalKills;\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nclass Player extends Character\r\n{\r\n    constructor(pos, playerIndex=0) \r\n    { \r\n        super(pos);\r\n\r\n        this.grenadeCount = 3;\r\n        this.burnTime = 2;\r\n        \r\n        this.eyeColor = (new Color).setHSLA(-playerIndex*.6,1,.5);\r\n        if (playerIndex)\r\n        {\r\n            this.color = (new Color).setHSLA(playerIndex*.3-.3,.5,.5);\r\n            this.extraAdditiveColor = (new Color).setHSLA(playerIndex*.3-.3,1,.1,0);\r\n        }\r\n\r\n        this.bodyTile = 5;\r\n        this.headTile = 18;\r\n        this.playerIndex = playerIndex;\r\n        this.renderOrder = 20 + 10*playerIndex;\r\n        this.walkSoundTime = 0;\r\n        this.persistent = this.wasHoldingJump = this.canBlink = this.isPlayer = 1;\r\n        this.team = team_player;\r\n        \r\n        new Weapon(this.pos, this);\r\n        players[playerIndex] = this;\r\n        \r\n        // small jump on spawn\r\n        this.velocity.y = .2;\r\n        this.mirror = playerIndex%2;\r\n        --playerLives;\r\n    }\r\n\r\n    update()\r\n    {\r\n        if (this.isDead())\r\n        {\r\n            if (this.persistent && playerLives)\r\n            {\r\n                if (players.length == 1)\r\n                {\r\n                    if (this.deadTimer.get() > 2)\r\n                    {\r\n                        this.persistent = 0;\r\n                        new Player(checkpointPos, this.playerIndex);\r\n                        playSound(sound_jump, cameraPos);\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    // respawn only if all players dead, or checkpoint touched\r\n                    let hasLivingPlayers = 0;\r\n                    let minDeadTime = 1e3;\r\n                    for(const player of players)\r\n                    {\r\n                        if (player)\r\n                        {\r\n                            minDeadTime = min(minDeadTime, player.isDead() ? player.deadTimer.get() : 1e3);\r\n                            hasLivingPlayers |= (!player.isDead() && player.getAliveTime() > .1);\r\n                        }\r\n                    }\r\n\r\n                    if (minDeadTime > 2)\r\n                    {\r\n                        if (!hasLivingPlayers)\r\n                        {\r\n                            // respawn all\r\n                            this.persistent = 0;\r\n                            new Player(checkpointPos.add(vec2(1-this.playerIndex/2,0)), this.playerIndex);\r\n                            this.playerIndex || playSound(sound_jump, cameraPos);\r\n                        }\r\n                        else if (checkpointTimer.active())\r\n                        {\r\n                            // respawn if checkpoint active\r\n                            this.persistent = 0;\r\n                            const player = new Player(checkpointPos, this.playerIndex);\r\n                            playSound(sound_jump, cameraPos);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            super.update();\r\n            return;\r\n        }\r\n\r\n        // wall climb\r\n        this.climbingWall = 0;\r\n        if (this.moveInput.x && !this.velocity.x && this.velocity.y < 0)\r\n        {\r\n            this.velocity.y *=.8;\r\n            this.climbingWall = 1;\r\n        }\r\n\r\n        // movement control\r\n        this.moveInput.x = isUsingGamepad || this.playerIndex ? gamepadStick(0, this.playerIndex).x : keyIsDown(39) - keyIsDown(37);\r\n\r\n        this.moveInput.y = isUsingGamepad || this.playerIndex ? gamepadStick(0, this.playerIndex).y : keyIsDown(38) - keyIsDown(40);\r\n        \r\n        // jump\r\n        this.holdingJump = (!this.playerIndex && keyIsDown(38)) || gamepadIsDown(0, this.playerIndex);\r\n        if (!this.holdingJump)\r\n            this.pressedJumpTimer.unset();\r\n        else if (!this.wasHoldingJump || this.climbingWall)\r\n            this.pressedJumpTimer.set(.3);\r\n        this.wasHoldingJump = this.holdingJump;\r\n\r\n        // controls\r\n        this.holdingShoot  = !this.playerIndex && (mouseIsDown(0) || keyIsDown(90)) || gamepadIsDown(2, this.playerIndex);\r\n        this.pressingThrow = !this.playerIndex && (mouseIsDown(2) || keyIsDown(67)) || gamepadIsDown(1, this.playerIndex);\r\n        this.pressedDodge  = !this.playerIndex && (mouseIsDown(1) || keyIsDown(88)) || gamepadIsDown(3, this.playerIndex);\r\n\r\n        super.update();\r\n\r\n        // update walk sound\r\n        this.walkSoundTime += abs(this.velocity.x);\r\n        if (abs(this.velocity.x) > .01 && this.groundTimer.active() && !this.dodgeTimer.active())\r\n        {\r\n            if (this.walkSoundTime > 1)\r\n            {\r\n                this.walkSoundTime = 0;\r\n                playSound(sound_walk, this.pos);\r\n            }\r\n        }\r\n        else\r\n            this.walkSoundTime = .5;\r\n\r\n        if (players.length > 1 && !this.isDead())\r\n        {\r\n            // move to other player if offscreen and multiplayer\r\n            if (!isOverlapping(this.pos, this.size, cameraPos, gameplayWindowSize))\r\n            {\r\n                // move to location of another player if not falling off a cliff\r\n                if (tileCollisionRaycast(this.pos,vec2(this.pos.x,0)))\r\n                {\r\n                    for(const player of players)\r\n                        if (player && player != this && !player.isDead())\r\n                        {\r\n                            this.pos = player.pos.copy();\r\n                            this.velocity = vec2();\r\n                            playSound(sound_jump, this.pos);\r\n                        }\r\n                }\r\n                else\r\n                    this.kill();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "appEffects.js",
    "content": "/*\r\n    Javascript Space Game\r\n    By Frank Force 2021\r\n\r\n*/\r\n\r\n'use strict';\r\n\r\nconst precipitationEnable = 1;\r\nconst debugFire = 0;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// sounds\r\n\r\nconst sound_shoot =        [,,90,,.01,.03,4,,,,,,,9,50,.2,,.2,.01];\r\nconst sound_destroyTile =  [.5,,1e3,.02,,.2,1,3,.1,,,,,1,-30,.5,,.5];\r\nconst sound_die =          [.5,.4,126,.05,,.2,1,2.09,,-4,,,1,1,1,.4,.03];\r\nconst sound_jump =         [.4,.2,250,.04,,.04,,,1,,,,,3];\r\nconst sound_dodge =        [.4,.2,150,.05,,.05,,,-1,,,,,4,,,,,.02];\r\nconst sound_walk =         [.3,.1,70,,,.01,4,,,,-9,.1,,,,,,.5];\r\nconst sound_explosion =    [2,.2,72,.01,.01,.2,4,,,,,,,1,,.5,.1,.5,.02];\r\nconst sound_checkpoint =   [.6,0,500,,.04,.3,1,2,,,570,.02,.02,,,,.04];\r\nconst sound_rain =         [.02,,1e3,2,,2,,,,,,,,99];\r\nconst sound_wind =         [.01,.3,2e3,2,1,2,,,,,,,1,2,,,,,,.1];\r\nconst sound_grenade =      [.5,.01,300,,,.02,3,.22,,,-9,.2,,,,,,.5];\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// special effects\r\n\r\nconst persistentParticleDestroyCallback = (particle)=>\r\n{\r\n    // copy particle to tile layer on death\r\n    ASSERT(particle.tileIndex < 0); // quick draw to tile layer uses canvas 2d so must be untextured\r\n    if (particle.groundObject)\r\n        tileLayer.drawTile(particle.pos, particle.size, particle.tileIndex, particle.tileSize, particle.color, particle.angle, particle.mirror);\r\n}\r\n\r\nfunction makeBlood(pos, amount=50)\r\n{\r\n    const emitter = new ParticleEmitter(\r\n        pos, 1, .1, amount, PI, // pos, emitSize, emitTime, emitRate, emiteCone\r\n        undefined, undefined,   // tileIndex, tileSize\r\n        new Color(1,0,0), new Color(.5,0,0), // colorStartA, colorStartB\r\n        new Color(1,0,0), new Color(.5,0,0), // colorEndA, colorEndB\r\n        3, .1, .1, .1, .1, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n        1, .95, .7, PI, 0,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n        .5, 1              // randomness, collide, additive, randomColorLinear, renderOrder\r\n    );\r\n    emitter.particleDestroyCallback = persistentParticleDestroyCallback;\r\n    return emitter;\r\n}\r\n\r\nfunction makeFire(pos = vec2())\r\n{\r\n    return new ParticleEmitter(\r\n        pos, 1, 0, 60, PI, // pos, emitSize, emitTime, emitRate, emiteCone\r\n        0, undefined,   // tileIndex, tileSize\r\n        new Color(1,1,0), new Color(1,.5,.5), // colorStartA, colorStartB\r\n        new Color(1,0,0), new Color(1,.5,.1), // colorEndA, colorEndB\r\n        .5, .5, .1, .01, .1, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n        .95, .1, -.05, PI, .5,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n        .5, 0, 1);             // randomness, collide, additive, randomColorLinear, renderOrder\r\n}\r\n\r\nfunction makeDebris(pos, color = new Color, amount = 100)\r\n{\r\n    const color2 = color.lerp(new Color, .5);\r\n    const emitter = new ParticleEmitter(\r\n        pos, 1, .1, amount, PI, // pos, emitSize, emitTime, emitRate, emiteCone\r\n        undefined, undefined, // tileIndex, tileSize\r\n        color, color2,       // colorStartA, colorStartB\r\n        color, color2,       // colorEndA, colorEndB\r\n        3, .2, .2, .1, .05, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n        1, .95, .4, PI, 0,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n        .5, 1               // randomness, collide, additive, randomColorLinear, renderOrder\r\n    );\r\n    emitter.elasticity = .3;\r\n    emitter.particleDestroyCallback = persistentParticleDestroyCallback;\r\n    return emitter;\r\n}\r\n\r\nfunction makeWater(pos, amount=400)\r\n{\r\n    // overall spray\r\n    new ParticleEmitter(\r\n        pos, 1, .05, 400, PI, // pos, emitSize, emitTime, emitRate, emiteCone\r\n        0, undefined,        // tileIndex, tileSize\r\n        new Color(1,1,1,.5), new Color(.5,1,1,.2), // colorStartA, colorStartB\r\n        new Color(1,1,1,.5), new Color(.5,1,1,.2), // colorEndA, colorEndB\r\n        .5, .5, 2, .1, .05, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n        .9, 1, 0, PI, .5,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n        .5, 0, 0, 0, 1e9              // randomness, collide, additive, randomColorLinear, renderOrder\r\n    );\r\n\r\n    // droplets\r\n    const emitter = new ParticleEmitter(\r\n        pos, 1, .1, amount, PI, // pos, emitSize, emitTime, emitRate, emiteCone\r\n        0, undefined,   // tileIndex, tileSize\r\n        new Color(.8,1,1,.6), new Color(.5,.5,1,.2), // colorStartA, colorStartB\r\n        new Color(.8,1,1,.6), new Color(.5,.5,1,.2), // colorEndA, colorEndB\r\n        2, .1, .1, .2, 0,  // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n        .99, 1, .5, PI, .2,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n        .5, 1              // randomness, collide, additive, randomColorLinear, renderOrder\r\n    );\r\n    emitter.elasticity = .2;\r\n    emitter.trailScale = 2;\r\n\r\n    // put out fires\r\n    const radius = 3;\r\n    forEachObject(pos, 3, (o)=> \r\n    {\r\n        if (o.isGameObject)\r\n        {\r\n            o.burnTimer.isSet() && o.extinguish();\r\n            const d = o.pos.distance(pos);\r\n            const p = percent(d, radius/2, radius);\r\n            const force = o.pos.subtract(pos).normalize(p*radius*.2);\r\n            o.applyForce(force);\r\n            if (o.isDead && o.isDead())\r\n                o.angleVelocity += randSign()*rand(radius/4,.3);\r\n        }\r\n    });\r\n\r\n    debugFire && debugCircle(pos, radius, '#0ff', 1)\r\n\r\n    return emitter;\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nfunction explosion(pos, radius=2)\r\n{\r\n    ASSERT(radius > 0);\r\n    if (levelWarmup)\r\n        return;\r\n\r\n    const damage = radius*2;\r\n\r\n    // destroy level\r\n    for(let x = -radius; x < radius; ++x)\r\n    {\r\n        const h = (radius**2 - x**2)**.5;\r\n        for(let y = -h; y <= h; ++y)\r\n            destroyTile(pos.add(vec2(x,y)), 0, 0);\r\n    }\r\n\r\n    // cleanup neighbors\r\n    const cleanupRadius = radius + 1;\r\n    for(let x = -cleanupRadius; x < cleanupRadius; ++x)\r\n    {\r\n        const h = (cleanupRadius**2 - x**2)**.5;\r\n        for(let y = -h; y < h; ++y)\r\n            decorateTile(pos.add(vec2(x,y)).int());\r\n    }\r\n\r\n    // kill/push objects\r\n    const maxRangeSquared = (radius*1.5)**2;\r\n    forEachObject(pos, radius*3, (o)=> \r\n    {\r\n        const d = o.pos.distance(pos);\r\n        if (o.isGameObject)\r\n        {\r\n            // do damage\r\n            d < radius && o.damage(damage);\r\n\r\n            // catch fire\r\n            d < radius*1.5 && o.burn();\r\n        }\r\n\r\n        // push\r\n        const p = percent(d, radius, 2*radius);\r\n        const force = o.pos.subtract(pos).normalize(p*radius*.2);\r\n        o.applyForce(force);\r\n        if (o.isDead && o.isDead())\r\n            o.angleVelocity += randSign()*rand(p*radius/4,.3);\r\n    });\r\n\r\n    playSound(sound_explosion, pos);\r\n    debugFire && debugCircle(pos, maxRangeSquared**.5, '#f00', 2);\r\n    debugFire && debugCircle(pos, radius**.5, '#ff0', 2);\r\n\r\n    // smoke\r\n    new ParticleEmitter(\r\n        pos, radius/2, .2, 50*radius, PI, // pos, emitSize, emitTime, emitRate, emiteCone\r\n        0, undefined,        // tileIndex, tileSize\r\n        new Color(0,0,0), new Color(0,0,0), // colorStartA, colorStartB\r\n        new Color(0,0,0,0), new Color(0,0,0,0), // colorEndA, colorEndB\r\n        1, .5, 2, .1, .05, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n        .9, 1, -.3, PI, .1,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n        .5, 0, 0, 0, 1e8              // randomness, collide, additive, randomColorLinear, renderOrder\r\n    );\r\n\r\n    // fire\r\n    new ParticleEmitter(\r\n        pos, radius/2, .1, 100*radius, PI, // pos, emitSize, emitTime, emitRate, emiteCone\r\n        0, undefined,        // tileIndex, tileSize\r\n        new Color(1,.5,.1), new Color(1,.1,.1), // colorStartA, colorStartB\r\n        new Color(1,.5,.1,0), new Color(1,.1,.1,0), // colorEndA, colorEndB\r\n        .5, .5, 2, .1, .05, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n        .9, 1, 0, PI, .05,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n        .5, 0, 1, 0, 1e9              // randomness, collide, additive, randomColorLinear, renderOrder\r\n    );\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nclass TileCascadeDestroy extends EngineObject \r\n{\r\n    constructor(pos, cascadeChance=1, glass=0)\r\n    {\r\n        super(pos, vec2());\r\n        this.cascadeChance = cascadeChance;\r\n        this.destroyTimer = new Timer(glass ? .05 : rand(.3, .1));\r\n    }\r\n\r\n    update()\r\n    {\r\n        if (this.destroyTimer.elapsed())\r\n        {\r\n            destroyTile(this.pos, 1, 1, this.cascadeChance);\r\n            this.destroy();\r\n        }\r\n    }\r\n}\r\n\r\nfunction decorateBackgroundTile(pos)\r\n{\r\n    const tileData = getTileBackgroundData(pos);\r\n    if (tileData <= 0)\r\n        return; // no need to clear if background cant change\r\n\r\n    // round corners\r\n    for(let i=4;i--;)\r\n    {\r\n        // check corner neighbors\r\n        const neighborTileDataA = getTileBackgroundData(pos.add(vec2().setAngle(i*PI/2)));\r\n        const neighborTileDataB = getTileBackgroundData(pos.add(vec2().setAngle((i+1)%4*PI/2)));\r\n\r\n        if (neighborTileDataA > 0 | neighborTileDataB > 0)\r\n            continue;\r\n\r\n        const directionVector = vec2().setAngle(i*PI/2+PI/4, 10).int();\r\n        let drawPos = pos.add(vec2(.5))            // center\r\n            .scale(16).add(directionVector).int(); // direction offset\r\n\r\n        // clear rect without any scaling to prevent blur from filtering\r\n        const s = 2;\r\n        tileBackgroundLayer.context.clearRect(\r\n            drawPos.x - s/2|0, \r\n            tileBackgroundLayer.canvas.height - drawPos.y - s/2|0, \r\n            s|0, s|0);\r\n    }\r\n}\r\n\r\nfunction decorateTile(pos)\r\n{\r\n    ASSERT((pos.x|0) == pos.x && (pos.y|0)== pos.y);\r\n    const tileData = getTileCollisionData(pos);\r\n    if (tileData <= 0)\r\n    {\r\n        tileData || tileLayer.setData(pos, new TileLayerData, 1); // force it to clear if it is empty\r\n        return;\r\n    }\r\n\r\n    if (tileData != tileType_dirt &\r\n            tileData != tileType_base &\r\n            tileData != tileType_pipeV &\r\n            tileData != tileType_pipeH &\r\n            tileData != tileType_solid)\r\n        return;\r\n\r\n    for(let i=4;i--;)\r\n    {\r\n        // outline towards neighbors of differing type\r\n        const neighborTileData = getTileCollisionData(pos.add(vec2().setAngle(i*PI/2)));\r\n        if (neighborTileData == tileData)\r\n            continue;\r\n\r\n        // hacky code to make pixel perfect outlines\r\n        let size = tileData == tileType_dirt ? vec2( rand(16,8), 2) : vec2( 16, 1);\r\n        i&1 && (size = size.flip());\r\n\r\n        const color = tileData == tileType_dirt ? levelGroundColor.mutate(.1) : new Color(.1,.1,.1);\r\n        tileLayer.context.fillStyle = color.rgba();\r\n        const drawPos = pos.scale(16);\r\n        if (tileData == tileType_dirt)\r\n            tileLayer.context.fillRect(\r\n                drawPos.x +   ((i==1?14:0)+(i&1?0:8-size.x/2)) |0, \r\n                tileLayer.canvas.height - drawPos.y + ((i==0?-14:0)-(i&1?8-size.y/2:0)) |0, \r\n                size.x|0, -size.y|0);\r\n        else\r\n            tileLayer.context.fillRect(\r\n                drawPos.x +  (i==1?15:0) |0, \r\n                tileLayer.canvas.height - drawPos.y + (i==0?-15:0) |0, \r\n                size.x|0, -size.y|0);\r\n    }\r\n}\r\n\r\nfunction destroyTile(pos, makeSound = 1, cleanNeighbors = 1, maxCascadeChance = 1)\r\n{\r\n    // pos must be an int\r\n    pos = pos.int();\r\n\r\n    // destroy tile\r\n    const tileType = getTileCollisionData(pos);\r\n\r\n    if (!tileType) return 1;                  // empty\r\n    if (tileType == tileType_solid) return 0; // indestructable\r\n\r\n    const centerPos = pos.add(vec2(.5));\r\n    const layerData = tileLayer.getData(pos);\r\n    if (layerData)\r\n    {\r\n        makeDebris(centerPos, layerData.color.mutate());\r\n        makeSound && playSound(sound_destroyTile, centerPos);\r\n\r\n        setTileCollisionData(pos, tileType_empty);\r\n        tileLayer.setData(pos, new TileLayerData, 1); // set and clear tile\r\n\r\n        // cleanup neighbors\r\n        if (cleanNeighbors)\r\n        {\r\n            for(let i=-1;i<=1;++i)\r\n            for(let j=-1;j<=1;++j)\r\n                decorateTile(pos.add(vec2(i,j)));\r\n        }\r\n\r\n        // if weak earth, random chance of delayed destruction of tile directly above\r\n        if (tileType == tileType_glass)\r\n        {\r\n            maxCascadeChance = 1;\r\n            if (getTileCollisionData(pos.add(vec2(0,-1))) == tileType)\r\n                new TileCascadeDestroy(pos.add(vec2(0,-1)), 1, 1);\r\n        }\r\n        else if (tileType != tileType_dirt)\r\n            maxCascadeChance = 0;\r\n\r\n        if (rand() < maxCascadeChance && getTileCollisionData(pos.add(vec2(0,1))) == tileType)\r\n            new TileCascadeDestroy(pos.add(vec2(0,1)), maxCascadeChance * .4, tileType == tileType_glass);\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nfunction drawStars()\r\n{\r\n    randSeed = levelSeed;\r\n    for(let i = lowGraphicsSettings ? 400 : 1e3; i--;)\r\n    {\r\n        let size = randSeeded(6, 1);\r\n        let speed = randSeeded() < .9 ? randSeeded(5) : randSeeded(99,9);\r\n        let color = (new Color).setHSLA(randSeeded(.2,-.3), randSeeded()**9, randSeeded(1,.5), randSeeded(.9,.3));\r\n        if (i < 9)\r\n        {\r\n            // suns or moons\r\n            size = randSeeded()**3*99 + 9;\r\n            speed = randSeeded(5);\r\n            color = (new Color).setHSLA(randSeeded(), randSeeded(), randSeeded(1,.5)).add(levelSkyColor.scale(.5)).clamp();\r\n        }\r\n        \r\n        const w = mainCanvas.width+400, h = mainCanvas.height+400;\r\n        const screenPos = vec2(\r\n            (randSeeded(w)+time*speed)%w-200,\r\n            (randSeeded(h)+time*speed*randSeeded(1,.2))%h-200);\r\n\r\n        if (lowGraphicsSettings)\r\n        {\r\n            // drawing stars with gl wont work in low graphics mode, just draw rects\r\n            mainContext.fillStyle = color.rgba();\r\n            if (size < 9)\r\n                mainContext.fillRect(screenPos.x, screenPos.y, size, size);\r\n            else\r\n                mainContext.beginPath(mainContext.fill(mainContext.arc(screenPos.x, screenPos.y, size, 0, 9)));\r\n        }\r\n        else\r\n            drawTileScreenSpace(screenPos, vec2(size), 0, vec2(16), color);\r\n    }\r\n}\r\n\r\nfunction updateSky()\r\n{\r\n    if (!skyParticles)\r\n        return;\r\n\r\n    let skyParticlesPos = cameraPos.add(vec2(rand(-40,40),0));\r\n    const raycastHit = tileCollisionRaycast(vec2(skyParticlesPos.x, levelSize.y), vec2(skyParticlesPos.x, 0));\r\n    if (raycastHit && raycastHit.y > cameraPos.y+10)\r\n        skyParticlesPos = raycastHit;\r\n    skyParticles.pos = skyParticlesPos.add(vec2(0,20));\r\n    \r\n    if (rand() < .002)\r\n    {\r\n        skyParticles.emitRate = clamp(skyParticles.emitRate + rand(200,-200), 500);\r\n        skyParticles.angle = clamp(skyParticles.angle + rand(.3,-.3),PI+.5,PI-.5);\r\n    }\r\n   \r\n    if (!levelWarmup && !skySoundTimer.active())\r\n    {\r\n        skySoundTimer.set(rand(2,1));\r\n        playSound(skyRain ? sound_rain : sound_wind, skyParticlesPos, 20, skyParticles.emitRate/1e3);\r\n        if (rand() < .1)\r\n            playSound(sound_wind, skyParticlesPos, 20, rand(skyParticles.emitRate/1e3));\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nlet tileParallaxLayers = [];\r\n\r\nfunction generateParallaxLayers()\r\n{\r\n    tileParallaxLayers = [];\r\n    for(let i=0; i<3; ++i)\r\n    {\r\n        const parallaxSize = vec2(600,300), startGroundLevel = rand(99,120)+i*30;\r\n        const tileParallaxLayer = tileParallaxLayers[i] = new TileLayer(vec2(), parallaxSize);\r\n        let groundLevel = startGroundLevel, groundSlope = rand(1,-1);\r\n        tileParallaxLayer.renderOrder = -3e3+i;\r\n        tileParallaxLayer.canvas.width = parallaxSize.x;\r\n\r\n        const layerColor = levelColor.mutate(.2).lerp(levelSkyColor,.95-i*.15);\r\n        const gradient = tileParallaxLayer.context.fillStyle = tileParallaxLayer.context.createLinearGradient(0,0,0,tileParallaxLayer.canvas.height = parallaxSize.y);\r\n        gradient.addColorStop(0,layerColor.rgba());\r\n        gradient.addColorStop(1,layerColor.subtract(new Color(1,1,1,0)).mutate(.1).clamp().rgba());\r\n\r\n        for(let x=parallaxSize.x;x--;)\r\n        {\r\n            // pull slope towards start ground level\r\n            tileParallaxLayer.context.fillRect(x,groundLevel += groundSlope = rand() < .05 ? rand(1,-1) :\r\n                groundSlope + (startGroundLevel - groundLevel)/2e3,1,parallaxSize.y)\r\n        }\r\n    }\r\n}\r\n\r\nfunction updateParallaxLayers()\r\n{\r\n    tileParallaxLayers.forEach((tileParallaxLayer, i)=>\r\n    {\r\n        const distance = 4+i;\r\n        const parallax = vec2(150,30).scale((i*i+1));\r\n        const cameraDeltaFromCenter = cameraPos.subtract(levelSize.scale(.5)).divide(levelSize.scale(-.5).divide(parallax));\r\n        tileParallaxLayer.scale = vec2(distance/cameraScale);\r\n        tileParallaxLayer.pos = cameraPos\r\n            .subtract(tileParallaxLayer.size.multiply(tileParallaxLayer.scale).scale(.5))\r\n            .add(cameraDeltaFromCenter.scale(1/cameraScale))\r\n            .subtract(vec2(0,150/cameraScale))\r\n    });\r\n}"
  },
  {
    "path": "appLevel.js",
    "content": "/*\r\n    Javascript Space Game\r\n    By Frank Force 2021\r\n\r\n*/\r\n\r\n'use strict';\r\n\r\nconst tileType_ladder  = -1;\r\nconst tileType_empty   = 0;\r\nconst tileType_solid   = 1;\r\nconst tileType_dirt    = 2;\r\nconst tileType_base    = 3;\r\nconst tileType_pipeH   = 4;\r\nconst tileType_pipeV   = 5;\r\nconst tileType_glass   = 6;\r\nconst tileType_baseBack= 7;\r\nconst tileType_window  = 8;\r\n\r\nconst tileRenderOrder = -1e3;\r\nconst tileBackgroundRenderOrder = -2e3;\r\n\r\n// level objects\r\nlet players=[], playerLives, tileLayer, tileBackgroundLayer, totalKills;\r\n\r\n// level settings\r\nlet levelSize, level, levelSeed, levelEnemyCount, levelWarmup;\r\nlet levelColor, levelBackgroundColor, levelSkyColor, levelSkyHorizonColor, levelGroundColor;\r\nlet skyParticles, skyRain, skySoundTimer = new Timer;\r\nlet gameTimer = new Timer, levelTimer = new Timer, levelEndTimer = new Timer;\r\n\r\nlet tileBackground;\r\nconst setTileBackgroundData = (pos, data=0)=>\r\n    pos.arrayCheck(tileCollisionSize) && (tileBackground[(pos.y|0)*tileCollisionSize.x+pos.x|0] = data);\r\nconst getTileBackgroundData = (pos)=>\r\n    pos.arrayCheck(tileCollisionSize) ? tileBackground[(pos.y|0)*tileCollisionSize.x+pos.x|0] : 0;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// level generation\r\n\r\nconst resetGame=()=>\r\n{\r\n    levelEndTimer.unset();\r\n    gameTimer.set(totalKills = level = 0);\r\n    nextLevel(playerLives = 6);\r\n}\r\n\r\nfunction buildTerrain(size)\r\n{\r\n    tileBackground = [];\r\n    initTileCollision(size);\r\n    let startGroundLevel = rand(40, 60);\r\n    let groundLevel = startGroundLevel;\r\n    let groundSlope = rand(.5,-.5);\r\n    let canayonWidth = 0, backgroundDelta = 0, backgroundDeltaSlope = 0;\r\n    for(let x=0; x < size.x; x++)\r\n    {\r\n        // pull slope towards start ground level\r\n        groundLevel += groundSlope = rand() < .05 ? rand(.5,-.5) :\r\n            groundSlope + (startGroundLevel - groundLevel)/1e3;\r\n        \r\n        // small jump\r\n        if (rand() < .04)\r\n            groundLevel += rand(9,-9);\r\n\r\n        if (rand() < .03)\r\n        {\r\n            // big jump\r\n            const jumpDelta = rand(9,-9);\r\n            startGroundLevel = clamp(startGroundLevel + jumpDelta, 80, 20);\r\n            groundLevel += jumpDelta;\r\n            groundSlope = rand(.5,-.5);\r\n        }\r\n\r\n        --canayonWidth;\r\n        if (rand() < .005)\r\n            canayonWidth = rand(7, 2);\r\n\r\n        backgroundDelta += backgroundDeltaSlope;\r\n        if (rand() < .1)\r\n            backgroundDelta = rand(3, -1);\r\n        if (rand() < .1)\r\n            backgroundDelta = 0;\r\n        if (rand() < .1)\r\n            backgroundDeltaSlope = rand(1,-1);\r\n        backgroundDelta = clamp(backgroundDelta, 3, -1)\r\n\r\n        groundLevel = clamp(groundLevel, 99, 30);\r\n        for(let y=0; y < size.y; y++)\r\n        {\r\n            const pos = vec2(x,y);\r\n\r\n            let frontTile = tileType_empty;\r\n            if (y < groundLevel && canayonWidth <= 0)\r\n                 frontTile = tileType_dirt;\r\n\r\n            let backTile = tileType_empty;\r\n            if (y < groundLevel + backgroundDelta)\r\n                 backTile = tileType_dirt;\r\n            \r\n            setTileCollisionData(pos, frontTile);\r\n            setTileBackgroundData(pos, backTile);\r\n        }\r\n    }\r\n\r\n    // add random holes\r\n    for(let i=levelSize.x; i--;)\r\n    {\r\n        const pos = vec2(rand(levelSize.x), rand(levelSize.y-19, 19));\r\n        for(let x = rand(9,1)|0;--x;)\r\n        for(let y = rand(9,1)|0;--y;)\r\n            setTileCollisionData(pos.add(vec2(x,y)), tileType_empty);\r\n    }\r\n}\r\n\r\nfunction spawnProps(pos)\r\n{\r\n    if (abs(checkpointPos.x-pos.x) > 5)\r\n    {\r\n        new Prop(pos);\r\n        const propPlaceSize = .51;\r\n        if (randSeeded() < .2)\r\n        {\r\n            // 3 triangle prop stack\r\n            new Prop(pos.add(vec2(propPlaceSize*2,0)));\r\n            if (randSeeded() < .2)\r\n                new Prop(pos.add(vec2(propPlaceSize,propPlaceSize*2)));\r\n        }\r\n        else if (randSeeded() < .2)\r\n        {\r\n            // 3 column prop stack\r\n            new Prop(pos.add(vec2(0,propPlaceSize*2)));\r\n            if (randSeeded() < .2)\r\n                new Prop(pos.add(vec2(0,propPlaceSize*4)));\r\n        }\r\n    }\r\n}\r\n\r\nfunction buildBase()\r\n{\r\n    let raycastHit;\r\n    for(let tries=99;!raycastHit;)\r\n    {\r\n        if (!tries--)\r\n            return 1; // count not find pos\r\n\r\n        const pos = vec2(randSeeded(levelSize.x-40,40), levelSize.y);\r\n\r\n        // must not be near player start\r\n        if (abs(checkpointPos.x-pos.x) > 30)\r\n            raycastHit = tileCollisionRaycast(pos, vec2(pos.x, 0));\r\n    }\r\n\r\n    const cave = rand() < .5;\r\n    const baseBottomCenterPos = raycastHit.int();\r\n    const baseSize = randSeeded(20,9)|0;\r\n    const baseFloors = cave? 1 : randSeeded(6,1)|0;\r\n    const basementFloors = randSeeded(cave?7:4, 0)|0;\r\n    let floorBottomCenterPos = baseBottomCenterPos.subtract(vec2(0,basementFloors*6));\r\n    floorBottomCenterPos.y = max(floorBottomCenterPos.y, 9); // prevent going through bottom\r\n\r\n    let floorWidth = baseSize;\r\n    let previousFloorHeight = 0;\r\n    for(let floor=-basementFloors; floor <= baseFloors; ++floor)\r\n    {  \r\n        const topFloor = floor == baseFloors;\r\n        const groundFloor = !floor;\r\n        const isCaveFloor = cave ? rand() < .8 | (floor == 0 && rand() < .6): 0;\r\n        let floorHeight = isCaveFloor ? randSeeded(9,2)|0 : topFloor? 0 : groundFloor? randSeeded(9,4)|0 : randSeeded(7,2)|0;\r\n        const floorSpace = topFloor ? 4 : max(floorHeight - 1, 0);\r\n\r\n        let backWindow = rand() < .5;\r\n        const windowTop = rand(4,2);\r\n\r\n        for(let x=-floorWidth; x <= floorWidth; ++x)\r\n        {\r\n            const isWindow = !isCaveFloor && randSeeded() < .3;\r\n            const hasSide = !isCaveFloor && randSeeded() < .9;\r\n\r\n            if (cave)\r\n                backWindow = 0;\r\n            else if (rand() < .1)\r\n                backWindow = !backWindow;\r\n\r\n            if (cave && rand() < .2)\r\n                floorHeight = clamp(floorHeight + rand(3,-3)|0, 9, 2)\r\n\r\n            for(let y=-1; y < floorHeight; ++y)\r\n            {\r\n                const pos = floorBottomCenterPos.add(vec2(x,y));\r\n                let foregroundTile = tileType_empty;\r\n                if (isCaveFloor)\r\n                {\r\n                    // add ceiling and floor\r\n                    if ( y < 0 | y == floorHeight-1)\r\n                        foregroundTile = tileType_dirt;\r\n\r\n                    setTileBackgroundData(pos, tileType_dirt);\r\n                    setTileCollisionData(pos, foregroundTile);\r\n                }\r\n                else\r\n                {\r\n                    // add ceiling and floor\r\n                    const isHorizontal = y < 0 | y == floorHeight-1;\r\n                    if (isHorizontal)\r\n                        foregroundTile = tileType_pipeH;\r\n\r\n                    // add walls and windows\r\n                    if (abs(x) == floorWidth)\r\n                        foregroundTile = isHorizontal ? tileType_base : isWindow ? tileType_glass : tileType_pipeV;\r\n\r\n                    let backgroundTile = foregroundTile>0||floorHeight<3? tileType_baseBack : tileType_base;\r\n                    if (backWindow && y > 0 && y < floorHeight-windowTop && abs(x) < floorWidth-2)\r\n                        backgroundTile = tileType_window;\r\n\r\n                    setTileBackgroundData(pos, backgroundTile);\r\n                    setTileCollisionData(pos, foregroundTile);\r\n                }\r\n            }\r\n        }\r\n\r\n        // add ladders to floor below\r\n        if (!cave || !topFloor)\r\n        for(let ladderCount=randSeeded(2)+1|0;ladderCount--;)\r\n        {\r\n            const x = randSeeded(floorWidth-1, -floorWidth+1)|0;\r\n            const pos = floorBottomCenterPos.add(vec2(x,-2));\r\n\r\n            let y=0;\r\n            let hitBottom = 0;\r\n            for(; y < levelSize.y; ++y)\r\n            {\r\n                const pos = floorBottomCenterPos.add(vec2(x,-y-1));\r\n                if (pos.y < 2)\r\n                {\r\n                    // hit bottom, no ladder\r\n                    break;\r\n                }\r\n                if (y && getTileCollisionData(pos) > 0 && getTileCollisionData(pos.add(vec2(0,1))) <= 0 )\r\n                {\r\n                    for(;y--;)\r\n                    {\r\n                        const pos = floorBottomCenterPos.add(vec2(x,-y-1));\r\n                        setTileCollisionData(pos, tileType_ladder);\r\n                    }\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n\r\n        // spawn crates\r\n        const propCount = randSeeded(floorWidth/2)|0;\r\n        for(let i = propCount; i--;)\r\n            spawnProps(floorBottomCenterPos.add(vec2(randSeeded( floorWidth-2,-floorWidth+2),.5)));\r\n\r\n        if (topFloor || floorSpace > 1)\r\n        {\r\n            // spawn enemies\r\n            for(let i = propCount; i--;)\r\n            {\r\n                const pos = floorBottomCenterPos.add(vec2(randSeeded( floorWidth-1,-floorWidth+1),.7));\r\n                new Enemy(pos);\r\n            }\r\n        }\r\n\r\n        const oldFloorWidth = floorWidth;\r\n        floorWidth = max(floorWidth + randSeeded(8,-8),9)|0;\r\n        floorBottomCenterPos.y += floorHeight;\r\n        floorBottomCenterPos.x += randSeeded(oldFloorWidth - floorWidth+1)|0;\r\n        previousFloorHeight = floorHeight;\r\n    }\r\n\r\n    //checkpointPos = floorBottomCenterPos.copy(); // start player on base for testing\r\n\r\n    // spawn random enemies and props\r\n    for(let i=20;levelEnemyCount>0&&i--;)\r\n    {\r\n        const pos = vec2(floorBottomCenterPos.x + randSeeded(99, -99), levelSize.y);\r\n        raycastHit = tileCollisionRaycast(pos, vec2(pos.x, 0));\r\n        // must not be near player start\r\n        if (raycastHit && abs(checkpointPos.x-pos.x) > 20)\r\n        {\r\n            const pos = raycastHit.add(vec2(0,2));\r\n            randSeeded() < .7 ? new Enemy(pos) : spawnProps(pos);\r\n        }\r\n    }\r\n}\r\n\r\nfunction generateLevel()\r\n{\r\n    levelEndTimer.unset();\r\n\r\n    // remove all objects that are not persistnt or are descendants of something persitant\r\n    for(const o of engineObjects)\r\n        o.destroy();\r\n    engineObjects = [];\r\n    engineCollideObjects = [];\r\n\r\n    // randomize ground level hills\r\n    buildTerrain(levelSize);\r\n\r\n    // find starting poing for player\r\n    let raycastHit;\r\n    for(let tries=99;!raycastHit;)\r\n    {\r\n        if (!tries--)\r\n            return 1; // count not find pos\r\n\r\n        // start on either side of level\r\n        checkpointPos = vec2(levelSize.x/2 + (levelSize.x/2-10-randSeeded(9))*(randSeeded()<.5?-1:1) | 0, levelSize.y);\r\n        raycastHit = tileCollisionRaycast(checkpointPos, vec2(checkpointPos.x, 0));\r\n    }\r\n    checkpointPos = raycastHit.add(vec2(0,1));\r\n\r\n    // random bases until there enough enemies\r\n    for(let tries=99;levelEnemyCount>0;)\r\n    {\r\n        if (!tries--)\r\n            return 1; // count not spawn enemies\r\n\r\n        if (buildBase())\r\n            return 1;\r\n    }\r\n\r\n    // build checkpoints\r\n    for(let x=0; x<levelSize.x-9; )\r\n    {\r\n        x += rand(100,70);\r\n        const pos = vec2(x, levelSize.y);\r\n        raycastHit = tileCollisionRaycast(pos, vec2(pos.x, 0));\r\n        // must not be near player start\r\n        if (raycastHit && abs(checkpointPos.x-pos.x) > 50)\r\n        {\r\n            // todo prevent overhangs\r\n            const pos = raycastHit.add(vec2(0,1));\r\n            new Checkpoint(pos);\r\n        }\r\n    }\r\n}\r\n\r\nconst groundTileStart = 8;\r\n\r\nfunction makeTileLayers(level_)\r\n{\r\n    // create foreground layer\r\n    tileLayer = new TileLayer(vec2(), levelSize);\r\n    tileLayer.renderOrder = tileRenderOrder;\r\n\r\n    // create background layer\r\n    tileBackgroundLayer = new TileLayer(vec2(), levelSize);\r\n    tileBackgroundLayer.renderOrder = tileBackgroundRenderOrder;\r\n\r\n    for(let x=levelSize.x;x--;)\r\n    for(let y=levelSize.y;y--;)\r\n    {\r\n        const pos = vec2(x,y);\r\n        let tileType = getTileCollisionData(pos);\r\n        if (tileType)\r\n        {\r\n            // todo pick tile, direction etc based on neighbors tile type\r\n            let direction = rand(4)|0\r\n            let mirror = rand(2)|0;\r\n            let color;\r\n\r\n            let tileIndex = groundTileStart;\r\n            if (tileType == tileType_dirt)\r\n            {\r\n                tileIndex = groundTileStart+2 + rand()**3*2|0;\r\n                color = levelColor.mutate(.03);\r\n            }\r\n            else if (tileType == tileType_pipeH)\r\n            {\r\n                tileIndex = groundTileStart+5;\r\n                direction = 1;\r\n            }\r\n            else if (tileType == tileType_pipeV)\r\n            {\r\n                tileIndex = groundTileStart+5;\r\n                direction = 0;\r\n            }\r\n            else if (tileType == tileType_glass)\r\n            {\r\n                tileIndex = groundTileStart+5;\r\n                direction = 0;\r\n                color = new Color(0,1,1,.5);\r\n            }\r\n            else if (tileType == tileType_base)\r\n                tileIndex = groundTileStart+4;\r\n            else if (tileType == tileType_ladder)\r\n            {\r\n                tileIndex = groundTileStart+7;\r\n                direction = mirror = 0;\r\n            }\r\n            tileLayer.setData(pos, new TileLayerData(tileIndex, direction, mirror, color));\r\n        }\r\n        \r\n        tileType = getTileBackgroundData(pos);\r\n        if (tileType)\r\n        {\r\n            // todo pick tile, direction etc based on neighbors tile type\r\n            const direction = rand(4)|0\r\n            const mirror = rand(2)|0;\r\n            let color = new Color();\r\n\r\n            let tileIndex = groundTileStart;\r\n            if (tileType == tileType_dirt)\r\n            {\r\n                tileIndex = groundTileStart +2 + rand()**3*2|0;\r\n                color = levelColor.mutate();\r\n            }\r\n            else if (tileType == tileType_base)\r\n            {\r\n                tileIndex = groundTileStart+6;\r\n                color = color.scale(rand(1,.7),1)\r\n            }\r\n            else if (tileType == tileType_baseBack)\r\n            {\r\n                tileIndex = groundTileStart+6;\r\n                color = color.scale(rand(.5,.3),1).mutate();\r\n            }\r\n            else if (tileType == tileType_window)\r\n            {\r\n                tileIndex = 0;\r\n                color = new Color(0,1,1,.5);\r\n            }\r\n            tileBackgroundLayer.setData(pos, new TileLayerData(tileIndex, direction, mirror, color.scale(.4,1)));\r\n        }\r\n    }\r\n    tileLayer.redraw();\r\n    tileBackgroundLayer.redraw();\r\n}\r\n\r\nfunction applyArtToLevel()\r\n{\r\n    makeTileLayers();\r\n    \r\n    // apply decoration to level tiles\r\n    for(let x=levelSize.x;x--;)\r\n    for(let y=levelSize.y;--y;)\r\n    {\r\n        decorateBackgroundTile(vec2(x,y));\r\n        decorateTile(vec2(x,y));\r\n    }\r\n\r\n    generateParallaxLayers();\r\n\r\n    if (precipitationEnable && !lowGraphicsSettings)\r\n    {\r\n        // create rain or snow particles\r\n        if (skyRain = rand() < .5)\r\n        {\r\n            // rain\r\n            skyParticles = new ParticleEmitter(\r\n                vec2(), 3, 0, 0, .3, // pos, emitSize, emitTime, emitRate, emiteCone\r\n                0, undefined,   // tileIndex, tileSize\r\n                new Color(.8,1,1,.6), new Color(.5,.5,1,.2), // colorStartA, colorStartB\r\n                new Color(.8,1,1,.6), new Color(.5,.5,1,.2), // colorEndA, colorEndB\r\n                2, .1, .1, .2, 0,  // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n                .99, 1, .5, PI, .2,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n                .5, 1              // randomness, collide, additive, randomColorLinear, renderOrder\r\n            );\r\n            skyParticles.elasticity = .2;\r\n            skyParticles.trailScale = 2;\r\n        }\r\n        else\r\n        {\r\n            // snow\r\n            skyParticles = new ParticleEmitter(\r\n                vec2(), 3, 0, 0, .5, // pos, emitSize, emitTime, emitRate, emiteCone\r\n                0, undefined,   // tileIndex, tileSize\r\n                new Color(1,1,1,.8), new Color(1,1,1,.2), // colorStartA, colorStartB\r\n                new Color(1,1,1,.8), new Color(1,1,1,.2), // colorEndA, colorEndB\r\n                3, .1, .1, .3, .01,  // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n                .98, 1, .2, PI, .2,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n                .5, 1              // randomness, collide, additive, randomColorLinear, renderOrder\r\n            );\r\n        }\r\n        skyParticles.emitRate = precipitationEnable && rand()<.5 ? rand(500) : 0;\r\n        skyParticles.angle = PI+rand(.5,-.5);\r\n    }\r\n}\r\n\r\nfunction nextLevel()\r\n{\r\n    playerLives += 4; // three for beating a level plus 1 for respawning\r\n    levelEnemyCount = 15 + min(level * 30, 300);\r\n    ++level;\r\n    levelSeed = randSeed = rand(1e9)|0;\r\n    levelSize = vec2(min(level*99,400),200);\r\n    levelColor = randColor(new Color(.2,.2,.2), new Color(.8,.8,.8));\r\n    levelSkyColor = randColor(new Color(.5,.5,.5), new Color(.9,.9,.9));\r\n    levelSkyHorizonColor = levelSkyColor.subtract(new Color(.05,.05,.05)).mutate(.3).clamp();\r\n    levelGroundColor = levelColor.mutate().add(new Color(.3,.3,.3)).clamp();\r\n\r\n    // keep trying until a valid level is generated\r\n    for(;generateLevel(););\r\n\r\n    // warm up level\r\n    levelWarmup = 1;\r\n\r\n    // objects that effect the level must be added here\r\n    const firstCheckpoint = new Checkpoint(checkpointPos).setActive();\r\n\r\n    applyArtToLevel();\r\n\r\n    const warmUpTime = 2;\r\n    for(let i=warmUpTime * FPS; i--;)\r\n    {\r\n        updateSky();\r\n        engineUpdateObjects();\r\n    }\r\n    levelWarmup = 0;\r\n\r\n    // destroy any objects that are stuck in collision\r\n    forEachObject(0, 0, (o)=>\r\n    {\r\n        if (o.isGameObject && o != firstCheckpoint)\r\n        {\r\n            const checkBackground = o.isCheckpoint;\r\n            (checkBackground ? getTileBackgroundData(o.pos) > 0 : tileCollisionTest(o.pos,o.size))  && o.destroy();\r\n        }\r\n    });\r\n\r\n    // hack, subtract off warm up time from main game timer\r\n    //gameTimer.time += warmUpTime;\r\n    levelTimer.set();\r\n\r\n    // spawn player\r\n    players = [];\r\n    new Player(checkpointPos);\r\n    //new Enemy(checkpointPos.add(vec2(3))); // test enemy\r\n}"
  },
  {
    "path": "appObjects.js",
    "content": "/*\r\n    Javascript Space Game\r\n    By Frank Force 2021\r\n\r\n*/\r\n\r\n'use strict';\r\n\r\nclass GameObject extends EngineObject \r\n{\r\n    constructor(pos, size, tileIndex, tileSize, angle)\r\n    {\r\n        super(pos, size, tileIndex, tileSize, angle);\r\n        this.isGameObject = 1;\r\n        this.health = this.healthMax = 0;\r\n        this.burnDelay = .1;\r\n        this.burnTime = 3;\r\n        this.damageTimer = new Timer;\r\n        this.burnDelayTimer = new Timer;\r\n        this.burnTimer = new Timer;\r\n        this.extinguishTimer = new Timer;\r\n        this.color = new Color;\r\n        this.additiveColor = new Color(0,0,0,0);\r\n    }\r\n\r\n    inUpdateWindow() { return levelWarmup || isOverlapping(this.pos, this.size, cameraPos, updateWindowSize); }\r\n\r\n    update()\r\n    {\r\n        if (this.parent || this.persistent || !this.groundObject || this.inUpdateWindow()) // pause physics if outside update window\r\n            super.update();\r\n\r\n        if (!this.isLavaRock)\r\n        {\r\n            if (!this.isDead() && this.damageTimer.isSet())\r\n            {\r\n                // flash white when damaged\r\n                const a = .5*percent(this.damageTimer.get(), 0, .15);\r\n                this.additiveColor = new Color(a,a,a,0);\r\n            }\r\n            else\r\n                this.additiveColor = new Color(0,0,0,0);\r\n        }\r\n        \r\n        if (!this.parent && this.pos.y < -1)\r\n        {\r\n            // kill and destroy if fall below level\r\n            this.kill();\r\n            this.persistent || this.destroy();\r\n        }\r\n        else if (this.burnTime)\r\n        {\r\n            if (this.burnTimer.isSet())\r\n            {\r\n                // burning\r\n                if (this.burnTimer.elapsed())\r\n                {\r\n                    this.kill();\r\n                    if (this.fireEmitter)\r\n                        this.fireEmitter.emitRate = 0;\r\n                }\r\n                else if (rand() < .01)\r\n                {\r\n                    // random chance to spread fire\r\n                    const spreadRadius = 2;\r\n                    debugFire && debugCircle(this.pos, spreadRadius, '#f00', 1);\r\n                    forEachObject(this.pos, spreadRadius, (o)=>o.isGameObject && o.burn());\r\n                }\r\n            }\r\n            else if (this.burnDelayTimer.elapsed())\r\n            {\r\n                // finished waiting to burn\r\n                this.burn(1);\r\n            }\r\n        }\r\n    }\r\n \r\n    render()\r\n    {\r\n        drawTile(this.pos, this.size, this.tileIndex, this.tileSize, this.color.scale(this.burnColorPercent(),1), this.angle, this.mirror, this.additiveColor);\r\n    }\r\n    \r\n    burnColorPercent() { return lerp(this.burnTimer.getPercent(), .2, 1); }\r\n\r\n    burn(instant)\r\n    {\r\n        if (!this.canBurn || this.burnTimer.isSet() || this.extinguishTimer.active())\r\n            return;\r\n\r\n        if (godMode && this.isPlayer)\r\n            return;\r\n\r\n        if (this.team == team_player)\r\n        {\r\n            // safety window after spawn\r\n            if (godMode || this.getAliveTime() < 2)\r\n                return;\r\n        }\r\n\r\n        if (instant)\r\n        {\r\n            this.burnTimer.set(this.burnTime*rand(1.5, 1));\r\n            this.fireEmitter = makeFire();\r\n            this.addChild(this.fireEmitter);\r\n        }\r\n        else\r\n            this.burnDelayTimer.isSet() || this.burnDelayTimer.set(this.burnDelay*rand(1.5, 1));\r\n    }\r\n\r\n    extinguish()\r\n    {\r\n        if (this.fireEmitter && this.fireEmitter.emitRate == 0)\r\n            return;\r\n\r\n        // stop burning\r\n        this.extinguishTimer.set(.1);\r\n        this.burnTimer.unset();\r\n        this.burnDelayTimer.unset();\r\n        if (this.fireEmitter)\r\n            this.fireEmitter.destroy();\r\n        this.fireEmitter = 0;\r\n    }\r\n    \r\n    heal(health)\r\n    {\r\n        assert(health >= 0);\r\n        if (this.isDead())\r\n            return 0;\r\n        \r\n        // apply healing and return amount healed\r\n        return this.health - (this.health = min(this.health + health, this.healthMax));\r\n    }\r\n\r\n    damage(damage, damagingObject)\r\n    {\r\n        ASSERT(damage >= 0);\r\n        if (this.isDead())\r\n            return 0;\r\n        \r\n        // set damage timer;\r\n        this.damageTimer.set();\r\n        for(const child of this.children)\r\n            child.damageTimer && child.damageTimer.set();\r\n\r\n        // apply damage and kill if necessary\r\n        const newHealth = max(this.health - damage, 0);\r\n        if (!newHealth)\r\n            this.kill(damagingObject);\r\n\r\n        // set new health and return amount damaged\r\n        return this.health - (this.health = newHealth);\r\n    }\r\n\r\n    isDead()                { return !this.health; }\r\n    kill(damagingObject)    { this.destroy(); }\r\n\r\n    collideWithObject(o)\r\n    {\r\n        if (o.isLavaRock && this.canBurn)\r\n        {\r\n            if (levelWarmup)\r\n            {\r\n                this.destroy();\r\n                return 1;\r\n            }\r\n            this.burn();\r\n        }\r\n        return 1;\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nconst propType_crate_wood           = 0;\r\nconst propType_crate_explosive      = 1;\r\nconst propType_crate_metal          = 2;\r\nconst propType_barrel_explosive     = 3;\r\nconst propType_barrel_water         = 4;\r\nconst propType_barrel_metal         = 5;\r\nconst propType_barrel_highExplosive = 6;\r\nconst propType_rock                 = 7;\r\nconst propType_rock_lava            = 8;\r\nconst propType_count                = 9;\r\n\r\nclass Prop extends GameObject \r\n{\r\n    constructor(pos, typeOverride) \r\n    { \r\n        super(pos);\r\n\r\n        const type = this.type = (typeOverride != undefined ? typeOverride : rand()**2*propType_count|0);\r\n        let health = 5;\r\n        this.tileIndex = 16;\r\n        this.explosionSize = 0;\r\n        if (this.type == propType_crate_wood)\r\n        {\r\n            this.color = new Color(1,.5,0);\r\n            this.canBurn = 1;\r\n        }\r\n        else if (this.type == propType_crate_metal)\r\n        {\r\n            this.color = new Color(.9,.9,1);\r\n            health = 10;\r\n        }\r\n        else if (this.type == propType_crate_explosive)\r\n        {\r\n            this.color = new Color(.2,.8,.2);\r\n            this.canBurn = 1;\r\n            this.explosionSize = 2;\r\n            health = 1e3;\r\n        }\r\n        else if (this.type == propType_barrel_metal)\r\n        {\r\n            this.tileIndex = 17;\r\n            this.color = new Color(.9,.9,1);\r\n            health = 10;\r\n        }\r\n        else if (this.type == propType_barrel_explosive)\r\n        {\r\n            this.tileIndex = 17;\r\n            this.color = new Color(.2,.8,.2);\r\n            this.canBurn = 1;\r\n            this.explosionSize = 2;\r\n            health = 1e3;\r\n        }\r\n        else if (this.type == propType_barrel_highExplosive)\r\n        {\r\n            this.tileIndex = 17;\r\n            this.color = new Color(1,.1,.1);\r\n            this.canBurn = 1;\r\n            this.explosionSize = 3;\r\n            this.burnTimeDelay = 0;\r\n            this.burnTime = rand(.5,.1);\r\n            health = 1e3;\r\n        }\r\n        else if (this.type == propType_barrel_water)\r\n        {\r\n            this.tileIndex = 17;\r\n            this.color = new Color(0,.6,1);\r\n            health = .01;\r\n        }\r\n        else if (this.type == propType_rock || this.type == propType_rock_lava)\r\n        {\r\n            this.tileIndex = 18;\r\n            this.color = new Color(.8,.8,.8).mutate(.2);\r\n            health = 30;\r\n            this.mass *= 4;\r\n            if (rand() < .2)\r\n            {\r\n                health = 99;\r\n                this.mass *= 4;\r\n                this.size = this.size.scale(2);\r\n                this.pos.y += .5;\r\n            }\r\n            this.isCrushing = 1;\r\n\r\n            if (this.type == propType_rock_lava)\r\n            {\r\n                this.color = new Color(1,.9,0);\r\n                this.additiveColor = new Color(1,0,0);\r\n                this.isLavaRock = 1;    \r\n            }\r\n        }\r\n\r\n        // randomly angle and flip axis (90 degree rotation)\r\n        this.angle = (rand(4)|0)*PI/2;\r\n        if (rand() < .5)\r\n            this.size = this.size.flip();\r\n\r\n        this.mirror = rand() < .5;\r\n        this.health = this.healthMax = health;\r\n        this.setCollision(1, 1);\r\n    }\r\n \r\n    update()\r\n    {\r\n        const oldVelocity = this.velocity.copy();\r\n        super.update();\r\n\r\n        // apply collision damage\r\n        const deltaSpeedSquared = this.velocity.subtract(oldVelocity).lengthSquared();\r\n        deltaSpeedSquared > .05 && this.damage(2*deltaSpeedSquared);\r\n    }\r\n\r\n    damage(damage, damagingObject)\r\n    {\r\n        (this.explosionSize || this.type == propType_crate_wood && rand() < .1) && this.burn();\r\n        super.damage(damage, damagingObject);\r\n    }\r\n\r\n    kill()\r\n    {\r\n        if (this.destroyed) return;\r\n\r\n        if (this.type == propType_barrel_water)\r\n            makeWater(this.pos);\r\n\r\n        this.destroy();\r\n        makeDebris(this.pos, this.color.scale(this.burnColorPercent(),1));\r\n        \r\n        this.explosionSize ? \r\n            explosion(this.pos, this.explosionSize) :\r\n            playSound(sound_destroyTile, this.pos);\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nlet checkpointPos, activeCheckpoint, checkpointTimer = new Timer;\r\n\r\nclass Checkpoint extends GameObject \r\n{\r\n    constructor(pos)\r\n    {\r\n        super(pos.int().add(vec2(.5)))\r\n        this.renderOrder = tileRenderOrder-1;\r\n        this.isCheckpoint = 1;\r\n        for(let x=3;x--;)\r\n        for(let y=6;y--;)\r\n            setTileCollisionData(pos.subtract(vec2(x-1,1-y)), y ? tileType_empty : tileType_solid);\r\n    }\r\n\r\n    update()\r\n    {\r\n        if (!this.inUpdateWindow())\r\n            return; // ignore offscreen objects\r\n\r\n        // check if player is near\r\n        for(const player of players)\r\n            player && !player.isDead() && this.pos.distanceSquared(player.pos) < 1 && this.setActive();\r\n    }\r\n\r\n    setActive()\r\n    {\r\n        if (activeCheckpoint != this && !levelWarmup)\r\n            playSound(sound_checkpoint, this.pos);\r\n\r\n        checkpointPos = this.pos;\r\n        activeCheckpoint = this;\r\n        checkpointTimer.set(.1);\r\n    }\r\n\r\n    render()\r\n    {\r\n        // draw flag\r\n        const height = 4;\r\n        const color = activeCheckpoint == this ? new Color(1,0,0) : new Color;\r\n        const a = Math.sin(time*4+this.pos.x);\r\n        drawTile(this.pos.add(vec2(.5,height-.3-.5-.03*a)), vec2(1,.6), 14, undefined, color, a*.06);  \r\n        drawRect(this.pos.add(vec2(0,height/2-.5)), vec2(.1,height), new Color(.9,.9,.9));\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nclass Grenade extends GameObject\r\n{\r\n    constructor(pos) \r\n    {\r\n        super(pos, vec2(.2), 5, vec2(8));\r\n\r\n        this.health = this.healthMax = 1e3;\r\n        this.beepTimer = new Timer(1);\r\n        this.elasticity = .3;\r\n        this.friction   = .9;\r\n        this.angleDamping = .96;\r\n        this.renderOrder = 1e8;\r\n        this.setCollision();\r\n    }\r\n\r\n    update()\r\n    {\r\n        super.update();\r\n\r\n        if (this.getAliveTime() > 3)\r\n        {\r\n            explosion(this.pos, 3);\r\n            this.destroy();\r\n            return;\r\n        }\r\n\r\n        if (this.beepTimer.elapsed())\r\n        {\r\n            playSound(sound_grenade, this.pos)\r\n            this.beepTimer.set(1);\r\n        }\r\n\r\n        alertEnemies(this.pos, this.pos);\r\n    }\r\n       \r\n    render()\r\n    {\r\n        drawTile(this.pos, vec2(.5), this.tileIndex, this.tileSize, this.color, this.angle);\r\n\r\n        const a = this.getAliveTime();\r\n        setBlendMode(1);\r\n        drawTile(this.pos, vec2(2), 0, vec2(16), new Color(1,0,0,.2-.2*Math.cos(a*2*PI)));\r\n        drawTile(this.pos, vec2(1), 0, vec2(16), new Color(1,0,0,.2-.2*Math.cos(a*2*PI)));\r\n        drawTile(this.pos, vec2(.5), 0, vec2(16), new Color(1,1,1,.2-.2*Math.cos(a*2*PI)));\r\n        setBlendMode(0);\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nclass Weapon extends EngineObject \r\n{\r\n    constructor(pos, parent) \r\n    { \r\n        super(pos, vec2(.6), 4, vec2(8));\r\n\r\n        // weapon settings\r\n        this.isWeapon = 1;\r\n        this.fireTimeBuffer = this.localAngle = 0;\r\n        this.recoilTimer = new Timer;\r\n\r\n        this.addChild(this.shellEmitter = new ParticleEmitter(\r\n            vec2(), 0, 0, 0, .1,  // pos, emitSize, emitTime, emitRate, emiteCone\r\n            undefined, undefined, // tileIndex, tileSize\r\n            new Color(1,.8,.5), new Color(.9,.7,.5), // colorStartA, colorStartB\r\n            new Color(1,.8,.5), new Color(.9,.7,.5), // colorEndA, colorEndB\r\n            3, .1, .1, .15, .1, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n            1, .95, 1, 0, 0,    // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n            .1, 1              // randomness, collide, additive, randomColorLinear, renderOrder\r\n        ));\r\n        this.shellEmitter.elasticity = .5;\r\n        this.shellEmitter.particleDestroyCallback = persistentParticleDestroyCallback;\r\n        this.renderOrder = parent.renderOrder+1;\r\n\r\n        parent.weapon = this;\r\n        parent.addChild(this, this.localOffset = vec2(.55,0));\r\n    }\r\n\r\n    update()\r\n    {\r\n        super.update();\r\n\r\n        const fireRate = 8;\r\n        const bulletSpeed = .5;\r\n        const spread = .1;\r\n\r\n        this.mirror = this.parent.mirror;\r\n        this.fireTimeBuffer += timeDelta;\r\n\r\n        if (this.recoilTimer.active())\r\n            this.localAngle = lerp(this.recoilTimer.getPercent(), 0, this.localAngle);\r\n\r\n        if (this.triggerIsDown)\r\n        {\r\n            // slow down enemy bullets\r\n            const speed = bulletSpeed * (this.parent.isPlayer ? 1 : .5);\r\n            const rate = 1/fireRate;\r\n            for(; this.fireTimeBuffer > 0; this.fireTimeBuffer -= rate)\r\n            {\r\n                this.localAngle = -rand(.2,.15);\r\n                this.recoilTimer.set(rand(.4,.3));\r\n                const bullet = new Bullet(this.pos, this.parent);\r\n                const direction = vec2(this.getMirrorSign(speed), 0);\r\n                bullet.velocity = direction.rotate(rand(spread,-spread));\r\n\r\n                this.shellEmitter.localAngle = -.8*this.getMirrorSign();\r\n                this.shellEmitter.emitParticle();\r\n                playSound(sound_shoot, this.pos);\r\n\r\n                // alert enemies\r\n                this.parent.isPlayer && alertEnemies(this.pos, this.pos);\r\n            }\r\n        }\r\n        else\r\n            this.fireTimeBuffer = min(this.fireTimeBuffer, 0);\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nclass Bullet extends EngineObject \r\n{\r\n    constructor(pos, attacker) \r\n    { \r\n        super(pos, vec2(0));\r\n        this.color = new Color(1,1,0,1);\r\n        this.lastVelocity = this.velocity;\r\n        this.setCollision();\r\n\r\n        this.damage = this.damping = 1;\r\n        this.gravityScale = 0;\r\n        this.attacker = attacker;\r\n        this.team = attacker.team;\r\n        this.renderOrder = 1e9;\r\n        this.range = 8;\r\n    }\r\n\r\n    update()\r\n    {\r\n        this.lastVelocity = this.velocity;\r\n        super.update();\r\n\r\n        this.range -= this.velocity.length();\r\n        if (this.range < 0)\r\n        {\r\n            const emitter = new ParticleEmitter(\r\n                this.pos, .2, .1, 100, PI, // pos, emitSize, emitTime, emitRate, emiteCone\r\n                0, undefined,     // tileIndex, tileSize\r\n                new Color(1,1,0,.5), new Color(1,1,1,.5), // colorStartA, colorStartB\r\n                new Color(1,1,0,0), new Color(1,1,1,0), // colorEndA, colorEndB\r\n                .1, .5, .1, .1, .1, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n                1, 1, .5, PI, .1,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n                .5, 0, 1           // randomness, collide, additive, randomColorLinear, renderOrder\r\n            );\r\n\r\n            this.destroy();\r\n            return;\r\n        }\r\n\r\n        // check if hit someone\r\n        forEachObject(this.pos, this.size, (o)=>\r\n        {\r\n            if (o.isGameObject && !o.parent && o.team != this.team)\r\n            if (!o.dodgeTimer || !o.dodgeTimer.active())\r\n                this.collideWithObject(o)\r\n        });\r\n    }\r\n    \r\n    collideWithObject(o)\r\n    {\r\n        if (o.isGameObject)\r\n        {\r\n            o.damage(this.damage, this);\r\n            o.applyForce(this.velocity.scale(.1));\r\n            if (o.isCharacter)\r\n            {\r\n                playSound(sound_walk, this.pos);\r\n                this.destroy();\r\n            }\r\n            else\r\n                this.kill();\r\n        }\r\n    \r\n        return 1; \r\n    }\r\n\r\n    collideWithTile(data, pos)\r\n    {\r\n        if (data <= 0)\r\n            return 0;\r\n            \r\n        const destroyTileChance = data == tileType_glass ? 1 : data == tileType_dirt ? .2 : .05;\r\n        rand() < destroyTileChance && destroyTile(pos);\r\n        this.kill();\r\n\r\n        return 1; \r\n    }\r\n\r\n    kill()\r\n    {\r\n        if (this.destroyed)\r\n            return;\r\n\r\n        const emitter = new ParticleEmitter(\r\n            this.pos, 0, .1, 100, .5, // pos, emitSize, emitTime, emitRate, emiteCone\r\n            undefined, undefined,     // tileIndex, tileSize\r\n            new Color(1,1,0), new Color(1,0,0), // colorStartA, colorStartB\r\n            new Color(1,1,0), new Color(1,0,0), // colorEndA, colorEndB\r\n            .2, .2, 0, .1, .1, // particleTime, sizeStart, sizeEnd, particleSpeed, particleAngleSpeed\r\n            1, 1, .5, PI, .1,  // damping, angleDamping, gravityScale, particleCone, fadeRate, \r\n            .5, 1, 1           // randomness, collide, additive, randomColorLinear, renderOrder\r\n        );\r\n        emitter.trailScale = 1;\r\n        emitter.angle = this.lastVelocity.angle() + PI;\r\n        emitter.elasticity = .3;\r\n\r\n        this.destroy();\r\n    }\r\n\r\n    render()\r\n    {\r\n        drawRect(this.pos, vec2(.4,.5), new Color(1,1,1,.5), this.velocity.angle());\r\n        drawRect(this.pos, vec2(.2,.5), this.color, this.velocity.angle());\r\n    }\r\n}"
  },
  {
    "path": "engine/build/build.bat",
    "content": "rem SIMPLE BUILD SCRIPT FOR JS13k by FRANK FORCE\nrem minfies and combines index.html and index.js and zips the result\n\nset name=app\n\nrem go to top of project\ncd ..\ncd ..\n\nrem remove old files\ndel %name%.zip index.min.html\nrmdir /s /q build\n\nrem combine code\nmkdir build\ntype engine\\engineUtil.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\build\\engineBuild.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\engine.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\engineAudio.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\engineObject.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\engineTileLayer.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\engineInput.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\engineParticle.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\engineWebGL.js >> build\\index.js\necho.>> build\\index.js\ntype engine\\engineDraw.js >> build\\index.js\necho.>> build\\index.js\n\nrem add app files to include here\ntype appObjects.js >> build\\index.js\necho.>> build\\index.js\ntype appCharacters.js >> build\\index.js\necho.>> build\\index.js\ntype appEffects.js >> build\\index.js\necho.>> build\\index.js\ntype appLevel.js >> build\\index.js\necho.>> build\\index.js\ntype app.js >> build\\index.js\necho.>> build\\index.js\n\nrem minify code with closure\ncall google-closure-compiler --js build\\index.js --js_output_file build\\index.js --compilation_level ADVANCED --language_out ECMASCRIPT_2019 --warning_level VERBOSE --jscomp_off * --assume_function_wrapper\nif %ERRORLEVEL% NEQ 0 (\n    pause\n    exit /b %ERRORLEVEL%\n)\n\nrem more minification with uglify or terser (they both are about the same)\ncall uglifyjs -o build\\index.js --compress --mangle -- build\\index.js\nrem call terser -o build\\index.js --compress --mangle -- build\\index.js\nif %ERRORLEVEL% NEQ 0 (\n    pause\n    exit /b %ERRORLEVEL%\n)\n\nrem roadroaller compresses the code better then zip\ncall roadroller build\\index.js -o build\\index.js\nif %ERRORLEVEL% NEQ 0 (\n    pause\n    exit /b %ERRORLEVEL%\n)\n\nrem build the html\ntype engine\\build\\index.html >> build\\index.html\necho ^<script^> >> build\\index.html\ntype build\\index.js >> build\\index.html\necho ^</script^> >> build\\index.html\n\nrem minify the png\ncall imagemin tiles.png > build\\tiles.png\nif %ERRORLEVEL% NEQ 0 (\n    pause\n    exit /b %ERRORLEVEL%\n)\n\nrem zip the result\ncd build\nrem call advzip -a -4 -i 99 ..\\%name%.zip index.html\ncall ..\\ect -9 -strip -zip ..\\%name%.zip index.html\nif %ERRORLEVEL% NEQ 0 (\n    pause\n    exit /b %ERRORLEVEL%\n)\n\nrem remove build folder\ncopy index.html ..\\index.min.html\ncd ..\nrmdir /s /q build\n\nrem pause to see result        ect -9 -strip -zip js13k.zip index.html"
  },
  {
    "path": "engine/build/build.html",
    "content": "<body>"
  },
  {
    "path": "engine/build/engineBuild.js",
    "content": "/*\n    LittleJS - Build include file\n    By Frank Force 2021\n\n    This file is automatically included first by the build system.\n*/\n\n\n'use strict';\n\nconst debug = 0;\nconst showWatermark = 0;\nconst godMode = 0;\nconst debugOverlay = 0;\nconst debugPhysics = 0;\nconst debugParticles = 0;\n\n// allow debug commands to be removed from the final build\nconst ASSERT      = ()=> {}\nconst debugPoint  = ()=> {}\nconst debugRect   = ()=> {}\nconst debugLine   = ()=> {}\nconst debugInit   = ()=> {}\nconst debugUpdate = ()=> {}\nconst debugRender = ()=> {}"
  },
  {
    "path": "engine/build/index.html",
    "content": "<body>"
  },
  {
    "path": "engine/build/setupBuild.bat",
    "content": "rem install these command line tools if necessary\nnpm install -g google-closure-compiler\nnpm install -g terser\nnpm install -g uglify\nnpm install -g roadroller\nnpm install --global imagemin-cli\nnpm install -g advzip-bin"
  },
  {
    "path": "engine/engine.js",
    "content": "/*\r\n    LittleJS - The Little JavaScript Game Engine That Can - By Frank Force 2021\r\n\r\n    Engine Features\r\n    - Engine and debug system are separate from game code\r\n    - Object oriented with base class engine object\r\n    - Engine handles core update loop\r\n    - Base class object handles update, physics, collision, rendering, etc\r\n    - Engine helper classes and functions like Vector2, Color, and Timer\r\n    - Super fast rendering system for tile sheets\r\n    - Sound effects audio with zzfx and music with zzfxm\r\n    - Input processing system with gamepad and touchscreen support\r\n    - Tile layer rendering and collision system\r\n    - Particle effect system\r\n    - Automatically calls appInit(), appUpdate(), appUpdatePost(), appRender(), appRenderPost()\r\n    - Debug tools and debug rendering system\r\n    - Call engineInit() to start it up!\r\n*/\r\n\r\n'use strict';\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// engine config\r\n\r\nconst engineName = 'LittleJS';\r\nconst engineVersion = 'v0.74';\r\nconst FPS = 60, timeDelta = 1/FPS;\r\nconst defaultFont = 'arial'; // font used for text rendering\r\nconst maxWidth = 1920, maxHeight = 1200; // up to 1080p and 16:10\r\nconst fixedWidth = 0; // native resolution\r\n//const fixedWidth = 1280, fixedHeight = 720; // 720p\r\n//const fixedWidth = 128,  fixedHeight = 128; // PICO-8\r\n//const fixedWidth = 240,  fixedHeight = 136; // TIC-80\r\n\r\n// tile sheet settings\r\n//const defaultTilesFilename = 'a.png'; // everything goes in one tile sheet\r\nconst defaultTileSize = vec2(16); // default size of tiles in pixels\r\nconst tileBleedShrinkFix = .3;    // prevent tile bleeding from neighbors\r\nconst pixelated = 1;              // use crisp pixels for pixel art\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// core engine\r\n\r\nconst gravity = -.01;\r\nlet mainCanvas=0, mainContext=0, mainCanvasSize=vec2();\r\nlet engineObjects=[], engineCollideObjects=[];\r\nlet frame=0, time=0, realTime=0, paused=0, frameTimeLastMS=0, frameTimeBufferMS=0, debugFPS=0;\r\nlet cameraPos=vec2(), cameraScale=4*max(defaultTileSize.x, defaultTileSize.y);\r\nlet tileImageSize, tileImageSizeInverse, shrinkTilesX, shrinkTilesY, drawCount;\r\n\r\nconst tileImage = new Image(); // the tile image used by everything\r\nfunction engineInit(appInit, appUpdate, appUpdatePost, appRender, appRenderPost)\r\n{\r\n    // init engine when tiles load\r\n    tileImage.onload = ()=>\r\n    {\r\n        // save tile image info\r\n        tileImageSizeInverse = vec2(1).divide(tileImageSize = vec2(tileImage.width, tileImage.height));\r\n        debug && (tileImage.onload=()=>ASSERT(1)); // tile sheet can not reloaded\r\n        shrinkTilesX = tileBleedShrinkFix/tileImageSize.x;\r\n        shrinkTilesY = tileBleedShrinkFix/tileImageSize.y;\r\n\r\n        // setup html\r\n        document.body.appendChild(mainCanvas = document.createElement('canvas'));\r\n        document.body.style = 'margin:0;overflow:hidden;background:#000';\r\n        mainCanvas.style = 'position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);image-rendering:crisp-edges;image-rendering:pixelated';          // pixelated rendering\r\n        mainContext = mainCanvas.getContext('2d');\r\n\r\n        debugInit();\r\n        glInit();\r\n        appInit();\r\n        engineUpdate();\r\n    };\r\n\r\n    // main update loop\r\n    const engineUpdate = (frameTimeMS=0)=>\r\n    {\r\n        requestAnimationFrame(engineUpdate);\r\n        \r\n        if (!document.hasFocus())\r\n            inputData[0].length = 0; // clear input when lost focus\r\n\r\n        // prepare to update time\r\n        const realFrameTimeDeltaMS = frameTimeMS - frameTimeLastMS;\r\n        let frameTimeDeltaMS = realFrameTimeDeltaMS;\r\n        frameTimeLastMS = frameTimeMS;\r\n        realTime = frameTimeMS / 1e3;\r\n        if (debug)\r\n            frameTimeDeltaMS *= keyIsDown(107) ? 5 : keyIsDown(109) ? .2 : 1;\r\n        if (!paused)\r\n            frameTimeBufferMS += frameTimeDeltaMS;\r\n\r\n        // update frame\r\n        mousePosWorld = screenToWorld(mousePosScreen);\r\n        updateGamepads();\r\n\r\n        // apply time delta smoothing, improves smoothness of framerate in some browsers\r\n        let deltaSmooth = 0;\r\n        if (frameTimeBufferMS < 0 && frameTimeBufferMS > -9)\r\n        {\r\n            // force an update each frame if time is close enough (not just a fast refresh rate)\r\n            deltaSmooth = frameTimeBufferMS;\r\n            frameTimeBufferMS = 0;\r\n            //debug && frameTimeBufferMS < 0 && console.log('time smoothing: ' + -deltaSmooth);\r\n        }\r\n        //debug && frameTimeBufferMS < 0 && console.log('skipped frame! ' + -frameTimeBufferMS);\r\n\r\n        // clamp incase of extra long frames (slow framerate)\r\n        frameTimeBufferMS = min(frameTimeBufferMS, 50);\r\n        \r\n        // update the frame\r\n        for (;frameTimeBufferMS >= 0; frameTimeBufferMS -= 1e3 / FPS)\r\n        {\r\n            // main frame update\r\n            appUpdate();\r\n            engineUpdateObjects();\r\n            appUpdatePost();\r\n            debugUpdate();\r\n\r\n            // update input\r\n            for(let deviceInputData of inputData)\r\n                deviceInputData.map(k=> k.r = k.p = 0);\r\n            mouseWheel = 0;\r\n        }\r\n\r\n        // add the smoothing back in\r\n        frameTimeBufferMS += deltaSmooth;\r\n\r\n        if (fixedWidth)\r\n        {\r\n            // clear and fill window if smaller\r\n            mainCanvas.width = fixedWidth;\r\n            mainCanvas.height = fixedHeight;\r\n            \r\n            // fit to window width if smaller\r\n            const fixedAspect = fixedWidth / fixedHeight;\r\n            const aspect = innerWidth / innerHeight;\r\n            mainCanvas.style.width = aspect < fixedAspect ? '100%' : '';\r\n            mainCanvas.style.height = aspect < fixedAspect ? '' : '100%';\r\n        }\r\n        else\r\n        {\r\n            // fill the window\r\n            mainCanvas.width = min(innerWidth, maxWidth);\r\n            mainCanvas.height = min(innerHeight, maxHeight);\r\n        }\r\n\r\n        // save canvas size\r\n        mainCanvasSize = vec2(mainCanvas.width, mainCanvas.height);\r\n        mainContext.imageSmoothingEnabled = !pixelated; // disable smoothing for pixel art\r\n\r\n        // render sort then render while removing destroyed objects\r\n        glPreRender(mainCanvas.width, mainCanvas.height);\r\n        appRender();\r\n        engineObjects.sort((a,b)=> a.renderOrder - b.renderOrder);\r\n        for(const o of engineObjects)\r\n            o.destroyed || o.render();\r\n        glCopyToContext(mainContext);\r\n        appRenderPost();\r\n        debugRender();\r\n\r\n        if (showWatermark)\r\n        {\r\n            // update fps\r\n            debugFPS = lerp(.05, 1e3/(realFrameTimeDeltaMS||1), debugFPS);\r\n            mainContext.textAlign = 'right';\r\n            mainContext.textBaseline = 'top';\r\n            mainContext.font = '1em monospace';\r\n            mainContext.fillStyle = '#000';\r\n            const text = engineName + ' ' + engineVersion + ' / ' \r\n                + drawCount + ' / ' + engineObjects.length + ' / ' + debugFPS.toFixed(1);\r\n            mainContext.fillText(text, mainCanvas.width-3, 3);\r\n            mainContext.fillStyle = '#fff';\r\n            mainContext.fillText(text, mainCanvas.width-2,2);\r\n            drawCount = 0;\r\n        }\r\n\r\n        // copy anything left in the buffer if necessary\r\n        glCopyToContext(mainContext);\r\n    }\r\n\r\n    //tileImage.src = 'tiles.png';\r\n    tileImage.src = \r\n`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAABABAMAAAAg+GJMAAAAJ1BMVEUAAAD///+AgID/AAAAAACJT6T/dwBIG11mlD2i91azs7PZ2dlAQEA9UPniAAAAAXRSTlMAQObYZgAAAoRJREFUeNqsk8dZw0AQhWfNiHDbARfgVAB0sNI3LTgcfSLcbasC0o0j6panHIYMT+FX+p8y/UdECJnNJlTn6PJnft4wEvHFasCkis2JakItl9dpemjZxgniywInnhX2hWAxXug0NIwKcduwjRTpF8hVLp7PJDSEuE5X24ofFZAQV7cAEZtDQ4jLJcSKgzuAXD8DDuVDdGOFmWjNaPN0v1zdPtU0BTSIi8cQY60ZPWcQ715r2oIzeqFupBQbZqVY0xY8PT1RN6zIh7QP8TTL+lcwmiE1megkRagif1DgvB8WsAILbQpYgZ2aD8kWsGLMUSybdfMpm1tgDRiJzfr7P5MteGufDpXchoE4jGcKj32C2oBKsM5jlPUlT4VKyN9TdFuSwKsfqrLHTcE5ucQgKL8H+GZW2n0YZptZKUXSXhIUic4nfa4OXrPPNmXTxI8BwzCBFcP6DjGxfwFmmwIwBv548/sccBJqPGRK10uYu5YCtRkD/r3xc8AEELDOk6ZAn3OHXR7h19D8OAckE3ukFiAkyb7V+lPXAqecd/8DYCSAkAGK+r37W3fhDZYCQqg4ICS/HKjNQsACbuYYRHLmHLh1BFfRHikKevd0dwATAQzTW3Dv7n8DKCrsZSF51wLh2hssfCOGQTLoegvZrn/j0iIlVEyKLSDjk0VaWGVjZERCQpHLqwywcEzIlbCChLArx1SbpQBgjITB5+f88l6bw+tLnbzW2eZWJQGEOMwKk3hz4JQnuy8FIH4tw+T2QNkNzSmeA0eA7T0BgFMc8mQox9qsCiQIY+AwDO/bNSOk4zaMIxxyvi8AMAW2xwcH1o+w/hHXf+P6RVq/yo86pjXn/PT09LTsL3dlHSBbTLmdAAAAAElFTkSuQmCC`;\r\n}\r\n\r\nfunction engineUpdateObjects()\r\n{\r\n    // recursive object update\r\n    const updateObject = (o)=>\r\n    {\r\n        if (!o.destroyed)\r\n        {\r\n            o.update();\r\n            for(const child of o.children)\r\n                updateObject(child);\r\n        }\r\n    }\r\n    for(const o of engineObjects)\r\n        o.parent || updateObject(o);\r\n    engineObjects = engineObjects.filter(o=>!o.destroyed);\r\n    engineCollideObjects = engineCollideObjects.filter(o=>!o.destroyed);\r\n    time = ++frame / FPS;\r\n}\r\n\r\nfunction forEachObject(pos, size=0, callbackFunction=(o)=>1, collideObjectsOnly=1)\r\n{\r\n    const objectList = collideObjectsOnly ? engineCollideObjects : engineObjects;\r\n    if (!size)\r\n    {\r\n        // no overlap test\r\n        for (const o of objectList)\r\n            callbackFunction(o);\r\n    }\r\n    else if (size.x != undefined)\r\n    {\r\n        // aabb test\r\n        for (const o of objectList)\r\n            isOverlapping(pos, size, o.pos, o.size) && callbackFunction(o);\r\n    }\r\n    else\r\n    {\r\n        // circle test\r\n        const sizeSquared = size**2;\r\n        for (const o of objectList)\r\n            pos.distanceSquared(o.pos) < sizeSquared && callbackFunction(o);\r\n    }\r\n}"
  },
  {
    "path": "engine/engineAudio.js",
    "content": "/*\r\n    LittleJS Audio System\r\n    - Speech Synthesis\r\n    - ZzFX Sound Effects\r\n    - ZzFXM Music\r\n    - Can attenuate zzfx sounds by camera range\r\n*/\r\n\r\n'use strict';\r\n\r\nconst soundEnable = 1;       // all audio can be disabled\r\nconst defaultSoundRange = 15;// distance where taper starts\r\nconst soundTaperPecent = .5; // extra range added for sound taper\r\nconst audioVolume = .5;        // volume for sound, music and speech\r\nlet audioContext;            // main audio context\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n// play a zzfx sound in world space with attenuation and culling\r\nfunction playSound(zzfxSound, pos, range=defaultSoundRange, volumeScale=1)\r\n{\r\n    if (!soundEnable) return;\r\n\r\n    const lengthSquared = cameraPos.distanceSquared(pos);\r\n    const maxRange = range * (soundTaperPecent + 1);\r\n    if (lengthSquared > maxRange**2)\r\n        return;\r\n\r\n    // copy sound (so volume scale isnt permanant)\r\n    zzfxSound = [...zzfxSound];\r\n\r\n    // scale volume\r\n    const scale = volumeScale * percent(lengthSquared**.5, range, maxRange);\r\n    zzfxSound[0] = (zzfxSound[0]||1) * scale;\r\n    zzfx(...zzfxSound);\r\n}\r\n\r\n// render and play zzfxm music with an option to loop\r\nfunction playMusic(zzfxmMusic, loop=1) \r\n{\r\n    if (!soundEnable) return;\r\n\r\n    const source = zzfxP(...zzfxM(...zzfxmMusic));\r\n    source && (source.loop = loop);\r\n    return source;\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// speak text with passed in settings\r\nfunction speak(text, language='', volume=1, rate=1, pitch=1)\r\n{\r\n    if (!soundEnable || !speechSynthesis) return;\r\n\r\n    // common languages (not supported by all browsers)\r\n    // en - english,  it - italian, fr - french,  de - german, es - spanish\r\n    // ja - japanese, ru - russian, zh - chinese, hi - hindi,  ko - korean\r\n\r\n    // build utterance and speak\r\n    const utterance = new SpeechSynthesisUtterance(text);\r\n    utterance.lang = language;\r\n    utterance.volume = volume*audioVolume*3;\r\n    utterance.rate = rate;\r\n    utterance.pitch = pitch;\r\n    speechSynthesis.speak(utterance);\r\n}\r\n\r\nconst stopSpeech = ()=> speechSynthesis && speechSynthesis.cancel();\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// ZzFXMicro - Zuper Zmall Zound Zynth - v1.1.8 by Frank Force\r\n\r\nconst zzfxR = 44100; // sample rate\r\nfunction zzfx(\r\n    // parameters\r\n    volume = 1, randomness = .05, frequency = 220, attack = 0, sustain = 0,\r\n    release = .1, shape = 0, shapeCurve = 1, slide = 0, deltaSlide = 0,\r\n    pitchJump = 0, pitchJumpTime = 0, repeatTime = 0, noise = 0, modulation = 0,\r\n    bitCrush = 0, delay = 0, sustainVolume = 1, decay = 0, tremolo = 0\r\n)\r\n{\r\n    // wait for user input to create audio context\r\n    if (!soundEnable || !hadInput) return;\r\n\r\n    // init parameters\r\n    let PI2 = PI*2, sign = v => v>0?1:-1,\r\n        startSlide = slide *= 500 * PI2 / zzfxR / zzfxR, b=[],\r\n        startFrequency = frequency *= (1 + randomness*2*Math.random() - randomness) * PI2 / zzfxR,\r\n        t=0, tm=0, i=0, j=1, r=0, c=0, s=0, f, length;\r\n        \r\n    // scale by sample rate\r\n    attack = attack * zzfxR + 9; // minimum attack to prevent pop\r\n    decay *= zzfxR;\r\n    sustain *= zzfxR;\r\n    release *= zzfxR;\r\n    delay *= zzfxR;\r\n    deltaSlide *= 500 * PI2 / zzfxR**3;\r\n    modulation *= PI2 / zzfxR;\r\n    pitchJump *= PI2 / zzfxR;\r\n    pitchJumpTime *= zzfxR;\r\n    repeatTime = repeatTime * zzfxR | 0;\r\n\r\n    // generate waveform\r\n    for(length = attack + decay + sustain + release + delay | 0;\r\n        i < length; b[i++] = s)\r\n    {\r\n        if (!(++c%(bitCrush*100|0)))                      // bit crush\r\n        {\r\n            s = shape? shape>1? shape>2? shape>3?         // wave shape\r\n                Math.sin((t%PI2)**3) :                    // 4 noise\r\n                Math.max(Math.min(Math.tan(t),1),-1):     // 3 tan\r\n                1-(2*t/PI2%2+2)%2:                        // 2 saw\r\n                1-4*abs(Math.round(t/PI2)-t/PI2):    // 1 triangle\r\n                Math.sin(t);                              // 0 sin\r\n                \r\n            s = (repeatTime ?\r\n                    1 - tremolo + tremolo*Math.sin(PI2*i/repeatTime) // tremolo\r\n                    : 1) *\r\n                sign(s)*(abs(s)**shapeCurve) *       // curve 0=square, 2=pointy\r\n                volume * audioVolume * (                  // envelope\r\n                i < attack ? i/attack :                   // attack\r\n                i < attack + decay ?                      // decay\r\n                1-((i-attack)/decay)*(1-sustainVolume) :  // decay falloff\r\n                i < attack  + decay + sustain ?           // sustain\r\n                sustainVolume :                           // sustain volume\r\n                i < length - delay ?                      // release\r\n                (length - i - delay)/release *            // release falloff\r\n                sustainVolume :                           // release volume\r\n                0);                                       // post release\r\n \r\n            s = delay ? s/2 + (delay > i ? 0 :            // delay\r\n                (i<length-delay? 1 : (length-i)/delay) *  // release delay \r\n                b[i-delay|0]/2) : s;                      // sample delay\r\n        }\r\n\r\n        f = (frequency += slide += deltaSlide) *          // frequency\r\n            Math.cos(modulation*tm++);                    // modulation\r\n        t += f - f*noise*(1 - (Math.sin(i)+1)*1e9%2);     // noise\r\n\r\n        if (j && ++j > pitchJumpTime)       // pitch jump\r\n        {\r\n            frequency += pitchJump;         // apply pitch jump\r\n            startFrequency += pitchJump;    // also apply to start\r\n            j = 0;                          // reset pitch jump time\r\n        }\r\n\r\n        if (repeatTime && !(++r % repeatTime)) // repeat\r\n        {\r\n            frequency = startFrequency;     // reset frequency\r\n            slide = startSlide;             // reset slide\r\n            j = j || 1;                     // reset pitch jump time\r\n        }\r\n    }\r\n    \r\n    // create audio context\r\n    if (!audioContext)\r\n        audioContext = new (window.AudioContext||webkitAudioContext);\r\n\r\n    // create buffer and source\r\n    const buffer = audioContext.createBuffer(1, b.length, zzfxR), \r\n        source = audioContext.createBufferSource();\r\n\r\n    // copy samples to buffer and play\r\n    buffer.getChannelData(0).set(b);\r\n    source.buffer = buffer;\r\n    source.connect(audioContext.destination);\r\n    source.start();\r\n    return source;\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// ZzFX Music Renderer v2.0.3 by Keith Clark and Frank Force\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// ZzFX Music Renderer v2.0.3 by Keith Clark and Frank Force\r\n\r\nfunction zzfxM(instruments, patterns, sequence, BPM = 125) \r\n{\r\n    if (!soundEnable) return;\r\n    let instrumentParameters;\r\n    let i;\r\n    let j;\r\n    let k;\r\n    let note;\r\n    let sample;\r\n    let patternChannel;\r\n    let notFirstBeat;\r\n    let stop;\r\n    let instrument;\r\n    let pitch;\r\n    let attenuation;\r\n    let outSampleOffset;\r\n    let isSequenceEnd;\r\n    let sampleOffset = 0;\r\n    let nextSampleOffset;\r\n    let sampleBuffer = [];\r\n    let leftChannelBuffer = [];\r\n    let rightChannelBuffer = [];\r\n    let channelIndex = 0;\r\n    let panning = 0;\r\n    let hasMore = 1;\r\n    let sampleCache = {};\r\n    let beatLength = zzfxR / BPM * 60 >> 2;\r\n\r\n    // for each channel in order until there are no more\r\n    for(; hasMore; channelIndex++) {\r\n\r\n        // reset current values\r\n        sampleBuffer = [hasMore = notFirstBeat = pitch = outSampleOffset = 0];\r\n\r\n        // for each pattern in sequence\r\n        sequence.map((patternIndex, sequenceIndex) => {\r\n            // get pattern for current channel, use empty 1 note pattern if none found\r\n            patternChannel = patterns[patternIndex][channelIndex] || [0, 0, 0];\r\n\r\n            // check if there are more channels\r\n            hasMore |= !!patterns[patternIndex][channelIndex];\r\n\r\n            // get next offset, use the length of first channel\r\n            nextSampleOffset = outSampleOffset + (patterns[patternIndex][0].length - 2 - !notFirstBeat) * beatLength;\r\n            // for each beat in pattern, plus one extra if end of sequence\r\n            isSequenceEnd = sequenceIndex == sequence.length - 1;\r\n            for (i = 2, k = outSampleOffset; i < patternChannel.length + isSequenceEnd; notFirstBeat = ++i) {\r\n\r\n                // <channel-note>\r\n                note = patternChannel[i];\r\n\r\n                // stop if end, different instrument or new note\r\n                stop = i == patternChannel.length + isSequenceEnd - 1 && isSequenceEnd ||\r\n                        instrument != (patternChannel[0] || 0) | note | 0;\r\n\r\n                // fill buffer with samples for previous beat, most cpu intensive part\r\n                for (j = 0; j < beatLength && notFirstBeat;\r\n\r\n                        // fade off attenuation at end of beat if stopping note, prevents clicking\r\n                        j++ > beatLength - 99 && stop ? attenuation += (attenuation < 1) / 99 : 0\r\n                ) {\r\n                    // copy sample to stereo buffers with panning\r\n                    sample = (1 - attenuation) * sampleBuffer[sampleOffset++] / 2 || 0;\r\n                    leftChannelBuffer[k] = (leftChannelBuffer[k] || 0) - sample * panning + sample;\r\n                    rightChannelBuffer[k] = (rightChannelBuffer[k++] || 0) + sample * panning + sample;\r\n                }\r\n\r\n                // set up for next note\r\n                if (note) {\r\n                    // set attenuation\r\n                    attenuation = note % 1;\r\n                    panning = patternChannel[1] || 0;\r\n                    if (note |= 0) {\r\n                        // get cached sample\r\n                        sampleBuffer = sampleCache[\r\n                            [\r\n                                instrument = patternChannel[sampleOffset = 0] || 0,\r\n                                note\r\n                            ]\r\n                        ] = sampleCache[[instrument, note]] || (\r\n                                // add sample to cache\r\n                                instrumentParameters = [...instruments[instrument]],\r\n                                instrumentParameters[2] *= 2 ** ((note - 12) / 12),\r\n\r\n                                // allow negative values to stop notes\r\n                                note > 0 ? zzfxG(...instrumentParameters) : []\r\n                        );\r\n                    }\r\n                }\r\n            }\r\n\r\n            // update the sample offset\r\n            outSampleOffset = nextSampleOffset;\r\n        });\r\n    }\r\n\r\n    return [leftChannelBuffer, rightChannelBuffer];\r\n}"
  },
  {
    "path": "engine/engineDebug.js",
    "content": "/*\n    LittleJS Debug System\n    \n    Debug Features\n    - debug console\n    - debug rendering\n    - debug controls\n    - save snapshot\n*/\n\n'use strict';\n\nconst debug = 1;\nconst enableAsserts = 1;\nconst debugPointSize = .5;\n\nlet showWatermark = 1;\nlet godMode = 0;\nlet debugRects = [];\nlet debugOverlay = 0;\nlet debugPhysics = 0;\nlet debugParticles = 0;\nlet debugCanvas = -1;\nlet debugTakeScreenshot;\nlet downloadLink;\n\n// debug helper functions\nconst ASSERT = enableAsserts ? (...assert)=> console.assert(...assert) : ()=>{};\nconst debugRect = (pos, size=0, color='#fff', time=0, angle=0, fill=0)=> \n{\n    ASSERT(typeof color == 'string'); // pass in regular html strings as colors\n    debugRects.push({pos, size, color, time:new Timer(time), angle, fill});\n}\nconst debugCircle = (pos, radius, color, time, fill=0)=> debugRect(pos, radius, color, time, fill);\nconst debugPoint = (pos, color, time, angle)=> debugRect(pos, 0, color, time, angle);\nconst debugLine = (posA, posB, color, thickness=.1, time)=>\n{\n    const halfDelta = vec2((posB.x - posA.x)*.5, (posB.y - posA.y)*.5);\n    const size = vec2(thickness, halfDelta.length()*2);\n    debugRect(posA.add(halfDelta), size, color, time, halfDelta.angle(), 1);\n}\n\nconst debugSaveCanvas = (canvas, filename = engineName + '.png') =>\n{\n    downloadLink.download = \"screenshot.png\";\n    downloadLink.href = canvas.toDataURL('image/png').replace('image/png','image/octet-stream');\n    downloadLink.click();\n}\nconst debugAABB = (pA, pB, sA, sB, color)=>\n{\n    const minPos = vec2(min(pA.x - sA.x/2, pB.x - sB.x/2), min(pA.y - sA.y/2, pB.y - sB.y/2));\n    const maxPos = vec2(max(pA.x + sA.x/2, pB.x + sB.x/2), max(pA.y + sA.y/2, pB.y + sB.y/2));\n    debugRect(minPos.lerp(maxPos,.5), maxPos.subtract(minPos), color);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// engine debug function (called automatically)\n\nconst debugInit = ()=>\n{\n    // create link for saving screenshots\n    document.body.appendChild(downloadLink = document.createElement('a'));\n    downloadLink.style.display = 'none';\n}\n\nconst debugUpdate = ()=>\n{\n    if (!debug)\n        return;\n        \n    if (keyWasPressed(192)) // ~\n    {\n        debugOverlay = !debugOverlay;\n    }\n    if (keyWasPressed(49)) // 1\n    {\n        debugPhysics = !debugPhysics;\n        debugParticles = 0;\n    }\n    if (keyWasPressed(50)) // 2\n    {\n        debugParticles = !debugParticles;\n        debugPhysics = 0;\n    }\n    if (keyWasPressed(51)) // 3\n    {\n        godMode = !godMode;\n    }\n        \n    if (keyWasPressed(53)) // 5\n    {\n        debugTakeScreenshot = 1;\n    }\n    if (keyWasPressed(54)) // 6\n    {\n        //debugToggleParticleEditor();\n        //debugPhysics = debugParticles = 0;\n    }\n    if (keyWasPressed(55)) // 7\n    {\n    }\n    if (keyWasPressed(56)) // 8\n    {\n    }\n    if (keyWasPressed(57)) // 9\n    {\n    }\n    if (keyWasPressed(48)) // 0\n    {\n        showWatermark = !showWatermark;\n    }\n\n    // asserts to check for things that could go wrong\n    ASSERT(gravity <= 0) // only supports downward gravity\n}\n\nconst debugRender = ()=>\n{\n    if (debugTakeScreenshot)\n    {\n        debugSaveCanvas(mainCanvas);\n        debugTakeScreenshot = 0;\n    }\n\n    if (debugOverlay)\n    {\n        for(const o of engineObjects)\n        {\n            if (o.canvas)\n                continue; // skip tile layers\n\n            const size = o.size.copy();\n            size.x = max(size.x, .2);\n            size.y = max(size.y, .2);\n\n            const color = new Color(\n                o.collideTiles?1:0, \n                o.collideSolidObjects?1:0,\n                o.isSolid?1:0, \n                o.parent ? .2 : .5);\n\n            // show object info\n            drawRect(o.pos, size, color);\n            drawRect(o.pos, size.scale(.8), o.parent ? new Color(1,1,1,.5) : new Color(0,0,0,.8));\n            o.parent && drawLine(o.pos, o.parent.pos, .1, new Color(0,0,1,.5));\n        }\n\n        // mouse pick\n        let bestDistance = Infinity, bestObject;\n        for(const o of engineObjects)\n        {\n            const distance = mousePosWorld.distanceSquared(o.pos);\n            if (distance < bestDistance)\n            {\n                bestDistance = distance;\n                bestObject = o\n            }\n        }\n        \n        if (bestObject)\n        {\n            const raycastHitPos = tileCollisionRaycast(bestObject.pos, mousePosWorld);\n            raycastHitPos && drawRect(raycastHitPos.int().add(vec2(.5)), vec2(1), new Color(0,1,1,.3));\n            drawRect(mousePosWorld.int().add(vec2(.5)), vec2(1), new Color(0,0,1,.5));\n            drawLine(mousePosWorld, bestObject.pos, .1, !raycastHitPos ? new Color(0,1,0,.5) : new Color(1,0,0,.5));\n\n            let pos = mousePosWorld.copy(), height = vec2(0,.5);\n            const printVec2 = (v)=> '(' + (v.x>0?' ':'') + (v.x).toFixed(2) + ',' + (v.y>0?' ':'')  + (v.y).toFixed(2) + ')';\n            const args = [.5, new Color, .05, undefined, undefined, 'monospace'];\n\n            drawText('pos = ' + printVec2(bestObject.pos) \n                + (bestObject.angle>0?'  ':' ') + (bestObject.angle*180/PI).toFixed(1) + '°', \n                pos = pos.add(height), ...args);\n            drawText('vel = ' + printVec2(bestObject.velocity), pos = pos.add(height), ...args);\n            drawText('size = ' + printVec2(bestObject.size), pos = pos.add(height), ...args);\n            drawText('collision = ' + getTileCollisionData(mousePosWorld), pos = mousePosWorld.subtract(height), ...args);\n        }\n\n        glCopyToContext(mainContext);\n    }\n\n    {\n        // render debug rects\n        mainContext.lineWidth = 1;\n        const pointSize = debugPointSize * cameraScale;\n        debugRects.forEach(r=>\n        {\n            // create canvas transform from world space to screen space\n            const pos = worldToScreen(r.pos);\n            \n            mainContext.save();\n            mainContext.lineWidth = 2;\n            mainContext.translate(pos.x|0, pos.y|0);\n            mainContext.rotate(r.angle);\n            mainContext.fillStyle = mainContext.strokeStyle = r.color;\n\n            if (r.size == 0 || r.size.x === 0 && r.size.y === 0 )\n            {\n                // point\n                mainContext.fillRect(-pointSize/2, -1, pointSize, 3), \n                mainContext.fillRect(-1, -pointSize/2, 3, pointSize);\n            }\n            else if (r.size.x != undefined)\n            {\n                // rect\n                const w = r.size.x*cameraScale|0, h = r.size.y*cameraScale|0;\n                r.fill && mainContext.fillRect(-w/2|0, -h/2|0, w, h),\n                mainContext.strokeRect(-w/2|0, -h/2|0, w, h);\n            }\n            else\n            {\n                // circle\n                mainContext.beginPath();\n                mainContext.arc(0, 0, r.size*cameraScale, 0, 9);\n                r.fill && mainContext.fill();\n                mainContext.stroke();\n            }\n\n            mainContext.restore();\n        });\n\n        mainContext.fillStyle = mainContext.strokeStyle = '#fff';\n    }\n\n    {\n        let x = 9, y = -20, h = 30;\n        mainContext.fillStyle = '#fff';\n        mainContext.textAlign = 'left';\n        mainContext.textBaseline = 'top';\n        mainContext.font = '28px monospace';\n        mainContext.shadowColor = '#000';\n        mainContext.shadowBlur = 9;\n\n        if (debugOverlay)\n        {\n            mainContext.fillText(engineName, x, y += h);\n            mainContext.fillText('Objects: ' + engineObjects.length, x, y += h);\n            mainContext.fillText('Time: ' + formatTime(time), x, y += h);\n            mainContext.fillText('---------', x, y += h);\n            mainContext.fillStyle = '#f00';\n            mainContext.fillText('~: Debug Overlay', x, y += h);\n            mainContext.fillStyle = debugPhysics ? '#f00' : '#fff';\n            mainContext.fillText('1: Debug Physics', x, y += h);\n            mainContext.fillStyle = debugParticles ? '#f00' : '#fff';\n            mainContext.fillText('2: Debug Particles', x, y += h);\n            mainContext.fillStyle = godMode ? '#f00' : '#fff';\n            mainContext.fillText('3: God Mode', x, y += h);\n            mainContext.fillStyle = '#fff';\n            mainContext.fillText('5: Save Screenshot', x, y += h);\n            //mainContext.fillStyle = debugParticleEditor ? '#f00' : '#fff';\n            //mainContext.fillText('6: Particle Editor', x, y += h);\n        }\n        else\n        {\n            mainContext.fillText(debugPhysics ? 'Debug Physics' : '', x, y += h);\n            mainContext.fillText(debugParticles ? 'Debug Particles' : '', x, y += h);\n            mainContext.fillText(godMode ? 'God Mode' : '', x, y += h);\n        }\n    \n        mainContext.shadowBlur = 0;\n    }\n\n    debugRects = debugRects.filter(r=>!r.time.elapsed());\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// particle system editor\nlet debugParticleEditor = 0, debugParticleSystem, debugParticleSystemDiv, particleSystemCode;\n\nconst debugToggleParticleEditor = ()=>\n{\n    debugParticleEditor = !debugParticleEditor;\n\n    if (debugParticleEditor)\n    {\n        if (!debugParticleSystem || debugParticleSystem.destroyed)\n            debugParticleSystem = new ParticleEmitter(cameraPos);\n    }\n    else if (debugParticleSystem && !debugParticleSystem.destroyed)\n        debugParticleSystem.destroy();\n\n\n    const colorToHex = (color)=>\n    {\n        const componentToHex = (c)=>\n        {\n            const hex = (c*255|0).toString(16);\n            return hex.length == 1 ? \"0\" + hex : hex;\n        }\n\n        return \"#\" + componentToHex(color.r) + componentToHex(color.g) + componentToHex(color.b);\n    }\n    const hexToColor = (hex)=>\n    {\n        return new Color(\n            parseInt(hex.substr(1,2), 16)/255,\n            parseInt(hex.substr(3,2), 16)/255,\n            parseInt(hex.substr(5,2), 16)/255)\n    }\n\n    if (!debugParticleSystemDiv)\n    {\n        const div = debugParticleSystemDiv = document.createElement('div');\n        div.innerHTML = '<big><b>Particle Editor';\n        div.style = 'position:absolute;top:10;left:10;color:#fff';\n        document.body.appendChild(div);\n\n        for( const setting of debugParticleSettings)\n        {\n            const input = setting[2] = document.createElement('input');\n            const name = setting[0];\n            const type = setting[1];\n            if (type)\n            {\n                if (type == 'color')\n                {\n                    input.type = type;\n                    const color = debugParticleSystem[name];\n                    input.value = colorToHex(color);\n                }\n                else if (type == 'alpha' && name == 'colorStartAlpha')\n                    input.value = debugParticleSystem.colorStartA.a;\n                else if (type == 'alpha' && name == 'colorEndAlpha')\n                    input.value = debugParticleSystem.colorEndA.a;\n                else if (name == 'tileSizeX')\n                    input.value = debugParticleSystem.tileSize.x;\n                else if (name == 'tileSizeY')\n                    input.value = debugParticleSystem.tileSize.y;\n            }\n            else\n                input.value = debugParticleSystem[name] || '0';\n\n            input.oninput = (e)=>\n            {\n                const inputFloat = parseFloat(input.value) || 0;\n                if (type)\n                {\n                    if (type == 'color')\n                    {\n                        const color = hexToColor(input.value);\n                        debugParticleSystem[name].r = color.r;\n                        debugParticleSystem[name].g = color.g;\n                        debugParticleSystem[name].b = color.b;\n                    }\n                    else if (type == 'alpha' && name == 'colorStartAlpha')\n                    {\n                        debugParticleSystem.colorStartA.a = clamp(inputFloat);\n                        debugParticleSystem.colorStartB.a = clamp(inputFloat);\n                    }\n                    else if (type == 'alpha' && name == 'colorEndAlpha')\n                    {\n                        debugParticleSystem.colorEndA.a = clamp(inputFloat);\n                        debugParticleSystem.colorEndB.a = clamp(inputFloat);\n                    }\n                    else if (name == 'tileSizeX')\n                    {\n                        debugParticleSystem.tileSize = vec2(parseInt(input.value), debugParticleSystem.tileSize.y);\n                    }\n                    else if (name == 'tileSizeY')\n                    {\n                        debugParticleSystem.tileSize.y = vec2(debugParticleSystem.tileSize.x, parseInt(input.value));\n                    }\n                }\n                else\n                    debugParticleSystem[name] = inputFloat;\n\n                updateCode();\n            }\n            div.appendChild(document.createElement('br'));\n            div.appendChild(input);\n            div.appendChild(document.createTextNode(' ' + name));\n        }\n\n        div.appendChild(document.createElement('br'));\n        div.appendChild(document.createElement('br'));\n        div.appendChild(particleSystemCode = document.createElement('input'));\n        particleSystemCode.disabled = true;\n        div.appendChild(document.createTextNode(' code'));\n\n        div.appendChild(document.createElement('br'));\n        const button = document.createElement('button')\n        div.appendChild(button);\n        button.innerHTML = 'Copy To Clipboard';\n        \n        button.onclick = (e)=> navigator.clipboard.writeText(particleSystemCode.value); \n\n        const updateCode = ()=>\n        {\n            let code = '';\n            let count = 0;\n            for( const setting of debugParticleSettings)\n            {\n                const name = setting[0];\n                const type = setting[1];\n                let value;\n                if (name == 'tileSizeX' || type == 'alpha')\n                    continue;\n\n                if (count++)\n                    code += ', ';\n\n                if (name == 'tileSizeY')\n                {\n                    value = `vec2(${debugParticleSystem.tileSize.x},${debugParticleSystem.tileSize.y})`;\n                }\n                else if (type == 'color')\n                {\n                    const c = debugParticleSystem[name];\n                    value = `new Color(${c.r},${c.g},${c.b},${c.a})`;\n                }\n                else\n                    value = debugParticleSystem[name];\n                code += value;\n            }\n\n            particleSystemCode.value = '...[' + code + ']';\n        }\n        updateCode();\n    }\n    debugParticleSystemDiv.style.display = debugParticleEditor ? '' : 'none'\n}\n\nconst debugParticleSettings = \n[\n    ['emitSize'],\n    ['emitTime'],\n    ['emitRate'],\n    ['emitConeAngle'],\n    ['tileIndex'],\n    ['tileSizeX', 'tileSize'],\n    ['tileSizeY', 'tileSize'],\n    ['colorStartA', 'color'],\n    ['colorStartB', 'color'],\n    ['colorStartAlpha', 'alpha'],\n    ['colorEndA',   'color'],\n    ['colorEndB',   'color'],\n    ['colorEndAlpha', 'alpha'],\n    ['particleTime'],\n    ['sizeStart'],\n    ['sizeEnd'],\n    ['speed'],\n    ['angleSpeed'],\n    ['damping'],\n    ['angleDamping'],\n    ['gravityScale'],\n    ['particleConeAngle'],\n    ['fadeRate'],\n    ['randomness'],\n    ['collideTiles'],\n    ['additive'],\n    ['randomColorComponents'],\n    ['renderOrder'],\n];"
  },
  {
    "path": "engine/engineDraw.js",
    "content": "/*\r\n    LittleJS Drawing System\r\n\r\n    - Super fast tile sheet rendering\r\n    - Utility functions for webgl\r\n    - Adapted from Tiny-Canvas https://github.com/bitnenfer/tiny-canvas\r\n*/\r\n\r\n'use strict';\r\n\r\n///////////////////////////////////////////////////////////////////////////////\\\r\n\r\nconst screenToWorld = (screenPos)=>\r\n    screenPos.add(vec2(.5)).subtract(mainCanvasSize.scale(.5)).multiply(vec2(1/cameraScale,-1/cameraScale)).add(cameraPos);\r\nconst worldToScreen = (worldPos)=>\r\n    worldPos.subtract(cameraPos).multiply(vec2(cameraScale,-cameraScale)).add(mainCanvasSize.scale(.5)).subtract(vec2(.5));\r\n\r\n// draw textured tile centered on pos\r\nfunction drawTile(pos, size=vec2(1), tileIndex=-1, tileSize=defaultTileSize, color=new Color, angle=0, mirror, \r\n    additiveColor=new Color(0,0,0,0))\r\n{\r\n    if (!size.x  | !size.y)\r\n        return;\r\n        \r\n    showWatermark && ++drawCount;\r\n    if (glEnable)\r\n    {\r\n        if (tileIndex < 0)\r\n        {\r\n            // if negative tile index, force untextured\r\n            glDraw(pos.x, pos.y, size.x, size.y, angle, 0, 0, 0, 0, 0, 0, color.rgbaInt()); \r\n        }\r\n        else\r\n        {\r\n            // calculate uvs and render\r\n            const cols = tileImage.width / tileSize.x |0;\r\n            const uvSizeX = tileSize.x * tileImageSizeInverse.x;\r\n            const uvSizeY = tileSize.y * tileImageSizeInverse.y;\r\n            const uvX = (tileIndex%cols)*uvSizeX, uvY = (tileIndex/cols|0)*uvSizeY;\r\n            glDraw(pos.x, pos.y, size.x, size.y, angle, mirror, \r\n                uvX, uvY, uvX + uvSizeX, uvY + uvSizeY, color.rgbaInt(), additiveColor.rgbaInt()); \r\n        }\r\n    }\r\n    else\r\n    {\r\n        // normal canvas 2D rendering method (slower)\r\n        drawCanvas2D(pos, size, angle, mirror, (context)=>\r\n        {\r\n            if (tileIndex < 0)\r\n            {\r\n                // if negative tile index, force untextured\r\n                context.fillStyle = color.rgba();\r\n                context.fillRect(-.5, -.5, 1, 1);\r\n            }\r\n            else\r\n            {\r\n                // calculate uvs and render\r\n                const cols = tileImage.width / tileSize.x |0;\r\n                const sX = (tileIndex%cols)*tileSize.x   + tileBleedShrinkFix;\r\n                const sY = (tileIndex/cols|0)*tileSize.y + tileBleedShrinkFix;\r\n                const sWidth  = tileSize.x - 2*tileBleedShrinkFix;\r\n                const sHeight = tileSize.y - 2*tileBleedShrinkFix;\r\n                context.globalAlpha = color.a; // only alpha is supported\r\n                context.drawImage(tileImage, sX, sY, sWidth, sHeight, -.5, -.5, 1, 1);\r\n            }\r\n        });\r\n    }\r\n}\r\n\r\n// draw a colored untextured rect centered on pos\r\nfunction drawRect(pos, size, color, angle)\r\n{\r\n    drawTile(pos, size, -1, defaultTileSize, color, angle);\r\n}\r\n\r\n// draw textured tile centered on pos in screen space\r\nfunction drawTileScreenSpace(pos, size=vec2(1), tileIndex, tileSize, color, angle, mirror, additiveColor)\r\n{\r\n    drawTile(screenToWorld(pos), size.scale(1/cameraScale), tileIndex, tileSize, color, angle, mirror, additiveColor);\r\n}\r\n\r\n// draw a colored untextured rect in screen space\r\nfunction drawRectScreenSpace(pos, size, color, angle)\r\n{\r\n    drawTileScreenSpace(pos, size, -1, defaultTileSize, color, angle);\r\n}\r\n\r\n// draw a colored line between two points\r\nfunction drawLine(posA, posB, thickness=.1, color)\r\n{\r\n    const halfDelta = vec2((posB.x - posA.x)*.5, (posB.y - posA.y)*.5);\r\n    const size = vec2(thickness, halfDelta.length()*2);\r\n    drawRect(posA.add(halfDelta), size, color, halfDelta.angle());\r\n}\r\n\r\n// draw directly to the 2d canvas in world space (bipass webgl)\r\nfunction drawCanvas2D(pos, size, angle, mirror, drawFunction)\r\n{\r\n    // create canvas transform from world space to screen space\r\n    pos = worldToScreen(pos);\r\n    size = size.scale(cameraScale);\r\n    mainContext.save();\r\n    mainContext.translate(pos.x+.5|0, pos.y-.5|0);\r\n    mainContext.rotate(angle);\r\n    mainContext.scale(mirror?-size.x:size.x, size.y);\r\n    drawFunction(mainContext);\r\n    mainContext.restore();\r\n}\r\n\r\n// draw text in world space without canvas scaling because that messes up fonts\r\nfunction drawText(text, pos, size=1, color=new Color, lineWidth=0, lineColor=new Color(0,0,0), textAlign='center', font=defaultFont)\r\n{\r\n    pos = worldToScreen(pos);\r\n    mainContext.font = size*cameraScale + 'px '+ font;\r\n    mainContext.textAlign = textAlign;\r\n    mainContext.textBaseline = 'middle';\r\n    if (lineWidth)\r\n    {\r\n        mainContext.lineWidth = lineWidth*cameraScale;\r\n        mainContext.strokeStyle = lineColor.rgba();\r\n        mainContext.strokeText(text, pos.x, pos.y);\r\n    }\r\n    mainContext.fillStyle = color.rgba();\r\n    mainContext.fillText(text, pos.x, pos.y);\r\n}\r\n\r\n// enable additive or regular blend mode\r\nfunction setBlendMode(additive)\r\n{\r\n    glEnable ? glSetBlendMode(additive) : mainContext.globalCompositeOperation = additive ? 'lighter' : 'source-over';\r\n}"
  },
  {
    "path": "engine/engineInput.js",
    "content": "/*\r\n    LittleJS Input System\r\n    - Tracks key down, pressed, and released\r\n    - Also tracks mouse buttons, position, and wheel\r\n    - Supports multiple gamepads\r\n*/\r\n\r\n'use strict';\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// input\r\n\r\nconst enableGamepads = 1;\r\nconst enableTouchInput = 0;\r\nconst copyGamepadDirectionToStick = 1;\r\nconst copyWASDToDpad = 1;\r\n\r\n// input for all devices including keyboard, mouse, and gamepad. (d=down, p=pressed, r=released)\r\nconst inputData = [[]];\r\nconst keyIsDown      = (key, device=0)=> inputData[device][key] && inputData[device][key].d ? 1 : 0;\r\nconst keyWasPressed  = (key, device=0)=> inputData[device][key] && inputData[device][key].p ? 1 : 0;\r\nconst keyWasReleased = (key, device=0)=> inputData[device][key] && inputData[device][key].r ? 1 : 0;\r\nconst clearInput     = ()=> inputData[0].length = 0;\r\n\r\n// mouse input is stored with keyboard\r\nlet hadInput   = 0;\r\nlet mouseWheel = 0;\r\nlet mousePosScreen = vec2();\r\nlet mousePosWorld  = vec2();\r\nconst mouseIsDown      = keyIsDown;\r\nconst mouseWasPressed  = keyWasPressed;\r\nconst mouseWasReleased = keyWasReleased;\r\n\r\n// handle input events\r\nonkeydown   = e=>\r\n{\r\n    if (debug && e.target != document.body) return;\r\n    e.repeat || (inputData[isUsingGamepad = 0][remapKeyCode(e.keyCode)] = {d:hadInput=1, p:1});\r\n}\r\nonkeyup     = e=>\r\n{\r\n    if (debug && e.target != document.body) return;\r\n    const c = remapKeyCode(e.keyCode); inputData[0][c] && (inputData[0][c].d = 0, inputData[0][c].r = 1);\r\n}\r\nonmousedown = e=> (inputData[0][e.button] = {d:hadInput=1, p:1}, onmousemove(e));\r\nonmouseup   = e=> inputData[0][e.button] && (inputData[0][e.button].d = 0, inputData[0][e.button].r = 1);\r\nonmousemove = e=>\r\n{\r\n    if (!mainCanvas)\r\n        return;\r\n\r\n    // convert mouse pos to canvas space\r\n    const rect = mainCanvas.getBoundingClientRect();\r\n    mousePosScreen.x = mainCanvasSize.x * percent(e.x, rect.right, rect.left);\r\n    mousePosScreen.y = mainCanvasSize.y * percent(e.y, rect.bottom, rect.top);\r\n}\r\nif(debug)\r\n    onwheel = e=> e.ctrlKey || (mouseWheel = sign(e.deltaY));\r\noncontextmenu = e=> !1; // prevent right click menu\r\nconst remapKeyCode = c=> copyWASDToDpad ? c==87?38 : c==83?40 : c==65?37 : c==68?39 : c : c;\r\n\r\n////////////////////////////////////////////////////////////////////\r\n// gamepad\r\n\r\nlet isUsingGamepad = 0;\r\nlet gamepadCount = 0;\r\nconst gamepadStick       = (stick,  gamepad=0)=> gamepad < gamepadCount ? inputData[gamepad+1].stickData[stick] : vec2();\r\nconst gamepadIsDown      = (button, gamepad=0)=> gamepad < gamepadCount ? keyIsDown     (button, gamepad+1) : 0;\r\nconst gamepadWasPressed  = (button, gamepad=0)=> gamepad < gamepadCount ? keyWasPressed (button, gamepad+1) : 0;\r\nconst gamepadWasReleased = (button, gamepad=0)=> gamepad < gamepadCount ? keyWasReleased(button, gamepad+1) : 0;\r\n\r\nfunction updateGamepads()\r\n{\r\n    if (!navigator.getGamepads || !enableGamepads)\r\n        return;\r\n\r\n    if (!document.hasFocus() && !debug)\r\n        return;\r\n\r\n    const gamepads = navigator.getGamepads();\r\n    gamepadCount = 0;\r\n    for(let i = 0; i < navigator.getGamepads().length; ++i)\r\n    {\r\n        // get or create gamepad data\r\n        const gamepad = gamepads[i];\r\n        let data = inputData[i+1];\r\n        if (!data)\r\n        {\r\n            data = inputData[i+1] = [];\r\n            data.stickData = [vec2(), vec2()];\r\n        }\r\n\r\n        if (gamepad && gamepad.axes.length >= 2)\r\n        {\r\n            gamepadCount = i+1;\r\n\r\n            // read analog sticks and clamp dead zone\r\n            const deadZone = .3, deadZoneMax = .8;\r\n            const applyDeadZone = (v)=> \r\n                v >  deadZone ?  percent( v, deadZoneMax, deadZone) : \r\n                v < -deadZone ? -percent(-v, deadZoneMax, deadZone) : 0;\r\n            data.stickData[0] = vec2(applyDeadZone(gamepad.axes[0]), applyDeadZone(-gamepad.axes[1]));\r\n            \r\n            if (copyGamepadDirectionToStick)\r\n            {\r\n                // copy dpad to left analog stick when pressed\r\n                if (gamepadIsDown(12,i)|gamepadIsDown(13,i)|gamepadIsDown(14,i)|gamepadIsDown(15,i))\r\n                    data.stickData[0] = vec2(gamepadIsDown(15,i) - gamepadIsDown(14,i), gamepadIsDown(12,i) - gamepadIsDown(13,i));\r\n            }\r\n\r\n            // clamp stick input to unit vector\r\n            data.stickData[0] = data.stickData[0].clampLength();\r\n            \r\n            // read buttons\r\n            gamepad.buttons.map((button, j)=>\r\n            {\r\n                inputData[i+1][j] = button.pressed ? {d:1, p:!gamepadIsDown(j,i)} : \r\n                inputData[i+1][j] = {r:gamepadIsDown(j,i)}\r\n                isUsingGamepad |= button.pressed && !i;\r\n            });\r\n        }\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// touch screen input\r\n\r\nif (enableTouchInput && window.ontouchstart !== undefined)\r\n{\r\n    // handle all touch events the same way\r\n    ontouchstart = ontouchmove = ontouchend = e=>\r\n    {\r\n        e.button = 0; // all touches are left click\r\n        hadInput || zzfx(hadInput = 1) ; // fix mobile audio, force it to play a sound the first time\r\n\r\n        // check if touching and pass to mouse events\r\n        const touching = e.touches.length;\r\n        if (touching)\r\n        {\r\n            // set event pos and pass it along\r\n            e.x = e.touches[0].clientX;\r\n            e.y = e.touches[0].clientY;\r\n            wasTouching ? onmousemove(e) : onmousedown(e);\r\n        }\r\n        else if (wasTouching)\r\n            wasTouching && onmouseup(e);\r\n\r\n        // set was touching\r\n        wasTouching = touching;\r\n    }\r\n    let wasTouching;\r\n}"
  },
  {
    "path": "engine/engineObject.js",
    "content": "/*\r\n    LittleJS Object Base Class\r\n    - Base object class used by the engine\r\n    - Automatically adds self to object list\r\n    - Will be updated and rendered each frame\r\n    - Renders as a sprite from a tilesheet by default\r\n    - Can have color and addtive color applied\r\n    - 2d Physics and collision system\r\n    - Sorted by renderOrder\r\n    - Objects can have children attached\r\n    - Parents are updated before children, and set child transform\r\n    - Call destroy() to get rid of objects\r\n*/\r\n\r\n'use strict';\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n// object defaults\r\nconst defaultObjectSize = vec2(.999);\r\nconst defaultObjectMass = 1;\r\nconst defaultObjectDamping = .99;\r\nconst defaultObjectAngleDamping = .99;\r\nconst defaultObjectElasticity = 0;\r\nconst defaultObjectFriction = .8;\r\nconst maxObjectSpeed = 1;\r\n\r\nclass EngineObject\r\n{\r\n    constructor(pos, size=defaultObjectSize, tileIndex=-1, tileSize=defaultTileSize, angle=0, color)\r\n    {\r\n        // set passed in params\r\n        ASSERT(pos);\r\n        this.pos = pos.copy();\r\n        this.size = size;\r\n        this.tileIndex = tileIndex;\r\n        this.tileSize = tileSize;\r\n        this.angle = angle;\r\n        this.color = color;\r\n\r\n        // set physics defaults\r\n        this.mass         = defaultObjectMass;\r\n        this.damping      = defaultObjectDamping;\r\n        this.angleDamping = defaultObjectAngleDamping;\r\n        this.elasticity   = defaultObjectElasticity;\r\n        this.friction     = defaultObjectFriction;\r\n\r\n        // init other object stuff\r\n        this.spawnTime = time;\r\n        this.velocity = vec2(this.collideSolidObjects = this.renderOrder = this.angleVelocity = 0);\r\n        this.collideTiles = this.gravityScale = 1;\r\n        this.children = [];\r\n\r\n        // add to list of objects\r\n        engineObjects.push(this);\r\n    }\r\n    \r\n    update()\r\n    {\r\n        if (this.parent)\r\n        {\r\n            // copy parent pos/angle\r\n            this.pos = this.localPos.multiply(vec2(this.getMirrorSign(),1)).rotate(-this.parent.angle).add(this.parent.pos);\r\n            this.angle = this.getMirrorSign()*this.localAngle + this.parent.angle;\r\n            return;\r\n        }\r\n\r\n        // limit max speed to prevent missing collisions\r\n        this.velocity.x = clamp(this.velocity.x, maxObjectSpeed, -maxObjectSpeed);\r\n        this.velocity.y = clamp(this.velocity.y, maxObjectSpeed, -maxObjectSpeed);\r\n\r\n        // apply physics\r\n        const oldPos = this.pos.copy();\r\n        this.pos.x += this.velocity.x = this.damping * this.velocity.x;\r\n        this.pos.y += this.velocity.y = this.damping * this.velocity.y + gravity * this.gravityScale;\r\n        this.angle += this.angleVelocity *= this.angleDamping;\r\n\r\n        // physics sanity checks\r\n        ASSERT(this.angleDamping >= 0 && this.angleDamping <= 1);\r\n        ASSERT(this.damping >= 0 && this.damping <= 1);\r\n\r\n        if (!this.mass) // do not update collision for fixed objects\r\n            return;\r\n\r\n        const wasMovingDown = this.velocity.y < 0;\r\n        if (this.groundObject)\r\n        {\r\n            // apply friction in local space of ground object\r\n            const groundSpeed = this.groundObject.velocity ? this.groundObject.velocity.x : 0;\r\n            this.velocity.x = groundSpeed + (this.velocity.x - groundSpeed) * this.friction;\r\n            this.groundObject = 0;\r\n            //debugPhysics && debugPoint(this.pos.subtract(vec2(0,this.size.y/2)), '#0f0');\r\n        }\r\n\r\n        if (this.collideSolidObjects)\r\n        {\r\n            // check collisions against solid objects\r\n            const epsilon = 1e-3; // necessary to push slightly outside of the collision\r\n            for(const o of engineCollideObjects)\r\n            {\r\n                // non solid objects don't collide with eachother\r\n                if (!this.isSolid & !o.isSolid || o.destroyed || o.parent)\r\n                    continue;\r\n\r\n                // check collision\r\n                if (!isOverlapping(this.pos, this.size, o.pos, o.size) || o == this)\r\n                    continue;\r\n\r\n                // pass collision to objects\r\n                if (!this.collideWithObject(o) | !o.collideWithObject(this))\r\n                    continue;\r\n\r\n                if (isOverlapping(oldPos, this.size, o.pos, o.size))\r\n                {\r\n                    // if already was touching, try to push away\r\n                    const deltaPos = oldPos.subtract(o.pos);\r\n                    const length = deltaPos.length();\r\n                    const pushAwayAccel = .001; // push away if alread overlapping\r\n                    const velocity = length < .01 ? randVector(pushAwayAccel) : deltaPos.scale(pushAwayAccel/length);\r\n                    this.velocity = this.velocity.add(velocity);\r\n                    if (o.mass) // push away if not fixed\r\n                        o.velocity = o.velocity.subtract(velocity);\r\n                        \r\n                    debugPhysics && debugAABB(this.pos, o.pos, this.size, o.size, '#f00');\r\n                    continue;\r\n                }\r\n\r\n                // check for collision\r\n                const sx = this.size.x + o.size.x;\r\n                const sy = this.size.y + o.size.y;\r\n                const smallStepUp = (oldPos.y - o.pos.y)*2 > sy + gravity; // prefer to push up if small delta\r\n                const isBlockedX = abs(oldPos.y - o.pos.y)*2 < sy;\r\n                const isBlockedY = abs(oldPos.x - o.pos.x)*2 < sx;\r\n                \r\n                if (smallStepUp || isBlockedY || !isBlockedX) // resolve y collision\r\n                {\r\n                    // push outside object collision\r\n                    this.pos.y = o.pos.y + (sy*.5 + epsilon) * sign(oldPos.y - o.pos.y);\r\n                    if (o.groundObject && wasMovingDown || !o.mass)\r\n                    {\r\n                        // set ground object if landed on something\r\n                        if (wasMovingDown)\r\n                            this.groundObject = o;\r\n\r\n                        // bounce if other object is fixed or grounded\r\n                        this.velocity.y *= -this.elasticity;\r\n                    }\r\n                    else if (o.mass)\r\n                    {\r\n                        // set center of mass velocity\r\n                        this.velocity.y = o.velocity.y = \r\n                            (this.mass * this.velocity.y + o.mass * o.velocity.y) / (this.mass + o.mass);\r\n                    }\r\n                    debugPhysics && smallStepUp && (abs(oldPos.x - o.pos.x)*2 > sx) && console.log('stepUp', oldPos.y - o.pos.y);\r\n                }\r\n                if (!smallStepUp && (isBlockedX || !isBlockedY)) // resolve x collision\r\n                {\r\n                    // push outside collision\r\n                    this.pos.x = o.pos.x + (sx*.5 + epsilon) * sign(oldPos.x - o.pos.x);\r\n                    if (o.mass)\r\n                    {\r\n                        // set center of mass velocity\r\n                        this.velocity.x = o.velocity.x = \r\n                            (this.mass * this.velocity.x + o.mass * o.velocity.x) / (this.mass + o.mass);\r\n                    }\r\n                    else // bounce if other object is fixed\r\n                        this.velocity.x *= -this.elasticity;\r\n                }\r\n\r\n                debugPhysics && debugAABB(this.pos, o.pos, this.size, o.size, '#f0f');\r\n            }\r\n        }\r\n        if (this.collideTiles)\r\n        {\r\n            // check collision against tiles\r\n            if (tileCollisionTest(this.pos, this.size, this))\r\n            {\r\n                //debugPhysics && debugRect(this.pos, this.size, '#ff0');\r\n\r\n                // if already was stuck in collision, don't do anything\r\n                // this should not happen unless something starts in collision\r\n                if (!tileCollisionTest(oldPos, this.size, this))\r\n                {\r\n                    // test which side we bounced off (or both if a corner)\r\n                    const isBlockedY = tileCollisionTest(new Vector2(oldPos.x, this.pos.y), this.size, this);\r\n                    const isBlockedX = tileCollisionTest(new Vector2(this.pos.x, oldPos.y), this.size, this);\r\n                    if (isBlockedY || !isBlockedX)\r\n                    {\r\n                        // set if landed on ground\r\n                        this.groundObject = wasMovingDown;\r\n\r\n                        // push out of collision and bounce\r\n                        this.pos.y = oldPos.y;\r\n                        this.velocity.y *= -this.elasticity;\r\n                    }\r\n                    if (isBlockedX || !isBlockedY)\r\n                    {\r\n                        // push out of collision and bounce\r\n                        this.pos.x = oldPos.x;\r\n                        this.velocity.x *= -this.elasticity;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n       \r\n    render()\r\n    {\r\n        // default object render\r\n        drawTile(this.pos, this.size, this.tileIndex, this.tileSize, this.color, this.angle, this.mirror, this.additiveColor);\r\n    }\r\n    \r\n    destroy()             \r\n    { \r\n        if (this.destroyed)\r\n            return;\r\n        \r\n        // disconnect from parent and destroy chidren\r\n        this.destroyed = 1;\r\n        this.parent && this.parent.removeChild(this);\r\n        for(const child of this.children)\r\n            child.destroy(child.parent = 0);\r\n    }\r\n    collideWithTile(data, pos)        { return data > 0; }\r\n    collideWithTileRaycast(data, pos) { return data > 0; }\r\n    collideWithObject(o)              { return 1; }\r\n    getAliveTime()                    { return time - this.spawnTime; }\r\n    applyAcceleration(a)              { ASSERT(!this.isFixed()); this.velocity = this.velocity.add(a); }\r\n    applyForce(force)\t              { this.applyAcceleration(force.scale(1/this.mass)); }\r\n    isFixed()                         { return !this.mass; }\r\n    getMirrorSign(s=1)                { return this.mirror ? -s : s; }\r\n\r\n    addChild(child, localPos=vec2(), localAngle=0)\r\n    {\r\n        ASSERT(!child.parent && !this.children.includes(child));\r\n        this.children.push(child);\r\n        child.parent = this;\r\n        child.localPos = localPos.copy();\r\n        child.localAngle = localAngle;\r\n    }\r\n    removeChild(child)\r\n    {\r\n        ASSERT(child.parent == this && this.children.includes(child));\r\n        this.children.splice(this.children.indexOf(child), 1);\r\n        child.parent = 0;\r\n    }\r\n\r\n    setCollision(collideSolidObjects=1, isSolid, collideTiles=1)\r\n    {\r\n        ASSERT(collideSolidObjects || !isSolid); // solid objects must be set to collide\r\n\r\n        // track collidable objects in separate list\r\n        if (collideSolidObjects && !this.collideSolidObjects)\r\n        {\r\n            ASSERT(!engineCollideObjects.includes(this));\r\n            engineCollideObjects.push(this);\r\n        }\r\n        else if (!collideSolidObjects && this.collideSolidObjects)\r\n        {\r\n            ASSERT(engineCollideObjects.includes(this))\r\n            engineCollideObjects.splice(engineCollideObjects.indexOf(this), 1);\r\n        }\r\n\r\n        this.collideSolidObjects = collideSolidObjects;\r\n        this.isSolid = isSolid;\r\n        this.collideTiles = collideTiles;\r\n    }\r\n}"
  },
  {
    "path": "engine/engineParticle.js",
    "content": "/*\r\n    LittleJS Particle System\r\n    - Spawns particles with randomness from parameters\r\n    - Updates particle physics\r\n    - Fast particle rendering\r\n*/\r\n\r\n'use strict';\r\n\r\nclass ParticleEmitter extends EngineObject\r\n{\r\n    constructor\r\n    ( \r\n        pos,                            // world space position of emitter\r\n        emitSize = 0,                   // size of emitter (float for circle diameter, vec2 for rect)\r\n        emitTime = 0,                   // how long to stay alive (0 is forever)\r\n        emitRate = 100,                 // how many particles per second to spawn\r\n        emitConeAngle = PI,             // local angle to apply velocity to particles from emitter\r\n        tileIndex = -1,                 // index into tile sheet, if <0 no texture is applied\r\n        tileSize = defaultTileSize,     // tile size for particles\r\n        colorStartA = new Color,        // color at start of life\r\n        colorStartB = new Color,        // randomized between start colors\r\n        colorEndA = new Color(1,1,1,0), // color at end of life\r\n        colorEndB = new Color(1,1,1,0), // randomized between end colors\r\n        particleTime = .5,              // how long particles live\r\n        sizeStart = .1,                 // how big are particles at start\r\n        sizeEnd = 1,                    // how big are particles at end\r\n        speed = .1,                     // how fast are particles when spawned\r\n        angleSpeed = .05,               // how fast are particles rotating\r\n        damping = 1,                    // how much to dampen particle speed\r\n        angleDamping = 1,               // how much to dampen particle angular speed\r\n        gravityScale = 0,               // how much does gravity effect particles\r\n        particleConeAngle = PI,         // cone for start particle angle\r\n        fadeRate = .1,                  // how quick to fade in particles at start/end in percent of life\r\n        randomness = .2,                // apply extra randomness percent\r\n        collideTiles,                   // do particles collide against tiles\r\n        additive,                       // should particles use addtive blend\r\n        randomColorLinear = 1,          // should color be randomized linearly or across each component\r\n        renderOrder = additive ? 1e9 : 0// render order for particles (additive is above other stuff by default)\r\n    )\r\n    {\r\n        super(pos, new Vector2, tileIndex, tileSize);\r\n\r\n        // emitter settings\r\n        this.emitSize = emitSize\r\n        this.emitTime = emitTime;\r\n        this.emitRate = emitRate;\r\n        this.emitConeAngle = emitConeAngle;\r\n\r\n        // color settings\r\n        this.colorStartA = colorStartA;\r\n        this.colorStartB = colorStartB;\r\n        this.colorEndA   = colorEndA;\r\n        this.colorEndB   = colorEndB;\r\n        this.randomColorLinear = randomColorLinear;\r\n\r\n        // particle settings\r\n        this.particleTime      = particleTime;\r\n        this.sizeStart         = sizeStart;\r\n        this.sizeEnd           = sizeEnd;\r\n        this.speed             = speed;\r\n        this.angleSpeed        = angleSpeed;\r\n        this.damping           = damping;\r\n        this.angleDamping      = angleDamping;\r\n        this.gravityScale      = gravityScale;\r\n        this.particleConeAngle = particleConeAngle;\r\n        this.fadeRate          = fadeRate;\r\n        this.randomness        = randomness;\r\n        this.collideTiles      = collideTiles;\r\n        this.additive          = additive;\r\n        this.renderOrder       = renderOrder;\r\n        this.trailScale        =  \r\n        this.emitTimeBuffer    = 0;\r\n    }\r\n    \r\n    update()\r\n    {\r\n        // only do default update to apply parent transforms\r\n        this.parent && super.update();\r\n\r\n        // update emitter\r\n        if (!this.emitTime || this.getAliveTime() <= this.emitTime)\r\n        {\r\n            // emit particles\r\n            if (this.emitRate)\r\n            {\r\n                const rate = 1/this.emitRate;\r\n                for(this.emitTimeBuffer += timeDelta; this.emitTimeBuffer > 0; this.emitTimeBuffer -= rate)\r\n                    this.emitParticle();\r\n            }\r\n        }\r\n        else\r\n            this.destroy();\r\n\r\n        debugParticles && debugRect(this.pos, vec2(this.emitSize), '#0f0', 0, this.angle);\r\n    }\r\n\r\n    emitParticle()\r\n    {\r\n        // spawn a particle\r\n        const pos = this.emitSize.x != undefined ? // check if vec2 was used for size\r\n            (new Vector2(rand(-.5,.5), rand(-.5,.5))).multiply(this.emitSize).rotate(this.angle) // box emitter\r\n            : randInCircle(this.emitSize * .5);                                                  // circle emitter\r\n        const particle = new Particle(this.pos.add(pos), this.tileIndex, this.tileSize, \r\n            this.angle + rand(this.particleConeAngle, -this.particleConeAngle));\r\n\r\n        // randomness scales each paremeter by a percentage\r\n        const randomness = this.randomness;\r\n        const randomizeScale = (v)=> v + v*rand(randomness, -randomness);\r\n\r\n        // randomize particle settings\r\n        const particleTime  = randomizeScale(this.particleTime);\r\n        const sizeStart     = randomizeScale(this.sizeStart);\r\n        const sizeEnd       = randomizeScale(this.sizeEnd);\r\n        const speed         = randomizeScale(this.speed);\r\n        const angleSpeed    = randomizeScale(this.angleSpeed) * randSign();\r\n        const coneAngle     = rand(this.emitConeAngle, -this.emitConeAngle);\r\n        const colorStart    = randColor(this.colorStartA, this.colorStartB, this.randomColorLinear);\r\n        const colorEnd      = randColor(this.colorEndA,   this.colorEndB, this.randomColorLinear);\r\n\r\n        // build particle settings\r\n        particle.colorStart      = colorStart;\r\n        particle.colorEndDelta   = colorEnd.subtract(colorStart);\r\n        particle.velocity        = (new Vector2).setAngle(this.angle + coneAngle, speed);\r\n        particle.angleVelocity   = angleSpeed;\r\n        particle.lifeTime        = particleTime;\r\n        particle.sizeStart       = sizeStart;\r\n        particle.sizeEndDelta    = sizeEnd - sizeStart;\r\n        //particle.mirror          = rand(2)|0; // random mirroring\r\n        particle.fadeRate        = this.fadeRate;\r\n        particle.damping         = this.damping;\r\n        particle.angleDamping    = this.angleDamping;\r\n        particle.elasticity      = this.elasticity;\r\n        particle.friction        = this.friction;\r\n        particle.gravityScale    = this.gravityScale;\r\n        particle.collideTiles    = this.collideTiles;\r\n        particle.additive        = this.additive;\r\n        particle.renderOrder     = this.renderOrder;\r\n        particle.trailScale      = this.trailScale;\r\n\r\n        // setup callbacks for particles\r\n        particle.destroyCallback = this.particleDestroyCallback;\r\n        this.particleCreateCallback && this.particleCreateCallback(particle);\r\n\r\n        // return the newly created particle\r\n        return particle;\r\n    }\r\n\r\n    render() {} // emitters are not rendered\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// particle object\r\n\r\nclass Particle extends EngineObject\r\n{\r\n    constructor(pos, tileIndex, tileSize, angle) { super(pos, new Vector2, tileIndex, tileSize, angle); }\r\n\r\n    render()\r\n    {\r\n        // modulate size and color\r\n        const p = min((time - this.spawnTime) / this.lifeTime, 1);\r\n        const radius = this.sizeStart + p * this.sizeEndDelta;\r\n        const size = new Vector2(radius, radius);\r\n\r\n        const fadeRate = this.fadeRate*.5;\r\n        const color = new Color(\r\n            this.colorStart.r + p * this.colorEndDelta.r,\r\n            this.colorStart.g + p * this.colorEndDelta.g,\r\n            this.colorStart.b + p * this.colorEndDelta.b,\r\n            (this.colorStart.a + p * this.colorEndDelta.a) * \r\n             (p < fadeRate ? p/fadeRate : p > 1-fadeRate ? (1-p)/fadeRate : 1)); // fade alpha\r\n\r\n        // draw the particle\r\n        this.additive && setBlendMode(1);\r\n        if (this.trailScale)\r\n        {\r\n            // trail style particles\r\n            const speed = this.velocity.length();\r\n            const direction = this.velocity.scale(1/speed);\r\n            const trailLength = speed * this.trailScale;\r\n            size.y = max(size.x, trailLength);\r\n            this.angle = direction.angle();\r\n            drawTile(this.pos.add(direction.multiply(vec2(0,-trailLength*.5))), size, this.tileIndex, this.tileSize, color, this.angle, this.mirror);\r\n        }\r\n        else\r\n            drawTile(this.pos, size, this.tileIndex, this.tileSize, color, this.angle, this.mirror);\r\n        this.additive && setBlendMode()\r\n        debugParticles && debugRect(this.pos, size, '#f005', 0, this.angle);\r\n\r\n        if (p == 1)\r\n        {\r\n            this.color = color;\r\n            this.size = size;\r\n            this.destroyCallback && this.destroyCallback(this);\r\n            this.destroyed = 1;\r\n            return;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "engine/engineTileLayer.js",
    "content": "/*\r\n    LittleJS Tile Layer System\r\n    - Caches arrays of tiles to offscreen canvas for fast rendering\r\n    - Unlimted numbers of layers, allocates canvases as needed\r\n    - Interfaces with EngineObject for collision\r\n    - Collision layer is separate from visible layers\r\n    - Tile layers can be drawn to using their context with canvas2d\r\n    - It is recommended to have a visible layer that matches the collision\r\n*/\r\n\r\n'use strict';\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// Tile Collision\r\n\r\nlet tileCollision = [];\r\nlet tileCollisionSize = vec2();\r\nconst tileLayerCanvasCache = [];\r\nconst defaultTileLayerRenderOrder = -1e9;\r\nconst debugRaycast = 0;\r\n\r\nfunction initTileCollision(size)\r\n{\r\n    // reset collision to be clear\r\n    tileCollisionSize = size;\r\n    tileCollision = [];\r\n    for(let i=tileCollision.length = tileCollisionSize.area(); i--;)\r\n        tileCollision[i] = 0;\r\n}\r\n\r\nconst setTileCollisionData = (pos, data=0)=>\r\n    pos.arrayCheck(tileCollisionSize) && (tileCollision[(pos.y|0)*tileCollisionSize.x+pos.x|0] = data);\r\nconst getTileCollisionData = (pos)=>\r\n    pos.arrayCheck(tileCollisionSize) ? tileCollision[(pos.y|0)*tileCollisionSize.x+pos.x|0] : 0;\r\n\r\nfunction tileCollisionTest(pos, size=vec2(), object)\r\n{\r\n    // check if there is collision in a given area\r\n    const minX = pos.x - size.x*.5|0;\r\n    const minY = pos.y - size.y*.5|0;\r\n    const maxX = pos.x + size.x*.5|0;\r\n    const maxY = pos.y + size.y*.5|0;\r\n    for(let y = minY; y <= maxY; ++y)\r\n    for(let x = minX; x <= maxX; ++x)\r\n    {\r\n        const tileData = tileCollision[y*tileCollisionSize.x + x];\r\n        if (tileData && (!object || object.collideWithTile(tileData, new Vector2(x, y))))\r\n            return 1;\r\n    }\r\n}\r\n\r\n// return the center of tile if any that is hit (this does not return the exact hit point)\r\n// todo: return the exact hit point, it must still be inside the hit tile\r\nfunction tileCollisionRaycast(posStart, posEnd, object)\r\n{\r\n    // test if a ray collides with tiles from start to end\r\n    posStart = posStart.int();\r\n    posEnd = posEnd.int();\r\n    const posDelta = posEnd.subtract(posStart);\r\n    const dx = abs(posDelta.x),  dy = -abs(posDelta.y);\r\n    const sx = sign(posDelta.x), sy = sign(posDelta.y);\r\n    let e = dx + dy;\r\n\r\n    for(let x = posStart.x, y = posStart.y;;)\r\n    {\r\n        const tileData = getTileCollisionData(vec2(x,y));\r\n        if (tileData && (object ? object.collideWithTileRaycast(tileData, new Vector2(x, y)) : tileData > 0))\r\n        {\r\n            debugRaycast && debugLine(posStart, posEnd, '#f00',.02, 1);\r\n            debugRaycast && debugPoint(new Vector2(x+.5, y+.5), '#ff0', 1);\r\n            return new Vector2(x+.5, y+.5);\r\n        }\r\n\r\n        // update Bresenham line drawing algorithm\r\n        if (x == posEnd.x & y == posEnd.y) break;\r\n        const e2 = 2*e;\r\n        if (e2 >= dy) e += dy, x += sx;\r\n        if (e2 <= dx) e += dx, y += sy;\r\n    }\r\n    debugRaycast && debugLine(posStart, posEnd, '#00f',.02, 1);\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// Tile Layer Rendering System\r\n\r\nclass TileLayerData\r\n{\r\n    constructor(tile=-1, direction=0, mirror=0, color=new Color)\r\n    {\r\n        this.tile      = tile;\r\n        this.direction = direction;\r\n        this.mirror    = mirror;\r\n        this.color     = color;\r\n    }\r\n    clear() { this.tile = this.direction = this.mirror = 0; color = new Color; }\r\n}\r\n\r\nclass TileLayer extends EngineObject\r\n{\r\n    constructor(pos, size, scale=vec2(1), layer=0)\r\n    {\r\n        super(pos, size);\r\n\r\n        // create new canvas if necessary\r\n        this.canvas = tileLayerCanvasCache.length ? tileLayerCanvasCache.pop() : document.createElement('canvas');\r\n        this.context = this.canvas.getContext('2d');\r\n\r\n        this.scale = scale;\r\n        this.tileSize = defaultTileSize.copy();\r\n        this.layer = layer;\r\n        this.renderOrder = defaultTileLayerRenderOrder + layer;\r\n        this.flushGLBeforeRender = 1;\r\n\r\n        // init tile data\r\n        this.data = [];\r\n        for(let j = this.size.area(); j--;)\r\n            this.data.push(new TileLayerData());\r\n    }\r\n\r\n    destroy()\r\n    {\r\n        // add canvas back to the cache\r\n        tileLayerCanvasCache.push(this.canvas);\r\n        super.destroy();\r\n    }\r\n    \r\n    setData(layerPos, data, redraw)\r\n    {\r\n        if (layerPos.arrayCheck(this.size))\r\n        {\r\n            this.data[(layerPos.y|0)*this.size.x+layerPos.x|0] = data;\r\n            redraw && this.drawTileData(layerPos);\r\n        }\r\n    }\r\n    \r\n    getData(layerPos)\r\n    { return layerPos.arrayCheck(this.size) && this.data[(layerPos.y|0)*this.size.x+layerPos.x|0]; }\r\n    \r\n    update() {} // tile layers are not updated\r\n    render()\r\n    {\r\n        ASSERT(mainContext != this.context); // must call redrawEnd() after drawing tiles\r\n\r\n        // flush and copy gl canvas because tile canvas does not use gl\r\n        this.flushGLBeforeRender && glEnable && glCopyToContext(mainContext);\r\n        \r\n        // draw the entire cached level onto the main canvas\r\n        const pos = worldToScreen(this.pos.add(vec2(0,this.size.y*this.scale.y)));\r\n        mainContext.drawImage\r\n        (\r\n            this.canvas, pos.x, pos.y,\r\n            cameraScale*this.size.x*this.scale.x, cameraScale*this.size.y*this.scale.y\r\n        );\r\n    }\r\n\r\n    redraw()\r\n    {\r\n        // draw all the tile data to an offscreen canvas using webgl if possible\r\n        this.redrawStart();\r\n        this.drawAllTileData();\r\n        this.redrawEnd();\r\n    }\r\n\r\n    redrawStart(clear = 1)\r\n    {\r\n        // clear and set size\r\n        const width = this.size.x * this.tileSize.x;\r\n        const height = this.size.y * this.tileSize.y;\r\n\r\n        if (clear)\r\n        {\r\n            this.canvas.width  = width;\r\n            this.canvas.height = height;\r\n        }\r\n\r\n        // save current render settings\r\n        this.savedRenderSettings = [mainCanvasSize, mainCanvas, mainContext, cameraScale, cameraPos];\r\n\r\n        // set camera transform for renering\r\n        cameraScale = this.tileSize.x;\r\n        cameraPos = this.size.scale(.5);\r\n        mainCanvas = this.canvas;\r\n        mainContext = this.context;\r\n        mainContext.imageSmoothingEnabled = !pixelated; // disable smoothing for pixel art\r\n        mainCanvasSize = vec2(width, height);\r\n        glPreRender(width, height);\r\n    }\r\n\r\n    redrawEnd()\r\n    {\r\n        ASSERT(mainContext == this.context); // must call redrawStart() before drawing tiles\r\n        glCopyToContext(mainContext, 1);\r\n        //debugSaveCanvas(this.canvas);\r\n\r\n        // set stuff back to normal\r\n        [mainCanvasSize, mainCanvas, mainContext, cameraScale, cameraPos] = this.savedRenderSettings;\r\n    }\r\n\r\n    drawTileData(layerPos)\r\n    {\r\n        // first clear out where the tile was\r\n        const pos = layerPos.int().add(this.pos).add(vec2(.5));\r\n        this.drawCanvas2D(pos, vec2(1), 0, 0, (context)=>context.clearRect(-.5, -.5, 1, 1));\r\n\r\n        // draw the tile\r\n        const d = this.getData(layerPos);\r\n        ASSERT(d.tile < 0 || mainContext == this.context); // must call redrawStart() before drawing tiles\r\n        d.tile < 0 || drawTile(pos, vec2(1), d.tile || -1, this.tileSize, d.color, d.direction*PI/2, d.mirror);\r\n    }\r\n\r\n    drawAllTileData()\r\n    {\r\n        for(let x = this.size.x; x--;)\r\n        for(let y = this.size.y; y--;)\r\n             this.drawTileData(vec2(x,y));\r\n    }\r\n\r\n    // draw directly to the 2d canvas in world space (bipass webgl)\r\n    drawCanvas2D(pos, size, angle, mirror, drawFunction)\r\n    {\r\n        const context = this.context;\r\n        context.save();\r\n        pos = pos.subtract(this.pos).multiply(this.tileSize);\r\n        size = size.multiply(this.tileSize);\r\n        context.translate(pos.x, this.canvas.height - pos.y);\r\n        context.rotate(angle);\r\n        context.scale(mirror?-size.x:size.x, size.y);\r\n        drawFunction(context);\r\n        context.restore();\r\n    }\r\n\r\n    drawTile(pos, size=vec2(1), tileIndex=0, tileSize=defaultTileSize, color=new Color, angle=0, mirror)\r\n    {\r\n        // draw a tile directly onto the layer canvas\r\n        this.drawCanvas2D(pos, size, angle, mirror, (context)=>\r\n        {\r\n            if (tileIndex < 0)\r\n            {\r\n                // untextured\r\n                context.fillStyle = color.rgba();\r\n                context.fillRect(-.5, -.5, 1, 1);\r\n            }\r\n            else\r\n            {\r\n                const cols = tileImage.width/tileSize.x;\r\n                context.globalAlpha = color.a; // full color not supported in this mode\r\n                context.drawImage(tileImage, \r\n                    (tileIndex%cols)*tileSize.x, (tileIndex/cols|0)*tileSize.x, \r\n                    tileSize.x, tileSize.y, -.5, -.5, 1, 1);\r\n            }\r\n        });\r\n    }\r\n\r\n    drawRect(pos, size, color, angle) { this.drawTile(pos, size, -1, 0, color, angle, 0); }\r\n}"
  },
  {
    "path": "engine/engineUtil.js",
    "content": "\r\n/*\r\n    LittleJS Utility Classes and Functions\r\n    - Vector2 - fast, simple, easy vector class\r\n    - Color - holds a rgba color with math functions\r\n    - Timer - tracks time automatically\r\n    - Small math lib\r\n*/\r\n\r\n'use strict';\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// helper functions\r\n\r\nconst PI            = Math.PI;\r\nconst abs           = (a)=>               a < 0 ? -a : a;\r\nconst sign          = (a)=>               a < 0 ? -1 : 1;\r\nconst min           = (a, b)=>            a < b ?  a : b;\r\nconst max           = (a, b)=>            a > b ?  a : b;\r\nconst mod           = (a, b)=>            ((a % b) + b) % b;\r\nconst clamp         = (v, max=1, min=0)=> (ASSERT(max > min), v < min ? min : v > max ? max : v);\r\nconst percent       = (v, max=1, min=0)=> max-min ? clamp((v-min) / (max-min)) : 0;\r\nconst lerp          = (p, max=1, min=0)=> min + clamp(p) * (max-min);\r\nconst formatTime    = (t)=>               (t/60|0)+':'+(t%60<10?'0':'')+(t%60|0);\r\nconst isOverlapping = (pA, sA, pB, sB)=>  abs(pA.x - pB.x)*2 < sA.x + sB.x & abs(pA.y - pB.y)*2 < sA.y + sB.y;\r\n\r\n// random functions\r\nconst rand         = (a=1, b=0)=>              b + (a-b)*Math.random();\r\nconst randSign     = ()=>                      (rand(2)|0)*2-1;\r\nconst randInCircle = (radius=1, minRadius=0)=> radius > 0 ? randVector(radius * rand(minRadius / radius, 1)**.5) : new Vector2;\r\nconst randVector   = (length=1)=>              new Vector2().setAngle(rand(2*PI), length);\r\nconst randColor    = (cA = new Color, cB = new Color(0,0,0,1), linear)=>\r\n    linear ?  cA.lerp(cB, rand()) : new Color(rand(cA.r,cB.r),rand(cA.g,cB.g),rand(cA.b,cB.b),rand(cA.a,cB.a));\r\n\r\n// seeded random numbers - Xorshift\r\nlet randSeed       = 0;\r\nconst randSeeded   = (a=1, b=0)=> b + (a-b)* (Math.sin(++randSeed)**2 * 1e9 % 1);\r\n\r\n// create a 2d vector, can take another Vector2 to copy, 2 scalars, or 1 scalar\r\nconst vec2 = (x=0, y)=> x.x == undefined? new Vector2(x, y == undefined? x : y) : new Vector2(x.x, x.y);\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\nclass Vector2\r\n{\r\n    constructor(x=0, y=0) { this.x = x; this.y = y; }\r\n\r\n    // basic math operators, a vector or scaler can be passed in\r\n    copy()                { return new Vector2(this.x, this.y); }\r\n    scale(s)              { ASSERT(s.x==undefined); return new Vector2(this.x * s, this.y * s); }\r\n    add(v)                { ASSERT(v.x!=undefined); return new Vector2(this.x + v.x, this.y + v.y); }\r\n    subtract(v)           { ASSERT(v.x!=undefined); return new Vector2(this.x - v.x, this.y - v.y); }\r\n    multiply(v)           { ASSERT(v.x!=undefined); return new Vector2(this.x * v.x, this.y * v.y); }\r\n    divide(v)             { ASSERT(v.x!=undefined); return new Vector2(this.x / v.x, this.y / v.y); }\r\n\r\n    // vector math operators\r\n    length()              { return this.lengthSquared()**.5; }\r\n    lengthSquared()       { return this.x**2 + this.y**2; }\r\n    distance(p)           { return this.distanceSquared(p)**.5; }\r\n    distanceSquared(p)    { return (this.x - p.x)**2 + (this.y - p.y)**2; }\r\n    normalize(length=1)   { const l = this.length(); return l ? this.scale(length/l) : new Vector2(length); }\r\n    clampLength(length=1) { const l = this.length(); return l > length ? this.scale(length/l) : this; }\r\n    dot(v)                { ASSERT(v.x!=undefined); return this.x*v.x + this.y*v.y; }\r\n    cross(v)              { ASSERT(v.x!=undefined); return this.x*v.y - this.y*v.x; }\r\n    angle()               { return Math.atan2(this.x, this.y); }\r\n    setAngle(a, length=1) { this.x = length*Math.sin(a); this.y = length*Math.cos(a); return this; }\r\n    rotate(a)             { const c = Math.cos(a), s = Math.sin(a); return new Vector2(this.x*c-this.y*s, this.x*s+this.y*c); }\r\n    direction()           { return abs(this.x) > abs(this.y) ? this.x < 0 ? 3 : 1 : this.y < 0 ? 2 : 0; }\r\n    flip()                { return new Vector2(this.y, this.x); }\r\n    invert()              { return new Vector2(this.y, -this.x); }\r\n    round()               { return new Vector2(Math.round(this.x), Math.round(this.y)); }\r\n    lerp(v, p)            { ASSERT(v.x!=undefined); return this.add(v.subtract(this).scale(clamp(p))); }\r\n    int()                 { return new Vector2(this.x|0, this.y|0); }\r\n    area()                { return this.x * this.y; }\r\n    arrayCheck(arraySize) { return this.x >= 0 && this.y >= 0 && this.x < arraySize.x && this.y < arraySize.y; } \r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\nclass Color\r\n{\r\n    constructor(r=1, g=1, b=1, a=1) { this.r=r; this.g=g; this.b=b; this.a=a; }\r\n\r\n    copy(c)     { return new Color(this.r, this.g, this.b, this.a); }\r\n    add(c)      { return new Color(this.r+c.r, this.g+c.g, this.b+c.b, this.a+c.a); }\r\n    subtract(c) { return new Color(this.r-c.r, this.g-c.g, this.b-c.b, this.a-c.a); }\r\n    multiply(c) { return new Color(this.r*c.r, this.g*c.g, this.b*c.b, this.a*c.a); }\r\n    scale(s,a=s){ return new Color(this.r*s, this.g*s, this.b*s, this.a*a); }\r\n    clamp()     { return new Color(clamp(this.r), clamp(this.g), clamp(this.b), clamp(this.a)); }\r\n    lerp(c, p)  { return this.add(c.subtract(this).scale(clamp(p))); }\r\n    mutate(amount=.05, alphaAmount=0) \r\n    {\r\n        return new Color\r\n        (\r\n            this.r + rand(amount, -amount),\r\n            this.g + rand(amount, -amount),\r\n            this.b + rand(amount, -amount),\r\n            this.a + rand(alphaAmount, -alphaAmount)\r\n        ).clamp();\r\n    }\r\n    rgba()      \r\n    { \r\n        ASSERT(this.r>=0 && this.r<=1 && this.g>=0 && this.g<=1 && this.b>=0 && this.b<=1 && this.a>=0 && this.a<=1);\r\n        return `rgb(${this.r*255|0},${this.g*255|0},${this.b*255|0},${this.a})`; \r\n    }\r\n    rgbaInt()  \r\n    {\r\n        ASSERT(this.r>=0 && this.r<=1 && this.g>=0 && this.g<=1 && this.b>=0 && this.b<=1 && this.a>=0 && this.a<=1);\r\n        return (this.r*255|0) + (this.g*255<<8) + (this.b*255<<16) + (this.a*255<<24); \r\n    }\r\n    setHSLA(h=0, s=0, l=1, a=1)\r\n    {\r\n        const q = l < .5 ? l*(1+s) : l+s-l*s, p = 2*l-q,\r\n            f = (p, q, t)=>\r\n                (t = ((t%1)+1)%1) < 1/6 ? p+(q-p)*6*t :\r\n                t < 1/2 ? q :\r\n                t < 2/3 ? p+(q-p)*(2/3-t)*6 : p;\r\n                \r\n        this.r = f(p, q, h + 1/3);\r\n        this.g = f(p, q, h);\r\n        this.b = f(p, q, h - 1/3);\r\n        this.a = a;\r\n        return this;\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\nclass Timer\r\n{\r\n    constructor(timeLeft)   { this.time = timeLeft == undefined ? undefined : time + timeLeft; this.setTime = timeLeft; }\r\n\r\n    set(timeLeft=0) { this.time = time + timeLeft; this.setTime = timeLeft; }\r\n    unset()         { this.time = undefined; }\r\n    isSet()         { return this.time != undefined; }\r\n    active()        { return time <= this.time; }  // is set and has no time left\r\n    elapsed()       { return time >  this.time; }  // is set and has time left\r\n    get()           { return this.isSet()? time - this.time : 0; }\r\n    getPercent()    { return this.isSet()? percent(this.time - time, 0, this.setTime) : 0; }\r\n}"
  },
  {
    "path": "engine/engineWebGL.js",
    "content": "/*\r\n    LittleJS WebGL Interface\r\n    - All webgl used by the engine is wrapped up here\r\n    - Can be disabled with glEnable to revert to 2D canvas rendering\r\n    - Batches sprite rendering on GPU for incredibly fast performance\r\n    - Sprite transform math is done in the shader where possible\r\n    - For normal stuff you won't need to call any functions in this file\r\n    - For advanced stuff there are helper functions to create shaders, textures, etc\r\n*/\r\n\r\n'use strict';\r\n\r\nconst glEnable = 1;     // can run without gl (texured coloring will be disabled)\r\nlet glCanvas, glContext, glTileTexture, glShader, glPositionData, glColorData, \r\n    glBatchCount, glDirty, glAdditive, glShrinkTilesX, glShrinkTilesY, glOverlay;\r\n\r\nfunction glInit()\r\n{\r\n    if (!glEnable) return;\r\n\r\n    // create the canvas and tile texture\r\n    glCanvas = document.createElement('canvas');\r\n    glContext = glCanvas.getContext('webgl', {antialias:!pixelated});\r\n    glTileTexture = glCreateTexture(tileImage);\r\n    glShrinkTilesX = tileBleedShrinkFix/tileImageSize.x;\r\n    glShrinkTilesY = tileBleedShrinkFix/tileImageSize.y;\r\n\r\n    if (glOverlay)\r\n    {\r\n        // firefox is much faster without copying the gl buffer so we just overlay it with some tradeoffs\r\n        document.body.appendChild(glCanvas);\r\n        glCanvas.style = mainCanvas.style.cssText;\r\n    }\r\n\r\n    // setup vertex and fragment shaders\r\n    glShader = glCreateProgram(\r\n        'precision lowp float;'+    // use lowp for better performance\r\n        'uniform mat4 m;'+          // transform matrix\r\n        'attribute float a;'+       // angle\r\n        'attribute vec2 p,s,t;'+    // position, size, uv\r\n        'attribute vec4 c,b;'+      // color, additiveColor\r\n        'varying vec2 v;'+          // return uv\r\n        'varying vec4 d,e;'+        // return color, additiveColor\r\n        'void main(){'+             // shader entry point\r\n        'gl_Position=m*vec4((s*cos(-a)+vec2(-s.y,s.x)*sin(-a))*.5+p,1,1);'+// transform position\r\n        'v=t;d=c;e=b;'+             // pass stuff to fragment shader\r\n        '}'                         // end of shader\r\n        ,\r\n        'precision lowp float;'+             // use lowp for better performance\r\n        'varying vec2 v;'+                   // uv\r\n        'varying vec4 d,e;'+                 // color, additiveColor\r\n        'uniform sampler2D j;'+              // texture\r\n        'void main(){'+                      // shader entry point\r\n        'gl_FragColor=texture2D(j,v)*d+e;'+  // modulate texture by color plus additive\r\n        '}'                                  // end of shader\r\n    );\r\n\r\n    // init buffers\r\n    const glVertexData = new ArrayBuffer(MAX_BATCH * VERTICES_PER_QUAD * VERTEX_STRIDE);\r\n    glCreateBuffer(gl_ARRAY_BUFFER, glVertexData.byteLength, gl_DYNAMIC_DRAW);\r\n    glPositionData = new Float32Array(glVertexData);\r\n    glColorData = new Uint32Array(glVertexData);\r\n\r\n    // setup the vertex data array\r\n    const initVertexAttribArray = (name, type, typeSize, size, normalize=0)=>\r\n    {\r\n        const location = glContext.getAttribLocation(glShader, name);\r\n        glContext.enableVertexAttribArray(location);\r\n        glContext.vertexAttribPointer(location, size, type, normalize, VERTEX_STRIDE, offset);\r\n        offset += size*typeSize;\r\n    }\r\n    let offset = glDirty = glBatchCount = 0;\r\n    initVertexAttribArray('a', gl_FLOAT, 4, 1);            // angle\r\n    initVertexAttribArray('p', gl_FLOAT, 4, 2);            // position\r\n    initVertexAttribArray('s', gl_FLOAT, 4, 2);            // size\r\n    initVertexAttribArray('t', gl_FLOAT, 4, 2);            // texture coords\r\n    initVertexAttribArray('c', gl_UNSIGNED_BYTE, 1, 4, 1); // color\r\n    initVertexAttribArray('b', gl_UNSIGNED_BYTE, 1, 4, 1); // additiveColor\r\n\r\n    // use point filtering for pixelated rendering\r\n    glContext.texParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, pixelated ? gl_NEAREST : gl_LINEAR);\r\n    glContext.texParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, pixelated ? gl_NEAREST : gl_LINEAR);\r\n}\r\n\r\nfunction glSetBlendMode(additive)\r\n{\r\n    if (!glEnable) return;\r\n        \r\n    if (additive != glAdditive)\r\n        glFlush();\r\n\r\n    // setup blending\r\n    glAdditive = additive;\r\n\r\n    glContext.blendFunc(gl_SRC_ALPHA, additive ? gl_ONE : gl_ONE_MINUS_SRC_ALPHA)\r\n    /*glContext.blendFuncSeparate(\r\n        gl_SRC_ALPHA, additive ? gl_ONE : gl_ONE_MINUS_SRC_ALPHA, \r\n        gl_ONE,       additive ? gl_ONE : gl_ONE_MINUS_SRC_ALPHA);*/\r\n    glContext.enable(gl_BLEND);\r\n}\r\n\r\nfunction glCompileShader(source, type)\r\n{\r\n    if (!glEnable) return;\r\n\r\n    // build the shader\r\n    const shader = glContext.createShader(type);\r\n    glContext.shaderSource(shader, source);\r\n    glContext.compileShader(shader);\r\n\r\n    // check for errors\r\n    if (debug && !glContext.getShaderParameter(shader, gl_COMPILE_STATUS))\r\n        throw glContext.getShaderInfoLog(shader);\r\n    return shader;\r\n}\r\n\r\nfunction glCreateProgram(vsSource, fsSource)\r\n{\r\n    if (!glEnable) return;\r\n\r\n    // build the program\r\n    const program = glContext.createProgram();\r\n    glContext.attachShader(program, glCompileShader(vsSource, gl_VERTEX_SHADER));\r\n    glContext.attachShader(program, glCompileShader(fsSource, gl_FRAGMENT_SHADER));\r\n    glContext.linkProgram(program);\r\n\r\n    // check for errors\r\n    if (debug && !glContext.getProgramParameter(program, gl_LINK_STATUS))\r\n        throw glContext.getProgramInfoLog(program);\r\n    return program;\r\n}\r\n\r\nfunction glCreateBuffer(bufferType, size, usage)\r\n{\r\n    if (!glEnable) return;\r\n\r\n    // build the buffer\r\n    const buffer = glContext.createBuffer();\r\n    glContext.bindBuffer(bufferType, buffer);\r\n    glContext.bufferData(bufferType, size, usage);\r\n    return buffer;\r\n}\r\n\r\nfunction glCreateTexture(image)\r\n{\r\n    if (!glEnable) return;\r\n\r\n    // build the texture\r\n    const texture = glContext.createTexture();\r\n    glContext.bindTexture(gl_TEXTURE_2D, texture);\r\n    glContext.texImage2D(gl_TEXTURE_2D, 0, gl_RGBA, gl_RGBA, gl_UNSIGNED_BYTE, image);\r\n    return texture;\r\n}\r\n\r\nfunction glPreRender(width, height)\r\n{\r\n    if (!glEnable) return;\r\n\r\n    // clear and set to same size as main canvas\r\n    glCanvas.width = width;\r\n    glCanvas.height = height;\r\n    glContext.viewport(0, 0, width, height);\r\n\r\n    // set up the shader\r\n    glContext.useProgram(glShader);\r\n    glSetBlendMode();\r\n\r\n    // build the transform matrix\r\n    const sx = 2 * cameraScale / width;\r\n    const sy = 2 * cameraScale / height;\r\n    glContext.uniformMatrix4fv(glContext.getUniformLocation(glShader, 'm'), 0,\r\n        new Float32Array([\r\n            sx, 0, 0, 0,\r\n            0, sy, 0, 0,\r\n            1, 1, -1, 1,\r\n            -1-sx*cameraPos.x, -1-sy*cameraPos.y, 0, 0\r\n        ])\r\n    );\r\n}\r\n\r\nfunction glFlush()\r\n{\r\n    if (!glEnable) return;\r\n    if (!glBatchCount)\r\n        return;\r\n\r\n    // draw all the sprites in the batch and reset the buffer\r\n    glContext.bufferSubData(gl_ARRAY_BUFFER, 0, glPositionData.subarray(0, glBatchCount * VERTICES_PER_QUAD * VERTEX_STRIDE));\r\n    glContext.drawArrays(gl_TRIANGLES, 0, glBatchCount * VERTICES_PER_QUAD);\r\n    glBatchCount = 0;\r\n}\r\n\r\nfunction glCopyToContext(context, forceDraw)\r\n{\r\n    if (!glEnable) return;\r\n    if (!glDirty)  return;\r\n    \r\n    // draw any sprites still in the buffer, copy to main canvas and clear\r\n    glFlush();\r\n\r\n    if (!glOverlay || forceDraw)\r\n    {\r\n        // do not draw/clear in overlay mode because the canvas is visible\r\n        context.drawImage(glCanvas, 0, glAdditive = glDirty = 0);\r\n        glContext.clear(gl_COLOR_BUFFER_BIT);\r\n    }\r\n}\r\n\r\nfunction glDraw(x, y, sizeX, sizeY, angle, mirror, uv0X, uv0Y, uv1X, uv1Y, abgr, abgrAdditive)\r\n{\r\n    if (!glEnable) return;\r\n    \r\n    // flush if there is no room for more verts\r\n    if (glBatchCount >= MAX_BATCH)\r\n        glFlush();\r\n\r\n    if (tileBleedShrinkFix)\r\n    {\r\n        // shrink tiles to prevent bleeding\r\n        uv0X += glShrinkTilesX;\r\n        uv0Y += glShrinkTilesY;\r\n        uv1X -= glShrinkTilesX;\r\n        uv1Y -= glShrinkTilesY;\r\n    }\r\n    \r\n    // setup 2 triangles to form a quad\r\n    let offset = glBatchCount++ * VERTICES_PER_QUAD * INDICIES_PER_VERT - 1;\r\n    sizeX = mirror ? -sizeX : sizeX;\r\n    glDirty = 1;\r\n\r\n    // vertex 0\r\n    glPositionData[++offset] = angle;\r\n    glPositionData[++offset] = x;\r\n    glPositionData[++offset] = y;\r\n    glPositionData[++offset] = -sizeX;\r\n    glPositionData[++offset] = -sizeY;\r\n    glPositionData[++offset] = uv0X;\r\n    glPositionData[++offset] = uv1Y;\r\n    glColorData[++offset] = abgr;\r\n    glColorData[++offset] = abgrAdditive;\r\n    \r\n    // vertex 1\r\n    glPositionData[++offset] = angle;\r\n    glPositionData[++offset] = x;\r\n    glPositionData[++offset] = y;\r\n    glPositionData[++offset] = sizeX;\r\n    glPositionData[++offset] = sizeY;\r\n    glPositionData[++offset] = uv1X;\r\n    glPositionData[++offset] = uv0Y;\r\n    glColorData[++offset] = abgr;\r\n    glColorData[++offset] = abgrAdditive;\r\n    \r\n    // vertex 2\r\n    glPositionData[++offset] = angle;\r\n    glPositionData[++offset] = x;\r\n    glPositionData[++offset] = y;\r\n    glPositionData[++offset] = -sizeX;\r\n    glPositionData[++offset] = sizeY;\r\n    glPositionData[++offset] = uv0X;\r\n    glPositionData[++offset] = uv0Y;\r\n    glColorData[++offset] = abgr;\r\n    glColorData[++offset] = abgrAdditive;\r\n    \r\n    // vertex 0\r\n    glPositionData[++offset] = angle;\r\n    glPositionData[++offset] = x;\r\n    glPositionData[++offset] = y;\r\n    glPositionData[++offset] = -sizeX;\r\n    glPositionData[++offset] = -sizeY;\r\n    glPositionData[++offset] = uv0X;\r\n    glPositionData[++offset] = uv1Y;\r\n    glColorData[++offset] = abgr;\r\n    glColorData[++offset] = abgrAdditive;\r\n\r\n    // vertex 3\r\n    glPositionData[++offset] = angle;\r\n    glPositionData[++offset] = x;\r\n    glPositionData[++offset] = y;\r\n    glPositionData[++offset] = sizeX;\r\n    glPositionData[++offset] = -sizeY;\r\n    glPositionData[++offset] = uv1X;\r\n    glPositionData[++offset] = uv1Y;\r\n    glColorData[++offset] = abgr;\r\n    glColorData[++offset] = abgrAdditive;\r\n\r\n    // vertex 1\r\n    glPositionData[++offset] = angle;\r\n    glPositionData[++offset] = x;\r\n    glPositionData[++offset] = y;\r\n    glPositionData[++offset] = sizeX;\r\n    glPositionData[++offset] = sizeY;\r\n    glPositionData[++offset] = uv1X;\r\n    glPositionData[++offset] = uv0Y;\r\n    glColorData[++offset] = abgr;\r\n    glColorData[++offset] = abgrAdditive;\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// store gl constants as integers so their name doesn't use space in minifed\r\nconst \r\ngl_ONE = 1,\r\ngl_TRIANGLES = 4,\r\ngl_SRC_ALPHA = 770,\r\ngl_ONE_MINUS_SRC_ALPHA = 771,\r\ngl_BLEND = 3042,\r\ngl_TEXTURE_2D = 3553,\r\ngl_UNSIGNED_BYTE = 5121,\r\ngl_FLOAT = 5126,\r\ngl_RGBA = 6408,\r\ngl_NEAREST = 9728,\r\ngl_LINEAR = 9729,\r\ngl_TEXTURE_MAG_FILTER = 10240,\r\ngl_TEXTURE_MIN_FILTER = 10241,\r\ngl_COLOR_BUFFER_BIT = 16384,\r\ngl_ARRAY_BUFFER = 34962,\r\ngl_DYNAMIC_DRAW = 35048,\r\ngl_FRAGMENT_SHADER = 35632, \r\ngl_VERTEX_SHADER = 35633,\r\ngl_COMPILE_STATUS = 35713,\r\ngl_LINK_STATUS = 35714,\r\n\r\n// constants for batch rendering\r\nVERTICES_PER_QUAD = 6,\r\nINDICIES_PER_VERT = 9,\r\nMAX_BATCH = 1<<16,\r\nVERTEX_STRIDE = 4 + (4 * 2) * 3 + (4) * 2; // float + vec2 * 3 + (char * 4) * 2"
  },
  {
    "path": "index.html",
    "content": "<head>\r\n<title>Space Huggers</title>\r\n<link rel=icon type=image/x-icon href='favicon.ico'/>\r\n<meta name=\"title\" content=\"Space Huggers\"></meta>\r\n<meta name=\"author\" content=\"Frank Force\"></meta>\r\n<meta name=\"description\" content=\"A run and gun roguelike platformer with destructible environments\"></meta>\r\n<meta name=viewport content='width=device-width,initial-scale=1,user-scalable=0'>\r\n<meta charset=utf-8>\r\n</head>\r\n<body>\r\n<script src=engine/engineUtil.js></script>\r\n<script src=engine/engineDebug.js></script>\r\n<script src=engine/engine.js></script>\r\n<script src=engine/engineObject.js></script>\r\n<script src=engine/engineWebGL.js></script>\r\n<script src=engine/engineDraw.js></script>\r\n<script src=engine/engineInput.js></script>\r\n<script src=engine/engineAudio.js></script>\r\n<script src=engine/engineTileLayer.js></script>\r\n<script src=engine/engineParticle.js></script>\r\n<script src=appObjects.js></script>\r\n<script src=appCharacters.js></script>\r\n<script src=appEffects.js></script>\r\n<script src=appLevel.js></script>\r\n<script src=app.js></script>"
  }
]