diff options
36 files changed, 2692 insertions, 0 deletions
diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..886d72a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,7 @@ +[*] +end_of_line = lf +indent_style = tab +ij_smart_tabs = true + +[*.json] +tab_width = 2
\ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c37caf --- /dev/null +++ b/.gitignore @@ -0,0 +1,118 @@ +# User-specific stuff +.idea/ + +*.iml +*.ipr +*.iws + +# IntelliJ +out/ +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Cache of project +.gradletasknamecache + +**/build/ + +# Common working directory +run/ + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar @@ -0,0 +1,631 @@ +Copyright (c) 2026 William Hergès + +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, 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. + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + 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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..000882d --- /dev/null +++ b/README.md @@ -0,0 +1,53 @@ +# Molehunt
+
+Molehunt is a Minecraft mod creating the game with the same name in this cubic game.
+
+A complete wiki is available [here](https://william.herges.fr/molehunt/introduction.html).
+
+## Usage
+
+Install the mod on the server and on all clients.
+
+Install [Simple Voice Chat](http://modrinth.com/mod/simple-voice-chat).
+
+Start the game with `/molehunt start` and enjoy!
+
+## Features
+
+Every player has the same skin.
+
+Players' nametags are disabled.
+
+The player list, the chat and the message commands (`/msg`, `/tell` and `/w`) are disabled.
+
+Death and advancement messages are disabled.
+
+World borders are set when starting and slowly shrink over the entire game.
+
+The mod stops the game when every innocent is dead or when the timer ended.
+
+The moles can see the name of other moles with `/molehunt moles`.
+
+Disable the nether, the end and every other portal.
+
+_Almost_ everything in the mod can configured.
+
+## Configuration
+
+To change most values, you can play with the gamerules added by the mod with the
+`/gamerule` command. Every gamerule introduced by the mod starts with `molehunt:`.
+
+To dive deeper into the
+configuration, [an online wiki is available](https://william.herges.fr/molehunt/configuration.html).
+
+## Technologies
+
+- Java 21
+- Fabric + Fabric API
+- Minecraft with Yarn Mappings
+
+## Credits
+
+Creator of the default skin used is unknown.
+
+Thanks @leo-210 for the help!
diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..3f30888 --- /dev/null +++ b/build.gradle @@ -0,0 +1,89 @@ +plugins { + id 'fabric-loom' version '1.15-SNAPSHOT' + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +loom { + splitEnvironmentSourceSets() + + mods { + "floodhunt" { + sourceSet sourceSets.main + sourceSet sourceSets.client + } + } +} + +repositories { + // Add repositories to retrieve artifacts from in here. + // You should only use this when depending on other mods because + // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html + // for more information about repositories. +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + // Fabric API. This is technically optional, but you probably want it anyway. + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" +} + +processResources { + inputs.property "version", project.version + inputs.property "minecraft_version", project.minecraft_version + inputs.property "loader_version", project.loader_version + filteringCharset "UTF-8" + + filesMatching("fabric.mod.json") { + expand "version": project.version, + "minecraft_version": project.minecraft_version, + "loader_version": project.loader_version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 21 + it.options.encoding = "UTF-8" +} + +java { + withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} + +jar { + from("LICENSE") { + rename { "${it}_${inputs.properties.archivesName}" } + } +} + +// configure the maven publication +publishing { + publications { + create("mavenJava", MavenPublication) { + artifactId = project.archives_base_name + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6a75d03 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,14 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx2G +# Fabric Properties +# check these on https://modmuss50.me/fabric.html +minecraft_version=1.21.11 +yarn_mappings=1.21.11+build.4 +loader_version=0.18.4 +# Mod Properties +mod_version=1.3.0 +maven_group=world.anhgelus +archives_base_name=Floodhunt +# Dependencies +# check this on https://modmuss50.me/fabric.html +fabric_version=0.141.3+1.21.11 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..e644113 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..dbc3ce4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..7101f8e --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..027b233 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} diff --git a/src/client/java/world/anhgelus/floodhunt/client/FloodhuntClient.java b/src/client/java/world/anhgelus/floodhunt/client/FloodhuntClient.java new file mode 100644 index 0000000..ab0139e --- /dev/null +++ b/src/client/java/world/anhgelus/floodhunt/client/FloodhuntClient.java @@ -0,0 +1,57 @@ +package world.anhgelus.floodhunt.client; + +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; +import net.minecraft.entity.player.PlayerModelPart; +import world.anhgelus.floodhunt.config.ConfigPayload; +import world.anhgelus.floodhunt.game.GamePayload; + +public class FloodhuntClient implements ClientModInitializer { + + private static boolean SHOW_SKINS = false; + private static boolean SHOW_NAMETAGS = false; + private static boolean SHOW_TAB = false; + + private static boolean GAME_STARTED = false; + + public static boolean showSkins() { + return SHOW_SKINS; + } + + public static boolean showNameTags() { + return SHOW_NAMETAGS; + } + + public static boolean showTab() { + return SHOW_TAB; + } + + public static boolean gameStarted() { + return GAME_STARTED; + } + + @Override + public void onInitializeClient() { + ClientPlayNetworking.registerGlobalReceiver(ConfigPayload.ID, (payload, context) -> context.client().execute(() -> { + SHOW_SKINS = payload.showSkins(); + SHOW_NAMETAGS = payload.showNametags(); + SHOW_TAB = payload.showTab(); + })); + ClientPlayNetworking.registerGlobalReceiver(GamePayload.ID, (payload, context) -> context.client().execute(() -> GAME_STARTED = payload.gameLaunched())); + + // Needed because else `client.options` is null + ClientLifecycleEvents.CLIENT_STARTED.register(client -> { + var options = client.options; + + options.setPlayerModelPart(PlayerModelPart.CAPE, true); + options.setPlayerModelPart(PlayerModelPart.HAT, true); + options.setPlayerModelPart(PlayerModelPart.JACKET, true); + options.setPlayerModelPart(PlayerModelPart.LEFT_SLEEVE, true); + options.setPlayerModelPart(PlayerModelPart.RIGHT_SLEEVE, true); + options.setPlayerModelPart(PlayerModelPart.LEFT_PANTS_LEG, true); + options.setPlayerModelPart(PlayerModelPart.RIGHT_PANTS_LEG, true); + }); + + } +} diff --git a/src/client/java/world/anhgelus/floodhunt/client/mixin/NoCustomizableSkinOverlay.java b/src/client/java/world/anhgelus/floodhunt/client/mixin/NoCustomizableSkinOverlay.java new file mode 100644 index 0000000..7220308 --- /dev/null +++ b/src/client/java/world/anhgelus/floodhunt/client/mixin/NoCustomizableSkinOverlay.java @@ -0,0 +1,18 @@ +package world.anhgelus.floodhunt.client.mixin; + +import net.minecraft.client.option.GameOptions; +import net.minecraft.entity.player.PlayerModelPart; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import world.anhgelus.floodhunt.client.FloodhuntClient; + +@Mixin(GameOptions.class) +public abstract class NoCustomizableSkinOverlay { + @Inject(at = @At("HEAD"), method = "setPlayerModelPart", cancellable = true) + public void togglePlayerModelPart(PlayerModelPart part, boolean enabled, CallbackInfo ci) { + if (FloodhuntClient.showSkins()) return; + ci.cancel(); + } +} diff --git a/src/client/java/world/anhgelus/floodhunt/client/mixin/NoNametags.java b/src/client/java/world/anhgelus/floodhunt/client/mixin/NoNametags.java new file mode 100644 index 0000000..ca75fd8 --- /dev/null +++ b/src/client/java/world/anhgelus/floodhunt/client/mixin/NoNametags.java @@ -0,0 +1,24 @@ +package world.anhgelus.floodhunt.client.mixin; + +import net.minecraft.client.render.command.OrderedRenderCommandQueue; +import net.minecraft.client.render.entity.EntityRenderer; +import net.minecraft.client.render.entity.state.EntityRenderState; +import net.minecraft.client.render.state.CameraRenderState; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityType; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import world.anhgelus.floodhunt.client.FloodhuntClient; + +@Mixin(EntityRenderer.class) +public class NoNametags<T extends Entity, S extends EntityRenderState> { + @Inject(at = @At("HEAD"), method = "render", cancellable = true) + private void renderLabelOrNot(S state, MatrixStack matrices, OrderedRenderCommandQueue queue, CameraRenderState cameraState, CallbackInfo ci) { + if (EntityType.PLAYER != state.entityType || FloodhuntClient.showNameTags() || !FloodhuntClient.gameStarted()) + return; + ci.cancel(); + } +} diff --git a/src/client/java/world/anhgelus/floodhunt/client/mixin/NoPlayerListHud.java b/src/client/java/world/anhgelus/floodhunt/client/mixin/NoPlayerListHud.java new file mode 100644 index 0000000..aa2f886 --- /dev/null +++ b/src/client/java/world/anhgelus/floodhunt/client/mixin/NoPlayerListHud.java @@ -0,0 +1,17 @@ +package world.anhgelus.floodhunt.client.mixin; + +import net.minecraft.client.gui.hud.PlayerListHud; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import world.anhgelus.floodhunt.client.FloodhuntClient; + +@Mixin(PlayerListHud.class) +public class NoPlayerListHud { + @Inject(at = @At("HEAD"), method = "render", cancellable = true) + public void render(CallbackInfo ci) { + if (FloodhuntClient.showTab() || !FloodhuntClient.gameStarted()) return; + ci.cancel(); + } +} diff --git a/src/client/java/world/anhgelus/floodhunt/client/mixin/NoSkin.java b/src/client/java/world/anhgelus/floodhunt/client/mixin/NoSkin.java new file mode 100644 index 0000000..22d2337 --- /dev/null +++ b/src/client/java/world/anhgelus/floodhunt/client/mixin/NoSkin.java @@ -0,0 +1,27 @@ +package world.anhgelus.floodhunt.client.mixin; + +import net.minecraft.client.network.AbstractClientPlayerEntity; +import net.minecraft.entity.player.PlayerSkinType; +import net.minecraft.entity.player.SkinTextures; +import net.minecraft.util.AssetInfo; +import net.minecraft.util.Identifier; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import world.anhgelus.floodhunt.Floodhunt; +import world.anhgelus.floodhunt.client.FloodhuntClient; + +@Mixin(AbstractClientPlayerEntity.class) +public class NoSkin { + @Inject(at = @At("HEAD"), method = "getSkin", cancellable = true) + public void getSkin(CallbackInfoReturnable<SkinTextures> cir) { + if (FloodhuntClient.showSkins() || !FloodhuntClient.gameStarted()) return; + cir.setReturnValue(SkinTextures.create( + new AssetInfo.TextureAssetInfo(Identifier.of(Floodhunt.MOD_ID, "skin")), + null, + null, + PlayerSkinType.WIDE + )); + } +} diff --git a/src/client/resources/assets/molehunt/lang/en_us.json b/src/client/resources/assets/molehunt/lang/en_us.json new file mode 100644 index 0000000..8d4bb70 --- /dev/null +++ b/src/client/resources/assets/molehunt/lang/en_us.json @@ -0,0 +1,28 @@ +{ + "commands.floodhunt.error.game_not_started": "The Floodhunt game has not been started yet.", + "commands.floodhunt.timer.show": "Showing Floodhunt timer.", + "commands.floodhunt.timer.hide": "Hiding Floodhunt timer.", + "commands.floodhunt.role.mole": "§cYou are a Mole.\nKill all the survivors before the timer runs out.", + "commands.floodhunt.role.mole.list": "§eThe moles are: %s", + "commands.floodhunt.role.survivor": "§aYou are not the Mole. \nSurvive until the timer runs out, and try to discover who's the Mole.", + "commands.floodhunt.role.survivor.mole_count": "§eThere are %d §emoles among you.", + "commands.floodhunt.stop.success": "The Floodhunt game has been stopped.", + "floodhunt.game.end.suspense.title": "§eAnd the winners are...", + "floodhunt.game.end.winners.moles.title": "§cThe Moles!", + "floodhunt.game.end.winners.survivors.title": "§aNot the Moles!", + "floodhunt.game.end.winners.subtitle": "§6The Moles were %s", + "floodhunt.game.start.suspense": "§eYou are...", + "floodhunt.game.start.mole.title": "§cThe Mole!", + "floodhunt.game.start.mole.subtitle": "§eGet the list of moles with §6/floodhunt role§e.", + "floodhunt.game.start.survivor.title": "§aNot the Mole!", + "floodhunt.game.start.survivor.subtitle": "§eTry to survive and find out who's the mole!", + "gamerule.floodhunt:gameDuration": "Floodhunt: Duration of a game", + "gamerule.floodhunt:molePercentage": "Floodhunt: Percentage of Mole", + "gamerule.floodhunt:moleCount": "Floodhunt: Number of Mole", + "gamerule.floodhunt:showNametags": "Floodhunt: Show players' nametag", + "gamerule.floodhunt:showTab": "Floodhunt: Enable the tab", + "gamerule.floodhunt:showSkins": "Floodhunt: Show players' skin", + "gamerule.floodhunt:initialWorldSize": "Floodhunt: Initial world size", + "gamerule.floodhunt:finalWorldSize": "Floodhunt: Final world size", + "gamerule.floodhunt:borderMovingStartingTimeOffsetMinutes": "Floodhunt: Time before moving the borders" +} diff --git a/src/client/resources/assets/molehunt/lang/fr_fr.json b/src/client/resources/assets/molehunt/lang/fr_fr.json new file mode 100644 index 0000000..77e8640 --- /dev/null +++ b/src/client/resources/assets/molehunt/lang/fr_fr.json @@ -0,0 +1,28 @@ +{ + "commands.floodhunt.error.game_not_started": "La partie de Floodhunt n'a pas encore commencé.", + "commands.floodhunt.timer.show": "Le timer est maintenant affiché.", + "commands.floodhunt.timer.hide": "Le timer est maintenant caché.", + "commands.floodhunt.role.mole": "§cVous êtes une taupe.\nTuez tous les survivants avant la fin de la partie..", + "commands.floodhunt.role.mole.list": "§eLes taupes sont : %s", + "commands.floodhunt.role.survivor": "§aVous n'êtes pas la taupe. \nSurvivez jusqu'à la fin, et découvrez qui sont les moles.", + "commands.floodhunt.role.survivor.mole_count": "§eIl y a %d §etaupes parmi vous.", + "commands.floodhunt.stop.success": "La partie de Floodhunt a été arrêtée.", + "floodhunt.game.end.suspense.title": "§eEt les gagnants sont...", + "floodhunt.game.end.winners.moles.title": "§cLes Taupes !", + "floodhunt.game.end.winners.survivors.title": "§aPas les Taupes !", + "floodhunt.game.end.winners.subtitle": "§Les Taupes sont", + "floodhunt.game.start.suspense": "§eVous êtes...", + "floodhunt.game.start.mole.title": "§cLa Taupe !", + "floodhunt.game.start.mole.subtitle": "§eRécupérer la liste des taupes avec §6/floodhunt moles", + "floodhunt.game.start.survivor.title": "§aPas la taupe!", + "floodhunt.game.start.survivor.subtitle": "§eEssaye de survivre et de trouver qui est la taupe !", + "gamerule.floodhunt:gameDuration": "Floodhunt : Durée d'une partie", + "gamerule.floodhunt:molePercentage": "Floodhunt : Pourcentage de Taupes", + "gamerule.floodhunt:moleCount": "Floodhunt : Nombre de Taupes", + "gamerule.floodhunt:showNametags": "Floodhunt : Affiche les nametags des joueurs", + "gamerule.floodhunt:showTab": "Floodhunt : Active la liste des joueurs", + "gamerule.floodhunt:showSkins": "Floodhunt : Affiche les skins des joueurs", + "gamerule.floodhunt:initialWorldSize": "Floodhunt : Taille initiale du monde", + "gamerule.floodhunt:finalWorldSize": "Floodhunt : Taille finale du monde", + "gamerule.floodhunt:borderMovingStartingTimeOffsetMinutes": "Floodhunt : Temps avant de bouger les bordures du monde" +} diff --git a/src/client/resources/assets/molehunt/textures/skin.png b/src/client/resources/assets/molehunt/textures/skin.png Binary files differnew file mode 100644 index 0000000..c1f728e --- /dev/null +++ b/src/client/resources/assets/molehunt/textures/skin.png diff --git a/src/client/resources/floodhunt.client.mixins.json b/src/client/resources/floodhunt.client.mixins.json new file mode 100644 index 0000000..f14542e --- /dev/null +++ b/src/client/resources/floodhunt.client.mixins.json @@ -0,0 +1,15 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "world.anhgelus.floodhunt.client.mixin", + "compatibilityLevel": "JAVA_21", + "client": [ + "NoCustomizableSkinOverlay", + "NoNametags", + "NoPlayerListHud", + "NoSkin" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/Floodhunt.java b/src/main/java/world/anhgelus/floodhunt/Floodhunt.java new file mode 100644 index 0000000..95aa95c --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/Floodhunt.java @@ -0,0 +1,225 @@ +package world.anhgelus.floodhunt; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; +import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents; +import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import net.fabricmc.fabric.api.gamerule.v1.GameRuleBuilder; +import net.fabricmc.fabric.api.gamerule.v1.GameRuleEvents; +import net.fabricmc.fabric.api.message.v1.ServerMessageEvents; +import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; +import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.network.packet.s2c.play.OverlayMessageS2CPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.command.CommandManager; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import net.minecraft.util.Identifier; +import net.minecraft.world.GameMode; +import net.minecraft.world.rule.GameRule; +import net.minecraft.world.rule.GameRuleCategory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import world.anhgelus.floodhunt.config.Config; +import world.anhgelus.floodhunt.config.ConfigPayload; +import world.anhgelus.floodhunt.config.SimpleConfig; +import world.anhgelus.floodhunt.game.Game; +import world.anhgelus.floodhunt.game.GamePayload; + +import java.util.HashMap; +import java.util.UUID; + +import static net.minecraft.server.command.CommandManager.literal; + + +public class Floodhunt implements ModInitializer { + + public static final String MOD_ID = "floodhunt"; + public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); + public static final SimpleConfig CONFIG_FILE = Config.configFile(MOD_ID); + public static final GameRule<Integer> GAME_DURATION = GameRuleBuilder + .forInteger(CONFIG_FILE.getOrDefault("game_duration", 90)) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "game_duration_minutes")); + public static final GameRule<Integer> MOLE_PERCENTAGE = GameRuleBuilder + .forInteger(CONFIG_FILE.getOrDefault("mole_percentage", 25)) + .range(0, 100) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "mole_percentage")); + public static final GameRule<Integer> MOLE_COUNT = GameRuleBuilder + .forInteger(CONFIG_FILE.getOrDefault("mole_count", -1)) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "mole_count")); + public static final GameRule<Boolean> SHOW_NAMETAGS = GameRuleBuilder + .forBoolean(CONFIG_FILE.getOrDefault("show_nametags", false)) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "show_nametags")); + public static final GameRule<Boolean> SHOW_TAB = GameRuleBuilder + .forBoolean(CONFIG_FILE.getOrDefault("show_tab", false)) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "show_tab")); + public static final GameRule<Boolean> SHOW_SKINS = GameRuleBuilder + .forBoolean(CONFIG_FILE.getOrDefault("show_skins", false)) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "show_skins")); + public static final GameRule<Integer> INITIAL_WORLD_SIZE = GameRuleBuilder + .forInteger(CONFIG_FILE.getOrDefault("initial_world_size", 600)) + .minValue(0) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "initial_world_size")); + public static final GameRule<Integer> FINAL_WORLD_SIZE = GameRuleBuilder + .forInteger(CONFIG_FILE.getOrDefault("final_world_size", 100)) + .minValue(0) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "final_world_size")); + public static final GameRule<Integer> MOVING_STARTING_TIME_OFFSET = GameRuleBuilder + .forInteger(CONFIG_FILE.getOrDefault("border_moving_starting_time_offset", 30)) + .minValue(0) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "border_moving_starting_time_offset_minutes")); + public static final GameRule<Boolean> ENABLE_PORTALS = GameRuleBuilder + .forBoolean(CONFIG_FILE.getOrDefault("enable_portals", false)) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "enable_portals")); + public static final GameRule<Boolean> FOOD_ON_START = GameRuleBuilder + .forBoolean(CONFIG_FILE.getOrDefault("food_on_start", true)) + .category(GameRuleCategory.MISC) + .buildAndRegister(Identifier.of(MOD_ID, "food_on_start")); + public static Config CONFIG; + public static HashMap<UUID, Boolean> timerVisibility = new HashMap<>(); + + static { + GameRuleEvents.changeCallback(SHOW_NAMETAGS).register(Floodhunt::sendConfigPayload); + GameRuleEvents.changeCallback(SHOW_TAB).register(Floodhunt::sendConfigPayload); + GameRuleEvents.changeCallback(SHOW_SKINS).register(Floodhunt::sendConfigPayload); + } + + public Game game; + + private static <T> void sendConfigPayload(T v, MinecraftServer server) { + if (CONFIG == null) return; + CONFIG.sendConfigPayload(); + } + + @Override + public void onInitialize() { + LOGGER.info("Initializing Floodhunt"); + + final var command = literal("floodhunt"); + command.then(literal("start") + .requires(CommandManager.requirePermissionLevel(CommandManager.GAMEMASTERS_CHECK)) + .executes(context -> { + game = new Game(context.getSource().getServer()); + game.start(); + return Command.SINGLE_SUCCESS; + })); + command.then(literal("timer").requires(ServerCommandSource::isExecutedByPlayer).then( + literal("show").executes(context -> { + var player = context.getSource().getPlayer(); + assert player != null; + + timerVisibility.put(player.getUuid(), true); + context.getSource().sendFeedback(() -> Text.translatable("commands.floodhunt.timer.show"), false); + + if (game == null || !game.started()) { + player.networkHandler.sendPacket(new OverlayMessageS2CPacket( + Text.translatable("commands.floodhunt.error.game_not_started").formatted(Formatting.RED) + )); + } else { + player.networkHandler.sendPacket(new OverlayMessageS2CPacket(Text.of(game.getRemainingText()))); + } + + return Command.SINGLE_SUCCESS; + }) + ).then( + literal("hide").executes(context -> { + var player = context.getSource().getPlayer(); + assert player != null; + + timerVisibility.put(player.getUuid(), false); + context.getSource().sendFeedback(() -> Text.translatable("commands.floodhunt.timer.hide"), false); + return Command.SINGLE_SUCCESS; + }) + )); + command.then(literal("role") + .requires(ServerCommandSource::isExecutedByPlayer) + .executes(context -> { + if (game == null || !game.started()) { + throw (new SimpleCommandExceptionType(Text.translatable("commands.floodhunt.error.game_not_started"))).create(); + } + + final var source = context.getSource(); + final var player = source.getPlayer(); + assert player != null; + + if (game.isMole(player)) { + source.sendFeedback( + () -> Text.translatable("commands.floodhunt.role.mole") + .append("\n\n") + .append(Text.translatable("commands.floodhunt.role.mole.list", game.getMolesAsString())), + false); + } else if (player.isSpectator()) { + source.sendFeedback( + () -> Text.translatable("commands.floodhunt.role.survivor.mole_count", game.getMolesCount()), + false); + } else { + source.sendFeedback( + () -> Text.translatable("commands.floodhunt.role.survivor") + .append("\n\n") + .append(Text.translatable("commands.floodhunt.role.survivor.mole_count", game.getMolesCount())), + false); + } + + return Command.SINGLE_SUCCESS; + })); + command.then(literal("stop") + .requires(CommandManager.requirePermissionLevel(CommandManager.GAMEMASTERS_CHECK)) + .executes(context -> { + if (game == null || !game.started()) { + throw (new SimpleCommandExceptionType(Text.translatable("commands.floodhunt.error.game_not_started"))).create(); + } + + game.stop(); + + return Command.SINGLE_SUCCESS; + })); + + ServerLifecycleEvents.SERVER_STARTED.register(server -> CONFIG = new Config(server)); + + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register(command)); + + ServerMessageEvents.ALLOW_CHAT_MESSAGE.register((message, sender, params) -> false); + + ServerLivingEntityEvents.AFTER_DEATH.register((entity, damageSource) -> { + if (!(entity instanceof ServerPlayerEntity) || game == null) return; + if (!game.started()) return; + if (game.wonByMoles()) game.end(); + }); + + ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> { + if (game == null) return; + if (!game.started()) return; + newPlayer.changeGameMode(GameMode.SPECTATOR); + }); + + ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> { + ServerPlayNetworking.send( + handler.player, + new ConfigPayload(CONFIG.nametagsEnabled(), CONFIG.skinsEnabled(), CONFIG.tabEnabled()) + ); + ServerPlayNetworking.send( + handler.player, + new GamePayload(game != null && game.started()) + ); + }); + + PayloadTypeRegistry.playS2C().register(ConfigPayload.ID, ConfigPayload.CODEC); + PayloadTypeRegistry.playS2C().register(GamePayload.ID, GamePayload.CODEC); + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/config/Config.java b/src/main/java/world/anhgelus/floodhunt/config/Config.java new file mode 100644 index 0000000..4ec87fb --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/config/Config.java @@ -0,0 +1,140 @@ +package world.anhgelus.floodhunt.config; + +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.server.MinecraftServer; +import world.anhgelus.floodhunt.Floodhunt; + +public class Config { + + private final MinecraftServer server; + + public Config(MinecraftServer server) { + this.server = server; + + sendConfigPayload(nametagsEnabled(), skinsEnabled(), tabEnabled()); + } + + public static SimpleConfig configFile(String fileName) { + return SimpleConfig.of(fileName).provider(Config::defaultConfig).request(); + } + + private static String defaultConfig(String s) { + return """ + # Floodhunt mod configuration file + # To regenerate the default configuration, delete, move or rename this file. + + # Game settings + + # The duration of a floodhunt game, in minutes. + # Default: 90 minutes (1 hour 30 minutes). + game_duration = 90 + + # Mole percentage. + # For example, a mole percentage of 25% will get 1 mole every 4 players. + # Default: 25 %. + mole_percentage = 25 + + # Mole count (absolute). + # This setting will overwrite the mole_percentage setting. + # If set below 0, this setting is disabled. + # Default: -1. + mole_count = -1 + + # Give food on start + # Default: true + food_on_start = true + + + # Client-side settings (applies to all players) + + # Show nametags + # Default: false + show_nametags = false + + # Show skins + # Default: false + show_skins = false + + # Show tab + # Default: false + show_tab = false + + + # World border settings + + # Initial world size (in blocks). + # Default: 600 blocks. + initial_world_size = 600 + + # Final world size (in blocks). + # Default: 100 blocks. + final_world_size = 100 + + # Moving starting time offset (in minutes) + # The time before starting to move the world borders. + # If this value is greater than the game duration, borders will never move. + # Default: 30 minutes. + border_moving_starting_time_offset = 30 + + # Other + + # Enable portals (nether, end, end gateway). + # Default: false. + enable_portals = false + """; + } + + public void sendConfigPayload() { + final var payload = new ConfigPayload(nametagsEnabled(), skinsEnabled(), tabEnabled()); + server.getPlayerManager().getPlayerList().forEach(p -> ServerPlayNetworking.send(p, payload)); + } + + public void sendConfigPayload(boolean showNametags, boolean showSkins, boolean showTab) { + final var payload = new ConfigPayload(showNametags, showSkins, showTab); + server.getPlayerManager().getPlayerList().forEach(p -> ServerPlayNetworking.send(p, payload)); + } + + public int getGameDuration() { + return server.getOverworld().getGameRules().getValue(Floodhunt.GAME_DURATION); + } + + public int getMolePercentage() { + return server.getOverworld().getGameRules().getValue(Floodhunt.MOLE_PERCENTAGE); + } + + public int getMoleCount() { + return server.getOverworld().getGameRules().getValue(Floodhunt.MOLE_COUNT); + } + + public boolean nametagsEnabled() { + return server.getOverworld().getGameRules().getValue(Floodhunt.SHOW_NAMETAGS); + } + + public boolean skinsEnabled() { + return server.getOverworld().getGameRules().getValue(Floodhunt.SHOW_SKINS); + } + + public boolean tabEnabled() { + return server.getOverworld().getGameRules().getValue(Floodhunt.SHOW_TAB); + } + + public int getInitialWorldSize() { + return server.getOverworld().getGameRules().getValue(Floodhunt.INITIAL_WORLD_SIZE); + } + + public int getFinalWorldSize() { + return server.getOverworld().getGameRules().getValue(Floodhunt.FINAL_WORLD_SIZE); + } + + public int getBorderShrinkingStartingTimeOffset() { + return server.getOverworld().getGameRules().getValue(Floodhunt.MOVING_STARTING_TIME_OFFSET); + } + + public boolean portalsEnabled() { + return server.getOverworld().getGameRules().getValue(Floodhunt.ENABLE_PORTALS); + } + + public boolean foodOnStart() { + return server.getOverworld().getGameRules().getValue(Floodhunt.FOOD_ON_START); + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/config/ConfigPayload.java b/src/main/java/world/anhgelus/floodhunt/config/ConfigPayload.java new file mode 100644 index 0000000..2b6eb88 --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/config/ConfigPayload.java @@ -0,0 +1,25 @@ +package world.anhgelus.floodhunt.config; + +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; +import net.minecraft.network.packet.CustomPayload; +import net.minecraft.util.Identifier; +import world.anhgelus.floodhunt.Floodhunt; + +public record ConfigPayload(boolean showNametags, boolean showSkins, boolean showTab) implements CustomPayload { + public static final Identifier CONFIG_PACKET_ID = Identifier.of(Floodhunt.MOD_ID, "config"); + + public static final CustomPayload.Id<ConfigPayload> ID = new CustomPayload.Id<>(CONFIG_PACKET_ID); + public static final PacketCodec<RegistryByteBuf, ConfigPayload> CODEC = PacketCodec.tuple( + PacketCodecs.BOOLEAN, ConfigPayload::showNametags, + PacketCodecs.BOOLEAN, ConfigPayload::showSkins, + PacketCodecs.BOOLEAN, ConfigPayload::showTab, + ConfigPayload::new + ); + + @Override + public Id<? extends CustomPayload> getId() { + return ID; + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/config/SimpleConfig.java b/src/main/java/world/anhgelus/floodhunt/config/SimpleConfig.java new file mode 100644 index 0000000..ed5f3ec --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/config/SimpleConfig.java @@ -0,0 +1,253 @@ +package world.anhgelus.floodhunt.config; + +/* + * Copyright (c) 2021 magistermaks + * Slightly modified by Léo-21 and Anhgelus Morhtuuzh + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import net.fabricmc.loader.api.FabricLoader; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Scanner; + +public class SimpleConfig { + + private static final Logger LOGGER = LogManager.getLogger("SimpleConfig"); + private final HashMap<String, String> config = new HashMap<>(); + private final ConfigRequest request; + private boolean broken = false; + + private SimpleConfig(ConfigRequest request) { + this.request = request; + String identifier = "Config '" + request.filename + "'"; + + if (!request.file.exists()) { + LOGGER.info("{} is missing, generating default one...", identifier); + + try { + createConfig(); + } catch (IOException e) { + LOGGER.error("{} failed to generate!", identifier); + LOGGER.trace(e); + broken = true; + } + } + + if (!broken) { + try { + loadConfig(); + } catch (Exception e) { + LOGGER.error("{} failed to load!", identifier); + LOGGER.trace(e); + broken = true; + } + } + + } + + /** + * Creates new config request object, ideally `namespace` + * should be the name of the mod id of the requesting mod + * + * @param filename - name of the config file + * @return new config request object + */ + public static ConfigRequest of(String filename) { + Path path = FabricLoader.getInstance().getConfigDir(); + return new ConfigRequest(path.resolve(filename + ".properties").toFile(), filename); + } + + private void createConfig() throws IOException { + + // try creating missing files + request.file.getParentFile().mkdirs(); + Files.createFile(request.file.toPath()); + + // write default config data + PrintWriter writer = new PrintWriter(request.file, StandardCharsets.UTF_8); + writer.write(request.getConfig()); + writer.close(); + + } + + private void loadConfig() throws IOException { + Scanner reader = new Scanner(request.file); + for (int line = 1; reader.hasNextLine(); line++) { + parseConfigEntry(reader.nextLine(), line); + } + } + + private void parseConfigEntry(String entry, int line) { + if (!entry.isEmpty() && !entry.startsWith("#")) { + String[] parts = entry.split("=", 2); + if (parts.length == 2) { + config.put(parts[0].stripTrailing(), parts[1].strip()); + } else { + throw new RuntimeException("Syntax error in config file on line " + line + "!"); + } + } + } + + /** + * Queries a value from config, returns `null` if the + * key does not exist. + * + * @return value corresponding to the given key + * @see SimpleConfig#getOrDefault + */ + @Deprecated + public String get(String key) { + return config.get(key); + } + + /** + * Returns string value from config corresponding to the given + * key, or the default string if the key is missing. + * + * @return value corresponding to the given key, or the default value + */ + public String getOrDefault(String key, String def) { + String val = get(key); + return val == null ? def : val; + } + + /** + * Returns integer value from config corresponding to the given + * key, or the default integer if the key is missing or invalid. + * + * @return value corresponding to the given key, or the default value + */ + public int getOrDefault(String key, int def) { + try { + return Integer.parseInt(get(key)); + } catch (Exception e) { + return def; + } + } + + /** + * Returns boolean value from config corresponding to the given + * key, or the default boolean if the key is missing. + * + * @return value corresponding to the given key, or the default value + */ + public boolean getOrDefault(String key, boolean def) { + String val = get(key); + if (val != null) { + return val.equalsIgnoreCase("true"); + } + + return def; + } + + /** + * Returns double value from config corresponding to the given + * key, or the default string if the key is missing or invalid. + * + * @return value corresponding to the given key, or the default value + */ + public double getOrDefault(String key, double def) { + try { + return Double.parseDouble(get(key)); + } catch (Exception e) { + return def; + } + } + + /** + * If any error occurred during loading or reading from the config + * a 'broken' flag is set, indicating that the config's state + * is undefined and should be discarded using `delete()` + * + * @return the 'broken' flag of the configuration + */ + public boolean isBroken() { + return broken; + } + + /** + * deletes the config file from the filesystem + * + * @return true if the operation was successful + */ + public boolean delete() { + LOGGER.warn("Config '{}' was removed from existence! Restart the game to regenerate it.", request.filename); + return request.file.delete(); + } + + public interface DefaultConfig { + static String empty(String namespace) { + return ""; + } + + String get(String namespace); + } + + public static class ConfigRequest { + + private final File file; + private final String filename; + private DefaultConfig provider; + + private ConfigRequest(File file, String filename) { + this.file = file; + this.filename = filename; + this.provider = DefaultConfig::empty; + } + + /** + * Sets the default config provider, used to generate the + * config if it's missing. + * + * @param provider default config provider + * @return current config request object + * @see DefaultConfig + */ + public ConfigRequest provider(DefaultConfig provider) { + this.provider = provider; + return this; + } + + /** + * Loads the config from the filesystem. + * + * @return config object + * @see SimpleConfig + */ + public SimpleConfig request() { + return new SimpleConfig(this); + } + + private String getConfig() { + return provider.get(filename) + "\n"; + } + + } + +} diff --git a/src/main/java/world/anhgelus/floodhunt/game/Game.java b/src/main/java/world/anhgelus/floodhunt/game/Game.java new file mode 100644 index 0000000..b395a06 --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/game/Game.java @@ -0,0 +1,204 @@ +package world.anhgelus.floodhunt.game; + +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.network.packet.s2c.play.OverlayMessageS2CPacket; +import net.minecraft.network.packet.s2c.play.SubtitleS2CPacket; +import net.minecraft.network.packet.s2c.play.TitleFadeS2CPacket; +import net.minecraft.network.packet.s2c.play.TitleS2CPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.Text; +import net.minecraft.world.GameMode; +import net.minecraft.world.rule.GameRules; +import world.anhgelus.floodhunt.Floodhunt; +import world.anhgelus.floodhunt.timer.TickTask; +import world.anhgelus.floodhunt.timer.TimerAccess; +import world.anhgelus.floodhunt.utils.TimeUtils; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Game { + + public final int defaultTime = Floodhunt.CONFIG.getGameDuration() * 60; + private final MinecraftServer server; + private final List<UUID> moles = new ArrayList<>(); + private final TitleFadeS2CPacket timing = new TitleFadeS2CPacket(20, 40, 20); + private int remaining = defaultTime; + private boolean started = false; + + public Game(MinecraftServer server) { + this.server = server; + } + + public void start() { + final int n = Floodhunt.CONFIG.getMoleCount() < 0 + ? Math.floorDiv(server.getCurrentPlayerCount(), Math.floorDiv(100, Floodhunt.CONFIG.getMolePercentage())) + : Floodhunt.CONFIG.getMoleCount(); + + final var playerManager = server.getPlayerManager(); + + final var players = new ArrayList<>(playerManager.getPlayerList()); + for (int i = 0; i < n && !players.isEmpty(); i++) { + final var r = ThreadLocalRandom.current().nextInt(0, players.size()); + final var mole = players.get(r); + if (mole == null) throw new IllegalStateException("Mole is null!"); + moles.add(mole.getUuid()); + players.remove(r); + } + + final var gamerules = server.getOverworld().getGameRules(); + // immutable gamerules + gamerules.setValue(GameRules.SHOW_DEATH_MESSAGES, false, server); + gamerules.setValue(GameRules.ANNOUNCE_ADVANCEMENTS, false, server); + // gamerules for the start + gamerules.setValue(GameRules.DO_IMMEDIATE_RESPAWN, true, server); + + final var timer = TimerAccess.getTimerFromOverworld(server); + + final var worldBorder = server.getOverworld().getWorldBorder(); + worldBorder.setSize(Floodhunt.CONFIG.getInitialWorldSize()); + if (Floodhunt.CONFIG.getBorderShrinkingStartingTimeOffset() < Floodhunt.CONFIG.getGameDuration()) { + timer.dds_runTask(new TickTask(() -> worldBorder.interpolateSize( + Floodhunt.CONFIG.getInitialWorldSize(), + Floodhunt.CONFIG.getFinalWorldSize(), + (Floodhunt.CONFIG.getGameDuration() - Floodhunt.CONFIG.getBorderShrinkingStartingTimeOffset()) * 60 * 20L, + 0L + ), Floodhunt.CONFIG.getBorderShrinkingStartingTimeOffset() * 60 * 20L)); + } + + final var title = new TitleS2CPacket(Text.translatable("floodhunt.game.start.suspense")); + playerManager.getPlayerList().forEach(p -> { + p.getInventory().clear(); + p.kill(p.getEntityWorld()); + p.networkHandler.sendPacket(timing); + p.networkHandler.sendPacket(title); + p.changeGameMode(GameMode.SURVIVAL); + if (Floodhunt.CONFIG.foodOnStart()) p.giveItemStack(new ItemStack(Items.COOKED_BEEF, 64)); + }); + + server.setDefaultGameMode(GameMode.SPECTATOR); + + timer.dds_runTask(new TickTask(() -> { + playerManager.getPlayerList().forEach(p -> { + p.networkHandler.sendPacket(timing); + if (moles.contains(p.getUuid())) { + p.networkHandler.sendPacket(new TitleS2CPacket(Text.translatable("floodhunt.game.start.mole.title"))); + p.networkHandler.sendPacket(new SubtitleS2CPacket(Text.translatable("floodhunt.game.start.mole.subtitle"))); + } else { + p.networkHandler.sendPacket(new TitleS2CPacket(Text.translatable("floodhunt.game.start.survivor.title"))); + p.networkHandler.sendPacket(new SubtitleS2CPacket(Text.translatable("floodhunt.game.start.survivor.subtitle"))); + } + // reset health and food level + p.setHealth(p.getMaxHealth()); + p.getHungerManager().setFoodLevel(20); + p.getHungerManager().setSaturationLevel(5.0f); + }); + // reset gamerules after the start + gamerules.setValue(GameRules.DO_IMMEDIATE_RESPAWN, false, server); + // reset time and weather + server.getOverworld().setTimeOfDay(0); + server.getOverworld().resetWeather(); + changeState(true); + timer.dds_runTask(new TickTask(() -> { + remaining--; + playerManager.getPlayerList().forEach(player -> { + if (Floodhunt.timerVisibility.getOrDefault(player.getUuid(), true)) { + player.networkHandler.sendPacket(new OverlayMessageS2CPacket(Text.of(getRemainingText()))); + } + }); + playerManager.sendToAll(timing); + if (remaining == 0) end(); + }, 5 * 20, 20)); + }, 4 * 20)); + } + + public void stop() { + server.getPlayerManager().broadcast(Text.translatable("commands.floodhunt.stop.success"), false); + end(); + } + + public void end() { + final var timer = TimerAccess.getTimerFromOverworld(server); + timer.dds_cancel(); + + final var worldBorder = server.getOverworld().getWorldBorder(); + // Stops the border shrinking. + worldBorder.setSize(worldBorder.getSize()); + + changeState(false); + final var pm = server.getPlayerManager(); + final var winnerSuspense = new TitleS2CPacket(Text.translatable("floodhunt.game.end.suspense.title")); + pm.getPlayerList().forEach(p -> { + p.networkHandler.sendPacket(timing); + p.networkHandler.sendPacket(winnerSuspense); + p.changeGameMode(GameMode.CREATIVE); + }); + timer.dds_runTask(new TickTask(() -> { + TitleS2CPacket winner; + if (wonByMoles()) { + winner = new TitleS2CPacket(Text.translatable("floodhunt.game.end.winners.moles.title")); + } else { + winner = new TitleS2CPacket(Text.translatable("floodhunt.game.end.winners.survivors.title")); + } + pm.sendToAll(new SubtitleS2CPacket(Text.translatable("floodhunt.game.end.winners.subtitle", getMolesAsString()))); + pm.sendToAll(winner); + pm.sendToAll(timing); + moles.clear(); + }, 4 * 20)); + } + + public Text getRemainingText() { + return Text.of("§c" + TimeUtils.generateShortString(remaining)); + } + + private Stream<ServerPlayerEntity> getMoles() { + return moles.stream() + .map(uuid -> server.getPlayerManager().getPlayer(uuid)) + .filter(Objects::nonNull) + .filter(p -> !p.isSpectator() && !p.isCreative()); + } + + public int getMolesCount() { + return getMoles().toArray().length; + } + + public String getMolesAsString() { + return getMoles().map(PlayerEntity::getDisplayName) + .filter(Objects::nonNull) + .map(Object::toString) + .collect(Collectors.joining(", ")); + } + + public boolean isMole(ServerPlayerEntity player) { + return moles.contains(player.getUuid()); + } + + public boolean wonByMoles() { + final var moles = getMoles().map(PlayerEntity::getUuid).toList(); + return !moles.isEmpty() && new HashSet<>(moles).containsAll( + server.getPlayerManager() + .getPlayerList() + .stream() + .filter(p -> !p.isSpectator() && !p.isCreative()) + .map(Entity::getUuid) + .toList() + ); + } + + public boolean started() { + return started; + } + + private void changeState(boolean hasStarted) { + started = hasStarted; + final var payload = new GamePayload(hasStarted); + server.getPlayerManager().sendToAll(ServerPlayNetworking.createS2CPacket(payload)); + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/game/GamePayload.java b/src/main/java/world/anhgelus/floodhunt/game/GamePayload.java new file mode 100644 index 0000000..76368df --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/game/GamePayload.java @@ -0,0 +1,23 @@ +package world.anhgelus.floodhunt.game; + +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; +import net.minecraft.network.packet.CustomPayload; +import net.minecraft.util.Identifier; +import world.anhgelus.floodhunt.Floodhunt; + +public record GamePayload(boolean gameLaunched) implements CustomPayload { + public static final Identifier GAME_PACKET_ID = Identifier.of(Floodhunt.MOD_ID, "game"); + + public static final CustomPayload.Id<GamePayload> ID = new CustomPayload.Id<>(GAME_PACKET_ID); + public static final PacketCodec<RegistryByteBuf, GamePayload> CODEC = PacketCodec.tuple( + PacketCodecs.BOOLEAN, GamePayload::gameLaunched, + GamePayload::new + ); + + @Override + public Id<? extends CustomPayload> getId() { + return ID; + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/mixin/NoJoinLeaveMessage.java b/src/main/java/world/anhgelus/floodhunt/mixin/NoJoinLeaveMessage.java new file mode 100644 index 0000000..376afba --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/mixin/NoJoinLeaveMessage.java @@ -0,0 +1,18 @@ +package world.anhgelus.floodhunt.mixin; + +import net.minecraft.server.PlayerManager; +import net.minecraft.text.Text; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(PlayerManager.class) +public class NoJoinLeaveMessage { + @Inject(at = @At("HEAD"), method = "broadcast*", cancellable = true) + public void broadcastNoJoinLeaveMessage(Text message, boolean overlay, CallbackInfo ci) { + final var content = message.getContent().toString(); + if (content.startsWith("translation{key='multiplayer.player.joined")) ci.cancel(); + else if (content.startsWith("translation{key='multiplayer.player.left")) ci.cancel(); + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/mixin/NoMsgCommand.java b/src/main/java/world/anhgelus/floodhunt/mixin/NoMsgCommand.java new file mode 100644 index 0000000..42ae152 --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/mixin/NoMsgCommand.java @@ -0,0 +1,17 @@ +package world.anhgelus.floodhunt.mixin; + +import com.mojang.brigadier.CommandDispatcher; +import net.minecraft.server.command.MessageCommand; +import net.minecraft.server.command.ServerCommandSource; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(MessageCommand.class) +public class NoMsgCommand { + @Inject(at = @At("HEAD"), method = "register", cancellable = true) + private static void register(CommandDispatcher<ServerCommandSource> dispatcher, CallbackInfo ci) { + ci.cancel(); + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/mixin/NoPortals.java b/src/main/java/world/anhgelus/floodhunt/mixin/NoPortals.java new file mode 100644 index 0000000..59ca3b7 --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/mixin/NoPortals.java @@ -0,0 +1,19 @@ +package world.anhgelus.floodhunt.mixin; + +import net.minecraft.entity.Entity; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.world.dimension.PortalManager; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import world.anhgelus.floodhunt.Floodhunt; + +@Mixin(PortalManager.class) +public class NoPortals { + @Inject(at = @At("HEAD"), method = "tick", cancellable = true) + public void disableTick(ServerWorld world, Entity entity, boolean canUsePortals, CallbackInfoReturnable<Boolean> cir) { + if (Floodhunt.CONFIG == null || Floodhunt.CONFIG.portalsEnabled()) return; + cir.setReturnValue(false); + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/mixin/WorldTimerAccess.java b/src/main/java/world/anhgelus/floodhunt/mixin/WorldTimerAccess.java new file mode 100644 index 0000000..3b7d7fb --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/mixin/WorldTimerAccess.java @@ -0,0 +1,45 @@ +package world.anhgelus.floodhunt.mixin; + +import net.minecraft.server.world.ServerWorld; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import world.anhgelus.floodhunt.timer.TimerAccess; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; + +@Mixin(ServerWorld.class) +public class WorldTimerAccess implements TimerAccess { + @Unique + private final List<TickTask> tasks = new ArrayList<>(); + + @Unique + private final List<TimerAccess.TickTask> tasksToAdd = new ArrayList<>(); + + @Inject(method = "tick", at = @At("TAIL")) + private void onTick(BooleanSupplier shouldKeepTicking, CallbackInfo ci) { + tasks.stream().filter(TickTask::isRunning).forEach(TickTask::tick); + tasks.addAll(tasksToAdd); + tasksToAdd.clear(); + } + + @Override + public void dds_runTask(TimerAccess.TickTask task) { + tasksToAdd.add(task); + } + + @Override + public void dds_cancel() { + tasks.stream().filter(TickTask::isRunning).forEach(TickTask::cancel); + tasks.clear(); + } + + @Override + public List<TickTask> dds_getTasks() { + return tasks.stream().filter(TickTask::isRunning).toList(); + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/timer/TickTask.java b/src/main/java/world/anhgelus/floodhunt/timer/TickTask.java new file mode 100644 index 0000000..ca7f700 --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/timer/TickTask.java @@ -0,0 +1,72 @@ +package world.anhgelus.floodhunt.timer; + +/** + * Represents a complete task called each tick + */ +public class TickTask implements TimerAccess.TickTask { + public final long ticksDelay; + public final long ticksRepeat; + public final boolean repeating; + public final TimerAccess.Task task; + private boolean cancelled = false; + private long currentTicking; + + /** + * Create a new repeating TickTask + * + * @param task Task to run after the delay or the repeat time + * @param ticksDelay Delay before the first task's run + * @param ticksRepeat Repeat each tick (if the repeat is 0, it will repeat each tick, if it is below 0, it will not repeat) + * @throws IllegalArgumentException if ticksDelay is below 0 + */ + public TickTask(TimerAccess.Task task, long ticksDelay, long ticksRepeat) { + if (ticksDelay < 0) throw new IllegalArgumentException("Ticks delay must be non-negative"); + this.ticksDelay = ticksDelay; + this.ticksRepeat = ticksRepeat; + this.task = task; + repeating = ticksRepeat >= 0; + currentTicking = ticksDelay; + } + + /** + * Create a new delayed TickTask + * + * @param task Task to run after the delay or the repeat time + * @param ticksDelay Delay before the first task's run + * @throws IllegalArgumentException if ticksDelay or if ticksRepeat is below 0 + */ + public TickTask(TimerAccess.Task task, long ticksDelay) { + if (ticksDelay < 0) throw new IllegalArgumentException("Ticks delay must be non-negative"); + this.ticksDelay = ticksDelay; + this.ticksRepeat = -1; + this.task = task; + repeating = false; + currentTicking = ticksDelay; + } + + public void tick() { + if (--currentTicking > 0) return; + task.run(); + if (repeating) { + currentTicking = ticksRepeat; + } else { + cancel(); + } + } + + public long cancel() { + if (cancelled) throw new IllegalStateException("Task already cancelled"); + cancelled = true; + return currentTicking; + } + + public boolean isRunning() { + return !cancelled; + } + + @Override + public long getTickingBeforeRun() { + if (cancelled) return -1; + return currentTicking; + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/timer/TimerAccess.java b/src/main/java/world/anhgelus/floodhunt/timer/TimerAccess.java new file mode 100644 index 0000000..714ee59 --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/timer/TimerAccess.java @@ -0,0 +1,65 @@ +package world.anhgelus.floodhunt.timer; + +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.World; + +import java.util.List; + +public interface TimerAccess { + /** + * Get the timer linked to the overworld + * + * @param server Current server + * @return TimerAccess linked to the overworld + */ + static TimerAccess getTimerFromOverworld(MinecraftServer server) { + final var timer = (TimerAccess) server.getWorld(World.OVERWORLD); + if (timer == null) + throw new NullPointerException("Impossible to get TimerAccess from the overworld (it is null)"); + return timer; + } + + /** + * Run a task (called each tick ticked) + * + * @param task Task to run + */ + void dds_runTask(TimerAccess.TickTask task); + + void dds_cancel(); + + /** + * @return All non-cancelled tasks + */ + List<TickTask> dds_getTasks(); + + interface TickTask { + /** + * Tick the task + */ + void tick(); + + /** + * Cancel the task + * + * @return the remaining ticks before the run of the Task + * @throws IllegalStateException if the task is already cancelled + */ + long cancel(); + + boolean isRunning(); + + /** + * @return the number of ticks before run of the task (if the task is cancelled, returns -1) + */ + long getTickingBeforeRun(); + } + + /** + * Represents a task to run after ticking + */ + @FunctionalInterface + interface Task { + void run(); + } +} diff --git a/src/main/java/world/anhgelus/floodhunt/utils/TimeUtils.java b/src/main/java/world/anhgelus/floodhunt/utils/TimeUtils.java new file mode 100644 index 0000000..756e0b0 --- /dev/null +++ b/src/main/java/world/anhgelus/floodhunt/utils/TimeUtils.java @@ -0,0 +1,52 @@ +package world.anhgelus.floodhunt.utils; + +public class TimeUtils { + + public static String generateString(long time) { + final var pt = generateTime(time); + + StringBuilder sb = new StringBuilder(); + if (pt.hours != 0) { + sb.append(pt.hours).append(" hours "); + } + if (pt.minutes != 0 || pt.hours != 0) { + sb.append(pt.minutes).append(" minutes "); + } + sb.append(pt.seconds).append(" seconds"); + + return sb.toString(); + } + + public static String generateShortString(long time) { + final var pt = generateTime(time); + + return padLeft(pt.hours) + ":" + + padLeft(pt.minutes) + ":" + + padLeft(pt.seconds); + } + + private static Time generateTime(long time) { + long hours = 0; + if (time > 3600) { + hours = Math.floorDiv(time, 3600); + } + long minutes = 0; + if (hours != 0 || time > 60) { + minutes = Math.floorDiv(time - hours * 3600, 60); + } + long seconds = (long) Math.floor(time - hours * 3600 - minutes * 60); + return new Time(hours, minutes, seconds); + } + + private static String padLeft(long n) { + if (n < 10 && n != 0) { + return "0" + Math.round(n); + } else if (n == 0) { + return "00"; + } + return Long.toString(Math.round(n)); + } + + private record Time(long hours, long minutes, long seconds) { + } +} diff --git a/src/main/resources/assets/floodhunt/icon.png b/src/main/resources/assets/floodhunt/icon.png Binary files differnew file mode 100644 index 0000000..315d580 --- /dev/null +++ b/src/main/resources/assets/floodhunt/icon.png diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..7b5b38d --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,36 @@ +{ + "schemaVersion": 1, + "id": "Floodhunt", + "version": "${version}", + "name": "Floodhunt", + "description": "Floodhunt mod", + "authors": [ + "Anhgelus Morhtuuzh" + ], + "contact": {}, + "license": "AGPL-3.0", + "icon": "assets/molehunt/icon.png", + "environment": "*", + "entrypoints": { + "client": [ + "world.anhgelus.floodhunt.client.FloodhuntClient" + ], + "server": [ + ], + "main": [ + "world.anhgelus.floodhunt.Floodhunt" + ] + }, + "mixins": [ + "Floodhunt.mixins.json", + { + "config": "Floodhunt.client.mixins.json", + "environment": "client" + } + ], + "depends": { + "fabricloader": ">=${loader_version}", + "fabric-api": "*", + "minecraft": "${minecraft_version}" + } +} diff --git a/src/main/resources/floodhunt.mixins.json b/src/main/resources/floodhunt.mixins.json new file mode 100644 index 0000000..dbebdd1 --- /dev/null +++ b/src/main/resources/floodhunt.mixins.json @@ -0,0 +1,15 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "world.anhgelus.floodhunt.mixin", + "compatibilityLevel": "JAVA_21", + "mixins": [ + "NoJoinLeaveMessage", + "NoMsgCommand", + "NoPortals", + "WorldTimerAccess" + ], + "injectors": { + "defaultRequire": 1 + } +} |
