commit 2f0e1614d02deca4900b351551bbedfaeaf5f5e0 Author: Jaidyn Ann Date: Thu Jan 7 01:29:06 2021 -0600 Init diff --git a/COPYING.txt b/COPYING.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/COPYING.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7702476 --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +love: + zip -9r bin/monkune.love ./* + +win32: love +ifeq (,$(wildcard bin/love-win32.zip)) + wget -O bin/love-win32.zip \ + https://github.com/love2d/love/releases/download/11.3/love-11.3-win32.zip +endif + unzip -d bin/ bin/love-win32.zip + mv bin/love-*-win32 bin/monkune-win32 + rm bin/monkune-win32/changes.txt + rm bin/monkune-win32/readme.txt + rm bin/monkune-win32/lovec.exe + cat bin/monkune.love >> bin/monkune-win32/love.exe + mv bin/monkune-win32/love.exe bin/monkune-win32/KunKune.exe + cp lib/bin-license.txt bin/monkune-win32/license.txt + zip -9jr bin/monkune-win32.zip bin/monkune-win32 + rm -rf bin/monkune-win32 + +test: love + love bin/monkune.love + +clean: + rm -rf ./bin/* + +all: love win32 diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..1595c60 --- /dev/null +++ b/README.txt @@ -0,0 +1,10 @@ +MONKUNE +================================================================================ +is a puzzle-ish game made for Librejam 2020-01! + +BORING STUFF! +-------------------------------------------------- +Jaidyn Ann ! +Code under GPLv3 (see COPYING.txt)! +Art under varying (libre; see ./art/COPYING.txt)! +Libraries under varying (libre; see ./lib/COPYING.txt)! diff --git a/art/COPYING.txt b/art/COPYING.txt new file mode 100644 index 0000000..24130fb --- /dev/null +++ b/art/COPYING.txt @@ -0,0 +1,10 @@ +All art assets are licensed under Free Culture licenses that allow +(commercial) redistribution, modification, etc. + +They're mostly under Creative Commons licenses, or the Public Domain. + +Each asset (under the "art" directory) has a corresponding text-file with +the author, the source URL, and licensing information. + + +DawnLike: diff --git a/art/font/alagard.ttf b/art/font/alagard.ttf new file mode 100644 index 0000000..c7ed1d9 Binary files /dev/null and b/art/font/alagard.ttf differ diff --git a/art/font/alagard.txt b/art/font/alagard.txt new file mode 100644 index 0000000..42487c0 --- /dev/null +++ b/art/font/alagard.txt @@ -0,0 +1,3 @@ +Author: Pix3M +Source: https://opengameart.org/content/pixel-fonts-by-pix3m +License: CC-BY 3.0 diff --git a/art/font/romulus.ttf b/art/font/romulus.ttf new file mode 100644 index 0000000..667fd0a Binary files /dev/null and b/art/font/romulus.ttf differ diff --git a/art/font/romulus.txt b/art/font/romulus.txt new file mode 100644 index 0000000..42487c0 --- /dev/null +++ b/art/font/romulus.txt @@ -0,0 +1,3 @@ +Author: Pix3M +Source: https://opengameart.org/content/pixel-fonts-by-pix3m +License: CC-BY 3.0 diff --git a/art/sprites/monk-frozen.png b/art/sprites/monk-frozen.png new file mode 100644 index 0000000..d9192de Binary files /dev/null and b/art/sprites/monk-frozen.png differ diff --git a/art/sprites/monk-frozen.wb b/art/sprites/monk-frozen.wb new file mode 100644 index 0000000..5b3f6c2 Binary files /dev/null and b/art/sprites/monk-frozen.wb differ diff --git a/art/sprites/monk-jump.png b/art/sprites/monk-jump.png new file mode 100644 index 0000000..6d028d4 Binary files /dev/null and b/art/sprites/monk-jump.png differ diff --git a/art/sprites/monk-jump.wb b/art/sprites/monk-jump.wb new file mode 100644 index 0000000..4275d57 Binary files /dev/null and b/art/sprites/monk-jump.wb differ diff --git a/art/sprites/monk.png b/art/sprites/monk.png new file mode 100644 index 0000000..f460387 Binary files /dev/null and b/art/sprites/monk.png differ diff --git a/art/sprites/monk.wb b/art/sprites/monk.wb new file mode 100644 index 0000000..044d257 Binary files /dev/null and b/art/sprites/monk.wb differ diff --git a/conf.lua b/conf.lua new file mode 100644 index 0000000..ba50335 --- /dev/null +++ b/conf.lua @@ -0,0 +1,5 @@ +function love.conf(t) + t.window.resizable = true + t.window.title = "Monkune" + t.window.vsync = 0 +end diff --git a/lib/COPYING.txt b/lib/COPYING.txt new file mode 100644 index 0000000..d72545d --- /dev/null +++ b/lib/COPYING.txt @@ -0,0 +1,7 @@ +All art assets are licensed under Free Culture licenses that allow +(commercial) redistribution, modification, etc. + +They're mostly under Creative Commons licenses, or the Public Domain. + +Each asset (under the "art" directory) has a corresponding text-file with +the author, the source URL, and licensing information. diff --git a/lib/STALKER-X/README.md b/lib/STALKER-X/README.md new file mode 100644 index 0000000..1bd3e81 --- /dev/null +++ b/lib/STALKER-X/README.md @@ -0,0 +1,808 @@ +**STALKER-X** is a camera module for LÖVE. It provides basic functionalities that a camera should have and is inspired by +[hump.camera](http://hump.readthedocs.io/en/latest/camera.html) and [FlxCamera](http://haxeflixel.com/demos/FlxCamera/). The goal +is to provide enough functions that building something like [in this video](https://www.youtube.com/watch?v=aAKwZt3aXQM) +becomes as easy as possible. + +# Contents + +* [Quick Start](#quick-start) + * [Creating a camera object](#creating-a-camera-object) + * [Following a target](#following-a-target) + * [Follow lerp and lead](#follow-lerp-and-lead) + * [Deadzones](#deadzones) + * [LOCKON](#lockon) + * [PLATFORMER](#platformer) + * [TOPDOWN](#topdown) + * [TOPDOWN_TIGHT](#topdown_tight) + * [SCREEN_BY_SCREEN](#screen_by_screen) + * [NO_DEADZONE](#no_deadzone) + * [Custom Deadzones](#custom-deadzones) + * [Shake](#shake) + * [Flash](#flash) + * [Fade](#fade) +* [Tips](#tips) + * [Pixel Camera](#pixel-camera) + * [Fixed Timestep](#fixed-timestep) +* [Documentation](#documentation) + * [Camera](#camerax-y-w-h-scale-rotation) + * [update](#updatedt) + * [draw](#draw) + * [attach](#attach) + * [detach](#detach) + * [x, y](#x-y) + * [scale](#scale) + * [rotation](#rotation) + * [toWorldCoords](#toworldcoordsx-y) + * [toCameraCoords](#tocameracoordsx-y) + * [getMousePosition](#getmouseposition) + * [shake](#shakeintensity-duration-frequency-axes) + * [flash](#flashduration-color) + * [fade](#fadeduration-color) + * [follow](#followx-y) + * [setFollowStyle](#setfollowstylefollow_style) + * [setDeadzone](#setdeadzonex-y-w-h) + * [draw_deadzone](#draw_deadzone) + * [setFollowLerp](#setfollowlerpx-y) + * [setFollowLead](#setfollowleadx-y) + * [setBounds](#setboundsx-y-w-h) + +
+ +# Quick Start + +Place the `Camera.lua` file inside your project and require it: + +```lua +Camera = require 'Camera' +``` + +
+ +## Creating a camera object + +```lua +function love.load() + camera = Camera() +end + +function love.update(dt) + camera:update(dt) +end + +function love.draw() + camera:attach() + -- Draw your game here + camera:detach() + camera:draw() -- Call this here if you're using camera:fade, camera:flash or debug drawing the deadzone +end +``` + +You can create multiple camera objects if needed, even though most of the time you can get away with just a single global one. + +
+ +## Following a target + +The main feature of this library is the ability to follow a target. We can do that in a basic way like this: + +```lua +function love.update(dt) + camera:update(dt) + camera:follow(player.x, player.y) +end +``` + +And that would look like this: + + +

+ +

+ +
+ +## Follow lerp and lead + +We can change how sticky or how ahead of the target the camera is by changing its lerp and lead variables. +Lerp is value that goes from 0 to 1. Closer to 0 means less sticky following, while closer to 1 means stickier following: + +```lua +function love.load() + camera = Camera() + camera:setFollowLerp(0.2) +end +``` + +And that would look like this: + +

+ +

+ +Lead is a value that goes from 0 to infinity. Closer to 0 means no look-ahead, while higher values will move the camera +in the direction of the target's movement more. In practice good lead values will range from 2 to 10. + +```lua +function love.load() + camera = Camera() + camera:setFollowLerp(0.2) + camera:setFollowLead(10) +end +``` + +

+ +

+ +
+ +## Deadzones + +Different deadzones define different areas in which the camera will or will not follow the target. +This can be useful to create all sorts of different behaviors like the some of the ones outlined in +[this article](https://www.gamasutra.com/blogs/ItayKeren/20150511/243083/Scroll_Back_The_Theory_and_Practice_of_Cameras_in_SideScrollers.php). All the examples below use a lerp +value of 0.2 and a lead value of 0. + +### LOCKON + +```lua +function love.load() + camera = Camera() + camera:setFollowStyle('LOCKON') +end +``` + +

+ +

+ +### PLATFORMER + +```lua +function love.load() + camera = Camera() + camera:setFollowStyle('PLATFORMER') +end +``` + +

+ +

+ +### TOPDOWN + +```lua +function love.load() + camera = Camera() + camera:setFollowStyle('TOPDOWN') +end +``` + +

+ +

+ +### TOPDOWN_TIGHT + +```lua +function love.load() + camera = Camera() + camera:setFollowStyle('TOPDOWN_TIGHT') +end +``` + +

+ +

+ +### SCREEN_BY_SCREEN + +In this one the camera will move whenever the target reaches the edges of the screen in a screen by screen basis. +Because of this we need to define the width and height of our screen, which can be seen below as the 3rd and 4rd arguments +to the `Camera` call. In most cases where the external screen size matches the internal screen size this will be done +automatically, but in some cases you might need to define it yourself. + +For instance, if you're doing a pixel art game which has an internal resolution of `360x270`, in which you draw the entire +game to a canvas and then draw the canvas scaled by a factor in the end to fit the final screen size, you'd want the camera's +internal width/height to be the base `360x270`, and not the final `1440x1080` in case of 4x scale factor. + +```lua +function love.load() + camera = Camera(200, 150, 400, 300) + camera:setFollowStyle('SCREEN_BY_SCREEN') +end +``` + +

+ +

+ +### NO_DEADZONE + +Without a deadzone the target will just be followed directly and without lerping or leading being applied. +If the lerp value is 1 and the lead value is 0 (the default values for both of those) then the camera will act +just like in the `NO_DEADZONE` mode, even though the default mode is `LOCKON`. + +```lua +function love.load() + camera = Camera() + camera:setFollowStyle('NO_DEADZONE') +end +``` + +

+ +

+ +### Custom Deadzones + +Custom deadzones can be set with the `:setDeadzone(x, y, w, h)` call. Deadzones are set in camera coordinates, +with the top-left being `0, 0` and the bottom-right being `camera.w, camera.h`. So the following call: + +```lua +function love.load() + local w, h = 400, 300 + camera = Camera(w/2, h/2, w, h) + camera:setDeadzone(40, h/2 - 40, w - 80, 80) +end +``` + +Will result in this: + +

+ +

+ +
+ +## Shake + +```lua +function love.keypressed(key) + if key == 's' then + camera:shake(8, 1, 60) + end +end +``` + +In this example the camera will shake with intensity 8 and for the duration of 1 second with a frequency of 60Hz. +The camera implementation is based on [this tutorial](https://jonny.morrill.me/en/blog/gamedev-how-to-implement-a-camera-shake-effect/) +which provides a nice additional `frequency` parameter. Higher frequency means jerkier motion, and lower frequency means +smoother motion. + +

+ +

+ +Note that if you have a target locked and you have `NO_DEADZONE` or a lerp of 1 set, then a screen shake won't happen +since the camera will be locked tightly to the target. + +
+ +## Flash + +This is a good effect for when the player gets hit, lightning strikes, or similar events. + +```lua +function love.draw() + camera:attach() + -- ... + camera:detach() + camera:draw() -- Must call this to use camera:flash! +end + +function love.keypressed(key) + if key == 'f' then + camera:flash(0.05, {0, 0, 0, 1}) + end +end +``` + +The example above will fill the screen with the black color for 0.05 seconds, which looks like this: + +

+ +

+ +
+ +## Fade + +This is a good effect for transitions between levels. + +```lua +function love.draw() + camera:attach() + -- ... + camera:detach() + camera:draw() -- Must call this to use camera:fade! +end + +function love.keypressed(key) + if key == 'f' then + camera:fade(1, {0, 0, 0, 1}) + end + + if key == 'g' then + camera:fade(1, {0, 0, 0, 0}) + end +end +``` + +In the example above, when `f` is pressed the screen will be gradually filled over 1 second with the black color +and then it will remain covered. If `g` is pressed after that then the screen will gradually go back to normal over 1 second. +The default color that covers the screen initially is `{0, 0, 0, 0}`. + +

+ +

+ +
+ +# Tips + +## Pixel Camera + +All the gifs above were created with what I call a pixel art setup. In that everything is drawn to a canvas at a base resolution +and then that canvas is scaled to the final screen using the `nearest` filter mode. This is how a chunky pixel look can be achieved and it's generally how pixel art is scaled in games. The advantages of this method is that you only have to care +about a single resolution and then everything else takes care of itself. The way this setup looks like in LÖVE code could go +something like this: + +```lua +function love.load() + love.graphics.setDefaultFilter('nearest', 'nearest') -- scale everything with nearest neighbor + canvas = love.graphics.newCanvas(400, 300) +end + +function love.draw() + love.graphics.setCanvas(canvas) + love.graphics.clear() + -- draw the game here + love.graphics.setCanvas() + + -- Draw the 400x300 canvas scaled by 2 to a 800x600 screen + love.graphics.setColor(1, 1, 1, 1) + love.graphics.setBlendMode('alpha', 'premultiplied') + love.graphics.draw(canvas, 0, 0, 0, 2, 2) + love.graphics.setBlendMode('alpha') +end +``` + +All the gifs above followed this code. It's a base resolution of `400x300` being drawn at a scale of 2 to a `800x600` screen. + +Now, this relates to the camera in that to make the camera work with this setup we need to tell it what's the base resolution +we're using. In this case it's `400x300` and so we can create the camera object specifying these values: + +```lua +function love.load() + camera = Camera(200, 150, 400, 300) + ... +end +``` + +The third and fourth arguments of the `Camera` call are for the internal width and height of the camera, and in this case +they should match the base resolution. If those arguments are omitted then it will default to whatever value is returned +by the `love.graphics.getWidth` and `love.graphics.getHeight` calls. In a pixel setup like this omitting those values is +problematic because then the camera would assume an internal resolution of `800x600` which would make everything not work properly. + +
+ +## Fixed Timestep + +If you're using a variable timestep you might notice a jerky motion when the camera tries to follow a target tightly. +This can be fixed by decreasing the lerp value, or more cleanly by using a fixed timestep setup. The code below is based +on the "Free the Physics" section of [this article](https://gafferongames.com/post/fix_your_timestep/). + +```lua +-- LÖVE 0.10.2 fixed timestep loop, Lua version +function love.run() + if love.math then love.math.setRandomSeed(os.time()) end + if love.load then love.load(arg) end + if love.timer then love.timer.step() end + + local dt = 0 + local fixed_dt = 1/60 + local accumulator = 0 + + while true do + if love.event then + love.event.pump() + for name, a, b, c, d, e, f in love.event.poll() do + if name == 'quit' then + if not love.quit or not love.quit() then + return a + end + end + love.handlers[name](a, b, c, d, e, f) + end + end + + if love.timer then + love.timer.step() + dt = love.timer.getDelta() + end + + accumulator = accumulator + dt + while accumulator >= fixed_dt do + if love.update then love.update(fixed_dt) end + accumulator = accumulator - fixed_dt + end + + if love.graphics and love.graphics.isActive() then + love.graphics.clear(love.graphics.getBackgroundColor()) + love.graphics.origin() + if love.draw then love.draw() end + love.graphics.present() + end + + if love.timer then love.timer.sleep(0.0001) end + end +end +``` + +```moonscript +-- LÖVE 0.10.2 fixed timestep loop, MoonScript version +love.run = () -> + if love.math then love.math.setRandomSeed(os.time()) + if love.load then love.load(arg) + if love.timer then love.timer.step() + + dt = 0 + fixed_dt = 1/60 + accumulator = 0 + + while true + if love.event + love.event.pump() + for name, a, b, c, d, e, f in love.event.poll() do + if name == "quit" + if not love.quit or not love.quit() + return a + love.handlers[name](a, b, c, d, e, f) + + if love.timer + love.timer.step() + dt = love.timer.getDelta() + + accumulator += dt + while accumulator >= fixed_dt do + if love.update then love.update(fixed_dt) + accumulator -= fixed_dt + + if love.graphics and love.graphics.isActive() + love.graphics.clear(love.graphics.getBackgroundColor()) + love.graphics.origin() + if love.draw then love.draw() + love.graphics.present() + + if love.timer then love.timer.sleep(0.0001) +``` + +
+ +# DOCUMENTATION + +#### `Camera(x, y, w, h, scale, rotation)` + +Creates a new Camera. + +```lua +camera = Camera() +``` + +Arguments: + +* `x=w/2` `(number)` - The camera's x position. Defaults to `w/2` +* `y=h/2` `(number)` - The camera's y position. Defaults to `h/2` +* `w=love.graphics.getWidth()` `(number)` - The camera's width. Defaults to `love.graphics.getWidth()` +* `h=love.graphics.getHeight()` `(number)` - The camera's height. Defaults to `love.graphics.getHeight()` +* `scale=1` `(number)` - The camera's scale. Defaults to `1` +* `rotation=0` `(number)` - The camera's rotation. Defaults to `0` + +Returns: + +* `Camera` `(table)` - the Camera object + +--- + +#### `:update(dt)` + +Updates the camera. + +```lua +camera:update(dt) +``` + +Arguments: + +* `dt` `(number)` - The time step delta + +--- + +#### `:draw()` + +Draws the camera, drawing the deadzone if `draw_deadzone` is `true` and also drawing the `flash` and `fade` effects. + +```lua +camera:draw() +``` + +--- + +#### `:attach()` + +Attaches the camera, making all following draw operations be affected by the camera's translation, scale and rotation transformations. + +```lua +camera:attach() +-- draw the game here +camera:detach() +``` + +--- + +#### `:detach()` + +Detaches the camera, returning the transformation stack back to normal. + +```lua +camera:attach() +-- draw the game here +camera:detach() +``` + +--- + +#### `.x, .y` + +The camera's position. This is the center of the camera and not its top-left position. This can be changed directly although +if you're using the `follow` function then changing this directly might result in bugs. + +```lua +camera.x, camera.y = 0, 0 +``` + +--- + +#### `.scale` + +The camera's scale/zoom. + +```lua +camera.scale = 2 +``` + +--- + +#### `.rotation` + +The camera's rotation. + +```lua +camera.rotation = math.pi/8 +``` + +--- + +#### `:toWorldCoords(x, y)` + +The same as [hump.camera:worldCoords](http://hump.readthedocs.io/en/latest/camera.html#camera:worldCoords). This takes in +a position in camera coordinates and translates it to world coordinates. An example of this is taking the position of the +mouse and seeing where it is in the world. + +```lua +mx, my = camera:toWorldCoords(love.mouse.getPosition()) +``` + +Arguments: + +* `x` `(number)` - The x position in camera coordinates +* `y` `(number)` - The y position in camera coordinates + +Returns: + +* `x` `(number)` - The x position in world coordinates +* `y` `(number)` - The y position in world coordinates + +--- + +#### `:toCameraCoords(x, y)` + +The same as [hump.camera:cameraCoords](http://hump.readthedocs.io/en/latest/camera.html#camera:cameraCoords). This takes in +a position in world coordinates and translates it to camera coordinates. An example of this is taking the position of the +player and + +```lua +player_x, player_y = camera:toCameraCoords(player.x, player.y) +love.graphics.line(player_x, player_y, love.mouse.getPosition()) +``` + +Arguments: + +* `x` `(number)` - The x position in world coordinates +* `y` `(number)` - The y position in world coordinates + +Returns: + +* `x` `(number)` - The x position in camera coordinates +* `y` `(number)` - The y position in camera coordinates + +--- + +#### `:getMousePosition()` + +Gets the position of the mouse in world coordinates. This position can also be accessed directly through `.mx, .my`. + +```lua +mx, my = camera:getMousePosition() +mx, my = camera.mx, camera.my +``` + +Returns: + +* `x` `(number)` - The x position of the mouse in world coordinates +* `y` `(number)` - The y position of the mouse in world coordinates + +--- + +#### `:shake(intensity, duration, frequency, axes)` + +Shakes the screen with intensity for a certain duration. + +```lua +camera:shake(8, 1, 60, 'X') +``` + +Arguments: + +* `intensity` `(number)` - The intensity of the shake in pixels. This will be decreased along the duration of the shake. +* `duration=1` `(number)` - The duration of the shake in seconds. Defaults to `1` +* `frequency=60` `(number)` - The frequency of the shake. Higher = jerkier, lower = smoother. Defaults to `60` +* `axes='XY'` `(string)` - The axes of the shake. Can be `'X'` for horizontal, `'Y'` for vertical or `'XY'` for both. Defaults to `'XY'` + +--- + +#### `:flash(duration, color)` + +Fills the screen up with a color for a certain duration. + +```lua +camera:flash(0.05, {0, 0, 0, 1}) +``` + +Arguments: + +* `duration` `(number)` - The duration of the flash in seconds +* `color={0, 0, 0, 1}` `(table[number])` - The color of the flash. Defaults to `{0, 0, 0, 1}` + +--- + +#### `:fade(duration, color, action)` + +Slowly fills up the screen with a color along the duration. + +```lua +camera:fade(1, {0, 0, 0, 1}, function() print(1) end) +``` + +Arguments: + +* `duration` `(number)` - The duration of the fade in seconds +* `color` `(table[number])` - The target color of the fade +* `action` `function` - An optional action that is run when the fade ends + +--- + +#### `:follow(x, y)` + +Follow the target according to the follow style and lerp, lead values. + +```lua +camera:follow(player.x, player.y) +``` + +Arguments: + +* `x` `(number)` - The x position of the target in world coordinates +* `y` `(number)` - The y position of the target in world coordinates + +--- + +#### `:setFollowStyle(follow_style)` + +Sets the follow style to be used by `camera:follow`. Possible values are `'LOCKON'`, `'PLATFORMER'`, `'TOPDOWN'`, `'TOPDOWN_TIGHT'`, `'SCREEN_BY_SCREEN'` and `'NO_DEADZONE'`. This can also be changed directly through `.follow_style`. + +```lua +camera:setFollowStyle('LOCKON') +camera.follow_style = 'LOCKON' +``` + +Arguments: + +* `follow_style` `(string)` - The follow style to be used + +--- + +#### `:setDeadzone(x, y, w, h)` + +Sets the deadzone directly. The follow style must be set to `nil` for this to work. + +```lua +camera:setDeadzone(0, 0, w, h) +``` + +Arguments: + +* `x` `(number)` - The top-left x position of the deadzone in camera coordinates +* `y` `(number)` - The top-left y position of the deadzone in camera coordinates +* `w` `(number)` - The width of the deadzone +* `h` `(number)` - The height of the deadzone + +--- + +#### `.draw_deadzone` + +Draws the deadzone if set to true. `camera:draw()` must be called outside the `camera:attach/detach` block for it to work. + +```lua +camera.draw_deadzone = true +``` + +--- + +#### `:setFollowLerp(x, y)` + +Sets the lerp value. This can be accessed directly through `.follow_lerp_x` and `.follow_lerp_y`. + +```lua +camera:setFollowLerp(0.2) +camera.follow_lerp_x = 0.2 +camera.follow_lerp_y = 0.2 +``` + +Arguments: + +* `x` `(number)` - The x lerp value +* `y=x` `(number)` - The y lerp value. Defaults to the `x` value + +--- + +#### `:setFollowLead(x, y)` + +Sets the lead value. This can be accessed directly through `.follow_lead_x` and `.follow_lead_y`. + +```lua +camera:setFollowLead(10) +camera.follow_lead_x = 10 +camera.follow_lead_y = 10 +``` + +Arguments: + +* `x` `(number)` - The x lead value +* `y=x` `(number)` The y lead value. Defaults to the `x` value + +--- + +#### `:setBounds(x, y, w, h)` + +Sets the boundaries of the camera in world coordinates. The camera won't be able to move past those points. + +```lua +camera:setBounds(0, 0, 800, 600) +``` + +Arguments: + +* `x` `(number)` - The top-left x position of the boundary +* `y` `(number)` - The top-left y position of the boundary +* `w` `(number)` - The width of the rectangle that defines the boundary +* `h` `(number)` - The height of the rectangle that defines the boundary + +--- + +
+ +# LICENSE + +You can do whatever you want with this. See the license at the top of the main file. diff --git a/lib/STALKER-X/init.lua b/lib/STALKER-X/init.lua new file mode 100644 index 0000000..e5661c0 --- /dev/null +++ b/lib/STALKER-X/init.lua @@ -0,0 +1,369 @@ +--[[ +MIT License + +Copyright (c) 2017 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 function lerp(a, b, x) return a + (b - a)*x end +local function csnap(v, x) return math.ceil(v/x)*x - x/2 end + +-- Shake according to https://jonny.morrill.me/en/blog/gamedev-how-to-implement-a-camera-shake-effect/ +local function newShake(amplitude, duration, frequency) + local self = { + amplitude = amplitude or 0, + duration = duration or 0, + frequency = frequency or 60, + samples = {}, + start_time = love.timer.getTime()*1000, + t = 0, + shaking = true, + } + + local sample_count = (self.duration/1000)*self.frequency + for i = 1, sample_count do self.samples[i] = 2*love.math.random()-1 end + + return self +end + +local function updateShake(self, dt) + self.t = love.timer.getTime()*1000 - self.start_time + if self.t > self.duration then self.shaking = false end +end + +local function shakeNoise(self, s) + if s >= #self.samples then return 0 end + return self.samples[s] or 0 +end + +local function shakeDecay(self, t) + if t > self.duration then return 0 end + return (self.duration - t)/self.duration +end + +local function getShakeAmplitude(self, t) + if not t then + if not self.shaking then return 0 end + t = self.t + end + + local s = (t/1000)*self.frequency + local s0 = math.floor(s) + local s1 = s0 + 1 + local k = shakeDecay(self, t) + return self.amplitude*(shakeNoise(self, s0) + (s - s0)*(shakeNoise(self, s1) - shakeNoise(self, s0)))*k +end + +-- Camera +local Camera = {} +Camera.__index = Camera + +local function new(x, y, w, h, scale, rotation) + return setmetatable({ + x = x or (w or love.graphics.getWidth())/2, y = y or (h or love.graphics.getHeight())/2, + mx = x or (w or love.graphics.getWidth())/2, my = y or (h or love.graphics.getHeight())/2, + screen_x = x or (w or love.graphics.getWidth())/2, screen_y = y or (h or love.graphics.getHeight())/2, + w = w or love.graphics.getWidth(), h = h or love.graphics.getHeight(), + scale = scale or 1, + rotation = rotation or 0, + horizontal_shakes = {}, vertical_shakes = {}, + target_x = nil, target_y = nil, + scroll_x = 0, scroll_y = 0, + last_target_x = nil, last_target_y = nil, + follow_lerp_x = 1, follow_lerp_y = 1, + follow_lead_x = 0, follow_lead_y = 0, + deadzone = nil, bound = nil, + draw_deadzone = false, + flash_duration = 1, flash_timer = 0, flash_color = {0, 0, 0, 1}, + last_horizontal_shake_amount = 0, last_vertical_shake_amount = 0, + fade_duration = 1, fade_timer = 0, fade_color = {0, 0, 0, 0}, + }, Camera) +end + +function Camera:attach() + love.graphics.push() + love.graphics.translate(self.w/2, self.h/2) + love.graphics.scale(self.scale) + love.graphics.rotate(self.rotation) + love.graphics.translate(-self.x, -self.y) +end + +function Camera:detach() + love.graphics.pop() +end + +function Camera:move(dx, dy) + self.x, self.y = self.x + dx, self.y + dy +end + +function Camera:toWorldCoords(x, y) + local c, s = math.cos(self.rotation), math.sin(self.rotation) + x, y = (x - self.w/2)/self.scale, (y - self.h/2)/self.scale + x, y = c*x - s*y, s*x + c*y + return x + self.x, y + self.y +end + +function Camera:toCameraCoords(x, y) + local c, s = math.cos(self.rotation), math.sin(self.rotation) + x, y = x - self.x, y - self.y + x, y = c*x - s*y, s*x + c*y + return x*self.scale + self.w/2, y*self.scale + self.h/2 +end + +function Camera:getMousePosition() + return self:toWorldCoords(love.mouse.getPosition()) +end + +function Camera:shake(intensity, duration, frequency, axes) + if not axes then axes = 'XY' end + axes = string.upper(axes) + + if string.find(axes, 'X') then table.insert(self.horizontal_shakes, newShake(intensity, duration*1000, frequency)) end + if string.find(axes, 'Y') then table.insert(self.vertical_shakes, newShake(intensity, duration*1000, frequency)) end +end + +function Camera:update(dt) + self.mx, self.my = self:toWorldCoords(love.mouse.getPosition()) + + -- Flash -- + if self.flashing then + self.flash_timer = self.flash_timer + dt + if self.flash_timer > self.flash_duration then + self.flash_timer = 0 + self.flashing = false + end + end + + -- Fade -- + if self.fading then + self.fade_timer = self.fade_timer + dt + self.fade_color = { + lerp(self.base_fade_color[1], self.target_fade_color[1], self.fade_timer/self.fade_duration), + lerp(self.base_fade_color[2], self.target_fade_color[2], self.fade_timer/self.fade_duration), + lerp(self.base_fade_color[3], self.target_fade_color[3], self.fade_timer/self.fade_duration), + lerp(self.base_fade_color[4], self.target_fade_color[4], self.fade_timer/self.fade_duration), + } + if self.fade_timer > self.fade_duration then + self.fade_timer = 0 + self.fading = false + if self.fade_action then self.fade_action() end + end + end + + -- Shake -- + local horizontal_shake_amount, vertical_shake_amount = 0, 0 + for i = #self.horizontal_shakes, 1, -1 do + updateShake(self.horizontal_shakes[i], dt) + horizontal_shake_amount = horizontal_shake_amount + getShakeAmplitude(self.horizontal_shakes[i]) + if not self.horizontal_shakes[i].shaking then table.remove(self.horizontal_shakes, i) end + end + for i = #self.vertical_shakes, 1, -1 do + updateShake(self.vertical_shakes[i], dt) + vertical_shake_amount = vertical_shake_amount + getShakeAmplitude(self.vertical_shakes[i]) + if not self.vertical_shakes[i].shaking then table.remove(self.vertical_shakes, i) end + end + self.x, self.y = self.x - self.last_horizontal_shake_amount, self.y - self.last_vertical_shake_amount + self:move(horizontal_shake_amount, vertical_shake_amount) + self.last_horizontal_shake_amount, self.last_vertical_shake_amount = horizontal_shake_amount, vertical_shake_amount + + -- Follow -- + if not self.target_x and not self.target_y then return end + + -- Set follow style deadzones + if self.follow_style == 'LOCKON' then + local w, h = self.w/16, self.w/16 + self:setDeadzone((self.w - w)/2, (self.h - h)/2, w, h) + + elseif self.follow_style == 'PLATFORMER' then + local w, h = self.w/8, self.h/3 + self:setDeadzone((self.w - w)/2, (self.h - h)/2 - h*0.25, w, h) + + elseif self.follow_style == 'TOPDOWN' then + local s = math.max(self.w, self.h)/4 + self:setDeadzone((self.w - s)/2, (self.h - s)/2, s, s) + + elseif self.follow_style == 'TOPDOWN_TIGHT' then + local s = math.max(self.w, self.h)/8 + self:setDeadzone((self.w - s)/2, (self.h - s)/2, s, s) + + elseif self.follow_style == 'SCREEN_BY_SCREEN' then + self:setDeadzone(0, 0, 0, 0) + + elseif self.follow_style == 'NO_DEADZONE' then + self.deadzone = nil + end + + -- No deadzone means we just track the target with no lerp + if not self.deadzone then + self.x, self.y = self.target_x, self.target_y + if self.bound then + self.x = math.min(math.max(self.x, self.bounds_min_x + self.w/2), self.bounds_max_x - self.w/2) + self.y = math.min(math.max(self.y, self.bounds_min_y + self.h/2), self.bounds_max_y - self.h/2) + end + return + end + + -- Convert appropriate variables to camera coordinates since the deadzone is applied in terms of the camera and not the world + local dx1, dy1, dx2, dy2 = self.deadzone_x, self.deadzone_y, self.deadzone_x + self.deadzone_w, self.deadzone_y + self.deadzone_h + local scroll_x, scroll_y = 0, 0 + local target_x, target_y = self:toCameraCoords(self.target_x, self.target_y) + local x, y = self:toCameraCoords(self.x, self.y) + + -- Screen by screen follow mode needs to be handled a bit differently + if self.follow_style == 'SCREEN_BY_SCREEN' then + -- Don't change self.screen_x/y if already at the boundaries + if self.bound then + if self.x > self.bounds_min_x + self.w/2 and target_x < 0 then self.screen_x = csnap(self.screen_x - self.w/self.scale, self.w/self.scale) end + if self.x < self.bounds_max_x - self.w/2 and target_x >= self.w then self.screen_x = csnap(self.screen_x + self.w/self.scale, self.w/self.scale) end + if self.y > self.bounds_min_y + self.h/2 and target_y < 0 then self.screen_y = csnap(self.screen_y - self.h/self.scale, self.h/self.scale) end + if self.y < self.bounds_max_y - self.h/2 and target_y >= self.h then self.screen_y = csnap(self.screen_y + self.h/self.scale, self.h/self.scale) end + -- Move to the next screen if the target is outside the screen boundaries + else + if target_x < 0 then self.screen_x = csnap(self.screen_x - self.w/self.scale, self.w/self.scale) end + if target_x >= self.w then self.screen_x = csnap(self.screen_x + self.w/self.scale, self.w/self.scale) end + if target_y < 0 then self.screen_y = csnap(self.screen_y - self.h/self.scale, self.h/self.scale) end + if target_y >= self.h then self.screen_y = csnap(self.screen_y + self.h/self.scale, self.h/self.scale) end + end + self.x = lerp(self.x, self.screen_x, self.follow_lerp_x) + self.y = lerp(self.y, self.screen_y, self.follow_lerp_y) + + -- Apply bounds + if self.bound then + self.x = math.min(math.max(self.x, self.bounds_min_x + self.w/2), self.bounds_max_x - self.w/2) + self.y = math.min(math.max(self.y, self.bounds_min_y + self.h/2), self.bounds_max_y - self.h/2) + end + + -- All other follow modes + else + -- Figure out how much the camera needs to scroll + if target_x < x + (dx1 + dx2 - x) then + local d = target_x - dx1 + if d < 0 then scroll_x = d end + end + if target_x > x - (dx1 + dx2 - x) then + local d = target_x - dx2 + if d > 0 then scroll_x = d end + end + if target_y < y + (dy1 + dy2 - y) then + local d = target_y - dy1 + if d < 0 then scroll_y = d end + end + if target_y > y - (dy1 + dy2 - y) then + local d = target_y - dy2 + if d > 0 then scroll_y = d end + end + + -- Apply lead + if not self.last_target_x and not self.last_target_y then self.last_target_x, self.last_target_y = self.target_x, self.target_y end + scroll_x = scroll_x + (self.target_x - self.last_target_x)*self.follow_lead_x + scroll_y = scroll_y + (self.target_y - self.last_target_y)*self.follow_lead_y + self.last_target_x, self.last_target_y = self.target_x, self.target_y + + -- Scroll towards target with lerp + self.x = lerp(self.x, self.x + scroll_x, self.follow_lerp_x) + self.y = lerp(self.y, self.y + scroll_y, self.follow_lerp_y) + + -- Apply bounds + if self.bound then + self.x = math.min(math.max(self.x, self.bounds_min_x + self.w/2), self.bounds_max_x - self.w/2) + self.y = math.min(math.max(self.y, self.bounds_min_y + self.h/2), self.bounds_max_y - self.h/2) + end + end +end + +function Camera:draw() + if self.draw_deadzone and self.deadzone then + local n = love.graphics.getLineWidth() + love.graphics.setLineWidth(2) + love.graphics.line(self.deadzone_x - 1, self.deadzone_y, self.deadzone_x + 6, self.deadzone_y) + love.graphics.line(self.deadzone_x, self.deadzone_y, self.deadzone_x, self.deadzone_y + 6) + love.graphics.line(self.deadzone_x - 1, self.deadzone_y + self.deadzone_h, self.deadzone_x + 6, self.deadzone_y + self.deadzone_h) + love.graphics.line(self.deadzone_x, self.deadzone_y + self.deadzone_h, self.deadzone_x, self.deadzone_y + self.deadzone_h - 6) + love.graphics.line(self.deadzone_x + self.deadzone_w + 1, self.deadzone_y + self.deadzone_h, self.deadzone_x + self.deadzone_w - 6, self.deadzone_y + self.deadzone_h) + love.graphics.line(self.deadzone_x + self.deadzone_w, self.deadzone_y + self.deadzone_h, self.deadzone_x + self.deadzone_w, self.deadzone_y + self.deadzone_h - 6) + love.graphics.line(self.deadzone_x + self.deadzone_w + 1, self.deadzone_y, self.deadzone_x + self.deadzone_w - 6, self.deadzone_y) + love.graphics.line(self.deadzone_x + self.deadzone_w, self.deadzone_y, self.deadzone_x + self.deadzone_w, self.deadzone_y + 6) + love.graphics.setLineWidth(n) + end + + if self.flashing then + local r, g, b, a = love.graphics.getColor() + love.graphics.setColor(self.flash_color) + love.graphics.rectangle('fill', 0, 0, self.w, self.h) + love.graphics.setColor(r, g, b, a) + end + + local r, g, b, a = love.graphics.getColor() + love.graphics.setColor(self.fade_color) + love.graphics.rectangle('fill', 0, 0, self.w, self.h) + love.graphics.setColor(r, g, b, a) +end + +function Camera:follow(x, y) + self.target_x, self.target_y = x, y +end + +function Camera:setDeadzone(x, y, w, h) + self.deadzone = true + self.deadzone_x = x + self.deadzone_y = y + self.deadzone_w = w + self.deadzone_h = h +end + +function Camera:setBounds(x, y, w, h) + self.bound = true + self.bounds_min_x = x + self.bounds_min_y = y + self.bounds_max_x = x + w + self.bounds_max_y = y + h +end + +function Camera:setFollowStyle(follow_style) + self.follow_style = follow_style +end + +function Camera:setFollowLerp(x, y) + self.follow_lerp_x = x + self.follow_lerp_y = y or x +end + +function Camera:setFollowLead(x, y) + self.follow_lead_x = x + self.follow_lead_y = y or x +end + +function Camera:flash(duration, color) + self.flash_duration = duration + self.flash_color = color or self.flash_color + self.flash_timer = 0 + self.flashing = true +end + +function Camera:fade(duration, color, action) + self.fade_duration = duration + self.base_fade_color = self.fade_color + self.target_fade_color = color + self.fade_timer = 0 + self.fade_action = action + self.fading = true +end + +return setmetatable({new = new}, {__call = function(_, ...) return new(...) end}) diff --git a/lib/bin-license.txt b/lib/bin-license.txt new file mode 100644 index 0000000..b061ed4 --- /dev/null +++ b/lib/bin-license.txt @@ -0,0 +1,1183 @@ +Licensing information +===================== + + KunKune! + Website: https://git.feneas.org/detruota/KunKune! + Website: https://github.com/jadedctrl/KunKune! + Website: https://xwx.moe + License: Code, GPLv3 + Assets, varying (CC0 or CC-BY-SA 2.0; see website for details) + + +This distribution contains code from the following projects (full license text below): + + - LOVE + Website: https://love2d.org/ + License: zlib + Copyright (c) 2006-2019 LOVE Development Team + + - ENet + Website: http://enet.bespin.org/index.html + License: MIT/Expat + Copyright (c) 2002-2016 Lee Salzman + + - GLAD + Website: http://glad.dav1d.de/ + License: MIT/Expat + Copyright (c) 2013 David Herberth, modified by Alex Szpakowski + + - glslang + Website: https://github.com/KhronosGroup/glslang + License: 3-Clause BSD + Copyright (C) 2002-2005 3Dlabs Inc. Ltd. + Copyright (C) 2013-2016 LunarG, Inc. + + - Kepler Project's lua-compat-5.3 + Website: https://github.com/keplerproject/lua-compat-5.3 + License: MIT/Expat + Copyright (c) 2015 Kepler Project. + + - lua-enet + Website: http://leafo.net/lua-enet/ + License: MIT/Expat + Copyright (C) 2011 by Leaf Corcoran + + - LuaJIT + Website: http://luajit.org/ + License: MIT/Expat + LuaJIT is Copyright (c) 2005-2016 Mike Pall + + - Lua's UTF-8 module + Website: https://www.lua.org/ + License: MIT/Expat + Copyright (C) 1994-2015 Lua.org, PUC-Rio, 2015 LOVE Development Team. + + - LuaSocket + Website: http://w3.impa.br/~diego/software/luasocket/home.html + License: MIT/Expat + Copyright (C) 2004-2013 Diego Nehab + + - LZ4 + Website: https://lz4.github.io/lz4/ + License: 2-Clause BSD + Copyright (C) 2011-2015, Yann Collet. + You can contact the author at : + - LZ4 source repository : https://github.com/Cyan4973/lz4 + - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c + + - TinyEXR + Website: https://github.com/syoyo/tinyexr + License: 3-Clause BSD + Copyright (c) 2014 - 2016, Syoyo Fujita + + - UTF8-CPP + Website: https://github.com/nemtrif/utfcpp + License: Unknown, MIT/Expat-like (listed as UTF8-CPP) + Copyright 2006 Nemanja Trifunovic + + - xxHash + Website: https://cyan4973.github.io/xxHash/ + License: 2-Clause BSD + Copyright (C) 2012-2016, Yann Collet. + You can contact the author at : + - xxHash source repository : https://github.com/Cyan4973/xxHash + + - dr_flac + Website: https://github.com/mackron/dr_libs + Source download: https://github.com/mackron/dr_libs/blob/41bc0e8/dr_flac.h + License: MIT/Expat + Copyright 2018 David Reid + + - libmpg123 + Website: http://www.mpg123.de/ + Source download: http://sourceforge.net/projects/mpg123/files/latest/download + License: LGPL 2.1 + Copyright (c) 1995-2013 by Michael Hipp and others, free software under the terms of the LGPL v2.1 + Detailed information from the debian project: + Copyright 1995-2016 by the mpg123 project + Copyright 2009-2011 by Malcolm Boczek + Copyright 2008 Christian Weisgerber + Copyright 2006-2007 by Zuxy Meng + Copyright 2000-2002 David Olofson + Copyright 1998 Fabrice Bellard + Copyright 1997 Mikko Tommila + + - OpenAL Soft + Website: http://kcat.strangesoft.net/openal.html + Source download: http://kcat.strangesoft.net/openal.html#download + License: Mixed, licensing information obtained from the debian project + - Alc/backends/opensl.c + License: Apache 2.0 + Copyright 2011 The Android Open Source Project + - examples/alhrtf.c examples/allatency.c examples/alloopback.c examples/alreverb.c examples/alstream.c examples/altonegen.c examples/common/alhelpers.c examples/common/sdl_sound.c utils/openal-info.c + License: MIT/Expat + Copyright © 2010, 2015 Chris Robinson + - examples/alffplay.c + License: unclear, presumed LGPL 2.1 or higher + Copyright © 2003 Fabrice Bellard + Copyright © Martin Bohme + - Alc/bs2b.c OpenAL32/Include/bs2b.h + License: MIT/Expat + Copyright 2005 by Boris Mikhaylov + - cmake/FindALSA.cmake cmake/FindFFmpeg.cmake cmake/FindJACK.cmake cmake/FindSDL2.cmake + License: 3-Clause BSD + Copyright © 2006 Matthias Kretz + Copyright © 2008 Alexander Neundorf + Copyright © 2003-2011 Kitware, Inc. + Copyright © 2009-2011 Philip Lowman + Copyright © 2011 Michael Jansen + Copyright © 2012 Benjamin Eikel + - utils/makehrtf.c (not included in distribution) + License: GPL 2 or higher (2 listed below) + Copyright 2011-2014 Christopher Fitzgerald + - Everything else: + License: LGPL 2.0 or higher (2.1 listed below) + Copyright © 1999-2014 the OpenAL team + Copyright © 2008-2015 Christopher Fitzgerald + Copyright © 2009-2015 Chris Robinson + Copyright © 2013 Anis A. Hireche + Copyright © 2013 Nasca Octavian Paul + Copyright © 2013 Mike Gorchak + Copyright © 2014 Timothy Arceri + +License text +============ + +zlib license + 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 acknowledgment 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. + +MIT/Expat + 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. + +3-Clause BSD + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + Neither the name of 3Dlabs Inc. Ltd. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES + LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +2-Clause BSD + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, + DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +UTF8-CPP + Permission is hereby granted, free of charge, to any person or organization + obtaining a copy of the software and accompanying documentation covered by + this license (the "Software") to use, reproduce, display, distribute, + execute, and transmit the Software, and to prepare derivative works of the + Software, and to permit third-parties to whom the Software is furnished to + do so, all subject to the following: + + The copyright notices in the Software and this entire statement, including + the above license grant, this restriction and the following disclaimer, + must be included in all copies of the Software, in whole or in part, and + all derivative works of the Software, unless such copies or derivative + works are solely in the form of machine-executable object code generated by + a source language processor. + + 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT + SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +LGPL 2.1 + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + [This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your + freedom to share and change it. By contrast, the GNU General Public + Licenses are intended to guarantee your freedom to share and change + free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some + specially designated software packages--typically libraries--of the + Free Software Foundation and other authors who decide to use it. You + can use it too, but we suggest you first think carefully about whether + this license or the ordinary General Public License is the better + strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, + 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 this service if you wish) that you receive source code or can get + it if you want it that you can change the software and use pieces of + it in new free programs and that you are informed that you can do + these things. + + To protect your rights, we need to make restrictions that forbid + distributors to deny you these rights or to ask you to surrender these + rights. These restrictions translate to certain responsibilities for + you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis + or for a fee, you must give the recipients all the rights that we gave + you. You must make sure that they, too, receive or can get the source + code. If you link other code with the library, you must provide + complete object files to the recipients, so that they can relink them + with the library after making changes to the library and recompiling + it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the + library, and (2) we offer you this license, which gives you legal + permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that + there is no warranty for the free library. Also, if the library is + modified by someone else and passed on, the recipients should know + that what they have is not the original version, so that the original + author's reputation will not be affected by problems that might be + introduced by others. + + Finally, software patents pose a constant threat to the existence of + any free program. We wish to make sure that a company cannot + effectively restrict the users of a free program by obtaining a + restrictive license from a patent holder. Therefore, we insist that + any patent license obtained for a version of the library must be + consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the + ordinary GNU General Public License. This license, the GNU Lesser + General Public License, applies to certain designated libraries, and + is quite different from the ordinary General Public License. We use + this license for certain libraries in order to permit linking those + libraries into non-free programs. + + When a program is linked with a library, whether statically or using + a shared library, the combination of the two is legally speaking a + combined work, a derivative of the original library. The ordinary + General Public License therefore permits such linking only if the + entire combination fits its criteria of freedom. The Lesser General + Public License permits more lax criteria for linking other code with + the library. + + We call this license the "Lesser" General Public License because it + does Less to protect the user's freedom than the ordinary General + Public License. It also provides other free software developers Less + of an advantage over competing non-free programs. These disadvantages + are the reason we use the ordinary General Public License for many + libraries. However, the Lesser license provides advantages in certain + special circumstances. + + For example, on rare occasions, there may be a special need to + encourage the widest possible use of a certain library, so that it becomes + a de-facto standard. To achieve this, non-free programs must be + allowed to use the library. A more frequent case is that a free + library does the same job as widely used non-free libraries. In this + case, there is little to gain by limiting the free library to free + software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free + programs enables a greater number of people to use a large body of + free software. For example, permission to use the GNU C Library in + non-free programs enables many more people to use the whole GNU + operating system, as well as its variant, the GNU/Linux operating + system. + + Although the Lesser General Public License is Less protective of the + users' freedom, it does ensure that the user of a program that is + linked with the Library has the freedom and the wherewithal to run + that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and + modification follow. Pay close attention to the difference between a + "work based on the library" and a "work that uses the library". The + former contains code derived from the library, whereas the latter must + be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other + program which contains a notice placed by the copyright holder or + other authorized party saying it may be distributed under the terms of + this Lesser General Public License (also called "this License"). + Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data + prepared so as to be conveniently linked with application programs + (which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work + which has been distributed under these terms. A "work based on the + Library" means either the Library or any derivative work under + copyright law: that is to say, a work containing the Library or a + portion of it, either verbatim or with modifications and/or translated + straightforwardly into another language. (Hereinafter, translation is + included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for + making modifications to it. For a library, complete source code means + all the source code for all modules it contains, plus any associated + interface definition files, plus the scripts used to control compilation + and installation of the library. + + Activities other than copying, distribution and modification are not + covered by this License they are outside its scope. The act of + running a program using the Library is not restricted, and output from + such a program is covered only if its contents constitute a work based + on the Library (independent of the use of the Library in a tool for + writing it). Whether that is true depends on what the Library does + and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's + complete source code as you receive it, in any medium, provided that + you conspicuously and appropriately publish on each copy an + appropriate copyright notice and disclaimer of warranty keep intact + all the notices that refer to this License and to the absence of any + warranty and distribute a copy of this License along with the + Library. + + You may charge a fee for the physical act of transferring a copy, + and you may at your option offer warranty protection in exchange for a + fee. + + 2. You may modify your copy or copies of the Library or any portion + of it, thus forming a work based on the Library, and copy and + distribute such modifications or work under the terms of Section 1 + above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + + These requirements apply to the modified work as a whole. If + identifiable sections of that work are not derived from the Library, + and can be reasonably considered independent and separate works in + themselves, then this License, and its terms, do not apply to those + sections when you distribute them as separate works. But when you + distribute the same sections as part of a whole which is a work based + on the Library, the distribution of the whole must be on the terms of + this License, whose permissions for other licensees extend to the + entire whole, and thus to each and every part regardless of who wrote + it. + + Thus, it is not the intent of this section to claim rights or contest + your rights to work written entirely by you rather, the intent is to + exercise the right to control the distribution of derivative or + collective works based on the Library. + + In addition, mere aggregation of another work not based on the Library + with the Library (or with a work based on the Library) on a volume of + a storage or distribution medium does not bring the other work under + the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public + License instead of this License to a given copy of the Library. To do + this, you must alter all the notices that refer to this License, so + that they refer to the ordinary GNU General Public License, version 2, + instead of to this License. (If a newer version than version 2 of the + ordinary GNU General Public License has appeared, then you can specify + that version instead if you wish.) Do not make any other change in + these notices. + + Once this change is made in a given copy, it is irreversible for + that copy, so the ordinary GNU General Public License applies to all + subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of + the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or + derivative of it, under Section 2) in object code or executable form + under the terms of Sections 1 and 2 above provided that you accompany + it with the complete corresponding machine-readable source code, which + must be distributed under the terms of Sections 1 and 2 above on a + medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy + from a designated place, then offering equivalent access to copy the + source code from the same place satisfies the requirement to + distribute the source code, even though third parties are not + compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the + Library, but is designed to work with the Library by being compiled or + linked with it, is called a "work that uses the Library". Such a + work, in isolation, is not a derivative work of the Library, and + therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library + creates an executable that is a derivative of the Library (because it + contains portions of the Library), rather than a "work that uses the + library". The executable is therefore covered by this License. + Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file + that is part of the Library, the object code for the work may be a + derivative work of the Library even though the source code is not. + Whether this is true is especially significant if the work can be + linked without the Library, or if the work is itself a library. The + threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data + structure layouts and accessors, and small macros and small inline + functions (ten lines or less in length), then the use of the object + file is unrestricted, regardless of whether it is legally a derivative + work. (Executables containing this object code plus portions of the + Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may + distribute the object code for the work under the terms of Section 6. + Any executables containing that work also fall under Section 6, + whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or + link a "work that uses the Library" with the Library to produce a + work containing portions of the Library, and distribute that work + under terms of your choice, provided that the terms permit + modification of the work for the customer's own use and reverse + engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the + Library is used in it and that the Library and its use are covered by + this License. You must supply a copy of this License. If the work + during execution displays copyright notices, you must include the + copyright notice for the Library among them, as well as a reference + directing the user to the copy of this License. Also, you must do one + of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above) and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the + Library" must include any data and utility programs needed for + reproducing the executable from it. However, as a special exception, + the materials to be distributed need not include anything that is + normally distributed (in either source or binary form) with the major + components (compiler, kernel, and so on) of the operating system on + which the executable runs, unless that component itself accompanies + the executable. + + It may happen that this requirement contradicts the license + restrictions of other proprietary libraries that do not normally + accompany the operating system. Such a contradiction means you cannot + use both them and the Library together in an executable that you + distribute. + + 7. You may place library facilities that are a work based on the + Library side-by-side in a single library together with other library + facilities not covered by this License, and distribute such a combined + library, provided that the separate distribution of the work based on + the Library and of the other library facilities is otherwise + permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute + the Library except as expressly provided under this License. Any + attempt otherwise to copy, modify, sublicense, link with, or + distribute the Library is void, and will automatically terminate your + rights under this License. However, parties who have received copies, + or rights, from you under this License will not have their licenses + terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not + signed it. However, nothing else grants you permission to modify or + distribute the Library or its derivative works. These actions are + prohibited by law if you do not accept this License. Therefore, by + modifying or distributing the Library (or any work based on the + Library), you indicate your acceptance of this License to do so, and + all its terms and conditions for copying, distributing or modifying + the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the + Library), the recipient automatically receives a license from the + original licensor to copy, distribute, link with or modify the Library + subject to these terms and conditions. You may not impose any further + restrictions on the recipients' exercise of the rights granted herein. + You are not responsible for enforcing compliance by third parties with + this License. + + 11. If, as a consequence of a court judgment or allegation of patent + infringement or for any other reason (not limited to patent issues), + 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 + distribute so as to satisfy simultaneously your obligations under this + License and any other pertinent obligations, then as a consequence you + may not distribute the Library at all. For example, if a patent + license would not permit royalty-free redistribution of the Library by + all those who receive copies directly or indirectly through you, then + the only way you could satisfy both it and this License would be to + refrain entirely from distribution of the Library. + + If any portion of this section is held invalid or unenforceable under any + particular circumstance, the balance of the section is intended to apply, + and the section as a whole is intended to apply in other circumstances. + + It is not the purpose of this section to induce you to infringe any + patents or other property right claims or to contest validity of any + such claims this section has the sole purpose of protecting the + integrity of the free software distribution system which is + implemented by public license practices. Many people have made + generous contributions to the wide range of software distributed + through that system in reliance on consistent application of that + system it is up to the author/donor to decide if he or she is willing + to distribute software through any other system and a licensee cannot + impose that choice. + + This section is intended to make thoroughly clear what is believed to + be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in + certain countries either by patents or by copyrighted interfaces, the + original copyright holder who places the Library under this License may add + an explicit geographical distribution limitation excluding those countries, + so that distribution is permitted only in or among countries not thus + excluded. In such case, this License incorporates the limitation as if + written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new + versions of the Lesser 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 Library + specifies a version number of this License which applies to it and + "any later version", you have the option of following the terms and + conditions either of that version or of any later version published by + the Free Software Foundation. If the Library does not specify a + license version number, you may choose any version ever published by + the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free + programs whose distribution conditions are incompatible with these, + write to the author to ask for permission. For software which is + copyrighted by the Free Software Foundation, write to the Free + Software Foundation we sometimes make exceptions for this. Our + decision will be guided by the two goals of preserving the free status + of all derivatives of our free software and of promoting the sharing + and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO + WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. + EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR + OTHER PARTIES PROVIDE THE LIBRARY "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 + LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME + THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN + WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY + AND/OR REDISTRIBUTE THE LIBRARY 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 + LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF + SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest + possible use to the public, we recommend making it free software that + everyone can redistribute and change. You can do so by permitting + redistribution under these terms (or, alternatively, under the terms of the + ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is + safest to attach them to the start of each source file to most effectively + convey the exclusion of warranty and each file should have at least the + "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + Also add information on how to contact you by electronic and paper mail. + + You should also get your employer (if you work as a programmer) or your + school, if any, to sign a "copyright disclaimer" for the library, if + necessary. Here is a sample alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + + That's all there is to it! + +GPL 2 + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your + freedom to share and change it. By contrast, the GNU General Public + License is intended to guarantee your freedom to share and change free + software--to make sure the software is free for all its users. This + General Public License applies to most of the Free Software + Foundation's software and to any other program whose authors commit to + using it. (Some other Free Software Foundation software is covered by + the GNU Lesser General Public License instead.) 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 + this service 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 make restrictions that forbid + anyone to deny you these rights or to ask you to surrender the rights. + These restrictions translate to certain responsibilities for you if you + distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether + gratis or for a fee, you must give the recipients all the rights that + you have. 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. + + We protect your rights with two steps: (1) copyright the software, and + (2) offer you this license which gives you legal permission to copy, + distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain + that everyone understands that there is no warranty for this free + software. If the software is modified by someone else and passed on, we + want its recipients to know that what they have is not the original, so + that any problems introduced by others will not reflect on the original + authors' reputations. + + Finally, any free program is threatened constantly by software + patents. We wish to avoid the danger that redistributors of a free + program will individually obtain patent licenses, in effect making the + program proprietary. To prevent this, we have made it clear that any + patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and + modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains + a notice placed by the copyright holder saying it may be distributed + under the terms of this General Public License. The "Program", below, + refers to any such program or work, and a "work based on the Program" + means either the Program or any derivative work under copyright law: + that is to say, a work containing the Program or a portion of it, + either verbatim or with modifications and/or translated into another + language. (Hereinafter, translation is included without limitation in + the term "modification".) Each licensee is addressed as "you". + + Activities other than copying, distribution and modification are not + covered by this License they are outside its scope. The act of + running the Program is not restricted, and the output from the Program + is covered only if its contents constitute a work based on the + Program (independent of having been made by running the Program). + Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty keep intact all the + notices that refer to this License and to the absence of any warranty + and give any other recipients of the Program a copy of this License + along with the Program. + + You may charge a fee for the physical act of transferring a copy, and + you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion + of it, thus forming a work based on the Program, and copy and + distribute such modifications or work under the terms of Section 1 + above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + + These requirements apply to the modified work as a whole. If + identifiable sections of that work are not derived from the Program, + and can be reasonably considered independent and separate works in + themselves, then this License, and its terms, do not apply to those + sections when you distribute them as separate works. But when you + distribute the same sections as part of a whole which is a work based + on the Program, the distribution of the whole must be on the terms of + this License, whose permissions for other licensees extend to the + entire whole, and thus to each and every part regardless of who wrote it. + + Thus, it is not the intent of this section to claim rights or contest + your rights to work written entirely by you rather, the intent is to + exercise the right to control the distribution of derivative or + collective works based on the Program. + + In addition, mere aggregation of another work not based on the Program + with the Program (or with a work based on the Program) on a volume of + a storage or distribution medium does not bring the other work under + the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, + under Section 2) in object code or executable form under the terms of + Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + + The source code for a work means the preferred form of the work for + making modifications to it. For an executable work, complete source + code means all the source code for all modules it contains, plus any + associated interface definition files, plus the scripts used to + control compilation and installation of the executable. However, as a + special exception, the source code distributed need not include + anything that is normally distributed (in either source or binary + form) with the major components (compiler, kernel, and so on) of the + operating system on which the executable runs, unless that component + itself accompanies the executable. + + If distribution of executable or object code is made by offering + access to copy from a designated place, then offering equivalent + access to copy the source code from the same place counts as + distribution of the source code, even though third parties are not + compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program + except as expressly provided under this License. Any attempt + otherwise to copy, modify, sublicense or distribute the Program is + void, and will automatically terminate your rights under this License. + However, parties who have received copies, or rights, from you under + this License will not have their licenses terminated so long as such + parties remain in full compliance. + + 5. You are not required to accept this License, since you have not + signed it. However, nothing else grants you permission to modify or + distribute the Program or its derivative works. These actions are + prohibited by law if you do not accept this License. Therefore, by + modifying or distributing the Program (or any work based on the + Program), you indicate your acceptance of this License to do so, and + all its terms and conditions for copying, distributing or modifying + the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the + Program), the recipient automatically receives a license from the + original licensor to copy, distribute or modify the Program subject to + these terms and conditions. You may not impose any further + restrictions on the recipients' exercise of the rights granted herein. + You are not responsible for enforcing compliance by third parties to + this License. + + 7. If, as a consequence of a court judgment or allegation of patent + infringement or for any other reason (not limited to patent issues), + 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 + distribute so as to satisfy simultaneously your obligations under this + License and any other pertinent obligations, then as a consequence you + may not distribute the Program at all. For example, if a patent + license would not permit royalty-free redistribution of the Program by + all those who receive copies directly or indirectly through you, then + the only way you could satisfy both it and this License would be to + refrain entirely from distribution of the Program. + + If any portion of this section is held invalid or unenforceable under + any particular circumstance, the balance of the section is intended to + apply and the section as a whole is intended to apply in other + circumstances. + + It is not the purpose of this section to induce you to infringe any + patents or other property right claims or to contest validity of any + such claims this section has the sole purpose of protecting the + integrity of the free software distribution system, which is + implemented by public license practices. Many people have made + generous contributions to the wide range of software distributed + through that system in reliance on consistent application of that + system it is up to the author/donor to decide if he or she is willing + to distribute software through any other system and a licensee cannot + impose that choice. + + This section is intended to make thoroughly clear what is believed to + be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in + certain countries either by patents or by copyrighted interfaces, the + original copyright holder who places the Program under this License + may add an explicit geographical distribution limitation excluding + those countries, so that distribution is permitted only in or among + countries not thus excluded. In such case, this License incorporates + the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions + of the 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 a version number of this License which applies to it and "any + later version", you have the option of following the terms and conditions + either of that version or of any later version published by the Free + Software Foundation. If the Program does not specify a version number of + this License, you may choose any version ever published by the Free Software + Foundation. + + 10. If you wish to incorporate parts of the Program into other free + programs whose distribution conditions are different, write to the author + to ask for permission. For software which is copyrighted by the Free + Software Foundation, write to the Free Software Foundation we sometimes + make exceptions for this. Our decision will be guided by the two goals + of preserving the free status of all derivatives of our free software and + of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING + WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR + REDISTRIBUTE 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. + + 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 + convey the exclusion of warranty and each file should have at least + the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation either version 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. + + Also add information on how to contact you by electronic and paper mail. + + If the program is interactive, make it output a short notice like this + when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may + be called something other than `show w' and `show c' they could even be + mouse-clicks or menu items--whatever suits your program. + + You should also get your employer (if you work as a programmer) or your + school, if any, to sign a "copyright disclaimer" for the program, if + necessary. Here is a sample alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + + This 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. + +Apache 2.0 + Apache License + + Version 2.0, January 2004 + + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + You must give any other recipients of the Work or Derivative Works a copy of this License and + You must cause any modified files to carry prominent notices stating that You changed the files and + You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works and + If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works within the Source form or documentation, if provided along with the Derivative Works or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + APPENDIX: How to apply the Apache License to your work + + To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License") + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +GNU GPLv3 diff --git a/lib/middleclass/.travis.yml b/lib/middleclass/.travis.yml new file mode 100644 index 0000000..53998d6 --- /dev/null +++ b/lib/middleclass/.travis.yml @@ -0,0 +1,36 @@ +language: python +sudo: false + +env: + - LUA="lua=5.1" + - LUA="lua=5.2" + - LUA="lua=5.3" + - LUA="luajit=2.0" + - LUA="luajit=2.1" + +before_install: + - pip install hererocks + - hererocks lua_install -r^ --$LUA + - export PATH=$PATH:$PWD/lua_install/bin # Add directory with all installed binaries to PATH + +install: + - luarocks install luacheck + - luarocks install busted + - luarocks install luacov + - luarocks install luacov-coveralls + +script: + - luacheck --no-unused-args --std max+busted *.lua spec + - busted --verbose --coverage + +after_success: + - luacov-coveralls --exclude $TRAVIS_BUILD_DIR/lua_install + +branches: + except: + - gh-pages + +notifications: + email: + on_success: change + on_failure: always diff --git a/lib/middleclass/CHANGELOG.md b/lib/middleclass/CHANGELOG.md new file mode 100644 index 0000000..5f8b93a --- /dev/null +++ b/lib/middleclass/CHANGELOG.md @@ -0,0 +1,55 @@ +middleclass changelog +==================== + +# Version 4.1.1 + +* Fixed a bug in which `static` values which evaluated to `false` were not available + in subclasses (#51, thanks @qaisjp for the patch!) +* `isInstanceOf` does not throw an error any more when its first parameter is a + primitive (#55) (This effectively undoes the change introduced in 4.1.0) + + +# Version 4.1.0 + +* Simplifies implementation of `isInstanceOf` and `isSubclassOf`. They will now raise an error if their first + parameter (the `self`) isn't an instance or a class respectively. + +# Version 4.0.0 + +* Unified the method and metamethod lookup into a single algorithm +* Added the capacity of setting up the `__index` metamethod in classes +* Removed global `Object` (classes created with `class()` have no superclass now) +* Removed default method `Class:implements()` +* Renamed several internal functions + +# Version 3.2.0 + +* Changed the way metamethods were handled to fix certain bugs (un-stubbed metamethods could not be inherited) + +# Version 3.1.0 + +* Added Lua 5.3 metamethod support (`__band`, `__bor`, `__bxor`, `__shl`, `__bnot`) + +# Version 3.0.1 + +* Added `__len`, `__ipairs` and `__pairs` metamethods for Lua 5.2 + +# Version 3.0 + +* Anything that behaves reasonably like a class can be a class (no internal list of classes) +* The `class` global function is now just the return value of `require +'middleclass'`. It is a callable table, but works exactly as before. +* The global variable `Object` becomes `class.Object` +* The global function `instanceOf` becomes `class.Object.isInstanceOf`. Parameter order is reversed. +* The global function `subclassOf` becomes `class.Object.static.isSubclassOf`. Parameter order is reversed. +* The global function `implements` becomes `class.Object.static.implements`. Parameter order is reversed. +* Specs have been translated from telescope to busted + +# Version 2.0 + +* Static methods are now separated from instance methods +* class.superclass has now become class.super +* It's now possible to do class.subclasses +* middleclass is now a single file; init.lua has dissapeared +* license is changed from BSD to MIT. License included in source FTW + diff --git a/lib/middleclass/MIT-LICENSE.txt b/lib/middleclass/MIT-LICENSE.txt new file mode 100644 index 0000000..525287a --- /dev/null +++ b/lib/middleclass/MIT-LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2011 Enrique García Cota + +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. diff --git a/lib/middleclass/README.md b/lib/middleclass/README.md new file mode 100644 index 0000000..fc1153b --- /dev/null +++ b/lib/middleclass/README.md @@ -0,0 +1,80 @@ +middleclass +=========== + +[![Build Status](https://travis-ci.org/kikito/middleclass.png?branch=master)](https://travis-ci.org/kikito/middleclass) +[![Coverage Status](https://coveralls.io/repos/kikito/middleclass/badge.svg?branch=master&service=github)](https://coveralls.io/github/kikito/middleclass?branch=master) + +A simple OOP library for Lua. It has inheritance, metamethods (operators), class variables and weak mixin support. + +Quick Look +========== + +```lua +local class = require 'middleclass' + +local Fruit = class('Fruit') -- 'Fruit' is the class' name + +function Fruit:initialize(sweetness) + self.sweetness = sweetness +end + +Fruit.static.sweetness_threshold = 5 -- class variable (also admits methods) + +function Fruit:isSweet() + return self.sweetness > Fruit.sweetness_threshold +end + +local Lemon = class('Lemon', Fruit) -- subclassing + +function Lemon:initialize() + Fruit.initialize(self, 1) -- invoking the superclass' initializer +end + +local lemon = Lemon:new() + +print(lemon:isSweet()) -- false +``` + +Documentation +============= + +See the [github wiki page](https://github.com/kikito/middleclass/wiki) for examples & documentation. + +You can read the `CHANGELOG.md` file to see what has changed on each version of this library. + +If you need help updating to a new middleclass version, read `UPDATING.md`. + +Installation +============ + +Just copy the middleclass.lua file wherever you want it (for example on a lib/ folder). Then write this in any Lua file where you want to use it: + +```lua +local class = require 'middleclass' +``` + +Specs +===== + +This project uses [busted](http://olivinelabs.com/busted/) for its specs. If you want to run the specs, you will have to install it first. Then just execute the following: + +```bash +cd /folder/where/the/spec/folder/is +busted +``` + +Performance tests +================= + +Middleclass also comes with a small performance test suite. Just run the following command: + +```bash +lua performance/run.lua +``` + +License +======= + +Middleclass is distributed under the MIT license. + + diff --git a/lib/middleclass/UPDATING.md b/lib/middleclass/UPDATING.md new file mode 100644 index 0000000..83855c9 --- /dev/null +++ b/lib/middleclass/UPDATING.md @@ -0,0 +1,69 @@ +Updating from 3.x to 4.x +======================== + +In middleclass 4.0 there is no global `Object` class any more. Classes created with `class()` don't have a superclass any more. +If you need a global `Object` class, you must create it explicitly and then use it when creating new classes: + +```lua +local Object = class('Object') + +... + +local MyClass = class('MyClass', Object) +``` + +If you are using a library which depends on the internal implementation of middleclass they might not work with middleclass 4.0. You might need to update those other libraries. + +Middleclass 4.0 comes with support for `__index` metamethod support. If your library manipulated the classes' `__instanceDict` internal attribute, you might do the same thing now using `__index` instead. + +Also note that the class method `:implements` has been removed. + +Updating from 2.x to 3.x +======================== + +Middleclass used to expose several global variables on the main scope. It does not do that anymore. + +`class` is now returned by `require 'middleclass'`, and it is not set globally. So you can do this: + +```lua +local class = require 'middleclass' +local MyClass = class('MyClass') -- works as before +``` + +`Object` is not a global variable any more. But you can get it from `class.Object` + +```lua +local class = require 'middleclass' +local Object = class.Object + +print(Object) -- prints 'class Object' +``` + +The public functions `instanceOf`, `subclassOf` and `includes` have been replaced by `Object.isInstanceOf`, `Object.static.isSubclassOf` and `Object.static.includes`. + +Prior to 3.x: + +```lua +instanceOf(MyClass, obj) +subclassOf(Object, aClass) +includes(aMixin, aClass) +``` + +Since 3.x: + +```lua +obj:isInstanceOf(MyClass) +aClass:isSubclassOf(Object) +aClass:includes(aMixin) +``` + +The 3.x code snippet will throw an error if `obj` is not an object, or if `aClass` is not a class (since they will not implement `isInstanceOf`, `isSubclassOf` or `includes`). +If you are unsure of whether `obj` and `aClass` are an object or a class, you can use the methods in `Object`. They are prepared to work with random types, not just classes and instances: + +```lua +Object.isInstanceOf(obj, MyClass) +Object.isSubclassOf(aClass, Object) +Object.includes(aClass, aMixin) +``` + +Notice that the parameter order is not the same now as it was in 2.x. Also note the change in naming: `isInstanceOf` instead of `instanceOf`, and `isSubclassOf` instead of `subclassOf`. diff --git a/lib/middleclass/init.lua b/lib/middleclass/init.lua new file mode 100644 index 0000000..7e36bcd --- /dev/null +++ b/lib/middleclass/init.lua @@ -0,0 +1,183 @@ +local middleclass = { + _VERSION = 'middleclass v4.1.1', + _DESCRIPTION = 'Object Orientation for Lua', + _URL = 'https://github.com/kikito/middleclass', + _LICENSE = [[ + MIT LICENSE + + Copyright (c) 2011 Enrique García Cota + + 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 function _createIndexWrapper(aClass, f) + if f == nil then + return aClass.__instanceDict + else + return function(self, name) + local value = aClass.__instanceDict[name] + + if value ~= nil then + return value + elseif type(f) == "function" then + return (f(self, name)) + else + return f[name] + end + end + end +end + +local function _propagateInstanceMethod(aClass, name, f) + f = name == "__index" and _createIndexWrapper(aClass, f) or f + aClass.__instanceDict[name] = f + + for subclass in pairs(aClass.subclasses) do + if rawget(subclass.__declaredMethods, name) == nil then + _propagateInstanceMethod(subclass, name, f) + end + end +end + +local function _declareInstanceMethod(aClass, name, f) + aClass.__declaredMethods[name] = f + + if f == nil and aClass.super then + f = aClass.super.__instanceDict[name] + end + + _propagateInstanceMethod(aClass, name, f) +end + +local function _tostring(self) return "class " .. self.name end +local function _call(self, ...) return self:new(...) end + +local function _createClass(name, super) + local dict = {} + dict.__index = dict + + local aClass = { name = name, super = super, static = {}, + __instanceDict = dict, __declaredMethods = {}, + subclasses = setmetatable({}, {__mode='k'}) } + + if super then + setmetatable(aClass.static, { + __index = function(_,k) + local result = rawget(dict,k) + if result == nil then + return super.static[k] + end + return result + end + }) + else + setmetatable(aClass.static, { __index = function(_,k) return rawget(dict,k) end }) + end + + setmetatable(aClass, { __index = aClass.static, __tostring = _tostring, + __call = _call, __newindex = _declareInstanceMethod }) + + return aClass +end + +local function _includeMixin(aClass, mixin) + assert(type(mixin) == 'table', "mixin must be a table") + + for name,method in pairs(mixin) do + if name ~= "included" and name ~= "static" then aClass[name] = method end + end + + for name,method in pairs(mixin.static or {}) do + aClass.static[name] = method + end + + if type(mixin.included)=="function" then mixin:included(aClass) end + return aClass +end + +local DefaultMixin = { + __tostring = function(self) return "instance of " .. tostring(self.class) end, + + initialize = function(self, ...) end, + + isInstanceOf = function(self, aClass) + return type(aClass) == 'table' + and type(self) == 'table' + and (self.class == aClass + or type(self.class) == 'table' + and type(self.class.isSubclassOf) == 'function' + and self.class:isSubclassOf(aClass)) + end, + + static = { + allocate = function(self) + assert(type(self) == 'table', "Make sure that you are using 'Class:allocate' instead of 'Class.allocate'") + return setmetatable({ class = self }, self.__instanceDict) + end, + + new = function(self, ...) + assert(type(self) == 'table', "Make sure that you are using 'Class:new' instead of 'Class.new'") + local instance = self:allocate() + instance:initialize(...) + return instance + end, + + subclass = function(self, name) + assert(type(self) == 'table', "Make sure that you are using 'Class:subclass' instead of 'Class.subclass'") + assert(type(name) == "string", "You must provide a name(string) for your class") + + local subclass = _createClass(name, self) + + for methodName, f in pairs(self.__instanceDict) do + _propagateInstanceMethod(subclass, methodName, f) + end + subclass.initialize = function(instance, ...) return self.initialize(instance, ...) end + + self.subclasses[subclass] = true + self:subclassed(subclass) + + return subclass + end, + + subclassed = function(self, other) end, + + isSubclassOf = function(self, other) + return type(other) == 'table' and + type(self.super) == 'table' and + ( self.super == other or self.super:isSubclassOf(other) ) + end, + + include = function(self, ...) + assert(type(self) == 'table', "Make sure you that you are using 'Class:include' instead of 'Class.include'") + for _,mixin in ipairs({...}) do _includeMixin(self, mixin) end + return self + end + } +} + +function middleclass.class(name, super) + assert(type(name) == 'string', "A name (string) is needed for the new class") + return super and super:subclass(name) or _includeMixin(_createClass(name), DefaultMixin) +end + +setmetatable(middleclass, { __call = function(_, ...) return middleclass.class(...) end }) + +return middleclass diff --git a/lib/middleclass/performance/run.lua b/lib/middleclass/performance/run.lua new file mode 100644 index 0000000..8d8ba47 --- /dev/null +++ b/lib/middleclass/performance/run.lua @@ -0,0 +1,43 @@ +local class = require 'middleclass' + +time = require 'performance/time' + +time('class creation', function() + local A = class('A') +end) + +local A = class('A') + +time('instance creation', function() + local a = A:new() +end) + +function A:foo() + return 1 +end + +local a = A:new() + +time('instance method invocation', function() + a:foo() +end) + +local B = class('B', A) + +local b = B:new() + +time('inherited method invocation', function() + b:foo() +end) + +function A.static:bar() + return 2 +end + +time('class method invocation', function() + A:bar() +end) + +time('inherited class method invocation', function() + B:bar() +end) diff --git a/lib/middleclass/performance/time.lua b/lib/middleclass/performance/time.lua new file mode 100644 index 0000000..dd02455 --- /dev/null +++ b/lib/middleclass/performance/time.lua @@ -0,0 +1,13 @@ +return function(title, f) + + collectgarbage() + + local startTime = os.clock() + + for i=0,10000 do f() end + + local endTime = os.clock() + + print( title, endTime - startTime ) + +end diff --git a/lib/middleclass/rockspecs/middleclass-3.0-0.rockspec b/lib/middleclass/rockspecs/middleclass-3.0-0.rockspec new file mode 100644 index 0000000..f9ec58c --- /dev/null +++ b/lib/middleclass/rockspecs/middleclass-3.0-0.rockspec @@ -0,0 +1,21 @@ +package = "middleclass" +version = "3.0-0" +source = { + url = "https://github.com/kikito/middleclass/archive/v3.0.0.tar.gz", + dir = "middleclass-3.0.0" +} +description = { + summary = "A simple OOP library for Lua", + detailed = "It has inheritance, metamethods (operators), class variables and weak mixin support", + homepage = "https://github.com/kikito/middleclass", + license = "MIT" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + middleclass = "middleclass.lua" + } +} diff --git a/lib/middleclass/rockspecs/middleclass-3.1-0.rockspec b/lib/middleclass/rockspecs/middleclass-3.1-0.rockspec new file mode 100644 index 0000000..24a233e --- /dev/null +++ b/lib/middleclass/rockspecs/middleclass-3.1-0.rockspec @@ -0,0 +1,21 @@ +package = "middleclass" +version = "3.1-0" +source = { + url = "https://github.com/kikito/middleclass/archive/v3.1.0.tar.gz", + dir = "middleclass-3.1.0" +} +description = { + summary = "A simple OOP library for Lua", + detailed = "It has inheritance, metamethods (operators), class variables and weak mixin support", + homepage = "https://github.com/kikito/middleclass", + license = "MIT" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + middleclass = "middleclass.lua" + } +} diff --git a/lib/middleclass/rockspecs/middleclass-3.2-0.rockspec b/lib/middleclass/rockspecs/middleclass-3.2-0.rockspec new file mode 100644 index 0000000..03e3b30 --- /dev/null +++ b/lib/middleclass/rockspecs/middleclass-3.2-0.rockspec @@ -0,0 +1,21 @@ +package = "middleclass" +version = "3.2-0" +source = { + url = "https://github.com/kikito/middleclass/archive/v3.2.0.tar.gz", + dir = "middleclass-3.2.0" +} +description = { + summary = "A simple OOP library for Lua", + detailed = "It has inheritance, metamethods (operators), class variables and weak mixin support", + homepage = "https://github.com/kikito/middleclass", + license = "MIT" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + middleclass = "middleclass.lua" + } +} diff --git a/lib/middleclass/rockspecs/middleclass-4.0-0.rockspec b/lib/middleclass/rockspecs/middleclass-4.0-0.rockspec new file mode 100644 index 0000000..517984e --- /dev/null +++ b/lib/middleclass/rockspecs/middleclass-4.0-0.rockspec @@ -0,0 +1,21 @@ +package = "middleclass" +version = "4.0-0" +source = { + url = "https://github.com/kikito/middleclass/archive/v4.0.0.tar.gz", + dir = "middleclass-4.0.0" +} +description = { + summary = "A simple OOP library for Lua", + detailed = "It has inheritance, metamethods (operators), class variables and weak mixin support", + homepage = "https://github.com/kikito/middleclass", + license = "MIT" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + middleclass = "middleclass.lua" + } +} diff --git a/lib/middleclass/rockspecs/middleclass-4.1-0.rockspec b/lib/middleclass/rockspecs/middleclass-4.1-0.rockspec new file mode 100644 index 0000000..dc710e9 --- /dev/null +++ b/lib/middleclass/rockspecs/middleclass-4.1-0.rockspec @@ -0,0 +1,21 @@ +package = "middleclass" +version = "4.1-0" +source = { + url = "https://github.com/kikito/middleclass/archive/v4.1.0.tar.gz", + dir = "middleclass-4.1.0" +} +description = { + summary = "A simple OOP library for Lua", + detailed = "It has inheritance, metamethods (operators), class variables and weak mixin support", + homepage = "https://github.com/kikito/middleclass", + license = "MIT" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + middleclass = "middleclass.lua" + } +} diff --git a/lib/middleclass/rockspecs/middleclass-4.1.1-0.rockspec b/lib/middleclass/rockspecs/middleclass-4.1.1-0.rockspec new file mode 100644 index 0000000..ddaacd9 --- /dev/null +++ b/lib/middleclass/rockspecs/middleclass-4.1.1-0.rockspec @@ -0,0 +1,21 @@ +package = "middleclass" +version = "4.1.1-0" +source = { + url = "https://github.com/kikito/middleclass/archive/v4.1.1.tar.gz", + dir = "middleclass-4.1.1" +} +description = { + summary = "A simple OOP library for Lua", + detailed = "It has inheritance, metamethods (operators), class variables and weak mixin support", + homepage = "https://github.com/kikito/middleclass", + license = "MIT" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + middleclass = "middleclass.lua" + } +} diff --git a/lib/middleclass/spec/class_spec.lua b/lib/middleclass/spec/class_spec.lua new file mode 100644 index 0000000..144cb9f --- /dev/null +++ b/lib/middleclass/spec/class_spec.lua @@ -0,0 +1,28 @@ +local class = require 'middleclass' + +describe('class()', function() + + describe('when given no params', function() + it('it throws an error', function() + assert.error(class) + end) + end) + + describe('when given a name', function() + it('the resulting class has the correct name and Object as its superclass', function() + local TheClass = class('TheClass') + assert.equal(TheClass.name, 'TheClass') + assert.is_nil(TheClass.super) + end) + end) + + describe('when given a name and a superclass', function() + it('the resulting class has the correct name and superclass', function() + local TheSuperClass = class('TheSuperClass') + local TheSubClass = class('TheSubClass', TheSuperClass) + assert.equal(TheSubClass.name, 'TheSubClass') + assert.equal(TheSubClass.super, TheSuperClass) + end) + end) + +end) diff --git a/lib/middleclass/spec/classes_spec.lua b/lib/middleclass/spec/classes_spec.lua new file mode 100644 index 0000000..7942f18 --- /dev/null +++ b/lib/middleclass/spec/classes_spec.lua @@ -0,0 +1,138 @@ +local class = require 'middleclass' + +describe('A Class', function() + + describe('Default stuff', function() + + local AClass + + before_each(function() + AClass = class('AClass') + end) + + describe('name', function() + it('is correctly set', function() + assert.equal(AClass.name, 'AClass') + end) + end) + + describe('tostring', function() + it('returns "class *name*"', function() + assert.equal(tostring(AClass), 'class AClass') + end) + end) + + describe('()', function() + it('returns an object, like Class:new()', function() + local obj = AClass() + assert.equal(obj.class, AClass) + end) + end) + + describe('include', function() + it('throws an error when used without the :', function() + assert.error(function() AClass.include() end) + end) + it('throws an error when passed a non-table:', function() + assert.error(function() AClass:include(1) end) + end) + end) + + describe('subclass', function() + + it('throws an error when used without the :', function() + assert.error(function() AClass.subclass() end) + end) + + it('throws an error when no name is given', function() + assert.error( function() AClass:subclass() end) + end) + + describe('when given a subclass name', function() + + local SubClass + + before_each(function() + function AClass.static:subclassed(other) self.static.child = other end + SubClass = AClass:subclass('SubClass') + end) + + it('it returns a class with the correct name', function() + assert.equal(SubClass.name, 'SubClass') + end) + + it('it returns a class with the correct superclass', function() + assert.equal(SubClass.super, AClass) + end) + + it('it invokes the subclassed hook method', function() + assert.equal(SubClass, AClass.child) + end) + + it('it includes the subclass in the list of subclasses', function() + assert.is_true(AClass.subclasses[SubClass]) + end) + + end) + + end) + + end) + + + + describe('attributes', function() + + local A, B + + before_each(function() + A = class('A') + A.static.foo = 'foo' + + B = class('B', A) + end) + + it('are available after being initialized', function() + assert.equal(A.foo, 'foo') + end) + + it('are available for subclasses', function() + assert.equal(B.foo, 'foo') + end) + + it('are overridable by subclasses, without affecting the superclasses', function() + B.static.foo = 'chunky bacon' + assert.equal(B.foo, 'chunky bacon') + assert.equal(A.foo, 'foo') + end) + + end) + + describe('methods', function() + + local A, B + + before_each(function() + A = class('A') + function A.static:foo() return 'foo' end + + B = class('B', A) + end) + + it('are available after being initialized', function() + assert.equal(A:foo(), 'foo') + end) + + it('are available for subclasses', function() + assert.equal(B:foo(), 'foo') + end) + + it('are overridable by subclasses, without affecting the superclasses', function() + function B.static:foo() return 'chunky bacon' end + assert.equal(B:foo(), 'chunky bacon') + assert.equal(A:foo(), 'foo') + end) + + end) + +end) diff --git a/lib/middleclass/spec/default_methods_spec.lua b/lib/middleclass/spec/default_methods_spec.lua new file mode 100644 index 0000000..91fd9b8 --- /dev/null +++ b/lib/middleclass/spec/default_methods_spec.lua @@ -0,0 +1,236 @@ +local class = require 'middleclass' + +describe('Default methods', function() + local Object + before_each(function() + Object = class('Object') + end) + + describe('name', function() + it('is correctly set', function() + assert.equal(Object.name, 'Object') + end) + end) + + describe('tostring', function() + it('returns "class Object"', function() + assert.equal(tostring(Object), 'class Object') + end) + end) + + describe('()', function() + it('returns an object, like Object:new()', function() + local obj = Object() + assert.is_true(obj:isInstanceOf(Object)) + end) + end) + + describe('subclass', function() + + it('throws an error when used without the :', function() + assert.error(function() Object.subclass() end) + end) + + it('throws an error when no name is given', function() + assert.error( function() Object:subclass() end) + end) + + describe('when given a class name', function() + + local SubClass + + before_each(function() + SubClass = Object:subclass('SubClass') + end) + + it('it returns a class with the correct name', function() + assert.equal(SubClass.name, 'SubClass') + end) + + it('it returns a class with the correct superclass', function() + assert.equal(SubClass.super, Object) + end) + + it('it includes the subclass in the list of subclasses', function() + assert.is_true(Object.subclasses[SubClass]) + end) + + end) + + end) + + describe('instance creation', function() + + local SubClass + + before_each(function() + SubClass = class('SubClass') + function SubClass:initialize() self.mark=true end + end) + + describe('allocate', function() + + it('allocates instances properly', function() + local instance = SubClass:allocate() + assert.equal(instance.class, SubClass) + assert.equal(tostring(instance), "instance of " .. tostring(SubClass)) + end) + + it('throws an error when used without the :', function() + assert.error(Object.allocate) + end) + + it('does not call the initializer', function() + local allocated = SubClass:allocate() + assert.is_nil(allocated.mark) + end) + + it('can be overriden', function() + + local previousAllocate = SubClass.static.allocate + + function SubClass.static:allocate() + local instance = previousAllocate(SubClass) + instance.mark = true + return instance + end + + local allocated = SubClass:allocate() + assert.is_true(allocated.mark) + end) + + end) + + describe('new', function() + + it('initializes instances properly', function() + local instance = SubClass:new() + assert.equal(instance.class, SubClass) + end) + + it('throws an error when used without the :', function() + assert.error(SubClass.new) + end) + + it('calls the initializer', function() + local initialized = SubClass:new() + assert.is_true(initialized.mark) + end) + + end) + + describe('isInstanceOf', function() + + describe('primitives', function() + local o = Object:new() + local primitives = {nil, 1, 'hello', {}, function() end, Object:new()} + + describe('used as classes', function() + for _,primitive in pairs(primitives) do + local theType = type(primitive) + it('object:isInstanceOf(, '.. theType ..') returns false', function() + assert.is_falsy(o:isInstanceOf(primitive)) + end) + end + end) + + describe('used as instances', function() + for _,primitive in pairs(primitives) do + local theType = type(primitive) + it('Object.isInstanceOf('.. theType ..', Object) returns false without error', function() + assert.is_falsy(Object.isInstanceOf(primitive, Object)) + end) + end + end) + + + end) + + describe('An instance', function() + local Class1 = class('Class1') + local Class2 = class('Class2', Class1) + local Class3 = class('Class3', Class2) + local UnrelatedClass = class('Unrelated') + + local o1, o2, o3 = Class1:new(), Class2:new(), Class3:new() + + it('isInstanceOf its class', function() + assert.is_true(o1:isInstanceOf(Class1)) + assert.is_true(o2:isInstanceOf(Class2)) + assert.is_true(o3:isInstanceOf(Class3)) + end) + + it('is instanceOf its class\' superclasses', function() + assert.is_true(o2:isInstanceOf(Class1)) + assert.is_true(o3:isInstanceOf(Class1)) + assert.is_true(o3:isInstanceOf(Class2)) + end) + + it('is not instanceOf its class\' subclasses', function() + assert.is_false(o1:isInstanceOf(Class2)) + assert.is_false(o1:isInstanceOf(Class3)) + assert.is_false(o2:isInstanceOf(Class3)) + end) + + it('is not instanceOf an unrelated class', function() + assert.is_false(o1:isInstanceOf(UnrelatedClass)) + assert.is_false(o2:isInstanceOf(UnrelatedClass)) + assert.is_false(o3:isInstanceOf(UnrelatedClass)) + end) + + end) + + end) + + end) + + describe('isSubclassOf', function() + + it('returns false for instances', function() + assert.is_false(Object:isSubclassOf(Object:new())) + end) + + describe('on primitives', function() + local primitives = {nil, 1, 'hello', {}, function() end} + + for _,primitive in pairs(primitives) do + local theType = type(primitive) + it('returns false for ' .. theType, function() + assert.is_false(Object:isSubclassOf(primitive)) + end) + end + + end) + + describe('Any class (except Object)', function() + local Class1 = class('Class1') + local Class2 = class('Class2', Class1) + local Class3 = class('Class3', Class2) + local UnrelatedClass = class('Unrelated') + + it('is subclassOf its direct superclass', function() + assert.is_true(Class2:isSubclassOf(Class1)) + assert.is_true(Class3:isSubclassOf(Class2)) + end) + + it('is subclassOf its ancestors', function() + assert.is_true(Class3:isSubclassOf(Class1)) + end) + + it('is a subclassOf its class\' subclasses', function() + assert.is_true(Class2:isSubclassOf(Class1)) + assert.is_true(Class3:isSubclassOf(Class1)) + assert.is_true(Class3:isSubclassOf(Class2)) + end) + + it('is not a subclassOf an unrelated class', function() + assert.is_false(Class1:isSubclassOf(UnrelatedClass)) + assert.is_false(Class2:isSubclassOf(UnrelatedClass)) + assert.is_false(Class3:isSubclassOf(UnrelatedClass)) + end) + + end) + end) +end) + + diff --git a/lib/middleclass/spec/instances_spec.lua b/lib/middleclass/spec/instances_spec.lua new file mode 100644 index 0000000..d9ac52c --- /dev/null +++ b/lib/middleclass/spec/instances_spec.lua @@ -0,0 +1,65 @@ +local class = require 'middleclass' + +describe('An instance', function() + + describe('attributes', function() + + local Person + + before_each(function() + Person = class('Person') + function Person:initialize(name) + self.name = name + end + end) + + it('are available in the instance after being initialized', function() + local bob = Person:new('bob') + assert.equal(bob.name, 'bob') + end) + + it('are available in the instance after being initialized by a superclass', function() + local AgedPerson = class('AgedPerson', Person) + function AgedPerson:initialize(name, age) + Person.initialize(self, name) + self.age = age + end + + local pete = AgedPerson:new('pete', 31) + assert.equal(pete.name, 'pete') + assert.equal(pete.age, 31) + end) + + end) + + describe('methods', function() + + local A, B, a, b + + before_each(function() + A = class('A') + function A:overridden() return 'foo' end + function A:regular() return 'regular' end + + B = class('B', A) + function B:overridden() return 'bar' end + + a = A:new() + b = B:new() + end) + + it('are available for any instance', function() + assert.equal(a:overridden(), 'foo') + end) + + it('are inheritable', function() + assert.equal(b:regular(), 'regular') + end) + + it('are overridable', function() + assert.equal(b:overridden(), 'bar') + end) + + end) + +end) diff --git a/lib/middleclass/spec/metamethods_lua_5_2.lua b/lib/middleclass/spec/metamethods_lua_5_2.lua new file mode 100644 index 0000000..2ea6c9b --- /dev/null +++ b/lib/middleclass/spec/metamethods_lua_5_2.lua @@ -0,0 +1,85 @@ +local class = require 'middleclass' + +local it = require('busted').it +local describe = require('busted').describe +local before_each = require('busted').before_each +local assert = require('busted').assert + +describe('Lua 5.2 Metamethods', function() + local Vector, v + before_each(function() + Vector= class('Vector') + function Vector.initialize(a,x,y,z) a.x, a.y, a.z = x,y,z end + function Vector.__eq(a,b) return a.x==b.x and a.y==b.y and a.z==b.z end + + function Vector.__len(a) return 3 end + function Vector.__pairs(a) + local t = {x=a.x,y=a.y,z=a.z} + return coroutine.wrap(function() + for k,val in pairs(t) do + coroutine.yield(k,val) + end + end) + end + function Vector.__ipairs(a) + local t = {a.x,a.y,a.z} + return coroutine.wrap(function() + for k,val in ipairs(t) do + coroutine.yield(k,val) + end + end) + end + + v = Vector:new(1,2,3) + end) + + it('implements __len', function() + assert.equal(#v, 3) + end) + + it('implements __pairs',function() + local output = {} + for k,val in pairs(v) do + output[k] = val + end + assert.are.same(output,{x=1,y=2,z=3}) + end) + + it('implements __ipairs',function() + local output = {} + for _,i in ipairs(v) do + output[#output+1] = i + end + assert.are.same(output,{1,2,3}) + end) + + describe('Inherited Metamethods', function() + local Vector2, v2 + before_each(function() + Vector2= class('Vector2', Vector) + function Vector2:initialize(x,y,z) Vector.initialize(self,x,y,z) end + + v2 = Vector2:new(1,2,3) + end) + + it('implements __len', function() + assert.equal(#v2, 3) + end) + + it('implements __pairs',function() + local output = {} + for k,val in pairs(v2) do + output[k] = val + end + assert.are.same(output,{x=1,y=2,z=3}) + end) + + it('implements __ipairs',function() + local output = {} + for _,i in ipairs(v2) do + output[#output+1] = i + end + assert.are.same(output,{1,2,3}) + end) + end) +end) diff --git a/lib/middleclass/spec/metamethods_lua_5_3.lua b/lib/middleclass/spec/metamethods_lua_5_3.lua new file mode 100644 index 0000000..e74f6d7 --- /dev/null +++ b/lib/middleclass/spec/metamethods_lua_5_3.lua @@ -0,0 +1,106 @@ +local class = require 'middleclass' + +local it = require('busted').it +local describe = require('busted').describe +local before_each = require('busted').before_each +local assert = require('busted').assert + +describe('Lua 5.3 Metamethods', function() + local Vector, v, last_gc + before_each(function() + Vector= class('Vector') + function Vector.initialize(a,x,y,z) a.x, a.y, a.z = x,y,z end + function Vector.__eq(a,b) return a.x==b.x and a.y==b.y and a.z==b.z end + function Vector.__pairs(a) + local t = {x=a.x,y=a.y,z=a.z} + return coroutine.wrap(function() + for k,val in pairs(t) do + coroutine.yield(k,val) + end + end) + end + function Vector.__len(a) return 3 end + + function Vector.__gc(a) last_gc = {a.class.name, a.x, a.y, a.z} end + function Vector.__band(a,n) return a.class:new(a.x & n, a.y & n, a.z & n) end + function Vector.__bor(a,n) return a.class:new(a.x | n, a.y | n, a.z | n) end + function Vector.__bxor(a,n) return a.class:new(a.x ~ n, a.y ~ n, a.z ~ n) end + function Vector.__shl(a,n) return a.class:new(a.x << n, a.y << n, a.z << n) end + function Vector.__shr(a,n) return a.class:new(a.x >> n, a.y >> n, a.z >> n) end + function Vector.__bnot(a) return a.class:new(~a.x, ~a.y, ~a.z) end + + v = Vector:new(1,2,3) + end) + + it('implements __gc', function() + collectgarbage() + v = nil + collectgarbage() + assert.are.same(last_gc, {"Vector",1,2,3}) + end) + + it('implements __band', function() + assert.equal(v & 1, Vector(1,0,1)) + end) + + it('implements __bor', function() + assert.equal(v | 0, Vector(1,2,3)) + end) + + it('implements __bxor', function() + assert.equal(v | 1, Vector(1,3,3)) + end) + + it('implements __shl', function() + assert.equal(v << 1, Vector(2,4,6)) + end) + + it('implements __shr', function() + assert.equal(v >> 1, Vector(0,1,1)) + end) + + it('implements __bnot', function() + assert.equal(~v, Vector(-2,-3,-4)) + end) + + describe('Inherited Metamethods', function() + local Vector2, v2 + before_each(function() + Vector2= class('Vector2', Vector) + function Vector2:initialize(x,y,z) Vector.initialize(self,x,y,z) end + + v2 = Vector2:new(1,2,3) + end) + + it('implements __gc', function() + collectgarbage() + v2 = nil + collectgarbage() + assert.are.same(last_gc, {"Vector2",1,2,3}) + end) + + it('implements __band', function() + assert.equal(v2 & 1, Vector2(1,0,1)) + end) + + it('implements __bor', function() + assert.equal(v2 | 0, Vector2(1,2,3)) + end) + + it('implements __bxor', function() + assert.equal(v2 | 1, Vector2(1,3,3)) + end) + + it('implements __shl', function() + assert.equal(v2 << 1, Vector2(2,4,6)) + end) + + it('implements __shr', function() + assert.equal(v2 >> 1, Vector2(0,1,1)) + end) + + it('implements __bnot', function() + assert.equal(~v2, Vector2(-2,-3,-4)) + end) + end) +end) diff --git a/lib/middleclass/spec/metamethods_spec.lua b/lib/middleclass/spec/metamethods_spec.lua new file mode 100644 index 0000000..73bf883 --- /dev/null +++ b/lib/middleclass/spec/metamethods_spec.lua @@ -0,0 +1,317 @@ +local class = require 'middleclass' + +local function is_lua_5_2_compatible() + return type(rawlen) == 'function' +end + +local function is_lua_5_3_compatible() + return type(string.unpack) == 'function' +end + +if is_lua_5_2_compatible() then + require 'spec/metamethods_lua_5_2' +end + +if is_lua_5_3_compatible() then + require 'spec.metamethods_lua_5_3' +end + +describe('Metamethods', function() + describe('Custom Metamethods', function() + local Vector, v, w + before_each(function() + Vector= class('Vector') + function Vector.initialize(a,x,y,z) a.x, a.y, a.z = x,y,z end + function Vector.__tostring(a) return a.class.name .. '[' .. a.x .. ',' .. a.y .. ',' .. a.z .. ']' end + function Vector.__eq(a,b) return a.x==b.x and a.y==b.y and a.z==b.z end + function Vector.__lt(a,b) return a() < b() end + function Vector.__le(a,b) return a() <= b() end + function Vector.__add(a,b) return a.class:new(a.x+b.x, a.y+b.y ,a.z+b.z) end + function Vector.__sub(a,b) return a.class:new(a.x-b.x, a.y-b.y, a.z-b.z) end + function Vector.__div(a,s) return a.class:new(a.x/s, a.y/s, a.z/s) end + function Vector.__unm(a) return a.class:new(-a.x, -a.y, -a.z) end + function Vector.__concat(a,b) return a.x*b.x+a.y*b.y+a.z*b.z end + function Vector.__call(a) return math.sqrt(a.x*a.x+a.y*a.y+a.z*a.z) end + function Vector.__pow(a,b) + return a.class:new(a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x) + end + function Vector.__mul(a,b) + if type(b)=="number" then return a.class:new(a.x*b, a.y*b, a.z*b) end + if type(a)=="number" then return b.class:new(a*b.x, a*b.y, a*b.z) end + end + Vector.__metatable = "metatable of a vector" + Vector.__mode = "k" + + v = Vector:new(1,2,3) + w = Vector:new(2,4,6) + end) + + it('implements __tostring', function() + assert.equal(tostring(v), "Vector[1,2,3]") + end) + + it('implements __eq', function() + assert.equal(v, v) + end) + + it('implements __lt', function() + assert.is_true(v < w) + end) + + it('implements __le', function() + assert.is_true(v <= w) + end) + + it('implements __add', function() + assert.equal(v+w, Vector(3,6,9)) + end) + + it('implements __sub', function() + assert.equal(w-v, Vector(1,2,3)) + end) + + it('implements __div', function() + assert.equal(w/2, Vector(1,2,3)) + end) + + it('implements __concat', function() + assert.equal(v..w, 28) + end) + + it('implements __call', function() + assert.equal(v(), math.sqrt(14)) + end) + + it('implements __pow', function() + assert.equal(v^w, Vector(0,0,0)) + end) + + it('implements __mul', function() + assert.equal(4*v, Vector(4,8,12)) + end) + + it('implements __metatable', function() + assert.equal("metatable of a vector", getmetatable(v)) + end) + + it('implements __mode', function() + v[{}] = true + collectgarbage() + for k in pairs(v) do assert.not_table(k) end + end) + + --[[ + it('implements __index', function() + assert.equal(b[1], 3) + end) + --]] + + describe('Inherited Metamethods', function() + local Vector2, v2, w2 + before_each(function() + Vector2= class('Vector2', Vector) + function Vector2:initialize(x,y,z) Vector.initialize(self,x,y,z) end + + v2 = Vector2:new(1,2,3) + w2 = Vector2:new(2,4,6) + end) + + it('implements __tostring', function() + assert.equal(tostring(v2), "Vector2[1,2,3]") + end) + + it('implements __eq', function() + assert.equal(v2, v2) + end) + + it('implements __lt', function() + assert.is_true(v2 < w2) + end) + + it('implements __le', function() + assert.is_true(v2 <= w2) + end) + + it('implements __add', function() + assert.equal(v2+w2, Vector2(3,6,9)) + end) + + it('implements __sub', function() + assert.equal(w2-v2, Vector2(1,2,3)) + end) + + it('implements __div', function() + assert.equal(w2/2, Vector2(1,2,3)) + end) + + it('implements __concat', function() + assert.equal(v2..w2, 28) + end) + + it('implements __call', function() + assert.equal(v2(), math.sqrt(14)) + end) + + it('implements __pow', function() + assert.equal(v2^w2, Vector2(0,0,0)) + end) + + it('implements __mul', function() + assert.equal(4*v2, Vector2(4,8,12)) + end) + + it('implements __metatable', function() + assert.equal("metatable of a vector", getmetatable(v2)) + end) + + it('implements __mode', function() + v2[{}] = true + collectgarbage() + for k in pairs(v2) do assert.not_table(k) end + end) + + it('allows inheriting further', function() + local Vector3 = class('Vector3', Vector2) + local v3 = Vector3(1,2,3) + local w3 = Vector3(3,4,5) + assert.equal(v3+w3, Vector3(4,6,8)) + end) + + describe('Updates', function() + it('overrides __add', function() + Vector2.__add = function(a, b) return Vector.__add(a, b)/2 end + assert.equal(v2+w2, Vector2(1.5,3,4.5)) + end) + + it('updates __add', function() + Vector.__add = Vector.__sub + assert.equal(v2+w2, Vector2(-1,-2,-3)) + end) + + it('does not update __add after overriding', function() + Vector2.__add = function(a, b) return Vector.__add(a, b)/2 end + Vector.__add = Vector.__sub + assert.equal(v2+w2, Vector2(-0.5,-1,-1.5)) + end) + + it('reverts __add override', function() + Vector2.__add = function(a, b) return Vector.__add(a, b)/2 end + Vector2.__add = nil + assert.equal(v2+w2, Vector2(3,6,9)) + end) + end) + end) + end) + + describe('Custom __index and __newindex', function() + describe('Tables', function() + local Proxy, fallback, p + before_each(function() + Proxy = class('Proxy') + fallback = {foo = 'bar', common = 'fallback'} + Proxy.__index = fallback + Proxy.__newindex = fallback + Proxy.common = 'class' + p = Proxy() + end) + + it('uses __index', function() + assert.equal(p.foo, 'bar') + end) + + it('does not use __index when field exists in class', function() + assert.equal(p.common, 'class') + end) + + it('uses __newindex', function() + p.key = 'value' + assert.equal(fallback.key, 'value') + end) + + it('uses __newindex when field exists in class', function() + p.common = 'value' + assert.equal(p.common, 'class') + assert.equal(Proxy.common, 'class') + assert.equal(fallback.common, 'value') + end) + end) + + describe('Functions', function() + local Namespace, Rectangle, r + before_each(function() + Namespace = class('Namespace') + function Namespace:__index(name) + local getter = self.class[name.."Getter"] + if getter then return getter(self) end + end + function Namespace:__newindex(name, value) + local setter = self.class[name.."Setter"] + if setter then setter(self, value) else rawset(self, name, value) end + end + Rectangle = class('Rectangle', Namespace) + function Rectangle:initialize(x, y, scale) + self._scale, self.x, self.y = 1, x, y + self.scale = scale + end + function Rectangle:scaleGetter() return self._scale end + function Rectangle:scaleSetter(v) + self.x = self.x*v/self._scale + self.y = self.y*v/self._scale + self._scale = v + end + function Rectangle:areaGetter() return self.x * self.y end + r = Rectangle(3, 4, 2) + end) + + it('uses setter', function() + assert.equal(r.x, 6) + assert.equal(r.y, 8) + r.scale = 3 + assert.equal(r.x, 9) + assert.equal(r.y, 12) + end) + + it('uses getters', function() + assert.equal(r.scale, 2) + assert.equal(r.area, 48) + end) + + it('updates inherited __index', function() + function Namespace.__index() return 42 end + assert.equal(r.area, 42) + function Rectangle.__index() return 24 end + assert.equal(r.area, 24) + function Namespace.__index() return 96 end + assert.equal(r.area, 24) + Rectangle.__index = nil + assert.equal(r.area, 96) + end) + end) + end) + + describe('Default Metamethods', function() + + local Peter, peter + + before_each(function() + Peter = class('Peter') + peter = Peter() + end) + + describe('A Class', function() + it('has a call metamethod properly set', function() + assert.is_true(peter:isInstanceOf(Peter)) + end) + it('has a tostring metamethod properly set', function() + assert.equal(tostring(Peter), 'class Peter') + end) + end) + + describe('An instance', function() + it('has a tostring metamethod, returning a different result from Object.__tostring', function() + assert.equal(tostring(peter), 'instance of class Peter') + end) + end) + end) + +end) diff --git a/lib/middleclass/spec/mixins_spec.lua b/lib/middleclass/spec/mixins_spec.lua new file mode 100644 index 0000000..ef592a1 --- /dev/null +++ b/lib/middleclass/spec/mixins_spec.lua @@ -0,0 +1,53 @@ +local class = require 'middleclass' + +describe('A Mixin', function() + + local Mixin1, Mixin2, Class1, Class2 + + before_each(function() + Mixin1, Mixin2 = {},{} + + function Mixin1:included(theClass) theClass.includesMixin1 = true end + function Mixin1:foo() return 'foo' end + function Mixin1:bar() return 'bar' end + Mixin1.static = {} + Mixin1.static.bazzz = function() return 'bazzz' end + + + function Mixin2:baz() return 'baz' end + + Class1 = class('Class1'):include(Mixin1, Mixin2) + function Class1:foo() return 'foo1' end + + Class2 = class('Class2', Class1) + function Class2:bar2() return 'bar2' end + end) + + it('invokes the "included" method when included', function() + assert.is_true(Class1.includesMixin1) + end) + + it('has all its functions (except "included") copied to its target class', function() + assert.equal(Class1:bar(), 'bar') + assert.is_nil(Class1.included) + end) + + it('makes its functions available to subclasses', function() + assert.equal(Class2:baz(), 'baz') + end) + + it('allows overriding of methods in the same class', function() + assert.equal(Class2:foo(), 'foo1') + end) + + it('allows overriding of methods on subclasses', function() + assert.equal(Class2:bar2(), 'bar2') + end) + + it('makes new static methods available in classes', function() + assert.equal(Class1:bazzz(), 'bazzz') + assert.equal(Class2:bazzz(), 'bazzz') + end) + +end) + diff --git a/lib/windfield/README.md b/lib/windfield/README.md new file mode 100644 index 0000000..0cd5c59 --- /dev/null +++ b/lib/windfield/README.md @@ -0,0 +1,941 @@ +**windfield** is a physics module for LÖVE. It wraps LÖVE's physics API so that using box2d becomes as simple as possible. + +# Contents + +* [Quick Start](#quick-start) + * [Create a world](#create-a-world) + * [Create colliders](#create-colliders) + * [Create joints](#create-joints) + * [Create collision classes](#create-collision-classes) + * [Capture collision events](#capture-collision-events) + * [Query the world](#query-the-world) +* [Examples & Tips](#examples-tips) + * [Checking collisions between game objects](#checking-collisions-between-game-objects) + * [One-way Platforms](#one-way-platforms) +* [Documentation](#documentation) + * [World](#world) + * [newWorld](#newworldxg-yg-sleep) + * [update](#updatedt) + * [draw](#drawalpha) + * [destroy](#destroy) + * [addCollisionClass](#addcollisionclasscollision_class_name-collision_class) + * [newCircleCollider](#newcirclecolliderx-y-r) + * [newRectangleCollider](#newrectanglecolliderx-y-w-h) + * [newBSGRectangleCollider](#newbsgrectanglecolliderx-y-w-h-corner_cut_size) + * [newPolygonCollider](#newpolygoncollidervertices) + * [newLineCollider](#newlinecolliderx1-y1-x2-y2) + * [newChainCollider](#newchaincollidervertices-loop) + * [queryCircleArea](#querycircleareax-y-r-collision_class_name) + * [queryRectangleArea](#queryrectangleareax-y-w-h-collision_class_names) + * [queryPolygonArea](#querypolygonareavertices-collision_class_names) + * [queryLine](#querylinex1-y1-x2-y2-collision_class_names) + * [addJoint](#addjointjoint_type) + * [removeJoint](#removejointjoint) + * [setExplicitCollisionEvents](#setexplicitcollisioneventsvalue) + * [setQueryDebugDrawing](#setquerydebugdrawingvalue) + * [Collider](#collider) + * [destroy](#destroy-1) + * [setCollisionClass](#setcollisionclasscollision_class_name) + * [enter](#enterother_collision_class_name) + * [getEnterCollisionData](#getentercollisiondataother_collision_class_name) + * [exit](#exitother_collision_class_name) + * [getExitCollisionData](#getexitcollisiondataother_collision_class_name) + * [stay](#stayother_collision_class_name) + * [getStayCollisionData](#getstaycollisiondataother_collision_class_name) + * [setPreSolve](#setpresolvecallback) + * [setPostSolve](#setpostsolvecallback) + * [addShape](#addshapeshape_name-shape_type) + * [removeShape](#removeshapeshape_name) + * [setObject](#setobjectobject) + * [getObject](#getobject) + +
+ +# Quick Start + +Place the `windfield` folder inside your project and require it: + +```lua +wf = require 'windfield' +``` + +
+ +## Create a world + +A physics world can be created just like in box2d. The world returned by `wf.newWorld` contains all the functions of a [LÖVE physics World](https://love2d.org/wiki/World) as well as additional ones defined by this library. + +```lua +function love.load() + world = wf.newWorld(0, 0, true) + world:setGravity(0, 512) +end + +function love.update(dt) + world:update(dt) +end +``` + +
+ +## Create colliders + +A collider is a composition of a single body, fixture and shape. For most use cases whenever box2d is needed a body will only have one fixture/shape attached to it, so it makes sense to work primarily on that level of abstraction. Colliders contain all the functions of a LÖVE physics [Body](https://love2d.org/wiki/Body), [Fixture](https://love2d.org/wiki/Fixture) and [Shape](https://love2d.org/wiki/Shape) as well as additional ones defined by this library: + +```lua +function love.load() + ... + + box = world:newRectangleCollider(400 - 50/2, 0, 50, 50) + box:setRestitution(0.8) + box:applyAngularImpulse(5000) + + ground = world:newRectangleCollider(0, 550, 800, 50) + wall_left = world:newRectangleCollider(0, 0, 50, 600) + wall_right = world:newRectangleCollider(750, 0, 50, 600) + ground:setType('static') -- Types can be 'static', 'dynamic' or 'kinematic'. Defaults to 'dynamic' + wall_left:setType('static') + wall_right:setType('static') +end + +... + +function love.draw() + world:draw() -- The world can be drawn for debugging purposes +end +``` + +And that looks like this: + +

+ +

+ +
+ +## Create joints + +Joints are mostly unchanged from how they work normally in box2d: + +```lua +function love.load() + ... + + box_1 = world:newRectangleCollider(400 - 50/2, 0, 50, 50) + box_1:setRestitution(0.8) + box_2 = world:newRectangleCollider(400 - 50/2, 50, 50, 50) + box_2:setRestitution(0.8) + box_2:applyAngularImpulse(5000) + joint = world:addJoint('RevoluteJoint', box_1, box_2, 400, 50, true) + + ... +end +``` + +And that looks like this: + +

+ +

+ +
+ +## Create collision classes + +Collision classes are used to make colliders ignore other colliders of certain classes and to capture collision events between colliders. The same concept goes by the name of 'collision layer' or 'collision tag' in other engines. In the example below we add a Solid and Ghost collision class. The Ghost collision class is set to ignore the Solid collision class. + +```lua +function love.load() + ... + + world:addCollisionClass('Solid') + world:addCollisionClass('Ghost', {ignores = {'Solid'}}) + + box_1 = world:newRectangleCollider(400 - 100, 0, 50, 50) + box_1:setRestitution(0.8) + box_2 = world:newRectangleCollider(400 + 50, 0, 50, 50) + box_2:setCollisionClass('Ghost') + + ground = world:newRectangleCollider(0, 550, 800, 50) + ground:setType('static') + ground:setCollisionClass('Solid') + + ... +end +``` + +And that looks like this: + +

+ +

+ +The box that was set be of the Ghost collision class ignored the ground and went right through it, since the ground is set to be of the Solid collision class. + +
+ +## Capture collision events + +Collision events can be captured inside the update function by calling the `enter`, `exit` or `stay` functions of a collider. In the example below, whenever the box collider enters contact with another collider of the Solid collision class it will get pushed to the right: + +```lua +function love.update(dt) + ... + if box:enter('Solid') then + box:applyLinearImpulse(1000, 0) + box:applyAngularImpulse(5000) + end +end +``` + +And that looks like this: + +

+ +

+ +
+ +## Query the world + +The world can be queried with a few area functions and then all colliders inside that area will be returned. In the example below, the world is queried at position 400, 300 with a circle of radius 100, and then all colliders in that area are pushed to the right and down. + +```lua +function love.load() + world = wf.newWorld(0, 0, true) + world:setQueryDebugDrawing(true) -- Draws the area of a query for 10 frames + + colliders = {} + for i = 1, 200 do + table.insert(colliders, world:newRectangleCollider(love.math.random(0, 800), love.math.random(0, 600), 25, 25)) + end +end + +function love.update(dt) + world:update(dt) +end + +function love.draw() + world:draw() +end + +function love.keypressed(key) + if key == 'p' then + local colliders = world:queryCircleArea(400, 300, 100) + for _, collider in ipairs(colliders) do + collider:applyLinearImpulse(1000, 1000) + end + end +end +``` + +And that looks like this: + +

+ +

+ +
+ +# Examples & Tips + +## Checking collisions between game objects + +The most common use case for a physics engine is doing things when things collide. For instance, when the Player collides with an enemy you might want to deal damage to the player. Here's the way to achieve that with this library: + + +```lua +-- in Player.lua +function Player:new() + self.collider = world:newRectangleCollider(...) + self.collider:setCollisionClass('Player') + self.collider:setObject(self) +end + +-- in Enemy.lua +function Enemy:new() + self.collider = world:newRectangleCollider(...) + self.collider:setCollisionClass('Enemy') + self.collider:setObject(self) +end +``` + +First we define in the constructor of both classes the collider that should be attached to them. We set their collision classes (Player and Enemy) and then link the object to the colliders with `setObject`. With this, we can capture collision events between both and then do whatever we wish when a collision happens: + +```lua +-- in Player.lua +function Player:update(dt) + if self.collider:enter('Enemy') then + local collision_data = self.collider:getEnterCollisionData('Enemy') + local enemy = collision_data.collider:getObject() + -- Kills the enemy on hit but also take damage + enemy:die() + self:takeDamage(10) + end +end +``` + +
+ +## One-way Platforms + +A common problem people have with using 2D physics engines seems to be getting one-way platforms to work. Here's one way to achieve this with this library: + +```lua +function love.load() + world = wf.newWorld(0, 512, true) + world:addCollisionClass('Platform') + world:addCollisionClass('Player') + + ground = world:newRectangleCollider(100, 500, 600, 50) + ground:setType('static') + platform = world:newRectangleCollider(350, 400, 100, 20) + platform:setType('static') + platform:setCollisionClass('Platform') + player = world:newRectangleCollider(390, 450, 20, 40) + player:setCollisionClass('Player') + + player:setPreSolve(function(collider_1, collider_2, contact) + if collider_1.collision_class == 'Player' and collider_2.collision_class == 'Platform' then + local px, py = collider_1:getPosition() + local pw, ph = 20, 40 + local tx, ty = collider_2:getPosition() + local tw, th = 100, 20 + if py + ph/2 > ty - th/2 then contact:setEnabled(false) end + end + end) +end + +function love.keypressed(key) + if key == 'space' then + player:applyLinearImpulse(0, -1000) + end +end +``` + +And that looks like this: + +

+ +

+ +The way this works is that by disabling the contact before collision response is applied (so in the preSolve callback) we can make a collider ignore another. And then all we do is check to see if the player is below platform, and if he is then we disable the contact. + +
+ +# Documentation + +## World + +On top of containing all functions exposed in this documentation it also contains all functions of a [box2d World](https://love2d.org/wiki/World). + +--- + +#### `.newWorld(xg, yg, sleep)` + +Creates a new World. + +```lua +world = wf.newWorld(0, 0, true) +``` + +Arguments: + +* `xg` `(number)` - The world's x gravity component +* `yg` `(number)` - The world's y gravity component +* `sleep=true` `(boolean)` - If the world's bodies are allowed to sleep or not + +Returns: + +* `World` `(table)` - the World object, containing all attributes and methods defined below as well as all of a [box2d World](https://love2d.org/wiki/World) + + +--- + +#### `:update(dt)` + +Updates the world. + +```lua +world:update(dt) +``` + +Arguments: + +* `dt` `(number)` - The time step delta + +--- + +#### `:draw(alpha)` + +Draws the world, drawing all colliders, joints and world queries (for debugging purposes). + +```lua +world:draw() -- default drawing +world:draw(128) -- semi transparent drawing +``` + +Arguments: + +* `alpha=255` `(number)` - The optional alpha value to use when drawing, defaults to 255 + +--- + +#### `:destroy()` + +Destroys the world and removes all bodies, fixtures, shapes and joints from it. This must be called whenever the World is to discarded otherwise it will result in it not getting collected (and so memory will leak). + +```lua +world:destroy() +``` + +--- + +#### `:addCollisionClass(collision_class_name, collision_class)` + +Adds a new collision class to the World. Collision classes are attached to Colliders and defined their behaviors in terms of which ones will physically ignore each other and which ones will generate collision events between each other. All collision classes must be added before any Collider is created. If `world:setExplicitCollisionEvents` is set to false (the default setting) then `enter`, `exit`, `pre` and `post` settings don't need to be specified, otherwise they do. +```lua +world:addCollisionClass('Player', {ignores = {'NPC', 'Enemy'}}) +``` + +Arguments: + +* `collision_class_name` `(string)` - The unique name of the collision class +* `collision_class` `(table)` - The collision class. This table can contain: + +Settings: + +* `[ignores]` `(table[string])` - The collision classes that will be physically ignored +* `[enter]` `(table[string])` - The collision classes that will generate collision events with the collider of this collision class when they enter contact with each other +* `[exit]` `(table[string])` - The collision classes that will generate collision events with the collider of this collision class when they exit contact with each other +* `[pre]` `(table[string])` - The collision classes that will generate collision events with the collider of this collision class right before collision response is applied +* `[post]` `(table[string])` - The collision classes that will generate collision events with the collider of this collision class right after collision response is applied + +--- + +#### `:newCircleCollider(x, y, r)` + +Creates a new CircleCollider. + +```lua +circle = world:newCircleCollider(100, 100, 30) +``` + +Arguments: + +* `x` `(number)` - The x position of the circle's center +* `y` `(number)` - The y position of the circle's center +* `r` `(number)` - The radius of the circle + +Returns: + +* `Collider` `(table)` - The newly created CircleCollider + +--- + +#### `:newRectangleCollider(x, y, w, h)` + +Creates a new RectangleCollider. + +```lua +rectangle = world:newRectangleCollider(100, 100, 50, 50) +``` + +Arguments: + +* `x` `(number)` - The x position of the rectangle's top-left corner +* `y` `(number)` - The y position of the rectangle's top-left corner +* `w` `(number)` - The width of the rectangle +* `h` `(number)` - The height of the rectangle + +Returns: + +* `Collider` `(table)` - The newly created RectangleCollider + +--- + +#### `:newBSGRectangleCollider(x, y, w, h, corner_cut_size)` + +Creates a new BSGRectangleCollider, which is a rectangle with its corners cut (an octagon). + +```lua +bsg_rectangle = world:newBSGRectangleCollider(100, 100, 50, 50, 5) +``` + +Arguments: + +* `x` `(number)` - The x position of the rectangle's top-left corner +* `y` `(number)` - The y position of the rectangle's top-left corner +* `w` `(number)` - The width of the rectangle +* `h` `(number)` - The height of the rectangle +* `corner_cut_size` `(number)` - The corner cut size + +Returns: + +* `Collider` `(table)` - The newly created BSGRectangleCollider + +--- + +#### `:newPolygonCollider(vertices)` + +Creates a new PolygonCollider. + +```lua +polygon = world:newPolygonCollider({10, 10, 10, 20, 20, 20, 20, 10}) +``` + +Arguments: + +* `vertices` `(table[number])` - The polygon vertices as a table of numbers + +Returns: + +* `Collider` `(table)` - The newly created PolygonCollider + +--- + +#### `:newLineCollider(x1, y1, x2, y2)` + +Creates a new LineCollider. + +```lua +line = world:newLineCollider(100, 100, 200, 200) +``` + +Arguments: + +* `x1` `(number)` - The x position of the first point of the line +* `y1` `(number)` - The y position of the first point of the line +* `x2` `(number)` - The x position of the second point of the line +* `y2` `(number)` - The y position of the second point of the line + +Returns: + +* `Collider` `(table)` - The newly created LineCollider + +--- + +#### `:newChainCollider(vertices, loop)` + +Creates a new ChainCollider. + +```lua +chain = world:newChainCollider({10, 10, 10, 20, 20, 20}, true) +``` + +Arguments: + +* `vertices` `(table[number])` - The chain vertices as a table of numbers +* `loop` `(boolean)` - If the chain should loop back from the last to the first point + +Returns: + +* `Collider` `(table)` - The newly created ChainCollider + +--- + +#### `:queryCircleArea(x, y, r, collision_class_names)` + +Queries a circular area around a point for colliders. + +```lua +colliders_1 = world:queryCircleArea(100, 100, 50, {'Enemy', 'NPC'}) +colliders_2 = world:queryCircleArea(100, 100, 50, {'All', except = {'Player'}}) +``` + +Arguments: + +* `x` `(number)` - The x position of the circle's center +* `y` `(number)` - The y position of the circle's center +* `r` `(number)` - The radius of the circle +* `[collision_class_names='All']` `(table[string])` - A table of strings with collision class names to be queried. The special value `'All'` (default) can be used to query for all existing collision classes. Another special value `except` can be used to exclude some collision classes when `'All'` is used. + +Returns: + +* `table[Collider]` - The table of colliders with the specified collision classes inside the area + +--- + +#### `:queryRectangleArea(x, y, w, h, collision_class_names)` + +Queries a rectangular area for colliders. + +```lua +colliders_1 = world:queryRectangleArea(100, 100, 50, 50, {'Enemy', 'NPC'}) +colliders_2 = world:queryRectangleArea(100, 100, 50, 50, {'All', except = {'Player'}}) +``` + +Arguments: + +* `x` `(number)` - The x position of the rectangle's top-left corner +* `y` `(number)` - The y position of the rectangle's top-left corner +* `w` `(number)` - The width of the rectangle +* `h` `(number)` - The height of the rectangle +* `[collision_class_names='All']` `(table[string])` - A table of strings with collision class names to be queried. The special value `'All'` (default) can be used to query for all existing collision classes. Another special value `except` can be used to exclude some collision classes when `'All'` is used. + +Returns: + +* `table[Collider]` - The table of colliders with the specified collision classes inside the area + +--- + +#### `:queryPolygonArea(vertices, collision_class_names)` + +Queries a polygon area for colliders. + +```lua +colliders_1 = world:queryPolygonArea({10, 10, 20, 10, 20, 20, 10, 20}, {'Enemy'}) +colliders_2 = world:queryPolygonArea({10, 10, 20, 10, 20, 20, 10, 20}, {'All', except = {'Player'}}) +``` + +Arguments: + +* `vertices` `(table[number])` - The polygon vertices as a table of numbers +* `[collision_class_names='All']` `(table[string])` - A table of strings with collision class names to be queried. The special value `'All'` (default) can be used to query for all existing collision classes. Another special value `except` can be used to exclude some collision classes when `'All'` is used. + +Returns: + +* `table[Collider]` - The table of colliders with the specified collision classes inside the area + +--- + +#### `:queryLine(x1, y1, x2, y2, collision_class_names)` + +Queries for colliders that intersect with a line. + +```lua +colliders_1 = world:queryLine(100, 100, 200, 200, {'Enemy', 'NPC', 'Projectile'}) +colliders_2 = world:queryLine(100, 100, 200, 200, {'All', except = {'Player'}}) +``` + +Arguments: + +* `x1` `(number)` - The x position of the first point of the line +* `y1` `(number)` - The y position of the first point of the line +* `x2` `(number)` - The x position of the second point of the line +* `y2` `(number)` - The y position of the second point of the line +* `[collision_class_names='All']` `(table[string])` - A table of strings with collision class names to be queried. The special value `'All'` (default) can be used to query for all existing collision classes. Another special value `except` can be used to exclude some collision classes when `'All'` is used. + +Returns: + +* `table[Collider]` - The table of colliders with the specified collision classes inside the area + +--- + +#### `:addJoint(joint_type, ...)` + +Adds a joint to the world. + +```lua +joint = world:addJoint('RevoluteJoint', collider_1, collider_2, 50, 50, true) +``` + +Arguments: + +* `joint_type` `(string)` - The joint type, it can be `'DistanceJoint'`, `'FrictionJoint'`, `'GearJoint'`, `'MouseJoint'`, `'PrismaticJoint'`, `'PulleyJoint'`, `'RevoluteJoint'`, `'RopeJoint'`, `'WeldJoint'` or `'WheelJoint'` +* `...` `(*)` - The joint creation arguments that are different for each joint type, check [here](https://love2d.org/wiki/Joint) for more details + +Returns: + +* `joint` `(Joint)` - The newly created Joint + +--- + +#### `:removeJoint(joint)` + +Removes a joint from the world. + +```lua +joint = world:addJoint('RevoluteJoint', collider_1, collider_2, 50, 50, true) +world:removeJoint(joint) +``` + +Arguments: + +* `joint` `(Joint)` - The joint to be removed + +--- + +#### `:setExplicitCollisionEvents(value)` + +Sets collision events to be explicit or not. If explicit, then collision events will only be generated between collision classes when they are specified in `addCollisionClasses`. By default this is set to false, meaning that collision events are generated between all collision classes. The main reason why you might want to set this to true is for performance, since not generating collision events between every collision class will require less computation. This function must be called before any collision class is added to the world. + +```lua +world:setExplicitCollisionEvents(true) +``` + +Arguments: + +* `value` `(boolean)` - If collision events are explicit or not + +--- + +#### `:setQueryDebugDrawing(value)` + +Sets query debug drawing to be active or not. If active, then collider queries will be drawn to the screen for 10 frames. This is used for debugging purposes and incurs a performance penalty. Don't forget to turn it off! + +```lua +world:setQueryDebugDrawing(true) +``` + +Arguments: + +* `value` `(boolean)` - If query debug drawing is active or not + +--- + +## Collider + +On top of containing all functions exposed in this documentation it also contains all functions of a [Body](https://love2d.org/wiki/Body), [Fixture](https://love2d.org/wiki/Fixture) and [Shape](https://love2d.org/wiki/Shape). + +--- + +#### `:destroy()` + +Destroys the collider and removes it from the world. This must be called whenever the Collider is to discarded otherwise it will result in it not getting collected (and so memory will leak). + +```lua +collider:destroy() +``` + +--- + +#### `:setCollisionClass(collision_class_name)` + +Sets this collider's collision class. The collision class must be a valid one previously added with `world:addCollisionClass`. + +```lua +world:addCollisionClass('Player') +collider = world:newRectangleCollider(100, 100, 50, 50) +collider:setCollisionClass('Player') +``` + +Arguments: + +* `collision_class_name` `(string)` - The name of the collision class + +--- + +#### `:enter(other_collision_class_name)` + +Checks for collision enter events from this collider with another. Enter events are generated on the frame when one collider enters contact with another. + +```lua +-- in some update function +if collider:enter('Enemy') then + print('Collision entered!') +end +``` + +Arguments: + +* `other_collision_class_name` `(string)` - The name of the target collision class + +Returns: + +* `boolean` - If the enter collision event between both colliders happened on this frame or not + +--- + +#### `:getEnterCollisionData(other_collision_class_name)` + +Gets the collision data generated from the last collision enter event + +```lua +-- in some update function +if collider:enter('Enemy') then + local collision_data = collider:getEnterCollisionData('Enemy') + print(collision_data.collider, collision_data.contact) +end +``` + +Arguments: + +* `other_collision_class_name` `(string)` - The name of the target collision class + +Returns: + +* `collision_data` `(table[Collider, Contact])` - A table containing the Collider and the [Contact](https://love2d.org/wiki/Contact) generated from the last enter collision event + +--- + +#### `:exit(other_collision_class_name)` + +Checks for collision exit events from this collider with another. Exit events are generated on the frame when one collider exits contact with another. + +```lua +-- in some update function +if collider:exit('Enemy') then + print('Collision exited!') +end +``` + +Arguments: + +* `other_collision_class_name` `(string)` - The name of the target collision class + +Returns: + +* `boolean` - If the exit collision event between both colliders happened on this frame or not + +--- + +#### `:getExitCollisionData(other_collision_class_name)` + +Gets the collision data generated from the last collision exit event + +```lua +-- in some update function +if collider:exit('Enemy') then + local collision_data = collider:getEnterCollisionData('Enemy') + print(collision_data.collider, collision_data.contact) +end +``` + +Arguments: + +* `other_collision_class_name` `(string)` - The name of the target collision class + +Returns: + +* `collision_data` `(table[Collider, Contact])` - A table containing the Collider and the [Contact](https://love2d.org/wiki/Contact) generated from the last exit collision event + +--- + +#### `:stay(other_collision_class_name)` + +Checks for collision stay events from this collider with another. Stay events are generated on every frame when one collider is in contact with another. + +```lua +-- in some update function +if collider:stay('Enemy') then + print('Collision staying!') +end +``` + +Arguments: + +* `other_collision_class_name` `(string)` - The name of the target collision class + +Returns: + +* `boolean` - If the stay collision event between both colliders is happening on this frame or not + +--- + +#### `:getStayCollisionData(other_collision_class_name)` + +Gets the collision data generated from the last collision stay event + +```lua +-- in some update function +if collider:stay('Enemy') then + local collision_data_list = collider:getStayCollisionData('Enemy') + for _, collision_data in ipairs(collision_data_list) do + print(collision_data.collider, collision_data.contact) + end +end +``` + +Arguments: + +* `other_collision_class_name` `(string)` - The name of the target collision class + +Returns: + +* `collision_data_list` `(table[table[Collider, Contact]])` - A table containing multiple Colliders and [Contacts](https://love2d.org/wiki/Contact) generated from the last stay collision event. Usually this list will be of size 1, but sometimes this collider will be staying in contact with multiple other colliders on the same frame, and so those multiple stay events (with multiple colliders) are returned. + +--- + +#### `:setPreSolve(callback)` + +Sets the preSolve callback. Unlike with `:enter` or `:exit` that can be delayed and checked after the physics simulation is done for this frame, both preSolve and postSolve must be callbacks that are resolved immediately, since they may change how the rest of the simulation plays out on this frame. + +```lua +collider:setPreSolve(function(collider_1, collider_2, contact) + contact:setEnabled(false) +end +``` + +Arguments: + +* `callback` `(function)` - The preSolve callback. Receives `collider_1`, `collider_2` and `contact` as arguments + +--- + +#### `:setPostSolve(callback)` + +Sets the postSolve callback. Unlike with `:enter` or `:exit` that can be delayed and checked after the physics simulation is done for this frame, both preSolve and postSolve must be callbacks that are resolved immediately, since they may change how the rest of the simulation plays out on this frame. + +```lua +collider:setPostSolve(function(collider_1, collider_2, contact, ni1, ti1, ni2, ti2) + contact:setEnabled(false) +end +``` + +Arguments: + +* `callback` `(function)` - The postSolve callback. Receives `collider_1`, `collider_2`, `contact`, `normal_impulse1`, `tangent_impulse1`, `normal_impulse2` and `tangent_impulse2` as arguments + +--- + +#### `:addShape(shape_name, shape_type, ...)` + +Adds a shape to the collider. A shape can be accessed via collider.shapes[shape_name]. A fixture of the same name is also added to attach the shape to the collider body. A fixture can be accessed via collider.fixtures[fixture_name]. + +Arguments: + +* `shape_name` `(string)` - The unique name of the shape +* `shape_type` `(string)` - The shape type, can be `'ChainShape'`, `'CircleShape'`, `'EdgeShape'`, `'PolygonShape'` or `'RectangleShape'` +* `...` `(*)` - The shape creation arguments that are different for each shape. Check [here](https://love2d.org/wiki/Shape) for more details + +--- + +#### `:removeShape(shape_name)` + +Removes a shape from the collider (also removes the accompanying fixture). + +Arguments: + +* `shape_name` `(string)` - The unique name of the shape to be removed. Must be a name previously added with `:addShape` + +--- + +#### `:setObject(object)` + +Sets the collider's object. This is useful to set to the object the collider belongs to, so that when a query call is made and colliders are returned you can immediately get the pertinent object. + +```lua +-- in the constructor of some object +self.collider = world:newRectangleCollider(...) +self.collider:setObject(self) +``` + +Arguments: + +* `object` `(*)` - The object that this collider belongs to + +--- + +#### `:getObject()` + +Gets the object a collider belongs to. + +```lua +-- in an update function +if self.collider:enter('Enemy') then + local collision_data = self.collider:getEnterCollisionData('SomeTag') + -- gets the reference to the enemy object, the enemy object must have used :setObject(self) to attach itself to the collider otherwise this wouldn't work + local enemy = collision_data.collider:getObject() +end +``` + +Returns: + +* `object` `(*)` - The object that is attached to this collider + +--- + +# LICENSE + +You can do whatever you want with this. See the license at the top of the main file. diff --git a/lib/windfield/init.lua b/lib/windfield/init.lua new file mode 100644 index 0000000..8554822 --- /dev/null +++ b/lib/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/lib/windfield/mlib/Changes.txt b/lib/windfield/mlib/Changes.txt new file mode 100644 index 0000000..1b41d50 --- /dev/null +++ b/lib/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/lib/windfield/mlib/LICENSE.md b/lib/windfield/mlib/LICENSE.md new file mode 100644 index 0000000..0e7071e --- /dev/null +++ b/lib/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/lib/windfield/mlib/README.md b/lib/windfield/mlib/README.md new file mode 100644 index 0000000..a5efed3 --- /dev/null +++ b/lib/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/lib/windfield/mlib/mlib.lua b/lib/windfield/mlib/mlib.lua new file mode 100644 index 0000000..76067c6 --- /dev/null +++ b/lib/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..872aeb0 --- /dev/null +++ b/main.lua @@ -0,0 +1,535 @@ +-- pls set tabs to width of 4 spaces +class = require "lib/middleclass" +wind = require "lib/windfield" +stalker = require "lib/STALKER-X" + +downwall = 1; rightwall = 2; leftwall = 3 +mainmenu = 0; game = 1; gameover = 2; pause = 3 + +world = wind.newWorld(0, 400, true) + +-- GAME STATES +-------------------------------------------------------------------------------- +-- LOVE +---------------------------------------- +function love.load () + math.randomseed(os.time()) + + dieParticle = nil + love.graphics.setDefaultFilter("nearest", "nearest") +-- a_ttf = love.graphics.newFont("art/font/alagard.ttf", nil, "none") + +-- mainmenu_load() + game_load() +end + + +function love.update(dt) + if(mode == mainmenu) then mainmenu_update(dt) + elseif(mode == game) then game_update(dt) + elseif(mode == gameover) then gameover_update(dt) + elseif(mode == pause) then pause_update(dt) + end +end + + +function love.draw () + if(mode == mainmenu) then mainmenu_draw() + elseif(mode == game) then game_draw() + elseif(mode == gameover) then gameover_draw() + elseif(mode == pause) then pause_draw() + end +end + + +function love.keypressed(key) + if(mode == mainmenu) then mainmenu_keypressed(key) + elseif(mode == game) then game_keypressed(key) + elseif(mode == gameover) then gameover_keypressed(key) + elseif(mode == pause) then pause_keypressed(key) + end +end + + +function love.keyreleased (key) + if(mode == mainmenu) then mainmenu_keyreleased(key) + elseif(mode == game) then game_keyreleased(key) + elseif(mode == gameover) then gameover_keyreleased(key) + elseif(mode == pause) then pause_keyreleased(key) + end +end + + +-- MENU STATE +---------------------------------------- +function mainmenu_load () + mode = mainmenu + selection = 1 +-- if(bgm) then +-- bgm:stop() +-- end +-- bgm = love.audio.newSource("art/music/menu.ogg", "static") +-- bgm:play() +-- bgm:setLooping(true) +-- bgm:setVolume(1.5) +-- +-- frontMenu = Menu:new(100, 100, 30, 50, 2, +-- { { love.graphics.newText(a_ttf, "get bannana!"), +-- function () game_load() end }, +-- { love.graphics.newText(a_ttf, "get help!"), +-- function () helpScreen = true end }, +-- { love.graphics.newText(a_ttf, "get outta dodge!"), +-- function () love.event.quit(0) end } }) +end + + +function mainmenu_update(dt) +end + + +function mainmenu_draw () +end + + +function mainmenu_keypressed(key) +end + + +function mainmenu_keyreleased(key) +end + + + +-- PAUSE STATE +---------------------------------------- +function pause_load () +end + + +function pause_update(dt) +end + + +function pause_draw () +end + + +function pause_keypressed(key) +end + + +function pause_keyreleased(key) +end + + +-- GAMEOVER STATE +---------------------------------------- +function gameover_load () +end + + +function gameover_update(dt) +end + + +function gameover_draw () + game_draw() +end + + +function gameover_keypressed(key) + if(key == "return" or key == "escape") then + mainmenu_load() + end +end + + +function gameover_keyreleased(key) +end + + + +-- GAME STATE +---------------------------------------- +function game_load () + mode = game + map = Map:new("maps/tutorial/1.lua") + camera = stalker() + camera:setFollowStyle('PLATFORMER') + camera:setFollowLerp(0.1) + +-- bgm:stop() +-- bgm = love.audio.newSource("art/music/game.ogg", "static") +-- bgm:play() +end + + +function game_update(dt) + world:update(dt) + player:update(dt) + map:update(dt) + + local x, y = player.monks[player.current].body:getPosition() + camera:update(dt) + camera:follow(x, y) +end + + +function game_draw () + camera:attach() + + map:draw() + player:draw() + + camera:detach() + camera:draw() +end + + +function game_keypressed(key) + local dir = player.directionals + + -- if a player presses the left key, then holds the right key, they should + -- go right until they let go, then they should go left. + if (key == "right" or key == "d") then + dir['right'] = 1 + if (dir['left'] == 1) then dir['left'] = 2; end + elseif (key == "left" or key == "a") then + dir['left'] = 1 + if (dir['right'] == 1) then dir['right'] = 2; end + elseif (key == "up" or key == "w") then + dir['up'] = 1 + if (dir['down'] == 1) then dir['down'] = 2; end + + elseif (key == "space") then + player:freeze() + + elseif (key == "f" and player.following == false) then + player.following = true + elseif (key == "f" and player.following == true) then + player.following = false + end +end + + +function game_keyreleased (key) + local dir = player.directionals + local monk = player.monks[player.current] + local dx, dy = monk:getLinearVelocity() + + if (key == "right" or key == "d") then + dir['right'] = 0 + monk:setLinearVelocity(dx - 150, dy) + elseif (key == "left" or key == "a") then + dir['left'] = 0 + monk:setLinearVelocity(dx + 150, dy) + elseif (key == "up" or key == "w") then + dir['up'] = 0 + elseif (key == "down") then + dir['down'] = 0 + end +end + + + +-- CLASSES +-------------------------------------------------------------------------------- +-- MONK player class +---------------------------------------- +Monk = class('Monk') +world:addCollisionClass('Monk') + +function Monk:initialize(x, y, count) + self.monks = {} + self.onGround = {} + self.current = 0 + self.last = count - 1 + self.following = false + self.directionals = {} + + self.monkSprites = {} + self.sprites ={ + ['default'] = love.graphics.newImage("art/sprites/monk.png"), + ['jump'] = love.graphics.newImage("art/sprites/monk-jump.png"), + ['frozen'] = love.graphics.newImage("art/sprites/monk-frozen.png") } + + for i=0,(count-1) do + self.monks[i] = world:newRectangleCollider(x - (i * 20), y, 16, 16); + self.monks[i]:setCollisionClass('Monk') + self.monks[i]:setObject(self) + self.monkSprites[i] = 'default' + + local collision = self:makeCollisionCallback(i) + self.monks[i]:setPreSolve(collision) + self.onGround[i] = 0 + end +end + + +function Monk:update(dt) + local dir = self.directionals + + if (self.following == true) then self:follow() + else self:idle() + end + + self:movement() + + for i=0,(self.last) do + if (self.onGround[i] > 0) then self.monkSprites[i] = 'default' + else self.monkSprites[i] = 'jump' + end + end + + -- cleanup + for i=0,(self.last) do + self.onGround[i] = 0 + end + if (dir['left'] == 2 and dir['right'] == 0) then dir['left'] = 1; end + if (dir['right'] == 2 and dir['left'] == 0) then dir['right'] = 1; end +end + + +function Monk:draw () + -- live monkeys + for i=self.current,self.last do + local monk = self.monks[i] + local x,y = monk.body:getWorldPoints(monk.shape:getPoints()) + + love.graphics.draw(self.sprites[self.monkSprites[i]], x, y, + monk.body:getAngle(), 1, 1) + end + -- frozen monkeys + for i=0,self.current-1 do + local monk = self.monks[i] + local x,y = monk.body:getWorldPoints(monk.shape:getPoints()) + + love.graphics.draw(self.sprites['frozen'], x, y, monk.body:getAngle(), + 1, 1) + end +end + + +function Monk:movement () + local monk = self.monks[self.current] + local dx, dy = monk:getLinearVelocity() + local dir = self.directionals + local newVel = 250 + local onGround = self.onGround[self.current] + + if not (onGround == downwall) then + newVel = newVel - 50 + end + + if (dir['left'] == 1) then + monk:setLinearVelocity(-newVel, dy); + elseif (dir['right'] == 1) then + monk:setLinearVelocity(newVel, dy); + end + + if (dir['up'] == 1 and onGround == downwall) then + monk:setLinearVelocity(dx, -newVel); + elseif (dir['up'] == 1 and onGround == leftwall) then + monk:setLinearVelocity(newVel, -newVel - 30); + elseif (dir['up'] == 1 and onGround == rightwall) then + monk:setLinearVelocity(-newVel, -newVel - 30); + end +end + + +-- try to get non-player monkeys in party to rougly follow player +function Monk:follow () + if (self.current == self.last) then return 0; end + + local monk = self.monks[self.current] + local x, y = monk.body:getPosition() + local newVel = 300 + if (self.onGround[self.current] == 0) then + newVel = newVel - 50 + end + + for i=self.current+1,self.last do + local thisMonk = self.monks[i] + local mx, my = thisMonk.body:getPosition() + local dx, dy = thisMonk:getLinearVelocity() + + if (mx < (x + 30)) then + thisMonk:setLinearVelocity(newVel, dy) + elseif ((x - 30) < mx) then + thisMonk:setLinearVelocity(-newVel, dy) + end + + if (y < my and self.onGround[i] == downwall) then + thisMonk:setLinearVelocity(dx, -newVel) + end + end +end + + +-- non-player monkeys hop every second-ish idly +function Monk:idle () + if (self.current == self.last) then return; end + + for i=self.current+1,self.last do + if (self.onGround[i] == downwall and math.random(20) == 5) then + local thisMonk = self.monks[i] + local dx, dy = thisMonk:getLinearVelocity() + self.monks[i]:setLinearVelocity(dx, -100) + end + end +end + + +-- freeze the player monkey in place, making it a platform +function Monk:freeze () + if not (self.current > self.last) then + local monk = self.monks[self.current] + monk:setType('static') + monk:setCollisionClass('Platform') + self:switch(self.current + 1) + end +end + + +-- switch from current monkey to next +function Monk:switch (index) + self.current = index + if (index > self.last) then + gameover_load() + end +end + + +-- each monkey in party needs a unique callback +function Monk:makeCollisionCallback (i) + local function collision(collision1, collision2, contact) + local nx, ny = contact:getNormal( ) + + if collision1.collision_class == "Monk" + and collision2.collision_class == "Platform" + then + if (math.abs(ny) == 1) then + self.onGround[i] = downwall + elseif (nx < 0) then + if not (self.onGround[i] == 0) then return; end + self.onGround[i] = leftwall + elseif (nx > 0) then + if not (self.onGround[i] == 0) then return; end + self.onGround[i] = rightwall + end + end + end + return collision +end + + + +-- MAP used to store map data (ofc) +---------------------------------------- +Map = class('Map') +world:addCollisionClass('Platform') + +function Map:initialize(filepath) + self.ground = {} + self.platforms = {} + self.objects = {} + self.object_c = 0 + local maptable = dofile(filepath) + + love.graphics.setBackgroundColor(146/255, 187/255, 203/255) + + for n,layer in pairs(maptable.layers) do + if not (layer.type == "objectgroup") then break; end + for nn,object in pairs(layer.objects) do + + if (object.shape == "rectangle") then + self.object_c = self.object_c + 1 + local o_c = self.object_c + self.objects[o_c] = + world:newRectangleCollider(object.x, object.y, + object.width, object.height) + self.objects[o_c]:setType('static') + self.objects[o_c]:setCollisionClass('Platform') + + elseif (object.shape == "point" and object.type == "spawn") then + local monkCount = 3 + if not (object.properties == nil + and object.properties["count"] == nil) then + monkCount = object.properties["count"] + end + player = Monk:new(object.x, object.y, monkCount) + end + end + end +end + + +function Map:update(dt) +end + + +function Map:draw() + for k,object in pairs(self.objects) do + love.graphics.polygon('fill', + object.body:getWorldPoints(object.shape:getPoints())) + end +end + + + +-- MENU used for creating menus (lol) +---------------------------------------- +Menu = class("Menu") + +function Menu:initialize(x, y, offset_x, offset_y, scale, menuItems) + self.x = x; self.y = y + self.offset_x = offset_x; self.offset_y = offset_y + self.scale = scale + self.options = menuItems + self.selected = 1 + self.enter = false + self.up = false + self.down = false +end + +function Menu:draw () +-- love.graphics.draw(love.graphics.newText(a_ttf, ">>"), +-- self.x - self.offset_x, this_y, 0, +-- self.scale, self.scale) +end + +function Menu:keypressed(key) + maxn = table.maxn(self.options) + + if(key == "return" and self.enter == false) then + self.enter = true + if(self.options[self.selected][2]) then + self.options[self.selected][2]() + end + elseif(key == "up" and self.selected > 1 and self.up == false) then + self.up = true + self.selected = self.selected - 1 + elseif(key == "up" and self.up == false) then + self.up = true + self.selected = maxn + elseif(key == "down" and self.selected < maxn and self.down == false) then + self.down = true + self.selected = self.selected + 1 + elseif(key == "down" and self.down == false) then + self.down = true + self.selected = 1 + end +end + + +function Menu:keyreleased(key) + if(key == "return") then + self.enter = false + elseif(key == "up") then + self.up = false + elseif(key == "down") then + self.down = false + end +end + + diff --git a/maps/README.txt b/maps/README.txt new file mode 100644 index 0000000..8f49e5d --- /dev/null +++ b/maps/README.txt @@ -0,0 +1,12 @@ +MAP EDITING +================================================================================ +Monkune maps are made using Tiled (https://mapeditor.org), and are made up of +rectangle objects and text-boxes. No tilesets are used. + +Rectangles will be filled with a random color. +Text-box formatting will be ignored, but the text is used. + +You can set the spawn point of the monkey party with a point object of type +"spawn". Otherwise, it defaults to (100,100). + +Export your map to Lua, put it in a custom "maps" folder, and you're good to go! diff --git a/maps/tutorial/1.lua b/maps/tutorial/1.lua new file mode 100644 index 0000000..aec8612 --- /dev/null +++ b/maps/tutorial/1.lua @@ -0,0 +1,363 @@ +return { + version = "1.4", + luaversion = "5.1", + tiledversion = "1.4.3", + orientation = "orthogonal", + renderorder = "right-down", + width = 100, + height = 100, + tilewidth = 16, + tileheight = 16, + nextlayerid = 5, + nextobjectid = 34, + properties = {}, + tilesets = {}, + layers = { + { + type = "objectgroup", + draworder = "topdown", + id = 2, + name = "Object Layer 1", + visible = true, + opacity = 1, + offsetx = 0, + offsety = 0, + properties = {}, + objects = { + { + id = 2, + name = "hi", + type = "", + shape = "text", + x = 37.6276, + y = 34.1667, + width = 94.08, + height = 17, + rotation = 0, + visible = true, + text = "Hello, monkeys.", + wrap = true, + properties = {} + }, + { + id = 30, + name = "", + type = "", + shape = "text", + x = 132.961, + y = 50.8333, + width = 82.0781, + height = 17, + rotation = 0, + visible = true, + text = "You're hungry, aren't you?", + wrap = true, + properties = {} + }, + { + id = 31, + name = "", + type = "", + shape = "text", + x = 230.294, + y = 70.8333, + width = 82.0781, + height = 17, + rotation = 0, + visible = true, + text = "Go on ahead, then.", + wrap = true, + properties = {} + } + } + }, + { + type = "objectgroup", + draworder = "topdown", + id = 3, + name = "Object Layer 2", + visible = true, + opacity = 1, + offsetx = 0, + offsety = 0, + properties = {}, + objects = { + { + id = 4, + name = "", + type = "", + shape = "rectangle", + x = 18, + y = 94, + width = 460.667, + height = 415.333, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 6, + name = "", + type = "", + shape = "rectangle", + x = 481.333, + y = 113.333, + width = 29.3333, + height = 397.333, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 7, + name = "", + type = "", + shape = "rectangle", + x = 512.667, + y = 128.667, + width = 30, + height = 383.333, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 10, + name = "", + type = "", + shape = "rectangle", + x = 545.333, + y = 145.333, + width = 29.3333, + height = 366.667, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 11, + name = "", + type = "", + shape = "rectangle", + x = 576, + y = 159.333, + width = 31.3333, + height = 352.667, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 13, + name = "", + type = "", + shape = "rectangle", + x = 607.333, + y = 176.667, + width = 32.6667, + height = 336, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 14, + name = "", + type = "", + shape = "rectangle", + x = 640.667, + y = 192, + width = 31.3333, + height = 320.667, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 15, + name = "", + type = "", + shape = "rectangle", + x = 672.667, + y = 208, + width = 30.6667, + height = 304, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 16, + name = "", + type = "", + shape = "rectangle", + x = 703.333, + y = 224, + width = 33.3333, + height = 288, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 17, + name = "", + type = "", + shape = "rectangle", + x = 737.333, + y = 240, + width = 30.6667, + height = 272.667, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 18, + name = "", + type = "", + shape = "rectangle", + x = 768.667, + y = 255.333, + width = 30.6667, + height = 256.667, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 19, + name = "", + type = "", + shape = "rectangle", + x = 799.333, + y = 272, + width = 33.3333, + height = 240, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 20, + name = "", + type = "", + shape = "rectangle", + x = 832.667, + y = 288, + width = 30.6667, + height = 224, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 21, + name = "", + type = "", + shape = "rectangle", + x = 864, + y = 303.333, + width = 32, + height = 208.667, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 22, + name = "", + type = "", + shape = "rectangle", + x = 895.333, + y = 320, + width = 32, + height = 191.333, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 23, + name = "", + type = "", + shape = "rectangle", + x = 927.333, + y = 336, + width = 30.6667, + height = 176, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 24, + name = "", + type = "", + shape = "rectangle", + x = 959.333, + y = 353.333, + width = 30.6667, + height = 157.333, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 26, + name = "", + type = "", + shape = "rectangle", + x = 989.333, + y = 367.333, + width = 34.6667, + height = 143.333, + rotation = 0, + visible = true, + properties = {} + }, + { + id = 29, + name = "", + type = "", + shape = "rectangle", + x = 1024, + y = 384.667, + width = 224, + height = 126.667, + rotation = 0, + visible = true, + properties = {} + } + } + }, + { + type = "objectgroup", + draworder = "topdown", + id = 4, + name = "Object Layer 3", + visible = true, + opacity = 1, + offsetx = 0, + offsety = 0, + properties = {}, + objects = { + { + id = 32, + name = "", + type = "spawn", + shape = "point", + x = 93, + y = 80, + width = 0, + height = 0, + rotation = 0, + visible = true, + properties = { + ["count"] = 4 + } + } + } + } + } +} diff --git a/maps/tutorial/1.tmx b/maps/tutorial/1.tmx new file mode 100644 index 0000000..244016f --- /dev/null +++ b/maps/tutorial/1.tmx @@ -0,0 +1,46 @@ + + + + + + + + Hello, monkeys. + + + You're hungry, aren't you? + + + Go on ahead, then. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +