diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..f74659f --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,651 @@ +GNU Affero General Public License +================================= + +_Version 3, 19 November 2007_ +_Copyright © 2007 Free Software Foundation, Inc. _ + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +## Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + +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. + +Developers that use our General Public Licenses protect your rights +with two steps: **(1)** assert copyright on the software, and **(2)** offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + +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 Affero 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. Remote Network Interaction; Use with the GNU General Public License + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + +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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + +### 14. Revised Versions of this License + +The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +### 16. Limitation of Liability + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16 + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +_END OF TERMS AND CONDITIONS_ + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the “copyright” line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a “Source” link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + +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 AGPL, see + diff --git a/core/pom.xml b/core/pom.xml index c6b83ae..7c7d199 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -35,6 +35,12 @@ 1.21.1-R0.1-SNAPSHOT provided + + org.bukkit + bukkit + 1.21.1-R0.1-SNAPSHOT + compile + com.comphenix.protocol ProtocolLib @@ -54,18 +60,6 @@ fastboard 2.1.3 - - org.spigotmc - spigot-api - 1.21.1-R0.1-SNAPSHOT - compile - - - org.bukkit - bukkit - 1.21.1-R0.1-SNAPSHOT - compile - org.bukkit bukkit diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/Config.java b/core/src/main/java/org/ef3d0c3e/sheepwars/Config.java new file mode 100644 index 0000000..adfc217 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/Config.java @@ -0,0 +1,16 @@ +package org.ef3d0c3e.sheepwars; + +import org.ef3d0c3e.sheepwars.config.BaseConfig; + +import java.io.File; + +public class Config extends BaseConfig +{ + public Config(File path) + { + super(path); + } + + public String LOBBY_WORLD; + public String GAME_WORLD; +} diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/SheepWars.java b/core/src/main/java/org/ef3d0c3e/sheepwars/SheepWars.java index 8336de9..716ddec 100644 --- a/core/src/main/java/org/ef3d0c3e/sheepwars/SheepWars.java +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/SheepWars.java @@ -1,21 +1,262 @@ package org.ef3d0c3e.sheepwars; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import lombok.Getter; import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; +import org.ef3d0c3e.sheepwars.events.CPlayerJoinEvent; +import org.ef3d0c3e.sheepwars.events.EventListenerFactory; +import org.ef3d0c3e.sheepwars.game.Game; +import org.ef3d0c3e.sheepwars.level.VoidChunkGenerator; +import org.ef3d0c3e.sheepwars.locale.LocaleManager; +import org.ef3d0c3e.sheepwars.player.CPlayer; +import org.ef3d0c3e.sheepwars.versions.WrapperFactory; +import org.jetbrains.annotations.NotNull; + +import java.io.*; +import java.text.MessageFormat; +import java.util.Enumeration; +import java.util.EventListener; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; public final class SheepWars extends JavaPlugin { + @Getter + private static Plugin plugin; + @Getter + private static ProtocolManager protocolManager; + @Getter + private static Config sheepWarsConfig; + @Getter + private static LocaleManager localeManager; + @Override public void onLoad() { + consoleMessage("--[ Setting up... ]--"); + // Extract resources + if (!saveResources()) + return; + + // Load configurations + sheepWarsConfig = new Config(new File(getDataFolder() + "/config.yml")); + localeManager = new LocaleManager(new File(getDataFolder() + "/locales")); + + // Modify the server's config + boolean needRestart = false; + // server.properties + { + consoleMessage("Overwriting 'server.properties'..."); + + final File properties = new File("server.properties"); + final StringBuffer buffer = new StringBuffer(); + try + { + // Modify properties line by line + final BufferedReader reader = new BufferedReader(new FileReader(properties)); + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + if (line.startsWith("level-name=world")) + { + needRestart = true; + buffer.append("level-name=" + sheepWarsConfig.LOBBY_WORLD); + } + else if (line.startsWith("allow-nether=true")) + { + buffer.append("allow-nether=false"); + needRestart = true; + } + else + buffer.append(line); + + buffer.append('\n'); + } + reader.close(); + + // Write buffer + final FileOutputStream out = new FileOutputStream(properties); + out.write(buffer.toString().getBytes()); + out.close(); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + + } + + { + consoleMessage("Overwriting 'bukkit.yml'..."); + + final File bukkit = new File("bukkit.yml"); + YamlConfiguration bukkitYml = new YamlConfiguration(); + + // Modify using YML + try + { + bukkitYml.load(bukkit); + bukkitYml.set("settings.allow-end", false); + + if (bukkitYml.get("worlds." + sheepWarsConfig.LOBBY_WORLD + ".generator") == null) + { + bukkitYml.set("worlds." + sheepWarsConfig.LOBBY_WORLD + ".generator", "SheepWars"); + needRestart = true; + } + if (bukkitYml.get("worlds." + sheepWarsConfig.GAME_WORLD + ".generator") == null) + { + bukkitYml.set("worlds." + sheepWarsConfig.GAME_WORLD + ".generator", "SheepWars"); + } + + bukkitYml.save(bukkit); + } + catch (IOException | InvalidConfigurationException e) + { + throw new RuntimeException(e); + } + } + + if (needRestart) + { + consoleMessage("Server restart needed. Please restart your server"); + Bukkit.shutdown(); + } + + // Resolve version wrappers for current Minecraft version + try + { + WrapperFactory.resolveWrappers(); + } + catch (Exception e) + { + e.printStackTrace(); + } + + consoleMessage("--[ Setup done ]--"); } @Override public void onDisable() { - Bukkit.getServer().getConsoleSender().sendMessage("§8[§aSheepWars§8]:§7 Plugin disabled"); + consoleMessage("Plugin Disabled!"); } @Override public void onEnable() { - Bukkit.getServer().getConsoleSender().sendMessage("§8[§aSheepWars§8]:§7 Plugin enabled!"); + plugin = this; + protocolManager = ProtocolLibrary.getProtocolManager(); + + // Factories + try { + EventListenerFactory.create(); + } + catch (Exception e) + { + e.printStackTrace(); + return; + } + + Game.init(); + + // Useful when /reloading + for (final Player p : Bukkit.getOnlinePlayers()) + { + CPlayer.add(p); + } + CPlayer.forEach(cp -> { + getServer().getPluginManager().callEvent(new CPlayerJoinEvent(cp, true)); + }); + + consoleMessage("Plugin Enabled!"); + } + + @Override + public ChunkGenerator getDefaultWorldGenerator(@NotNull String worldName, String id) + { + return new VoidChunkGenerator(); + } + + + /** + * Writes message to console using plugin's prefix + * @param message Message to write + */ + public static void consoleMessage(final String message) + { + Bukkit.getConsoleSender().sendMessage("§8[§9§lSheepWars§8]:§7 " + message); + } + + /** + * Writes a debug message to the console + * @param message Message to write + */ + public static void debugMessage(final String message) + { + Bukkit.getConsoleSender().sendMessage("§d§lSW/Debug:§f " + message); + } + + /** + * Extract all resources from the jar into the 'plugins/SheepWars' directory + */ + boolean saveResources() + { + if (getDataFolder().exists()) + { + consoleMessage("Using resources from 'SheepWars'"); + return true; + } + + // Create 'plugins/SheepWars' + consoleMessage("Creating resource directory..."); + try { + if (!getDataFolder().mkdirs()) + return false; + } + catch (SecurityException e) { + e.printStackTrace(); + return false; + } + + // Iterate over plugin's jar + try + { + final JarFile jar = new JarFile(getClass().getProtectionDomain().getCodeSource().getLocation().getFile()); + Bukkit.getConsoleSender().sendMessage(jar.toString()); + Enumeration entries = (Enumeration)jar.entries(); + while (entries.hasMoreElements()) + { + JarEntry ent = entries.nextElement(); + if (!ent.getName().startsWith("exports/")) continue; + Bukkit.getConsoleSender().sendMessage(ent.getName()); + final String stripped = ent.getName().substring("exports/".length()); + if (stripped.isEmpty()) continue; + + final File file = new File(getDataFolder() + "/" + stripped); + if (!file.getName().contains(".")) // Directory + continue; + + // File + if (!file.getParentFile().exists()) file.getParentFile().mkdirs(); + file.createNewFile(); + + OutputStream out = new FileOutputStream(file); + InputStream in = jar.getInputStream(ent); + in.transferTo(out); + out.close(); + in.close(); + + consoleMessage(MessageFormat.format("Created file ''{0}''.", file.getAbsolutePath())); + } + } + catch (IOException e) + { + e.printStackTrace(); + return false; + } + + return true; } } diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/config/AnyLocation.java b/core/src/main/java/org/ef3d0c3e/sheepwars/config/AnyLocation.java new file mode 100644 index 0000000..0d42d62 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/config/AnyLocation.java @@ -0,0 +1,30 @@ +package org.ef3d0c3e.sheepwars.config; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Location; +import org.bukkit.World; + +/** + * Location without world, useful for config + */ +@AllArgsConstructor +public class AnyLocation +{ + @Getter @Setter + public double x, y, z; + @Getter @Setter + public float pitch, yaw; + + /** + * Gets location from AnyLocation + * @param world World + * @return Location + */ + public Location getLocation(final World world) + { + return new Location(world, x, y, z, pitch, yaw); + } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/config/BaseConfig.java b/core/src/main/java/org/ef3d0c3e/sheepwars/config/BaseConfig.java new file mode 100644 index 0000000..4cd0296 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/config/BaseConfig.java @@ -0,0 +1,121 @@ +package org.ef3d0c3e.sheepwars.config; + +import com.google.common.base.CaseFormat; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.util.Vector; +import org.ef3d0c3e.sheepwars.SheepWars; +//import org.ef3d0c3e.sheepwars.locale.Locale; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.text.MessageFormat; +import java.util.HashSet; +import java.util.List; + +/** + * Derive this class to create a config-exportable class + * For non-exportable fields, @see @ConfigExclude + */ +public abstract class BaseConfig +{ + /** + * Format the name of identifiers to YML format + * @param name Identifier name + * @return Identifier name in YML + */ + private static String formatName(String name) + { + return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name); + } + + @ConfigExclude + private File configFile; + + /** + * Constructor + * @param path Config YML file path + */ + public BaseConfig(final File path) + { + this.configFile = path; + YamlConfiguration config = new YamlConfiguration(); + try + { + config.load(path); + } + catch (IOException | InvalidConfigurationException e) + { + e.printStackTrace(); + } + + deserialize(config); + } + + /** + * Loads config from YML + */ + private void deserialize(final YamlConfiguration config) + { + final Field[] fields = this.getClass().getDeclaredFields(); + final HashSet setFields = new HashSet<>(); + + for (final Field f : fields) + { + if (f.getAnnotation(ConfigExclude.class) != null) continue; + + final String name = formatName(f.getName()).replace('-', '.'); + + if (config.contains(name)) + { + try + { + if (f.getType().equals(String.class)) // String + f.set(this, config.get(name)); + else if (f.getType().equals(int.class)) // int + f.set(this, config.getInt(name)); + else if (f.getType().equals(double.class)) // double + f.set(this, config.getDouble(name)); + else if (f.getType().equals(Vector.class)) // Vector + { + final List lst = config.getDoubleList(name); + if (lst.size() != 3) throw new Exception("In " + configFile.getName() + ": While parsing `" + name + "`: Invalid number of elements for Vector expected 3 got " + lst.size()); + f.set(this, new Vector(lst.get(0), lst.get(1), lst.get(2))); + } + else if (f.getType().equals(AnyLocation.class)) + { + final List lst = config.getDoubleList(name); + if (lst.size() != 5) throw new Exception("In " + configFile.getName() + ": While parsing `" + name + "`: Invalid number of elements for AnyLocation expected 5 got " + lst.size()); + f.set(this, new AnyLocation(lst.get(0), lst.get(1), lst.get(2), lst.get(3).floatValue(), lst.get(4).floatValue())); + } + else if (f.getType().equals(List.class)) + f.set(this, config.getStringList(name)); + else + throw new IllegalArgumentException("Field `" + f.getName() + "` of type " + f.getType().getName() + " cannot be parsed."); + + setFields.add(f); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + else + { + Bukkit.getConsoleSender().sendMessage(MessageFormat.format("In `{0}`: Unknown config variable: {1}", configFile.getName(), name)); + } + } + + // Verify + for (final Field f : fields) + { + if (setFields.contains(f)) continue; + + SheepWars.consoleMessage(MessageFormat.format("In `{0}`: Missing variable in config: {1}", configFile.getName(), formatName(f.getName()))); + } + + } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/config/ConfigExclude.java b/core/src/main/java/org/ef3d0c3e/sheepwars/config/ConfigExclude.java new file mode 100644 index 0000000..296cd34 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/config/ConfigExclude.java @@ -0,0 +1,16 @@ +package org.ef3d0c3e.sheepwars.config; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Use this annotation to exclude a field from being exported to a configuration file + */ +@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.SOURCE) +public @interface ConfigExclude +{ +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/events/CPlayerJoinEvent.java b/core/src/main/java/org/ef3d0c3e/sheepwars/events/CPlayerJoinEvent.java new file mode 100644 index 0000000..04eedb7 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/events/CPlayerJoinEvent.java @@ -0,0 +1,39 @@ +package org.ef3d0c3e.sheepwars.events; + +import lombok.Getter; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.ef3d0c3e.sheepwars.player.CPlayer; + + +public class CPlayerJoinEvent extends Event +{ + private static final HandlerList HANDLERS_LIST = new HandlerList(); + + public static HandlerList getHandlerList() + { + return HANDLERS_LIST; + } + @Override + public HandlerList getHandlers() + { + return HANDLERS_LIST; + } + + @Getter + final private CPlayer player; + @Getter + final private boolean newPlayer; + + /** + * Constructor + * @param cp Player + * @param newPlayer Whether player is a new player or not (first time joining) + */ + public CPlayerJoinEvent(final CPlayer cp, final boolean newPlayer) + { + this.player = cp; + this.newPlayer = newPlayer; + } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/events/CPlayerQuitEvent.java b/core/src/main/java/org/ef3d0c3e/sheepwars/events/CPlayerQuitEvent.java new file mode 100644 index 0000000..bbf9aff --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/events/CPlayerQuitEvent.java @@ -0,0 +1,34 @@ +package org.ef3d0c3e.sheepwars.events; + +import lombok.Getter; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.ef3d0c3e.sheepwars.player.CPlayer; + + +public class CPlayerQuitEvent extends Event +{ + private static final HandlerList HANDLERS_LIST = new HandlerList(); + + public static HandlerList getHandlerList() + { + return HANDLERS_LIST; + } + @Override + public HandlerList getHandlers() + { + return HANDLERS_LIST; + } + + @Getter + final private CPlayer player; + + /** + * Constructor + * @param cp Player + */ + public CPlayerQuitEvent(final CPlayer cp) + { + this.player = cp; + } +} diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/events/EventListenerFactory.java b/core/src/main/java/org/ef3d0c3e/sheepwars/events/EventListenerFactory.java new file mode 100644 index 0000000..c01cf87 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/events/EventListenerFactory.java @@ -0,0 +1,89 @@ +package org.ef3d0c3e.sheepwars.events; + +import org.bukkit.Bukkit; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.ef3d0c3e.sheepwars.SheepWars; +import org.reflections.Reflections; +import org.reflections.scanners.Scanners; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class EventListenerFactory +{ + static private final HashSet> registrableClasses = new HashSet<>(); + static private final HashSet registeredClasses = new HashSet<>(); + + public static void create() throws Exception + { + final Reflections refl = new Reflections("org.ef3d0c3e.sheepwars"); + + // Classes + final Set> classes = refl.getSubTypesOf(Listener.class); + for (final Class clz : classes) + { + if (clz.getAnnotation(WantsListen.class) == null) + throw new Exception("Listener " + clz.getName() + " is missing WantsListen annotation"); + + registrableClasses.add(clz); + } + } + + /** + * Registers all listeners for the current phase + * Unregisters unneeded listeners + * @param phase Current phase + */ + public static void update(final WantsListen.Target phase) + { + // Un register + for (Iterator it = registeredClasses.iterator(); it.hasNext();) + { + final Listener listener = it.next(); + final WantsListen.Target target = listener.getClass().getAnnotation(WantsListen.class).phase(); + + if (target.isCompatible(phase)) continue; + + HandlerList.unregisterAll(listener); + it.remove(); + SheepWars.debugMessage("Unregistered listener " + listener.getClass().getName()); + } + + // Register + for (final Class clz : registrableClasses) + { + final WantsListen.Target target = clz.getAnnotation(WantsListen.class).phase(); + + if (!target.isCompatible(phase)) continue; + + boolean shouldRegister = true; + // Check if not already registered + for (final Listener l : registeredClasses) + { + if (!l.getClass().equals(clz)) continue; + + shouldRegister = false; + break; + } + if (!shouldRegister) continue; + + try + { + final Listener l = clz.getDeclaredConstructor().newInstance(); + + registeredClasses.add(l); + Bukkit.getPluginManager().registerEvents(l, SheepWars.getPlugin()); + SheepWars.debugMessage("Registered listener " + l.getClass().getName()); + } + catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) + { + e.printStackTrace(); + } + } + } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/events/Events.java b/core/src/main/java/org/ef3d0c3e/sheepwars/events/Events.java new file mode 100644 index 0000000..b680a26 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/events/Events.java @@ -0,0 +1,43 @@ +package org.ef3d0c3e.sheepwars.events; + +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.ef3d0c3e.sheepwars.player.CPlayer; + +/** + * Transforms minecraft's events to events for SheepWars + * Mainly used for wrapping the player into the CPlayer wrapper + */ +@WantsListen(phase = WantsListen.Target.Always) +public class Events implements Listener { + @EventHandler + public void onJoin(final PlayerJoinEvent ev) + { + ev.setJoinMessage(null); + + CPlayer cp = CPlayer.get(ev.getPlayer()); + boolean newPlayer = false; + if (cp == null) // New player + Bukkit.getPluginManager().callEvent(new CPlayerJoinEvent( + CPlayer.add(ev.getPlayer()), true)); + else + { + // Update + cp.setHandle(ev.getPlayer()); + Bukkit.getPluginManager().callEvent(new CPlayerJoinEvent(cp, false)); + } + + } + + @EventHandler + public void onQuit(final PlayerQuitEvent ev) + { + ev.setQuitMessage(null); + + Bukkit.getPluginManager().callEvent(new CPlayerQuitEvent(CPlayer.get(ev.getPlayer()))); + } + +} diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/events/WantsListen.java b/core/src/main/java/org/ef3d0c3e/sheepwars/events/WantsListen.java new file mode 100644 index 0000000..062bfb8 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/events/WantsListen.java @@ -0,0 +1,43 @@ +package org.ef3d0c3e.sheepwars.events; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface WantsListen +{ + enum Target + { + None(0b000), + Lobby(0b001), + Game(0b010), + End(0b100), + Always(0b111); + + private int flag; + + /** + * Gets whether two game phases are compatible + * @param other Other game phase + * @return true if both phase are compatible + */ + public boolean isCompatible(final Target other) + { + return (other.flag & this.flag) != 0; + } + + public String toBitSet() { return Integer.toBinaryString(flag); } + + Target(int flag) + { + this.flag = flag; + } + } + + + Target phase(); +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/game/Game.java b/core/src/main/java/org/ef3d0c3e/sheepwars/game/Game.java new file mode 100644 index 0000000..25866b5 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/game/Game.java @@ -0,0 +1,62 @@ +package org.ef3d0c3e.sheepwars.game; + +import lombok.Getter; +import org.bukkit.scheduler.BukkitRunnable; +import org.ef3d0c3e.sheepwars.SheepWars; +import org.ef3d0c3e.sheepwars.events.EventListenerFactory; +import org.ef3d0c3e.sheepwars.events.WantsListen; +import org.ef3d0c3e.sheepwars.level.LevelFactory; +import org.ef3d0c3e.sheepwars.level.lobby.LobbyLevel; + +public class Game { + private static void changePhase(WantsListen.Target phase) + { + Game.phase = phase; + + EventListenerFactory.update(phase); + //TimedListenerFactory.update(phase); + //PacketListenerFactory.update(phase); + //RecipeFactory.update(phase); + } + + @Getter + private static WantsListen.Target phase; + + @Getter + private static LobbyLevel lobby; + + //@Getter + //private static GameLevel level; + + + /** + * Sets default phase to lobby + */ + static public void init() + { + changePhase(WantsListen.Target.Lobby); + + // Register levels + lobby = new LobbyLevel(); + LevelFactory.add(lobby); + //level = new GameLevel(); + //LevelFactory.add(level); + + // Create lobby world + // Game level is created once it is needeed + // @see CmdHunt + new BukkitRunnable() + { + @Override + public void run() + { + try { + lobby.create(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }.runTask(SheepWars.getPlugin()); + } + +} diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/level/Level.java b/core/src/main/java/org/ef3d0c3e/sheepwars/level/Level.java new file mode 100644 index 0000000..a87ad6d --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/level/Level.java @@ -0,0 +1,94 @@ +package org.ef3d0c3e.sheepwars.level; + +import lombok.Getter; +import lombok.NonNull; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.WorldInitEvent; +import org.ef3d0c3e.sheepwars.events.WantsListen; + +/** + * Wrapper for {@link org.bukkit.World}; + */ +public abstract class Level +{ + /** + * Constructor + * @param name World name + */ + protected Level(final @NonNull String name) + { + this.worldName = name; + } + + @Getter + private final String worldName; + @Getter + private World handle; /* World's handle */ + + /** + * Stores whether the world has been initialized yet + * The world get initialized after `postWorld()` call + */ + private boolean initialized = false; + + protected abstract @NonNull World generate() throws Exception; + + /** + * Creates world or load world + * Adds level to level list + */ + public void create() throws Exception + { + LevelFactory.add(this); + + // Try to get world handle + handle = Bukkit.getWorld(worldName); + if (handle != null) return; + + // Create World + handle = generate(); + } + + /** + * Called when world has finished initialization + * i.e. getHandle() is non-null + */ + protected void postWorld() {} + + /** + * On chunk load + * @param chunk Loaded chunk + * @param newChunk Whether loaded chuck is a new chunk + */ + protected abstract void onLoad(final Chunk chunk, boolean newChunk); + + @WantsListen(phase = WantsListen.Target.Always) + public static class Events implements Listener + { + @EventHandler + public void onChunkLoad(final ChunkLoadEvent ev) + { + final Level level = LevelFactory.get(ev.getWorld().getName()); + if (level == null) return; + if (!level.initialized) + { + level.handle = Bukkit.getWorld(level.getWorldName()); + level.postWorld(); + level.initialized = true; + } + level.onLoad(ev.getChunk(), ev.isNewChunk()); + } + + @EventHandler + public void onWorldInit(final WorldInitEvent ev) + { + ev.getWorld().setKeepSpawnInMemory(false); + } + } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/level/LevelFactory.java b/core/src/main/java/org/ef3d0c3e/sheepwars/level/LevelFactory.java new file mode 100644 index 0000000..a0db0d8 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/level/LevelFactory.java @@ -0,0 +1,19 @@ +package org.ef3d0c3e.sheepwars.level; + +import lombok.NonNull; + +import javax.annotation.Nullable; +import java.util.HashMap; + +public class LevelFactory +{ + /** + * All registered levels + */ + public static HashMap levels = new HashMap<>(); + + public static void add(final @NonNull Level l) { levels.put(l.getWorldName(), l); } + + public static @Nullable Level get(final @NonNull String name) { return levels.get(name); } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/level/VoidBiomeProvider.java b/core/src/main/java/org/ef3d0c3e/sheepwars/level/VoidBiomeProvider.java new file mode 100644 index 0000000..b3defe7 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/level/VoidBiomeProvider.java @@ -0,0 +1,28 @@ +package org.ef3d0c3e.sheepwars.level; + +import com.google.common.collect.Lists; +import org.bukkit.block.Biome; +import org.bukkit.generator.BiomeProvider; +import org.bukkit.generator.WorldInfo; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * Provides the biome for the plugin's generator + */ +public class VoidBiomeProvider extends BiomeProvider +{ + public @NotNull Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z) + { + return Biome.PLAINS; + } + + @Override + public @NotNull List getBiomes(@NotNull WorldInfo worldInfo) + { + return Lists.newArrayList(Biome.PLAINS); + } + +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/level/VoidChunkGenerator.java b/core/src/main/java/org/ef3d0c3e/sheepwars/level/VoidChunkGenerator.java new file mode 100644 index 0000000..98da3d1 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/level/VoidChunkGenerator.java @@ -0,0 +1,63 @@ +package org.ef3d0c3e.sheepwars.level; + +import org.bukkit.World; +import org.bukkit.generator.BiomeProvider; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.generator.WorldInfo; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.List; + +public class VoidChunkGenerator extends ChunkGenerator +{ + @Override + public boolean shouldGenerateNoise() + { + return false; + } + + @Override + public boolean shouldGenerateSurface() + { + return false; + } + + @Override + public boolean shouldGenerateCaves() + { + return false; + } + + @Override + public boolean shouldGenerateDecorations() + { + return false; + } + + @Override + public boolean shouldGenerateMobs() + { + return false; + } + + @Override + public boolean shouldGenerateStructures() + { + return false; + } + + @Override + public BiomeProvider getDefaultBiomeProvider(final @NotNull WorldInfo worldInfo) + { + return new VoidBiomeProvider(); + } + + @Override + public @NotNull List getDefaultPopulators(final World world) + { + return Collections.emptyList(); + } + +} \ No newline at end of file diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyConfig.java b/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyConfig.java new file mode 100644 index 0000000..7726487 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyConfig.java @@ -0,0 +1,25 @@ +package org.ef3d0c3e.sheepwars.level.lobby; + +import org.bukkit.util.Vector; +import org.ef3d0c3e.sheepwars.SheepWars; +import org.ef3d0c3e.sheepwars.config.AnyLocation; +import org.ef3d0c3e.sheepwars.config.BaseConfig; + +import java.io.File; + +public class LobbyConfig extends BaseConfig +{ + public LobbyConfig() + { + super(new File(SheepWars.getPlugin().getDataFolder() + "/lobby.yml")); + } + + public Vector OFFSET; + public AnyLocation SPAWN; + public int LIMBO; + public AnyLocation INFO; + public AnyLocation SKIN; + public AnyLocation TEAM; + public AnyLocation KIT; +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyEvents.java b/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyEvents.java new file mode 100644 index 0000000..d477f31 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyEvents.java @@ -0,0 +1,183 @@ +package org.ef3d0c3e.sheepwars.level.lobby; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.*; +import org.bukkit.event.entity.EntityDismountEvent; +import org.bukkit.event.entity.EntityMountEvent; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.PlayerInventory; +import org.ef3d0c3e.sheepwars.events.*; +import org.ef3d0c3e.sheepwars.game.Game; + +@WantsListen(phase = WantsListen.Target.Lobby) +public class LobbyEvents implements Listener +{ + @EventHandler + public void onPlayerJoin(final CPlayerJoinEvent ev) + { + if (Game.getLobby().getSpawn() != null) // For /reload only since lobby won't be null after server restart + ev.getPlayer().getHandle().teleport(Game.getLobby().getSpawn()); + + final PlayerInventory inv = ev.getPlayer().getHandle().getInventory(); + //inv.setItem(0, TeamItem.getItem(ev.getPlayer())); + //inv.setItem(1, KitItem.getItem(ev.getPlayer())); + //inv.setItem(4, RocketItem.getItem(ev.getPlayer())); + //inv.setItem(7, SkinItem.getItem(ev.getPlayer())); + } + + /* + @EventHandler + public void onTeamChange(final TeamChangeEvent ev) + { + final ItemStack replace = TeamItem.getItem(ev.getPlayer()); + if (!ItemBase.replace(ev.getPlayer().getHandle().getInventory(), TeamItem.ITEM, replace)) + ev.getPlayer().getHandle().getInventory().setItem(0, replace); + } + + @EventHandler + public void onKitChange(final KitChangeEvent ev) + { + final ItemStack replace = KitItem.getItem(ev.getPlayer()); + if (!ItemBase.replace(ev.getPlayer().getHandle().getInventory(), KitItem.ITEM, replace)) + ev.getPlayer().getHandle().getInventory().setItem(1, replace); + } + + @EventHandler + public void onSkinChange(final SkinChangeEvent ev) + { + final ItemStack replace = SkinItem.getItem(ev.getPlayer()); + if (!ItemBase.replace(ev.getPlayer().getHandle().getInventory(), SkinItem.ITEM, replace)) + ev.getPlayer().getHandle().getInventory().setItem(7, replace); + }*/ + + // Cancel all unwanted events + @EventHandler + public void onEntityInteract(final EntityInteractEvent ev) + { + if (ev.getEntity() instanceof Player && ((Player)ev.getEntity()).isOp()) + return; + + ev.setCancelled(true); + } + + @EventHandler + public void onFoodLevelChange(final FoodLevelChangeEvent ev) + { + ev.setCancelled(true); + } + + @EventHandler + public void onEntityAirChange(final EntityAirChangeEvent ev) + { + ev.setCancelled(true); + } + + @EventHandler + public void onEntityMount(final EntityMountEvent ev) + { + ev.setCancelled(true); + } + + @EventHandler + public void onEntityCombust(final EntityCombustEvent ev) + { + ev.setCancelled(true); + } + + @EventHandler + public void onEntityDamage(final EntityDamageEvent ev) + { + if (ev instanceof EntityDamageByEntityEvent) + return; + ev.setCancelled(true); + } + + @EventHandler + public void onEntityDamageByEntity(final EntityDamageByEntityEvent ev) + { + if (ev.getDamager() instanceof Player && (ev.getDamager().isOp())) + return; + ev.setCancelled(true); + } + + @EventHandler + public void onEntityDismount(final EntityDismountEvent ev) + { + ev.setCancelled(true); + } + + @EventHandler + public void onEntityDropItem(final EntityDropItemEvent ev) + { + ev.setCancelled(true); + } + + @EventHandler + public void onPlayerDropItem(final PlayerDropItemEvent ev) + { + if (ev.getPlayer().isOp()) + return; + + ev.setCancelled(true); + } + + @EventHandler + public void onEntityExhaust(final EntityExhaustionEvent ev) + { + ev.setCancelled(true); + } + + @EventHandler + public void onEntityPickupItem(final EntityPickupItemEvent ev) + { + if (ev.getEntity() instanceof Player && (ev.getEntity()).isOp()) + return; + + ev.setCancelled(true); + } + + @EventHandler + public void onEntityPlace(final EntityPlaceEvent ev) + { + if (ev.getEntity() instanceof Player && (ev.getEntity()).isOp()) + return; + + ev.setCancelled(true); + } + + @EventHandler + public void onBlockBreak(final BlockBreakEvent ev) + { + if ((ev.getPlayer()).isOp()) + return; + + ev.setCancelled(true); + } + + @EventHandler + public void onCraftItem(final CraftItemEvent ev) + { + ev.setCancelled(true); + } + + @EventHandler + public void onPlayerMoveEvent(final PlayerMoveEvent ev) + { + if (ev.getTo().getY() > Game.getLobby().getConfig().LIMBO) + return; + + ev.setTo(Game.getLobby().getSpawn()); + } + + @EventHandler + public void onDamage(final EntityDamageEvent ev) + { + ev.setCancelled(true); + } + +} diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyLevel.java b/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyLevel.java new file mode 100644 index 0000000..a130cb1 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/level/lobby/LobbyLevel.java @@ -0,0 +1,132 @@ +package org.ef3d0c3e.sheepwars.level.lobby; + +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; +import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.function.operation.Operations; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.session.ClipboardHolder; +import lombok.Getter; +import lombok.NonNull; +import org.bukkit.*; +import org.ef3d0c3e.sheepwars.SheepWars; +import org.ef3d0c3e.sheepwars.level.Level; +import org.ef3d0c3e.sheepwars.level.VoidBiomeProvider; +import org.ef3d0c3e.sheepwars.level.VoidChunkGenerator; + +import java.io.*; + +public class LobbyLevel extends Level +{ + @Getter + private final LobbyConfig config; + @Getter + private Location spawn; + + //@Getter + //private LobbyHologram hologram; + //private SkinDisplayNPC skinNpc; + //private TeamNPC teamNpc; + //private KitNPC kitNpc; + + /** + * Constructor + */ + public LobbyLevel() + { + super(SheepWars.getSheepWarsConfig().LOBBY_WORLD); + config = new LobbyConfig(); + } + + @Override + protected void postWorld() + { + spawn = config.SPAWN.getLocation(getHandle()); + + /* + hologram = new LobbyHologram(config.INFO.getLocation(getHandle())); + HologramFactory.register(hologram); + + skinNpc = new SkinDisplayNPC(config.SKIN.getLocation(getHandle())); + NPCManager.register(skinNpc); + + teamNpc = new TeamNPC(config.TEAM.getLocation(getHandle())); + NPCManager.register(teamNpc); + + kitNpc = new KitNPC(config.KIT.getLocation(getHandle())); + NPCManager.register(kitNpc); + */ + } + + @Override + protected @NonNull World generate() + { + final WorldCreator creator = new WorldCreator(getWorldName()) + .generator(new VoidChunkGenerator()) + .biomeProvider(new VoidBiomeProvider()) + .seed(0) + .environment(World.Environment.NORMAL) + .generateStructures(false) + .keepSpawnInMemory(false) + .type(WorldType.NORMAL); + + return Bukkit.createWorld(creator); + } + + @Override + protected void onLoad(final Chunk chunk, boolean newChunk) + { + if (!newChunk || + chunk.getX() != Math.round(config.SPAWN.getX()/16) || + chunk.getZ() != Math.round(config.SPAWN.getZ()/16)) + return; + + // Paste schematic + SheepWars.consoleMessage("Pasting lobby schematic..."); + try + { + File lobby = new File(SheepWars.getPlugin().getDataFolder().getAbsolutePath() + "/lobby.schem"); + ClipboardFormat format = ClipboardFormats.findByFile(lobby); + ClipboardReader reader = format.getReader(new FileInputStream(lobby)); + Clipboard clipboard = reader.read(); + + com.sk89q.worldedit.world.World adaptedWorld = BukkitAdapter.adapt(getHandle()); + EditSession editSession = WorldEdit.getInstance().newEditSession(adaptedWorld); + Operation operation = new ClipboardHolder(clipboard).createPaste(editSession) + .to(BlockVector3.at(config.OFFSET.getX(), config.OFFSET.getY(), config.OFFSET.getZ())) + .ignoreAirBlocks(true) + .build(); + + Operations.complete(operation); + editSession.close(); + + // Biome TODO + //final Location origin = new Location(ev.getWorld(), config.OFFSET.getX(), config.OFFSET.getY()+64, config.OFFSET.getZ()); + //Biomes.setBiome(origin, clipboard, Biomes.lobbyBiome); + } + catch (IOException | WorldEditException e) + { + e.printStackTrace(); + } + SheepWars.consoleMessage("Lobby generated!"); + + getHandle().setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false); + getHandle().setGameRule(GameRule.DO_WEATHER_CYCLE, false); + getHandle().setGameRule(GameRule.SEND_COMMAND_FEEDBACK, false); + getHandle().setGameRule(GameRule.RANDOM_TICK_SPEED, 0); + getHandle().setGameRule(GameRule.DO_MOB_SPAWNING, false); + getHandle().setGameRule(GameRule.DO_INSOMNIA, false); + getHandle().setGameRule(GameRule.SPAWN_RADIUS, 0); + getHandle().setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false); + getHandle().setTime(6000); + getHandle().setWeatherDuration(0); + getHandle().setSpawnLocation((int)config.SPAWN.getX(), (int)config.SPAWN.getY(), (int)config.SPAWN.getZ()); + } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/locale/Locale.java b/core/src/main/java/org/ef3d0c3e/sheepwars/locale/Locale.java new file mode 100644 index 0000000..fbb7523 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/locale/Locale.java @@ -0,0 +1,152 @@ +package org.ef3d0c3e.sheepwars.locale; + +import com.google.common.base.CaseFormat; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.lang.reflect.Field; +import java.text.MessageFormat; +import java.util.List; + +public class Locale +{ + /** + * Format the name of identifiers to YML format + * @param name Identifier name + * @return Identifier name in YML + */ + private static String formatName(String name) + { + return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name); + } + + // Config + public ItemStack CONFIG_BANNER; + public String CONFIG_NAME; + public String CONFIG_DISPLAYNAME; + + // System + public String SYSTEM_QUIT; + public String SYSTEM_JOIN; + + // Game + public String GAME_SETTINGS_RADIUSCHANGE; + public String GAME_SETTINGS_DURATIONCHANGE; + + // GUIs + public String GUI_NEXT; + public String GUI_PREVIOUS; + + // Items + public String ITEMS_RIGHTCLICK; + public String ITEMS_ROCKET; + public String ITEMS_TEAM; + public List ITEMS_TEAMLORE; + public String ITEMS_SKIN; + public List ITEMS_SKINLORE; + public String ITEMS_KIT; + public List ITEMS_KITLORE; + + // Info hologram + public String LOBBY_INFO_RADIUS; + public String LOBBY_INFO_DURATION; + + // Scoreboard + public String SCOREBOARD_TEAM; + public String SCOREBOARD_KIT; + + // Skin + public String SKIN_PICKER; + public String SKIN_NPCNAME; + public String SKIN_NPCCURRENT; + public String SKIN_MENU; + public List SKIN_MENULORE; + + // Team + public String TEAM_PICKER; + public String TEAM_NPCNAME; + public String TEAM_NPCCURRENT; + + // Kits + public String KIT_PICKER; + public String KIT_NPCNAME; + public String KIT_NPCCURRENT; + + /** + * Constructor + */ + public Locale() + { + } + + + public YamlConfiguration serialize() + { + final YamlConfiguration cfg = new YamlConfiguration(); + final Field[] fields = Locale.class.getDeclaredFields(); + + cfg.set("config.banner", CONFIG_BANNER); + + for (Field f : fields) + { + + final String name = formatName(f.getName()); + Bukkit.getConsoleSender().sendMessage(name); + try + { + if (f.getType().equals(String.class)) + cfg.set(name, f.get(this)); + else if (f.getType().equals(List.class)) + cfg.set(name, f.get(this)); + } + catch (IllegalAccessException e) + { + e.printStackTrace(); + } + } + + return cfg; + } + + public void deserialize(YamlConfiguration cfg) + { + CONFIG_BANNER = cfg.getItemStack("config.banner"); + + final Field[] fields = Locale.class.getDeclaredFields(); + for (Field f : fields) + { + final String name = formatName(f.getName()).replace('-', '.'); + + if (cfg.contains(name)) + { + try + { + if (f.getType().equals(String.class)) + f.set(this, cfg.get(name)); + else if (f.getType().equals(List.class)) + f.set(this, cfg.getStringList(name)); + } + catch (IllegalAccessException e) + { + e.printStackTrace(); + } + } + else + { + Bukkit.getConsoleSender().sendMessage(MessageFormat.format("Unknown locale string: {0}", name)); + } + } + + // Banner name + final ItemMeta meta = CONFIG_BANNER.getItemMeta(); + meta.setDisplayName("§9" + CONFIG_DISPLAYNAME); + meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + meta.addItemFlags(ItemFlag.HIDE_DYE); + CONFIG_BANNER.setItemMeta(meta); + + } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/locale/LocaleManager.java b/core/src/main/java/org/ef3d0c3e/sheepwars/locale/LocaleManager.java new file mode 100644 index 0000000..6d3d02d --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/locale/LocaleManager.java @@ -0,0 +1,68 @@ +package org.ef3d0c3e.sheepwars.locale; + +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; + +public class LocaleManager +{ + @Getter + private DirectoryStream localeDir; + @Getter + private final List locales = new ArrayList<>(); + + public Locale getDefaultLocale() + { + // TODO: config.default_locale + for (Locale l : locales) + { + if (l.CONFIG_NAME.equals("en")) + return l; + } + return locales.get(0); + } + + public LocaleManager(File dir) + { + try + { + localeDir = Files.newDirectoryStream(dir.toPath()); + } + catch (IOException e) + { + Bukkit.getServer().getLogger().log(Level.WARNING, "Unable to create/read locale directory : " + e.getMessage()); + } + + // Read locales + for (final Path p : localeDir) + { + final YamlConfiguration cfg = new YamlConfiguration(); + try + { + Bukkit.getServer().getLogger().log(Level.INFO, "Reading locale : " + p.toString()); + cfg.load(p.toFile()); + final Locale l = new Locale(); + l.deserialize(cfg); + + locales.add(l); + } + catch (IOException | InvalidConfigurationException e) + { + Bukkit.getServer().getLogger().log(Level.WARNING, "Unable to save default locale to 'en.yml' : " + e.getMessage()); + } + } + } + + public int size() { return locales.size(); } +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/player/CPlayer.java b/core/src/main/java/org/ef3d0c3e/sheepwars/player/CPlayer.java new file mode 100644 index 0000000..98a62f9 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/player/CPlayer.java @@ -0,0 +1,173 @@ +package org.ef3d0c3e.sheepwars.player; + +import lombok.Getter; +import lombok.NonNull; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.checkerframework.checker.units.qual.C; +import org.ef3d0c3e.sheepwars.SheepWars; +import org.ef3d0c3e.sheepwars.events.CPlayerJoinEvent; +import org.ef3d0c3e.sheepwars.events.CPlayerQuitEvent; +import org.ef3d0c3e.sheepwars.events.WantsListen; +import org.ef3d0c3e.sheepwars.locale.Locale; + +import javax.annotation.Nullable; +import java.text.MessageFormat; +import java.util.HashMap; + +/** + * The wrapper class for the player + */ +public class CPlayer { + /** + * Holds a list of all players that have connected on this session + */ + private static HashMap playerList = new HashMap<>(); + + /** + * Gets CPlayer from player list + * @param p Player + * @return CPlayer or null + */ + static public @Nullable CPlayer get(final Player p) + { + return playerList.get(p.getName()); + } + + /** + * Adds player to player list + * @param p Player to add + * @return Newly created player or existing player + */ + static public CPlayer add(final @NonNull Player p) + { + CPlayer cp = get(p); + if (cp != null) return cp; + + // Add + cp = new CPlayer(p); + playerList.put(p.getName(), cp); + + return cp; + } + + public interface ForEachPlayer + { + public void operation(final CPlayer cp); + } + + public interface PlayerPredicate + { + public boolean operation(final CPlayer cp); + } + + /** + * Executes lambda for all players + * @param f Lambda expression to execute on all players + */ + public static void forEach(final ForEachPlayer f) + { + for (final CPlayer cp : playerList.values()) + f.operation(cp); + } + + /** + * Executes lambda for all players + * @param pre Predicate + * @param f Lambda expression to execute on all players + */ + public static void forEach(final PlayerPredicate pre, final ForEachPlayer f) + { + for (final CPlayer cp : playerList.values()) + if (pre.operation(cp)) f.operation(cp); + } + + /** + * Executes lambda for all online players + * @param f Lambda expression to execute for all lambda players + */ + public static void forEachOnline(final ForEachPlayer f) + { + for (final CPlayer cp : playerList.values()) + if (cp.isOnline()) f.operation(cp); + } + + /** + * The player handle + */ + @Getter + private Player handle; + /** + * The OfflinePlayer handle + */ + @Getter + private OfflinePlayer offlinePlayer; + + /** + * The locale configured for the player + */ + @Getter + private Locale locale; + /** + * The player's cosmetics + */ + @Getter + private CosmeticManager cosmetics = new CosmeticManager(this); + + /** + * Updates the player handle + * @param handle New handle + */ + public void setHandle(final @NonNull Player handle) + { + this.handle = handle; + this.offlinePlayer = Bukkit.getOfflinePlayer(handle.getUniqueId()); + this.locale = SheepWars.getLocaleManager().getDefaultLocale(); + } + + + private CPlayer(@NonNull final Player handle) + { + setHandle(handle); + } + + /** + * Check if the player is online + * @return Whether player is online or not + */ + public boolean isOnline() + { + return offlinePlayer.isOnline(); + } + + /** + * Events for the player wrapper + * When a player joins or quits + */ + @WantsListen(phase = WantsListen.Target.Always) + public static class Events implements Listener + { + @EventHandler + public void onJoin(final CPlayerJoinEvent ev) + { + CPlayer.forEachOnline(cp -> + cp.getHandle().sendMessage(MessageFormat.format(cp.getLocale().SYSTEM_JOIN, ev.getPlayer().getHandle().getName())) + ); + } + + @EventHandler + public void onQuit(final CPlayerQuitEvent ev) + { + // FIXME: After some time (only in lobby mode & for alive players in the game mode) + // We need to set the handle to null to allow GC (and remove from the hashmap) + // Send message + CPlayer.forEachOnline(cp -> + cp.getHandle().sendMessage(MessageFormat.format(cp.getLocale().SYSTEM_QUIT, ev.getPlayer().getHandle().getName())) + ); + } + } + +} diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/player/CosmeticManager.java b/core/src/main/java/org/ef3d0c3e/sheepwars/player/CosmeticManager.java new file mode 100644 index 0000000..d85c10d --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/player/CosmeticManager.java @@ -0,0 +1,23 @@ +package org.ef3d0c3e.sheepwars.player; + +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import org.ef3d0c3e.sheepwars.player.skin.Skin; + +/** + * Manages cosmetics for the player + */ +public class CosmeticManager { + private CPlayer cp; + + @Getter @Setter + private Skin originalSkin = null; + @Getter + private Skin currentSkin = null; + + protected CosmeticManager(final @NonNull CPlayer cp) + { + this.cp = cp; + } +} diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/player/skin/Skin.java b/core/src/main/java/org/ef3d0c3e/sheepwars/player/skin/Skin.java new file mode 100644 index 0000000..b7a3837 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/player/skin/Skin.java @@ -0,0 +1,82 @@ +package org.ef3d0c3e.sheepwars.player.skin; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import lombok.Getter; +import lombok.NonNull; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; +import org.ef3d0c3e.sheepwars.player.CPlayer; +import org.ef3d0c3e.sheepwars.versions.AutoWrapper; +import org.ef3d0c3e.sheepwars.versions.SkinVersionWrapper; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class Skin { + @AutoWrapper(name = "Skin") + public static SkinVersionWrapper WRAPPER; + + @Getter + private String name; + @Getter + private ItemStack displayItem; + @Getter + private String texture; + @Getter + private String signature; + + public Skin(final String texture, final String signature, final String name) { + this.name = name; + this.displayItem = new ItemStack(Material.PLAYER_HEAD); + final SkullMeta meta = (SkullMeta) displayItem.getItemMeta(); + meta.setDisplayName("§9" + name); + + GameProfile profile = new GameProfile(UUID.randomUUID(), ""); + profile.getProperties().put("textures", new Property("textures", texture)); + try { + Field profileField = meta.getClass().getDeclaredField("profile"); + profileField.setAccessible(true); + profileField.set(meta, profile); + displayItem.setItemMeta(meta); + } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException ex) { + ex.printStackTrace(); + } + + this.texture = texture; + this.signature = signature; + } + + /** + * Gets skin as property + * + * @return Skin as property + */ + public Property toProperty() { + return new Property("textures", texture, signature); + } + + /** + * Gets current skin of player + * + * @param cp Player to get skin of + * @return Skin of player + */ + public static Skin fromPlayer(final @NonNull CPlayer cp) { + return WRAPPER.fromPlayer(cp); + } + + /** + * Changes player skin + * + * @param cp Player to change the skin of + */ + public static void updateSkin(final @NonNull CPlayer cp) { + WRAPPER.updateSkin(cp); + } + + protected static List skinList = new ArrayList<>(); +} \ No newline at end of file diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/versions/AutoWrapper.java b/core/src/main/java/org/ef3d0c3e/sheepwars/versions/AutoWrapper.java new file mode 100644 index 0000000..43ab3c0 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/versions/AutoWrapper.java @@ -0,0 +1,15 @@ +package org.ef3d0c3e.sheepwars.versions; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface AutoWrapper +{ + String name(); + + String path() default "version"; +} diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/versions/SkinVersionWrapper.java b/core/src/main/java/org/ef3d0c3e/sheepwars/versions/SkinVersionWrapper.java new file mode 100644 index 0000000..a9e7348 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/versions/SkinVersionWrapper.java @@ -0,0 +1,30 @@ +package org.ef3d0c3e.sheepwars.versions; + +import com.mojang.authlib.properties.PropertyMap; +import lombok.NonNull; +import org.ef3d0c3e.sheepwars.player.CPlayer; +import org.ef3d0c3e.sheepwars.player.skin.Skin; + +public interface SkinVersionWrapper +{ + /** + * Updates player skin + * @param cp Player + */ + void updateSkin(final @NonNull CPlayer cp); + + /** + * Gets the skin of a player + * @param cp Player to get the skin from + * @return Player's skin + */ + @NonNull Skin fromPlayer(final @NonNull CPlayer cp); + + /** + * Gets the player's PropertyMap + * @param cp Player to get the PropertyMap from + * @return Player's PropertyMap + */ + @NonNull PropertyMap getProperties(final @NonNull CPlayer cp); +} + diff --git a/core/src/main/java/org/ef3d0c3e/sheepwars/versions/WrapperFactory.java b/core/src/main/java/org/ef3d0c3e/sheepwars/versions/WrapperFactory.java new file mode 100644 index 0000000..8f10d36 --- /dev/null +++ b/core/src/main/java/org/ef3d0c3e/sheepwars/versions/WrapperFactory.java @@ -0,0 +1,67 @@ +package org.ef3d0c3e.sheepwars.versions; + +import org.bukkit.Bukkit; +import org.ef3d0c3e.sheepwars.SheepWars; +import org.reflections.Reflections; +import org.reflections.scanners.Scanners; +import org.reflections.util.ConfigurationBuilder; +import org.reflections.util.FilterBuilder; + +import java.lang.reflect.Field; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class WrapperFactory +{ + private static void resolve(final String version, final Field wrapperField) throws Exception + { + final AutoWrapper wrapper = wrapperField.getAnnotation(AutoWrapper.class); + wrapperField.setAccessible(true); + + // Resolve correct wrapper + final Class wrapperClz = Class.forName("org.ef3d0c3e.sheepwars.v" + version + "." + wrapper.name()); + + // Check if wrapper implementation implements abstract wrapper class + boolean valid = false; + for (final Class inter : wrapperClz.getInterfaces()) + { + if (!inter.equals(wrapperField.getType())) continue; + + valid = true; + break; + } + if (!valid) throw new RuntimeException("Wrapper implementation " + wrapperClz.getName() + " does not implement " + wrapperField.getType().getName()); + + // Set wrapper field + wrapperField.set(null, wrapperClz.getDeclaredConstructor().newInstance()); + + SheepWars.debugMessage("Wrapper for " + wrapperField.getDeclaringClass().getName() + " set to " + wrapperClz.getName()); + } + + public static void resolveWrappers() throws Exception + { + // Build version string (e.g: "1.20.2" -> "1_20_R2") + final String bukkitVersion = Bukkit.getVersion(); + Bukkit.getConsoleSender().sendMessage("version=" + bukkitVersion); + Matcher matcher = Pattern.compile("\\(MC: (?\\d)\\.(?\\d+)(?:\\.(?\\d+))?\\)").matcher(bukkitVersion); + if (!matcher.find()) throw new RuntimeException("Could not determine minecraft version from Bukkit version: `" + bukkitVersion + "`"); + String version; + if (matcher.group("minor") == null) + version = matcher.group("version") + "_" + matcher.group("major") + "_R0"; + else + version = matcher.group("version") + "_" + matcher.group("major") + "_R" + matcher.group("minor"); + + SheepWars.debugMessage("Resolving wrappers for NMS " + version + "..."); + + // Loop annotated fields + final Reflections refl = new Reflections( + new ConfigurationBuilder() + .forPackage("org.ef3d0c3e.sheepwars") + .filterInputsBy(new FilterBuilder().includePackage("org.ef3d0c3e.sheepwars")) + .setScanners(Scanners.FieldsAnnotated)); + + for (final Field wrapperField : refl.getFieldsAnnotatedWith(AutoWrapper.class)) + resolve(version, wrapperField); + } +} + diff --git a/core/src/main/resources/exports/config.yml b/core/src/main/resources/exports/config.yml index 476f9b7..d1b77c5 100644 --- a/core/src/main/resources/exports/config.yml +++ b/core/src/main/resources/exports/config.yml @@ -1,4 +1,4 @@ lobby: world: "lobby" game: - overworld: "sheepwars" + world: "sheepwars" diff --git a/core/src/main/resources/exports/locales/fr.yml b/core/src/main/resources/exports/locales/fr.yml index 21ff519..4a1fcc8 100644 --- a/core/src/main/resources/exports/locales/fr.yml +++ b/core/src/main/resources/exports/locales/fr.yml @@ -1,6 +1,6 @@ config: - name: french - displayname: Français + name: "french" + displayname: "Français" banner: ==: org.bukkit.inventory.ItemStack v: 3578 @@ -18,10 +18,6 @@ config: system: join: "§8[§a+§8] §7{0}" quit: "§8[§c-§8] §7{0}" -game: - settings: - radiuschange: "Rayons de la map modifiés: {0} → {1}" - durationchange: "Durée de la partie modifiée: {0}" gui: next: "Suivant" previous: "Précédent" @@ -59,23 +55,8 @@ team: picker: "Choisissez une équipe" npcname: "Choisissez une équipe" npccurrent: "Votre équipe:" - iconpicker: "Choisissez une icône" - create: - item: "Créez une équipe" - itemlore: - - "Utilisez cet item pour créer" - - "une nouvelle équipe" - gui: "Nommez votre équipe" - defaultname: "<Équipe>" - dupe: "L''équipe {0} existe déjà!" - toolong: "Le nom de l''équipe est trop long! (max: {0})" - tooshort: "Le nom de l''équipe est trop court! (min: {0})" - invalidcolor: "Veuillez entrer une couleur valide." - created: "L''équipe {0} vient d''être crée!" kit: picker: "Choisissez un kit" npcname: "Choisissez un kit" - npccurrent: "Votre kit:" - zombie: - zombification: "Zombification" + npccurrent: "Votre kit:" \ No newline at end of file diff --git a/dist/dependency-reduced-pom.xml b/dist/dependency-reduced-pom.xml index 652f19a..cc1b32a 100644 --- a/dist/dependency-reduced-pom.xml +++ b/dist/dependency-reduced-pom.xml @@ -33,7 +33,7 @@ maven-jar-plugin 2.3.2 - Hunt + SheepWars /home/baraquiel/Programming/Minecraft/Sheepwars211/plugins diff --git a/dist/pom.xml b/dist/pom.xml index 48e0979..3d98d3b 100644 --- a/dist/pom.xml +++ b/dist/pom.xml @@ -39,7 +39,7 @@ maven-jar-plugin 2.3.2 - Hunt + SheepWars /home/baraquiel/Programming/Minecraft/Sheepwars211/plugins @@ -47,6 +47,7 @@ + org.ef3d0c3e.sheepwars SheepWars-core diff --git a/spigot-1.21.1/pom.xml b/spigot-1.21.1/pom.xml index 858df9d..0fef0db 100644 --- a/spigot-1.21.1/pom.xml +++ b/spigot-1.21.1/pom.xml @@ -3,6 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + org.ef3d0c3e.sheepwars SheepWars @@ -15,6 +16,7 @@ 22 22 22 + UTF-8 1.21.1-R0.1-SNAPSHOT @@ -23,7 +25,7 @@ net.md-5 specialsource-maven-plugin - 1.2.2 + 2.0.3 package diff --git a/spigot-1.21.1/src/main/java/org/ef3d0c3e/sheepwars/v1_21_R1/Skin.java b/spigot-1.21.1/src/main/java/org/ef3d0c3e/sheepwars/v1_21_R1/Skin.java new file mode 100644 index 0000000..d30da78 --- /dev/null +++ b/spigot-1.21.1/src/main/java/org/ef3d0c3e/sheepwars/v1_21_R1/Skin.java @@ -0,0 +1,126 @@ +package org.ef3d0c3e.sheepwars.v1_21_R1; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.PacketContainer; +import com.mojang.authlib.properties.Property; +import com.mojang.authlib.properties.PropertyMap; +import lombok.NonNull; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_21_R1.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.ef3d0c3e.sheepwars.SheepWars; +import org.ef3d0c3e.sheepwars.player.CPlayer; +import org.ef3d0c3e.sheepwars.versions.SkinVersionWrapper; + +import java.util.Arrays; + +public class Skin implements SkinVersionWrapper +{ + @Override + public void updateSkin(final @NonNull CPlayer cp) + { + // FIXME: May not work in offline mode, may work with SkinRestorer + final org.ef3d0c3e.sheepwars.player.skin.Skin skin = cp.getCosmetics().getCurrentSkin(); + final PropertyMap pm = ((CraftPlayer)cp.getHandle()).getHandle().getGameProfile().getProperties(); + Property text = pm.get("textures").iterator().next(); + + pm.remove("textures", text); + pm.put("textures", new Property("textures", skin.getTexture(), skin.getSignature())); + + for (final Player p : Bukkit.getOnlinePlayers()) + { + p.hidePlayer(SheepWars.getPlugin(), cp.getHandle()); + p.showPlayer(SheepWars.getPlugin(), cp.getHandle()); + } + + final Location loc = cp.getHandle().getLocation(); + + // Remove info packet + final PacketContainer infoRemove = SheepWars.getProtocolManager().createPacket(PacketType.Play.Server.PLAYER_INFO_REMOVE); + infoRemove.getUUIDLists().write(0, Arrays.asList(cp.getHandle().getUniqueId())); + + /* TODO: Port the ProtocolWrapper code to raw Protocollib + // Update info packet + final WrapperPlayServerPlayerInfo info = new WrapperPlayServerPlayerInfo(); + info.setActions(Sets.newHashSet(EnumWrappers.PlayerInfoAction.ADD_PLAYER, EnumWrappers.PlayerInfoAction.UPDATE_LISTED)); + + final PlayerInfoData data = new PlayerInfoData( + cp.getHandle().getUniqueId(), + 0, + true, + EnumWrappers.NativeGameMode.fromBukkit(cp.getHandle().getGameMode()), + WrappedGameProfile.fromPlayer(cp.getHandle()), + WrappedChatComponent.fromText(cp.getHandle().getName()) + ); + info.setEntries(Collections.singletonList(data)); + + // Respawn packet + final ServerLevel level = ((CraftWorld)loc.getWorld()).getHandle(); + final ServerPlayer p = ((CraftPlayer)cp.getHandle()).getHandle(); + + final CommonPlayerSpawnInfo respawn = new CommonPlayerSpawnInfo( + level.getLevel().dimensionTypeId(), + level.dimension(), + level.getSeed(), + p.gameMode.getGameModeForPlayer(), + p.gameMode.getGameModeForPlayer(), + false, + level.isFlat(), + Optional.of( + GlobalPos.of(level.dimension(), new BlockPos( + p.getBlockX(), + p.getBlockY(), + p.getBlockZ()) + )), + 0 + ); + + Hunt.getProtocolManager().sendServerPacket(cp.getHandle(), infoRemove); + Hunt.getProtocolManager().sendServerPacket(cp.getHandle(), info.getHandle()); + p.connection.send(new ClientboundRespawnPacket(respawn, (byte)0x2)); + + final int slot = cp.getHandle().getInventory().getHeldItemSlot(); + final Collection effects = cp.getHandle().getActivePotionEffects(); + final float exp = cp.getHandle().getExp(); + final double health = cp.getHandle().getHealth(); + + // Resend data + new BukkitRunnable() + { + @Override + public void run() + { + final Player p = cp.getHandle(); + + p.getInventory().setHeldItemSlot(slot); + p.addPotionEffects(effects); + p.setExp(exp); + p.setHealth(health-0.00001); + + // Inventory + p.openInventory(cp.getHandle().getEnderChest()); + p.closeInventory(); + + + } + }.runTask(Hunt.getPlugin()); + */ + } + + @Override + public @NonNull org.ef3d0c3e.sheepwars.player.skin.Skin fromPlayer(final @NonNull CPlayer cp) + { + final PropertyMap pm = ((CraftPlayer)cp.getHandle()).getHandle().getGameProfile().getProperties(); + final Property text = pm.get("textures").iterator().next(); + + return new org.ef3d0c3e.sheepwars.player.skin.Skin(text.value(), text.signature(), ""); + } + + @Override + public @NonNull PropertyMap getProperties(final @NonNull CPlayer cp) + { + return ((CraftPlayer)cp.getHandle()).getHandle().getGameProfile().getProperties(); + } +} +