This commit is contained in:
Jaidyn Ann 2021-02-05 20:58:58 -06:00
commit 7074fe6d2e
42 changed files with 9752 additions and 0 deletions

674
COPYING.txt Normal file
View File

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

26
Makefile Normal file
View File

@ -0,0 +1,26 @@
love:
zip -9r bin/horsehorse.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/horsehorse-win32
rm bin/horsehorse-win32/changes.txt
rm bin/horsehorse-win32/readme.txt
rm bin/horsehorse-win32/lovec.exe
cat bin/horsehorse.love >> bin/horsehorse-win32/love.exe
mv bin/horsehorse-win32/love.exe bin/horsehorse-win32/HorseHorse.exe
cp lib/bin-license.txt bin/horsehorse-win32/license.txt
zip -9jr bin/horsehorse-win32.zip bin/horsehorse-win32
rm -rf bin/horsehorse-win32
test: love
love bin/horsehorse.love
clean:
rm -rf ./bin/*
all: love win32

20
README.txt Normal file
View File

@ -0,0 +1,20 @@
HORSEHORSE
================================================================================
HorseHorse is an tank-control dual-ish game, where valiant non-horses are pitted
against one another.
Made for Librejam 2020-02, with the theme "SUBNAUTICAL."
RUNNING
--------------------------------------------------
LINUX/UNIX/HAIKU
--------------------
Make sure love2d is installed with your package manager, and then:
$ make test
BORING STUFF
--------------------------------------------------
Jaidyn Ann <jadedctrl@teknik.io>
Code under GPLv3 (see COPYING.txt)
Art assets all under the CC-BY 3.0

5
art/COPYING.txt Normal file
View File

@ -0,0 +1,5 @@
All art assets are licensed under Free Culture licenses that allow
(commercial) redistribution, modification, etc.
Each asset (under the "art" directory) has a corresponding text-file with
the author, the source URL, and licensing information.

BIN
art/font/alagard.ttf Normal file

Binary file not shown.

3
art/font/alagard.txt Normal file
View File

@ -0,0 +1,3 @@
Author: Pix3M
Source: https://opengameart.org/content/pixel-fonts-by-pix3m
License: CC-BY 3.0

BIN
art/font/romulus.ttf Normal file

Binary file not shown.

3
art/font/romulus.txt Normal file
View File

@ -0,0 +1,3 @@
Author: Pix3M
Source: https://opengameart.org/content/pixel-fonts-by-pix3m
License: CC-BY 3.0

5
conf.lua Normal file
View File

@ -0,0 +1,5 @@
function love.conf(t)
t.window.resizable = true
t.window.title = "HorseHorse"
t.window.vsync = 0
end

7
lib/COPYING.txt Normal file
View File

@ -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.

808
lib/STALKER-X/README.md Normal file
View File

@ -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)
<br>
# Quick Start
Place the `Camera.lua` file inside your project and require it:
```lua
Camera = require 'Camera'
```
<br>
## 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.
<br>
## 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:
<p align="center">
<img src="https://i.imgur.com/CmGYXxW.gif"/>
</p>
<br>
## 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:
<p align="center">
<img src="https://i.imgur.com/qtdTzU6.gif"/>
</p>
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
```
<p align="center">
<img src="https://i.imgur.com/ZcOZ6n6.gif"/>
</p>
<br>
## 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
```
<p align="center">
<img src="https://i.imgur.com/9NCOySe.gif"/>
</p>
### PLATFORMER
```lua
function love.load()
camera = Camera()
camera:setFollowStyle('PLATFORMER')
end
```
<p align="center">
<img src="https://i.imgur.com/eNny8VU.gif"/>
</p>
### TOPDOWN
```lua
function love.load()
camera = Camera()
camera:setFollowStyle('TOPDOWN')
end
```
<p align="center">
<img src="https://i.imgur.com/eA57zFd.gif"/>
</p>
### TOPDOWN_TIGHT
```lua
function love.load()
camera = Camera()
camera:setFollowStyle('TOPDOWN_TIGHT')
end
```
<p align="center">
<img src="https://i.imgur.com/FqiTqOM.gif"/>
</p>
### 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
```
<p align="center">
<img src="https://i.imgur.com/SN1S0Jo.gif"/>
</p>
### 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
```
<p align="center">
<img src="https://i.imgur.com/TBQE88l.gif"/>
</p>
### 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:
<p align="center">
<img src="https://i.imgur.com/rDpdvRI.gif"/>
</p>
<br>
## 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.
<p align="center">
<img src="https://i.imgur.com/0GaczA3.gif"/>
</p>
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.
<br>
## 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:
<p align="center">
<img src="https://i.imgur.com/UkhiyzE.gif"/>
</p>
<br>
## 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}`.
<p align="center">
<img src="https://i.imgur.com/o3r2noG.gif"/>
</p>
<br>
# 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.
<br>
## 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)
```
<br>
# 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
---
<br>
# LICENSE
You can do whatever you want with this. See the license at the top of the main file.

369
lib/STALKER-X/init.lua Normal file
View File

@ -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})

1183
lib/bin-license.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -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

View File

@ -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(<name>)` have no superclass now)
* Removed default method `Class:implements(<mixin>)`
* 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

View File

@ -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.

80
lib/middleclass/README.md Normal file
View File

@ -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.

View File

@ -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(<name>)` 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`.

183
lib/middleclass/init.lua Normal file
View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

941
lib/windfield/README.md Normal file
View File

@ -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)
<br>
# Quick Start
Place the `windfield` folder inside your project and require it:
```lua
wf = require 'windfield'
```
<br>
## 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
```
<br>
## 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:
<p align="center">
<img src="http://i.imgur.com/ytfhmjc.gif"/>
</p>
<br>
## 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:
<p align="center">
<img src="http://i.imgur.com/tSqkxJR.gif"/>
</p>
<br>
## 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:
<p align="center">
<img src="http://i.imgur.com/j7IhVSe.gif"/>
</p>
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.
<br>
## 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:
<p align="center">
<img src="http://i.imgur.com/uF1bqKM.gif"/>
</p>
<br>
## 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:
<p align="center">
<img src="http://i.imgur.com/YVxAiuu.gif"/>
</p>
<br>
# 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
```
<br>
## 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:
<p align="center">
<img src="http://i.imgur.com/ouwxVRH.gif"/>
</p>
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.
<br>
# 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.

929
lib/windfield/init.lua Normal file
View File

@ -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

View File

@ -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

View File

@ -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.

View File

@ -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

1152
lib/windfield/mlib/mlib.lua Normal file

File diff suppressed because it is too large Load Diff

499
main.lua Normal file
View File

@ -0,0 +1,499 @@
-- pls set tabs to width of 4 spaces
class = require "lib/middleclass"
wind = require "lib/windfield"
stalker = require "lib/STALKER-X"
mainmenu = 0; game = 1; gameover = 2; pause = 3; youwin = 4
world = wind.newWorld(0, 40, 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")
r_ttf = love.graphics.newFont("art/font/romulus.ttf", nil, "none")
camera = stalker()
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 == youwin) then youwin_update(dt)
elseif(mode == pause) then pause_update(dt)
end
camera:update(dt)
end
function love.draw()
camera:attach()
if(mode == mainmenu) then mainmenu_draw()
elseif(mode == game) then game_draw()
elseif(mode == gameover) then gameover_draw()
elseif(mode == youwin) then youwin_draw()
elseif(mode == pause) then pause_draw()
end
camera:detach()
camera:draw()
end
function love.resize()
camera = stalker()
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 == youwin) then youwin_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 == youwin) then youwin_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/default.mp3", "static")
-- bgm:play()
-- bgm:setLooping(true)
-- bgm:setVolume(1.5)
frontMenu = nil
frontMenu_init()
camera = stalker()
map = Map:new("maps/sys/menu.lua")
end
function mainmenu_update(dt)
if not (mapMenu == nil) then return; end
world:update(dt)
player:update(dt)
map:update(dt)
-- make player monkey move randomly
local num = math.random(100)
local dirs = player.directionals
if (num == 1) then
dirs['left'] = 1
dirs['right'] = 0
elseif (num == 2) then
dirs['right'] = 1
dirs['left'] = 0
elseif (num == 3) then
dirs['up'] = 1
end
end
function mainmenu_draw ()
if (mapMenu == nil) then
map:draw()
player:draw()
frontMenu:draw()
else
mapMenu:draw()
end
end
function mainmenu_keypressed(key)
if (mapMenu == nil) then
frontMenu:keypressed(key)
else
mapMenu:keypressed(key)
end
end
function mainmenu_keyreleased(key)
if (mapMenu == nil) then
frontMenu:keyreleased(key)
else
mapMenu:keyreleased(key)
end
end
function frontMenu_init()
frontMenu = Menu:new(100, 100, 30, 50, 3, {
{love.graphics.newText(a_ttf, ""),
function () mapMenu_init() end},
-- camera:fade(.2, {0,0,0,1}, function() mapMenu_init() end)
-- 2, {0,0,0,1}, function() mapMenu_init() end)
-- end},
{love.graphics.newText(a_ttf, "Quit"),
function () love.event.quit(0) end }})
mapMenu = nil
end
function mapMenu_init(directory)
directory = directory or "maps"
local menuEntries = {[1] = {love.graphics.newText(a_ttf, "../"),
function () mainmenu_load() end}}
-- if (directory == "maps") then mainmenu_load()
local indice = 2
local files = love.filesystem.getDirectoryItems(directory)
for k,file in pairs(files) do
file = directory .. "/" .. file
local filetype = love.filesystem.getInfo(file).type
local fileSplit = split(file, ".")
local fileExt = fileSplit[2] or ""
if (filetype == "directory") then
menuEntries[indice] = {love.graphics.newText(a_ttf, file .. "/"),
function() mapMenu_init(file) end}
indice = indice + 1
elseif (filetype == "file" and fileExt == "lua") then
menuEntries[indice] = {love.graphics.newText(a_ttf, fileSplit[1]),
function() game_load(file) end}
indice = indice + 1
end
end
mapMenu = Menu:new(100, 100, 30, 50, 3, menuEntries)
frontMenu = nil
end
-- PAUSE STATE
----------------------------------------
function pause_load()
if(bgm) then
bgm:stop()
end
mode = pause
end
function pause_update(dt)
end
function pause_draw ()
game_draw()
camera:detach()
love.graphics.draw(love.graphics.newText(r_ttf,
"paused\n[enter to continue]\n[escape to exit]"), 200, 200, 0, 3, 3)
camera:attach()
end
function pause_keypressed(key)
if (key == "return") then
if(bgm) then
bgm:play()
end
mode = game
elseif (key == "escape") then
mainmenu_load()
end
end
function pause_keyreleased(key)
end
-- GAMEOVER STATE
----------------------------------------
function gameover_load ()
mode = gameover
end
function gameover_update(dt)
end
function gameover_draw ()
game_draw()
camera:detach()
love.graphics.draw(love.graphics.newText(r_ttf,
"nice try!\n[enter to restart]\n[escape to exit]"), 200, 200, 0, 3, 3)
camera:attach()
end
function gameover_keypressed(key)
if (key == "return" or key == "space") then
camera:fade(.2, {0,0,0,1}, function() game_load() end)
elseif (key == "escape") then
mainmenu_load()
end
end
function gameover_keyreleased(key)
end
-- GAME STATE
----------------------------------------
function game_load(mapfile)
mode = game
world:destroy()
world = wind.newWorld(0, 400, true)
world:addCollisionClass('Fighter')
-- mapfile = mapfile or map.filepath
-- map = Map:new(mapfile)
player = Fighter:new(100, 100)
camera:fade(.2, {0,0,0,0})
camera:setFollowLerp(0.1)
camera:setFollowStyle('PLATFORMER')
-- 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.body:getPosition()
camera:follow(x, y)
end
function game_draw ()
-- map:draw()
world:draw()
player: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 == "=" and camera.scale < 10) then
camera.scale = camera.scale + .5
elseif (key == "-" and camera.scale > .5) then
camera.scale = camera.scale - .5
elseif (key == "escape") then
pause_load()
end
end
function game_keyreleased (key)
local dir = player.directionals
local dx, dy = player.body:getLinearVelocity()
if (key == "right" or key == "d") then
dir['right'] = 0
player.body:setLinearVelocity(dx - 150, dy)
elseif (key == "left" or key == "a") then
dir['left'] = 0
player.body: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
----------------------------------------
Fighter = class('Fighter')
function Fighter:initialize(x, y)
self.directionals = {}
-- self.sprite = love.graphics.newImage("art/sprites/monk-jump.png")
self.body = world:newRectangleCollider(x, y, 16, 16);
self.body:setCollisionClass('Fighter')
self.body:setObject(self)
end
function Fighter:update(dt)
local dir = self.directionals
if (self.following == true) then self:follow()
else self:idle()
end
self:movement()
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 Fighter:draw ()
-- local x,y = self.body:getWorldPoints(monk.shape:getPoints())
-- love.graphics.draw(self.sprite, x, y, monk.body:getAngle(), 1, 1)
-- end
end
function Fighter:movement ()
local dx, dy = self.body:getLinearVelocity()
local dir = self.directionals
local newVel = 250
if not (self.onGround == downwall) then
newVel = newVel - 50
end
if (dir['left'] == 1) then
self.body:setLinearVelocity(-newVel, dy);
elseif (dir['right'] == 1) then
self.body:setLinearVelocity(newVel, dy);
end
if (dir['up'] == 1 and onGround == downwall) then
self.body:setLinearVelocity(dx, -newVel);
elseif (dir['up'] == 1 and onGround == leftwall) then
self.body:setLinearVelocity(newVel, -newVel - 30);
elseif (dir['up'] == 1 and onGround == rightwall) then
self.body:setLinearVelocity(-newVel, -newVel - 30);
end
end
-- Fighter should jitter when inactive, every once in a while
function Fighter:idle ()
-- if (self.onGround[i] == downwall and math.random(20) == 5) then
-- end
end
-- MENU used for creating menus (lol)
----------------------------------------
Menu = class("Menu")
function Menu:initialize(x, y, offset_x, offset_y, scale, menuItems)
self.x,self.y = x,y
self.offset_x,self.offset_y = offset_x,offset_y
self.options = menuItems
self.selected = 1
self.scale = scale
self.keys = {}
self.keys['up'] = false
self.keys['down'] = false
self.keys['enter'] = false
self.ttf = r_ttf
end
function Menu:draw ()
for i=1,table.maxn(self.options) do
local this_y = self.y + (self.offset_y * i)
love.graphics.draw(self.options[i][1],
self.x, this_y, 0, self.scale, self.scale)
if (i == self.selected) then
love.graphics.draw(love.graphics.newText(self.ttf, ">>"),
self.x - self.offset_x, this_y, 0, self.scale, self.scale)
end
end
end
function Menu:keypressed(key)
maxn = table.maxn(self.options)
if (key == "return" or key == "space") then
self.keys['enter'] = true
if(self.options[self.selected][2]) then
self.options[self.selected][2]()
end
elseif (key == "up" and self.selected > 1
and self.keys['up'] == false) then
self.keys['up'] = true
self.selected = self.selected - 1
elseif (key == "up" and self.keys['up'] == false) then
self.keys['up'] = true
self.selected = maxn
elseif (key == "down" and self.selected < maxn
and self.keys['down'] == false) then
self.keys['down'] = true
self.selected = self.selected + 1
elseif (key == "down" and self.keys['down'] == false) then
self.keys['down'] = true
self.selected = 1
end
end
function Menu:keyreleased(key)
if (key == "return" or key == "space") then
self.keys['enter'] = false
elseif (key == "up") then
self.keys['up'] = false
elseif (key == "down") then
self.keys['down'] = false
end
end
function split(inputString, seperator)
local newString = {}
for stringBit in string.gmatch(inputString, "([^"..seperator.."]+)") do
table.insert(newString, stringBit)
end
return newString
end