diff options
58 files changed, 10395 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b51d381 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.mp3 +*.ogg +*.tmx +*.aseprite +*.log
\ No newline at end of file @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>.
\ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..283bde6 --- /dev/null +++ b/README.md @@ -0,0 +1,20 @@ +## Your Enemy is in Another Dungeon + +Source code of my ```LÖVE Jam 2022``` entry. + +This game is written in lua and LÖVE 2D framework. You may need LÖVE 2D installed to run. + +### Libraries Used +- [anim8](https://github.com/kikito/anim8) +- [hump](https://github.com/vrld/hump) +- [moonshine](https://github.com/vrld/moonshine) +- [o-ten-one](https://github.com/love2d-community/splashes) +- [sti](https://github.com/karai17/Simple-Tiled-Implementation) +- [windfield](https://github.com/a327ex/windfield) + + +Also few assets are deliberately not included due to license. + +Distributed under GPL 3.0. + +```Indrajith K L, 2022```
\ No newline at end of file diff --git a/assets/fonts/minecraftia.ttf b/assets/fonts/minecraftia.ttf Binary files differnew file mode 100644 index 0000000..7247ad7 --- /dev/null +++ b/assets/fonts/minecraftia.ttf diff --git a/assets/images/main_menu_title.png b/assets/images/main_menu_title.png Binary files differnew file mode 100644 index 0000000..59d6e56 --- /dev/null +++ b/assets/images/main_menu_title.png diff --git a/assets/images/particle.png b/assets/images/particle.png Binary files differnew file mode 100644 index 0000000..e8b825e --- /dev/null +++ b/assets/images/particle.png diff --git a/assets/images/tileset.png b/assets/images/tileset.png Binary files differnew file mode 100644 index 0000000..888d549 --- /dev/null +++ b/assets/images/tileset.png diff --git a/assets/maps/level1.lua b/assets/maps/level1.lua new file mode 100644 index 0000000..ffcb4eb --- /dev/null +++ b/assets/maps/level1.lua @@ -0,0 +1,107 @@ +return { + version = "1.5", + luaversion = "5.1", + tiledversion = "1.8.2", + orientation = "orthogonal", + renderorder = "right-down", + width = 16, + height = 16, + tilewidth = 16, + tileheight = 16, + nextlayerid = 3, + nextobjectid = 2, + properties = {}, + tilesets = { + { + name = "tileset", + firstgid = 1, + tilewidth = 16, + tileheight = 16, + spacing = 0, + margin = 0, + columns = 32, + image = "../images/tileset.png", + imagewidth = 512, + imageheight = 512, + objectalignment = "unspecified", + tileoffset = { + x = 0, + y = 0 + }, + grid = { + orientation = "orthogonal", + width = 16, + height = 16 + }, + properties = {}, + wangsets = {}, + tilecount = 1024, + tiles = {} + } + }, + layers = { + { + type = "tilelayer", + x = 0, + y = 0, + width = 16, + height = 16, + id = 1, + name = "ground", + visible = true, + opacity = 1, + offsetx = 0, + offsety = 0, + parallaxx = 1, + parallaxy = 1, + properties = {}, + encoding = "lua", + data = { + 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, + 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, + 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, + 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, + 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, + 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0 + } + }, + { + type = "objectgroup", + draworder = "topdown", + id = 2, + name = "entities", + visible = true, + opacity = 1, + offsetx = 0, + offsety = 0, + parallaxx = 1, + parallaxy = 1, + properties = {}, + objects = { + { + id = 1, + name = "player", + type = "entity", + shape = "rectangle", + x = 14.6667, + y = 13.3333, + width = 0, + height = 0, + rotation = 0, + visible = true, + properties = {} + } + } + } + } +} diff --git a/assets/music/credits.txt b/assets/music/credits.txt new file mode 100644 index 0000000..d6b920e --- /dev/null +++ b/assets/music/credits.txt @@ -0,0 +1,3 @@ +Stevia Sphere + +https://steviasphere.bandcamp.com/album/drum-machine-dreams-single diff --git a/conf.lua b/conf.lua new file mode 100644 index 0000000..1ae0863 --- /dev/null +++ b/conf.lua @@ -0,0 +1,7 @@ +function love.conf(t) + t.window.width = 800 + t.window.height = 600 + t.window.fullscreen = false + t.window.title = "<Your Enemy is in Another Dungeon>" + t.window.usedpiscale = true +end
\ No newline at end of file diff --git a/entities/player.lua b/entities/player.lua new file mode 100644 index 0000000..cfb3d15 --- /dev/null +++ b/entities/player.lua @@ -0,0 +1,9 @@ +local Class = require("libs.hump.class"); + +Player = Class{ + init = function(self) + print("Player Init") + end +} + +return Player
\ No newline at end of file diff --git a/libs/anim8 b/libs/anim8 new file mode 160000 +Subproject bd38defa844ab2dfa3bf416a10c45ce376ba4c5 diff --git a/libs/hump/camera.lua b/libs/hump/camera.lua new file mode 100644 index 0000000..cb86a79 --- /dev/null +++ b/libs/hump/camera.lua @@ -0,0 +1,216 @@ +--[[ +Copyright (c) 2010-2015 Matthias Richter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +Except as contained in this notice, the name(s) of the above copyright holders +shall not be used in advertising or otherwise to promote the sale, use or +other dealings in this Software without prior written authorization. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +]]-- + +local _PATH = (...):match('^(.*[%./])[^%.%/]+$') or '' +local cos, sin = math.cos, math.sin + +local camera = {} +camera.__index = camera + +-- Movement interpolators (for camera locking/windowing) +camera.smooth = {} + +function camera.smooth.none() + return function(dx,dy) return dx,dy end +end + +function camera.smooth.linear(speed) + assert(type(speed) == "number", "Invalid parameter: speed = "..tostring(speed)) + return function(dx,dy, s) + -- normalize direction + local d = math.sqrt(dx*dx+dy*dy) + local dts = math.min((s or speed) * love.timer.getDelta(), d) -- prevent overshooting the goal + if d > 0 then + dx,dy = dx/d, dy/d + end + + return dx*dts, dy*dts + end +end + +function camera.smooth.damped(stiffness) + assert(type(stiffness) == "number", "Invalid parameter: stiffness = "..tostring(stiffness)) + return function(dx,dy, s) + local dts = love.timer.getDelta() * (s or stiffness) + return dx*dts, dy*dts + end +end + + +local function new(x,y, zoom, rot, smoother) + x,y = x or love.graphics.getWidth()/2, y or love.graphics.getHeight()/2 + zoom = zoom or 1 + rot = rot or 0 + smoother = smoother or camera.smooth.none() -- for locking, see below + return setmetatable({x = x, y = y, scale = zoom, rot = rot, smoother = smoother}, camera) +end + +function camera:lookAt(x,y) + self.x, self.y = x, y + return self +end + +function camera:move(dx,dy) + self.x, self.y = self.x + dx, self.y + dy + return self +end + +function camera:position() + return self.x, self.y +end + +function camera:rotate(phi) + self.rot = self.rot + phi + return self +end + +function camera:rotateTo(phi) + self.rot = phi + return self +end + +function camera:zoom(mul) + self.scale = self.scale * mul + return self +end + +function camera:zoomTo(zoom) + self.scale = zoom + return self +end + +function camera:attach(x,y,w,h, noclip) + x,y = x or 0, y or 0 + w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight() + + self._sx,self._sy,self._sw,self._sh = love.graphics.getScissor() + if not noclip then + love.graphics.setScissor(x,y,w,h) + end + + local cx,cy = x+w/2, y+h/2 + love.graphics.push() + love.graphics.translate(cx, cy) + love.graphics.scale(self.scale) + love.graphics.rotate(self.rot) + love.graphics.translate(-self.x, -self.y) +end + +function camera:detach() + love.graphics.pop() + love.graphics.setScissor(self._sx,self._sy,self._sw,self._sh) +end + +function camera:draw(...) + local x,y,w,h,noclip,func + local nargs = select("#", ...) + if nargs == 1 then + func = ... + elseif nargs == 5 then + x,y,w,h,func = ... + elseif nargs == 6 then + x,y,w,h,noclip,func = ... + else + error("Invalid arguments to camera:draw()") + end + + self:attach(x,y,w,h,noclip) + func() + self:detach() +end + +-- world coordinates to camera coordinates +function camera:cameraCoords(x,y, ox,oy,w,h) + ox, oy = ox or 0, oy or 0 + w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight() + + -- x,y = ((x,y) - (self.x, self.y)):rotated(self.rot) * self.scale + center + local c,s = cos(self.rot), sin(self.rot) + x,y = x - self.x, y - self.y + x,y = c*x - s*y, s*x + c*y + return x*self.scale + w/2 + ox, y*self.scale + h/2 + oy +end + +-- camera coordinates to world coordinates +function camera:worldCoords(x,y, ox,oy,w,h) + ox, oy = ox or 0, oy or 0 + w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight() + + -- x,y = (((x,y) - center) / self.scale):rotated(-self.rot) + (self.x,self.y) + local c,s = cos(-self.rot), sin(-self.rot) + x,y = (x - w/2 - ox) / self.scale, (y - h/2 - oy) / self.scale + x,y = c*x - s*y, s*x + c*y + return x+self.x, y+self.y +end + +function camera:mousePosition(ox,oy,w,h) + local mx,my = love.mouse.getPosition() + return self:worldCoords(mx,my, ox,oy,w,h) +end + +-- camera scrolling utilities +function camera:lockX(x, smoother, ...) + local dx, dy = (smoother or self.smoother)(x - self.x, self.y, ...) + self.x = self.x + dx + return self +end + +function camera:lockY(y, smoother, ...) + local dx, dy = (smoother or self.smoother)(self.x, y - self.y, ...) + self.y = self.y + dy + return self +end + +function camera:lockPosition(x,y, smoother, ...) + return self:move((smoother or self.smoother)(x - self.x, y - self.y, ...)) +end + +function camera:lockWindow(x, y, x_min, x_max, y_min, y_max, smoother, ...) + -- figure out displacement in camera coordinates + x,y = self:cameraCoords(x,y) + local dx, dy = 0,0 + if x < x_min then + dx = x - x_min + elseif x > x_max then + dx = x - x_max + end + if y < y_min then + dy = y - y_min + elseif y > y_max then + dy = y - y_max + end + + -- transform displacement to movement in world coordinates + local c,s = cos(-self.rot), sin(-self.rot) + dx,dy = (c*dx - s*dy) / self.scale, (s*dx + c*dy) / self.scale + + -- move + self:move((smoother or self.smoother)(dx,dy,...)) +end + +-- the module +return setmetatable({new = new, smooth = camera.smooth}, + {__call = function(_, ...) return new(...) end}) diff --git a/libs/hump/class.lua b/libs/hump/class.lua new file mode 100644 index 0000000..7d62707 --- /dev/null +++ b/libs/hump/class.lua @@ -0,0 +1,98 @@ +--[[ +Copyright (c) 2010-2013 Matthias Richter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +Except as contained in this notice, the name(s) of the above copyright holders +shall not be used in advertising or otherwise to promote the sale, use or +other dealings in this Software without prior written authorization. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +]]-- + +local function include_helper(to, from, seen) + if from == nil then + return to + elseif type(from) ~= 'table' then + return from + elseif seen[from] then + return seen[from] + end + + seen[from] = to + for k,v in pairs(from) do + k = include_helper({}, k, seen) -- keys might also be tables + if to[k] == nil then + to[k] = include_helper({}, v, seen) + end + end + return to +end + +-- deeply copies `other' into `class'. keys in `other' that are already +-- defined in `class' are omitted +local function include(class, other) + return include_helper(class, other, {}) +end + +-- returns a deep copy of `other' +local function clone(other) + return setmetatable(include({}, other), getmetatable(other)) +end + +local function new(class) + -- mixins + class = class or {} -- class can be nil + local inc = class.__includes or {} + if getmetatable(inc) then inc = {inc} end + + for _, other in ipairs(inc) do + if type(other) == "string" then + other = _G[other] + end + include(class, other) + end + + -- class implementation + class.__index = class + class.init = class.init or class[1] or function() end + class.include = class.include or include + class.clone = class.clone or clone + + -- constructor call + return setmetatable(class, {__call = function(c, ...) + local o = setmetatable({}, c) + o:init(...) + return o + end}) +end + +-- interface for cross class-system compatibility (see https://github.com/bartbes/Class-Commons). +if class_commons ~= false and not common then + common = {} + function common.class(name, prototype, parent) + return new{__includes = {prototype, parent}} + end + function common.instance(class, ...) + return class(...) + end +end + + +-- the module +return setmetatable({new = new, include = include, clone = clone}, + {__call = function(_,...) return new(...) end}) diff --git a/libs/hump/gamestate.lua b/libs/hump/gamestate.lua new file mode 100644 index 0000000..059dbb9 --- /dev/null +++ b/libs/hump/gamestate.lua @@ -0,0 +1,116 @@ +--[[ +Copyright (c) 2010-2013 Matthias Richter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +Except as contained in this notice, the name(s) of the above copyright holders +shall not be used in advertising or otherwise to promote the sale, use or +other dealings in this Software without prior written authorization. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +]]-- + +local function __NULL__() end + + -- default gamestate produces error on every callback +local state_init = setmetatable({leave = __NULL__}, + {__index = function() error("Gamestate not initialized. Use Gamestate.switch()") end}) +local stack = {state_init} +local initialized_states = setmetatable({}, {__mode = "k"}) +local state_is_dirty = true + +local GS = {} +function GS.new(t) return t or {} end -- constructor - deprecated! + +local function change_state(stack_offset, to, ...) + local pre = stack[#stack] + + -- initialize only on first call + ;(initialized_states[to] or to.init or __NULL__)(to) + initialized_states[to] = __NULL__ + + stack[#stack+stack_offset] = to + state_is_dirty = true + return (to.enter or __NULL__)(to, pre, ...) +end + +function GS.switch(to, ...) + assert(to, "Missing argument: Gamestate to switch to") + assert(to ~= GS, "Can't call switch with colon operator") + ;(stack[#stack].leave or __NULL__)(stack[#stack]) + return change_state(0, to, ...) +end + +function GS.push(to, ...) + assert(to, "Missing argument: Gamestate to switch to") + assert(to ~= GS, "Can't call push with colon operator") + return change_state(1, to, ...) +end + +function GS.pop(...) + assert(#stack > 1, "No more states to pop!") + local pre, to = stack[#stack], stack[#stack-1] + stack[#stack] = nil + ;(pre.leave or __NULL__)(pre) + state_is_dirty = true + return (to.resume or __NULL__)(to, pre, ...) +end + +function GS.current() + return stack[#stack] +end + +-- XXX: don't overwrite love.errorhandler by default: +-- this callback is different than the other callbacks +-- (see http://love2d.org/wiki/love.errorhandler) +-- overwriting thi callback can result in random crashes (issue #95) +local all_callbacks = { 'draw', 'update' } + +-- fetch event callbacks from love.handlers +for k in pairs(love.handlers) do + all_callbacks[#all_callbacks+1] = k +end + +function GS.registerEvents(callbacks) + local registry = {} + callbacks = callbacks or all_callbacks + for _, f in ipairs(callbacks) do + registry[f] = love[f] or __NULL__ + love[f] = function(...) + registry[f](...) + return GS[f](...) + end + end +end + +local function_cache = {} + +-- forward any undefined functions +setmetatable(GS, {__index = function(_, func) + -- call function only if at least one 'update' was called beforehand + -- (see issue #46) + if not state_is_dirty or func == 'update' then + state_is_dirty = false + function_cache[func] = function_cache[func] or function(...) + return (stack[#stack][func] or __NULL__)(stack[#stack], ...) + end + return function_cache[func] + end + return __NULL__ +end}) + +return GS diff --git a/libs/hump/timer.lua b/libs/hump/timer.lua new file mode 100644 index 0000000..8315f68 --- /dev/null +++ b/libs/hump/timer.lua @@ -0,0 +1,215 @@ +--[[ +Copyright (c) 2010-2013 Matthias Richter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +Except as contained in this notice, the name(s) of the above copyright holders +shall not be used in advertising or otherwise to promote the sale, use or +other dealings in this Software without prior written authorization. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +]]-- + +local Timer = {} +Timer.__index = Timer + +local function _nothing_() end + +local function updateTimerHandle(handle, dt) + -- handle: { + -- time = <number>, + -- after = <function>, + -- during = <function>, + -- limit = <number>, + -- count = <number>, + -- } + handle.time = handle.time + dt + handle.during(dt, math.max(handle.limit - handle.time, 0)) + + while handle.time >= handle.limit and handle.count > 0 do + if handle.after(handle.after) == false then + handle.count = 0 + break + end + handle.time = handle.time - handle.limit + handle.count = handle.count - 1 + end +end + +function Timer:update(dt) + -- timers may create new timers, which leads to undefined behavior + -- in pairs() - so we need to put them in a different table first + local to_update = {} + for handle in pairs(self.functions) do + to_update[handle] = handle + end + + for handle in pairs(to_update) do + if self.functions[handle] then + updateTimerHandle(handle, dt) + if handle.count == 0 then + self.functions[handle] = nil + end + end + end +end + +function Timer:during(delay, during, after) + local handle = { time = 0, during = during, after = after or _nothing_, limit = delay, count = 1 } + self.functions[handle] = true + return handle +end + +function Timer:after(delay, func) + return self:during(delay, _nothing_, func) +end + +function Timer:every(delay, after, count) + local count = count or math.huge -- exploit below: math.huge - 1 = math.huge + local handle = { time = 0, during = _nothing_, after = after, limit = delay, count = count } + self.functions[handle] = true + return handle +end + +function Timer:cancel(handle) + self.functions[handle] = nil +end + +function Timer:clear() + self.functions = {} +end + +function Timer:script(f) + local co = coroutine.wrap(f) + co(function(t) + self:after(t, co) + coroutine.yield() + end) +end + +Timer.tween = setmetatable({ + -- helper functions + out = function(f) -- 'rotates' a function + return function(s, ...) return 1 - f(1-s, ...) end + end, + chain = function(f1, f2) -- concatenates two functions + return function(s, ...) return (s < .5 and f1(2*s, ...) or 1 + f2(2*s-1, ...)) * .5 end + end, + + -- useful tweening functions + linear = function(s) return s end, + quad = function(s) return s*s end, + cubic = function(s) return s*s*s end, + quart = function(s) return s*s*s*s end, + quint = function(s) return s*s*s*s*s end, + sine = function(s) return 1-math.cos(s*math.pi/2) end, + expo = function(s) return 2^(10*(s-1)) end, + circ = function(s) return 1 - math.sqrt(1-s*s) end, + + back = function(s,bounciness) + bounciness = bounciness or 1.70158 + return s*s*((bounciness+1)*s - bounciness) + end, + + bounce = function(s) -- magic numbers ahead + local a,b = 7.5625, 1/2.75 + return math.min(a*s^2, a*(s-1.5*b)^2 + .75, a*(s-2.25*b)^2 + .9375, a*(s-2.625*b)^2 + .984375) + end, + + elastic = function(s, amp, period) + amp, period = amp and math.max(1, amp) or 1, period or .3 + return (-amp * math.sin(2*math.pi/period * (s-1) - math.asin(1/amp))) * 2^(10*(s-1)) + end, +}, { + +-- register new tween +__call = function(tween, self, len, subject, target, method, after, ...) + -- recursively collects fields that are defined in both subject and target into a flat list + local function tween_collect_payload(subject, target, out) + for k,v in pairs(target) do + local ref = subject[k] + assert(type(v) == type(ref), 'Type mismatch in field "'..k..'".') + if type(v) == 'table' then + tween_collect_payload(ref, v, out) + else + local ok, delta = pcall(function() return (v-ref)*1 end) + assert(ok, 'Field "'..k..'" does not support arithmetic operations') + out[#out+1] = {subject, k, delta} + end + end + return out + end + + method = tween[method or 'linear'] -- see __index + local payload, t, args = tween_collect_payload(subject, target, {}), 0, {...} + + local last_s = 0 + return self:during(len, function(dt) + t = t + dt + local s = method(math.min(1, t/len), unpack(args)) + local ds = s - last_s + last_s = s + for _, info in ipairs(payload) do + local ref, key, delta = unpack(info) + ref[key] = ref[key] + delta * ds + end + end, after) +end, + +-- fetches function and generated compositions for method `key` +__index = function(tweens, key) + if type(key) == 'function' then return key end + + assert(type(key) == 'string', 'Method must be function or string.') + if rawget(tweens, key) then return rawget(tweens, key) end + + local function construct(pattern, f) + local method = rawget(tweens, key:match(pattern)) + if method then return f(method) end + return nil + end + + local out, chain = rawget(tweens,'out'), rawget(tweens,'chain') + return construct('^in%-([^-]+)$', function(...) return ... end) + or construct('^out%-([^-]+)$', out) + or construct('^in%-out%-([^-]+)$', function(f) return chain(f, out(f)) end) + or construct('^out%-in%-([^-]+)$', function(f) return chain(out(f), f) end) + or error('Unknown interpolation method: ' .. key) +end}) + +-- Timer instancing +function Timer.new() + return setmetatable({functions = {}, tween = Timer.tween}, Timer) +end + +-- default instance +local default = Timer.new() + +-- module forwards calls to default instance +local module = {} +for k in pairs(Timer) do + if k ~= "__index" then + module[k] = function(...) return default[k](default, ...) end + end +end +module.tween = setmetatable({}, { + __index = Timer.tween, + __newindex = function(k,v) Timer.tween[k] = v end, + __call = function(t, ...) return default:tween(...) end, +}) + +return setmetatable(module, {__call = Timer.new}) diff --git a/libs/moonshine/README.md b/libs/moonshine/README.md new file mode 100644 index 0000000..062937a --- /dev/null +++ b/libs/moonshine/README.md @@ -0,0 +1,580 @@ +# moonshine + +Chainable post-processing shaders for LÖVE. + +## Overview + +* [Getting started](#getting-started) +* [General usage](#general-usage) +* [List of effects](#list-of-effects) +* [Writing effects](#writing-effects) +* [License](#license) + +<a name="getting-started"></a> +## Getting started + +Clone this repository into your game folder: + + git clone https://github.com/vrld/moonshine.git + +This will create the folder `moonshine`. + +In your `main.lua`, or wherever you load your libraries, add the following: + +```lua +local moonshine = require 'moonshine' +``` + +Create and parametrize the post-processing effect in `love.load()`, for example: + +```lua +function love.load() + effect = moonshine(moonshine.effects.filmgrain) + .chain(moonshine.effects.vignette) + effect.filmgrain.size = 2 +end +``` + +Lastly, wrap the things you want to be drawn with the effect inside a function: + +```lua +function love.draw() + effect(function() + love.graphics.rectangle("fill", 300,200, 200,200) + end) +end +``` + +When you package your game for release, you might want consider deleting the +(hidden) `.git` folder in the moonshine directory. + + +<a name="general-usage"></a> +## General usage + +The main concept behind moonshine are chains. A chain consists of one or more +effects. Effects that come later in the chain will be applied to the result of +the effects that come before. In the example above, the vignette is drawn on +top of the filmgrain. + +### Chains + +Chains are created using the `moonshine.chain` function: + +```lua +chain = moonshine.chain(effect) +``` + +For convenience, `moonshine(effect)` is an alias to `moonshine.chain(effect)`. +You can add new effects to a chain using + +```lua +chain = chain.chain(another_effect) +``` + +or using `chain.next()`, which is an alias to `chain.chain()`. +As the function returns the chain, you can specify your whole chain in one go, +as shown in the example above. + +### Effects and effect parameters + +The effects that come bundled with moonshine (see [List of effects](#list-of-effects)) +are accessed by `chain.effects.<effect-name>`, e.g., + +```lua +moonshine.effects.glow +``` + +Most effects are parametrized to change how they look. In the example above, +the size of the grains was set to 2 pixels (the default is 1 pixel). +Effect parameters are set by first specifying the name of the effect and then +the name of the parameter: + +```lua +chain.<effect>.<parameter> = <value> +``` + +For example, if `chain` contained the `glow` and `crt` effects, you can set the +glow `strength` parameter and crt `distortionFactor` parameter as such: + +```lua +chain.glow.strength = 10 +chain.crt.distortionFactor = {1.06, 1.065} +``` + +Because you likely initialize a bunch of parameters at once, you can set all +parameters with the special key `parameters` (or `params` or `settings`). This +is equivalent to the above: + +```lua +chain.parameters = { + glow = {strength = 10}, + crt = {distortionFactor = {1.06, 1.065}}, +} +``` + +Note that this will only set the parameters specified in the table. The crt +parameter `feather`, for example, will be left untouched. + +### Drawing effects + +Creating effects and setting parameters is fine, but not very useful on its +own. You also need to apply it to something. This is done using `chain.draw()`: + +```lua +chain.draw(func, ...) +``` + +This will apply the effect to everything that is drawn inside `func(...)`. +Everything that is drawn outside of `func(...)` will not be affected. For +example, + +```lua +love.graphics.draw(img1, 0,0) +chain.draw(function() + love.graphics.draw(img2, 200,0) +end) +love.graphics.draw(img3, 400,0) +``` + +will apply the effect to `img2`, but not to `img1` and `img3`. Note that some +effects (like filmgrain) draw on the whole screen. So if in this example `chain` +would consist of a gaussianblur and filmgrain effect, `img1` will be covered +with grain, but will not be blurred, `img2` will get both effects, and `img3` +will be left untouched. + +Similar to chain creation, `chain(func, ...)` is an alias to the more verbose +`chain.draw(func, ...)`. + +### Temporarily disabling effects + +You can disable effects in a chain by using `chain.disable(names...)` and +`chain.enable(names...)`. +For example, + +```lua +effect = moonshine(moonshine.effects.boxblur) + .chain(moonshine.effects.filmgrain) + .chain(moonshine.effects.vignette) +effect.disable("boxblur", "filmgrain") +effect.enable("filmgrain") +``` + +would first disable the boxblur and filmgrain effect, and then enable the +filmgrain again. +Note that the effects are still in the chain, they are only not drawn. + +### Canvas size + +You can change the size of the internal canvas, for example when the window was +resized, by calling `chain.resize(width, height)`. +Do this anytime you want, but best not during `chain.draw()`. + +You can also specify the initial canvas size by starting the chain like this: + +```lua +effect = moonshine(400,300, moonshine.effects.vignette) +``` + +That is, you specify the width and height before the first effect in the chain. + +### Is this efficient? + +Of course, using moonshine is not as efficient as writing your own shader that +does all the effects you want in the least amount of passes, but moonshine +tries to minimize the overhead. + +On the other hand, you don't waste time writing the same shader over and over +again when using moonshine: You're trading a small amount of computation time +for a large amount of development time. + + +<a name="list-of-effects"></a> +## List of effects + +Currently, moonshine contains the following effects (in alphabetical order): + +* [boxblur](#effect-boxblur): simple blurring +* [chromasep](#effect-chromasep): cheap/fake chromatic aberration +* [colorgradesimple](#effect-colorgradesimple): weighting of color channels +* [crt](#effect-crt): crt/barrel distortion +* [desaturate](#effect-desaturate): desaturation and tinting +* [dmg](#effect-dmg): Gameboy and other four color palettes +* [fastgaussianblur](#effect-fastgaussianblur): faster Gaussian blurring +* [filmgrain](#effect-filmgrain): image noise +* [gaussianblur](#effect-gaussianblur): Gaussian blurring +* [glow](#effect-glow): aka (light bloom +* [godsray](#effect-godsray): aka light scattering +* [pixelate](#effect-pixelate): sub-sampling (for that indie look) +* [posterize](#effect-posterize): restrict number of colors +* [scanlines](#effect-scanlines): horizontal lines +* [sketch](#effect-sketch): simulate pencil drawings +* [vignette](#effect-vignette): shadow in the corners + + +<a name="effect-boxblur"></a> +### boxblur + +```lua +moonshine.effects.boxblur +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +radius | number or table of numbers | {3,3} +radius_x | number | 3 +radius_y | number | 3 + + +<a name="effect-chromasep"></a> +### chromasep + +```lua +moonshine.effects.chromasep +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +angle | number (in radians) | 0 +radius | number | 0 + + +<a name="effect-colorgradesimple"></a> +### colorgradesimple + +```lua +moonshine.effects.colorgradesimple +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +factors | table of numbers | {1,1,1} + + +<a name="effect-crt"></a> +### crt + +```lua +moonshine.effects.crt +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +distortionFactor | table of numbers | {1.06, 1.065} +x | number | 1.06 +y | number | 1.065 +scaleFactor | number or table of numbers | {1,1} +feather | number | 0.02 + + +<a name="effect-desaturate"></a> +### desaturate + +```lua +moonshine.effects.desaturate +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +tint | color / table of numbers | {1,1,1} +strength | number between 0 and 1 | 0.5 + + +<a name="effect-dmg"></a> +### dmg + +```lua +moonshine.effects.dmg +``` + +Name | Type | Default +-----|------|-------- +palette | number or string or table of table of numbers | "default" + +DMG ships with 7 palettes: + +1. `default` +2. `dark_yellow` +3. `light_yellow` +4. `green` +5. `greyscale` +6. `stark_bw` +7. `pocket` + +Custom palettes must be in the format `{{R,G,B}, {R,G,B}, {R,G,B}, {R,G,B}}`, +where `R`, `G`, and `B` are numbers between `0` and `1`. + + +<a name="effect-fastgaussianblur"></a> +### fastgaussianblur + +```lua +moonshine.effects.fastgaussianblur +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +taps | odd number >= 3 | 7 | (amount of blur) +offset | number | 1 +sigma | number | -1 + + +<a name="effect-filmgrain"></a> +### filmgrain + +```lua +moonshine.effects.filmgrain +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +opacity | number | 0.3 +size | number | 1 + + +<a name="effect-gaussianblur"></a> +### gaussianblur + +```lua +moonshine.effects.gaussianblur +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +sigma | number | 1 | (amount of blur) + + +<a name="effect-glow"></a> +### glow + +```lua +moonshine.effects.glow +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +min_luma | number between 0 and 1 | 0.7 +strength | number >= 0 | 5 + + +<a name="effect-godsray"></a> +### godsray + +```lua +moonshine.effects.godsray +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +exposire | number between 0 and 1 | 0.5 +decay | number between 0 and 1 | 0.95 +density | number between 0 and 1 | 0.05 +weight | number between 0 and 1 | 0.5 +light_position | table of two numbers | {0.5, 0.5} +light_x | number | 0.5 +light_y | number | 0.5 +samples | number >= 1 | 70 + + +<a name="effect-pixelate"></a> +### pixelate + +```lua +moonshine.effects.pixelate +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +size | number or table of two numbers | {5,5} +feedback | number between 0 and 1 | 0 + + +<a name="effect-posterize"></a> +### posterize + +```lua +moonshine.effects.posterize +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +num_bands | number >= 1 | 3 + + +<a name="effect-scanlines"></a> +### scanlines + +```lua +moonshine.effects.scanlines +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +width | number | 2 +frequency | number | screen-height +phase | number | 0 +thickness | number | 1 +opacity | number | 1 +color | color / table of numbers | {0,0,0} + + +<a name="effect-sketch"></a> +### sketch + +```lua +moonshine.effects.sketch +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +amp | number | 0.0007 +center | table of numbers | {0,0} + + +<a name="effect-vignette"></a> +### vignette + +```lua +moonshine.effects.vignette +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +radius | number > 0 | 0.8 +softness | number > 0 | 0.5 +opacity | number > 0 | 0.5 +color | color / table of numbers | {0,0,0} + +<a name="effect-fog"></a> +### fog + +```lua +moonshine.effects.fog +``` + +**Parameters:** + +Name | Type | Default +-----|------|-------- +fog_color | color/table of numbers | {0.35, 0.48, 0.95} +octaves | number > 0 | 4 +speed | vec2/table of numbers | {0.5, 0.5} + + +<a name="writing-effects"></a> +## Writing effects + +An effect is essentially a function that returns a `moonshine.Effect{}`, which +must specify at least a `name` and a `shader` or a `draw` function. + +It may also specify a `setters` table that contains functions that set the +effect parameters and a `defaults` table with the corresponding default values. +The default values will be set when the effect is instantiated. + +A good starting point to see how to write effects is the `colorgradesimple` +effect, which uses the `shader`, `setters` and `defaults` fields. + +Moonshine uses double buffering to draw the effects. A function to swap and +access the buffers is provided to the `draw(buffer)` function of your effect: + +```lua +front, back = buffer() -- swaps front and back buffer and returns both +``` + +You don't have to care about canvases or restoring defaults, moonshine handles +all that for you. + +If you only need a custom draw function because your effect needs multiple +shader passes, moonshine provides the `draw_shader(buffer, shader)` function. +As you might have guessed, this function uses `shader` to draw the front buffer +to the back buffer. The `boxblur` effect gives a simple example how to use this +function. + +If for some reason you need more than two buffer, you are more or less on your +own. You can do everything, but make sure that the blend mode and the order of +back and front buffer is the same before and after your custom `draw` function. +The `glow` effect gives an example of a more complicated `draw` function. + + +<a name="license"></a> +## License + +See [here](https://github.com/vrld/moonshine/graphs/contributors) for a list of +contributors. + +The main library can freely be used under the following conditions: + + The MIT License (MIT) + + Copyright (c) 2017 Matthias Richter + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +Most of the effects are public domain (see comments inside the files): + +* boxblur.lua +* chromasep.lua +* colorgradesimple.lua +* crt.lua +* desaturate.lua +* filmgrain.lua +* gaussianblur.lua +* glow.lua +* pixelate.lua +* posterize.lua +* scanlines.lua +* vignette.lua + +These effects are MIT-licensed with multiple authors: + +* dmg.lua: Joseph Patoprsty, Matthias Richter +* fastgaussianblur.lua: Tim Moore, Matthias Richter +* godsray.lua: Joseph Patoprsty, Matthias Richter. Based on work by ioxu, Fabien Sanglard, Kenny Mitchell and Jason Mitchell. +* sketch.lua: Martin Felis, Matthias Richter +* fog.lua: Brandon Blanker Lim-it. Based on work by Gonkee. diff --git a/libs/moonshine/boxblur.lua b/libs/moonshine/boxblur.lua new file mode 100644 index 0000000..bb6afc1 --- /dev/null +++ b/libs/moonshine/boxblur.lua @@ -0,0 +1,62 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local radius_x, radius_y = 3, 3 + local shader = love.graphics.newShader[[ + extern vec2 direction; + extern number radius; + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { + vec4 c = vec4(0.0); + + for (float i = -radius; i <= radius; i += 1.0) + { + c += Texel(texture, tc + i * direction); + } + return c / (2.0 * radius + 1.0) * color; + }]] + + local setters = {} + setters.radius = function(v) + if type(v) == "number" then + radius_x, radius_y = v, v + elseif type(v) == "table" and #v >= 2 then + radius_x, radius_y = tonumber(v[1] or v.h or v.x), tonumber(v[2] or v.v or v.y) + else + error("Invalid argument `radius'") + end + end + setters.radius_x = function(v) radius_x = tonumber(v) end + setters.radius_y = function(v) radius_y = tonumber(v) end + + local draw = function(buffer) + shader:send('direction', {1 / love.graphics.getWidth(), 0}) + shader:send('radius', math.floor(radius_x + .5)) + moonshine.draw_shader(buffer, shader) + + shader:send('direction', {0, 1 / love.graphics.getHeight()}) + shader:send('radius', math.floor(radius_y + .5)) + moonshine.draw_shader(buffer, shader) + end + + return moonshine.Effect{ + name = "boxblur", + draw = draw, + setters = setters, + defaults = {radius = 3} + } +end diff --git a/libs/moonshine/chromasep.lua b/libs/moonshine/chromasep.lua new file mode 100644 index 0000000..f528733 --- /dev/null +++ b/libs/moonshine/chromasep.lua @@ -0,0 +1,49 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern vec2 direction; + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) + { + return color * vec4( + Texel(texture, tc - direction).r, + Texel(texture, tc).g, + Texel(texture, tc + direction).b, + 1.0); + }]] + + local angle, radius = 0, 0 + local setters = { + angle = function(v) angle = tonumber(v) or 0 end, + radius = function(v) radius = tonumber(v) or 0 end + } + + local draw = function(buffer, effect) + local dx = math.cos(angle) * radius / love.graphics.getWidth() + local dy = math.sin(angle) * radius / love.graphics.getHeight() + shader:send("direction", {dx,dy}) + moonshine.draw_shader(buffer, shader) + end + + return moonshine.Effect{ + name = "chromasep", + draw = draw, + setters = setters, + defaults = {angle = 0, radius = 0} + } +end diff --git a/libs/moonshine/colorgradesimple.lua b/libs/moonshine/colorgradesimple.lua new file mode 100644 index 0000000..f0e0278 --- /dev/null +++ b/libs/moonshine/colorgradesimple.lua @@ -0,0 +1,33 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern vec3 factors; + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { + return vec4(factors, 1.0) * Texel(texture, tc) * color; + }]] + + local setters = {} + + return moonshine.Effect{ + name = "colorgradesimple", + shader = shader, + setters = {factors = function(v) shader:send("factors", v) end}, + defaults = {factors = {1,1,1}} + } +end diff --git a/libs/moonshine/crt.lua b/libs/moonshine/crt.lua new file mode 100644 index 0000000..9b73799 --- /dev/null +++ b/libs/moonshine/crt.lua @@ -0,0 +1,79 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + -- Barrel distortion adapted from Daniel Oaks (see commit cef01b67fd) + -- Added feather to mask out outside of distorted texture + local distortionFactor + local shader = love.graphics.newShader[[ + extern vec2 distortionFactor; + extern vec2 scaleFactor; + extern number feather; + + vec4 effect(vec4 color, Image tex, vec2 uv, vec2 px) { + // to barrel coordinates + uv = uv * 2.0 - vec2(1.0); + + // distort + uv *= scaleFactor; + uv += (uv.yx*uv.yx) * uv * (distortionFactor - 1.0); + number mask = (1.0 - smoothstep(1.0-feather,1.0,abs(uv.x))) + * (1.0 - smoothstep(1.0-feather,1.0,abs(uv.y))); + + // to cartesian coordinates + uv = (uv + vec2(1.0)) / 2.0; + + return color * Texel(tex, uv) * mask; + } + ]] + + local setters = {} + + setters.distortionFactor = function(v) + assert(type(v) == "table" and #v == 2, "Invalid value for `distortionFactor'") + distortionFactor = {unpack(v)} + shader:send("distortionFactor", v) + end + + setters.x = function(v) setters.distortionFactor{v, distortionFactor[2]} end + setters.y = function(v) setters.distortionFactor{distortionFactor[1], v} end + + setters.scaleFactor = function(v) + if type(v) == "table" and #v == 2 then + shader:send("scaleFactor", v) + elseif type(v) == "number" then + shader:send("scaleFactor", {v,v}) + else + error("Invalid value for `scaleFactor'") + end + end + + setters.feather = function(v) shader:send("feather", v) end + + local defaults = { + distortionFactor = {1.06, 1.065}, + feather = 0.02, + scaleFactor = 1, + } + + return moonshine.Effect{ + name = "crt", + shader = shader, + setters = setters, + defaults = defaults + } +end diff --git a/libs/moonshine/desaturate.lua b/libs/moonshine/desaturate.lua new file mode 100644 index 0000000..dd51230 --- /dev/null +++ b/libs/moonshine/desaturate.lua @@ -0,0 +1,53 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern vec4 tint; + extern number strength; + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { + color = Texel(texture, tc); + number luma = dot(vec3(0.299, 0.587, 0.114), color.rgb); + return mix(color, tint * luma, strength); + }]] + + local setters = {} + + setters.tint = function(c) + assert(type(c) == "table" and #c == 3, "Invalid value for `tint'") + assert(c[1] <= 1, "Colors should be normalized in [0,1]") + shader:send("tint", { + (tonumber(c[1]) or 0), + (tonumber(c[2]) or 0), + (tonumber(c[3]) or 0), + 1 + }) + end + + setters.strength = function(v) + shader:send("strength", math.max(0, math.min(1, tonumber(v) or 0))) + end + + local defaults = {tint = {1,1,1}, strength = 0.5} + + return moonshine.Effect{ + name = "desaturate", + shader = shader, + setters = setters, + defaults = defaults + } +end diff --git a/libs/moonshine/dmg.lua b/libs/moonshine/dmg.lua new file mode 100644 index 0000000..b426852 --- /dev/null +++ b/libs/moonshine/dmg.lua @@ -0,0 +1,153 @@ +--[[ +The MIT License (MIT) + +Original code: Copyright (c) 2015 Josef Patoprsty +Port to moonshine: Copyright (c) 2017 Matthias Richter <vrld@vrld.org> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +]]-- + +local palettes = { + -- Default color palette. Source: + -- http://en.wikipedia.org/wiki/List_of_video_game_console_palettes#Original_Game_Boy + { + name = "default", + colors = { + { 15/255, 56/255, 15/255}, + { 48/255, 98/255, 48/255}, + {139/255,172/255, 15/255}, + {155/255,188/255, 15/255} + } + }, + -- Hardcore color profiles. Source: + -- http://www.hardcoregaming101.net/gbdebate/gbcolours.htm + { + name = "dark_yellow", + colors = { + {33/255,32/255,16/255}, + {107/255,105/255,49/255}, + {181/255,174/255,74/255}, + {255/255,247/255,123/255} + } + }, + { + name = "light_yellow", + colors = { + {102/255,102/255,37/255}, + {148/255,148/255,64/255}, + {208/255,208/255,102/255}, + {255/255,255/255,148/255} + } + }, + { + name = "green", + colors = { + {8/255,56/255,8/255}, + {48/255,96/255,48/255}, + {136/255,168/255,8/255}, + {183/255,220/255,17/255} + } + }, + { + name = "greyscale", + colors = { + {56/255,56/255,56/255}, + {117/255,117/255,117/255}, + {178/255,178/255,178/255}, + {239/255,239/255,239/255} + } + }, + { + name = "stark_bw", + colors = { + {0/255,0/255,0/255}, + {117/255,117/255,117/255}, + {178/255,178/255,178/255}, + {255/255,255/255,255/255} + } + }, + { + name = "pocket", + colors = { + {108/255,108/255,78/255}, + {142/255,139/255,87/255}, + {195/255,196/255,165/255}, + {227/255,230/255,201/255} + } + } +} + +local lookup_palette = function(name) + for _,palette in pairs(palettes) do + if palette.name == name then + return palette + end + end +end + +local is_valid_palette = function(v) + -- Needs to match: {{R,G,B},{R,G,B},{R,G,B},{R,G,B}} + if #v ~= 4 then return false end + + for i = 1,4 do + if type(v[i]) ~= "table" or #v[i] ~= 3 then return false end + for c = 1,3 do + if type(v[i][c]) ~= "number" then return false end + local x = v[i][c] + if x > 1 then x = x / 255 end + if x < 0 or x > 1 then return false end + v[i][c] = x + end + end + return true +end + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern vec3 palette[ 4 ]; + + vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 pixel_coords) { + vec4 pixel = Texel(texture, texture_coords); + float avg = min(0.9999,max(0.0001,(pixel.r + pixel.g + pixel.b)/3)); + int index = int(avg*4); + return vec4(palette[index], pixel.a); + }]] + + local setters = {} + setters.palette = function(v) + if type(v) == "number" and palettes[math.floor(v)] then -- indexed palette + palette = palettes[math.floor(v)] + elseif type(v) == "string" then -- named palette + palette = lookup_palette(v) + elseif type(v) == "table" and is_valid_palette(v) then -- custom palette + palette = {colors=v} + else -- Fall back to default + palette = palettes[1] + end + shader:send("palette", palette.colors[1], palette.colors[2], + palette.colors[3], palette.colors[4], {}) + end + + return moonshine.Effect{ + name = "dmg", + shader = shader, + setters = setters, + defaults = {palette = "default"} + } +end diff --git a/libs/moonshine/fastgaussianblur.lua b/libs/moonshine/fastgaussianblur.lua new file mode 100644 index 0000000..364b766 --- /dev/null +++ b/libs/moonshine/fastgaussianblur.lua @@ -0,0 +1,139 @@ +--[[ +The MIT License (MIT) + +Copyright (c) 2017 Tim Moore +Adapted for new moonshine API by Matthias Richter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +]]-- + +-- Bilinear Gaussian blur filter as detailed here: http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/ +-- Produces near identical results to a standard Gaussian blur by using sub-pixel sampling, +-- this allows us to do ~1/2 the number of pixel lookups. + +-- unroll convolution loop +local function build_shader(taps, offset, offset_type, sigma) + taps = math.floor(taps) + sigma = sigma >= 1 and sigma or (taps - 1) * offset / 6 + sigma = math.max(sigma, 1) + + local steps = (taps + 1) / 2 + + -- Calculate gaussian function. + local g_offsets = {} + local g_weights = {} + for i = 1, steps, 1 do + g_offsets[i] = offset * (i - 1) + + -- We don't need to include the constant part of the gaussian function as we normalize later. + -- 1 / math.sqrt(2 * sigma ^ math.pi) * math.exp(-0.5 * ((offset - 0) / sigma) ^ 2 ) + g_weights[i] = math.exp(-0.5 * (g_offsets[i] - 0) ^ 2 * 1 / sigma ^ 2 ) + end + + -- Calculate offsets and weights for sub-pixel samples. + local offsets = {} + local weights = {} + for i = #g_weights, 2, -2 do + local oA, oB = g_offsets[i], g_offsets[i - 1] + local wA, wB = g_weights[i], g_weights[i - 1] + wB = oB == 0 and wB / 2 or wB -- On center tap the middle is getting sampled twice so half weight. + local weight = wA + wB + offsets[#offsets + 1] = offset_type == 'center' and (oA + oB) / 2 or (oA * wA + oB * wB) / weight + weights[#weights + 1] = weight + end + + local code = {[[ + extern vec2 direction; + vec4 effect(vec4 color, Image tex, vec2 tc, vec2 sc) {]]} + + local norm = 0 + if #g_weights % 2 == 0 then + code[#code+1] = 'vec4 c = vec4( 0.0 );' + else + local weight = g_weights[1] + norm = norm + weight + code[#code+1] = ('vec4 c = %f * texture2D(tex, tc);'):format(weight) + end + + local tmpl = 'c += %f * ( texture2D(tex, tc + %f * direction)+ texture2D(tex, tc - %f * direction));\n' + for i = 1, #offsets, 1 do + local offset = offsets[i] + local weight = weights[i] + norm = norm + weight * 2 + code[#code+1] = tmpl:format(weight, offset, offset) + end + code[#code+1] = ('return c * vec4(%f) * color; }'):format(1 / norm) + + local shader = table.concat(code) + return love.graphics.newShader(shader) +end + +return function(moonshine) + local taps, offset, offset_type, sigma = 7, 1, 'weighted', -1 + local shader = build_shader(taps, offset, offset_type, sigma) + + local function draw(buffer) + shader:send('direction', {1 / love.graphics.getWidth(), 0}) + moonshine.draw_shader(buffer, shader) + + shader:send('direction', {0, 1 / love.graphics.getHeight()}) + moonshine.draw_shader(buffer, shader) + end + + local setters = {} + + -- Number of effective samples to take per pass. e.g. 3-tap is the current pixel and the neighbors each side. + -- More taps = larger blur, but slower. + setters.taps = function(v) + assert(tonumber(v) >= 3, "Invalid value for `taps': Must be >= 3") + assert(tonumber(v)%2 == 1, "Invalid value for `taps': Must be odd") + taps = tonumber(v) + shader = build_shader(taps, offset, offset_type, sigma) + end + + -- Offset of each tap. + -- For highest quality this should be <=1 but if the image has low entropy we + -- can approximate the blur with a number > 1 and less taps, for better performance. + setters.offset = function(v) + offset = tonumber(v) or 0 + shader = build_shader(taps, offset, offset_type, sigma) + end + + -- Offset type, either 'weighted' or 'center'. + -- 'weighted' gives a more accurate gaussian decay but can introduce modulation + -- for high frequency details. + setters.offset_type = function(v) + assert(v == 'weighted' or v == 'center', "Invalid value for 'offset_type': Must be 'weighted' or 'center'.") + offset_type = v + shader = build_shader(taps, offset, offset_type, sigma) + end + + -- Sigma value for gaussian distribution. You don't normally need to set this. + setters.sigma = function(v) + sigma = tonumber(v) or -1 + shader = build_shader(taps, offset, offset_type, sigma) + end + + return moonshine.Effect{ + name = "fastgaussianblur", + draw = draw, + setters = setters, + -- no defaults here, as we dont want the shader to be built 3 times on startup + } +end diff --git a/libs/moonshine/filmgrain.lua b/libs/moonshine/filmgrain.lua new file mode 100644 index 0000000..7044567 --- /dev/null +++ b/libs/moonshine/filmgrain.lua @@ -0,0 +1,63 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local noisetex = love.image.newImageData(256,256) + noisetex:mapPixel(function() + local l = love.math.random() + return l,l,l,l + end) + noisetex = love.graphics.newImage(noisetex) + + local shader = love.graphics.newShader[[ + extern number opacity; + extern number size; + extern vec2 noise; + extern Image noisetex; + extern vec2 tex_ratio; + + float rand(vec2 co) { + return Texel(noisetex, mod(co * tex_ratio / vec2(size), vec2(1.0))).r; + } + + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { + return color * Texel(texture, tc) * mix(1.0, rand(tc+vec2(noise)), opacity); + }]] + + shader:send("noisetex", noisetex) + shader:send("tex_ratio", {love.graphics.getWidth() / noisetex:getWidth(), + love.graphics.getHeight() / noisetex:getHeight()}) + + local setters = {} + for _,k in ipairs{"opacity", "size"} do + setters[k] = function(v) shader:send(k, math.max(0, tonumber(v) or 0)) end + end + + local defaults = {opacity = .3, size = 1} + + local draw = function(buffer) + shader:send("noise", {love.math.random(), love.math.random()}) + moonshine.draw_shader(buffer, shader) + end + + return moonshine.Effect{ + name = "filmgrain", + draw = draw, + setters = setters, + defaults = defaults + } +end diff --git a/libs/moonshine/fog.lua b/libs/moonshine/fog.lua new file mode 100644 index 0000000..9c90f9a --- /dev/null +++ b/libs/moonshine/fog.lua @@ -0,0 +1,129 @@ +--[[ +Animated 2D Fog (procedural) +Originally for Godot Engine by Gonkee https://www.youtube.com/watch?v=QEaTsz_0o44&t=6s + +Translated for löve by Brandon Blanker Lim-it @flamendless +]]-- + +--[[ +SAMPLE USAGE: +local moonshine = require("moonshine") +local effect + +local image, bg +local image_data +local shader_fog +local time = 0 + +function love.load() + image_data = love.image.newImageData(love.graphics.getWidth(), love.graphics.getHeight()) + image = love.graphics.newImage(image_data) + bg = love.graphics.newImage("bg.png") + effect = moonshine(moonshine.effects.fog) + effect.fog.fog_color = {0.1, 0.0, 0.0} + effect.fog.speed = {0.2, 0.9} +end + +function love.update(dt) + time = time + dt + effect.fog.time = time +end + +function love.draw() + love.graphics.draw(bg) + effect(function() + love.graphics.draw(image) + end) +end +]] + +return function(moonshine) + local fog_color + local octaves + local speed + local time + + local shader = love.graphics.newShader([[ + extern vec3 fog_color = vec3(0.35, 0.48, 0.95); + extern int octaves = 4; + extern vec2 speed = vec2(0.0, 1.0); + extern float time; + + float rand(vec2 coord) + { + return fract(sin(dot(coord, vec2(56, 78)) * 1000.0) * 1000.0); + } + + float noise(vec2 coord) + { + vec2 i = floor(coord); //get the whole number + vec2 f = fract(coord); //get the fraction number + float a = rand(i); //top-left + float b = rand(i + vec2(1.0, 0.0)); //top-right + float c = rand(i + vec2(0.0, 1.0)); //bottom-left + float d = rand(i + vec2(1.0, 1.0)); //bottom-right + vec2 cubic = f * f * (3.0 - 2.0 * f); + return mix(a, b, cubic.x) + (c - a) * cubic.y * (1.0 - cubic.x) + (d - b) * cubic.x * cubic.y; //interpolate + } + + float fbm(vec2 coord) //fractal brownian motion + { + float value = 0.0; + float scale = 0.5; + for (int i = 0; i < octaves; i++) + { + value += noise(coord) * scale; + coord *= 2.0; + scale *= 0.5; + } + return value; + } + + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 sc) + { + vec2 coord = tc * 20.0; + vec2 motion = vec2(fbm(coord + vec2(time * speed.x, time * speed.y))); + float final = fbm(coord + motion); + return vec4(fog_color, final * 0.5); + } + ]]) + + local setters = {} + + setters.fog_color = function(t) + assert(type(t) == "table", "Passed argument to fog_color must be a table containing 3 color values") + fog_color = t + shader:send("fog_color", fog_color) + end + + setters.octaves = function(i) + assert(type(i) == "number", "Passed argument to octaves must be an integer") + octaves = i + shader:send("octaves", octaves) + end + + setters.speed = function(t) + assert(type(t) == "table", "Passed argument to speed must be a table containing 2 values") + speed = t + shader:send("speed", speed) + end + + setters.time = function(n) + assert(type(n) == "number", "Passed argument to time must be a number") + time = n + shader:send("time", time) + end + + local defaults = { + fog_color = {0.35, 0.48, 0.95}, + octaves = 4, + speed = {0.5, 0.5}, + } + + return moonshine.Effect({ + name = "fog", + shader = shader, + setters = setters, + defaults = defaults, + }) +end diff --git a/libs/moonshine/gaussianblur.lua b/libs/moonshine/gaussianblur.lua new file mode 100644 index 0000000..693414a --- /dev/null +++ b/libs/moonshine/gaussianblur.lua @@ -0,0 +1,55 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +]]-- +local function resetShader(sigma) + local support = math.max(1, math.floor(3*sigma + .5)) + local one_by_sigma_sq = sigma > 0 and 1 / (sigma * sigma) or 1 + local norm = 0 + + local code = {[[ + extern vec2 direction; + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) + { vec4 c = vec4(0.0); + ]]} + local blur_line = "c += vec4(%f) * Texel(texture, tc + vec2(%f) * direction);" + + for i = -support,support do + local coeff = math.exp(-.5 * i*i * one_by_sigma_sq) + norm = norm + coeff + code[#code+1] = blur_line:format(coeff, i) + end + + code[#code+1] = ("return c * vec4(%f) * color;}"):format(norm > 0 and 1/norm or 1) + + return love.graphics.newShader(table.concat(code)) +end + +return function(moonshine) + local shader + + local setters = {} + setters.sigma = function(v) + shader = resetShader(math.max(0,tonumber(v) or 1)) + end + + local draw = function(buffer) + shader:send('direction', {1 / love.graphics.getWidth(), 0}) + moonshine.draw_shader(buffer, shader) + + shader:send('direction', {0, 1 / love.graphics.getHeight()}) + moonshine.draw_shader(buffer, shader) + end + + return moonshine.Effect{ + name = "gaussianblur", + draw = draw, + setters = setters, + defaults = {sigma = 1}, + } +end diff --git a/libs/moonshine/glow.lua b/libs/moonshine/glow.lua new file mode 100644 index 0000000..cec010b --- /dev/null +++ b/libs/moonshine/glow.lua @@ -0,0 +1,104 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + + +-- unroll convolution loop for gaussian blur shader +local function make_blur_shader(sigma) + local support = math.max(1, math.floor(3*sigma + .5)) + local one_by_sigma_sq = sigma > 0 and 1 / (sigma * sigma) or 1 + local norm = 0 + + local code = {[[ + extern vec2 direction; + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { + vec4 c = vec4(0.0); + ]]} + local blur_line = "c += vec4(%f) * Texel(texture, tc + vec2(%f) * direction);" + + for i = -support,support do + local coeff = math.exp(-.5 * i*i * one_by_sigma_sq) + norm = norm + coeff + code[#code+1] = blur_line:format(coeff, i) + end + + code[#code+1] = ("return c * vec4(%f) * color;}"):format(1 / norm) + + return love.graphics.newShader(table.concat(code)) +end + +return function(moonshine) + local blurshader -- set in setters.glow_strength + local threshold = love.graphics.newShader[[ + extern number min_luma; + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { + vec4 c = Texel(texture, tc); + number luma = dot(vec3(0.299, 0.587, 0.114), c.rgb); + return c * step(min_luma, luma) * color; + }]] + + local setters = {} + setters.strength = function(v) + blurshader = make_blur_shader(math.max(0,tonumber(v) or 1)) + end + setters.min_luma = function(v) + threshold:send("min_luma", math.max(0, math.min(1, tonumber(v) or 0.5))) + end + + local scene = love.graphics.newCanvas() + local draw = function(buffer) + local front, back = buffer() -- scene so far is in `back' + scene, back = back, scene -- save it for second draw below + + -- 1st pass: draw scene with brightness threshold + love.graphics.setCanvas(front) + love.graphics.clear() + love.graphics.setShader(threshold) + love.graphics.draw(scene) + + -- 2nd pass: apply blur shader in x + blurshader:send('direction', {1 / love.graphics.getWidth(), 0}) + love.graphics.setCanvas(back) + love.graphics.clear() + love.graphics.setShader(blurshader) + love.graphics.draw(front) + + -- 3nd pass: apply blur shader in y and draw original and blurred scene + love.graphics.setCanvas(front) + love.graphics.clear() + + -- original scene without blur shader + love.graphics.setShader() + love.graphics.setBlendMode("add", "premultiplied") + love.graphics.draw(scene) -- original scene + + -- second pass of light blurring + blurshader:send('direction', {0, 1 / love.graphics.getHeight()}) + love.graphics.setShader(blurshader) + love.graphics.draw(back) + + -- restore things as they were before entering draw() + love.graphics.setBlendMode("alpha", "premultiplied") + scene = back + end + + return moonshine.Effect{ + name = "glow", + draw = draw, + setters = setters, + defaults = {min_luma=.7, strength = 5} + } +end diff --git a/libs/moonshine/godsray.lua b/libs/moonshine/godsray.lua new file mode 100644 index 0000000..6c9f74a --- /dev/null +++ b/libs/moonshine/godsray.lua @@ -0,0 +1,107 @@ +--[[ +The MIT License (MIT) + +Original code: Copyright (c) 2015 Josef Patoprsty +Port to moonshine: Copyright (c) 2017 Matthias Richter <vrld@vrld.org> + +Based on work by: ioxu + +https://www.love2d.org/forums/viewtopic.php?f=4&t=3733&start=120#p71099 + +Based on work by: Fabien Sanglard + +http://fabiensanglard.net/lightScattering/index.php + +Based on work from: + +[Mitchell]: Kenny Mitchell "Volumetric Light Scattering as a Post-Process" GPU Gems 3 (2005). +[Mitchell2]: Jason Mitchell "Light Shaft Rendering" ShadersX3 (2004). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +]]-- + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern number exposure; + extern number decay; + extern number density; + extern number weight; + extern vec2 light_position; + extern number samples; + + vec4 effect(vec4 color, Image tex, vec2 uv, vec2 px) { + color = Texel(tex, uv); + + vec2 offset = (uv - light_position) * density / samples; + number illumination = decay; + vec4 c = vec4(.0, .0, .0, 1.0); + + for (int i = 0; i < int(samples); ++i) { + uv -= offset; + c += Texel(tex, uv) * illumination * weight; + illumination *= decay; + } + + return vec4(c.rgb * exposure + color.rgb, color.a); + }]] + + + local setters, light_position = {} + + for _,k in ipairs{"exposure", "decay", "density", "weight"} do + setters[k] = function(v) + shader:send(k, math.min(1, math.max(0, tonumber(v) or 0))) + end + end + + setters.light_position = function(v) + light_position = {unpack(v)} + shader:send("light_position", v) + end + + setters.light_x = function(v) + assert(type(v) == "number", "Invalid value for `light_x'") + setters.light_position{v, light_position[2]} + end + + setters.light_y = function(v) + assert(type(v) == "number", "Invalid value for `light_y'") + setters.light_position{light_position[1], v} + end + + setters.samples = function(v) + shader:send("samples", math.max(1,tonumber(v) or 1)) + end + + local defaults = { + exposure = 0.25, + decay = 0.95, + density = 0.15, + weight = 0.5, + light_position = {0.5,0.5}, + samples = 70 + } + + return moonshine.Effect{ + name = "godsray", + shader = shader, + setters = setters, + defaults = defaults + } +end diff --git a/libs/moonshine/init.lua b/libs/moonshine/init.lua new file mode 100644 index 0000000..431c6c0 --- /dev/null +++ b/libs/moonshine/init.lua @@ -0,0 +1,171 @@ +--[[ +The MIT License (MIT) + +Copyright (c) 2017 Matthias Richter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +]]-- + +local BASE = ... + +local moonshine = {} + +moonshine.draw_shader = function(buffer, shader) + local front, back = buffer() + love.graphics.setCanvas(front) + love.graphics.clear() + if shader ~= love.graphics.getShader() then + love.graphics.setShader(shader) + end + love.graphics.draw(back) +end + +moonshine.chain = function(w,h,effect) + -- called as moonshine.chain(effect)' + if h == nil then + effect, w,h = w, love.window.getMode() + end + assert(effect ~= nil, "No effect") + + local front, back = love.graphics.newCanvas(w,h), love.graphics.newCanvas(w,h) + local buffer = function() + back, front = front, back + return front, back + end + + local disabled = {} -- set of disabled effects + local chain = {} + chain.resize = function(w, h) + front, back = love.graphics.newCanvas(w,h), love.graphics.newCanvas(w,h) + return chain + end + + chain.draw = function(func, ...) + -- save state + local canvas = love.graphics.getCanvas() + local shader = love.graphics.getShader() + local fg_r, fg_g, fg_b, fg_a = love.graphics.getColor() + + -- draw scene to front buffer + love.graphics.setCanvas((buffer())) -- parens are needed: take only front buffer + love.graphics.clear(love.graphics.getBackgroundColor()) + func(...) + + -- save more state + local blendmode = love.graphics.getBlendMode() + + -- process all shaders + love.graphics.setColor(fg_r, fg_g, fg_b, fg_a) + love.graphics.setBlendMode("alpha", "premultiplied") + for _,e in ipairs(chain) do + if not disabled[e.name] then + (e.draw or moonshine.draw_shader)(buffer, e.shader) + end + end + + -- present result + love.graphics.setShader() + love.graphics.setCanvas(canvas) + love.graphics.draw(front,0,0) + + -- restore state + love.graphics.setBlendMode(blendmode) + love.graphics.setShader(shader) + end + + chain.next = function(e) + if type(e) == "function" then + e = e() + end + assert(e.name, "Invalid effect: must provide `name'.") + assert(e.shader or e.draw, "Invalid effect: must provide `shader' or `draw'.") + table.insert(chain, e) + return chain + end + chain.chain = chain.next + + chain.disable = function(name, ...) + if name then + disabled[name] = name + return chain.disable(...) + end + end + + chain.enable = function(name, ...) + if name then + disabled[name] = nil + return chain.enable(...) + end + end + + setmetatable(chain, { + __call = function(_, ...) return chain.draw(...) end, + __index = function(_,k) + for _, e in ipairs(chain) do + if e.name == k then return e end + end + error(("Effect `%s' not in chain"):format(k), 2) + end, + __newindex = function(_, k, v) + if k == "parameters" or k == "params" or k == "settings" then + for e,par in pairs(v) do + for k,v in pairs(par) do + chain[e][k] = v + end + end + else + rawset(chain, k, v) + end + end + }) + + return chain.next(effect) +end + +moonshine.Effect = function(e) + -- set defaults + for k,v in pairs(e.defaults or {}) do + assert(e.setters[k], ("No setter for parameter `%s'"):format(k))(v, k) + e.setters[k](v,k) + end + + -- expose setters + return setmetatable(e, { + __newindex = function(self,k,v) + assert(self.setters[k], ("Unknown property: `%s.%s'"):format(e.name, k)) + self.setters[k](v, k) + end}) +end + +-- autoloading effects +moonshine.effects = setmetatable({}, {__index = function(self, key) + local ok, effect = pcall(require, BASE .. "." .. key) + if not ok then + error("No such effect: "..key, 2) + end + + -- expose moonshine to effect + local con = function(...) return effect(moonshine, ...) end + + -- cache effect constructor + self[key] = con + return con +end}) + +return setmetatable(moonshine, {__call = function(_, ...) return moonshine.chain(...) end}) diff --git a/libs/moonshine/pixelate.lua b/libs/moonshine/pixelate.lua new file mode 100644 index 0000000..42fd76e --- /dev/null +++ b/libs/moonshine/pixelate.lua @@ -0,0 +1,55 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern vec2 size; + extern number feedback; + vec4 effect(vec4 color, Image tex, vec2 tc, vec2 _) + { + vec4 c = Texel(tex, tc); + + // average pixel color over 5 samples + vec2 scale = love_ScreenSize.xy / size; + tc = floor(tc * scale + vec2(.5)); + vec4 meanc = Texel(tex, tc/scale); + meanc += Texel(tex, (tc+vec2( 1.0, .0))/scale); + meanc += Texel(tex, (tc+vec2(-1.0, .0))/scale); + meanc += Texel(tex, (tc+vec2( .0, 1.0))/scale); + meanc += Texel(tex, (tc+vec2( .0,-1.0))/scale); + + return color * mix(.2*meanc, c, feedback); + } + ]] + + local setters = {} + setters.size = function(v) + if type(v) == "number" then v = {v,v} end + assert(type(v) == "table" and #v == 2, "Invalid value for `size'") + shader:send("size", v) + end + setters.feedback = function(v) + shader:send("feedback", math.min(1, math.max(0, tonumber(v) or 0))) + end + + return moonshine.Effect{ + name = "pixelate", + shader = shader, + setters = setters, + defaults = {size = {5,5}, feedback = 0} + } +end diff --git a/libs/moonshine/posterize.lua b/libs/moonshine/posterize.lua new file mode 100644 index 0000000..bc98805 --- /dev/null +++ b/libs/moonshine/posterize.lua @@ -0,0 +1,59 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +shader based on code by sam hocevar, see +https://gamedev.stackexchange.com/questions/59797/glsl-shader-change-hue-saturation-brightness + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern number num_bands; + vec3 rgb2hsv(vec3 c) + { + vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); + } + + vec3 hsv2rgb(vec3 c) + { + vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); + } + + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) + { + color = Texel(texture, tc); + vec3 hsv = floor((rgb2hsv(color.rgb) * num_bands) + vec3(0.5)) / num_bands; + return vec4(hsv2rgb(hsv), color.a); + }]] + + return moonshine.Effect{ + name = "posterize", + shader = shader, + setters = { + num_bands = function(v) + shader:send("num_bands", math.max(1, tonumber(v) or 1)) + end + }, + defaults = {num_bands = 3} + } +end diff --git a/libs/moonshine/scanlines.lua b/libs/moonshine/scanlines.lua new file mode 100644 index 0000000..fb5423d --- /dev/null +++ b/libs/moonshine/scanlines.lua @@ -0,0 +1,74 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern number width; + extern number phase; + extern number thickness; + extern number opacity; + extern vec3 color; + vec4 effect(vec4 c, Image tex, vec2 tc, vec2 _) { + number v = .5*(sin(tc.y * 3.14159 / width * love_ScreenSize.y + phase) + 1.); + c = Texel(tex,tc); + //c.rgb = mix(color, c.rgb, mix(1, pow(v, thickness), opacity)); + c.rgb -= (color - c.rgb) * (pow(v,thickness) - 1.0) * opacity; + return c; + }]] + + + local defaults = { + width = 2, + phase = 0, + thickness = 1, + opacity = 1, + color = {0,0,0}, + } + + local setters = {} + setters.width = function(v) + shader:send("width", tonumber(v) or defaults.width) + end + setters.frequency = function(v) + shader:send("width", love.graphics.getHeight()/(tonumber(v) or love.graphics.getHeight())) + end + setters.phase = function(v) + shader:send("phase", tonumber(v) or defaults.phase) + end + setters.thickness = function(v) + shader:send("thickness", math.max(0, tonumber(v) or defaults.thickness)) + end + setters.opacity = function(v) + shader:send("opacity", math.min(1, math.max(0, tonumber(v) or defaults.opacity))) + end + setters.color = function(c) + assert(type(c) == "table" and #c == 3, "Invalid value for `color'") + assert(c[1] <= 1, "Colors should be normalized in [0,1]") + shader:send("color", { + (tonumber(c[1]) or defaults.color[1]), + (tonumber(c[2]) or defaults.color[2]), + (tonumber(c[3]) or defaults.color[3]) + }) + end + + return moonshine.Effect{ + name = "scanlines", + shader = shader, + setters = setters, + defaults = defaults, + } +end diff --git a/libs/moonshine/sketch.lua b/libs/moonshine/sketch.lua new file mode 100644 index 0000000..dcd4844 --- /dev/null +++ b/libs/moonshine/sketch.lua @@ -0,0 +1,64 @@ +--[[ +The MIT License (MIT) + +Copyright (c) 2015 Martin Felis +Copyright (c) 2017 Matthias Richter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +]]-- + +return function(moonshine) + local noisetex = love.image.newImageData(256,256) + noisetex:mapPixel(function() + return love.math.random(),love.math.random(), 0, 0 + end) + noisetex = love.graphics.newImage(noisetex) + noisetex:setWrap ("repeat", "repeat") + noisetex:setFilter("nearest", "nearest") + + local shader = love.graphics.newShader[[ + extern Image noisetex; + extern number amp; + extern vec2 center; + + vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { + vec2 displacement = Texel(noisetex, tc + center).rg; + tc += normalize(displacement * 2.0 - vec2(1.0)) * amp; + + return Texel(texture, tc); + }]] + + shader:send("noisetex", noisetex) + + local setters = {} + setters.amp = function(v) + shader:send("amp", math.max(0, tonumber(v) or 0)) + end + setters.center = function(v) + assert(type(v) == "table" and #v == 2, "Invalid value for `center'") + shader:send("center", v) + end + + return moonshine.Effect{ + name = "sketch", + shader = shader, + setters = setters, + defaults = {amp = .0007, center = {0,0}} + } +end diff --git a/libs/moonshine/vignette.lua b/libs/moonshine/vignette.lua new file mode 100644 index 0000000..f13fb8b --- /dev/null +++ b/libs/moonshine/vignette.lua @@ -0,0 +1,60 @@ +--[[ +Public domain: + +Copyright (C) 2017 by Matthias Richter <vrld@vrld.org> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +]]-- + +return function(moonshine) + local shader = love.graphics.newShader[[ + extern number radius; + extern number softness; + extern number opacity; + extern vec4 color; + + vec4 effect(vec4 c, Image tex, vec2 tc, vec2 _) + { + number aspect = love_ScreenSize.x / love_ScreenSize.y; + aspect = max(aspect, 1.0 / aspect); // use different aspect when in portrait mode + number v = 1.0 - smoothstep(radius, radius-softness, + length((tc - vec2(0.5)) * aspect)); + return mix(Texel(tex, tc), color, v*opacity); + }]] + + local setters = {} + for _,k in ipairs{"radius", "softness", "opacity"} do + setters[k] = function(v) shader:send(k, math.max(0, tonumber(v) or 0)) end + end + setters.color = function(c) + assert(type(c) == "table" and #c == 3, "Invalid value for `color'") + assert(c[1] <= 1, "Colors should be normalized in [0,1]") + shader:send("color", { + (tonumber(c[1]) or 0), + (tonumber(c[2]) or 0), + (tonumber(c[3]) or 0), + 1 + }) + end + + return moonshine.Effect{ + name = "vignette", + shader = shader, + setters = setters, + defaults = { + radius = .8, + softness = .5, + opacity = .5, + color = {0,0,0} + } + } +end diff --git a/libs/o-ten-one/baby.png b/libs/o-ten-one/baby.png Binary files differnew file mode 100644 index 0000000..de89bb6 --- /dev/null +++ b/libs/o-ten-one/baby.png diff --git a/libs/o-ten-one/handy-andy.otf b/libs/o-ten-one/handy-andy.otf Binary files differnew file mode 100644 index 0000000..3e7abfa --- /dev/null +++ b/libs/o-ten-one/handy-andy.otf diff --git a/libs/o-ten-one/heart.png b/libs/o-ten-one/heart.png Binary files differnew file mode 100644 index 0000000..fc6933c --- /dev/null +++ b/libs/o-ten-one/heart.png diff --git a/libs/o-ten-one/init.lua b/libs/o-ten-one/init.lua new file mode 100644 index 0000000..7909357 --- /dev/null +++ b/libs/o-ten-one/init.lua @@ -0,0 +1,393 @@ +local splashlib = { + _VERSION = "v1.2.0", + _DESCRIPTION = "a 0.10.1 splash", + _URL = "https://github.com/love2d-community/splashes", + _LICENSE = [[Copyright (c) 2016 love-community members (as per git commits in repository above) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgement in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +The font used in this splash is "Handy Andy" by www.andrzejgdula.com]] +} + +local current_module = (...):gsub("%.init$", "") +local current_folder = current_module:gsub("%.", "/") + +local timer = require(current_module .. ".timer") + +local colors = { + bg = {.42, .75, .89}, + white = { 1, 1, 1}, + blue = {.15, .67, .88}, + pink = {.91, .29, .6}, + shadow = {0, 0, 0, .33} +} + +-- patch shader:send if 'lighten' gets optimized away +local function safesend(shader, name, ...) + if shader:hasUniform(name) then + shader:send(name, ...) + end +end + +function splashlib.new(init) + init = init or {} + local self = {} + local width, height = love.graphics.getDimensions() + + self.background = init.background == nil and colors.bg or init.background + self.delay_before = init.delay_before or 0.3 + self.delay_after = init.delay_after or 0.7 + + if init.fill == "rain" then + local rain = {} + rain.spacing_x = 110 + rain.spacing_y = 80 + rain.image = love.graphics.newImage(current_folder .. "/baby.png") + rain.img_w = rain.image:getWidth() + rain.img_h = rain.image:getHeight() + rain.ox = -rain.img_w / 2 + rain.oy = -rain.img_h / 2 + rain.batch = love.graphics.newSpriteBatch(rain.image, 512) + rain.t = 0 + + local gradient = love.graphics.newMesh({ + { 0, height/4, 0, 0, 0, 0, 0, 0}, + {width, height/4, 0, 0, 0, 0, 0, 0}, + {width, height, 0, 0, 0, 0, 0, 200}, + { 0, height, 0, 0, 0, 0, 0, 200}, + }, "fan", "static") + do + local batch = rain.batch + + local sx = rain.spacing_x + local sy = rain.spacing_y + local ox = rain.ox + local oy = rain.oy + + local batch_w = 2 * math.ceil(love.graphics.getWidth() / sx) + 2 + local batch_h = 2 * math.ceil(love.graphics.getHeight() / sy) + 2 + + batch:clear() + + if batch:getBufferSize() < batch_w * batch_h then + batch:setBufferSize(batch_w * batch_h) + end + + for i = 0, batch_h - 1 do + for j = 0, batch_w - 1 do + local is_even = (j % 2) == 0 + local offset_y = is_even and 0 or sy / 2 + local x = ox + j * sx + local y = oy + i * sy + offset_y + batch:add(x, y) + end + end + + batch:flush() + end + + function self.fill() + local y = rain.spacing_y * select(2, math.modf(self.elapsed)) + + local small_y = -rain.spacing_y + y / 2 + local big_y = -rain.spacing_y + y + + love.graphics.setBlendMode("subtract") + love.graphics.setColor(1, 1, 1, .5) + love.graphics.draw(rain.batch, -rain.spacing_x, small_y, 0, 0.5, 0.5) + + love.graphics.setBlendMode("alpha") + love.graphics.setColor(.81, .81, .81, 1) + love.graphics.draw(rain.batch, -rain.spacing_x, big_y) + + love.graphics.draw(gradient) + end + end + + -- radial mask shader + self.maskshader = love.graphics.newShader((init.fill == "lighten" and "#define LIGHTEN" or "") .. [[ + + extern number radius; + extern number blur; + extern number shadow; + extern number lighten; + + vec4 desat(vec4 color) { + number g = dot(vec3(.299, .587, .114), color.rgb); + return vec4(g, g, g, 1.0) * lighten; + } + + vec4 effect(vec4 global_color, Image canvas, vec2 tc, vec2 _) + { + // radial mask + vec4 color = Texel(canvas, tc); + number r = length((tc - vec2(.5)) * love_ScreenSize.xy); + number s = smoothstep(radius+blur, radius-blur, r); + #ifdef LIGHTEN + color = color + desat(color) * (1.0-s); + #else + color.a *= s; + #endif + color.a *= global_color.a; + + // add shadow on lower diagonal along the circle + number sr = 7. * (1. - smoothstep(-.1,.04,(1.-tc.x)-tc.y)); + s = (1. - pow(exp(-pow(radius-r, 2.) / sr),3.) * shadow); + + return color - vec4(1, 1, 1, 0) * (1.0-s); + } + ]]) + + -- this shader makes the text appear from left to right + self.textshader = love.graphics.newShader[[ + extern number alpha; + + vec4 effect(vec4 color, Image logo, vec2 tc, vec2 sc) + { + //Probably would be better to just use the texture's dimensions instead; faster reaction. + vec2 sd = sc / love_ScreenSize.xy; + + if (sd.x <= alpha) { + return color * Texel(logo, tc); + } + return vec4(0); + } + ]] + + -- this shader applies a stroke effect on the logo using a gradient mask + self.logoshader = love.graphics.newShader[[ + //Using the pen extern, only draw out pixels that have their color below a certain treshold. + //Since pen will eventually equal 1.0, the full logo will be drawn out. + + extern number pen; + extern Image mask; + + vec4 effect(vec4 color, Image logo, vec2 tc, vec2 sc) + { + number value = max(Texel(mask, tc).r, max(Texel(mask, tc).g, Texel(mask, tc).b)); + number alpha = Texel(mask, tc).a; + + //probably could be optimzied... + if (alpha > 0.0) { + if (pen >= value) { + return color * Texel(logo, tc); + } + } + return vec4(0); + } + ]] + + self.canvas = love.graphics.newCanvas() + + self.elapsed = 0 + self.alpha = 1 + self.heart = { + sprite = love.graphics.newImage(current_folder .. "/heart.png"), + scale = 0, + rot = 0 + } + + self.stripes = { + rot = 0, + height = 100, + offset = -2 * width, + radius = math.max(width, height), + lighten = 0, + shadow = 0, + } + + self.text = { + obj = love.graphics.newText(love.graphics.newFont(current_folder .. "/handy-andy.otf", 22), "made with"), + alpha = 0 + } + self.text.width, self.text.height = self.text.obj:getDimensions() + + self.logo = { + sprite = love.graphics.newImage(current_folder .. "/logo.png"), + mask = love.graphics.newImage(current_folder .. "/logo-mask.png"), + pen = 0 + } + self.logo.width, self.logo.height = self.logo.sprite:getDimensions() + + safesend(self.maskshader, "radius", width*height) + safesend(self.maskshader, "lighten", 0) + safesend(self.maskshader, "shadow", 0) + safesend(self.maskshader, "blur", 1) + + safesend(self.textshader, "alpha", 0) + + safesend(self.logoshader, "pen", 0) + safesend(self.logoshader, "mask", self.logo.mask) + + timer.clear() + timer.script(function(wait) + + wait(self.delay_before) + + -- roll in stripes + timer.tween(0.5, self.stripes, {offset = 0}) + wait(0.3) + + timer.tween(0.3, self.stripes, {rot = -5 * math.pi / 18, height=height}) + wait(0.2) + + -- hackety hack: execute timer to update shader every frame + timer.every(0, function() + safesend(self.maskshader, "radius", self.stripes.radius) + safesend(self.maskshader, "lighten", self.stripes.lighten) + safesend(self.maskshader, "shadow", self.stripes.shadow) + safesend(self.textshader, "alpha", self.text.alpha) + safesend(self.logoshader, "pen", self.logo.pen) + end) + + -- focus the heart, desaturate the rest + timer.tween(0.2, self.stripes, {radius = 170*love.graphics.getDPIScale()}) + timer.tween(0.4, self.stripes, {lighten = .06}, "quad") + wait(0.2) + + timer.tween(0.2, self.stripes, {radius = 70*love.graphics.getDPIScale()}, "out-back") + timer.tween(0.7, self.stripes, {shadow = .3}, "back") + timer.tween(0.8, self.heart, {scale = 1}, "out-elastic", nil, 1, 0.3) + + -- write out the text + timer.tween(.75, self.text, {alpha = 1}, "linear") + + -- draw out the logo, in parts + local mult = 0.65 + local function tween_and_wait(dur, pen, easing) + timer.tween(mult * dur, self.logo, {pen = pen/255}, easing) + wait(mult * dur) + end + tween_and_wait(0.175, 50, "in-quad") -- L + tween_and_wait(0.300, 100, "in-out-quad") -- O + tween_and_wait(0.075, 115, "out-sine") -- first dot on O + tween_and_wait(0.075, 129, "out-sine") -- second dot on O + tween_and_wait(0.125, 153, "in-out-quad") -- \ + tween_and_wait(0.075, 179, "in-quad") -- / + tween_and_wait(0.250, 205, "in-quart") -- e->break + tween_and_wait(0.150, 230, "out-cubic") -- e finish + tween_and_wait(0.150, 244, "linear") -- () + tween_and_wait(0.100, 255, "linear") -- R + wait(0.4) + + -- no more skipping + wait(self.delay_after) + self.done = true + + timer.tween(0.3, self, {alpha = 0}) + wait(0.3) + + timer.clear() + + if self.onDone then self.onDone() end + end) + + self.draw = splashlib.draw + self.update = splashlib.update + self.skip = splashlib.skip + + return self +end + +function splashlib:draw() + local width, height = love.graphics.getDimensions() + + if self.background then + love.graphics.clear(self.background) + end + + if self.fill and self.elapsed > self.delay_before + 0.6 then + self:fill() + end + + self.canvas:renderTo(function() + love.graphics.push() + love.graphics.translate(width / 2, height / 2) + + love.graphics.push() + love.graphics.rotate(self.stripes.rot) + love.graphics.setColor(colors.pink) + love.graphics.rectangle( + "fill", + self.stripes.offset - width, -self.stripes.height, + width * 2, self.stripes.height + ) + + love.graphics.setColor(colors.blue) + love.graphics.rectangle( + "line", -- draw line for anti aliasing + -width - self.stripes.offset, 0, + width * 2, self.stripes.height + ) + love.graphics.rectangle( + "fill", + -width - self.stripes.offset, 0, + width * 2, self.stripes.height + ) + love.graphics.pop() + + love.graphics.setColor(1, 1, 1, self.heart.scale) + love.graphics.draw(self.heart.sprite, 0, 5, self.heart.rot, self.heart.scale, self.heart.scale, 43, 39) + love.graphics.pop() + end) + + love.graphics.setColor(1, 1, 1, self.alpha) + love.graphics.setShader(self.maskshader) + love.graphics.draw(self.canvas, 0,0) + love.graphics.setShader() + + love.graphics.push() + love.graphics.setShader(self.textshader) + love.graphics.draw( + self.text.obj, + (width / 2) - (self.text.width / 2), + (height / 2) - (self.text.height / 2) + (height / 10) + 62 + ) + love.graphics.pop() + + love.graphics.push() + love.graphics.setShader(self.logoshader) + love.graphics.draw( + self.logo.sprite, + (width / 2) - (self.logo.width / 4), + (height / 2) + (self.logo.height / 4) + (height / 10), + 0, 0.5, 0.5 + ) + love.graphics.setShader() + love.graphics.pop() +end + +function splashlib:update(dt) + timer.update(dt) + self.elapsed = self.elapsed + dt +end + +function splashlib:skip() + if not self.done then + self.done = true + + timer.tween(0.3, self, {alpha = 0}) + timer.after(0.3, function () + timer.clear() -- to be safe + if self.onDone then self.onDone() end + end) + end +end + +setmetatable(splashlib, { __call = function(self, ...) return self.new(...) end }) + +return splashlib diff --git a/libs/o-ten-one/logo-mask.png b/libs/o-ten-one/logo-mask.png Binary files differnew file mode 100644 index 0000000..b81d2ea --- /dev/null +++ b/libs/o-ten-one/logo-mask.png diff --git a/libs/o-ten-one/logo.png b/libs/o-ten-one/logo.png Binary files differnew file mode 100644 index 0000000..d3bfd49 --- /dev/null +++ b/libs/o-ten-one/logo.png diff --git a/libs/o-ten-one/timer.lua b/libs/o-ten-one/timer.lua new file mode 100644 index 0000000..ef4a750 --- /dev/null +++ b/libs/o-ten-one/timer.lua @@ -0,0 +1,197 @@ +--[[ +Copyright (c) 2010-2013 Matthias Richter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +Except as contained in this notice, the name(s) of the above copyright holders +shall not be used in advertising or otherwise to promote the sale, use or +other dealings in this Software without prior written authorization. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +]]-- + +local Timer = {} +Timer.__index = Timer + +local function _nothing_() end + +function Timer:update(dt) + local to_remove = {} + for handle, delay in pairs(self.functions) do + delay = delay - dt + if delay <= 0 then + to_remove[#to_remove+1] = handle + end + self.functions[handle] = delay + handle.func(dt, delay) + end + for _,handle in ipairs(to_remove) do + self.functions[handle] = nil + handle.after(handle.after) + end +end + +function Timer:during(delay, func, after) + local handle = {func = func, after = after or _nothing_} + self.functions[handle] = delay + return handle +end + +function Timer:after(delay, func) + return self:during(delay, _nothing_, func) +end + +function Timer:every(delay, func, count) + local count, handle = count or math.huge -- exploit below: math.huge - 1 = math.huge + + handle = self:after(delay, function(f) + if func(func) == false then return end + count = count - 1 + if count > 0 then + self.functions[handle] = delay + end + end) + return handle +end + +function Timer:cancel(handle) + self.functions[handle] = nil +end + +function Timer:clear() + self.functions = {} +end + +function Timer:script(f) + local co = coroutine.wrap(f) + co(function(t) + self:after(t, co) + coroutine.yield() + end) +end + +Timer.tween = setmetatable({ + -- helper functions + out = function(f) -- 'rotates' a function + return function(s, ...) return 1 - f(1-s, ...) end + end, + chain = function(f1, f2) -- concatenates two functions + return function(s, ...) return (s < .5 and f1(2*s, ...) or 1 + f2(2*s-1, ...)) * .5 end + end, + + -- useful tweening functions + linear = function(s) return s end, + quad = function(s) return s*s end, + cubic = function(s) return s*s*s end, + quart = function(s) return s*s*s*s end, + quint = function(s) return s*s*s*s*s end, + sine = function(s) return 1-math.cos(s*math.pi/2) end, + expo = function(s) return 2^(10*(s-1)) end, + circ = function(s) return 1 - math.sqrt(1-s*s) end, + + back = function(s,bounciness) + bounciness = bounciness or 1.70158 + return s*s*((bounciness+1)*s - bounciness) + end, + + bounce = function(s) -- magic numbers ahead + local a,b = 7.5625, 1/2.75 + return math.min(a*s^2, a*(s-1.5*b)^2 + .75, a*(s-2.25*b)^2 + .9375, a*(s-2.625*b)^2 + .984375) + end, + + elastic = function(s, amp, period) + amp, period = amp and math.max(1, amp) or 1, period or .3 + return (-amp * math.sin(2*math.pi/period * (s-1) - math.asin(1/amp))) * 2^(10*(s-1)) + end, +}, { + +-- register new tween +__call = function(tween, self, len, subject, target, method, after, ...) + -- recursively collects fields that are defined in both subject and target into a flat list + local function tween_collect_payload(subject, target, out) + for k,v in pairs(target) do + local ref = subject[k] + assert(type(v) == type(ref), 'Type mismatch in field "'..k..'".') + if type(v) == 'table' then + tween_collect_payload(ref, v, out) + else + local ok, delta = pcall(function() return (v-ref)*1 end) + assert(ok, 'Field "'..k..'" does not support arithmetic operations') + out[#out+1] = {subject, k, delta} + end + end + return out + end + + method = tween[method or 'linear'] -- see __index + local payload, t, args = tween_collect_payload(subject, target, {}), 0, {...} + + local last_s = 0 + return self:during(len, function(dt) + t = t + dt + local s = method(math.min(1, t/len), unpack(args)) + local ds = s - last_s + last_s = s + for _, info in ipairs(payload) do + local ref, key, delta = unpack(info) + ref[key] = ref[key] + delta * ds + end + end, after) +end, + +-- fetches function and generated compositions for method `key` +__index = function(tweens, key) + if type(key) == 'function' then return key end + + assert(type(key) == 'string', 'Method must be function or string.') + if rawget(tweens, key) then return rawget(tweens, key) end + + local function construct(pattern, f) + local method = rawget(tweens, key:match(pattern)) + if method then return f(method) end + return nil + end + + local out, chain = rawget(tweens,'out'), rawget(tweens,'chain') + return construct('^in%-([^-]+)$', function(...) return ... end) + or construct('^out%-([^-]+)$', out) + or construct('^in%-out%-([^-]+)$', function(f) return chain(f, out(f)) end) + or construct('^out%-in%-([^-]+)$', function(f) return chain(out(f), f) end) + or error('Unknown interpolation method: ' .. key) +end}) + +-- the module +local function new() + local timer = setmetatable({functions = {}, tween = Timer.tween}, Timer) + return setmetatable({ + new = new, + update = function(...) return timer:update(...) end, + during = function(...) return timer:during(...) end, + after = function(...) return timer:after(...) end, + every = function(...) return timer:every(...) end, + script = function(...) return timer:script(...) end, + cancel = function(...) return timer:cancel(...) end, + clear = function(...) return timer:clear(...) end, + tween = setmetatable({}, { + __index = Timer.tween, + __newindex = function(_,k,v) Timer.tween[k] = v end, + __call = function(t,...) return timer:tween(...) end, + }) + }, {__call = new}) +end + +return new() diff --git a/libs/sti/graphics.lua b/libs/sti/graphics.lua new file mode 100644 index 0000000..6acf8d6 --- /dev/null +++ b/libs/sti/graphics.lua @@ -0,0 +1,132 @@ +local lg = _G.love.graphics +local graphics = { isCreated = lg and true or false } + +function graphics.newSpriteBatch(...) + if graphics.isCreated then + return lg.newSpriteBatch(...) + end +end + +function graphics.newCanvas(...) + if graphics.isCreated then + return lg.newCanvas(...) + end +end + +function graphics.newImage(...) + if graphics.isCreated then + return lg.newImage(...) + end +end + +function graphics.newQuad(...) + if graphics.isCreated then + return lg.newQuad(...) + end +end + +function graphics.getCanvas(...) + if graphics.isCreated then + return lg.getCanvas(...) + end +end + +function graphics.setCanvas(...) + if graphics.isCreated then + return lg.setCanvas(...) + end +end + +function graphics.clear(...) + if graphics.isCreated then + return lg.clear(...) + end +end + +function graphics.push(...) + if graphics.isCreated then + return lg.push(...) + end +end + +function graphics.origin(...) + if graphics.isCreated then + return lg.origin(...) + end +end + +function graphics.scale(...) + if graphics.isCreated then + return lg.scale(...) + end +end + +function graphics.translate(...) + if graphics.isCreated then + return lg.translate(...) + end +end + +function graphics.pop(...) + if graphics.isCreated then + return lg.pop(...) + end +end + +function graphics.draw(...) + if graphics.isCreated then + return lg.draw(...) + end +end + +function graphics.rectangle(...) + if graphics.isCreated then + return lg.rectangle(...) + end +end + +function graphics.getColor(...) + if graphics.isCreated then + return lg.getColor(...) + end +end + +function graphics.setColor(...) + if graphics.isCreated then + return lg.setColor(...) + end +end + +function graphics.line(...) + if graphics.isCreated then + return lg.line(...) + end +end + +function graphics.polygon(...) + if graphics.isCreated then + return lg.polygon(...) + end +end + +function graphics.points(...) + if graphics.isCreated then + return lg.points(...) + end +end + +function graphics.getWidth() + if graphics.isCreated then + return lg.getWidth() + end + return 0 +end + +function graphics.getHeight() + if graphics.isCreated then + return lg.getHeight() + end + return 0 +end + +return graphics diff --git a/libs/sti/init.lua b/libs/sti/init.lua new file mode 100644 index 0000000..9214112 --- /dev/null +++ b/libs/sti/init.lua @@ -0,0 +1,1616 @@ +--- Simple and fast Tiled map loader and renderer. +-- @module sti +-- @author Landon Manning +-- @copyright 2019 +-- @license MIT/X11 + +local STI = { + _LICENSE = "MIT/X11", + _URL = "https://github.com/karai17/Simple-Tiled-Implementation", + _VERSION = "1.2.3.0", + _DESCRIPTION = "Simple Tiled Implementation is a Tiled Map Editor library designed for the *awesome* LÖVE framework.", + cache = {} +} +STI.__index = STI + +local love = _G.love +local cwd = (...):gsub('%.init$', '') .. "." +local utils = require(cwd .. "utils") +local ceil = math.ceil +local floor = math.floor +local lg = require(cwd .. "graphics") +local Map = {} +Map.__index = Map + +local function new(map, plugins, ox, oy) + local dir = "" + + if type(map) == "table" then + map = setmetatable(map, Map) + else + -- Check for valid map type + local ext = map:sub(-4, -1) + assert(ext == ".lua", string.format( + "Invalid file type: %s. File must be of type: lua.", + ext + )) + + -- Get directory of map + dir = map:reverse():find("[/\\]") or "" + if dir ~= "" then + dir = map:sub(1, 1 + (#map - dir)) + end + + -- Load map + map = setmetatable(assert(love.filesystem.load(map))(), Map) + end + + map:init(dir, plugins, ox, oy) + + return map +end + +--- Instance a new map. +-- @param map Path to the map file or the map table itself +-- @param plugins A list of plugins to load +-- @param ox Offset of map on the X axis (in pixels) +-- @param oy Offset of map on the Y axis (in pixels) +-- @return table The loaded Map +function STI.__call(_, map, plugins, ox, oy) + return new(map, plugins, ox, oy) +end + +--- Flush image cache. +function STI:flush() + self.cache = {} +end + +--- Map object + +--- Instance a new map +-- @param path Path to the map file +-- @param plugins A list of plugins to load +-- @param ox Offset of map on the X axis (in pixels) +-- @param oy Offset of map on the Y axis (in pixels) +function Map:init(path, plugins, ox, oy) + if type(plugins) == "table" then + self:loadPlugins(plugins) + end + + self:resize() + self.objects = {} + self.tiles = {} + self.tileInstances = {} + self.drawRange = { + sx = 1, + sy = 1, + ex = self.width, + ey = self.height, + } + self.offsetx = ox or 0 + self.offsety = oy or 0 + + self.freeBatchSprites = {} + setmetatable(self.freeBatchSprites, { __mode = 'k' }) + + -- Set tiles, images + local gid = 1 + for i, tileset in ipairs(self.tilesets) do + assert(tileset.image, "STI does not support Tile Collections.\nYou need to create a Texture Atlas.") + + -- Cache images + if lg.isCreated then + local formatted_path = utils.format_path(path .. tileset.image) + + if not STI.cache[formatted_path] then + utils.fix_transparent_color(tileset, formatted_path) + utils.cache_image(STI, formatted_path, tileset.image) + else + tileset.image = STI.cache[formatted_path] + end + end + + gid = self:setTiles(i, tileset, gid) + end + + local layers = {} + for _, layer in ipairs(self.layers) do + self:groupAppendToList(layers, layer) + end + self.layers = layers + + -- Set layers + for _, layer in ipairs(self.layers) do + self:setLayer(layer, path) + end +end + +--- Layers from the group are added to the list +-- @param layers List of layers +-- @param layer Layer data +function Map:groupAppendToList(layers, layer) + if layer.type == "group" then + for _, groupLayer in pairs(layer.layers) do + groupLayer.name = layer.name .. "." .. groupLayer.name + groupLayer.visible = layer.visible + groupLayer.opacity = layer.opacity * groupLayer.opacity + groupLayer.offsetx = layer.offsetx + groupLayer.offsetx + groupLayer.offsety = layer.offsety + groupLayer.offsety + + for key, property in pairs(layer.properties) do + if groupLayer.properties[key] == nil then + groupLayer.properties[key] = property + end + end + + self:groupAppendToList(layers, groupLayer) + end + else + table.insert(layers, layer) + end +end + +--- Load plugins +-- @param plugins A list of plugins to load +function Map:loadPlugins(plugins) + for _, plugin in ipairs(plugins) do + local pluginModulePath = cwd .. 'plugins.' .. plugin + local ok, pluginModule = pcall(require, pluginModulePath) + if ok then + for k, func in pairs(pluginModule) do + if not self[k] then + self[k] = func + end + end + end + end +end + +--- Create Tiles +-- @param index Index of the Tileset +-- @param tileset Tileset data +-- @param gid First Global ID in Tileset +-- @return number Next Tileset's first Global ID +function Map:setTiles(index, tileset, gid) + local quad = lg.newQuad + local imageW = tileset.imagewidth + local imageH = tileset.imageheight + local tileW = tileset.tilewidth + local tileH = tileset.tileheight + local margin = tileset.margin + local spacing = tileset.spacing + local w = utils.get_tiles(imageW, tileW, margin, spacing) + local h = utils.get_tiles(imageH, tileH, margin, spacing) + + for y = 1, h do + for x = 1, w do + local id = gid - tileset.firstgid + local quadX = (x - 1) * tileW + margin + (x - 1) * spacing + local quadY = (y - 1) * tileH + margin + (y - 1) * spacing + local type = "" + local properties, terrain, animation, objectGroup + + for _, tile in pairs(tileset.tiles) do + if tile.id == id then + properties = tile.properties + animation = tile.animation + objectGroup = tile.objectGroup + type = tile.type + + if tile.terrain then + terrain = {} + + for i = 1, #tile.terrain do + terrain[i] = tileset.terrains[tile.terrain[i] + 1] + end + end + end + end + + local tile = { + id = id, + gid = gid, + tileset = index, + type = type, + quad = quad( + quadX, quadY, + tileW, tileH, + imageW, imageH + ), + properties = properties or {}, + terrain = terrain, + animation = animation, + objectGroup = objectGroup, + frame = 1, + time = 0, + width = tileW, + height = tileH, + sx = 1, + sy = 1, + r = 0, + offset = tileset.tileoffset, + } + + self.tiles[gid] = tile + gid = gid + 1 + end + end + + return gid +end + +--- Create Layers +-- @param layer Layer data +-- @param path (Optional) Path to an Image Layer's image +function Map:setLayer(layer, path) + if layer.encoding then + if layer.encoding == "base64" then + assert(require "ffi", "Compressed maps require LuaJIT FFI.\nPlease Switch your interperator to LuaJIT or your Tile Layer Format to \"CSV\".") + local fd = love.data.decode("string", "base64", layer.data) + + if not layer.compression then + layer.data = utils.get_decompressed_data(fd) + else + assert(love.data.decompress, "zlib and gzip compression require LOVE 11.0+.\nPlease set your Tile Layer Format to \"Base64 (uncompressed)\" or \"CSV\".") + + if layer.compression == "zlib" then + local data = love.data.decompress("string", "zlib", fd) + layer.data = utils.get_decompressed_data(data) + end + + if layer.compression == "gzip" then + local data = love.data.decompress("string", "gzip", fd) + layer.data = utils.get_decompressed_data(data) + end + end + end + end + + layer.x = (layer.x or 0) + layer.offsetx + self.offsetx + layer.y = (layer.y or 0) + layer.offsety + self.offsety + layer.update = function() end + + if layer.type == "tilelayer" then + self:setTileData(layer) + self:setSpriteBatches(layer) + layer.draw = function() self:drawTileLayer(layer) end + elseif layer.type == "objectgroup" then + self:setObjectData(layer) + self:setObjectCoordinates(layer) + self:setObjectSpriteBatches(layer) + layer.draw = function() self:drawObjectLayer(layer) end + elseif layer.type == "imagelayer" then + layer.draw = function() self:drawImageLayer(layer) end + + if layer.image ~= "" then + local formatted_path = utils.format_path(path .. layer.image) + if not STI.cache[formatted_path] then + utils.cache_image(STI, formatted_path) + end + + layer.image = STI.cache[formatted_path] + layer.width = layer.image:getWidth() + layer.height = layer.image:getHeight() + end + end + + self.layers[layer.name] = layer +end + +--- Add Tiles to Tile Layer +-- @param layer The Tile Layer +function Map:setTileData(layer) + if layer.chunks then + for _, chunk in ipairs(layer.chunks) do + self:setTileData(chunk) + end + return + end + + local i = 1 + local map = {} + + for y = 1, layer.height do + map[y] = {} + for x = 1, layer.width do + local gid = layer.data[i] + + -- NOTE: Empty tiles have a GID of 0 + if gid > 0 then + map[y][x] = self.tiles[gid] or self:setFlippedGID(gid) + end + + i = i + 1 + end + end + + layer.data = map +end + +--- Add Objects to Layer +-- @param layer The Object Layer +function Map:setObjectData(layer) + for _, object in ipairs(layer.objects) do + object.layer = layer + self.objects[object.id] = object + end +end + +--- Correct position and orientation of Objects in an Object Layer +-- @param layer The Object Layer +function Map:setObjectCoordinates(layer) + for _, object in ipairs(layer.objects) do + local x = layer.x + object.x + local y = layer.y + object.y + local w = object.width + local h = object.height + local cos = math.cos(math.rad(object.rotation)) + local sin = math.sin(math.rad(object.rotation)) + + if object.shape == "rectangle" and not object.gid then + object.rectangle = {} + + local vertices = { + { x=x, y=y }, + { x=x + w, y=y }, + { x=x + w, y=y + h }, + { x=x, y=y + h }, + } + + for _, vertex in ipairs(vertices) do + vertex.x, vertex.y = utils.rotate_vertex(self, vertex, x, y, cos, sin) + table.insert(object.rectangle, { x = vertex.x, y = vertex.y }) + end + elseif object.shape == "ellipse" then + object.ellipse = {} + local vertices = utils.convert_ellipse_to_polygon(x, y, w, h) + + for _, vertex in ipairs(vertices) do + vertex.x, vertex.y = utils.rotate_vertex(self, vertex, x, y, cos, sin) + table.insert(object.ellipse, { x = vertex.x, y = vertex.y }) + end + elseif object.shape == "polygon" then + for _, vertex in ipairs(object.polygon) do + vertex.x = vertex.x + x + vertex.y = vertex.y + y + vertex.x, vertex.y = utils.rotate_vertex(self, vertex, x, y, cos, sin) + end + elseif object.shape == "polyline" then + for _, vertex in ipairs(object.polyline) do + vertex.x = vertex.x + x + vertex.y = vertex.y + y + vertex.x, vertex.y = utils.rotate_vertex(self, vertex, x, y, cos, sin) + end + end + end +end + +--- Convert tile location to tile instance location +-- @param layer Tile layer +-- @param tile Tile +-- @param x Tile location on X axis (in tiles) +-- @param y Tile location on Y axis (in tiles) +-- @return number Tile instance location on X axis (in pixels) +-- @return number Tile instance location on Y axis (in pixels) +function Map:getLayerTilePosition(layer, tile, x, y) + local tileW = self.tilewidth + local tileH = self.tileheight + local tileX, tileY + + if self.orientation == "orthogonal" then + local tileset = self.tilesets[tile.tileset] + tileX = (x - 1) * tileW + tile.offset.x + tileY = (y - 0) * tileH + tile.offset.y - tileset.tileheight + tileX, tileY = utils.compensate(tile, tileX, tileY, tileW, tileH) + elseif self.orientation == "isometric" then + tileX = (x - y) * (tileW / 2) + tile.offset.x + layer.width * tileW / 2 - self.tilewidth / 2 + tileY = (x + y - 2) * (tileH / 2) + tile.offset.y + else + local sideLen = self.hexsidelength or 0 + if self.staggeraxis == "y" then + if self.staggerindex == "odd" then + if y % 2 == 0 then + tileX = (x - 1) * tileW + tileW / 2 + tile.offset.x + else + tileX = (x - 1) * tileW + tile.offset.x + end + else + if y % 2 == 0 then + tileX = (x - 1) * tileW + tile.offset.x + else + tileX = (x - 1) * tileW + tileW / 2 + tile.offset.x + end + end + + local rowH = tileH - (tileH - sideLen) / 2 + tileY = (y - 1) * rowH + tile.offset.y + else + if self.staggerindex == "odd" then + if x % 2 == 0 then + tileY = (y - 1) * tileH + tileH / 2 + tile.offset.y + else + tileY = (y - 1) * tileH + tile.offset.y + end + else + if x % 2 == 0 then + tileY = (y - 1) * tileH + tile.offset.y + else + tileY = (y - 1) * tileH + tileH / 2 + tile.offset.y + end + end + + local colW = tileW - (tileW - sideLen) / 2 + tileX = (x - 1) * colW + tile.offset.x + end + end + + return tileX, tileY +end + +--- Place new tile instance +-- @param layer Tile layer +-- @param chunk Layer chunk +-- @param tile Tile +-- @param number Tile location on X axis (in tiles) +-- @param number Tile location on Y axis (in tiles) +function Map:addNewLayerTile(layer, chunk, tile, x, y) + local tileset = tile.tileset + local image = self.tilesets[tile.tileset].image + local batches + local size + + if chunk then + batches = chunk.batches + size = chunk.width * chunk.height + else + batches = layer.batches + size = layer.width * layer.height + end + + batches[tileset] = batches[tileset] or lg.newSpriteBatch(image, size) + + local batch = batches[tileset] + local tileX, tileY = self:getLayerTilePosition(layer, tile, x, y) + + local instance = { + layer = layer, + chunk = chunk, + gid = tile.gid, + x = tileX, + y = tileY, + r = tile.r, + oy = 0 + } + + -- NOTE: STI can run headless so it is not guaranteed that a batch exists. + if batch then + instance.batch = batch + instance.id = batch:add(tile.quad, tileX, tileY, tile.r, tile.sx, tile.sy) + end + + self.tileInstances[tile.gid] = self.tileInstances[tile.gid] or {} + table.insert(self.tileInstances[tile.gid], instance) +end + +function Map:set_batches(layer, chunk) + if chunk then + chunk.batches = {} + else + layer.batches = {} + end + + if self.orientation == "orthogonal" or self.orientation == "isometric" then + local offsetX = chunk and chunk.x or 0 + local offsetY = chunk and chunk.y or 0 + + local startX = 1 + local startY = 1 + local endX = chunk and chunk.width or layer.width + local endY = chunk and chunk.height or layer.height + local incrementX = 1 + local incrementY = 1 + + -- Determine order to add tiles to sprite batch + -- Defaults to right-down + if self.renderorder == "right-up" then + startY, endY, incrementY = endY, startY, -1 + elseif self.renderorder == "left-down" then + startX, endX, incrementX = endX, startX, -1 + elseif self.renderorder == "left-up" then + startX, endX, incrementX = endX, startX, -1 + startY, endY, incrementY = endY, startY, -1 + end + + for y = startY, endY, incrementY do + for x = startX, endX, incrementX do + -- NOTE: Cannot short circuit this since it is valid for tile to be assigned nil + local tile + if chunk then + tile = chunk.data[y][x] + else + tile = layer.data[y][x] + end + + if tile then + self:addNewLayerTile(layer, chunk, tile, x + offsetX, y + offsetY) + end + end + end + else + if self.staggeraxis == "y" then + for y = 1, (chunk and chunk.height or layer.height) do + for x = 1, (chunk and chunk.width or layer.width) do + -- NOTE: Cannot short circuit this since it is valid for tile to be assigned nil + local tile + if chunk then + tile = chunk.data[y][x] + else + tile = layer.data[y][x] + end + + if tile then + self:addNewLayerTile(layer, chunk, tile, x, y) + end + end + end + else + local i = 0 + local _x + + if self.staggerindex == "odd" then + _x = 1 + else + _x = 2 + end + + while i < (chunk and chunk.width * chunk.height or layer.width * layer.height) do + for _y = 1, (chunk and chunk.height or layer.height) + 0.5, 0.5 do + local y = floor(_y) + + for x = _x, (chunk and chunk.width or layer.width), 2 do + i = i + 1 + + -- NOTE: Cannot short circuit this since it is valid for tile to be assigned nil + local tile + if chunk then + tile = chunk.data[y][x] + else + tile = layer.data[y][x] + end + + if tile then + self:addNewLayerTile(layer, chunk, tile, x, y) + end + end + + if _x == 1 then + _x = 2 + else + _x = 1 + end + end + end + end + end +end + +--- Batch Tiles in Tile Layer for improved draw speed +-- @param layer The Tile Layer +function Map:setSpriteBatches(layer) + if layer.chunks then + for _, chunk in ipairs(layer.chunks) do + self:set_batches(layer, chunk) + end + return + end + + self:set_batches(layer) +end + +--- Batch Tiles in Object Layer for improved draw speed +-- @param layer The Object Layer +function Map:setObjectSpriteBatches(layer) + local newBatch = lg.newSpriteBatch + local batches = {} + + if layer.draworder == "topdown" then + table.sort(layer.objects, function(a, b) + return a.y + a.height < b.y + b.height + end) + end + + for _, object in ipairs(layer.objects) do + if object.gid then + local tile = self.tiles[object.gid] or self:setFlippedGID(object.gid) + local tileset = tile.tileset + local image = self.tilesets[tileset].image + + batches[tileset] = batches[tileset] or newBatch(image) + + local sx = object.width / tile.width + local sy = object.height / tile.height + + -- Tiled rotates around bottom left corner, where love2D rotates around top left corner + local ox = 0 + local oy = tile.height + + local batch = batches[tileset] + local tileX = object.x + tile.offset.x + local tileY = object.y + tile.offset.y + local tileR = math.rad(object.rotation) + + -- Compensation for scale/rotation shift + if tile.sx == -1 then + tileX = tileX + object.width + + if tileR ~= 0 then + tileX = tileX - object.width + ox = ox + tile.width + end + end + + if tile.sy == -1 then + tileY = tileY - object.height + + if tileR ~= 0 then + tileY = tileY + object.width + oy = oy - tile.width + end + end + + local instance = { + id = batch:add(tile.quad, tileX, tileY, tileR, tile.sx * sx, tile.sy * sy, ox, oy), + batch = batch, + layer = layer, + gid = tile.gid, + x = tileX, + y = tileY - oy, + r = tileR, + oy = oy + } + + self.tileInstances[tile.gid] = self.tileInstances[tile.gid] or {} + table.insert(self.tileInstances[tile.gid], instance) + end + end + + layer.batches = batches +end + +--- Create a Custom Layer to place userdata in (such as player sprites) +-- @param name Name of Custom Layer +-- @param index Draw order within Layer stack +-- @return table Custom Layer +function Map:addCustomLayer(name, index) + index = index or #self.layers + 1 + local layer = { + type = "customlayer", + name = name, + visible = true, + opacity = 1, + properties = {}, + } + + function layer.draw() end + function layer.update() end + + table.insert(self.layers, index, layer) + self.layers[name] = self.layers[index] + + return layer +end + +--- Convert another Layer into a Custom Layer +-- @param index Index or name of Layer to convert +-- @return table Custom Layer +function Map:convertToCustomLayer(index) + local layer = assert(self.layers[index], "Layer not found: " .. index) + + layer.type = "customlayer" + layer.x = nil + layer.y = nil + layer.width = nil + layer.height = nil + layer.encoding = nil + layer.data = nil + layer.chunks = nil + layer.objects = nil + layer.image = nil + + function layer.draw() end + function layer.update() end + + return layer +end + +--- Remove a Layer from the Layer stack +-- @param index Index or name of Layer to remove +function Map:removeLayer(index) + local layer = assert(self.layers[index], "Layer not found: " .. index) + + if type(index) == "string" then + for i, l in ipairs(self.layers) do + if l.name == index then + table.remove(self.layers, i) + self.layers[index] = nil + break + end + end + else + local name = self.layers[index].name + table.remove(self.layers, index) + self.layers[name] = nil + end + + -- Remove layer batches + if layer.batches then + for _, batch in pairs(layer.batches) do + self.freeBatchSprites[batch] = nil + end + end + + -- Remove chunk batches + if layer.chunks then + for _, chunk in ipairs(layer.chunks) do + for _, batch in pairs(chunk.batches) do + self.freeBatchSprites[batch] = nil + end + end + end + + -- Remove tile instances + if layer.type == "tilelayer" then + for _, tiles in pairs(self.tileInstances) do + for i = #tiles, 1, -1 do + local tile = tiles[i] + if tile.layer == layer then + table.remove(tiles, i) + end + end + end + end + + -- Remove objects + if layer.objects then + for i, object in pairs(self.objects) do + if object.layer == layer then + self.objects[i] = nil + end + end + end +end + +--- Animate Tiles and update every Layer +-- @param dt Delta Time +function Map:update(dt) + for _, tile in pairs(self.tiles) do + local update = false + + if tile.animation then + tile.time = tile.time + dt * 1000 + + while tile.time > tonumber(tile.animation[tile.frame].duration) do + update = true + tile.time = tile.time - tonumber(tile.animation[tile.frame].duration) + tile.frame = tile.frame + 1 + + if tile.frame > #tile.animation then tile.frame = 1 end + end + + if update and self.tileInstances[tile.gid] then + for _, j in pairs(self.tileInstances[tile.gid]) do + local t = self.tiles[tonumber(tile.animation[tile.frame].tileid) + self.tilesets[tile.tileset].firstgid] + j.batch:set(j.id, t.quad, j.x, j.y, j.r, tile.sx, tile.sy, 0, j.oy) + end + end + end + end + + for _, layer in ipairs(self.layers) do + layer:update(dt) + end +end + +--- Draw every Layer +-- @param tx Translate on X +-- @param ty Translate on Y +-- @param sx Scale on X +-- @param sy Scale on Y +function Map:draw(tx, ty, sx, sy) + local current_canvas = lg.getCanvas() + lg.setCanvas(self.canvas) + lg.clear() + + -- Scale map to 1.0 to draw onto canvas, this fixes tearing issues + -- Map is translated to correct position so the right section is drawn + lg.push() + lg.origin() + lg.translate(math.floor(tx or 0), math.floor(ty or 0)) + + for _, layer in ipairs(self.layers) do + if layer.visible and layer.opacity > 0 then + self:drawLayer(layer) + end + end + + lg.pop() + + -- Draw canvas at 0,0; this fixes scissoring issues + -- Map is scaled to correct scale so the right section is shown + lg.push() + lg.origin() + lg.scale(sx or 1, sy or sx or 1) + + lg.setCanvas(current_canvas) + lg.draw(self.canvas) + + lg.pop() +end + +--- Draw an individual Layer +-- @param layer The Layer to draw +function Map.drawLayer(_, layer) + local r,g,b,a = lg.getColor() + lg.setColor(r, g, b, a * layer.opacity) + layer:draw() + lg.setColor(r,g,b,a) +end + +--- Default draw function for Tile Layers +-- @param layer The Tile Layer to draw +function Map:drawTileLayer(layer) + if type(layer) == "string" or type(layer) == "number" then + layer = self.layers[layer] + end + + assert(layer.type == "tilelayer", "Invalid layer type: " .. layer.type .. ". Layer must be of type: tilelayer") + + -- NOTE: This does not take into account any sort of draw range clipping and will always draw every chunk + if layer.chunks then + for _, chunk in ipairs(layer.chunks) do + for _, batch in pairs(chunk.batches) do + lg.draw(batch, 0, 0) + end + end + + return + end + + for _, batch in pairs(layer.batches) do + lg.draw(batch, floor(layer.x), floor(layer.y)) + end +end + +--- Default draw function for Object Layers +-- @param layer The Object Layer to draw +function Map:drawObjectLayer(layer) + if type(layer) == "string" or type(layer) == "number" then + layer = self.layers[layer] + end + + assert(layer.type == "objectgroup", "Invalid layer type: " .. layer.type .. ". Layer must be of type: objectgroup") + + local line = { 160, 160, 160, 255 * layer.opacity } + local fill = { 160, 160, 160, 255 * layer.opacity * 0.5 } + local r,g,b,a = lg.getColor() + local reset = { r, g, b, a * layer.opacity } + + local function sortVertices(obj) + local vertex = {} + + for _, v in ipairs(obj) do + table.insert(vertex, v.x) + table.insert(vertex, v.y) + end + + return vertex + end + + local function drawShape(obj, shape) + local vertex = sortVertices(obj) + + if shape == "polyline" then + lg.setColor(line) + lg.line(vertex) + return + elseif shape == "polygon" then + lg.setColor(fill) + if not love.math.isConvex(vertex) then + local triangles = love.math.triangulate(vertex) + for _, triangle in ipairs(triangles) do + lg.polygon("fill", triangle) + end + else + lg.polygon("fill", vertex) + end + else + lg.setColor(fill) + lg.polygon("fill", vertex) + end + + lg.setColor(line) + lg.polygon("line", vertex) + end + + for _, object in ipairs(layer.objects) do + if object.visible then + if object.shape == "rectangle" and not object.gid then + drawShape(object.rectangle, "rectangle") + elseif object.shape == "ellipse" then + drawShape(object.ellipse, "ellipse") + elseif object.shape == "polygon" then + drawShape(object.polygon, "polygon") + elseif object.shape == "polyline" then + drawShape(object.polyline, "polyline") + elseif object.shape == "point" then + lg.points(object.x, object.y) + end + end + end + + lg.setColor(reset) + for _, batch in pairs(layer.batches) do + lg.draw(batch, 0, 0) + end + lg.setColor(r,g,b,a) +end + +--- Default draw function for Image Layers +-- @param layer The Image Layer to draw +function Map:drawImageLayer(layer) + if type(layer) == "string" or type(layer) == "number" then + layer = self.layers[layer] + end + + assert(layer.type == "imagelayer", "Invalid layer type: " .. layer.type .. ". Layer must be of type: imagelayer") + + if layer.image ~= "" then + lg.draw(layer.image, layer.x, layer.y) + end +end + +--- Resize the drawable area of the Map +-- @param w The new width of the drawable area (in pixels) +-- @param h The new Height of the drawable area (in pixels) +function Map:resize(w, h) + if lg.isCreated then + w = w or lg.getWidth() + h = h or lg.getHeight() + + self.canvas = lg.newCanvas(w, h) + self.canvas:setFilter("nearest", "nearest") + end +end + +--- Create flipped or rotated Tiles based on bitop flags +-- @param gid The flagged Global ID +-- @return table Flipped Tile +function Map:setFlippedGID(gid) + local bit31 = 2147483648 + local bit30 = 1073741824 + local bit29 = 536870912 + local flipX = false + local flipY = false + local flipD = false + local realgid = gid + + if realgid >= bit31 then + realgid = realgid - bit31 + flipX = not flipX + end + + if realgid >= bit30 then + realgid = realgid - bit30 + flipY = not flipY + end + + if realgid >= bit29 then + realgid = realgid - bit29 + flipD = not flipD + end + + local tile = self.tiles[realgid] + local data = { + id = tile.id, + gid = gid, + tileset = tile.tileset, + frame = tile.frame, + time = tile.time, + width = tile.width, + height = tile.height, + offset = tile.offset, + quad = tile.quad, + properties = tile.properties, + terrain = tile.terrain, + animation = tile.animation, + sx = tile.sx, + sy = tile.sy, + r = tile.r, + } + + if flipX then + if flipY and flipD then + data.r = math.rad(-90) + data.sy = -1 + elseif flipY then + data.sx = -1 + data.sy = -1 + elseif flipD then + data.r = math.rad(90) + else + data.sx = -1 + end + elseif flipY then + if flipD then + data.r = math.rad(-90) + else + data.sy = -1 + end + elseif flipD then + data.r = math.rad(90) + data.sy = -1 + end + + self.tiles[gid] = data + + return self.tiles[gid] +end + +--- Get custom properties from Layer +-- @param layer The Layer +-- @return table List of properties +function Map:getLayerProperties(layer) + local l = self.layers[layer] + + if not l then + return {} + end + + return l.properties +end + +--- Get custom properties from Tile +-- @param layer The Layer that the Tile belongs to +-- @param x The X axis location of the Tile (in tiles) +-- @param y The Y axis location of the Tile (in tiles) +-- @return table List of properties +function Map:getTileProperties(layer, x, y) + local tile = self.layers[layer].data[y][x] + + if not tile then + return {} + end + + return tile.properties +end + +--- Get custom properties from Object +-- @param layer The Layer that the Object belongs to +-- @param object The index or name of the Object +-- @return table List of properties +function Map:getObjectProperties(layer, object) + local o = self.layers[layer].objects + + if type(object) == "number" then + o = o[object] + else + for _, v in ipairs(o) do + if v.name == object then + o = v + break + end + end + end + + if not o then + return {} + end + + return o.properties +end + +--- Change a tile in a layer to another tile +-- @param layer The Layer that the Tile belongs to +-- @param x The X axis location of the Tile (in tiles) +-- @param y The Y axis location of the Tile (in tiles) +-- @param gid The gid of the new tile +function Map:setLayerTile(layer, x, y, gid) + layer = self.layers[layer] + + layer.data[y] = layer.data[y] or {} + local tile = layer.data[y][x] + local instance + if tile then + local tileX, tileY = self:getLayerTilePosition(layer, tile, x, y) + for _, inst in pairs(self.tileInstances[tile.gid]) do + if inst.x == tileX and inst.y == tileY then + instance = inst + break + end + end + end + + if tile == self.tiles[gid] then + return + end + + tile = self.tiles[gid] + + if instance then + self:swapTile(instance, tile) + else + self:addNewLayerTile(layer, tile, x, y) + end + layer.data[y][x] = tile +end + +--- Swap a tile in a spritebatch +-- @param instance The current Instance object we want to replace +-- @param tile The Tile object we want to use +-- @return none +function Map:swapTile(instance, tile) + -- Update sprite batch + if instance.batch then + if tile then + instance.batch:set( + instance.id, + tile.quad, + instance.x, + instance.y, + tile.r, + tile.sx, + tile.sy + ) + else + instance.batch:set( + instance.id, + instance.x, + instance.y, + 0, + 0) + + self.freeBatchSprites[instance.batch] = self.freeBatchSprites[instance.batch] or {} + table.insert(self.freeBatchSprites[instance.batch], instance) + end + end + + -- Remove old tile instance + for i, ins in ipairs(self.tileInstances[instance.gid]) do + if ins.batch == instance.batch and ins.id == instance.id then + table.remove(self.tileInstances[instance.gid], i) + break + end + end + + -- Add new tile instance + if tile then + self.tileInstances[tile.gid] = self.tileInstances[tile.gid] or {} + + local freeBatchSprites = self.freeBatchSprites[instance.batch] + local newInstance + if freeBatchSprites and #freeBatchSprites > 0 then + newInstance = freeBatchSprites[#freeBatchSprites] + freeBatchSprites[#freeBatchSprites] = nil + else + newInstance = {} + end + + newInstance.layer = instance.layer + newInstance.batch = instance.batch + newInstance.id = instance.id + newInstance.gid = tile.gid or 0 + newInstance.x = instance.x + newInstance.y = instance.y + newInstance.r = tile.r or 0 + newInstance.oy = tile.r ~= 0 and tile.height or 0 + table.insert(self.tileInstances[tile.gid], newInstance) + end +end + +--- Convert tile location to pixel location +-- @param x The X axis location of the point (in tiles) +-- @param y The Y axis location of the point (in tiles) +-- @return number The X axis location of the point (in pixels) +-- @return number The Y axis location of the point (in pixels) +function Map:convertTileToPixel(x,y) + if self.orientation == "orthogonal" then + local tileW = self.tilewidth + local tileH = self.tileheight + return + x * tileW, + y * tileH + elseif self.orientation == "isometric" then + local mapH = self.height + local tileW = self.tilewidth + local tileH = self.tileheight + local offsetX = mapH * tileW / 2 + return + (x - y) * tileW / 2 + offsetX, + (x + y) * tileH / 2 + elseif self.orientation == "staggered" or + self.orientation == "hexagonal" then + local tileW = self.tilewidth + local tileH = self.tileheight + local sideLen = self.hexsidelength or 0 + + if self.staggeraxis == "x" then + return + x * tileW, + ceil(y) * (tileH + sideLen) + (ceil(y) % 2 == 0 and tileH or 0) + else + return + ceil(x) * (tileW + sideLen) + (ceil(x) % 2 == 0 and tileW or 0), + y * tileH + end + end +end + +--- Convert pixel location to tile location +-- @param x The X axis location of the point (in pixels) +-- @param y The Y axis location of the point (in pixels) +-- @return number The X axis location of the point (in tiles) +-- @return number The Y axis location of the point (in tiles) +function Map:convertPixelToTile(x, y) + if self.orientation == "orthogonal" then + local tileW = self.tilewidth + local tileH = self.tileheight + return + x / tileW, + y / tileH + elseif self.orientation == "isometric" then + local mapH = self.height + local tileW = self.tilewidth + local tileH = self.tileheight + local offsetX = mapH * tileW / 2 + return + y / tileH + (x - offsetX) / tileW, + y / tileH - (x - offsetX) / tileW + elseif self.orientation == "staggered" then + local staggerX = self.staggeraxis == "x" + local even = self.staggerindex == "even" + + local function topLeft(x, y) + if staggerX then + if ceil(x) % 2 == 1 and even then + return x - 1, y + else + return x - 1, y - 1 + end + else + if ceil(y) % 2 == 1 and even then + return x, y - 1 + else + return x - 1, y - 1 + end + end + end + + local function topRight(x, y) + if staggerX then + if ceil(x) % 2 == 1 and even then + return x + 1, y + else + return x + 1, y - 1 + end + else + if ceil(y) % 2 == 1 and even then + return x + 1, y - 1 + else + return x, y - 1 + end + end + end + + local function bottomLeft(x, y) + if staggerX then + if ceil(x) % 2 == 1 and even then + return x - 1, y + 1 + else + return x - 1, y + end + else + if ceil(y) % 2 == 1 and even then + return x, y + 1 + else + return x - 1, y + 1 + end + end + end + + local function bottomRight(x, y) + if staggerX then + if ceil(x) % 2 == 1 and even then + return x + 1, y + 1 + else + return x + 1, y + end + else + if ceil(y) % 2 == 1 and even then + return x + 1, y + 1 + else + return x, y + 1 + end + end + end + + local tileW = self.tilewidth + local tileH = self.tileheight + + if staggerX then + x = x - (even and tileW / 2 or 0) + else + y = y - (even and tileH / 2 or 0) + end + + local halfH = tileH / 2 + local ratio = tileH / tileW + local referenceX = ceil(x / tileW) + local referenceY = ceil(y / tileH) + local relativeX = x - referenceX * tileW + local relativeY = y - referenceY * tileH + + if (halfH - relativeX * ratio > relativeY) then + return topLeft(referenceX, referenceY) + elseif (-halfH + relativeX * ratio > relativeY) then + return topRight(referenceX, referenceY) + elseif (halfH + relativeX * ratio < relativeY) then + return bottomLeft(referenceX, referenceY) + elseif (halfH * 3 - relativeX * ratio < relativeY) then + return bottomRight(referenceX, referenceY) + end + + return referenceX, referenceY + elseif self.orientation == "hexagonal" then + local staggerX = self.staggeraxis == "x" + local even = self.staggerindex == "even" + local tileW = self.tilewidth + local tileH = self.tileheight + local sideLenX = 0 + local sideLenY = 0 + + local colW = tileW / 2 + local rowH = tileH / 2 + if staggerX then + sideLenX = self.hexsidelength + x = x - (even and tileW or (tileW - sideLenX) / 2) + colW = colW - (colW - sideLenX / 2) / 2 + else + sideLenY = self.hexsidelength + y = y - (even and tileH or (tileH - sideLenY) / 2) + rowH = rowH - (rowH - sideLenY / 2) / 2 + end + + local referenceX = ceil(x) / (colW * 2) + local referenceY = ceil(y) / (rowH * 2) + + -- If in staggered line, then shift reference by 0.5 of other axes + if staggerX then + if (floor(referenceX) % 2 == 0) == even then + referenceY = referenceY - 0.5 + end + else + if (floor(referenceY) % 2 == 0) == even then + referenceX = referenceX - 0.5 + end + end + + local relativeX = x - referenceX * colW * 2 + local relativeY = y - referenceY * rowH * 2 + local centers + + if staggerX then + local left = sideLenX / 2 + local centerX = left + colW + local centerY = tileH / 2 + + centers = { + { x = left, y = centerY }, + { x = centerX, y = centerY - rowH }, + { x = centerX, y = centerY + rowH }, + { x = centerX + colW, y = centerY }, + } + else + local top = sideLenY / 2 + local centerX = tileW / 2 + local centerY = top + rowH + + centers = { + { x = centerX, y = top }, + { x = centerX - colW, y = centerY }, + { x = centerX + colW, y = centerY }, + { x = centerX, y = centerY + rowH } + } + end + + local nearest = 0 + local minDist = math.huge + + local function len2(ax, ay) + return ax * ax + ay * ay + end + + for i = 1, 4 do + local dc = len2(centers[i].x - relativeX, centers[i].y - relativeY) + + if dc < minDist then + minDist = dc + nearest = i + end + end + + local offsetsStaggerX = { + { x = 1, y = 1 }, + { x = 2, y = 0 }, + { x = 2, y = 1 }, + { x = 3, y = 1 }, + } + + local offsetsStaggerY = { + { x = 1, y = 1 }, + { x = 0, y = 2 }, + { x = 1, y = 2 }, + { x = 1, y = 3 }, + } + + local offsets = staggerX and offsetsStaggerX or offsetsStaggerY + + return + referenceX + offsets[nearest].x, + referenceY + offsets[nearest].y + end +end + +--- A list of individual layers indexed both by draw order and name +-- @table Map.layers +-- @see TileLayer +-- @see ObjectLayer +-- @see ImageLayer +-- @see CustomLayer + +--- A list of individual tiles indexed by Global ID +-- @table Map.tiles +-- @see Tile +-- @see Map.tileInstances + +--- A list of tile instances indexed by Global ID +-- @table Map.tileInstances +-- @see TileInstance +-- @see Tile +-- @see Map.tiles + +--- A list of no-longer-used batch sprites, indexed by batch +--@table Map.freeBatchSprites + +--- A list of individual objects indexed by Global ID +-- @table Map.objects +-- @see Object + +--- @table TileLayer +-- @field name The name of the layer +-- @field x Position on the X axis (in pixels) +-- @field y Position on the Y axis (in pixels) +-- @field width Width of layer (in tiles) +-- @field height Height of layer (in tiles) +-- @field visible Toggle if layer is visible or hidden +-- @field opacity Opacity of layer +-- @field properties Custom properties +-- @field data A tileWo dimensional table filled with individual tiles indexed by [y][x] (in tiles) +-- @field update Update function +-- @field draw Draw function +-- @see Map.layers +-- @see Tile + +--- @table ObjectLayer +-- @field name The name of the layer +-- @field x Position on the X axis (in pixels) +-- @field y Position on the Y axis (in pixels) +-- @field visible Toggle if layer is visible or hidden +-- @field opacity Opacity of layer +-- @field properties Custom properties +-- @field objects List of objects indexed by draw order +-- @field update Update function +-- @field draw Draw function +-- @see Map.layers +-- @see Object + +--- @table ImageLayer +-- @field name The name of the layer +-- @field x Position on the X axis (in pixels) +-- @field y Position on the Y axis (in pixels) +-- @field visible Toggle if layer is visible or hidden +-- @field opacity Opacity of layer +-- @field properties Custom properties +-- @field image Image to be drawn +-- @field update Update function +-- @field draw Draw function +-- @see Map.layers + +--- Custom Layers are used to place userdata such as sprites within the draw order of the map. +-- @table CustomLayer +-- @field name The name of the layer +-- @field x Position on the X axis (in pixels) +-- @field y Position on the Y axis (in pixels) +-- @field visible Toggle if layer is visible or hidden +-- @field opacity Opacity of layer +-- @field properties Custom properties +-- @field update Update function +-- @field draw Draw function +-- @see Map.layers +-- @usage +-- -- Create a Custom Layer +-- local spriteLayer = map:addCustomLayer("Sprite Layer", 3) +-- +-- -- Add data to Custom Layer +-- spriteLayer.sprites = { +-- player = { +-- image = lg.newImage("assets/sprites/player.png"), +-- x = 64, +-- y = 64, +-- r = 0, +-- } +-- } +-- +-- -- Update callback for Custom Layer +-- function spriteLayer:update(dt) +-- for _, sprite in pairs(self.sprites) do +-- sprite.r = sprite.r + math.rad(90 * dt) +-- end +-- end +-- +-- -- Draw callback for Custom Layer +-- function spriteLayer:draw() +-- for _, sprite in pairs(self.sprites) do +-- local x = math.floor(sprite.x) +-- local y = math.floor(sprite.y) +-- local r = sprite.r +-- lg.draw(sprite.image, x, y, r) +-- end +-- end + +--- @table Tile +-- @field id Local ID within Tileset +-- @field gid Global ID +-- @field tileset Tileset ID +-- @field quad Quad object +-- @field properties Custom properties +-- @field terrain Terrain data +-- @field animation Animation data +-- @field frame Current animation frame +-- @field time Time spent on current animation frame +-- @field width Width of tile +-- @field height Height of tile +-- @field sx Scale value on the X axis +-- @field sy Scale value on the Y axis +-- @field r Rotation of tile (in radians) +-- @field offset Offset drawing position +-- @field offset.x Offset value on the X axis +-- @field offset.y Offset value on the Y axis +-- @see Map.tiles + +--- @table TileInstance +-- @field batch Spritebatch the Tile Instance belongs to +-- @field id ID within the spritebatch +-- @field gid Global ID +-- @field x Position on the X axis (in pixels) +-- @field y Position on the Y axis (in pixels) +-- @see Map.tileInstances +-- @see Tile + +--- @table Object +-- @field id Global ID +-- @field name Name of object (non-unique) +-- @field shape Shape of object +-- @field x Position of object on X axis (in pixels) +-- @field y Position of object on Y axis (in pixels) +-- @field width Width of object (in pixels) +-- @field height Heigh tof object (in pixels) +-- @field rotation Rotation of object (in radians) +-- @field visible Toggle if object is visible or hidden +-- @field properties Custom properties +-- @field ellipse List of verticies of specific shape +-- @field rectangle List of verticies of specific shape +-- @field polygon List of verticies of specific shape +-- @field polyline List of verticies of specific shape +-- @see Map.objects + +return setmetatable({}, STI) diff --git a/libs/sti/plugins/box2d.lua b/libs/sti/plugins/box2d.lua new file mode 100644 index 0000000..c6d4148 --- /dev/null +++ b/libs/sti/plugins/box2d.lua @@ -0,0 +1,323 @@ +--- Box2D plugin for STI +-- @module box2d +-- @author Landon Manning +-- @copyright 2019 +-- @license MIT/X11 + +local love = _G.love +local utils = require((...):gsub('plugins.box2d', 'utils')) +local lg = require((...):gsub('plugins.box2d', 'graphics')) + +return { + box2d_LICENSE = "MIT/X11", + box2d_URL = "https://github.com/karai17/Simple-Tiled-Implementation", + box2d_VERSION = "2.3.2.7", + box2d_DESCRIPTION = "Box2D hooks for STI.", + + --- Initialize Box2D physics world. + -- @param world The Box2D world to add objects to. + box2d_init = function(map, world) + assert(love.physics, "To use the Box2D plugin, please enable the love.physics module.") + + local body = love.physics.newBody(world, map.offsetx, map.offsety) + local collision = { + body = body, + } + + local function addObjectToWorld(objshape, vertices, userdata, object) + local shape + + if objshape == "polyline" then + if #vertices == 4 then + shape = love.physics.newEdgeShape(unpack(vertices)) + else + shape = love.physics.newChainShape(false, unpack(vertices)) + end + else + shape = love.physics.newPolygonShape(unpack(vertices)) + end + + local currentBody = body + --dynamic are objects/players etc. + if userdata.properties.dynamic == true then + currentBody = love.physics.newBody(world, map.offsetx, map.offsety, 'dynamic') + -- static means it shouldn't move. Things like walls/ground. + elseif userdata.properties.static == true then + currentBody = love.physics.newBody(world, map.offsetx, map.offsety, 'static') + -- kinematic means that the object is static in the game world but effects other bodies + elseif userdata.properties.kinematic == true then + currentBody = love.physics.newBody(world, map.offsetx, map.offsety, 'kinematic') + end + + local fixture = love.physics.newFixture(currentBody, shape) + fixture:setUserData(userdata) + + -- Set some custom properties from userdata (or use default set by box2d) + fixture:setFriction(userdata.properties.friction or 0.2) + fixture:setRestitution(userdata.properties.restitution or 0.0) + fixture:setSensor(userdata.properties.sensor or false) + fixture:setFilterData( + userdata.properties.categories or 1, + userdata.properties.mask or 65535, + userdata.properties.group or 0 + ) + + local obj = { + object = object, + body = currentBody, + shape = shape, + fixture = fixture, + } + + table.insert(collision, obj) + end + + local function getPolygonVertices(object) + local vertices = {} + for _, vertex in ipairs(object.polygon) do + table.insert(vertices, vertex.x) + table.insert(vertices, vertex.y) + end + + return vertices + end + + local function calculateObjectPosition(object, tile) + local o = { + shape = object.shape, + x = (object.dx or object.x) + map.offsetx, + y = (object.dy or object.y) + map.offsety, + w = object.width, + h = object.height, + polygon = object.polygon or object.polyline or object.ellipse or object.rectangle + } + + local userdata = { + object = o, + properties = object.properties + } + + o.r = object.rotation or 0 + if o.shape == "rectangle" then + local cos = math.cos(math.rad(o.r)) + local sin = math.sin(math.rad(o.r)) + local oy = 0 + + if object.gid then + local tileset = map.tilesets[map.tiles[object.gid].tileset] + local lid = object.gid - tileset.firstgid + local t = {} + + -- This fixes a height issue + o.y = o.y + map.tiles[object.gid].offset.y + oy = o.h + + for _, tt in ipairs(tileset.tiles) do + if tt.id == lid then + t = tt + break + end + end + + if t.objectGroup then + for _, obj in ipairs(t.objectGroup.objects) do + -- Every object in the tile + calculateObjectPosition(obj, object) + end + + return + else + o.w = map.tiles[object.gid].width + o.h = map.tiles[object.gid].height + end + end + + o.polygon = { + { x=o.x+0, y=o.y+0 }, + { x=o.x+o.w, y=o.y+0 }, + { x=o.x+o.w, y=o.y+o.h }, + { x=o.x+0, y=o.y+o.h } + } + + for _, vertex in ipairs(o.polygon) do + vertex.x, vertex.y = utils.rotate_vertex(map, vertex, o.x, o.y, cos, sin, oy) + end + + local vertices = getPolygonVertices(o) + addObjectToWorld(o.shape, vertices, userdata, tile or object) + elseif o.shape == "ellipse" then + if not o.polygon then + o.polygon = utils.convert_ellipse_to_polygon(o.x, o.y, o.w, o.h) + end + local vertices = getPolygonVertices(o) + local triangles = love.math.triangulate(vertices) + + for _, triangle in ipairs(triangles) do + addObjectToWorld(o.shape, triangle, userdata, tile or object) + end + elseif o.shape == "polygon" then + -- Recalculate collision polygons inside tiles + if tile then + local cos = math.cos(math.rad(o.r)) + local sin = math.sin(math.rad(o.r)) + for _, vertex in ipairs(o.polygon) do + vertex.x = vertex.x + o.x + vertex.y = vertex.y + o.y + vertex.x, vertex.y = utils.rotate_vertex(map, vertex, o.x, o.y, cos, sin) + end + end + + local vertices = getPolygonVertices(o) + local triangles = love.math.triangulate(vertices) + + for _, triangle in ipairs(triangles) do + addObjectToWorld(o.shape, triangle, userdata, tile or object) + end + elseif o.shape == "polyline" then + local vertices = getPolygonVertices(o) + addObjectToWorld(o.shape, vertices, userdata, tile or object) + end + end + + for _, tile in pairs(map.tiles) do + if map.tileInstances[tile.gid] then + for _, instance in ipairs(map.tileInstances[tile.gid]) do + -- Every object in every instance of a tile + if tile.objectGroup then + for _, object in ipairs(tile.objectGroup.objects) do + if object.properties.collidable == true then + object = utils.deepCopy(object) + object.dx = instance.x + object.x + object.dy = instance.y + object.y + calculateObjectPosition(object, instance) + end + end + end + + -- Every instance of a tile + if tile.properties.collidable == true then + local object = { + shape = "rectangle", + x = instance.x, + y = instance.y, + width = map.tilewidth, + height = map.tileheight, + properties = tile.properties + } + + calculateObjectPosition(object, instance) + end + end + end + end + + for _, layer in ipairs(map.layers) do + -- Entire layer + if layer.properties.collidable == true then + if layer.type == "tilelayer" then + for gid, tiles in pairs(map.tileInstances) do + local tile = map.tiles[gid] + local tileset = map.tilesets[tile.tileset] + + for _, instance in ipairs(tiles) do + if instance.layer == layer then + local object = { + shape = "rectangle", + x = instance.x, + y = instance.y, + width = tileset.tilewidth, + height = tileset.tileheight, + properties = tile.properties + } + + calculateObjectPosition(object, instance) + end + end + end + elseif layer.type == "objectgroup" then + for _, object in ipairs(layer.objects) do + calculateObjectPosition(object) + end + elseif layer.type == "imagelayer" then + local object = { + shape = "rectangle", + x = layer.x or 0, + y = layer.y or 0, + width = layer.width, + height = layer.height, + properties = layer.properties + } + + calculateObjectPosition(object) + end + end + + -- Individual objects + if layer.type == "objectgroup" then + for _, object in ipairs(layer.objects) do + if object.properties.collidable == true then + calculateObjectPosition(object) + end + end + end + end + + map.box2d_collision = collision + end, + + --- Remove Box2D fixtures and shapes from world. + -- @param index The index or name of the layer being removed + box2d_removeLayer = function(map, index) + local layer = assert(map.layers[index], "Layer not found: " .. index) + local collision = map.box2d_collision + + -- Remove collision objects + for i = #collision, 1, -1 do + local obj = collision[i] + + if obj.object.layer == layer then + obj.fixture:destroy() + table.remove(collision, i) + end + end + end, + + --- Draw Box2D physics world. + -- @param tx Translate on X + -- @param ty Translate on Y + -- @param sx Scale on X + -- @param sy Scale on Y + box2d_draw = function(map, tx, ty, sx, sy) + local collision = map.box2d_collision + + lg.push() + lg.scale(sx or 1, sy or sx or 1) + lg.translate(math.floor(tx or 0), math.floor(ty or 0)) + + for _, obj in ipairs(collision) do + local points = {obj.body:getWorldPoints(obj.shape:getPoints())} + local shape_type = obj.shape:getType() + + if shape_type == "edge" or shape_type == "chain" then + love.graphics.line(points) + elseif shape_type == "polygon" then + love.graphics.polygon("line", points) + else + error("sti box2d plugin does not support "..shape_type.." shapes") + end + end + + lg.pop() + end +} + +--- Custom Properties in Tiled are used to tell this plugin what to do. +-- @table Properties +-- @field collidable set to true, can be used on any Layer, Tile, or Object +-- @field sensor set to true, can be used on any Tile or Object that is also collidable +-- @field dynamic set to true, can be used on any Tile or Object +-- @field friction can be used to define the friction of any Object +-- @field restitution can be used to define the restitution of any Object +-- @field categories can be used to set the filter Category of any Object +-- @field mask can be used to set the filter Mask of any Object +-- @field group can be used to set the filter Group of any Object diff --git a/libs/sti/plugins/bump.lua b/libs/sti/plugins/bump.lua new file mode 100644 index 0000000..1d4b828 --- /dev/null +++ b/libs/sti/plugins/bump.lua @@ -0,0 +1,193 @@ +--- Bump.lua plugin for STI +-- @module bump.lua +-- @author David Serrano (BobbyJones|FrenchFryLord) +-- @copyright 2019 +-- @license MIT/X11 + +local lg = require((...):gsub('plugins.bump', 'graphics')) + +return { + bump_LICENSE = "MIT/X11", + bump_URL = "https://github.com/karai17/Simple-Tiled-Implementation", + bump_VERSION = "3.1.7.1", + bump_DESCRIPTION = "Bump hooks for STI.", + + --- Adds each collidable tile to the Bump world. + -- @param world The Bump world to add objects to. + -- @return collidables table containing the handles to the objects in the Bump world. + bump_init = function(map, world) + local collidables = {} + + for _, tileset in ipairs(map.tilesets) do + for _, tile in ipairs(tileset.tiles) do + local gid = tileset.firstgid + tile.id + + if map.tileInstances[gid] then + for _, instance in ipairs(map.tileInstances[gid]) do + -- Every object in every instance of a tile + if tile.objectGroup then + for _, object in ipairs(tile.objectGroup.objects) do + if object.properties.collidable == true then + local t = { + name = object.name, + type = object.type, + x = instance.x + map.offsetx + object.x, + y = instance.y + map.offsety + object.y, + width = object.width, + height = object.height, + layer = instance.layer, + properties = object.properties + + } + + world:add(t, t.x, t.y, t.width, t.height) + table.insert(collidables, t) + end + end + end + + -- Every instance of a tile + if tile.properties and tile.properties.collidable == true then + local t = { + x = instance.x + map.offsetx, + y = instance.y + map.offsety, + width = map.tilewidth, + height = map.tileheight, + layer = instance.layer, + type = tile.type, + properties = tile.properties + } + + world:add(t, t.x, t.y, t.width, t.height) + table.insert(collidables, t) + end + end + end + end + end + + for _, layer in ipairs(map.layers) do + -- Entire layer + if layer.properties.collidable == true then + if layer.type == "tilelayer" then + for y, tiles in ipairs(layer.data) do + for x, tile in pairs(tiles) do + + if tile.objectGroup then + for _, object in ipairs(tile.objectGroup.objects) do + if object.properties.collidable == true then + local t = { + name = object.name, + type = object.type, + x = ((x-1) * map.tilewidth + tile.offset.x + map.offsetx) + object.x, + y = ((y-1) * map.tileheight + tile.offset.y + map.offsety) + object.y, + width = object.width, + height = object.height, + layer = layer, + properties = object.properties + } + + world:add(t, t.x, t.y, t.width, t.height) + table.insert(collidables, t) + end + end + end + + + local t = { + x = (x-1) * map.tilewidth + tile.offset.x + map.offsetx, + y = (y-1) * map.tileheight + tile.offset.y + map.offsety, + width = tile.width, + height = tile.height, + layer = layer, + type = tile.type, + properties = tile.properties + } + + world:add(t, t.x, t.y, t.width, t.height) + table.insert(collidables, t) + end + end + elseif layer.type == "imagelayer" then + world:add(layer, layer.x, layer.y, layer.width, layer.height) + table.insert(collidables, layer) + end + end + + -- individual collidable objects in a layer that is not "collidable" + -- or whole collidable objects layer + if layer.type == "objectgroup" then + for _, obj in ipairs(layer.objects) do + if layer.properties.collidable == true or obj.properties.collidable == true then + if obj.shape == "rectangle" then + local t = { + name = obj.name, + type = obj.type, + x = obj.x + map.offsetx, + y = obj.y + map.offsety, + width = obj.width, + height = obj.height, + layer = layer, + properties = obj.properties + } + + if obj.gid then + t.y = t.y - obj.height + end + + world:add(t, t.x, t.y, t.width, t.height) + table.insert(collidables, t) + end -- TODO implement other object shapes? + end + end + end + end + + map.bump_world = world + map.bump_collidables = collidables + end, + + --- Remove layer + -- @param index to layer to be removed + bump_removeLayer = function(map, index) + local layer = assert(map.layers[index], "Layer not found: " .. index) + local collidables = map.bump_collidables + + -- Remove collision objects + for i = #collidables, 1, -1 do + local obj = collidables[i] + + if obj.layer == layer + and ( + layer.properties.collidable == true + or obj.properties.collidable == true + ) then + map.bump_world:remove(obj) + table.remove(collidables, i) + end + end + end, + + --- Draw bump collisions world. + -- @param world bump world holding the tiles geometry + -- @param tx Translate on X + -- @param ty Translate on Y + -- @param sx Scale on X + -- @param sy Scale on Y + bump_draw = function(map, tx, ty, sx, sy) + lg.push() + lg.scale(sx or 1, sy or sx or 1) + lg.translate(math.floor(tx or 0), math.floor(ty or 0)) + + local items = map.bump_world:getItems() + for _, item in ipairs(items) do + lg.rectangle("line", map.bump_world:getRect(item)) + end + + lg.pop() + end +} + +--- Custom Properties in Tiled are used to tell this plugin what to do. +-- @table Properties +-- @field collidable set to true, can be used on any Layer, Tile, or Object diff --git a/libs/sti/utils.lua b/libs/sti/utils.lua new file mode 100644 index 0000000..95e857a --- /dev/null +++ b/libs/sti/utils.lua @@ -0,0 +1,217 @@ +-- Some utility functions that shouldn't be exposed. +local utils = {} + +-- https://github.com/stevedonovan/Penlight/blob/master/lua/pl/path.lua#L286 +function utils.format_path(path) + local np_gen1,np_gen2 = '[^SEP]+SEP%.%.SEP?','SEP+%.?SEP' + local np_pat1, np_pat2 = np_gen1:gsub('SEP','/'), np_gen2:gsub('SEP','/') + local k + + repeat -- /./ -> / + path,k = path:gsub(np_pat2,'/',1) + until k == 0 + + repeat -- A/../ -> (empty) + path,k = path:gsub(np_pat1,'',1) + until k == 0 + + if path == '' then path = '.' end + + return path +end + +-- Compensation for scale/rotation shift +function utils.compensate(tile, tileX, tileY, tileW, tileH) + local compx = 0 + local compy = 0 + + if tile.sx < 0 then compx = tileW end + if tile.sy < 0 then compy = tileH end + + if tile.r > 0 then + tileX = tileX + tileH - compy + tileY = tileY + tileH + compx - tileW + elseif tile.r < 0 then + tileX = tileX + compy + tileY = tileY - compx + tileH + else + tileX = tileX + compx + tileY = tileY + compy + end + + return tileX, tileY +end + +-- Cache images in main STI module +function utils.cache_image(sti, path, image) + image = image or love.graphics.newImage(path) + image:setFilter("nearest", "nearest") + sti.cache[path] = image +end + +-- We just don't know. +function utils.get_tiles(imageW, tileW, margin, spacing) + imageW = imageW - margin + local n = 0 + + while imageW >= tileW do + imageW = imageW - tileW + if n ~= 0 then imageW = imageW - spacing end + if imageW >= 0 then n = n + 1 end + end + + return n +end + +-- Decompress tile layer data +function utils.get_decompressed_data(data) + local ffi = require "ffi" + local d = {} + local decoded = ffi.cast("uint32_t*", data) + + for i = 0, data:len() / ffi.sizeof("uint32_t") do + table.insert(d, tonumber(decoded[i])) + end + + return d +end + +-- Convert a Tiled ellipse object to a LOVE polygon +function utils.convert_ellipse_to_polygon(x, y, w, h, max_segments) + local ceil = math.ceil + local cos = math.cos + local sin = math.sin + + local function calc_segments(segments) + local function vdist(a, b) + local c = { + x = a.x - b.x, + y = a.y - b.y, + } + + return c.x * c.x + c.y * c.y + end + + segments = segments or 64 + local vertices = {} + + local v = { 1, 2, ceil(segments/4-1), ceil(segments/4) } + + local m + if love and love.physics then + m = love.physics.getMeter() + else + m = 32 + end + + for _, i in ipairs(v) do + local angle = (i / segments) * math.pi * 2 + local px = x + w / 2 + cos(angle) * w / 2 + local py = y + h / 2 + sin(angle) * h / 2 + + table.insert(vertices, { x = px / m, y = py / m }) + end + + local dist1 = vdist(vertices[1], vertices[2]) + local dist2 = vdist(vertices[3], vertices[4]) + + -- Box2D threshold + if dist1 < 0.0025 or dist2 < 0.0025 then + return calc_segments(segments-2) + end + + return segments + end + + local segments = calc_segments(max_segments) + local vertices = {} + + table.insert(vertices, { x = x + w / 2, y = y + h / 2 }) + + for i = 0, segments do + local angle = (i / segments) * math.pi * 2 + local px = x + w / 2 + cos(angle) * w / 2 + local py = y + h / 2 + sin(angle) * h / 2 + + table.insert(vertices, { x = px, y = py }) + end + + return vertices +end + +function utils.rotate_vertex(map, vertex, x, y, cos, sin, oy) + if map.orientation == "isometric" then + x, y = utils.convert_isometric_to_screen(map, x, y) + vertex.x, vertex.y = utils.convert_isometric_to_screen(map, vertex.x, vertex.y) + end + + vertex.x = vertex.x - x + vertex.y = vertex.y - y + + return + x + cos * vertex.x - sin * vertex.y, + y + sin * vertex.x + cos * vertex.y - (oy or 0) +end + +--- Project isometric position to cartesian position +function utils.convert_isometric_to_screen(map, x, y) + local mapW = map.width + local tileW = map.tilewidth + local tileH = map.tileheight + local tileX = x / tileH + local tileY = y / tileH + local offsetX = mapW * tileW / 2 + + return + (tileX - tileY) * tileW / 2 + offsetX, + (tileX + tileY) * tileH / 2 +end + +function utils.hex_to_color(hex) + if hex:sub(1, 1) == "#" then + hex = hex:sub(2) + end + + return { + r = tonumber(hex:sub(1, 2), 16) / 255, + g = tonumber(hex:sub(3, 4), 16) / 255, + b = tonumber(hex:sub(5, 6), 16) / 255 + } +end + +function utils.pixel_function(_, _, r, g, b, a) + local mask = utils._TC + + if r == mask.r and + g == mask.g and + b == mask.b then + return r, g, b, 0 + end + + return r, g, b, a +end + +function utils.fix_transparent_color(tileset, path) + local image_data = love.image.newImageData(path) + tileset.image = love.graphics.newImage(image_data) + + if tileset.transparentcolor then + utils._TC = utils.hex_to_color(tileset.transparentcolor) + + image_data:mapPixel(utils.pixel_function) + tileset.image = love.graphics.newImage(image_data) + end +end + +function utils.deepCopy(t) + local copy = {} + for k,v in pairs(t) do + if type(v) == "table" then + v = utils.deepCopy(v) + end + copy[k] = v + end + return copy +end + +return utils diff --git a/libs/windfield/init.lua b/libs/windfield/init.lua new file mode 100644 index 0000000..2c7192a --- /dev/null +++ b/libs/windfield/init.lua @@ -0,0 +1,929 @@ +--[[ +The MIT License (MIT) + +Copyright (c) 2018 SSYGEN + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +]]-- + +local path = ... .. '.' +local wf = {} +wf.Math = require(path .. 'mlib.mlib') + +World = {} +World.__index = World + +function wf.newWorld(xg, yg, sleep) + local world = wf.World.new(wf, xg, yg, sleep) + + world.box2d_world:setCallbacks(world.collisionOnEnter, world.collisionOnExit, world.collisionPre, world.collisionPost) + world:collisionClear() + world:addCollisionClass('Default') + + -- Points all box2d_world functions to this wf.World object + -- This means that the user can call world:setGravity for instance without having to say world.box2d_world:setGravity + for k, v in pairs(world.box2d_world.__index) do + if k ~= '__gc' and k ~= '__eq' and k ~= '__index' and k ~= '__tostring' and k ~= 'update' and k ~= 'destroy' and k ~= 'type' and k ~= 'typeOf' then + world[k] = function(self, ...) + return v(self.box2d_world, ...) + end + end + end + + return world +end + +function World.new(wf, xg, yg, sleep) + local self = {} + local settings = settings or {} + self.wf = wf + + self.draw_query_for_n_frames = 10 + self.query_debug_drawing_enabled = false + self.explicit_collision_events = false + self.collision_classes = {} + self.masks = {} + self.is_sensor_memo = {} + self.query_debug_draw = {} + + love.physics.setMeter(32) + self.box2d_world = love.physics.newWorld(xg, yg, sleep) + + return setmetatable(self, World) +end + +function World:update(dt) + self:collisionEventsClear() + self.box2d_world:update(dt) +end + +function World:draw(alpha) + -- get the current color values to reapply + local r, g, b, a = love.graphics.getColor() + -- alpha value is optional + alpha = alpha or 255 + -- Colliders debug + love.graphics.setColor(222, 222, 222, alpha) + local bodies = self.box2d_world:getBodies() + for _, body in ipairs(bodies) do + local fixtures = body:getFixtures() + for _, fixture in ipairs(fixtures) do + if fixture:getShape():type() == 'PolygonShape' then + love.graphics.polygon('line', body:getWorldPoints(fixture:getShape():getPoints())) + elseif fixture:getShape():type() == 'EdgeShape' or fixture:getShape():type() == 'ChainShape' then + local points = {body:getWorldPoints(fixture:getShape():getPoints())} + for i = 1, #points, 2 do + if i < #points-2 then love.graphics.line(points[i], points[i+1], points[i+2], points[i+3]) end + end + elseif fixture:getShape():type() == 'CircleShape' then + local body_x, body_y = body:getPosition() + local shape_x, shape_y = fixture:getShape():getPoint() + local r = fixture:getShape():getRadius() + love.graphics.circle('line', body_x + shape_x, body_y + shape_y, r, 360) + end + end + end + love.graphics.setColor(255, 255, 255, alpha) + + -- Joint debug + love.graphics.setColor(222, 128, 64, alpha) + local joints = self.box2d_world:getJoints() + for _, joint in ipairs(joints) do + local x1, y1, x2, y2 = joint:getAnchors() + if x1 and y1 then love.graphics.circle('line', x1, y1, 4) end + if x2 and y2 then love.graphics.circle('line', x2, y2, 4) end + end + love.graphics.setColor(255, 255, 255, alpha) + + -- Query debug + love.graphics.setColor(64, 64, 222, alpha) + for _, query_draw in ipairs(self.query_debug_draw) do + query_draw.frames = query_draw.frames - 1 + if query_draw.type == 'circle' then + love.graphics.circle('line', query_draw.x, query_draw.y, query_draw.r) + elseif query_draw.type == 'rectangle' then + love.graphics.rectangle('line', query_draw.x, query_draw.y, query_draw.w, query_draw.h) + elseif query_draw.type == 'line' then + love.graphics.line(query_draw.x1, query_draw.y1, query_draw.x2, query_draw.y2) + elseif query_draw.type == 'polygon' then + local triangles = love.math.triangulate(query_draw.vertices) + for _, triangle in ipairs(triangles) do love.graphics.polygon('line', triangle) end + end + end + for i = #self.query_debug_draw, 1, -1 do + if self.query_debug_draw[i].frames <= 0 then + table.remove(self.query_debug_draw, i) + end + end + love.graphics.setColor(r, g, b, a) +end + +function World:setQueryDebugDrawing(value) + self.query_debug_drawing_enabled = value +end + +function World:setExplicitCollisionEvents(value) + self.explicit_collision_events = value +end + +function World:addCollisionClass(collision_class_name, collision_class) + if self.collision_classes[collision_class_name] then error('Collision class ' .. collision_class_name .. ' already exists.') end + + if self.explicit_collision_events then + self.collision_classes[collision_class_name] = collision_class or {} + else + self.collision_classes[collision_class_name] = collision_class or {} + self.collision_classes[collision_class_name].enter = {} + self.collision_classes[collision_class_name].exit = {} + self.collision_classes[collision_class_name].pre = {} + self.collision_classes[collision_class_name].post = {} + for c_class_name, _ in pairs(self.collision_classes) do + table.insert(self.collision_classes[collision_class_name].enter, c_class_name) + table.insert(self.collision_classes[collision_class_name].exit, c_class_name) + table.insert(self.collision_classes[collision_class_name].pre, c_class_name) + table.insert(self.collision_classes[collision_class_name].post, c_class_name) + end + for c_class_name, _ in pairs(self.collision_classes) do + table.insert(self.collision_classes[c_class_name].enter, collision_class_name) + table.insert(self.collision_classes[c_class_name].exit, collision_class_name) + table.insert(self.collision_classes[c_class_name].pre, collision_class_name) + table.insert(self.collision_classes[c_class_name].post, collision_class_name) + end + end + + self:collisionClassesSet() +end + +function World:collisionClassesSet() + self:generateCategoriesMasks() + + self:collisionClear() + local collision_table = self:getCollisionCallbacksTable() + for collision_class_name, collision_list in pairs(collision_table) do + for _, collision_info in ipairs(collision_list) do + if collision_info.type == 'enter' then self:addCollisionEnter(collision_class_name, collision_info.other) end + if collision_info.type == 'exit' then self:addCollisionExit(collision_class_name, collision_info.other) end + if collision_info.type == 'pre' then self:addCollisionPre(collision_class_name, collision_info.other) end + if collision_info.type == 'post' then self:addCollisionPost(collision_class_name, collision_info.other) end + end + end + + self:collisionEventsClear() +end + +function World:collisionClear() + self.collisions = {} + self.collisions.on_enter = {} + self.collisions.on_enter.sensor = {} + self.collisions.on_enter.non_sensor = {} + self.collisions.on_exit = {} + self.collisions.on_exit.sensor = {} + self.collisions.on_exit.non_sensor = {} + self.collisions.pre = {} + self.collisions.pre.sensor = {} + self.collisions.pre.non_sensor = {} + self.collisions.post = {} + self.collisions.post.sensor = {} + self.collisions.post.non_sensor = {} +end + +function World:collisionEventsClear() + local bodies = self.box2d_world:getBodies() + for _, body in ipairs(bodies) do + local collider = body:getFixtures()[1]:getUserData() + collider:collisionEventsClear() + end +end + +function World:addCollisionEnter(type1, type2) + if not self:isCollisionBetweenSensors(type1, type2) then + table.insert(self.collisions.on_enter.non_sensor, {type1 = type1, type2 = type2}) + else table.insert(self.collisions.on_enter.sensor, {type1 = type1, type2 = type2}) end +end + +function World:addCollisionExit(type1, type2) + if not self:isCollisionBetweenSensors(type1, type2) then + table.insert(self.collisions.on_exit.non_sensor, {type1 = type1, type2 = type2}) + else table.insert(self.collisions.on_exit.sensor, {type1 = type1, type2 = type2}) end +end + +function World:addCollisionPre(type1, type2) + if not self:isCollisionBetweenSensors(type1, type2) then + table.insert(self.collisions.pre.non_sensor, {type1 = type1, type2 = type2}) + else table.insert(self.collisions.pre.sensor, {type1 = type1, type2 = type2}) end +end + +function World:addCollisionPost(type1, type2) + if not self:isCollisionBetweenSensors(type1, type2) then + table.insert(self.collisions.post.non_sensor, {type1 = type1, type2 = type2}) + else table.insert(self.collisions.post.sensor, {type1 = type1, type2 = type2}) end +end + +function World:doesType1IgnoreType2(type1, type2) + local collision_ignores = {} + for collision_class_name, collision_class in pairs(self.collision_classes) do + collision_ignores[collision_class_name] = collision_class.ignores or {} + end + local all = {} + for collision_class_name, _ in pairs(collision_ignores) do + table.insert(all, collision_class_name) + end + local ignored_types = {} + for _, collision_class_type in ipairs(collision_ignores[type1]) do + if collision_class_type == 'All' then + for _, collision_class_name in ipairs(all) do + table.insert(ignored_types, collision_class_name) + end + else table.insert(ignored_types, collision_class_type) end + end + for key, _ in pairs(collision_ignores[type1]) do + if key == 'except' then + for _, except_type in ipairs(collision_ignores[type1].except) do + for i = #ignored_types, 1, -1 do + if ignored_types[i] == except_type then table.remove(ignored_types, i) end + end + end + end + end + for _, ignored_type in ipairs(ignored_types) do + if ignored_type == type2 then return true end + end +end + +function World:isCollisionBetweenSensors(type1, type2) + if not self.is_sensor_memo[type1] then self.is_sensor_memo[type1] = {} end + if not self.is_sensor_memo[type1][type2] then self.is_sensor_memo[type1][type2] = (self:doesType1IgnoreType2(type1, type2) or self:doesType1IgnoreType2(type2, type1)) end + if self.is_sensor_memo[type1][type2] then return true + else return false end +end + +-- https://love2d.org/forums/viewtopic.php?f=4&t=75441 +function World:generateCategoriesMasks() + local collision_ignores = {} + for collision_class_name, collision_class in pairs(self.collision_classes) do + collision_ignores[collision_class_name] = collision_class.ignores or {} + end + local incoming = {} + local expanded = {} + local all = {} + for object_type, _ in pairs(collision_ignores) do + incoming[object_type] = {} + expanded[object_type] = {} + table.insert(all, object_type) + end + for object_type, ignore_list in pairs(collision_ignores) do + for key, ignored_type in pairs(ignore_list) do + if ignored_type == 'All' then + for _, all_object_type in ipairs(all) do + table.insert(incoming[all_object_type], object_type) + table.insert(expanded[object_type], all_object_type) + end + elseif type(ignored_type) == 'string' then + if ignored_type ~= 'All' then + table.insert(incoming[ignored_type], object_type) + table.insert(expanded[object_type], ignored_type) + end + end + if key == 'except' then + for _, except_ignored_type in ipairs(ignored_type) do + for i, v in ipairs(incoming[except_ignored_type]) do + if v == object_type then + table.remove(incoming[except_ignored_type], i) + break + end + end + end + for _, except_ignored_type in ipairs(ignored_type) do + for i, v in ipairs(expanded[object_type]) do + if v == except_ignored_type then + table.remove(expanded[object_type], i) + break + end + end + end + end + end + end + local edge_groups = {} + for k, v in pairs(incoming) do + table.sort(v, function(a, b) return string.lower(a) < string.lower(b) end) + end + local i = 0 + for k, v in pairs(incoming) do + local str = "" + for _, c in ipairs(v) do + str = str .. c + end + if not edge_groups[str] then i = i + 1; edge_groups[str] = {n = i} end + table.insert(edge_groups[str], k) + end + local categories = {} + for k, _ in pairs(collision_ignores) do + categories[k] = {} + end + for k, v in pairs(edge_groups) do + for i, c in ipairs(v) do + categories[c] = v.n + end + end + for k, v in pairs(expanded) do + local category = {categories[k]} + local current_masks = {} + for _, c in ipairs(v) do + table.insert(current_masks, categories[c]) + end + self.masks[k] = {categories = category, masks = current_masks} + end +end + +function World:getCollisionCallbacksTable() + local collision_table = {} + for collision_class_name, collision_class in pairs(self.collision_classes) do + collision_table[collision_class_name] = {} + for _, v in ipairs(collision_class.enter or {}) do table.insert(collision_table[collision_class_name], {type = 'enter', other = v}) end + for _, v in ipairs(collision_class.exit or {}) do table.insert(collision_table[collision_class_name], {type = 'exit', other = v}) end + for _, v in ipairs(collision_class.pre or {}) do table.insert(collision_table[collision_class_name], {type = 'pre', other = v}) end + for _, v in ipairs(collision_class.post or {}) do table.insert(collision_table[collision_class_name], {type = 'post', other = v}) end + end + return collision_table +end + +local function collEnsure(collision_class_name1, a, collision_class_name2, b) + if a.collision_class == collision_class_name2 and b.collision_class == collision_class_name1 then return b, a + else return a, b end +end + +local function collIf(collision_class_name1, collision_class_name2, a, b) + if (a.collision_class == collision_class_name1 and b.collision_class == collision_class_name2) or + (a.collision_class == collision_class_name2 and b.collision_class == collision_class_name1) then + return true + else return false end +end + +function World.collisionOnEnter(fixture_a, fixture_b, contact) + local a, b = fixture_a:getUserData(), fixture_b:getUserData() + + if fixture_a:isSensor() and fixture_b:isSensor() then + if a and b then + for _, collision in ipairs(a.world.collisions.on_enter.sensor) do + if collIf(collision.type1, collision.type2, a, b) then + a, b = collEnsure(collision.type1, a, collision.type2, b) + table.insert(a.collision_events[collision.type2], {collision_type = 'enter', collider_1 = a, collider_2 = b, contact = contact}) + if collision.type1 == collision.type2 then + table.insert(b.collision_events[collision.type1], {collision_type = 'enter', collider_1 = b, collider_2 = a, contact = contact}) + end + end + end + end + + elseif not (fixture_a:isSensor() or fixture_b:isSensor()) then + if a and b then + for _, collision in ipairs(a.world.collisions.on_enter.non_sensor) do + if collIf(collision.type1, collision.type2, a, b) then + a, b = collEnsure(collision.type1, a, collision.type2, b) + table.insert(a.collision_events[collision.type2], {collision_type = 'enter', collider_1 = a, collider_2 = b, contact = contact}) + if collision.type1 == collision.type2 then + table.insert(b.collision_events[collision.type1], {collision_type = 'enter', collider_1 = b, collider_2 = a, contact = contact}) + end + end + end + end + end +end + +function World.collisionOnExit(fixture_a, fixture_b, contact) + local a, b = fixture_a:getUserData(), fixture_b:getUserData() + + if fixture_a:isSensor() and fixture_b:isSensor() then + if a and b then + for _, collision in ipairs(a.world.collisions.on_exit.sensor) do + if collIf(collision.type1, collision.type2, a, b) then + a, b = collEnsure(collision.type1, a, collision.type2, b) + table.insert(a.collision_events[collision.type2], {collision_type = 'exit', collider_1 = a, collider_2 = b, contact = contact}) + if collision.type1 == collision.type2 then + table.insert(b.collision_events[collision.type1], {collision_type = 'exit', collider_1 = b, collider_2 = a, contact = contact}) + end + end + end + end + + elseif not (fixture_a:isSensor() or fixture_b:isSensor()) then + if a and b then + for _, collision in ipairs(a.world.collisions.on_exit.non_sensor) do + if collIf(collision.type1, collision.type2, a, b) then + a, b = collEnsure(collision.type1, a, collision.type2, b) + table.insert(a.collision_events[collision.type2], {collision_type = 'exit', collider_1 = a, collider_2 = b, contact = contact}) + if collision.type1 == collision.type2 then + table.insert(b.collision_events[collision.type1], {collision_type = 'exit', collider_1 = b, collider_2 = a, contact = contact}) + end + end + end + end + end +end + +function World.collisionPre(fixture_a, fixture_b, contact) + local a, b = fixture_a:getUserData(), fixture_b:getUserData() + + if fixture_a:isSensor() and fixture_b:isSensor() then + if a and b then + for _, collision in ipairs(a.world.collisions.pre.sensor) do + if collIf(collision.type1, collision.type2, a, b) then + a, b = collEnsure(collision.type1, a, collision.type2, b) + a:preSolve(b, contact) + if collision.type1 == collision.type2 then + b:preSolve(a, contact) + end + end + end + end + + elseif not (fixture_a:isSensor() or fixture_b:isSensor()) then + if a and b then + for _, collision in ipairs(a.world.collisions.pre.non_sensor) do + if collIf(collision.type1, collision.type2, a, b) then + a, b = collEnsure(collision.type1, a, collision.type2, b) + a:preSolve(b, contact) + if collision.type1 == collision.type2 then + b:preSolve(a, contact) + end + end + end + end + end +end + +function World.collisionPost(fixture_a, fixture_b, contact, ni1, ti1, ni2, ti2) + local a, b = fixture_a:getUserData(), fixture_b:getUserData() + + if fixture_a:isSensor() and fixture_b:isSensor() then + if a and b then + for _, collision in ipairs(a.world.collisions.post.sensor) do + if collIf(collision.type1, collision.type2, a, b) then + a, b = collEnsure(collision.type1, a, collision.type2, b) + a:postSolve(b, contact, ni1, ti1, ni2, ti2) + if collision.type1 == collision.type2 then + b:postSolve(a, contact, ni1, ti1, ni2, ti2) + end + end + end + end + + elseif not (fixture_a:isSensor() or fixture_b:isSensor()) then + if a and b then + for _, collision in ipairs(a.world.collisions.post.non_sensor) do + if collIf(collision.type1, collision.type2, a, b) then + a, b = collEnsure(collision.type1, a, collision.type2, b) + a:postSolve(b, contact, ni1, ti1, ni2, ti2) + if collision.type1 == collision.type2 then + b:postSolve(a, contact, ni1, ti1, ni2, ti2) + end + end + end + end + end +end + +function World:newCircleCollider(x, y, r, settings) + return self.wf.Collider.new(self, 'Circle', x, y, r, settings) +end + +function World:newRectangleCollider(x, y, w, h, settings) + return self.wf.Collider.new(self, 'Rectangle', x, y, w, h, settings) +end + +function World:newBSGRectangleCollider(x, y, w, h, corner_cut_size, settings) + return self.wf.Collider.new(self, 'BSGRectangle', x, y, w, h, corner_cut_size, settings) +end + +function World:newPolygonCollider(vertices, settings) + return self.wf.Collider.new(self, 'Polygon', vertices, settings) +end + +function World:newLineCollider(x1, y1, x2, y2, settings) + return self.wf.Collider.new(self, 'Line', x1, y1, x2, y2, settings) +end + +function World:newChainCollider(vertices, loop, settings) + return self.wf.Collider.new(self, 'Chain', vertices, loop, settings) +end + +-- Internal AABB box2d query used before going for more specific and precise computations. +function World:_queryBoundingBox(x1, y1, x2, y2) + local colliders = {} + local callback = function(fixture) + if not fixture:isSensor() then table.insert(colliders, fixture:getUserData()) end + return true + end + self.box2d_world:queryBoundingBox(x1, y1, x2, y2, callback) + return colliders +end + +function World:collisionClassInCollisionClassesList(collision_class, collision_classes) + if collision_classes[1] == 'All' then + local all_collision_classes = {} + for class, _ in pairs(self.collision_classes) do + table.insert(all_collision_classes, class) + end + if collision_classes.except then + for _, except in ipairs(collision_classes.except) do + for i, class in ipairs(all_collision_classes) do + if class == except then + table.remove(all_collision_classes, i) + break + end + end + end + end + for _, class in ipairs(all_collision_classes) do + if class == collision_class then return true end + end + else + for _, class in ipairs(collision_classes) do + if class == collision_class then return true end + end + end +end + +function World:queryCircleArea(x, y, radius, collision_class_names) + if not collision_class_names then collision_class_names = {'All'} end + if self.query_debug_drawing_enabled then table.insert(self.query_debug_draw, {type = 'circle', x = x, y = y, r = radius, frames = self.draw_query_for_n_frames}) end + + local colliders = self:_queryBoundingBox(x-radius, y-radius, x+radius, y+radius) + local outs = {} + for _, collider in ipairs(colliders) do + if self:collisionClassInCollisionClassesList(collider.collision_class, collision_class_names) then + for _, fixture in ipairs(collider.body:getFixtures()) do + if self.wf.Math.polygon.getCircleIntersection(x, y, radius, {collider.body:getWorldPoints(fixture:getShape():getPoints())}) then + table.insert(outs, collider) + break + end + end + end + end + return outs +end + +function World:queryRectangleArea(x, y, w, h, collision_class_names) + if not collision_class_names then collision_class_names = {'All'} end + if self.query_debug_drawing_enabled then table.insert(self.query_debug_draw, {type = 'rectangle', x = x, y = y, w = w, h = h, frames = self.draw_query_for_n_frames}) end + + local colliders = self:_queryBoundingBox(x, y, x+w, y+h) + local outs = {} + for _, collider in ipairs(colliders) do + if self:collisionClassInCollisionClassesList(collider.collision_class, collision_class_names) then + for _, fixture in ipairs(collider.body:getFixtures()) do + if self.wf.Math.polygon.isPolygonInside({x, y, x+w, y, x+w, y+h, x, y+h}, {collider.body:getWorldPoints(fixture:getShape():getPoints())}) then + table.insert(outs, collider) + break + end + end + end + end + return outs +end + +function World:queryPolygonArea(vertices, collision_class_names) + if not collision_class_names then collision_class_names = {'All'} end + if self.query_debug_drawing_enabled then table.insert(self.query_debug_draw, {type = 'polygon', vertices = vertices, frames = self.draw_query_for_n_frames}) end + + local cx, cy = self.wf.Math.polygon.getCentroid(vertices) + local d_max = 0 + for i = 1, #vertices, 2 do + local d = self.wf.Math.line.getLength(cx, cy, vertices[i], vertices[i+1]) + if d > d_max then d_max = d end + end + local colliders = self:_queryBoundingBox(cx-d_max, cy-d_max, cx+d_max, cy+d_max) + local outs = {} + for _, collider in ipairs(colliders) do + if self:collisionClassInCollisionClassesList(collider.collision_class, collision_class_names) then + for _, fixture in ipairs(collider.body:getFixtures()) do + if self.wf.Math.polygon.isPolygonInside(vertices, {collider.body:getWorldPoints(fixture:getShape():getPoints())}) then + table.insert(outs, collider) + break + end + end + end + end + return outs +end + +function World:queryLine(x1, y1, x2, y2, collision_class_names) + if not collision_class_names then collision_class_names = {'All'} end + if self.query_debug_drawing_enabled then + table.insert(self.query_debug_draw, {type = 'line', x1 = x1, y1 = y1, x2 = x2, y2 = y2, frames = self.draw_query_for_n_frames}) + end + + local colliders = {} + local callback = function(fixture, ...) + if not fixture:isSensor() then table.insert(colliders, fixture:getUserData()) end + return 1 + end + self.box2d_world:rayCast(x1, y1, x2, y2, callback) + + local outs = {} + for _, collider in ipairs(colliders) do + if self:collisionClassInCollisionClassesList(collider.collision_class, collision_class_names) then + table.insert(outs, collider) + end + end + return outs +end + +function World:addJoint(joint_type, ...) + local args = {...} + if args[1].body then args[1] = args[1].body end + if type(args[2]) == "table" and args[2].body then args[2] = args[2].body end + local joint = love.physics['new' .. joint_type](unpack(args)) + return joint +end + +function World:removeJoint(joint) + joint:destroy() +end + +function World:destroy() + local bodies = self.box2d_world:getBodies() + for _, body in ipairs(bodies) do + local collider = body:getFixtures()[1]:getUserData() + collider:destroy() + end + local joints = self.box2d_world:getJoints() + for _, joint in ipairs(joints) do joint:destroy() end + self.box2d_world:destroy() + self.box2d_world = nil +end + + + +local Collider = {} +Collider.__index = Collider + +local generator = love.math.newRandomGenerator(os.time()) +local function UUID() + local fn = function(x) + local r = generator:random(16) - 1 + r = (x == "x") and (r + 1) or (r % 4) + 9 + return ("0123456789abcdef"):sub(r, r) + end + return (("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"):gsub("[xy]", fn)) +end + +function Collider.new(world, collider_type, ...) + local self = {} + self.id = UUID() + self.world = world + self.type = collider_type + self.object = nil + + self.shapes = {} + self.fixtures = {} + self.sensors = {} + + self.collision_events = {} + self.collision_stay = {} + self.enter_collision_data = {} + self.exit_collision_data = {} + self.stay_collision_data = {} + + local args = {...} + local shape, fixture + if self.type == 'Circle' then + self.collision_class = (args[4] and args[4].collision_class) or 'Default' + self.body = love.physics.newBody(self.world.box2d_world, args[1], args[2], (args[4] and args[4].body_type) or 'dynamic') + shape = love.physics.newCircleShape(args[3]) + + elseif self.type == 'Rectangle' then + self.collision_class = (args[5] and args[5].collision_class) or 'Default' + self.body = love.physics.newBody(self.world.box2d_world, args[1] + args[3]/2, args[2] + args[4]/2, (args[5] and args[5].body_type) or 'dynamic') + shape = love.physics.newRectangleShape(args[3], args[4]) + + elseif self.type == 'BSGRectangle' then + self.collision_class = (args[6] and args[6].collision_class) or 'Default' + self.body = love.physics.newBody(self.world.box2d_world, args[1] + args[3]/2, args[2] + args[4]/2, (args[6] and args[6].body_type) or 'dynamic') + local w, h, s = args[3], args[4], args[5] + shape = love.physics.newPolygonShape({ + -w/2, -h/2 + s, -w/2 + s, -h/2, + w/2 - s, -h/2, w/2, -h/2 + s, + w/2, h/2 - s, w/2 - s, h/2, + -w/2 + s, h/2, -w/2, h/2 - s + }) + + elseif self.type == 'Polygon' then + self.collision_class = (args[2] and args[2].collision_class) or 'Default' + self.body = love.physics.newBody(self.world.box2d_world, 0, 0, (args[2] and args[2].body_type) or 'dynamic') + shape = love.physics.newPolygonShape(unpack(args[1])) + + elseif self.type == 'Line' then + self.collision_class = (args[5] and args[5].collision_class) or 'Default' + self.body = love.physics.newBody(self.world.box2d_world, 0, 0, (args[5] and args[5].body_type) or 'dynamic') + shape = love.physics.newEdgeShape(args[1], args[2], args[3], args[4]) + + elseif self.type == 'Chain' then + self.collision_class = (args[3] and args[3].collision_class) or 'Default' + self.body = love.physics.newBody(self.world.box2d_world, 0, 0, (args[3] and args[3].body_type) or 'dynamic') + shape = love.physics.newChainShape(args[1], unpack(args[2])) + end + + -- Define collision classes and attach them to fixture and sensor + fixture = love.physics.newFixture(self.body, shape) + if self.world.masks[self.collision_class] then + fixture:setCategory(unpack(self.world.masks[self.collision_class].categories)) + fixture:setMask(unpack(self.world.masks[self.collision_class].masks)) + end + fixture:setUserData(self) + local sensor = love.physics.newFixture(self.body, shape) + sensor:setSensor(true) + sensor:setUserData(self) + + self.shapes['main'] = shape + self.fixtures['main'] = fixture + self.sensors['main'] = sensor + self.shape = shape + self.fixture = fixture + + self.preSolve = function() end + self.postSolve = function() end + + -- Points all body, fixture and shape functions to this wf.Collider object + -- This means that the user can call collider:setLinearVelocity for instance without having to say collider.body:setLinearVelocity + for k, v in pairs(self.body.__index) do + if k ~= '__gc' and k ~= '__eq' and k ~= '__index' and k ~= '__tostring' and k ~= 'destroy' and k ~= 'type' and k ~= 'typeOf' then + self[k] = function(self, ...) + return v(self.body, ...) + end + end + end + for k, v in pairs(self.fixture.__index) do + if k ~= '__gc' and k ~= '__eq' and k ~= '__index' and k ~= '__tostring' and k ~= 'destroy' and k ~= 'type' and k ~= 'typeOf' then + self[k] = function(self, ...) + return v(self.fixture, ...) + end + end + end + for k, v in pairs(self.shape.__index) do + if k ~= '__gc' and k ~= '__eq' and k ~= '__index' and k ~= '__tostring' and k ~= 'destroy' and k ~= 'type' and k ~= 'typeOf' then + self[k] = function(self, ...) + return v(self.shape, ...) + end + end + end + + return setmetatable(self, Collider) +end + +function Collider:collisionEventsClear() + self.collision_events = {} + for other, _ in pairs(self.world.collision_classes) do + self.collision_events[other] = {} + end +end + +function Collider:setCollisionClass(collision_class_name) + if not self.world.collision_classes[collision_class_name] then error("Collision class " .. collision_class_name .. " doesn't exist.") end + self.collision_class = collision_class_name + for _, fixture in pairs(self.fixtures) do + if self.world.masks[collision_class_name] then + fixture:setCategory(unpack(self.world.masks[collision_class_name].categories)) + fixture:setMask(unpack(self.world.masks[collision_class_name].masks)) + end + end +end + +function Collider:enter(other_collision_class_name) + local events = self.collision_events[other_collision_class_name] + if events and #events >= 1 then + for _, e in ipairs(events) do + if e.collision_type == 'enter' then + if not self.collision_stay[other_collision_class_name] then self.collision_stay[other_collision_class_name] = {} end + table.insert(self.collision_stay[other_collision_class_name], {collider = e.collider_2, contact = e.contact}) + self.enter_collision_data[other_collision_class_name] = {collider = e.collider_2, contact = e.contact} + return true + end + end + end +end + +function Collider:getEnterCollisionData(other_collision_class_name) + return self.enter_collision_data[other_collision_class_name] +end + +function Collider:exit(other_collision_class_name) + local events = self.collision_events[other_collision_class_name] + if events and #events >= 1 then + for _, e in ipairs(events) do + if e.collision_type == 'exit' then + if self.collision_stay[other_collision_class_name] then + for i = #self.collision_stay[other_collision_class_name], 1, -1 do + local collision_stay = self.collision_stay[other_collision_class_name][i] + if collision_stay.collider.id == e.collider_2.id then table.remove(self.collision_stay[other_collision_class_name], i) end + end + end + self.exit_collision_data[other_collision_class_name] = {collider = e.collider_2, contact = e.contact} + return true + end + end + end +end + +function Collider:getExitCollisionData(other_collision_class_name) + return self.exit_collision_data[other_collision_class_name] +end + +function Collider:stay(other_collision_class_name) + if self.collision_stay[other_collision_class_name] then + if #self.collision_stay[other_collision_class_name] >= 1 then + return true + end + end +end + +function Collider:getStayCollisionData(other_collision_class_name) + return self.collision_stay[other_collision_class_name] +end + +function Collider:setPreSolve(callback) + self.preSolve = callback +end + +function Collider:setPostSolve(callback) + self.postSolve = callback +end + +function Collider:setObject(object) + self.object = object +end + +function Collider:getObject() + return self.object +end + +function Collider:addShape(shape_name, shape_type, ...) + if self.shapes[shape_name] or self.fixtures[shape_name] then error("Shape/fixture " .. shape_name .. " already exists.") end + local args = {...} + local shape = love.physics['new' .. shape_type](unpack(args)) + local fixture = love.physics.newFixture(self.body, shape) + if self.world.masks[self.collision_class] then + fixture:setCategory(unpack(self.world.masks[self.collision_class].categories)) + fixture:setMask(unpack(self.world.masks[self.collision_class].masks)) + end + fixture:setUserData(self) + local sensor = love.physics.newFixture(self.body, shape) + sensor:setSensor(true) + sensor:setUserData(self) + + self.shapes[shape_name] = shape + self.fixtures[shape_name] = fixture + self.sensors[shape_name] = sensor +end + +function Collider:removeShape(shape_name) + if not self.shapes[shape_name] then return end + self.shapes[shape_name] = nil + self.fixtures[shape_name]:setUserData(nil) + self.fixtures[shape_name]:destroy() + self.fixtures[shape_name] = nil + self.sensors[shape_name]:setUserData(nil) + self.sensors[shape_name]:destroy() + self.sensors[shape_name] = nil +end + +function Collider:destroy() + self.collision_stay = nil + self.enter_collision_data = nil + self.exit_collision_data = nil + self:collisionEventsClear() + + self:setObject(nil) + for name, _ in pairs(self.fixtures) do + self.shapes[name] = nil + self.fixtures[name]:setUserData(nil) + self.fixtures[name] = nil + self.sensors[name]:setUserData(nil) + self.sensors[name] = nil + end + self.body:destroy() + self.body = nil +end + +wf.World = World +wf.Collider = Collider + +return wf + diff --git a/libs/windfield/mlib/Changes.txt b/libs/windfield/mlib/Changes.txt new file mode 100644 index 0000000..4e7fc52 --- /dev/null +++ b/libs/windfield/mlib/Changes.txt @@ -0,0 +1,568 @@ +0.11.0 +==== +Added: +---- +- mlib.vec2 component + +To-Do: +---- +- Update README.md +- Update spec.lua +- Fix tabbing + +0.10.1 +==== +Added: +---- +- Point category + - point.rotate + - point.scale + - point.polarToCartesian + - point.cartesianToPolar + +Changed: +---- +- math.getPercent now returns decimals (instead of percentages) since those are more common to use. + +To-Do: +---- +- Determine if isCompletelyInsideFunctions should return true with tangents. +- Check argument order for logicality and consistency. +- Add error checking. +- Make sure to see if any aliases were missed. (e.g. isSegmentInside) +- Clean up and correct README (add "Home" link, etc.) + +0.10.0 +==== +Added: +---- + +Changed: +---- +- mlib.line.segment is now mlib.segment. +- mlib.line.getIntercept has been renamed to mlib.line.getYIntercept +- mlib.line.getYIntercept now returns the x-coordinate for vertical lines instead of false. +- mlib.line.getYIntercept now returns the value `isVertical` as the second return value. +- mlib.line.getPerpendicularBisector is now mlib.segment.getPerpendicularBisector. + +Fixed: +---- +- mlib.line.getIntersection now should handle vertical slopes better. +- mlib.line.getClosestPoint now uses local function checkFuzzy for checking horizontal lines. +- Fixed possible bug in mlib.line.getSegmentIntersection and vertical lines. +- mlib.segment.getIntersection now uses fuzzy checking for parallel lines. +- mlib.math.round is now much more efficient. +- Removed some useless code from mlib.polygon.isSegmentInside. + +To-Do: +---- +- Determine if isCompletelyInsideFunctions should return true with tangents. +- Check argument order for logicality and consistency. +- Improve speed. +- Add error checking. +- Make sure to see if any aliases were missed. (e.g. isSegmentInside) +- Implement mlib.shapes again(?) +- Clean up and correct README (add "Home" link, etc.) + +0.9.4 +==== +Added: +---- + +Changed: +---- +- mlib.line.getDistance is now slightly faster. +- Made code much easier to debug by using new utility `cycle`. +- Added new utility. +- Various other minor changes. + +Removed: +---- +- Unused local utility function copy + +To-Do +---- +- Determine if isCompletelyInsideFunctions should return true with tangents. +- Make argument order more logical. +- Improve speed and error checking. +- Make sure to see if any aliases were missed. (e.g. isSegmentInside) +- Implement mlib.shapes again(?) +- Clean up README (add "Home" link, etc.) + +0.9.3 +==== +Added: +---- +- milb.circle.isCircleCompletelyInside +- mlib.circle.isPolygonCompletelyInside +- milb.circle.isSegmentCompletelyInside +- mlib.polygon.isCircleCompletelyInside +- mlib.polygon.isPolygonCompletelyInside +- mlib.polygon.isSegmentCompletelyInside + + - ALIASES - +- mlib.circle.getPolygonIntersection +- mlib.circle.isCircleInsidePolygon +- mlib.circle.isCircleCompletelyInsidePolygon +- milb.line.getCircleIntersection +- milb.line.getPolygonIntersection +- milb.line.getLineIntersection +- mlib.line.segment.getCircleIntersection +- mlib.line.segment.getPolygonIntersection +- mlib.line.segment.getLineIntersection +- mlib.line.segment.getSegmentIntersection +- mlib.line.segment.isSegmentCompletelyInsideCircle +- mlib.line.segment.isSegmentCompletelyInsidePolygon +- mlib.polygon.isCircleCompletelyOver + +Changed: +---- +- mlib.circle.getCircleIntersection now returns 'inside' instead of 'intersection' if the point has not intersections but is within the circle. +- Fixed problem involving mlib.circle.getSegmentIntersection + +- README.md now has more information on how to run specs and other minor improvements. +- Fixed some commenting on explanation of derivation of mlib.line.getIntersection. +- Updated the example to use the current version of mlib. +- Made/Changed some comments in the example main.lua. + +Removed: +---- + +To-Do +---- +- Make examples file on github (examples/shapes/main.lua, etc.) not just one line. +- Determine if isCompletelyInsideFunctions should return true with tangents. +- Make argument order more logical. +- Make sure to see if any aliases were missed. (e.g. isSegmentInside) +- Update spec links in README + +0.9.2 +==== +Added: +---- + +Changed: +---- +- mlib.polygon.getPolygonIntersection now does not create duplicate local table. +- mlib.line.getPerpendicularSlope now does not create a global variable. +- mlib.math.getSummation now allows the error to go through instead of returning false if the stop value is not a number. + +- Changed any instance of the term "userdata" with "input" + +Removed: +---- + +0.9.1 +==== +Added: +---- +- Added mlib.statistics.getCentralTendency +- Added mlib.statistics.getDispersion +- Added mlib.statistics.getStandardDeviation +- Added mlib.statistics.getVariation +- Added mlib.statistics.getVariationRatio + +Removed: +---- + +Changed: +---- +- FIX: mlib.polygon.checkPoint now handles vertices better. + + +To-Do +---- +- Add more functions. + +0.9.0 +==== +Added: +---- +- mlib.line.getDistance as an alias for mlib.line.getLength. +- mlib.line.checkPoint +- Internal documentation. + +Removed: +---- +- mlib.circle.isPointInCircle is replaced with mlib.circle.checkPoint +- mlib.circle.checkPoint is replaced with mlib.circle.isPointOnCircle +- Variation of mlib.circle.getLineIntersection( cx, cy, radius, slope, intercept ) is no longer supported, as it can cause errors with vertical lines. + +Changed: +---- +- CHANGE: mlib.line.getIntersection now returns true for colinear lines. +- CHANGE: mlib.line.getIntersection now returns true if the line are collinear. +- CHANGE: mlib.line.getIntersection now returns true if vertical lines are collinear. +- CHANGE: mlib.line.getSegmentIntersection now returns true if the line and segment are collinear. +- CHANGE: Changed the order of mlib.line.segment.checkPoint arguments. +- NAME: mlib.polygon.lineIntersects is now mlib.polygon.getLineIntersection +- NAME: mlib.polygon.lineSegmentIntersects is now mlib.polygon.getSegmentIntersection +- NAME: mlib.polygon.isLineSegmentInside is now mlib.polygon.isSegmentInside +- NAME: mlib.polygon.polygonIntersects is now mlib.polygon.getPolygonIntersection +- CHANGED: mlib.circle.checkPoint now takes arguments ( px, py, cx, cy, radius ). +- CHANGED: mlib.circle.isPointOnCircle now takes arguments ( px, py, cx, cy, radius ). +- NAME: mlib.polygon.circleIntersects is now mlib.polygon.getCircleIntersection +- NAME: mlib.circle.isLineSecant is now mlib.circle.getLineIntersection +- NAME: mlib.circle.isSegmentSecant is now mlib.circle.getSegmentIntersection +- NAME: mlib.circle.circlesIntersects is now mlib.circle.getCircleIntersection +- CHANGE: Added types 'tangent' and 'intersection' to mlib.circle.getCircleIntersection. +- NAME: mlib.math.getRootsOfQuadratic is now mlib.math.getQuadraticRoots +- CHANGE: mlib.math.getRoot now only returns the positive, since it there is not always negatives. +- NAME: mlib.math.getPercent is now mlib.math.getPercentage + +- Cleaned up code (added comments, spaced lines, etc.) +- Made syntax that uses camelCase instead of CamelCase. + - Match style of more programmers. + - Easier to type. +- Moved to semantic numbering. +- Made any returns strings lower-case. +- Updated specs for missing functions. + +To-Do +---- +- Update readme. +- Add mlib.statistics.getStandardDeviation +- Add mlib.statistics.getMeasuresOfCentralTendency +- Add mlib.statistics.getMeasuresOfDispersion + +1.1.0.2 +==== +Added: +---- +- MLib.Polygon.IsPolygonInside + +Removed: +---- +- Removed all MLib.Shape: + - Was very slow. + - Could not define custom callbacks. + - Allow for flexibility. + +Changed: +---- +- Switched MLib.Line.GetIntersection back to the old way +- MLib.Line.GetSegmentIntersection now returns 4 values if the lines are parallel. + +TODO: +- Make it so that MLib.Shape objects can use ':' syntax for other functions (i.e. MLib.Line.GetLength for Line objects, etc.) +- Intuitive error messages. + + +1.1.0.1 +==== +Added: +---- + +Removed: +---- + +Changed: +- MLib.Line.GetIntersection now returns true, instead of two points. + +---- + +Fixed: +---- +- MLib.Line.GetIntersection now handles vertical lines: returns true if they collide, false otherwise. +- MLib.Polygon.LineIntersects now also handles verticals. + +TODO: +- Fix + - MLib.Shape Table can't have metatables. + +1.1.0.0 +==== +Added: +---- +- MLib.Polygon.IsCircleInside +- MLib.Polygon.LineSegmentIntersects +- MLib.Polygon.IsLineSegmentInside +- MLib.Statistics.GetFrequency +- MLib.Math.Factorial +- MLib.Math.SystemOfEquations + +Removed: +---- + +Changed: +---- +- MLib.Polygon.LineIntersects is now MLib.Polygon.LineSegmentIntersects. +- Put Word-wrap on Changes.txt + +Fixed: +---- +- Problems with numberous MLib.Polygon and MLib.Circle problems. + +TODO: +- Fix + - MLib.Shape Table can't have metatables. + +1.0.0.3 +==== +Added: +---- + +Removed: +---- + +Changed: +---- + +Fixed: +---- +- README.md + +TODO: +- Add: + - Frequency + - Binomial Probability + - Standard Deviation + - Conditional Probability + +1.0.0.2 +==== +Added: +---- + +Removed: +---- +- Ability to use a direction for Math.GetAngle's 5th argument instead of having a third point. See Fixed for more. + +Changed: +---- +- Changed README.md for clarity and consistency. +- Updated spec.lua +- See Fixed for more. + +Fixed: +---- +- Circle.IsSegmentSecant now properly accounts for chords actually being chords, and not secants. +- Circle.CircleIntersects now can return 'Colinear' or 'Equal' if the circles have same x and y but different radii (Colinear) or are exactly the same (Equal). +- Statistics.GetMode now returns a table with the modes, and the second argument as the number of times they appear. +- Math.GetRoot now returns the negative number as a second argument. +- Math.GetPercentOfChange now works for 0 to 0 (previously false). +- Math.GetAngle now takes only three points and no direction option. +- Typos in Shape.CheckCollisions and Shape.Remove. +- Fixed nil problems in Shape.CheckCollisions. +- Improved readablility and DRYness of Shape.CheckCollisions. +- Bugs in Shape.Remove and Shape.CheckCollisions regarding passing tables as arguments. + +TODO: +- Add: + - Frequency + - Binomial Probability + - Standard Deviation + - Conditional Probability + +1.0.0.1 +==== +Added: +---- + +Removed: +---- + +Changed: +---- +- Changes.txt now expanded to include short excertps from all previous commits. +- Changed release number from 3.0.0 to 1.0.0.1 +- Math.Round now can round to decimal places as the second argument. +- Commented unnecessary call of Segment.CheckPoint in Polygon.LineIntersects. +- Polygon.LineIntersects now returns where the lines intersect. + - false if not intersection. + - A table with all of the intersections { { px, py } } +- Same with Polygon.PolygonIntersects, Polygon.CircleIntersects, + +Fixed: +---- +- Error with GetSlope being called incorrectly. +- README.md Line.GetPerpendicularSlope misdirection. +- Same with Line.GetPerpendicularBisector, Line.Segment.GetIntersection, Circle.IsLineSecant, Circle.IsSegmentSecant, Statistics.GetMean, Median, Mode, and Range, and Shape:Remove, and fixed the naming for Shape:CheckCollisions and Shape:Remove. +- Clarified README.md +- Made util SortWithReferences local. +- Errors caused by local functions. + +TODO: +- Add: + - Frequency + - Binomial Probability + - Standard Deviation + - Conditional Probability + +3.0.0 +----- +ADDED: +- Added function GetSignedArea. +REMOVED: +- Removed drawing functions. +- Removed MLib.Line.Functions entirely. +CHANGED: +- Changed all the names to CamelCase. +- Changed module name to MLib. +- Changed return order of GetPerpendicualrBisector from Slope, Midpoint to Midpoint, Slope. +- Changed returned string of MLib.circle.isLineSecant to be upper-case. +- Changed IsPrime to accept only one number at a time. +- Changed NewShape's type to Capitals. + +Related to code: +- Added more accuarate comments. +- Made code more DRY. +- Made code monkey-patchable and saved space (by declaring all functions as local values then inserted them into a large table. + +TODO: +- Make LineIntersectsPolygon return where intersection occurs. +- Ditto with PolygonIntersectsPolygon. +- Add: + - Frequency + - Binomial Probability + - Standard Deviation + - Conditional Probability + + +Not as accurately maintained before 2.0.2 +----------------------------------------- + +2.0.2 +----- +- Cleaned up code, mostly. + +2.0.1 +----- +- Bug fixes, mlib.shape:remove & demos added. + +2.0.0 +----- +- Added mlib.shape and various bug fixes. + +2.0.0 +----- +- Made mlib.shape and made numberous bug fixes. + +1.9.4 +----- +- Made mlib.math.prime faster and removed ability to test multiple numbers at once. Thanks Robin! + +1.9.3 +----- +- Fixed polygon.area and polygon.centroid + +1.9.2 +----- +- Updated to LOVE 0.9.0. + +1.9.1 +----- +- Made mlib.line.closestPoint able to take either two points on the slope or the slope and intercept. + +1.9.0 +----- +- Added mlib.lineSegmentIntersects (no affiliation with previous one (changed to mlib.line.segment.intersect)) and mlib.line.closestPoint + +1.8.3 +----- +- Changed naming mechanism to be more organized. + +1.8.2 +----- +- "Fixed" mlib.lineSegmentsIntersect AGAIN!!!! :x + +1.8.1 +----- +- Removed a print statement. + +1.8.0 +----- +- mlib.pointInPolygon added + +1.7.5 +----- +- mlib.lineSegmentsIntersect vertical lines fixed again. This time for real. I promise... or hope, at least... :P + +1.7.4 +----- +- mlib.lineSegmentsIntersect vertical parallels fixed + +1.7.3 +----- +- mlib.lineSegmentsIntersect parallels fixed + +1.7.2 +----- +- mlib.lineSegmentsIntersect now handles vertical lines + +1.7.1 +----- +- mlib.lineSegmentsIntersect now returns the two places in between where the line segments begin to intersect. + +1.7.0 +----- +- Added mlib.circlesIntersect, mlib.pointOnLineSegment, mlib.linesIntersect, and mlib.lineSegmentsIntersect + +1.6.1 +----- +- Employed usage of summations for mlib.getPolygonArea and mlib.getPolygonCentroid and removed area as an argument for mlib.getPolygonCentroid. + +1.6.0 +----- +- Added several functions. + +1.5.0 +----- +- Made lots of changes to syntax to make it easier to use (hopefully). I also put out specs. + +1.4.1 +----- +- Localized mlib. Thanks, Yonaba! + +1.4.0 +----- +- Added mlib.getPolygonCentroid (gets the midpoint of a non-self-intersecting polygons) + +1.3.2 +----- +- Made mlib.getPrime take tables as arguments, so you can check all the values of a table. + +1.3.1 +----- +- Changed name method to mlib.getPolygonArea + +1.3.0 +----- +- Added mlib.get_polygon_area and removed mlib.get_convex_area and mlib.get_triangle_area since they are repetitive. + +1.2.2 +----- +- Made functions return faster, functions that previously returned tables now return multiple arguments. + +1.2.1 +----- +- Localized functions, made tables acceptable as arguments, refined function speed, mlib.get_mode now returns number most repeated as well as how many times. + +1.2.0 +----- +- Added mlib.get_angle + +1.1.0 +----- +- Added mlib.get_convex_area + +1.0.4 +----- +- Fixed get_mode to handle bimodials. + +1.0.3 +----- +- Prime Checker optimized (hopefully final update on this.) + +1.0.2 +----- +- Prime checker now works! (At least to 1000. I haven't tested any +further) + +1.0.1 +----- +- 'Fixed' the prime checker + +1.0.0 +----- +- Initial release diff --git a/libs/windfield/mlib/LICENSE.md b/libs/windfield/mlib/LICENSE.md new file mode 100644 index 0000000..38331e3 --- /dev/null +++ b/libs/windfield/mlib/LICENSE.md @@ -0,0 +1,17 @@ +Copyright (c) 2015 Davis Claiborne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgement in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. diff --git a/libs/windfield/mlib/README.md b/libs/windfield/mlib/README.md new file mode 100644 index 0000000..6bbfdb2 --- /dev/null +++ b/libs/windfield/mlib/README.md @@ -0,0 +1,890 @@ +MLib +==== + +__MLib__ is a math and shape-intersection detection library written in Lua. It's aim is to be __robust__ and __easy to use__. + +__NOTE:__ +- I am (slowly) working on completely rewriting this in order to be easier to use and less bug-prone. You can check out the progress [here](../../tree/dev). +- I am currently slowing development of MLib while moving over to helping with [CPML](https://github.com/excessive/cpml). To discuss this, please comment [here](../../issues/12). + +If you are looking for a library that handles updating/collision responses for you, take a look at [hxdx](https://github.com/adonaac/hxdx). It uses MLib functions as well as Box2d to handle physics calculations. + +## Downloading +You can download the latest __stable__ version of MLib by downloading the latest [release](../../releases/). +You can download the latest __working__ version of MLib by downloading the latest [commit](../../commits/master/). Documentation will __only__ be updated upon releases, not upon commits. + +## Implementing +To use MLib, simply place [mlib.lua](mlib.lua) inside the desired folder in your project. Then use the `require 'path.to.mlib'` to use any of the functions. + +## Examples +If you don't have [LÖVE](https://love2d.org/) installed, you can download the .zip of the demo from the [Executables](Examples/Executables) folder and extract and run the .exe that way. +You can see some examples of the code in action [here](Examples). +All examples are done using the *awesome* engine of [LÖVE](https://love2d.org/). +To run them properly, download the [.love file](Examples/LOVE) and install LÖVE to your computer. +After that, make sure you set .love files to open with "love.exe". +For more, see [here](https://love2d.org/). + +## When should I use MLib? +- If you need to know exactly where two objects intersect. +- If you need general mathematical equations to be done. +- If you need very precise details about point intersections. + +## When should I __not__ use MLib? +- All of the objects in a platformer, or other game, for instance, should not be registered with MLib. Only ones that need very specific information. +- When you don't need precise information/odd shapes. + +## Specs +#### For Windows +If you run Windows and have Telescope in `%USERPROFILE%\Documents\GitHub` (you can also manually change the path in [test.bat](test.bat)) you can simply run [test.bat](test.bat) and it will display the results, and then clean up after it's finished. + +#### Default +Alternatively, you can find the tests [here](spec.lua). Keep in mind that you may need to change certain semantics to suit your OS. +You can run them via [Telescope](https://github.com/norman/telescope/) and type the following command in the command-line of the root folder: +``` +tsc -f specs.lua +``` +If that does not work, you made need to put a link to Lua inside of the folder for `telescope` and run the following command: +``` +lua tsc -f specs.lua +``` +If you encounter further errors, try to run the command line as an administrator (usually located in `C:\Windows\System32\`), then right-click on `cmd.exe` and select `Run as administrator`, then do +``` +cd C:\Path\to\telescope\ +``` +And __then__ run one of the above commands. If none of those work, just take my word for it that all the tests pass and look at this picture. +![Success](Reference Pictures/Success.png) + +## Functions +- [mlib.line](#mlibline) + - [mlib.line.checkPoint](#mliblinecheckpoint) + - [mlib.line.getClosestPoint](#mliblinegetclosestpoint) + - [mlib.line.getYIntercept](#mliblinegetintercept) + - [mlib.line.getIntersection](#mliblinegetintersection) + - [mlib.line.getLength](#mliblinegetlength) + - [mlib.line.getMidpoint](#mliblinegetmidpoint) + - [mlib.line.getPerpendicularSlope](#mliblinegetperpendicularslope) + - [mlib.line.getSegmentIntersection](#mliblinegetsegmentintersection) + - [mlib.line.getSlope](#mliblinegetslope) +- [mlib.segment](#mlibsegment) + - [mlib.segment.checkPoint](#mlibsegmentcheckpoint) + - [mlib.segment.getPerpendicularBisector](#mlibsegmentgetperpendicularbisector) + - [mlib.segment.getIntersection](#mlibsegmentgetintersection) +- [mlib.polygon](#mlibpolygon) + - [mlib.polygon.checkPoint](#mlibpolygoncheckpoint) + - [mlib.polygon.getCentroid](#mlibpolygongetcentroid) + - [mlib.polygon.getCircleIntersection](#mlibpolygongetcircleintersection) + - [mlib.polygon.getLineIntersection](#mlibpolygongetlineintersection) + - [mlib.polygon.getPolygonArea](#mlibpolygongetpolygonarea) + - [mlib.polygon.getPolygonIntersection](#mlibpolygongetpolygonintersection) + - [mlib.polygon.getSegmentIntersection](#mlibpolygongetsegmentintersection) + - [mlib.polygon.getSignedPolygonArea](#mlibpolygongetsignedpolygonarea) + - [mlib.polygon.getTriangleHeight](#mlibpolygongettriangleheight) + - [mlib.polygon.isCircleInside](#mlibpolygoniscircleinside) + - [mlib.polygon.isCircleCompletelyInside](#mlibpolygoniscirclecompletelyinside) + - [mlib.polygon.isPolygonInside](#mlibpolygonispolygoninside) + - [mlib.polygon.isPolygonCompletelyInside](#mlibpolygonispolygoncompletelyinside) + - [mlib.polygon.isSegmentInside](#mlibpolygonissegmentinside) + - [mlib.polygon.isSegmentCompletelyInside](#mlibpolygonissegmentcompletelyinside) +- [mlib.circle](#mlibcircle) + - [mlib.circle.checkPoint](#mlibcirclecheckpoint) + - [mlib.circle.getArea](#mlibcirclegetarea) + - [mlib.circle.getCircleIntersection](#mlibcirclegetcircleintersection) + - [mlib.circle.getCircumference](#mlibcirclegetcircumference) + - [mlib.circle.getLineIntersection](#mlibcirclegetlineintersection) + - [mlib.circle.getSegmentIntersection](#mlibcirclegetsegmentintersection) + - [mlib.circle.isCircleCompletelyInside](#mlibcircleiscirclecompletelyinside) + - [mlib.circle.isCircleCompletelyInsidePolygon](#mlibcircleiscirclecompletelyinsidepolygon) + - [mlib.circle.isPointOnCircle](#mlibcircleispointoncircle) + - [mlib.circle.isPolygonCompletelyInside](#mlibcircleispolygoncompletelyinside) +- [mlib.statistics](#mlibstatistics) + - [mlib.statistics.getCentralTendency](#mlibstatisticsgetcentraltendency) + - [mlib.statistics.getDispersion](#mlibstatisticsgetdispersion) + - [mlib.statistics.getMean](#mlibstatisticsgetmean) + - [mlib.statistics.getMedian](#mlibstatisticsgetmedian) + - [mlib.statistics.getMode](#mlibstatisticsgetmode) + - [mlib.statistics.getRange](#mlibstatisticsgetrange) + - [mlib.statistics.getStandardDeviation](#mlibstatisticsgetstandarddeviation) + - [mlib.statistics.getVariance](#mlibstatisticsgetvariance) + - [mlib.statistics.getVariationRatio](#mlibstatisticsgetvariationratio) +- [mlib.math](#mlibmath) + - [mlib.math.getAngle](#mlibmathgetangle) + - [mlib.math.getPercentage](#mlibmathgetpercentage) + - [mlib.math.getPercentOfChange](#mlibmathgetpercentofchange) + - [mlib.math.getQuadraticRoots](#mlibmathgetquadraticroots) + - [mlib.math.getRoot](#mlibmathgetroot) + - [mlib.math.getSummation](#mlibmathgetsummation) + - [mlib.math.isPrime](#mlibmathisprime) + - [mlib.math.round](#mlibmathround) +- [Aliases](#aliases) + +#### mlib.line +- Deals with linear aspects, such as slope and length. + +##### mlib.line.checkPoint +- Checks if a point lies on a line. +- Synopsis: + - `onPoint = mlib.line.checkPoint( px, px, x1, y1, x2, y2 )` +- Arguments: + - `px`, `py`: Numbers. The x and y coordinates of the point being tested. + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates of the line being tested. +- Returns: + - `onPoint`: Boolean. + - `true` if the point is on the line. + - `false` if it does not. +- Notes: + - You cannot use the format `mlib.line.checkPoint( px, px, slope, intercept )` because this would lead to errors on vertical lines. + +##### mlib.line.getClosestPoint +- Gives the closest point to a line. +- Synopses: + - `cx, cy = mlib.line.getClosestPoint( px, py, x1, y1, x2, y2 )` + - `cx, cy = mlib.line.getClosestPoint( px, py, slope, intercept )` +- Arguments: + - `x`, `y`: Numbers. The x and y coordinates of the point. + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates on the line. + - `slope`, `intercept`: + - Numbers. The slope and y-intercept of the line. + - Booleans (`false`). The slope and y-intercept of a vertical line. +- Returns: + - `cx`, `cy`: Numbers. The closest points that lie on the line to the point. + +##### mlib.line.getYIntercept +- Gives y-intercept of the line. +- Synopses: + - `intercept, isVertical = mlib.line.getYIntercept( x1, y1, x2, y2 )` + - `intercept, isVertical = mlib.line.getYIntercept( x1, y1, slope )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates that lie on the line. + - `slope`: + - Number. The slope of the line. +- Returns: + - `intercept`: + - Number. The y-intercept of the line. + - Number. The `x1` coordinate of the line if the line is vertical. + - `isVertical`: + - Boolean. `true` if the line is vertical, `false` if the line is not vertical. + +##### mlib.line.getIntersection +- Gives the intersection of two lines. +- Synopses: + - `x, y = mlib.line.getIntersection( x1, y1, x2, y2, x3, y3, x4, y4 )` + - `x, y = mlib.line.getIntersection( slope1, intercept1, x3, y3, x4, y4 )` + - `x, y = mlib.line.getIntersection( slope1, intercept1, slope2, intercept2 )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates that lie on the first line. + - `x3`, `y3`, `x4`, `y4`: Numbers. Two x and y coordinates that lie on the second line. + - `slope1`, `intercept1`: + - Numbers. The slope and y-intercept of the first line. + - Booleans (`false`). The slope and y-intercept of the first line (if the first line is vertical). + - `slope2`, `intercept2`: + - Numbers. The slope and y-intercept of the second line. + - Booleans (`false`). The slope and y-intercept of the second line (if the second line is vertical). +- Returns: + - `x`, `y`: + - Numbers. The x and y coordinate where the lines intersect. + - Boolean: + - `true`, `nil`: The lines are collinear. + - `false`, `nil`: The lines are parallel and __not__ collinear. + +##### mlib.line.getLength +- Gives the distance between two points. +- Synopsis: + - `length = mlib.line.getLength( x1, y1, x2, y2 ) +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates. +- Returns: + - `length`: Number. The distance between the two points. + +##### mlib.line.getMidpoint +- Gives the midpoint of two points. +- Synopsis: + - `x, y = mlib.line.getMidpoint( x1, y1, x2, y2 )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates. +- Returns: + - `x`, `y`: Numbers. The midpoint x and y coordinates. + +##### mlib.line.getPerpendicularSlope +- Gives the perpendicular slope of a line. +- Synopses: + - `perpSlope = mlib.line.getPerpendicularSlope( x1, y1, x2, y2 )` + - `perpSlope = mlib.line.getPerpendicularSlope( slope )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates. + - `slope`: Number. The slope of the line. +- Returns: + - `perpSlope`: + - Number. The perpendicular slope of the line. + - Boolean (`false`). The perpendicular slope of the line (if the original line was horizontal). + +##### mlib.line.getSegmentIntersection +- Gives the intersection of a line segment and a line. +- Synopses: + - `x1, y1, x2, y2 = mlib.line.getSegmentIntersection( x1, y1, x2, y2, x3, y3, x4, y4 )` + - `x1, y1, x2, y2 = mlib.line.getSegmentIntersection( x1, y1, x2, y2, slope, intercept )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates that lie on the line segment. + - `x3`, `y3`, `x4`, `y4`: Numbers. Two x and y coordinates that lie on the line. + - `slope`, `intercept`: + - Numbers. The slope and y-intercept of the the line. + - Booleans (`false`). The slope and y-intercept of the line (if the line is vertical). +- Returns: + - `x1`, `y1`, `x2`, `y2`: + - Number, Number, Number, Number. + - The points of the line segment if the line and segment are collinear. + - Number, Number, Boolean (`nil`), Boolean (`nil`). + - The coordinate of intersection if the line and segment intersect and are not collinear. + - Boolean (`false`), Boolean (`nil`), Boolean (`nil`), + - Boolean (`nil`). If the line and segment don't intersect. + +##### mlib.line.getSlope +- Gives the slope of a line. +- Synopsis: + - `slope = mlib.line.getSlope( x1, y1, x2, y2 ) +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates. +- Returns: + - `slope`: + - Number. The slope of the line. + - Boolean (`false`). The slope of the line (if the line is vertical). + +#### mlib.segment +- Deals with line segments. + +##### mlib.segment.checkPoint +- Checks if a point lies on a line segment. +- Synopsis: + - `onSegment = mlib.segment.checkPoint( px, py, x1 y1, x2, y2 )` +- Arguments: + - `px`, `py`: Numbers. The x and y coordinates of the point being checked. + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates. +- Returns: + - `onSegment`: Boolean. + - `true` if the point lies on the line segment. + - `false` if the point does not lie on the line segment. + +##### mlib.segment.getPerpendicularBisector +- Gives the perpendicular bisector of a line. +- Synopsis: + - `x, y, slope = mlib.segment.getPerpendicularBisector( x1, y1, x2, y2 )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates. +- Returns: + - `x`, `y`: Numbers. The midpoint of the line. + - `slope`: + - Number. The perpendicular slope of the line. + - Boolean (`false`). The perpendicular slope of the line (if the original line was horizontal). + +##### mlib.segment.getIntersection +- Checks if two line segments intersect. +- Synopsis: + - `cx1, cy1, cx2, cy2 = mlib.segment.getIntersection( x1, y1, x2, y2, x3, y3 x4, y4 )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates of the first line segment. + - `x3`, `y3`, `x4`, `y4`: Numbers. Two x and y coordinates of the second line segment. +- Returns: + - `cx1`, `cy1`, `cx2`, `cy2`: + - Number, Number, Number, Number. + - The points of the resulting intersection if the line segments are collinear. + - Number, Number, Boolean (`nil`), Boolean (`nil`). + - The point of the resulting intersection if the line segments are not collinear. + - Boolean (`false`), Boolean (`nil`), Boolean (`nil`) , Boolean (`nil`). + - If the line segments don't intersect. + +#### mlib.polygon +- Handles aspects involving polygons. + +##### mlib.polygon.checkPoint +- Checks if a point is inside of a polygon. +- Synopses: + - `inPolygon = mlib.polygon.checkPoint( px, py, vertices )` + - `inPolygon = mlib.polygon.checkPoint( px, py, ... )` +- Arguments: + - `px`, `py`: Numbers. The x and y coordinate of the point being checked. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `inPolygon`: Boolean. + - `true` if the point is inside the polygon. + - `false` if the point is not inside the polygon. + +##### mlib.polygon.getCentroid +- Returns the centroid of the polygon. +- Synopses: + - `cx, cy = mlib.polygon.getCentroid( vertices )` + - `cx, cy = mlib.polygon.getCentroid( ... )` +- Arguments: + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `cx`, `cy`: Numbers. The x and y coordinates of the centroid. + +##### mlib.polygon.getCircleIntersection +- Returns the coordinates of where a circle intersects a polygon. +- Synopses: + - `intersections = mlib.polygon.getCircleIntersection( cx, cy, radius, vertices )` + - `intersections = mlib.polygon.getCircleIntersection( cx, cy, radius, ... ) +- Arguments: + - `cx`, `cy`: Number. The coordinates of the center of the circle. + - `radius`: Number. The radius of the circle. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `intersections`: Table. Contains the intersections and type. +- Example: +```lua +local tab = _.polygon.getCircleIntersection( 5, 5, 1, 4, 4, 6, 4, 6, 6, 4, 6 ) +for i = 1, # tab do + print( i .. ':', unpack( tab[i] ) ) +end +-- 1: tangent 5 4 +-- 2: tangent 6 5 +-- 3: tangent 5 6 +-- 4: tagnent 4 5 +``` +- For more see [mlib.circle.getSegmentIntersection](#mlibcirclegetsegmentintersection) or the [specs](spec.lua# L676) + +##### mlib.polygon.getLineIntersection +- Returns the coordinates of where a line intersects a polygon. +- Synopses: + - `intersections = mlib.polygon.getLineIntersection( x1, y1, x2, y2, vertices )` + - `intersections = mlib.polygon.getLineIntersection( x1, y1, x2, y2, ... ) +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `intersections`: Table. Contains the intersections. +- Notes: + - With collinear lines, they are actually broken up. i.e. `{ 0, 4, 0, 0 }` would become `{ 0, 4 }, { 0, 0 }`. + +##### mlib.polygon.getPolygonArea +- Gives the area of a polygon. +- Synopses: + - `area = mlib.polygon.getArea( vertices )` + - `area = mlib.polygon.getArea( ... ) +- Arguments: + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `area`: Number. The area of the polygon. + +##### mlib.polygon.getPolygonIntersection +- Gives the intersection of two polygons. +- Synopsis: + - `intersections = mlib.polygon.getPolygonIntersections( polygon1, polygon2 )` +- Arguments: + - `polygon1`: Table. The vertices of the first polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `polygon2`: Table. The vertices of the second polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` +- Returns: + - `intersections`: Table. A table of the points of intersection. + +##### mlib.polygon.getSegmentIntersection +- Returns the coordinates of where a line segmeing intersects a polygon. +- Synopses: + - `intersections = mlib.polygon.getSegmentIntersection( x1, y1, x2, y2, vertices )` + - `intersections = mlib.polygon.getSegmentIntersection( x1, y1, x2, y2, ... ) +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `intersections`: Table. Contains the intersections. +- Notes: + - With collinear line segments, they are __not__ broken up. See the [specs](spec.lua# L508) for more. + +##### mlib.polygon.getSignedPolygonArea +- Gets the signed area of the polygon. If the points are ordered counter-clockwise the area is positive. If the points are ordered clockwise the number is negative. +- Synopses: + - `area = mlib.polygon.getLineIntersection( vertices )` + - `area = mlib.polygon.getLineIntersection( ... ) +- Arguments: + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `area`: Number. The __signed__ area of the polygon. If the points are ordered counter-clockwise the area is positive. If the points are ordered clockwise the number is negative. + +##### mlib.polygon.getTriangleHeight +- Gives the height of a triangle. +- Synopses: + - `height = mlib.polygon.getTriangleHeigh( base, x1, y1, x2, y2, x3, y3 )` + - `height = mlib.polygon.getTriangleHeight( base, area )` +- Arguments: + - `base`: Number. The length of the base of the triangle. + - `x1`, `y1`, `x2`, `y2`, `x3`, `y3`: Numbers. The x and y coordinates of the triangle. + - `area`: Number. The regular area of the triangle. __Not__ the signed area. +- Returns: + - `height`: Number. The height of the triangle. + +##### mlib.polygon.isCircleInside +- Checks if a circle is inside the polygon. +- Synopses: + - `inPolygon = mlib.polygon.isCircleInside( cx, cy, radius, vertices )` + - `inPolygon = mlib.polygon.isCircleInside( cx, cy, radius, ... )` +- Arguments: + - `cx`, `cy`: Numbers. The x and y coordinates for the center of the circle. + - `radius`: Number. The radius of the circle. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `inPolygon`: Boolean. + - `true` if the circle is inside the polygon. + - `false` if the circle is not inside the polygon. +- Notes: + - Only returns true if the center of the circle is inside the circle. + +##### mlib.polygon.isCircleCompletelyInside +- Checks if a circle is completely inside the polygon. +- Synopses: + - `inPolygon = mlib.polygon.isCircleCompletelyInside( cx, cy, radius, vertices )` + - `inPolygon = mlib.polygon.isCircleCompletelyInside( cx, cy, radius, ... )` +- Arguments: + - `cx`, `cy`: Numbers. The x and y coordinates for the center of the circle. + - `radius`: Number. The radius of the circle. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `inPolygon`: Boolean. + - `true` if the circle is __completely__ inside the polygon. + - `false` if the circle is not inside the polygon. + +##### mlib.polygon.isPolygonInside +- Checks if a polygon is inside a polygon. +- Synopsis: + - `inPolygon = mlib.polygon.isPolygonInside( polygon1, polygon2 )` +- Arguments: + - `polygon1`: Table. The vertices of the first polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `polygon2`: Table. The vertices of the second polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` +- Returns: + - `inPolygon`: Boolean. + - `true` if the `polygon2` is inside of `polygon1`. + - `false` if `polygon2` is not inside of `polygon2`. +- Notes: + - Returns true as long as any of the line segments of `polygon2` are inside of the `polygon1`. + +##### mlib.polygon.isPolygonCompletelyInside +- Checks if a polygon is completely inside a polygon. +- Synopsis: + - `inPolygon = mlib.polygon.isPolygonCompletelyInside( polygon1, polygon2 )` +- Arguments: + - `polygon1`: Table. The vertices of the first polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `polygon2`: Table. The vertices of the second polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` +- Returns: + - `inPolygon`: Boolean. + - `true` if the `polygon2` is __completely__ inside of `polygon1`. + - `false` if `polygon2` is not inside of `polygon2`. + +##### mlib.polygon.isSegmentInside +- Checks if a line segment is inside a polygon. +- Synopses: + - `inPolygon = mlib.polygon.isSegmentInside( x1, y1, x2, y2, vertices )` + - `inPolygon = mlib.polygon.isSegmentInside( x1, y1, x2, y2, ... )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. The x and y coordinates of the line segment. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `inPolygon`: Boolean. + - `true` if the line segment is inside the polygon. + - `false` if the line segment is not inside the polygon. +- Note: + - Only one of the points has to be in the polygon to be considered 'inside' of the polygon. + - This is really just a faster version of [mlib.polygon.getPolygonIntersection](#mlibpolygongetpolygonintersection) that does not give the points of intersection. + +##### mlib.polygon.isSegmentCompletelyInside +- Checks if a line segment is completely inside a polygon. +- Synopses: + - `inPolygon = mlib.polygon.isSegmentCompletelyInside( x1, y1, x2, y2, vertices )` + - `inPolygon = mlib.polygon.isSegmentCompletelyInside( x1, y1, x2, y2, ... )` +- Arguments: + - `x1`, `y1`, `x2`, `y2`: Numbers. The x and y coordinates of the line segment. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `inPolygon`: Boolean. + - `true` if the line segment is __completely__ inside the polygon. + - `false` if the line segment is not inside the polygon. + +#### mlib.circle +- Handles aspects involving circles. + +##### mlib.circle.checkPoint +- Checks if a point is on the inside or on the edge the circle. +- Synopsis: + - `inCircle = mlib.circle.checkPoint( px, px, cx, cy, radius )` +- Arguments: + - `px`, `py`: Numbers. The x and y coordinates of the point being tested. + - `cx`, `cy`: Numbers. The x and y coordinates of the center of the circle. + - `radius`: Number. The radius of the circle. +- Returns: + - `inCircle`: Boolean. + - `true` if the point is inside or on the circle. + - `false` if the point is outside of the circle. + +##### mlib.circle.getArea +- Gives the area of a circle. +- Synopsis: + - `area = mlib.circle.getArea( radius )` +- Arguments: + - `radius`: Number. The radius of the circle. +- Returns: + - `area`: Number. The area of the circle. + +##### mlib.circle.getCircleIntersection +- Gives the intersections of two circles. +- Synopsis: + - `intersections = mlib.circle.getCircleIntersection( c1x, c1y, radius1, c2x, c2y, radius2 ) +- Arguments: + - `c1x`, `c1y`: Numbers. The x and y coordinate of the first circle. + - `radius1`: Number. The radius of the first circle. + - `c2x`, `c2y`: Numbers. The x and y coordinate of the second circle. + - `radius2`: Number. The radius of the second circle. +- Returns: + - `intersections`: Table. A table that contains the type and where the circle collides. See the [specs](spec.lua# L698) for more. + +##### mlib.circle.getCircumference +- Returns the circumference of a circle. +- Synopsis: + - `circumference = mlib.circle.getCircumference( radius )` +- Arguments: + - `radius`: Number. The radius of the circle. +- Returns: + - `circumference`: Number. The circumference of a circle. + +##### mlib.circle.getLineIntersection +- Returns the intersections of a circle and a line. +- Synopsis: + - `intersections = mlib.circle.getLineIntersections( cx, cy, radius, x1, y1, x2, y2 )` +- Arguments: + - `cx`, `cy`: Numbers. The x and y coordinates for the center of the circle. + - `radius`: Number. The radius of the circle. + - `x1`, `y1`, `x2`, `y2`: Numbers. Two x and y coordinates the lie on the line. +- Returns: + - `intersections`: Table. A table with the type and where the intersections happened. Table is formatted: + - `type`, `x1`, `y1`, `x2`, `y2` + - String (`'secant'`), Number, Number, Number, Number + - The numbers are the x and y coordinates where the line intersects the circle. + - String (`'tangent'`), Number, Number, Boolean (`nil`), Boolean (`nil`) + - `x1` and `x2` represent where the line intersects the circle. + - Boolean (`false`), Boolean (`nil`), Boolean (`nil`), Boolean (`nil`), Boolean (`nil`) + - No intersection. + - For more see the [specs](spec.lua# L660). + +##### mlib.circle.getSegmentIntersection +- Returns the intersections of a circle and a line segment. +- Synopsis: + - `intersections = mlib.circle.getSegmentIntersections( cx, cy, radius, x1, y1, x2, y2 )` +- Arguments: + - `cx`, `cy`: Numbers. The x and y coordinates for the center of the circle. + - `radius`: Number. The radius of the circle. + - `x1`, `y1`, `x2`, `y2`: Numbers. The two x and y coordinates of the line segment. +- Returns: + - `intersections`: Table. A table with the type and where the intersections happened. Table is formatted: + - `type`, `x1`, `y1`, `x2`, `y2` + - String (`'chord'`), Number, Number, Number, Number + - The numbers are the x and y coordinates where the line segment is on both edges of the circle. + - String (`'enclosed'`), Number, Number, Number, Number + - The numbers are the x and y coordinates of the line segment if it is fully inside of the circle. + - String (`'secant'`), Number, Number, Number, Number + - The numbers are the x and y coordinates where the line segment intersects the circle. + - String (`'tangent'`), Number, Number, Boolean (`nil`), Boolean (`nil`) + - `x1` and `x2` represent where the line segment intersects the circle. + - Boolean (`false`), Boolean (`nil`), Boolean (`nil`), Boolean (`nil`), Boolean (`nil`) + - No intersection. + - For more see the [specs](spec.lua# L676). + +##### mlib.circle.isCircleCompletelyInside +- Checks if one circle is completely inside of another circle. +- Synopsis: + - `completelyInside = mlib.circle.isCircleCompletelyInside( c1x, c1y, c1radius, c2x, c2y, c2radius )` +- Arguments: + - `c1x`, `c1y`: Numbers. The x and y coordinates of the first circle. + - `c1radius`: Number. The radius of the first circle. + - `c2x`, `c2y`: Numbers. The x and y coordinates of the second circle. + - `c2radius`: Number. The radius of the second circle. +- Returns: + - `completelyInside`: Boolean. + - `true` if circle1 is inside of circle2. + - `false` if circle1 is not __completely__ inside of circle2. + +##### mlib.circle.isCircleCompletelyInsidePolygon +- Checks if a circle is completely inside the polygon. +- Synopses: + - `inPolygon = mlib.polygon.isCircleCompletelyInside( cx, cy, radius, vertices )` + - `inPolygon = mlib.polygon.isCircleCompletelyInside( cx, cy, radius, ... )` +- Arguments: + - `cx`, `cy`: Numbers. The x and y coordinates for the center of the circle. + - `radius`: Number. The radius of the circle. + - `vertices`: Table. The vertices of the polygon in the format `{ x1, y1, x2, y2, x3, y3, ... }` + - `...`: Numbers. The x and y coordinates of the polygon. (Same as using `unpack( vertices )`) +- Returns: + - `inPolygon`: Boolean. + - `true` if the circle is __completely__ inside the polygon. + - `false` if the circle is not inside the polygon. + +##### mlib.circle.isPointOnCircle +- Checks if a point is __exactly__ on the edge of the circle. +- Synopsis: + - `onCircle = mlib.circle.checkPoint( px, px, cx, cy, radius )` +- Arguments: + - `px`, `py`: Numbers. The x and y coordinates of the point being tested. + - `cx`, `cy`: Numbers. The x and y coordinates of the center of the circle. + - `radius`: Number. The radius of the circle. +- Returns: + - `onCircle`: Boolean. + - `true` if the point is on the circle. + - `false` if the point is on the inside or outside of the circle. +- Notes: + - Will return false if the point is inside __or__ outside of the circle. + +##### mlib.circle.isPolygonCompletelyInside +- Checks if a polygon is completely inside of a circle. +- Synopsis: + - `completelyInside = mlib.circle.isPolygonCompletelyInside( circleX, circleY, circleRadius, vertices )` + - `completelyInside = mlib.circle.isPolygonCompletelyInside( circleX, circleY, circleRadius, ... )` +- Arguments: + - `circleX`, `circleY`: Numbers. The x and y coordinates of the circle. + - `circleRadius`: Number. The radius of the circle. + - `vertices`: Table. A table containing all of the vertices of the polygon. + - `...`: Numbers. All of the points of the polygon. +- Returns: + - `completelyInside`: Boolean. + - `true` if the polygon is inside of the circle. + - `false` if the polygon is not __completely__ inside of the circle. + +#### mlib.statistics +- Handles statistical aspects of math. + +##### mlib.statistics.getCentralTendency +- Gets the central tendency of the data. +- Synopses: + - `modes, occurrences, median, mean = mlib.statistics.getCentralTendency( data )` + - `modes, occurrences, median, mean = mlib.statistics.getCentralTendency( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `modes, occurrences`: Table, Number. The modes of the data and the number of times it occurs. See [mlib.statistics.getMode](#mlibstatisticsgetmode). + - `median`: Number. The median of the data set. + - `mean`: Number. The mean of the data set. + +##### mlib.statistics.getDispersion +- Gets the dispersion of the data. +- Synopses: + - `variationRatio, range, standardDeviation = mlib.statistics.getDispersion( data )` + - `variationRatio, range, standardDeviation = mlib.statistics.getDispersion( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `variationRatio`: Number. The variation ratio of the data set. + - `range`: Number. The range of the data set. + - `standardDeviation`: Number. The standard deviation of the data set. + +##### mlib.statistics.getMean +- Gets the arithmetic mean of the data. +- Synopses: + - `mean = mlib.statistics.getMean( data )` + - `mean = mlib.statistics.getMean( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `mean`: Number. The arithmetic mean of the data set. + +##### mlib.statistics.getMedian +- Gets the median of the data set. +- Synopses: + - `median = mlib.statistics.getMedian( data )` + - `median = mlib.statistics.getMedian( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `median`: Number. The median of the data. + +##### mlib.statistics.getMode +- Gets the mode of the data set. +- Synopses: + - `mode, occurrences = mlib.statistics.getMode( data )` + - `mode, occurrences = mlib.statistics.getMode( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `mode`: Table. The mode(s) of the data. + - `occurrences`: Number. The number of time the mode(s) occur. + +##### mlib.statistics.getRange +- Gets the range of the data set. +- Synopses: + - `range = mlib.statistics.getRange( data )` + - `range = mlib.statistics.getRange( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `range`: Number. The range of the data. + +##### mlib.statistics.getStandardDeviation +- Gets the standard deviation of the data. +- Synopses: + - `standardDeviation = mlib.statistics.getStandardDeviation( data )` + - `standardDeviation = mlib.statistics.getStandardDeviation( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `standardDeviation`: Number. The standard deviation of the data set. + +##### mlib.statistics.getVariance +- Gets the variation of the data. +- Synopses: + - `variance = mlib.statistics.getVariance( data )` + - `variance = mlib.statistics.getVariance( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `variance`: Number. The variation of the data set. + +##### mlib.statistics.getVariationRatio +- Gets the variation ratio of the data. +- Synopses: + - `variationRatio = mlib.statistics.getVariationRatio( data )` + - `variationRatio = mlib.statistics.getVariationRatio( ... )` +- Arguments: + - `data`: Table. A table containing the values of data. + - `...`: Numbers. All of the numbers in the data set. +- Returns: + - `variationRatio`: Number. The variation ratio of the data set. + +#### mlib.math +- Miscellaneous functions that have no home. + +##### mlib.math.getAngle +- Gets the angle between three points. +- Synopsis: + - `angle = mlib.math.getAngle( x1, y1, x2, y2, x3, y3 )` +- Arguments: + - `x1`, `y1`: Numbers. The x and y coordinates of the first point. + - `x2`, `y2`: Numbers. The x and y coordinates of the vertex of the two points. + - `x3`, `y3`: Numbers. The x and y coordinates of the second point. + +##### mlib.math.getPercentage +- Gets the percentage of a number. +- Synopsis: + - `percentage = mlib.math.getPercentage( percent, number )` +- Arguments: + - `percent`: Number. The decimal value of the percent (i.e. 100% is 1, 50% is .5). + - `number`: Number. The number to get the percentage of. +- Returns: + - `percentage`: Number. The `percent`age or `number`. + +##### mlib.math.getPercentOfChange +- Gets the percent of change from one to another. +- Synopsis: + - `change = mlib.math.getPercentOfChange( old, new )` +- Arguments: + - `old`: Number. The original number. + - `new`: Number. The new number. +- Returns: + - `change`: Number. The percent of change from `old` to `new`. + +##### mlib.math.getQuadraticRoots +- Gets the quadratic roots of the the equation. +- Synopsis: + - `root1, root2 = mlib.math.getQuadraticRoots( a, b, c )` +- Arguments: + - `a`, `b`, `c`: Numbers. The a, b, and c values of the equation `a * x ^ 2 + b * x ^ 2 + c`. +- Returns: + - `root1`, `root2`: Numbers. The roots of the equation (where `a * x ^ 2 + b * x ^ 2 + c = 0`). + +##### mlib.math.getRoot +- Gets the `n`th root of a number. +- Synopsis: + - `x = mlib.math.getRoot( number, root )` +- Arguments: + - `number`: Number. The number to get the root of. + - `root`: Number. The root. +- Returns: + - `x`: The `root`th root of `number`. +- Example: +```lua +local a = mlib.math.getRoot( 4, 2 ) -- Same as saying 'math.pow( 4, .5 )' or 'math.sqrt( 4 )' in this case. +local b = mlib.math.getRoot( 27, 3 ) + +print( a, b ) --> 2, 3 +``` + - For more, see the [specs](spec.lua# L860). + +##### mlib.math.getSummation +- Gets the summation of numbers. +- Synopsis: + - `summation = mlib.math.getSummation( start, stop, func )` +- Arguments: + - `start`: Number. The number at which to start the summation. + - `stop`: Number. The number at which to stop the summation. + - `func`: Function. The method to add the numbers. + - Arguments: + - `i`: Number. Index. + - `previous`: Table. The previous values used. +- Returns: + - `Summation`: Number. The summation of the numbers. + - For more, see the [specs](spec.lua# L897). + +##### mlib.math.isPrime +- Checks if a number is prime. +- Synopsis: + - `isPrime = mlib.math.isPrime( x )` +- Arguments: + - `x`: Number. The number to check if it's prime. +- Returns: + - `isPrime`: Boolean. + - `true` if the number is prime. + - `false` if the number is not prime. + +##### mlib.math.round +- Rounds a number to the given decimal place. +- Synopsis: + - `rounded = mlib.math.round( number, [place] ) +- Arguments: + - `number`: Number. The number to round. + - `place (1)`: Number. The decimal place to round to. Defaults to 1. +- Returns: + - The rounded number. + - For more, see the [specs](spec.lua# L881). + +#### Aliases +| Alias | Corresponding Function | +| ----------------------------------------------|:---------------------------------------------------------------------------------:| +| milb.line.getDistance | [mlib.line.getLength](#mliblinegetlength) | +| mlib.line.getCircleIntersection | [mlib.circle.getLineIntersection](#mlibcirclegetlineintersection) | +| milb.line.getPolygonIntersection | [mlib.polygon.getLineIntersection](#mlibpolygongetlineintersection) | +| mlib.line.getLineIntersection | [mlib.line.getIntersection](#mliblinegetintersection) | +| mlib.segment.getCircleIntersection | [mlib.circle.getSegmentIntersection](#mlibcirclegetsegmentintersection) | +| milb.segment.getPolygonIntersection | [mlib.pollygon.getSegmentIntersection](#mlibpollygongetsegmentintersection) | +| mlib.segment.getLineIntersection | [mlib.line.getSegmentIntersection](#mliblinegetsegmentintersection) | +| mlib.segment.getSegmentIntersection | [mlib.segment.getIntersection](#mlibsegmentgetintersection) | +| milb.segment.isSegmentCompletelyInsideCircle | [mlib.circle.isSegmentCompletelyInside](#mlibcircleissegmentcompletelyinside) | +| mlib.segment.isSegmentCompletelyInsidePolygon | [mlib.polygon.isSegmentCompletelyInside](#mlibpolygonissegmentcompletelyinside) | +| mlib.circle.getPolygonIntersection | [mlib.polygon.getCircleIntersection](#mlibpolygongetcircleintersection) | +| mlib.circle.isCircleInsidePolygon | [mlib.polygon.isCircleInside](#mlibpolygoniscircleinside) | +| mlib.circle.isCircleCompletelyInsidePolygon | [mlib.polygon.isCircleCompletelyInside](#mlibpolygoniscirclecompletelyinside) | +| mlib.polygon.isCircleCompletelyOver | [mlib.circleisPolygonCompletelyInside](#mlibcircleispolygoncompletelyinside) | + +## License +A math library made in Lua +copyright (C) 2014 Davis Claiborne +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +Contact me at davisclaib at gmail.com diff --git a/libs/windfield/mlib/mlib.lua b/libs/windfield/mlib/mlib.lua new file mode 100644 index 0000000..488fdb7 --- /dev/null +++ b/libs/windfield/mlib/mlib.lua @@ -0,0 +1,1152 @@ +--[[ License + A math library made in Lua + copyright (C) 2014 Davis Claiborne + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + Contact me at davisclaib@gmail.com +]] + +-- Local Utility Functions ---------------------- {{{ +local unpack = table.unpack or unpack + +-- Used to handle variable-argument functions and whether they are passed as func{ table } or func( unpack( table ) ) +local function checkInput( ... ) + local input = {} + if type( ... ) ~= 'table' then input = { ... } else input = ... end + return input +end + +-- Deals with floats / verify false false values. This can happen because of significant figures. +local function checkFuzzy( number1, number2 ) + return ( number1 - .00001 <= number2 and number2 <= number1 + .00001 ) +end + +-- Remove multiple occurrences from a table. +local function removeDuplicatePairs( tab ) + for index1 = #tab, 1, -1 do + local first = tab[index1] + for index2 = #tab, 1, -1 do + local second = tab[index2] + if index1 ~= index2 then + if type( first[1] ) == 'number' and type( second[1] ) == 'number' and type( first[2] ) == 'number' and type( second[2] ) == 'number' then + if checkFuzzy( first[1], second[1] ) and checkFuzzy( first[2], second[2] ) then + table.remove( tab, index1 ) + end + elseif first[1] == second[1] and first[2] == second[2] then + table.remove( tab, index1 ) + end + end + end + end + return tab +end + + +local function removeDuplicates4Points( tab ) + for index1 = #tab, 1, -1 do + local first = tab[index1] + for index2 = #tab, 1, -1 do + local second = tab[index2] + if index1 ~= index2 then + if type( first[1] ) ~= type( second[1] ) then return false end + if type( first[2] ) == 'number' and type( second[2] ) == 'number' and type( first[3] ) == 'number' and type( second[3] ) == 'number' then + if checkFuzzy( first[2], second[2] ) and checkFuzzy( first[3], second[3] ) then + table.remove( tab, index1 ) + end + elseif checkFuzzy( first[1], second[1] ) and checkFuzzy( first[2], second[2] ) and checkFuzzy( first[3], second[3] ) then + table.remove( tab, index1 ) + end + end + end + end + return tab +end + + +-- Add points to the table. +local function addPoints( tab, x, y ) + tab[#tab + 1] = x + tab[#tab + 1] = y +end + +-- Like removeDuplicatePairs but specifically for numbers in a flat table +local function removeDuplicatePointsFlat( tab ) + for i = #tab, 1 -2 do + for ii = #tab - 2, 3, -2 do + if i ~= ii then + local x1, y1 = tab[i], tab[i + 1] + local x2, y2 = tab[ii], tab[ii + 1] + if checkFuzzy( x1, x2 ) and checkFuzzy( y1, y2 ) then + table.remove( tab, ii ); table.remove( tab, ii + 1 ) + end + end + end + end + return tab +end + + +-- Check if input is actually a number +local function validateNumber( n ) + if type( n ) ~= 'number' then return false + elseif n ~= n then return false -- nan + elseif math.abs( n ) == math.huge then return false + else return true end +end + +local function cycle( tab, index ) return tab[( index - 1 ) % #tab + 1] end + +local function getGreatestPoint( points, offset ) + offset = offset or 1 + local start = 2 - offset + local greatest = points[start] + local least = points[start] + for i = 2, #points / 2 do + i = i * 2 - offset + if points[i] > greatest then + greatest = points[i] + end + if points[i] < least then + least = points[i] + end + end + return greatest, least +end + +local function isWithinBounds( min, num, max ) + return num >= min and num <= max +end + +local function distance2( x1, y1, x2, y2 ) -- Faster since it does not use math.sqrt + local dx, dy = x1 - x2, y1 - y2 + return dx * dx + dy * dy +end -- }}} + +-- Points -------------------------------------- {{{ +local function rotatePoint( x, y, rotation, ox, oy ) + ox, oy = ox or 0, oy or 0 + return ( x - ox ) * math.cos( rotation ) + ox - ( y - oy ) * math.sin( rotation ), ( x - ox ) * math.sin( rotation ) + ( y - oy ) * math.cos( rotation ) + oy +end + +local function scalePoint( x, y, scale, ox, oy ) + ox, oy = ox or 0, oy or 0 + return ( x - ox ) * scale + ox, ( y - oy ) * scale + oy +end +-- }}} + +-- Lines --------------------------------------- {{{ +-- Returns the length of a line. +local function getLength( x1, y1, x2, y2 ) + local dx, dy = x1 - x2, y1 - y2 + return math.sqrt( dx * dx + dy * dy ) +end + +-- Gives the midpoint of a line. +local function getMidpoint( x1, y1, x2, y2 ) + return ( x1 + x2 ) / 2, ( y1 + y2 ) / 2 +end + +-- Gives the slope of a line. +local function getSlope( x1, y1, x2, y2 ) + if checkFuzzy( x1, x2 ) then return false end -- Technically it's undefined, but this is easier to program. + return ( y1 - y2 ) / ( x1 - x2 ) +end + +-- Gives the perpendicular slope of a line. +-- x1, y1, x2, y2 +-- slope +local function getPerpendicularSlope( ... ) + local input = checkInput( ... ) + local slope + + if #input ~= 1 then + slope = getSlope( unpack( input ) ) + else + slope = unpack( input ) + end + + if not slope then return 0 -- Vertical lines become horizontal. + elseif checkFuzzy( slope, 0 ) then return false -- Horizontal lines become vertical. + else return -1 / slope end +end + +-- Gives the y-intercept of a line. +-- x1, y1, x2, y2 +-- x1, y1, slope +local function getYIntercept( x, y, ... ) + local input = checkInput( ... ) + local slope + + if #input == 1 then + slope = input[1] + else + slope = getSlope( x, y, unpack( input ) ) + end + + if not slope then return x, true end -- This way we have some information on the line. + return y - slope * x, false +end + +-- Gives the intersection of two lines. +-- slope1, slope2, x1, y1, x2, y2 +-- slope1, intercept1, slope2, intercept2 +-- x1, y1, x2, y2, x3, y3, x4, y4 +local function getLineLineIntersection( ... ) + local input = checkInput( ... ) + local x1, y1, x2, y2, x3, y3, x4, y4 + local slope1, intercept1 + local slope2, intercept2 + local x, y + + if #input == 4 then -- Given slope1, intercept1, slope2, intercept2. + slope1, intercept1, slope2, intercept2 = unpack( input ) + + -- Since these are lines, not segments, we can use arbitrary points, such as ( 1, y ), ( 2, y ) + y1 = slope1 and slope1 * 1 + intercept1 or 1 + y2 = slope1 and slope1 * 2 + intercept1 or 2 + y3 = slope2 and slope2 * 1 + intercept2 or 1 + y4 = slope2 and slope2 * 2 + intercept2 or 2 + x1 = slope1 and ( y1 - intercept1 ) / slope1 or intercept1 + x2 = slope1 and ( y2 - intercept1 ) / slope1 or intercept1 + x3 = slope2 and ( y3 - intercept2 ) / slope2 or intercept2 + x4 = slope2 and ( y4 - intercept2 ) / slope2 or intercept2 + elseif #input == 6 then -- Given slope1, intercept1, and 2 points on the other line. + slope1, intercept1 = input[1], input[2] + slope2 = getSlope( input[3], input[4], input[5], input[6] ) + intercept2 = getYIntercept( input[3], input[4], input[5], input[6] ) + + y1 = slope1 and slope1 * 1 + intercept1 or 1 + y2 = slope1 and slope1 * 2 + intercept1 or 2 + y3 = input[4] + y4 = input[6] + x1 = slope1 and ( y1 - intercept1 ) / slope1 or intercept1 + x2 = slope1 and ( y2 - intercept1 ) / slope1 or intercept1 + x3 = input[3] + x4 = input[5] + elseif #input == 8 then -- Given 2 points on line 1 and 2 points on line 2. + slope1 = getSlope( input[1], input[2], input[3], input[4] ) + intercept1 = getYIntercept( input[1], input[2], input[3], input[4] ) + slope2 = getSlope( input[5], input[6], input[7], input[8] ) + intercept2 = getYIntercept( input[5], input[6], input[7], input[8] ) + + x1, y1, x2, y2, x3, y3, x4, y4 = unpack( input ) + end + + if not slope1 and not slope2 then -- Both are vertical lines + if x1 == x3 then -- Have to have the same x positions to intersect + return true + else + return false + end + elseif not slope1 then -- First is vertical + x = x1 -- They have to meet at this x, since it is this line's only x + y = slope2 and slope2 * x + intercept2 or 1 + elseif not slope2 then -- Second is vertical + x = x3 -- Vice-Versa + y = slope1 * x + intercept1 + elseif checkFuzzy( slope1, slope2 ) then -- Parallel (not vertical) + if checkFuzzy( intercept1, intercept2 ) then -- Same intercept + return true + else + return false + end + else -- Regular lines + x = ( -intercept1 + intercept2 ) / ( slope1 - slope2 ) + y = slope1 * x + intercept1 + end + + return x, y +end + +-- Gives the closest point on a line to a point. +-- perpendicularX, perpendicularY, x1, y1, x2, y2 +-- perpendicularX, perpendicularY, slope, intercept +local function getClosestPoint( perpendicularX, perpendicularY, ... ) + local input = checkInput( ... ) + local x, y, x1, y1, x2, y2, slope, intercept + + if #input == 4 then -- Given perpendicularX, perpendicularY, x1, y1, x2, y2 + x1, y1, x2, y2 = unpack( input ) + slope = getSlope( x1, y1, x2, y2 ) + intercept = getYIntercept( x1, y1, x2, y2 ) + elseif #input == 2 then -- Given perpendicularX, perpendicularY, slope, intercept + slope, intercept = unpack( input ) + x1, y1 = 1, slope and slope * 1 + intercept or 1 -- Need x1 and y1 in case of vertical/horizontal lines. + end + + if not slope then -- Vertical line + x, y = x1, perpendicularY -- Closest point is always perpendicular. + elseif checkFuzzy( slope, 0 ) then -- Horizontal line + x, y = perpendicularX, y1 + else + local perpendicularSlope = getPerpendicularSlope( slope ) + local perpendicularIntercept = getYIntercept( perpendicularX, perpendicularY, perpendicularSlope ) + x, y = getLineLineIntersection( slope, intercept, perpendicularSlope, perpendicularIntercept ) + end + + return x, y +end + +-- Gives the intersection of a line and a line segment. +-- x1, y1, x2, y2, x3, y3, x4, y4 +-- x1, y1, x2, y2, slope, intercept +local function getLineSegmentIntersection( x1, y1, x2, y2, ... ) + local input = checkInput( ... ) + + local slope1, intercept1, x, y, lineX1, lineY1, lineX2, lineY2 + local slope2, intercept2 = getSlope( x1, y1, x2, y2 ), getYIntercept( x1, y1, x2, y2 ) + + if #input == 2 then -- Given slope, intercept + slope1, intercept1 = input[1], input[2] + lineX1, lineY1 = 1, slope1 and slope1 + intercept1 + lineX2, lineY2 = 2, slope1 and slope1 * 2 + intercept1 + else -- Given x3, y3, x4, y4 + lineX1, lineY1, lineX2, lineY2 = unpack( input ) + slope1 = getSlope( unpack( input ) ) + intercept1 = getYIntercept( unpack( input ) ) + end + + if not slope1 and not slope2 then -- Vertical lines + if checkFuzzy( x1, lineX1 ) then + return x1, y1, x2, y2 + else + return false + end + elseif not slope1 then -- slope1 is vertical + x, y = input[1], slope2 * input[1] + intercept2 + elseif not slope2 then -- slope2 is vertical + x, y = x1, slope1 * x1 + intercept1 + else + x, y = getLineLineIntersection( slope1, intercept1, slope2, intercept2 ) + end + + local length1, length2, distance + if x == true then -- Lines are collinear. + return x1, y1, x2, y2 + elseif x then -- There is an intersection + length1, length2 = getLength( x1, y1, x, y ), getLength( x2, y2, x, y ) + distance = getLength( x1, y1, x2, y2 ) + else -- Lines are parallel but not collinear. + if checkFuzzy( intercept1, intercept2 ) then + return x1, y1, x2, y2 + else + return false + end + end + + if length1 <= distance and length2 <= distance then return x, y else return false end +end + +-- Checks if a point is on a line. +-- Does not support the format using slope because vertical lines would be impossible to check. +local function checkLinePoint( x, y, x1, y1, x2, y2 ) + local m = getSlope( x1, y1, x2, y2 ) + local b = getYIntercept( x1, y1, m ) + + if not m then -- Vertical + return checkFuzzy( x, x1 ) + end + return checkFuzzy( y, m * x + b ) +end -- }}} + +-- Segment -------------------------------------- {{{ +-- Gives the perpendicular bisector of a line. +local function getPerpendicularBisector( x1, y1, x2, y2 ) + local slope = getSlope( x1, y1, x2, y2 ) + local midpointX, midpointY = getMidpoint( x1, y1, x2, y2 ) + return midpointX, midpointY, getPerpendicularSlope( slope ) +end + +-- Gives whether or not a point lies on a line segment. +local function checkSegmentPoint( px, py, x1, y1, x2, y2 ) + -- Explanation around 5:20: https://www.youtube.com/watch?v=A86COO8KC58 + local x = checkLinePoint( px, py, x1, y1, x2, y2 ) + if not x then return false end + + local lengthX = x2 - x1 + local lengthY = y2 - y1 + + if checkFuzzy( lengthX, 0 ) then -- Vertical line + if checkFuzzy( px, x1 ) then + local low, high + if y1 > y2 then low = y2; high = y1 + else low = y1; high = y2 end + + if py >= low and py <= high then return true + else return false end + else + return false + end + elseif checkFuzzy( lengthY, 0 ) then -- Horizontal line + if checkFuzzy( py, y1 ) then + local low, high + if x1 > x2 then low = x2; high = x1 + else low = x1; high = x2 end + + if px >= low and px <= high then return true + else return false end + else + return false + end + end + + local distanceToPointX = ( px - x1 ) + local distanceToPointY = ( py - y1 ) + local scaleX = distanceToPointX / lengthX + local scaleY = distanceToPointY / lengthY + + if ( scaleX >= 0 and scaleX <= 1 ) and ( scaleY >= 0 and scaleY <= 1 ) then -- Intersection + return true + end + return false +end + +-- Gives the point of intersection between two line segments. +local function getSegmentSegmentIntersection( x1, y1, x2, y2, x3, y3, x4, y4 ) + local slope1, intercept1 = getSlope( x1, y1, x2, y2 ), getYIntercept( x1, y1, x2, y2 ) + local slope2, intercept2 = getSlope( x3, y3, x4, y4 ), getYIntercept( x3, y3, x4, y4 ) + + if ( ( slope1 and slope2 ) and checkFuzzy( slope1, slope2 ) ) or ( not slope1 and not slope2 ) then -- Parallel lines + if checkFuzzy( intercept1, intercept2 ) then -- The same lines, possibly in different points. + local points = {} + if checkSegmentPoint( x1, y1, x3, y3, x4, y4 ) then addPoints( points, x1, y1 ) end + if checkSegmentPoint( x2, y2, x3, y3, x4, y4 ) then addPoints( points, x2, y2 ) end + if checkSegmentPoint( x3, y3, x1, y1, x2, y2 ) then addPoints( points, x3, y3 ) end + if checkSegmentPoint( x4, y4, x1, y1, x2, y2 ) then addPoints( points, x4, y4 ) end + + points = removeDuplicatePointsFlat( points ) + if #points == 0 then return false end + return unpack( points ) + else + return false + end + end + + local x, y = getLineLineIntersection( x1, y1, x2, y2, x3, y3, x4, y4 ) + if x and checkSegmentPoint( x, y, x1, y1, x2, y2 ) and checkSegmentPoint( x, y, x3, y3, x4, y4 ) then + return x, y + end + return false +end -- }}} + +-- Math ----------------------------------------- {{{ +-- Get the root of a number (i.e. the 2nd (square) root of 4 is 2) +local function getRoot( number, root ) + return number ^ ( 1 / root ) +end + +-- Checks if a number is prime. +local function isPrime( number ) + if number < 2 then return false end + + for i = 2, math.sqrt( number ) do + if number % i == 0 then + return false + end + end + return true +end + +-- Rounds a number to the xth decimal place (round( 3.14159265359, 4 ) --> 3.1416) +local function round( number, place ) + local pow = 10 ^ ( place or 0 ) + return math.floor( number * pow + .5 ) / pow +end + +-- Gives the summation given a local function +local function getSummation( start, stop, func ) + local returnValues = {} + local sum = 0 + for i = start, stop do + local value = func( i, returnValues ) + returnValues[i] = value + sum = sum + value + end + return sum +end + +-- Gives the percent of change. +local function getPercentOfChange( old, new ) + if old == 0 and new == 0 then + return 0 + else + return ( new - old ) / math.abs( old ) + end +end + +-- Gives the percentage of a number. +local function getPercentage( percent, number ) + return percent * number +end + +-- Returns the quadratic roots of an equation. +local function getQuadraticRoots( a, b, c ) + local discriminant = b ^ 2 - ( 4 * a * c ) + if discriminant < 0 then return false end + discriminant = math.sqrt( discriminant ) + local denominator = ( 2 * a ) + return ( -b - discriminant ) / denominator, ( -b + discriminant ) / denominator +end + +-- Gives the angle between three points. +local function getAngle( x1, y1, x2, y2, x3, y3 ) + local a = getLength( x3, y3, x2, y2 ) + local b = getLength( x1, y1, x2, y2 ) + local c = getLength( x1, y1, x3, y3 ) + + return math.acos( ( a * a + b * b - c * c ) / ( 2 * a * b ) ) +end -- }}} + +-- Circle --------------------------------------- {{{ +-- Gives the area of the circle. +local function getCircleArea( radius ) + return math.pi * ( radius * radius ) +end + +-- Checks if a point is within the radius of a circle. +local function checkCirclePoint( x, y, circleX, circleY, radius ) + return getLength( circleX, circleY, x, y ) <= radius +end + +-- Checks if a point is on a circle. +local function isPointOnCircle( x, y, circleX, circleY, radius ) + return checkFuzzy( getLength( circleX, circleY, x, y ), radius ) +end + +-- Gives the circumference of a circle. +local function getCircumference( radius ) + return 2 * math.pi * radius +end + +-- Gives the intersection of a line and a circle. +local function getCircleLineIntersection( circleX, circleY, radius, x1, y1, x2, y2 ) + slope = getSlope( x1, y1, x2, y2 ) + intercept = getYIntercept( x1, y1, slope ) + + if slope then + local a = ( 1 + slope ^ 2 ) + local b = ( -2 * ( circleX ) + ( 2 * slope * intercept ) - ( 2 * circleY * slope ) ) + local c = ( circleX ^ 2 + intercept ^ 2 - 2 * ( circleY ) * ( intercept ) + circleY ^ 2 - radius ^ 2 ) + + x1, x2 = getQuadraticRoots( a, b, c ) + + if not x1 then return false end + + y1 = slope * x1 + intercept + y2 = slope * x2 + intercept + + if checkFuzzy( x1, x2 ) and checkFuzzy( y1, y2 ) then + return 'tangent', x1, y1 + else + return 'secant', x1, y1, x2, y2 + end + else -- Vertical Lines + local lengthToPoint1 = circleX - x1 + local remainingDistance = lengthToPoint1 - radius + local intercept = math.sqrt( -( lengthToPoint1 ^ 2 - radius ^ 2 ) ) + + if -( lengthToPoint1 ^ 2 - radius ^ 2 ) < 0 then return false end + + local bottomX, bottomY = x1, circleY - intercept + local topX, topY = x1, circleY + intercept + + if topY ~= bottomY then + return 'secant', topX, topY, bottomX, bottomY + else + return 'tangent', topX, topY + end + end +end + +-- Gives the type of intersection of a line segment. +local function getCircleSegmentIntersection( circleX, circleY, radius, x1, y1, x2, y2 ) + local Type, x3, y3, x4, y4 = getCircleLineIntersection( circleX, circleY, radius, x1, y1, x2, y2 ) + if not Type then return false end + + local slope, intercept = getSlope( x1, y1, x2, y2 ), getYIntercept( x1, y1, x2, y2 ) + + if isPointOnCircle( x1, y1, circleX, circleY, radius ) and isPointOnCircle( x2, y2, circleX, circleY, radius ) then -- Both points are on line-segment. + return 'chord', x1, y1, x2, y2 + end + + if slope then + if checkCirclePoint( x1, y1, circleX, circleY, radius ) and checkCirclePoint( x2, y2, circleX, circleY, radius ) then -- Line-segment is fully in circle. + return 'enclosed', x1, y1, x2, y2 + elseif x3 and x4 then + if checkSegmentPoint( x3, y3, x1, y1, x2, y2 ) and not checkSegmentPoint( x4, y4, x1, y1, x2, y2 ) then -- Only the first of the points is on the line-segment. + return 'tangent', x3, y3 + elseif checkSegmentPoint( x4, y4, x1, y1, x2, y2 ) and not checkSegmentPoint( x3, y3, x1, y1, x2, y2 ) then -- Only the second of the points is on the line-segment. + return 'tangent', x4, y4 + else -- Neither of the points are on the circle (means that the segment is not on the circle, but "encasing" the circle) + if checkSegmentPoint( x3, y3, x1, y1, x2, y2 ) and checkSegmentPoint( x4, y4, x1, y1, x2, y2 ) then + return 'secant', x3, y3, x4, y4 + else + return false + end + end + elseif not x4 then -- Is a tangent. + if checkSegmentPoint( x3, y3, x1, y1, x2, y2 ) then + return 'tangent', x3, y3 + else -- Neither of the points are on the line-segment (means that the segment is not on the circle or "encasing" the circle). + local length = getLength( x1, y1, x2, y2 ) + local distance1 = getLength( x1, y1, x3, y3 ) + local distance2 = getLength( x2, y2, x3, y3 ) + + if length > distance1 or length > distance2 then + return false + elseif length < distance1 and length < distance2 then + return false + else + return 'tangent', x3, y3 + end + end + end + else + local lengthToPoint1 = circleX - x1 + local remainingDistance = lengthToPoint1 - radius + local intercept = math.sqrt( -( lengthToPoint1 ^ 2 - radius ^ 2 ) ) + + if -( lengthToPoint1 ^ 2 - radius ^ 2 ) < 0 then return false end + + local topX, topY = x1, circleY - intercept + local bottomX, bottomY = x1, circleY + intercept + + local length = getLength( x1, y1, x2, y2 ) + local distance1 = getLength( x1, y1, topX, topY ) + local distance2 = getLength( x2, y2, topX, topY ) + + if bottomY ~= topY then -- Not a tangent + if checkSegmentPoint( topX, topY, x1, y1, x2, y2 ) and checkSegmentPoint( bottomX, bottomY, x1, y1, x2, y2 ) then + return 'chord', topX, topY, bottomX, bottomY + elseif checkSegmentPoint( topX, topY, x1, y1, x2, y2 ) then + return 'tangent', topX, topY + elseif checkSegmentPoint( bottomX, bottomY, x1, y1, x2, y2 ) then + return 'tangent', bottomX, bottomY + else + return false + end + else -- Tangent + if checkSegmentPoint( topX, topY, x1, y1, x2, y2 ) then + return 'tangent', topX, topY + else + return false + end + end + end +end + +-- Checks if one circle intersects another circle. +local function getCircleCircleIntersection( circle1x, circle1y, radius1, circle2x, circle2y, radius2 ) + local length = getLength( circle1x, circle1y, circle2x, circle2y ) + if length > radius1 + radius2 then return false end -- If the distance is greater than the two radii, they can't intersect. + if checkFuzzy( length, 0 ) and checkFuzzy( radius1, radius2 ) then return 'equal' end + if checkFuzzy( circle1x, circle2x ) and checkFuzzy( circle1y, circle2y ) then return 'collinear' end + + local a = ( radius1 * radius1 - radius2 * radius2 + length * length ) / ( 2 * length ) + local h = math.sqrt( radius1 * radius1 - a * a ) + + local p2x = circle1x + a * ( circle2x - circle1x ) / length + local p2y = circle1y + a * ( circle2y - circle1y ) / length + local p3x = p2x + h * ( circle2y - circle1y ) / length + local p3y = p2y - h * ( circle2x - circle1x ) / length + local p4x = p2x - h * ( circle2y - circle1y ) / length + local p4y = p2y + h * ( circle2x - circle1x ) / length + + if not validateNumber( p3x ) or not validateNumber( p3y ) or not validateNumber( p4x ) or not validateNumber( p4y ) then + return 'inside' + end + + if checkFuzzy( length, radius1 + radius2 ) or checkFuzzy( length, math.abs( radius1 - radius2 ) ) then return 'tangent', p3x, p3y end + return 'intersection', p3x, p3y, p4x, p4y +end + +-- Checks if circle1 is entirely inside of circle2. +local function isCircleCompletelyInsideCircle( circle1x, circle1y, circle1radius, circle2x, circle2y, circle2radius ) + if not checkCirclePoint( circle1x, circle1y, circle2x, circle2y, circle2radius ) then return false end + local Type = getCircleCircleIntersection( circle2x, circle2y, circle2radius, circle1x, circle1y, circle1radius ) + if ( Type ~= 'tangent' and Type ~= 'collinear' and Type ~= 'inside' ) then return false end + return true +end + +-- Checks if a line-segment is entirely within a circle. +local function isSegmentCompletelyInsideCircle( circleX, circleY, circleRadius, x1, y1, x2, y2 ) + local Type = getCircleSegmentIntersection( circleX, circleY, circleRadius, x1, y1, x2, y2 ) + return Type == 'enclosed' +end -- }}} + +-- Polygon -------------------------------------- {{{ +-- Gives the signed area. +-- If the points are clockwise the number is negative, otherwise, it's positive. +local function getSignedPolygonArea( ... ) + local points = checkInput( ... ) + + -- Shoelace formula (https://en.wikipedia.org/wiki/Shoelace_formula). + points[#points + 1] = points[1] + points[#points + 1] = points[2] + + return ( .5 * getSummation( 1, #points / 2, + function( index ) + index = index * 2 - 1 -- Convert it to work properly. + return ( ( points[index] * cycle( points, index + 3 ) ) - ( cycle( points, index + 2 ) * points[index + 1] ) ) + end + ) ) +end + +-- Simply returns the area of the polygon. +local function getPolygonArea( ... ) + return math.abs( getSignedPolygonArea( ... ) ) +end + +-- Gives the height of a triangle, given the base. +-- base, x1, y1, x2, y2, x3, y3, x4, y4 +-- base, area +local function getTriangleHeight( base, ... ) + local input = checkInput( ... ) + local area + + if #input == 1 then area = input[1] -- Given area. + else area = getPolygonArea( input ) end -- Given coordinates. + + return ( 2 * area ) / base, area +end + +-- Gives the centroid of the polygon. +local function getCentroid( ... ) + local points = checkInput( ... ) + + points[#points + 1] = points[1] + points[#points + 1] = points[2] + + local area = getSignedPolygonArea( points ) -- Needs to be signed here in case points are counter-clockwise. + + -- This formula: https://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon + local centroidX = ( 1 / ( 6 * area ) ) * ( getSummation( 1, #points / 2, + function( index ) + index = index * 2 - 1 -- Convert it to work properly. + return ( ( points[index] + cycle( points, index + 2 ) ) * ( ( points[index] * cycle( points, index + 3 ) ) - ( cycle( points, index + 2 ) * points[index + 1] ) ) ) + end + ) ) + + local centroidY = ( 1 / ( 6 * area ) ) * ( getSummation( 1, #points / 2, + function( index ) + index = index * 2 - 1 -- Convert it to work properly. + return ( ( points[index + 1] + cycle( points, index + 3 ) ) * ( ( points[index] * cycle( points, index + 3 ) ) - ( cycle( points, index + 2 ) * points[index + 1] ) ) ) + end + ) ) + + return centroidX, centroidY +end + +-- Returns whether or not a line intersects a polygon. +-- x1, y1, x2, y2, polygonPoints +local function getPolygonLineIntersection( x1, y1, x2, y2, ... ) + local input = checkInput( ... ) + local choices = {} + + local slope = getSlope( x1, y1, x2, y2 ) + local intercept = getYIntercept( x1, y1, slope ) + + local x3, y3, x4, y4 + if slope then + x3, x4 = 1, 2 + y3, y4 = slope * x3 + intercept, slope * x4 + intercept + else + x3, x4 = x1, x1 + y3, y4 = y1, y2 + end + + for i = 1, #input, 2 do + local x1, y1, x2, y2 = getLineSegmentIntersection( input[i], input[i + 1], cycle( input, i + 2 ), cycle( input, i + 3 ), x3, y3, x4, y4 ) + if x1 and not x2 then choices[#choices + 1] = { x1, y1 } + elseif x1 and x2 then choices[#choices + 1] = { x1, y1, x2, y2 } end + -- No need to check 2-point sets since they only intersect each poly line once. + end + + local final = removeDuplicatePairs( choices ) + return #final > 0 and final or false +end + +-- Returns if the line segment intersects the polygon. +-- x1, y1, x2, y2, polygonPoints +local function getPolygonSegmentIntersection( x1, y1, x2, y2, ... ) + local input = checkInput( ... ) + local choices = {} + + for i = 1, #input, 2 do + local x1, y1, x2, y2 = getSegmentSegmentIntersection( input[i], input[i + 1], cycle( input, i + 2 ), cycle( input, i + 3 ), x1, y1, x2, y2 ) + if x1 and not x2 then choices[#choices + 1] = { x1, y1 } + elseif x2 then choices[#choices + 1] = { x1, y1, x2, y2 } end + end + + local final = removeDuplicatePairs( choices ) + return #final > 0 and final or false +end + +-- Checks if the point lies INSIDE the polygon not on the polygon. +local function checkPolygonPoint( px, py, ... ) + local points = { unpack( checkInput( ... ) ) } -- Make a new table, as to not edit values of previous. + + local greatest, least = getGreatestPoint( points, 0 ) + if not isWithinBounds( least, py, greatest ) then return false end + greatest, least = getGreatestPoint( points ) + if not isWithinBounds( least, px, greatest ) then return false end + + local count = 0 + for i = 1, #points, 2 do + if checkFuzzy( points[i + 1], py ) then + points[i + 1] = py + .001 -- Handles vertices that lie on the point. + -- Not exactly mathematically correct, but a lot easier. + end + if points[i + 3] and checkFuzzy( points[i + 3], py ) then + points[i + 3] = py + .001 -- Do not need to worry about alternate case, since points[2] has already been done. + end + local x1, y1 = points[i], points[i + 1] + local x2, y2 = points[i + 2] or points[1], points[i + 3] or points[2] + + if getSegmentSegmentIntersection( px, py, greatest, py, x1, y1, x2, y2 ) then + count = count + 1 + end + end + + return count and count % 2 ~= 0 +end + +-- Returns if the line segment is fully or partially inside. +-- x1, y1, x2, y2, polygonPoints +local function isSegmentInsidePolygon( x1, y1, x2, y2, ... ) + local input = checkInput( ... ) + + local choices = getPolygonSegmentIntersection( x1, y1, x2, y2, input ) -- If it's partially enclosed that's all we need. + if choices then return true end + + if checkPolygonPoint( x1, y1, input ) or checkPolygonPoint( x2, y2, input ) then return true end + return false +end + +-- Returns whether two polygons intersect. +local function getPolygonPolygonIntersection( polygon1, polygon2 ) + local choices = {} + + for index1 = 1, #polygon1, 2 do + local intersections = getPolygonSegmentIntersection( polygon1[index1], polygon1[index1 + 1], cycle( polygon1, index1 + 2 ), cycle( polygon1, index1 + 3 ), polygon2 ) + if intersections then + for index2 = 1, #intersections do + choices[#choices + 1] = intersections[index2] + end + end + end + + for index1 = 1, #polygon2, 2 do + local intersections = getPolygonSegmentIntersection( polygon2[index1], polygon2[index1 + 1], cycle( polygon2, index1 + 2 ), cycle( polygon2, index1 + 3 ), polygon1 ) + if intersections then + for index2 = 1, #intersections do + choices[#choices + 1] = intersections[index2] + end + end + end + + choices = removeDuplicatePairs( choices ) + for i = #choices, 1, -1 do + if type( choices[i][1] ) == 'table' then -- Remove co-linear pairs. + table.remove( choices, i ) + end + end + + return #choices > 0 and choices +end + +-- Returns whether the circle intersects the polygon. +-- x, y, radius, polygonPoints +local function getPolygonCircleIntersection( x, y, radius, ... ) + local input = checkInput( ... ) + local choices = {} + + for i = 1, #input, 2 do + local Type, x1, y1, x2, y2 = getCircleSegmentIntersection( x, y, radius, input[i], input[i + 1], cycle( input, i + 2 ), cycle( input, i + 3 ) ) + if x2 then + choices[#choices + 1] = { Type, x1, y1, x2, y2 } + elseif x1 then choices[#choices + 1] = { Type, x1, y1 } end + end + + local final = removeDuplicates4Points( choices ) + + return #final > 0 and final +end + +-- Returns whether the circle is inside the polygon. +-- x, y, radius, polygonPoints +local function isCircleInsidePolygon( x, y, radius, ... ) + local input = checkInput( ... ) + return checkPolygonPoint( x, y, input ) +end + +-- Returns whether the polygon is inside the polygon. +local function isPolygonInsidePolygon( polygon1, polygon2 ) + local bool = false + for i = 1, #polygon2, 2 do + local result = false + result = isSegmentInsidePolygon( polygon2[i], polygon2[i + 1], cycle( polygon2, i + 2 ), cycle( polygon2, i + 3 ), polygon1 ) + if result then bool = true; break end + end + return bool +end + +-- Checks if a segment is completely inside a polygon +local function isSegmentCompletelyInsidePolygon( x1, y1, x2, y2, ... ) + local polygon = checkInput( ... ) + if not checkPolygonPoint( x1, y1, polygon ) + or not checkPolygonPoint( x2, y2, polygon ) + or getPolygonSegmentIntersection( x1, y1, x2, y2, polygon ) then + return false + end + return true +end + +-- Checks if a polygon is completely inside another polygon +local function isPolygonCompletelyInsidePolygon( polygon1, polygon2 ) + for i = 1, #polygon1, 2 do + local x1, y1 = polygon1[i], polygon1[i + 1] + local x2, y2 = polygon1[i + 2] or polygon1[1], polygon1[i + 3] or polygon1[2] + if not isSegmentCompletelyInsidePolygon( x1, y1, x2, y2, polygon2 ) then + return false + end + end + return true +end + +-------------- Circle w/ Polygons -------------- +-- Gets if a polygon is completely within a circle +-- circleX, circleY, circleRadius, polygonPoints +local function isPolygonCompletelyInsideCircle( circleX, circleY, circleRadius, ... ) + local input = checkInput( ... ) + local function isDistanceLess( px, py, x, y, circleRadius ) -- Faster, does not use math.sqrt + local distanceX, distanceY = px - x, py - y + return distanceX * distanceX + distanceY * distanceY < circleRadius * circleRadius -- Faster. For comparing distances only. + end + + for i = 1, #input, 2 do + if not checkCirclePoint( input[i], input[i + 1], circleX, circleY, circleRadius ) then return false end + end + return true +end + +-- Checks if a circle is completely within a polygon +-- circleX, circleY, circleRadius, polygonPoints +local function isCircleCompletelyInsidePolygon( circleX, circleY, circleRadius, ... ) + local input = checkInput( ... ) + if not checkPolygonPoint( circleX, circleY, ... ) then return false end + + local rad2 = circleRadius * circleRadius + + for i = 1, #input, 2 do + local x1, y1 = input[i], input[i + 1] + local x2, y2 = input[i + 2] or input[1], input[i + 3] or input[2] + if distance2( x1, y1, circleX, circleY ) <= rad2 then return false end + if getCircleSegmentIntersection( circleX, circleY, circleRadius, x1, y1, x2, y2 ) then return false end + end + return true +end -- }}} + +-- Statistics ----------------------------------- {{{ +-- Gets the average of a list of points +-- points +local function getMean( ... ) + local input = checkInput( ... ) + + mean = getSummation( 1, #input, + function( i, t ) + return input[i] + end + ) / #input + + return mean +end + +local function getMedian( ... ) + local input = checkInput( ... ) + + table.sort( input ) + + local median + if #input % 2 == 0 then -- If you have an even number of terms, you need to get the average of the middle 2. + median = getMean( input[#input / 2], input[#input / 2 + 1] ) + else + median = input[#input / 2 + .5] + end + + return median +end + +-- Gets the mode of a number. +local function getMode( ... ) + local input = checkInput( ... ) + + table.sort( input ) + local sorted = {} + for i = 1, #input do + local value = input[i] + sorted[value] = sorted[value] and sorted[value] + 1 or 1 + end + + local occurrences, least = 0, {} + for i, value in pairs( sorted ) do + if value > occurrences then + least = { i } + occurrences = value + elseif value == occurrences then + least[#least + 1] = i + end + end + + if #least >= 1 then return least, occurrences + else return false end +end + +-- Gets the range of the numbers. +local function getRange( ... ) + local input = checkInput( ... ) + local high, low = math.max( unpack( input ) ), math.min( unpack( input ) ) + return high - low +end + +-- Gets the variance of a set of numbers. +local function getVariance( ... ) + local input = checkInput( ... ) + local mean = getMean( ... ) + local sum = 0 + for i = 1, #input do + sum = sum + ( mean - input[i] ) * ( mean - input[i] ) + end + return sum / #input +end + +-- Gets the standard deviation of a set of numbers. +local function getStandardDeviation( ... ) + return math.sqrt( getVariance( ... ) ) +end + +-- Gets the central tendency of a set of numbers. +local function getCentralTendency( ... ) + local mode, occurrences = getMode( ... ) + return mode, occurrences, getMedian( ... ), getMean( ... ) +end + +-- Gets the variation ratio of a data set. +local function getVariationRatio( ... ) + local input = checkInput( ... ) + local numbers, times = getMode( ... ) + times = times * #numbers -- Account for bimodal data + return 1 - ( times / #input ) +end + +-- Gets the measures of dispersion of a data set. +local function getDispersion( ... ) + return getVariationRatio( ... ), getRange( ... ), getStandardDeviation( ... ) +end -- }}} + +return { + _VERSION = 'MLib 0.10.0', + _DESCRIPTION = 'A math and shape-intersection detection library for Lua', + _URL = 'https://github.com/davisdude/mlib', + point = { + rotate = rotatePoint, + scale = scalePoint, + }, + line = { + getLength = getLength, + getMidpoint = getMidpoint, + getSlope = getSlope, + getPerpendicularSlope = getPerpendicularSlope, + getYIntercept = getYIntercept, + getIntersection = getLineLineIntersection, + getClosestPoint = getClosestPoint, + getSegmentIntersection = getLineSegmentIntersection, + checkPoint = checkLinePoint, + + -- Aliases + getDistance = getLength, + getCircleIntersection = getCircleLineIntersection, + getPolygonIntersection = getPolygonLineIntersection, + getLineIntersection = getLineLineIntersection, + }, + segment = { + checkPoint = checkSegmentPoint, + getPerpendicularBisector = getPerpendicularBisector, + getIntersection = getSegmentSegmentIntersection, + + -- Aliases + getCircleIntersection = getCircleSegmentIntersection, + getPolygonIntersection = getPolygonSegmentIntersection, + getLineIntersection = getLineSegmentIntersection, + getSegmentIntersection = getSegmentSegmentIntersection, + isSegmentCompletelyInsideCircle = isSegmentCompletelyInsideCircle, + isSegmentCompletelyInsidePolygon = isSegmentCompletelyInsidePolygon, + }, + math = { + getRoot = getRoot, + isPrime = isPrime, + round = round, + getSummation = getSummation, + getPercentOfChange = getPercentOfChange, + getPercentage = getPercentage, + getQuadraticRoots = getQuadraticRoots, + getAngle = getAngle, + }, + circle = { + getArea = getCircleArea, + checkPoint = checkCirclePoint, + isPointOnCircle = isPointOnCircle, + getCircumference = getCircumference, + getLineIntersection = getCircleLineIntersection, + getSegmentIntersection = getCircleSegmentIntersection, + getCircleIntersection = getCircleCircleIntersection, + isCircleCompletelyInside = isCircleCompletelyInsideCircle, + isPolygonCompletelyInside = isPolygonCompletelyInsideCircle, + isSegmentCompletelyInside = isSegmentCompletelyInsideCircle, + + -- Aliases + getPolygonIntersection = getPolygonCircleIntersection, + isCircleInsidePolygon = isCircleInsidePolygon, + isCircleCompletelyInsidePolygon = isCircleCompletelyInsidePolygon, + }, + polygon = { + getSignedArea = getSignedPolygonArea, + getArea = getPolygonArea, + getTriangleHeight = getTriangleHeight, + getCentroid = getCentroid, + getLineIntersection = getPolygonLineIntersection, + getSegmentIntersection = getPolygonSegmentIntersection, + checkPoint = checkPolygonPoint, + isSegmentInside = isSegmentInsidePolygon, + getPolygonIntersection = getPolygonPolygonIntersection, + getCircleIntersection = getPolygonCircleIntersection, + isCircleInside = isCircleInsidePolygon, + isPolygonInside = isPolygonInsidePolygon, + isCircleCompletelyInside = isCircleCompletelyInsidePolygon, + isSegmentCompletelyInside = isSegmentCompletelyInsidePolygon, + isPolygonCompletelyInside = isPolygonCompletelyInsidePolygon, + + -- Aliases + isCircleCompletelyOver = isPolygonCompletelyInsideCircle, + }, + statistics = { + getMean = getMean, + getMedian = getMedian, + getMode = getMode, + getRange = getRange, + getVariance = getVariance, + getStandardDeviation = getStandardDeviation, + getCentralTendency = getCentralTendency, + getVariationRatio = getVariationRatio, + getDispersion = getDispersion, + }, +} diff --git a/main.lua b/main.lua new file mode 100644 index 0000000..7f7c10d --- /dev/null +++ b/main.lua @@ -0,0 +1,33 @@ +local Gamestate = require("libs.hump.gamestate") +local LoveSplash = require("libs.o-ten-one") +require("scenes.menu_scene"); + +function love.load() + splash = LoveSplash({background={0, 0, 0}}) + splash.onDone = onLoveSplashDone +end + +function onLoveSplashDone() + splash = nil + Gamestate.switch(menu) + Gamestate.registerEvents() +end + +function love.draw() + if splash then + splash:draw() + end +end + +function love.update(dt) + if splash then + splash:update(dt) + end +end + +function love.keyreleased(key, scancode) + -- Temporary + if scancode == 'escape' then + love.event.quit() + end +end
\ No newline at end of file diff --git a/scenes/level1_scene.lua b/scenes/level1_scene.lua new file mode 100644 index 0000000..83d676e --- /dev/null +++ b/scenes/level1_scene.lua @@ -0,0 +1,35 @@ +level1 = {} -- Level1 State + +Map = require("utils.map") +-- imports +require("utils.constants") + +local map = nil + +function level1:init() + constants.resetColors() + map = Map("level1") +end + +function level1:enter(previous) + +end + +function level1:update(dt) + map.update(dt) +end + +function level1:draw() + map.draw() + --love.graphics.print("Level 1", 100, 200) +end + +function level1:keypressed(key, scancode) + +end + +function level1:leave() + map = nil +end + +return level1
\ No newline at end of file diff --git a/scenes/menu_scene.lua b/scenes/menu_scene.lua new file mode 100644 index 0000000..a513d6d --- /dev/null +++ b/scenes/menu_scene.lua @@ -0,0 +1,79 @@ +menu = {} -- Menu Game State + +local Timer = require "libs.hump.timer" +local Gamestate = require("libs.hump.gamestate") + +-- scenes +require("scenes.level1_scene"); + +local titleFontSize = 25 +local msgFontSize = 15 +local defaultFontFactor = 8 +local windowWidth = love.graphics.getWidth() +local windowHeight = love.graphics.getHeight() + +function menu:init() + print("Entering Menu") + titleFont = love.graphics.newFont('assets/fonts/minecraftia.ttf', titleFontSize) + startMsgFont = love.graphics.newFont('assets/fonts/minecraftia.ttf', msgFontSize) + music = love.audio.newSource("assets/music/Stevia Sphere - Drum machine dreams.ogg", "stream") + music:setLooping(true) + msgFontColor = {0, 0, 0} + titleFontColor = {1, 1, 1} + starfield = generateStarfield() + + fadeIn = function() + Timer.tween(0.5, msgFontColor, {1, 1, 1}, 'linear', fadeOut) + end + + fadeOut = function() + Timer.tween(0.5, msgFontColor, {0, 0, 0}, 'linear', fadeIn) + end + + fadeIn() + music:play() +end + +function menu:enter(previous) + +end + +function menu:leave() + music:stop() +end + +function menu:update(dt) + psystem:update(dt) + Timer.update(dt) +end + +function menu:draw() + love.graphics.setFont(titleFont) + love.graphics.setColor(titleFontColor) + love.graphics.draw(starfield, love.graphics.getWidth() * 0.5, love.graphics.getHeight() * 0.5) + love.graphics.print("Enemy is in Another Dungeon",(windowWidth * 0.5) - (titleFontSize * defaultFontFactor), (windowHeight * 0.5) - 50) + + love.graphics.setFont(startMsgFont) + love.graphics.setColor(msgFontColor) + love.graphics.print("Press X to START", (windowWidth * 0.5) - (msgFontSize * (defaultFontFactor/1.5)), windowHeight - 50) + +end + +function menu:keyreleased(key, scancode) + if scancode == 'x' then + Gamestate.switch(level1) + end +end + +function generateStarfield() + image = love.graphics.newImage("assets/images/particle.png") + psystem = love.graphics.newParticleSystem(image, 500) + psystem:setParticleLifetime(2, 15) -- Particles live at least 2s and at most 5s. + psystem:setEmissionRate(500) + psystem:setSizeVariation(1) + psystem:setLinearAcceleration(-20, -20, 20, 20) -- Random movement in all directions. + psystem:setColors(1, 1, 1, 1, 1, 1, 1, 0) -- Fade to transparency. + return psystem +end + +return menu
\ No newline at end of file diff --git a/utils/constants.lua b/utils/constants.lua new file mode 100644 index 0000000..2210d65 --- /dev/null +++ b/utils/constants.lua @@ -0,0 +1,11 @@ +constants = {} + +constants.resetBgColor = {0, 0, 0} +constants.resetFgColor = {1, 1, 1} + +function constants:resetColors() + love.graphics.setColor(constants.resetFgColor) + love.graphics.setBackgroundColor(constants.resetBgColor) +end + +return constants
\ No newline at end of file diff --git a/utils/enitity.lua b/utils/enitity.lua new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/utils/enitity.lua diff --git a/utils/map.lua b/utils/map.lua new file mode 100644 index 0000000..f8f4043 --- /dev/null +++ b/utils/map.lua @@ -0,0 +1,51 @@ +Class = require("libs.hump.class") +Gamestate = require("libs.hump.gamestate") +STI = require("libs.sti") +Moonshine = require("libs.moonshine") +Camera = require("libs.hump.camera") + +Map = Class { + init = function(self, mapName) -- TODO pass map instance parameter + width, height = love.graphics.getDimensions( ) + effect = Moonshine(width, height, Moonshine.effects.crt) + .chain(Moonshine.effects.vignette) + .chain(Moonshine.effects.scanlines) + .chain(Moonshine.effects.chromasep) + effect.scanlines.thickness = .2 + effect.scanlines.opacity = .5 + effect.chromasep.angle = 1 + effect.chromasep.radius = 5 + camera = Camera() + camera:zoom(1) + print("Map Manager") + currentMap = STI("assets/maps/"..mapName..".lua") + if currentMap.layers["entities"] then + for i,obj in pairs(currentMap.layers["entities"].objects) do + print(obj.name) + end + end + end, + entities={} +} + +function Map:update(dt) + print("Map Update") + currentMap:update(dt) +end + +function Map:draw() + print("Map Draw") + camera:attach() + effect(function() + + currentMap:drawLayer(currentMap.layers["ground"]) + + end) + camera:detach() +end + +function Map:keypressed(key, scancode) + +end + +return Map
\ No newline at end of file |