diff --git a/ADDITIONAL-TERMS b/ADDITIONAL-TERMS new file mode 100644 index 000000000..8a44d5b00 --- /dev/null +++ b/ADDITIONAL-TERMS @@ -0,0 +1,21 @@ +Additional terms for Challenges under section 7 of the GNU Affero General Public License + +Copyright (c) 2020-present anweisen & DomiIRL (cyperia.net, formerly coding-area.net) + +Challenges is licensed under the GNU Affero General Public License version 3 in LICENSE, supplemented by +the following terms as its section 7 permits. They apply to every copy and every modified version, +including one that is only run on a server that players interact with. + +1. Author attributions (section 7 b). Challenges shows its Appropriate Legal Notices to every player, in +chat when they join a server and when they use the /help command. These notices name cyperia.net, DomiIRL +and anweisen as the authors and name the license. They must be preserved and keep being shown in both +places to every player, unchanged, legible and not hidden, whether through the program's own settings, +its message or language files, other plugins, proxies or resource packs. Translating the text around +them is allowed as long as the names and their meaning stay. + +2. Modified versions (section 7 c). A modified version must be marked as modified in a reasonable way, +in its notices as well, and must not be presented as the original version or as the work of cyperia.net. + +3. Names (section 7 e). This license grants no right to use the names cyperia or cyperia.net as +trademarks, or to suggest that cyperia.net endorses, runs or is affiliated with a server, product or +service. Naming cyperia.net as an author as point 1 requires is not such a suggestion. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..72ac1734f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,5 @@ +# Contributing + +By submitting a contribution, such as code, a translation or an asset, to github.com/cyperia/Challenges, you confirm that you have the right to do so and grant anweisen and DomiIRL (cyperia.net) a non-exclusive, free of charge, perpetual, irrevocable, worldwide, transferable and sublicensable right to use the contribution in every way known at the time of submission, in particular to reproduce, modify, distribute and make it available to the public, also commercially, and to publish it under this or any other license. + +Your contribution is also published under the GNU Affero General Public License version 3 with the additional terms in [ADDITIONAL-TERMS](ADDITIONAL-TERMS), like the rest of the repository. diff --git a/LICENSE b/LICENSE index 1d0726dde..be3f7b28e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,163 +1,661 @@ -Challenges License - -Copyright (c) 2020-present anweisen & DomiIRL (cyperia.net, formerly coding-area.net) - -Definitions - -"Software" means the Challenges plugin in source or binary form, including its -documentation, language files and every part of it, such as individual -challenges, settings and menus. Ports or translations of its code into another -language, platform or mod loader are modified versions of the Software. - -"Official sources" means only the GitHub repository github.com/cyperia/Challenges -with its releases, and the Modrinth project page modrinth.com/plugin/challengesplugin. -Obtaining the Software through a tool that downloads it from an official source, -such as a server panel's plugin installer, counts as obtaining it from that source. - -"Server" means a Minecraft server or a network of servers, including its proxy, -lobbies and every round, world or instance the Software runs on. - -"Operator" means whoever runs a Server, together with its staff and anyone acting -on its behalf. Someone who rents or is given a round, world, instance or private -server inside another's Server is a player of that Server, not its Operator. - -"Hosting provider" means a business that rents servers or server resources to -customers who run them as their own Operator, with access to the server's files -and configuration. - -"Payment" means money or anything else of value, given directly or through a -third party, including in-game currency, items, ranks, donations, subscriptions, -memberships, votes, boosts, sponsorships and advertising. - -"Content" means videos, streams, clips, posts, articles and other media that a -content creator publishes. "Content creator" means a natural person who publishes -Content under their own name or channel. - -Permission - -Permission is granted, free of charge, to any person to obtain the Software from -an official source and to copy, use, modify and compile it, only under the -following conditions. These conditions limit the permission itself. - -1. No payment. No Operator may require or accept Payment, from players or from -anyone else, in connection with the Software. In particular, no Payment may: -a. be required to join a Server, round or world where the Software runs, or to -use any part of the Software, including through a paid whitelist, membership, -entry fee or tournament fee; -b. unlock, extend, speed up, prioritize, influence or otherwise improve anyone's -access to or use of the Software, including through perks that apply to the whole -Server, such as a priority queue or reserved slots; -c. give rewards, multipliers, statistics or other advantages for playing with the -Software; -d. buy advertising, sponsorship messages or other promotion within the Software -or within rounds played with it. -Roles such as staff or administrator may have more rights in the Software than -other players, as long as no role or right is obtained through Payment. A Server -may sell cosmetics or perks that have no effect on the Software, on joining it or -on gameplay with it, and that are not made for, named after or advertised with -the Software. Paying a hosting provider for a Server one runs as its Operator is -not Payment under this condition. - -2. Content creation. Content made with the Software may be published and -monetized, including with sponsorships, advertising, subscriptions and -memberships. Visible credit naming cyperia.net must be given in or with the -Content; the in-game credit shown in the Content counts. Payment received for -the Content itself is not Payment under condition 1. A sponsorship or -advertisement that a content creator shows within their own rounds as part of -their Content is part of the Content, not a case of condition 1 d. As the only -exception to condition 1 a. and b., a content creator may let only their -subscribers or members join a round, if: -a. the creator plays in that round personally and it is streamed live or -recorded for publication; -b. the Server is open only during such rounds; and -c. the subscription or membership is a general one of the creator's channel and -is not offered or advertised mainly as access to the Software or to a Server -running it. - -3. No sale. The Software and any part of it, modified or not, must not be sold, -rented, licensed, sublicensed or otherwise offered for Payment, alone or as part -of a bundle, pack, template or setup. This includes servers, rounds, -installation, configuration, add-ons, presets, configurations, worlds and other -products or services made for or with the Software and offered for Payment. -Renting out servers or server resources on which customers install the Software -themselves is not affected. There are only these exceptions: -a. A hosting provider may offer an unmodified copy of the Software from an -official source preinstalled or as part of a hosting package, and pass it on to -its customers for running their own Server, as long as the same offer without -the Software is available at the same price, no price, fee, plan or tier depends -on whether the Software is included, and cyperia.net is named as the author of -the Software wherever the Software is offered or listed. -b. A content creator may commission someone to install, configure or modify the -Software for that creator's own Content under condition 2. The work must be made -for that creator alone and not be a standard package offered to several -creators. The person commissioned may pass the result only to that creator, and -the creator may use it only for their own Content. Running or providing a Server -for the creator is not covered by this exception. -Any other paid offer that includes the Software needs the consent of the -copyright holders in text form. - -4. Authorship and endorsement. The Software must not be presented as one's own -work, and modified versions must state that they are modified. Nothing may -suggest that cyperia.net endorses, runs or is affiliated with a Server, Content -or offer. Naming cyperia.net as the author, as this license requires, is not -such a suggestion. - -5. Credits and references. No credit or reference to cyperia.net in the Software -may be removed, hidden, shortened, changed or replaced by any means, including in -modified versions, through the Software's own settings, its messages or language -files, or through other plugins, proxies or resource packs. This includes the -credits, the links and the beta challenges that are shown locked in the public -releases, together with their notes. Translating the text around a credit or -reference is allowed as long as its meaning and the name cyperia.net stay. - -6. Copies. The Software must only be obtained from an official source. It must -not be published, uploaded, mirrored or passed on, modified or not, except: -a. to the Operator of the same Server, including its hosting provider, for -running that Server; -b. in a fork of the official repository on GitHub, as long as no releases or -compiled builds are published from it; -c. in private storage that only the Operator can access; -d. by a hosting provider to its customers under condition 3 a.; or -e. by someone a content creator commissioned under condition 3 b., to that creator. -A copy received under a., d. or e. counts as obtained from an official source. -Every permitted copy must include this license. - -7. Scope. Parts of the Software that the copyright holders have not published in -an official source, and parts marked in the Software as excluded from this -license, such as the code of internal beta challenges, are not licensed and -remain all rights reserved. This license applies to all versions of the Software -published by the copyright holders, including earlier releases. Rights that -anyone has or obtains in a copy under a license other than a version of this -license, such as the Apache License 2.0 for releases published before March 2022, -are not affected. - -8. Contributions. By submitting a contribution, such as code, a translation or -an asset, to an official source, the contributor confirms they have the right to -do so and grants the copyright holders a non-exclusive, free of charge, -perpetual, irrevocable, worldwide, transferable and sublicensable right to use the -contribution in every way known at the time of submission, in particular to -reproduce, modify, distribute and make it available to the public, also -commercially, and to publish it under this or any other license. - -9. Breach. If a person does not meet any of these conditions, all rights under -this license end automatically for that person, for every version of the -Software, including rights under later versions of this license. They are -restored only if the copyright holders agree in text form. - -10. Law and liability. This license is governed by German law, excluding the UN -Convention on Contracts for the International Sale of Goods. Mandatory consumer -protection of the country where a consumer lives is not affected. The Software is -provided free of charge and as is, without any warranty. The copyright holders -are liable only for intent and gross negligence, except where mandatory law, -such as the German Product Liability Act, provides otherwise. - -11. New versions and termination. The copyright holders may publish a new -version of this license at any time. It applies to releases published after it, -and anyone may choose to use an earlier release under it instead. For earlier -releases, the copyright holders may end this license with at least 90 days -notice, published in the official GitHub repository and on the official Modrinth -page. Until the notice period ends, earlier releases stay under this version. -After that, every version of the Software may only be used under the license -version then in force, except as stated in condition 7; anyone who does not -accept that version must stop using the Software. Content published before the -notice period ends may stay published. + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 2dd9aa628..fc5b4b445 100644 --- a/README.md +++ b/README.md @@ -167,11 +167,11 @@ Every command has its own permission, `challenges.command.`; operators On another Minecraft version the plugin still starts, but it warns in the console and in chat, and we do not support it there. · Auf einer anderen Minecraft-Version startet das Plugin trotzdem, warnt aber in der Konsole und im Chat, und wir geben dafür keinen Support. -Challenges is free of charge and published under the **[Challenges License](https://github.com/cyperia/Challenges/blob/main/LICENSE)**, © [cyperia.net](https://cyperia.net) (anweisen & DomiIRL). +Challenges is free and open source under the **[GNU AGPL v3](https://github.com/cyperia/Challenges/blob/main/LICENSE)** with **[additional terms](https://github.com/cyperia/Challenges/blob/main/ADDITIONAL-TERMS)**, © [cyperia.net](https://cyperia.net) (anweisen & DomiIRL). Releases up to 3.0 keep the license they were published with. -> 🇬🇧 **Free to play, show and stream.** You may run the plugin on your server and use it in videos and streams, monetized ones included, as long as you credit [cyperia.net](https://cyperia.net). +> 🇬🇧 **Run it, change it, stream it, keep the credits.** You may run the plugin on any server, change it and show it in monetized videos and streams. The credits to [cyperia.net](https://cyperia.net) in chat and in `/help` have to stay visible to every player, and if you run a modified version, its source has to be available to your players. -> 🇩🇪 **Frei zum Spielen, Zeigen und Streamen.** Du darfst das Plugin auf deinem Server nutzen und in Videos und Streams zeigen, auch monetarisiert, solange du [cyperia.net](https://cyperia.net) nennst. +> 🇩🇪 **Nutzen, ändern, streamen, Credits behalten.** Du darfst das Plugin auf jedem Server nutzen, verändern und in monetarisierten Videos und Streams zeigen. Die Credits an [cyperia.net](https://cyperia.net) im Chat und in `/help` müssen für jeden Spieler sichtbar bleiben, und wenn du eine veränderte Version betreibst, muss ihr Quellcode für deine Spieler verfügbar sein. Bug reports and questions belong on Discord or GitHub. Please do not use reviews for support, we cannot reply properly there. · Bug-Meldungen und Fragen gehören auf Discord oder GitHub. Bitte nutze dafür keine Bewertungen, dort können wir nicht richtig antworten. diff --git a/build.gradle.kts b/build.gradle.kts index a0cb1cca4..f5352906e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -9,6 +9,9 @@ allprojects { maven("https://repo.papermc.io/repository/maven-public/") maven("https://libraries.minecraft.net/") maven("https://jitpack.io") + maven("https://maven.canvasmc.io/releases") { + content { includeGroup("io.canvasmc.canvas") } + } } } @@ -37,7 +40,7 @@ subprojects { filesMatching(listOf("plugin.yml", "config.yml")) { expand(tokens) } - from(rootProject.file("LICENSE")) + from(rootProject.file("LICENSE"), rootProject.file("ADDITIONAL-TERMS")) } } diff --git a/catalog-plugin/src/main/resources/plugin.yml b/catalog-plugin/src/main/resources/plugin.yml index b64ee1d8a..3561e9029 100644 --- a/catalog-plugin/src/main/resources/plugin.yml +++ b/catalog-plugin/src/main/resources/plugin.yml @@ -6,3 +6,4 @@ authors: website: cyperia.net api-version: 1.14 main: net.cyperia.challenges.catalog.plugin.CatalogPlugin +folia-supported: true diff --git a/catalog/README.md b/catalog/README.md index d68eed14c..3e0e4df74 100644 --- a/catalog/README.md +++ b/catalog/README.md @@ -40,6 +40,10 @@ relative to. - `since`, `updated` mark the entry new or updated in the menu; `beta` leaves its class out of the public release, which shows the entry locked instead. - `excludeFromRandom` keeps the random challenge from picking it. +- `permission` locks the entry for a player without that permission: it shows locked and cannot be + changed, and the random challenge never picks it. With `"hidden": true` such a player does not see it + at all. This keeps an entry in the same build as everything else while only some players can use it, + for example an event goal or a challenge of a rank. - `featured` puts it among the highlighted entries of a listing outside the plugin, such as the export below. - `"registered": false` keeps a challenge out of the plugin without losing its entry, for one that is broken or not ready; anything listing challenges should skip it too. diff --git a/catalog/export/catalog.json b/catalog/export/catalog.json index f30e86129..c0e180e71 100644 --- a/catalog/export/catalog.json +++ b/catalog/export/catalog.json @@ -24308,10 +24308,10 @@ }, "description": { "en": [ - "The whole world is just one block wide. Next to the line is the void, and it runs through the stronghold" + "The whole world is just one block wide. Next to the line is the void" ], "de": [ - "Die ganze Welt ist nur einen Block breit. Neben der Linie ist das Void, und sie führt durch den Stronghold" + "Die ganze Welt ist nur einen Block breit. Neben der Linie ist das Void" ] }, "styled": { @@ -24346,18 +24346,6 @@ { "text": "void", "color": "#00AAAA" - }, - { - "text": "," - } - ], - [ - { - "text": "and it runs " - }, - { - "text": "through the stronghold", - "color": "#00AAAA" } ] ], @@ -24406,20 +24394,6 @@ { "text": "void", "color": "#00AAAA" - }, - { - "text": ",", - "color": "#AAAAAA" - } - ], - [ - { - "text": "and it runs ", - "color": "#AAAAAA" - }, - { - "text": "through the stronghold", - "color": "#00AAAA" } ] ] @@ -24455,18 +24429,6 @@ { "text": "Void", "color": "#00AAAA" - }, - { - "text": "," - } - ], - [ - { - "text": "und sie führt " - }, - { - "text": "durch den Stronghold", - "color": "#00AAAA" } ] ], @@ -24515,20 +24477,6 @@ { "text": "Void", "color": "#00AAAA" - }, - { - "text": ",", - "color": "#AAAAAA" - } - ], - [ - { - "text": "und sie führt ", - "color": "#AAAAAA" - }, - { - "text": "durch den Stronghold", - "color": "#00AAAA" } ] ] @@ -29429,7 +29377,7 @@ ], "category": "misc_challenge", "icon": { - "material": "COOKED_BEEF" + "material": "BOWL" }, "name": { "en": "No Eating", @@ -41610,6 +41558,230 @@ } } }, + { + "id": "collecteverything", + "category": "misc_goal", + "icon": { + "material": "DRAGON_EGG" + }, + "name": { + "en": "Collect Everything", + "de": "Alles sammeln" + }, + "description": { + "en": [ + "Together, find every item, kill every mob and get every advancement once" + ], + "de": [ + "Gemeinsam jedes Item finden, jeden Mob töten und jedes Advancement einmal holen" + ] + }, + "styled": { + "en": { + "name": [ + { + "text": "Collect Everything", + "color": "#FFAA00" + } + ], + "description": [ + [ + { + "text": "Together, find " + }, + { + "text": "every item", + "color": "#FFAA00" + }, + { + "text": "," + } + ], + [ + { + "text": "kill " + }, + { + "text": "every mob", + "color": "#FFAA00" + }, + { + "text": " and get" + } + ], + [ + { + "text": "every advancement", + "color": "#FFAA00" + }, + { + "text": " once" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Collect Everything", + "color": "#FFAA00" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "Together, find ", + "color": "#AAAAAA" + }, + { + "text": "every item", + "color": "#FFAA00" + }, + { + "text": ",", + "color": "#AAAAAA" + } + ], + [ + { + "text": "kill ", + "color": "#AAAAAA" + }, + { + "text": "every mob", + "color": "#FFAA00" + }, + { + "text": " and get", + "color": "#AAAAAA" + } + ], + [ + { + "text": "every advancement", + "color": "#FFAA00" + }, + { + "text": " once", + "color": "#AAAAAA" + } + ] + ] + }, + "de": { + "name": [ + { + "text": "Alles sammeln", + "color": "#FFAA00" + } + ], + "description": [ + [ + { + "text": "Gemeinsam " + }, + { + "text": "jedes Item", + "color": "#FFAA00" + }, + { + "text": " finden," + } + ], + [ + { + "text": "jeden Mob", + "color": "#FFAA00" + }, + { + "text": " töten und " + }, + { + "text": "jedes", + "color": "#FFAA00" + } + ], + [ + { + "text": "Advancement", + "color": "#FFAA00" + }, + { + "text": " einmal holen" + } + ] + ], + "tooltip": [ + [ + { + "text": "»", + "color": "#555555" + }, + { + "text": " " + }, + { + "text": "Alles sammeln", + "color": "#FFAA00" + } + ], + [ + { + "text": " " + } + ], + [ + { + "text": "Gemeinsam ", + "color": "#AAAAAA" + }, + { + "text": "jedes Item", + "color": "#FFAA00" + }, + { + "text": " finden,", + "color": "#AAAAAA" + } + ], + [ + { + "text": "jeden Mob", + "color": "#FFAA00" + }, + { + "text": " töten und ", + "color": "#AAAAAA" + }, + { + "text": "jedes", + "color": "#FFAA00" + } + ], + [ + { + "text": "Advancement", + "color": "#FFAA00" + }, + { + "text": " einmal holen", + "color": "#AAAAAA" + } + ] + ] + } + } + }, { "id": "damagerulenone", "category": "damage_rule", diff --git a/catalog/src/main/java/net/cyperia/challenges/catalog/Challenge.java b/catalog/src/main/java/net/cyperia/challenges/catalog/Challenge.java index 3639d5c19..7934aa22a 100644 --- a/catalog/src/main/java/net/cyperia/challenges/catalog/Challenge.java +++ b/catalog/src/main/java/net/cyperia/challenges/catalog/Challenge.java @@ -6,10 +6,12 @@ import java.util.List; // id is the key the plugin saves the challenge's settings under, fallbackIds are ids it was saved under before; -// an entry that is not registered keeps a challenge the plugin does not offer (yet), for example one that is still broken +// an entry that is not registered keeps a challenge the plugin does not offer (yet), for example one that is still broken; +// a player without the permission sees the entry locked, or not at all when it is hidden public record Challenge(@NotNull String id, @NotNull List fallbackIds, @NotNull String key, @NotNull String category, @NotNull Icon icon, @NotNull Definition definition, @Nullable Pairing pairing, boolean excludeFromRandom, - boolean featured, boolean registered, @NotNull Release release) { + boolean featured, boolean registered, @NotNull Release release, @Nullable String permission, + boolean hidden) { // The trigger and action a challenge with a class of its own plays at heart, its extra rules on top, so a custom // challenge builder outside the plugin can point a player who builds that pairing to it diff --git a/catalog/src/main/java/net/cyperia/challenges/catalog/ChallengeCatalog.java b/catalog/src/main/java/net/cyperia/challenges/catalog/ChallengeCatalog.java index 48ac085de..355181c1e 100644 --- a/catalog/src/main/java/net/cyperia/challenges/catalog/ChallengeCatalog.java +++ b/catalog/src/main/java/net/cyperia/challenges/catalog/ChallengeCatalog.java @@ -23,7 +23,8 @@ public final class ChallengeCatalog { public static final String DIRECTORY = "challenges-catalog/"; private static final Set CHALLENGE_FIELDS = Set.of("id", "fallbackIds", "key", "category", "icon", "color", "since", - "updated", "beta", "excludeFromRandom", "featured", "registered", "class", "requires", "pairing", "preset", "damageRule", "materialRule"); + "updated", "beta", "excludeFromRandom", "featured", "registered", "permission", "hidden", "class", "requires", "pairing", + "preset", "damageRule", "materialRule"); private static final Set DEFINITIONS = Set.of("class", "preset", "damageRule", "materialRule"); private static final Set CLASS_ONLY = Set.of("requires", "pairing"); private static final Set CUSTOM_SETTING_FIELDS = Set.of("id", "class", "icon", "color", "since", "updated", @@ -180,6 +181,10 @@ private static Challenge challenge(@NotNull JsonObject json, @Nullable String cl if (!json.has("class") && CLASS_ONLY.stream().anyMatch(json::has)) { throw new IllegalArgumentException(id + ": " + CLASS_ONLY + " only apply to an entry with a class"); } + String permission = optionalString(json, "permission"); + if (permission == null && flag(json, "hidden")) { + throw new IllegalArgumentException(id + ": hidden only applies to an entry with a permission"); + } Definition definition = switch (definitions.getFirst()) { case "class" -> new Definition.Implementation(className(classPackage, string(json, "class")), optionalString(json, "requires")); @@ -189,7 +194,7 @@ private static Challenge challenge(@NotNull JsonObject json, @Nullable String cl }; return new Challenge(id, strings(json, "fallbackIds"), string(json, "key"), string(json, "category"), icon(json), definition, pairing(json), flag(json, "excludeFromRandom"), flag(json, "featured"), !json.has("registered") || json.get("registered").getAsBoolean(), - release(json)); + release(json), permission, flag(json, "hidden")); } @Nullable diff --git a/catalog/src/main/resources/challenges-catalog/challenges.json b/catalog/src/main/resources/challenges-catalog/challenges.json index b3897100b..08922ffd4 100644 --- a/catalog/src/main/resources/challenges-catalog/challenges.json +++ b/catalog/src/main/resources/challenges-catalog/challenges.json @@ -1400,7 +1400,7 @@ "fallbackIds": ["preset-no-eating"], "key": "no-eating", "category": "misc_challenge", - "icon": "COOKED_BEEF", + "icon": "BOWL", "preset": { "trigger": "consume_item", "triggerSettings": {"item": "any"}, @@ -1882,6 +1882,16 @@ "since": "2.0", "updated": "3.0" }, + { + "id": "collecteverything", + "key": "collect-everything", + "category": "misc_goal", + "icon": "DRAGON_EGG", + "class": "goal.CollectEverythingGoal", + "beta": true, + "permission": "challenges.play.collect-everything", + "hidden": true + }, { "id": "damagerulenone", "key": "damage-rule.none", diff --git a/catalog/src/test/java/net/cyperia/challenges/catalog/ChallengeCatalogTest.java b/catalog/src/test/java/net/cyperia/challenges/catalog/ChallengeCatalogTest.java index 47e4856b6..0930067df 100644 --- a/catalog/src/test/java/net/cyperia/challenges/catalog/ChallengeCatalogTest.java +++ b/catalog/src/test/java/net/cyperia/challenges/catalog/ChallengeCatalogTest.java @@ -112,6 +112,30 @@ void rejectsAnUnknownField(@TempDir Path dir) throws IOException { """, "colour"); } + @Test + void readsThePermissionOfAnEntry(@TempDir Path dir) throws IOException { + Challenge gated = load(dir, """ + {"challenges": [{"id": "a", "key": "a", "category": "c", "icon": "STONE", "class": "A", + "permission": "challenges.play.a", "hidden": true}]} + """).challenge("a").orElseThrow(); + assertEquals("challenges.play.a", gated.permission()); + assertTrue(gated.hidden()); + } + + @Test + void anEntryWithoutPermissionIsOpenToEveryone() { + Challenge cutClean = bundled.challenge("cutclean").orElseThrow(); + assertNull(cutClean.permission()); + assertFalse(cutClean.hidden()); + } + + @Test + void rejectsHiddenWithoutPermission(@TempDir Path dir) throws IOException { + assertRejected(dir, """ + {"challenges": [{"id": "a", "key": "a", "category": "c", "icon": "STONE", "class": "A", "hidden": true}]} + """, "hidden only applies"); + } + @Test void rejectsAnEntryWithTwoDefinitions(@TempDir Path dir) throws IOException { assertRejected(dir, """ diff --git a/catalog/src/test/java/net/cyperia/challenges/catalog/LocalesTest.java b/catalog/src/test/java/net/cyperia/challenges/catalog/LocalesTest.java index ec6449677..30741f32f 100644 --- a/catalog/src/test/java/net/cyperia/challenges/catalog/LocalesTest.java +++ b/catalog/src/test/java/net/cyperia/challenges/catalog/LocalesTest.java @@ -41,6 +41,23 @@ void resolvesReferencesAndColorizersAndDropsMetaTags() { assertFalse(resolved.containsKey("challenge.x.*colorize*")); } + @ParameterizedTest + @ValueSource(strings = {"en", "de"}) + void everyAllGoalBossbarStartsWithTheGoalNameInItsColor(String language) { + Map messages = Locales.load(language); + Map colors = Map.of( + "all-mobs", "", "all-monster", "", "goal-all-bosses", "", "goal-all-bosses-new", "", + "collect-all-items", "", "collect-everything", "" + ); + colors.forEach((goal, color) -> { + for (String bar : new String[]{"bossbar", "bossbar-next"}) { + String text = String.join("", messages.get("challenge." + goal + "." + bar)); + assertFalse(text.contains("*"), goal + "." + bar + ": " + text); + assertTrue(text.contains(color), goal + "." + bar + ": " + text); + } + }); + } + @Test void rejectsALanguageThatIsNotBundled() { assertThrows(IllegalArgumentException.class, () -> Locales.load("xx")); diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d10aec309..9ccb0f81f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,6 +5,7 @@ java = "25" # minecraft spigot = "26.1.2-R0.1-SNAPSHOT" paper = "26.3.build.+" +canvas = "26.3.build.991-stable" protocol-lib = "5.4.0" @@ -42,6 +43,8 @@ mockito = "5.21.0" spigot-api = { group = "org.spigotmc", name = "spigot-api", version.ref = "spigot" } paper-api = { group = "io.papermc.paper", name = "paper-api", version.ref = "paper" } +canvas-api = { group = "io.canvasmc.canvas", name = "canvas-api", version.ref = "canvas" } + protocol-lib = { group = "net.dmulloy2", name = "ProtocolLib", version.ref = "protocol-lib" } # utilities diff --git a/language/locales/de.json b/language/locales/de.json index 3424bfdc4..18a3d95b8 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -159,6 +159,10 @@ "join": "*Auf {0} spielen*", "cancel": "*Abbrechen*" }, + "restricted": { + "state": "Für dich gesperrt", + "click": "Das ist für dich gesperrt" + }, "generic": { "tooltip": { "left": "{@format('Links-Klick', '{0}')}", @@ -265,7 +269,41 @@ "killed-by": "Getötet von {0}", "collected-by": "Gesammelt von {0}", "died-by": "So gestorben: {0}", - "earned-by": "Erreicht von {0}" + "earned-by": "Erreicht von {0}", + "done-by": "Erledigt von {0}", + "found-at": "Timer: {0}", + "found-by-at": [ + "{0}", + "Timer: {1}" + ], + "view": { + "sort": { + "default": "Sortierung: Standard", + "time": "Sortierung: Fundzeit", + "finder": "Sortierung: Finder" + }, + "sort-name": { + "default": "Standard", + "time": "Fundzeit", + "finder": "Finder" + }, + "switch-sort": "Nach {0} sortieren", + "ascending": "Reihenfolge: Aufsteigend", + "descending": "Reihenfolge: Absteigend", + "switch-ascending": "Zu aufsteigend wechseln", + "switch-descending": "Zu absteigend wechseln", + "filter": { + "all": "Anzeige: Alle", + "missing": "Anzeige: Fehlende", + "found": "Anzeige: Gefundene" + }, + "filter-name": { + "all": "Alle", + "missing": "Fehlende", + "found": "Gefundene" + }, + "switch-filter": "{0} anzeigen" + } }, "challenges": { "menu": "Challenges", @@ -1363,13 +1401,6 @@ "einen *zufälligen Effekt*" ] }, - "biome-effect": { - "name": "*Biom = Effekt*", - "desc": [ - "Jedes *Biom* gibt dir", - "einen *eigenen Effekt*" - ] - }, "block-effect": { "name": "*Neuer Block = Zufallseffekt*", "desc": [ @@ -1646,8 +1677,7 @@ "name": "*2D-Welt*", "desc": [ "Die ganze Welt ist nur *einen Block*", - "breit. Neben der *Linie* ist das *Void*,", - "und sie führt *durch den Stronghold*" + "breit. Neben der *Linie* ist das *Void*" ] }, "grid-world": { @@ -2156,7 +2186,9 @@ " ", "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name})" ], - "bossbar": "{@bossbar.format-arg('Alle Bosse', '{0} / {1}')}" + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "Alle Bosse", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" }, "goal-all-bosses-new": { "name": "*Alle Bosse (+ Warden)*", @@ -2166,7 +2198,9 @@ " ", "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name}, {@goal-warden.name})" ], - "bossbar": "{@goal-all-bosses.bossbar}" + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "Alle Bosse (+ Warden)", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" }, "iron-golem": { "name": "*Eisengolem*", @@ -2186,7 +2220,9 @@ "Es müssen *alle Mobs* einmal", "*getötet* werden, um zu *gewinnen*" ], - "bossbar": "{@bossbar.format-arg('Alle Mobs', '{0} / {1}')}" + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "Alle Mobs", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" }, "all-monster": { "name": "*Alle Monster*", @@ -2194,7 +2230,9 @@ "Es müssen *alle Monster* einmal", "*getötet* werden, um zu *gewinnen*" ], - "bossbar": "{@bossbar.format-arg('Alle Monster', '{0} / {1}')}" + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "Alle Monster", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" }, "most-deaths": { "name": "*Meiste Todesarten*", @@ -2546,11 +2584,26 @@ "desc": [ "Finde *alle Items*, die es *in Minecraft gibt*" ], - "bossbar-current": "{@bossbar.format-arg('{0}', '{1} / {2}')}", - "bossbar-finished": "{@bossbar.format('Alle Items gefunden')}", - "skipped": "Item {0} geskippt", - "already-finished": "Es wurden bereits alle Items gefunden", - "found": "Das Item {0} wurde von {1} registriert {@generic.goal-link}" + "bossbar-finished": "{@bossbar.format-arg('{@name}', 'Alle gefunden')}", + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "Alle Items", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" + }, + "collect-everything": { + "name": "*Alles sammeln*", + "desc": [ + "Gemeinsam *jedes Item* finden,", + "*jeden Mob* töten und *jedes*", + "*Advancement* einmal holen" + ], + "bossbar": "{@bossbar.format-arg('{@name}', '{0} {1} / {2}')}", + "menu": "Alles sammeln", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}", + "category": { + "items": "Items", + "mobs": "Mobs", + "advancements": "Fortschritte" + } }, "damage-teleport": { "name": "*Schaden = Zufälliger Teleport*", @@ -2802,12 +2855,220 @@ "disabled": "Diese Challenge ist derzeit deaktiviert", "item-collected": "Item {0} wurde registriert {@generic.goal-link}", "items-to-collect": "Items zu sammeln » {0}", - "mob-killed": "{0} wurde besiegt ({1} / {2}) {@generic.goal-link}", "goal-link": "[Liste]", "height-reached": "{0} hat Höhe {1} erreicht!", "points": "{0} Punkte", "bossbar-height": "{@bossbar.format-arg('Ziel', 'Y: {0}')}", - "leaderboard-entry": "{0} » {1} ┃ {2}" + "leaderboard-entry": "{0} » {1} ┃ {2}", + "sub": { + "ranking": { + "name": "*Rangliste*", + "desc": [ + "Zeigt ein *Scoreboard*, das die", + "Spieler danach ordnet, wer", + "am meisten *zuerst gefunden* hat" + ] + }, + "random-order": { + "name": "*Feste Reihenfolge*", + "desc": [ + "Alles muss *nacheinander*", + "in einer *zufälligen*", + "*Reihenfolge* gefunden werden" + ] + }, + "item-variants": { + "name": "*Alle Varianten*", + "desc": [ + "Jedes *verzauberte Buch* und", + "jeder *Trank* muss einzeln", + "gefunden werden" + ] + }, + "mob-attributes": { + "name": "*Mob-Attribute*", + "desc": [ + "Jede *Variante* eines Mobs,", + "etwa Fell, Farbe oder Baby,", + "muss einzeln getötet werden" + ] + }, + "mob-equipment": { + "name": "*Mob-Ausrüstung*", + "desc": [ + "Jedes *Item*, jede *Rüstung* und", + "jeder *Reiter* eines Mobs", + "muss einzeln getötet werden" + ] + } + }, + "found": { + "item": "{0} wurde von {1} gefunden {@generic.goal-link}", + "mob": "{0} wurde von {1} getötet {@generic.goal-link}", + "mob-without-finder": "{0} wurde getötet {@generic.goal-link}", + "advancement": "{0} wurde von {1} erreicht {@generic.goal-link}" + }, + "skipped": "{0} wurde übersprungen", + "item-variant": { + "enchanted-book": "{0} ({1})", + "long": "{0} (Verlängert)", + "strong": "{0} II" + }, + "mob-variant": { + "1": "{0} ({1})", + "2": "{0} ({1}, {2})", + "3": "{0} ({1}, {2}, {3})", + "4": "{0} ({1}, {2}, {3}, {4})" + }, + "mob-trait": { + "baby": "Baby", + "left-handed": "Linkshänder", + "right-handed": "Rechtshänder", + "charged": "Aufgeladen", + "raid-captain": "Hauptmann", + "sheared": "Geschoren", + "no-pumpkin": "Ohne Kürbis", + "screaming": "Schreiend", + "left-horn-missing": "Ohne linkes Horn", + "right-horn-missing": "Ohne rechtes Horn", + "nectar": "Mit Nektar", + "angry": "Wütend", + "riding": "auf {0}", + "ridden-by": "mit {0} als Reiter", + "ridden-by-captain": "mit {0}-Hauptmann als Reiter", + "armor": { + "leather": "Lederrüstung", + "copper": "Kupferrüstung", + "iron": "Eisenrüstung", + "chainmail": "Kettenrüstung", + "diamond": "Diamantrüstung", + "golden": "Goldrüstung" + }, + "size": { + "small": "Klein", + "medium": "Mittel", + "large": "Groß" + }, + "climate": { + "temperate": "Gemäßigt", + "warm": "Warm", + "cold": "Kalt" + }, + "biome": { + "plains": "Ebene", + "desert": "Wüste", + "jungle": "Dschungel", + "savanna": "Savanne", + "snow": "Verschneit", + "swamp": "Sumpf", + "taiga": "Taiga" + }, + "profession": { + "none": "Arbeitslos" + }, + "mooshroom": { + "red": "Rot", + "brown": "Braun" + }, + "wolf": { + "ashen": "Aschgrau", + "black": "Schwarz", + "chestnut": "Kastanienbraun", + "pale": "Blass", + "rusty": "Rostrot", + "snowy": "Schneeweiß", + "spotted": "Gefleckt", + "striped": "Gestreift", + "woods": "Wald" + }, + "cat": { + "all_black": "Ganz schwarz", + "black": "Smoking", + "british_shorthair": "Britisch Kurzhaar", + "calico": "Kaliko", + "jellie": "Jellie", + "persian": "Perser", + "ragdoll": "Ragdoll", + "red": "Rot", + "siamese": "Siam", + "tabby": "Getigert", + "white": "Weiß" + }, + "horse-color": { + "white": "Weiß", + "creamy": "Cremefarben", + "chestnut": "Kastanienbraun", + "brown": "Braun", + "black": "Schwarz", + "gray": "Grau", + "dark_brown": "Dunkelbraun" + }, + "horse-marking": { + "none": "Ohne Abzeichen", + "white": "Weiße Stiefel und Blesse", + "whitefield": "Weißes Feld", + "white_dots": "Weiße Tupfen", + "black_dots": "Schwarze Punkte" + }, + "llama": { + "creamy": "Cremefarben", + "white": "Weiß", + "brown": "Braun", + "gray": "Grau" + }, + "parrot": { + "red": "Rot", + "blue": "Blau", + "green": "Grün", + "cyan": "Türkis", + "gray": "Grau" + }, + "rabbit": { + "brown": "Braun", + "white": "Weiß", + "black": "Schwarz", + "black_and_white": "Schwarz-weiß", + "gold": "Gold", + "salt_and_pepper": "Pfeffer und Salz" + }, + "fox": { + "red": "Rot", + "snow": "Schnee" + }, + "panda": { + "normal": "Normal", + "lazy": "Faul", + "worried": "Besorgt", + "playful": "Verspielt", + "brown": "Braun", + "weak": "Schwach", + "aggressive": "Aggressiv" + }, + "axolotl": { + "lucy": "Leuzistisch", + "wild": "Braun", + "gold": "Gold", + "cyan": "Türkis", + "blue": "Blau" + }, + "zombie-nautilus": { + "temperate": "Gemäßigt", + "warm": "Koralle" + }, + "copper": { + "unaffected": "Unoxidiert", + "exposed": "Angelaufen", + "weathered": "Verwittert", + "oxidized": "Oxidiert" + } + } + }, + "biome-effect": { + "name": "*Biom = Effekt*", + "desc": [ + "Jedes *Biom* gibt dir", + "einen *eigenen Effekt*" + ] }, "kill-effect": { "name": "*Kill = Effekt*", @@ -3618,6 +3879,9 @@ "goal": { "none": "Es ist kein Ziel aktiviert", "no-checklist": "Das Ziel {0} hat keine weiteren Informationen", + "no-skip": "Beim Ziel {0} gibt es nichts zu überspringen", + "skip-any-order": "Nur ein Ziel mit zufälliger Reihenfolge hat ein aktuelles Ziel zum Überspringen", + "skip-finished": "Es wurde bereits alles gefunden", "description": "Zeigt, was das aktuelle Ziel noch braucht und wer was gefunden hat." }, "randomizer": { @@ -3720,9 +3984,6 @@ "difficulty": { "description": "Zeigt oder ändert den Schwierigkeitsgrad." }, - "skipitem": { - "description": "Überspringt das gesuchte Item." - }, "openmissingitems": { "description": "Öffnet das Menü der fehlenden Items erneut." }, diff --git a/language/locales/en.json b/language/locales/en.json index e1bbd21ef..5fa6c1ebf 100644 --- a/language/locales/en.json +++ b/language/locales/en.json @@ -159,6 +159,10 @@ "join": "*Play on {0}*", "cancel": "*Cancel*" }, + "restricted": { + "state": "Locked for you", + "click": "This is locked for you" + }, "generic": { "tooltip": { "left": "{@format('Left-Click', '{0}')}", @@ -184,7 +188,7 @@ "back_menu": "Back to the previous menu", "back_main_menu": "Back to the main menu", "close_menu": "Close the menu", - "next": "Gp to the next page", + "next": "Go to the next page", "next_shift": "Go on {0} pages", "next_last": "Go to the last page", "punishment": "Change punishment", @@ -265,7 +269,41 @@ "killed-by": "Killed by {0}", "collected-by": "Collected by {0}", "died-by": "Died this way: {0}", - "earned-by": "Earned by {0}" + "earned-by": "Earned by {0}", + "done-by": "Done by {0}", + "found-at": "Timer: {0}", + "found-by-at": [ + "{0}", + "Timer: {1}" + ], + "view": { + "sort": { + "default": "Sort: Default", + "time": "Sort: Time found", + "finder": "Sort: Finder" + }, + "sort-name": { + "default": "default", + "time": "time found", + "finder": "finder" + }, + "switch-sort": "Sort by {0}", + "ascending": "Order: Ascending", + "descending": "Order: Descending", + "switch-ascending": "Switch to ascending", + "switch-descending": "Switch to descending", + "filter": { + "all": "Show: All", + "missing": "Show: Missing", + "found": "Show: Found" + }, + "filter-name": { + "all": "all", + "missing": "missing", + "found": "found" + }, + "switch-filter": "Show {0}" + } }, "challenges": { "menu": "Challenges", @@ -1361,13 +1399,6 @@ "a random *potion effect*" ] }, - "biome-effect": { - "name": "*Biome = Effect*", - "desc": [ - "Every *biome* gives you", - "its own *potion effect*" - ] - }, "block-effect": { "name": "*New Block = Random Effect*", "desc": [ @@ -1644,8 +1675,7 @@ "name": "*2D World*", "desc": [ "The whole world is just *one block*", - "wide. Next to the *line* is the *void*,", - "and it runs *through the stronghold*" + "wide. Next to the *line* is the *void*" ] }, "grid-world": { @@ -2146,7 +2176,9 @@ " ", "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name})" ], - "bossbar": "{@bossbar.format-arg('All Bosses', '{0} / {1}')}" + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "All Bosses", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" }, "goal-all-bosses-new": { "name": "*All Bosses (+ Warden)*", @@ -2156,7 +2188,9 @@ " ", "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name}, {@goal-warden.name})" ], - "bossbar": "{@goal-all-bosses.bossbar}" + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "All Bosses (+ Warden)", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" }, "iron-golem": { "name": "*Iron Golem*", @@ -2175,14 +2209,18 @@ "desc": [ "Each mob has to be killed once to win" ], - "bossbar": "{@bossbar.format-arg('All Mobs', '{0} / {1}')}" + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "All Mobs", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" }, "all-monster": { "name": "*All Monsters*", "desc": [ "Each monster has to be killed once to win" ], - "bossbar": "{@bossbar.format-arg('All Monsters', '{0} / {1}')}" + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "All Monsters", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" }, "most-deaths": { "name": "*Most Death Types*", @@ -2527,11 +2565,26 @@ "desc": [ "Find *all items* that are in *Minecraft*" ], - "bossbar-current": "{@bossbar.format-arg('{0}', '{1} / {2}')}", - "bossbar-finished": "{@bossbar.format('All items found')}", - "skipped": "Item {0} skipped", - "already-finished": "All items has been already found", - "found": "Item {0} registered by {1} {@generic.goal-link}" + "bossbar-finished": "{@bossbar.format-arg('{@name}', 'All found')}", + "bossbar": "{@bossbar.format-arg('{@name}', '{0} / {1}')}", + "menu": "All Items", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}" + }, + "collect-everything": { + "name": "*Collect Everything*", + "desc": [ + "Together, find *every item*,", + "kill *every mob* and get", + "*every advancement* once" + ], + "bossbar": "{@bossbar.format-arg('{@name}', '{0} {1} / {2}')}", + "menu": "Collect Everything", + "bossbar-next": "{@bossbar.format-arg('{@name}', '{0} {@symbol.vertical} {1} / {2}')}", + "category": { + "items": "Items", + "mobs": "Mobs", + "advancements": "Advancements" + } }, "damage-teleport": { "name": "*Damage = Random Teleport*", @@ -2783,12 +2836,219 @@ "disabled": "This challenge is currently deactivated", "item-collected": "Item {0} registered {@generic.goal-link}", "items-to-collect": "Items to collect » {0}", - "mob-killed": "{0} has been killed ({1} / {2}) {@generic.goal-link}", "goal-link": "[List]", "height-reached": "{0} reached Y = {1} first!", "points": "{0} Points", "bossbar-height": "{@bossbar.format-arg('Goal', 'Y: {0}')}", - "leaderboard-entry": "{0} » {1} ┃ {2}" + "leaderboard-entry": "{0} » {1} ┃ {2}", + "sub": { + "ranking": { + "name": "*Ranking*", + "desc": [ + "Shows a *scoreboard* of who", + "found the *most first*" + ] + }, + "random-order": { + "name": "*Fixed Order*", + "desc": [ + "Everything has to be found", + "*one after another* in", + "a *random order*" + ] + }, + "item-variants": { + "name": "*All Variants*", + "desc": [ + "Every *enchanted book* level", + "and every *potion* has to", + "be found on its own" + ] + }, + "mob-attributes": { + "name": "*Mob Attributes*", + "desc": [ + "Every *variant* of a mob,", + "like coats, colours or babies,", + "has to be killed on its own" + ] + }, + "mob-equipment": { + "name": "*Mob Equipment*", + "desc": [ + "Every *item, armor and rider*", + "of a mob has to be", + "killed on its own" + ] + } + }, + "found": { + "item": "{0} has been found by {1} {@generic.goal-link}", + "mob": "{0} has been killed by {1} {@generic.goal-link}", + "mob-without-finder": "{0} has been killed {@generic.goal-link}", + "advancement": "{0} has been achieved by {1} {@generic.goal-link}" + }, + "skipped": "{0} has been skipped", + "item-variant": { + "enchanted-book": "{0} ({1})", + "long": "{0} (Extended)", + "strong": "{0} II" + }, + "mob-variant": { + "1": "{0} ({1})", + "2": "{0} ({1}, {2})", + "3": "{0} ({1}, {2}, {3})", + "4": "{0} ({1}, {2}, {3}, {4})" + }, + "mob-trait": { + "baby": "Baby", + "left-handed": "Left-handed", + "right-handed": "Right-handed", + "charged": "Charged", + "raid-captain": "Raid Captain", + "sheared": "Sheared", + "no-pumpkin": "Without Pumpkin", + "screaming": "Screaming", + "left-horn-missing": "Left Horn Missing", + "right-horn-missing": "Right Horn Missing", + "nectar": "With Nectar", + "angry": "Angry", + "riding": "on {0}", + "ridden-by": "ridden by {0}", + "ridden-by-captain": "ridden by {0} Raid Captain", + "armor": { + "leather": "Leather Armor", + "copper": "Copper Armor", + "iron": "Iron Armor", + "chainmail": "Chainmail Armor", + "diamond": "Diamond Armor", + "golden": "Gold Armor" + }, + "size": { + "small": "Small", + "medium": "Medium", + "large": "Large" + }, + "climate": { + "temperate": "Temperate", + "warm": "Warm", + "cold": "Cold" + }, + "biome": { + "plains": "Plains", + "desert": "Desert", + "jungle": "Jungle", + "savanna": "Savanna", + "snow": "Snowy", + "swamp": "Swamp", + "taiga": "Taiga" + }, + "profession": { + "none": "Unemployed" + }, + "mooshroom": { + "red": "Red", + "brown": "Brown" + }, + "wolf": { + "ashen": "Ashen", + "black": "Black", + "chestnut": "Chestnut", + "pale": "Pale", + "rusty": "Rusty", + "snowy": "Snowy", + "spotted": "Spotted", + "striped": "Striped", + "woods": "Woods" + }, + "cat": { + "all_black": "All Black", + "black": "Tuxedo", + "british_shorthair": "British Shorthair", + "calico": "Calico", + "jellie": "Jellie", + "persian": "Persian", + "ragdoll": "Ragdoll", + "red": "Red", + "siamese": "Siamese", + "tabby": "Tabby", + "white": "White" + }, + "horse-color": { + "white": "White", + "creamy": "Creamy", + "chestnut": "Chestnut", + "brown": "Brown", + "black": "Black", + "gray": "Gray", + "dark_brown": "Dark Brown" + }, + "horse-marking": { + "none": "No Markings", + "white": "White Stockings and Blaze", + "whitefield": "White Field", + "white_dots": "White Spots", + "black_dots": "Black Dots" + }, + "llama": { + "creamy": "Creamy", + "white": "White", + "brown": "Brown", + "gray": "Gray" + }, + "parrot": { + "red": "Red", + "blue": "Blue", + "green": "Green", + "cyan": "Cyan", + "gray": "Gray" + }, + "rabbit": { + "brown": "Brown", + "white": "White", + "black": "Black", + "black_and_white": "Black and White", + "gold": "Gold", + "salt_and_pepper": "Salt and Pepper" + }, + "fox": { + "red": "Red", + "snow": "Snow" + }, + "panda": { + "normal": "Normal", + "lazy": "Lazy", + "worried": "Worried", + "playful": "Playful", + "brown": "Brown", + "weak": "Weak", + "aggressive": "Aggressive" + }, + "axolotl": { + "lucy": "Leucistic", + "wild": "Brown", + "gold": "Gold", + "cyan": "Cyan", + "blue": "Blue" + }, + "zombie-nautilus": { + "temperate": "Temperate", + "warm": "Coral" + }, + "copper": { + "unaffected": "Unoxidized", + "exposed": "Exposed", + "weathered": "Weathered", + "oxidized": "Oxidized" + } + } + }, + "biome-effect": { + "name": "*Biome = Effect*", + "desc": [ + "Every *biome* gives you", + "its own *potion effect*" + ] }, "kill-effect": { "name": "*Kill = Effect*", @@ -3599,6 +3859,9 @@ "goal": { "none": "No goal is enabled", "no-checklist": "The goal {0} has no additional information", + "no-skip": "The goal {0} has nothing to skip", + "skip-any-order": "Only a goal in random order has a current target to skip", + "skip-finished": "Everything has already been found", "description": "Shows what the current goal still needs and who found what." }, "randomizer": { @@ -3701,9 +3964,6 @@ "difficulty": { "description": "Shows or changes the difficulty." }, - "skipitem": { - "description": "Skips the item you are looking for." - }, "openmissingitems": { "description": "Opens the missing items menu again." }, diff --git a/language/locales/global.json b/language/locales/global.json index f2f735c0e..a02a3e5d1 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -73,8 +73,10 @@ "title": "{@title-format('Challenges')}", "leaderboard": { "entry": "{0} {@symbol.vertical} {1} {@symbol.arrow} {2}", - "entry-detail": "{@entry} {@symbol.vertical} {3}" - } + "entry-detail": "{@entry} {@symbol.vertical} {3}", + "skipped": "..." + }, + "footer": "" }, "hotbar": { "format": "{0} {@symbol.vertical} {1}", @@ -669,9 +671,6 @@ "chunk-effect": { "*colorize*": "{0}" }, - "biome-effect": { - "*colorize*": "{0}" - }, "block-effect": { "*colorize*": "{0}" }, @@ -1080,6 +1079,9 @@ "collect-all-items": { "*colorize*": "{0}" }, + "collect-everything": { + "*colorize*": "{0}" + }, "damage-teleport": { "*colorize*": "{0}" }, @@ -1220,6 +1222,28 @@ "settings-modifier-radius": "{@generic.radius}: {0}", "settings-modifier-damage": "{@generic.damage}: {0}", "settings-modifier-max-health": "{@generic.max-health}: {0}", + "generic": { + "sub": { + "ranking": { + "*colorize*": "{0}" + }, + "random-order": { + "*colorize*": "{0}" + }, + "item-variants": { + "*colorize*": "{0}" + }, + "mob-attributes": { + "*colorize*": "{0}" + }, + "mob-equipment": { + "*colorize*": "{0}" + } + } + }, + "biome-effect": { + "*colorize*": "{0}" + }, "kill-effect": { "*colorize*": "{0}" }, diff --git a/mongo-connector/src/main/resources/plugin.yml b/mongo-connector/src/main/resources/plugin.yml index c5f157c84..dd82739d2 100644 --- a/mongo-connector/src/main/resources/plugin.yml +++ b/mongo-connector/src/main/resources/plugin.yml @@ -9,3 +9,4 @@ depend: - Challenges description: | Provides the needed dependencies to the ChallengesPlugin to connect to a MongoDB database +folia-supported: true diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 12c6d90bb..775982d0c 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -5,11 +5,25 @@ plugins { group = "net.cyperia.challenges" +// Canvas-only classes. Compiled against canvas-api, which the plugin never touches unless the server +// is Canvas (see RespawnPortalAdapters), so the plugin still loads on Paper and Purpur. +val canvas: SourceSet by sourceSets.creating { + compileClasspath += sourceSets.main.get().output +} + +// The Canvas adapter runs against canvas-api only: its classes are a superset of paper-api, which would +// shadow them if both were on the classpath. +val canvasTest: SourceSet by sourceSets.creating { + compileClasspath += canvas.output + sourceSets.main.get().output + runtimeClasspath += canvas.output + sourceSets.main.get().output +} + dependencies { compileOnly(libs.slf4j.api) compileOnly(libs.paper.api) compileOnly(libs.protocol.lib) + "canvasCompileOnly"(libs.canvas.api) compileOnly(libs.jetbrains.annotations) compileOnly(libs.lombok) @@ -35,6 +49,26 @@ dependencies { testImplementation(libs.mockito.core) testImplementation(libs.paper.api) testRuntimeOnly(libs.protocol.lib) + + "canvasTestImplementation"(libs.canvas.api) + "canvasTestImplementation"(platform(libs.junit.bom)) + "canvasTestImplementation"(libs.junit.jupiter) + "canvasTestImplementation"(libs.mockito.core) + "canvasTestImplementation"(libs.slf4j.api) + "canvasTestImplementation"(libs.gson) + "canvasTestRuntimeOnly"(libs.junit.platform.launcher) +} + +val canvasTestTask = tasks.register("canvasTest") { + description = "Runs the Canvas adapter tests against canvas-api." + group = "verification" + testClassesDirs = canvasTest.output.classesDirs + classpath = canvasTest.runtimeClasspath + useJUnitPlatform() +} + +tasks.check { + dependsOn(canvasTestTask) } tasks.test { @@ -59,6 +93,7 @@ tasks { attributes["paperweight-mappings-namespace"] = "mojang" } + from(canvas.output) // no explicit dependencies block - bundle "implementation" deps by default } diff --git a/plugin/src/canvas/java/net/cyperia/challenges/plugin/spigot/region/CanvasRespawnPortalAdapter.java b/plugin/src/canvas/java/net/cyperia/challenges/plugin/spigot/region/CanvasRespawnPortalAdapter.java new file mode 100644 index 000000000..66c494de7 --- /dev/null +++ b/plugin/src/canvas/java/net/cyperia/challenges/plugin/spigot/region/CanvasRespawnPortalAdapter.java @@ -0,0 +1,43 @@ +package net.cyperia.challenges.plugin.spigot.region; + +import io.canvasmc.canvas.event.EntityPortalAsyncEvent; +import io.canvasmc.canvas.event.EntityPostPortalAsyncEvent; +import io.canvasmc.canvas.event.PlayerPostRespawnAsyncEvent; +import io.canvasmc.canvas.event.PlayerRespawnAsyncEvent; +import net.cyperia.challenges.plugin.spigot.events.PortalTravelEvent; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.jetbrains.annotations.NotNull; + +public final class CanvasRespawnPortalAdapter implements Listener { + + @EventHandler + public void onRespawn(@NotNull PlayerRespawnAsyncEvent event) { + Location original = event.getRespawnLocation(); + Location settled = RespawnPortalEvents.respawnLocation(event.getPlayer(), original); + if (settled != original) event.setRespawnLocation(settled); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPostRespawn(@NotNull PlayerPostRespawnAsyncEvent event) { + RespawnPortalEvents.respawned(event.getPlayer()); + } + + @EventHandler + public void onPortal(@NotNull EntityPortalAsyncEvent event) { + World target = event.getTo(); + PortalTravelEvent travel = RespawnPortalEvents.portalTravel(event.getEntity(), event.getFrom(), target, + event.getPortalType(), null, event.isCancelled()); + if (travel.isCancelled() != event.isCancelled()) event.setCancelled(travel.isCancelled()); + if (travel.getTargetWorld() != target) event.setTo(travel.getTargetWorld()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPostPortal(@NotNull EntityPostPortalAsyncEvent event) { + RespawnPortalEvents.portalArrived(event.getEntity(), event.getFrom(), event.getPortalType()); + } + +} diff --git a/plugin/src/canvasTest/java/net/cyperia/challenges/plugin/spigot/region/CanvasRespawnPortalAdapterTest.java b/plugin/src/canvasTest/java/net/cyperia/challenges/plugin/spigot/region/CanvasRespawnPortalAdapterTest.java new file mode 100644 index 000000000..e8a85282c --- /dev/null +++ b/plugin/src/canvasTest/java/net/cyperia/challenges/plugin/spigot/region/CanvasRespawnPortalAdapterTest.java @@ -0,0 +1,124 @@ +package net.cyperia.challenges.plugin.spigot.region; + +import io.canvasmc.canvas.event.EntityPortalAsyncEvent; +import io.canvasmc.canvas.event.EntityPostPortalAsyncEvent; +import io.canvasmc.canvas.event.PlayerPostRespawnAsyncEvent; +import io.canvasmc.canvas.event.PlayerRespawnAsyncEvent; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnLocationEvent; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnedEvent; +import net.cyperia.challenges.plugin.spigot.events.PortalArrivedEvent; +import net.cyperia.challenges.plugin.spigot.events.PortalTravelEvent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.PortalType; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.player.PlayerRespawnEvent.RespawnReason; +import org.bukkit.plugin.PluginManager; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; + +class CanvasRespawnPortalAdapterTest { + + private final CanvasRespawnPortalAdapter adapter = new CanvasRespawnPortalAdapter(); + private final PluginManager pluginManager = mock(PluginManager.class); + private final List fired = new ArrayList<>(); + private final World overworld = mock(World.class); + private final World nether = mock(World.class); + private final World replacement = mock(World.class); + private final Player player = mock(Player.class); + private MockedStatic bukkit; + private Consumer listener = _ -> { + }; + + @BeforeEach + void mockServer() { + bukkit = org.mockito.Mockito.mockStatic(Bukkit.class); + bukkit.when(Bukkit::getPluginManager).thenReturn(pluginManager); + bukkit.when(Bukkit::isPrimaryThread).thenReturn(true); + doAnswer(invocation -> { + Event event = invocation.getArgument(0); + fired.add(event); + listener.accept(event); + return null; + }).when(pluginManager).callEvent(any(Event.class)); + } + + @AfterEach + void closeServer() { + bukkit.close(); + } + + @Test + void respawn_appliesTheLocationTheOwnEventSettledOn() { + Location moved = new Location(replacement, 5, 70, 5); + listener = event -> { + if (event instanceof PlayerRespawnLocationEvent respawn) respawn.setRespawnLocation(moved); + }; + PlayerRespawnAsyncEvent event = new PlayerRespawnAsyncEvent(player, new Location(overworld, 1, 64, 1), false, false, false, RespawnReason.DEATH); + + adapter.onRespawn(event); + + assertEquals(moved, event.getRespawnLocation()); + } + + @Test + void postRespawn_firesTheOwnEvent() { + adapter.onPostRespawn(new PlayerPostRespawnAsyncEvent(player, new Location(overworld, 1, 64, 1), false, false, false, RespawnReason.DEATH)); + + assertSame(player, assertInstanceOf(PlayerRespawnedEvent.class, fired.getFirst()).getPlayer()); + } + + @Test + void portal_hasNoDestinationAndTakesTheChosenWorldAndCancel() { + Entity entity = mock(Entity.class); + listener = event -> { + if (event instanceof PortalTravelEvent travel) { + travel.setTargetWorld(replacement); + travel.setCancelled(true); + } + }; + EntityPortalAsyncEvent event = new EntityPortalAsyncEvent(entity, overworld, nether, PortalType.NETHER); + + adapter.onPortal(event); + + PortalTravelEvent travel = assertInstanceOf(PortalTravelEvent.class, fired.getFirst()); + assertEquals(null, travel.getDestination()); + assertEquals(PortalType.NETHER, travel.getPortalType()); + assertSame(replacement, event.getTo()); + assertTrue(event.isCancelled()); + } + + @Test + void adapterIsPickedByTheCanvasEventsPresence() { + assertTrue(RespawnPortalAdapters.isClassPresent(RespawnPortalAdapters.CANVAS_EVENT)); + assertInstanceOf(CanvasRespawnPortalAdapter.class, RespawnPortalAdapters.create()); + } + + @Test + void postPortal_firesTheArrivalForTheEntity() { + adapter.onPostPortal(new EntityPostPortalAsyncEvent(player, overworld, nether, PortalType.NETHER)); + + PortalArrivedEvent arrived = assertInstanceOf(PortalArrivedEvent.class, fired.getFirst()); + assertSame(player, arrived.getEntity()); + assertSame(overworld, arrived.getFrom()); + assertEquals(PortalType.NETHER, arrived.getPortalType()); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/ChallengeAPI.java b/plugin/src/main/java/net/cyperia/challenges/plugin/ChallengeAPI.java index 0d6c56bca..df024614e 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/ChallengeAPI.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/ChallengeAPI.java @@ -5,6 +5,7 @@ import net.cyperia.challenges.plugin.content.loader.ContentLoader; import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; @@ -129,8 +130,8 @@ public static boolean isPlayerInGameWorld(@NotNull Environment environment) { } public static boolean isPlayerInGameWorld(@NotNull World world) { - for (Player player : world.getPlayers()) { - if (!AbstractChallenge.ignorePlayer(player)) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getWorld() == world && !AbstractChallenge.ignorePlayer(player)) { return true; } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/Challenges.java b/plugin/src/main/java/net/cyperia/challenges/plugin/Challenges.java index c29185664..ca8d0abf8 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/Challenges.java @@ -31,7 +31,9 @@ import net.cyperia.challenges.plugin.spigot.command.*; import net.cyperia.challenges.plugin.spigot.command.WeatherCommand.Weather; import net.cyperia.challenges.plugin.spigot.listener.*; +import net.cyperia.challenges.plugin.spigot.region.RespawnPortalAdapters; import net.cyperia.commons.bukkit.core.BukkitModule; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.version.Version; import org.bukkit.GameMode; import org.jetbrains.annotations.NotNull; @@ -103,7 +105,6 @@ protected void handleEnable() { } enableManagers(); - registerCommands(); registerListeners(); } @@ -130,7 +131,7 @@ private void createManagers() { borderManager = new BorderManager(); serverManager = new ServerManager(); autoResetManager = new AutoResetManager(); - scheduler = new ScheduleManager(); + scheduler = new ScheduleManager(this); playerManager = new PlayerManager(); scoreboardManager = new ScoreboardManager(); cloudSupportManager = new CloudSupportManager(); @@ -157,6 +158,8 @@ private void loadManagers() { challengeTimer.loadSession(); } + // The challenges and their commands are registered here, in onEnable: the server builds its command tree + // right after plugins enable, so a registration pushed to the global region would miss it. private void enableManagers() { gameWorldStorage.enable(); // Before challengeLoader: the presets it registers resolve their trigger and action from here. @@ -164,6 +167,11 @@ private void enableManagers() { challengeLoader.enable(); borderManager.enable(); databaseManager.enable(); + // onEnable is not on the global region, which creating worlds, time, weather and game rules need + Regions.global(this, this::enableWorlds); + } + + private void enableWorlds() { worldManager.enable(); challengeTimer.enable(); challengeManager.enable(); @@ -236,7 +244,8 @@ private void registerListeners() { new CustomEventListener(), new HelpListener(), new GeneratorWorldsListener(), - new ScoreboardUpdateListener() + new ScoreboardUpdateListener(), + RespawnPortalAdapters.create() ); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/TriggerActionChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/TriggerActionChallenge.java index 9d64e83ca..f8192e16f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/TriggerActionChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/TriggerActionChallenge.java @@ -1,12 +1,10 @@ package net.cyperia.challenges.plugin.challenges.custom; -import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.cyperia.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.cyperia.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.cyperia.challenges.plugin.challenges.custom.settings.trigger.IChallengeTrigger; import net.cyperia.challenges.plugin.challenges.type.IChallenge; -import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -96,10 +94,6 @@ default boolean isTriggerMet(ChallengeExecutionData data) { default void executeAction(ChallengeExecutionData challengeExecutionData) { ChallengeAction action = getAction(); if (action == null) return; - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> action.execute(challengeExecutionData, getSubActions())); - return; - } action.execute(challengeExecutionData, getSubActions()); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java index e2f39c670..d04d2f821 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java @@ -2,9 +2,10 @@ import com.google.common.collect.Lists; import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.cyperia.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import org.bukkit.World; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; @@ -14,65 +15,70 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Predicate; public interface IEntityTargetAction extends IChallengeAction { - static List getTargets(Entity triggerTarget, Map subActions) { + // The mobs of a world are only visible from the region they stand in, so those targets complete once every region was scanned + static CompletableFuture> getTargets(Entity triggerTarget, Map subActions) { return getTargets(triggerTarget, subActions, SubSettingsHelper.TARGET_ENTITY); } - static List getTargets(Entity triggerTarget, Map subActions, String key) { + static CompletableFuture> getTargets(Entity triggerTarget, Map subActions, String key) { if (!subActions.containsKey(key)) { - return Lists.newLinkedList(); + return CompletableFuture.completedFuture(Lists.newLinkedList()); } String targetEntity = subActions.get(key)[0]; switch (targetEntity) { case "random_player": List players = ChallengeAPI.getIngamePlayers(); - if (players.isEmpty()) return new LinkedList<>(); - return Collections.singletonList(players.get(random.nextInt(players.size()))); + if (players.isEmpty()) return CompletableFuture.completedFuture(new LinkedList<>()); + return CompletableFuture.completedFuture(Collections.singletonList(players.get(random.nextInt(players.size())))); case "every_player": - return Lists.newLinkedList(ChallengeAPI.getIngamePlayers()); + return CompletableFuture.completedFuture(Lists.newLinkedList(ChallengeAPI.getIngamePlayers())); case "current_player": - return triggerTarget instanceof Player ? Lists.newArrayList(triggerTarget) : Lists.newLinkedList(); + return CompletableFuture.completedFuture(triggerTarget instanceof Player ? Lists.newArrayList(triggerTarget) : Lists.newLinkedList()); case "every_mob": - List everyList = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - everyList.addAll(world.getLivingEntities()); - } - return everyList; + return everyMob(entity -> true); case "every_mob_except_current": - List exceptList = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - exceptList.addAll(world.getLivingEntities()); - } - exceptList.remove(triggerTarget); - return exceptList; + return everyMob(entity -> entity != triggerTarget); case "every_mob_except_players": - List noPlayers = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity.getType() == EntityType.PLAYER) continue; - noPlayers.add(entity); - } - } - - return noPlayers; + return everyMob(entity -> entity.getType() != EntityType.PLAYER); case "console": - return Collections.singletonList(null); + return CompletableFuture.completedFuture(Collections.singletonList(null)); } if (triggerTarget == null) { - return Lists.newLinkedList(); + return CompletableFuture.completedFuture(Lists.newLinkedList()); } - return Lists.newArrayList(triggerTarget); + return CompletableFuture.completedFuture(Lists.newArrayList(triggerTarget)); + } + + private static CompletableFuture> everyMob(Predicate filter) { + List found = new CopyOnWriteArrayList<>(); + CompletableFuture[] scans = ChallengeAPI.getGameWorlds().stream() + .map(world -> Regions.forEachRegion(Challenges.getInstance(), world, () -> { + for (LivingEntity entity : world.getLivingEntities()) { + if (filter.test(entity)) found.add(entity); + } + })) + .toArray(CompletableFuture[]::new); + return CompletableFuture.allOf(scans).thenApply(_ -> found); } @Override default void execute(ChallengeExecutionData executionData, Map subActions) { - for (Entity target : getTargets(executionData.getEntity(), subActions)) { - executeFor(target, subActions); - } + getTargets(executionData.getEntity(), subActions).thenAccept(targets -> { + for (Entity target : targets) { + if (target == null) { + executeFor(null, subActions); + continue; + } + Regions.entity(Challenges.getInstance(), target, () -> executeFor(target, subActions)); + } + }); } void executeFor(Entity entity, Map subActions); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java index 012d482bd..89806927a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java @@ -7,19 +7,20 @@ public class CancelEventAction extends ChallengeAction { - public static boolean inCanceling; + // Set and read on the thread that fires the trigger, which runs the actions inline + private static final ThreadLocal inCanceling = ThreadLocal.withInitial(() -> false); public CancelEventAction(String name) { super(name); } public static void onPreTrigger() { - inCanceling = false; + inCanceling.set(false); } public static boolean shouldCancel() { - if (inCanceling) { - inCanceling = false; + if (inCanceling.get()) { + inCanceling.set(false); return true; } return false; @@ -27,7 +28,7 @@ public static boolean shouldCancel() { @Override public void execute(ChallengeExecutionData executionData, Map subActions) { - inCanceling = true; + inCanceling.set(true); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index 0c05a3f99..a67060acc 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -9,6 +9,7 @@ import net.cyperia.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import net.cyperia.commons.bukkit.utils.misc.Regions; import java.util.Map; @@ -28,7 +29,7 @@ public void execute(ChallengeExecutionData executionData, Map try { int change = Integer.parseInt(subActions.get("change")[0]); - Challenges.getInstance().getBorderManager().changeSize(change); + Regions.global(Challenges.getInstance(), () -> Challenges.getInstance().getBorderManager().changeSize(change)); } catch (NumberFormatException | IndexOutOfBoundsException ex) { Logger.error("Error while accessing change border action values", ex); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java index 4dc3be2b8..f6ba73809 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java @@ -6,6 +6,7 @@ import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.management.files.ConfigManager; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -49,7 +50,7 @@ public void executeForPlayer(Player player, Map subActions) { ? command : "execute as " + player.getName() + " at " + player.getName() + " run " + command; - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), fullCommand); + Regions.global(Challenges.getInstance(), () -> Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), fullCommand)); } private static String commandName(String input) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java index 9db87eb2b..cf4863f27 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java @@ -1,9 +1,11 @@ package net.cyperia.challenges.plugin.challenges.custom.settings.action.impl; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.cyperia.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.cyperia.challenges.plugin.challenges.implementation.challenge.extraworld.JumpAndRunChallenge; import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.cyperia.commons.bukkit.utils.misc.Regions; import java.util.Map; @@ -17,7 +19,7 @@ public JumpAndRunAction(String name) { public void execute( ChallengeExecutionData executionData, Map subActions) { - AbstractChallenge.getFirstInstance(JumpAndRunChallenge.class).startWorldChallenge(); + Regions.global(Challenges.getInstance(), () -> AbstractChallenge.getFirstInstance(JumpAndRunChallenge.class).startWorldChallenge()); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index ef0f24619..2c9176528 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -1,7 +1,9 @@ package net.cyperia.challenges.plugin.challenges.custom.settings.action.impl; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.cyperia.challenges.plugin.challenges.type.helper.SubSettingsHelper; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.IRandom; import org.bukkit.*; import org.bukkit.entity.Entity; @@ -14,8 +16,8 @@ public class PlaceStructureAction extends EntityTargetAction { - private List structureKeys; - private List villageKeys; + private volatile List structureKeys; + private volatile List villageKeys; public PlaceStructureAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true).addChild(SubSettingsHelper.createStructureSettingsBuilder())); @@ -45,24 +47,28 @@ public void executeFor(Entity entity, Map subActions) { Location location = entity.getLocation(); String locationString = (int) location.getX() + " " + (int) location.getY() + " " + (int) location.getZ(); String command = String.format("minecraft:place structure %s %s", structureKey, locationString); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + Regions.global(Challenges.getInstance(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)); } private void reloadStructureKeys() { - structureKeys = StructureType.getStructureTypes().values().stream() + List structures = StructureType.getStructureTypes().values().stream() .map(StructureType::getKey) .collect(Collectors.toList()); - structureKeys.remove(StructureType.OCEAN_RUIN.getKey()); - structureKeys.add(NamespacedKey.minecraft("ocean_ruin_cold")); - structureKeys.add(NamespacedKey.minecraft("ocean_ruin_warm")); + structures.remove(StructureType.OCEAN_RUIN.getKey()); + structures.add(NamespacedKey.minecraft("ocean_ruin_cold")); + structures.add(NamespacedKey.minecraft("ocean_ruin_warm")); - villageKeys = new ArrayList<>(); - villageKeys.add(NamespacedKey.minecraft("village_desert")); - villageKeys.add(NamespacedKey.minecraft("village_plains")); - villageKeys.add(NamespacedKey.minecraft("village_savanna")); - villageKeys.add(NamespacedKey.minecraft("village_snowy")); - villageKeys.add(NamespacedKey.minecraft("village_taiga")); + List villages = new ArrayList<>(); + villages.add(NamespacedKey.minecraft("village_desert")); + villages.add(NamespacedKey.minecraft("village_plains")); + villages.add(NamespacedKey.minecraft("village_savanna")); + villages.add(NamespacedKey.minecraft("village_snowy")); + villages.add(NamespacedKey.minecraft("village_taiga")); + + // Entity threads can enter concurrently; villageKeys must be set before structureKeys is visible. + villageKeys = villages; + structureKeys = structures; } private NamespacedKey getStructureKey(StructureType structureType) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java index 438467474..bb8ffcf93 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java @@ -1,11 +1,13 @@ package net.cyperia.challenges.plugin.challenges.custom.settings.action.impl; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.cyperia.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.cyperia.challenges.plugin.challenges.custom.settings.action.IEntityTargetAction; import net.cyperia.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.cyperia.challenges.plugin.content.i18n.MessageKeySpace; import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -39,11 +41,13 @@ public void execute( String[] singleItem = subActions.get("single_item"); boolean single = singleItem != null && singleItem.length > 0 && singleItem[0].equals("enabled"); - for (Entity target : IEntityTargetAction.getTargets(executionData.getEntity(), subActions)) { - if (target instanceof Player player) { - giveRandomItemToPlayer(player, single); + IEntityTargetAction.getTargets(executionData.getEntity(), subActions).thenAccept(targets -> { + for (Entity target : targets) { + if (target instanceof Player player) { + Regions.entity(Challenges.getInstance(), player, () -> giveRandomItemToPlayer(player, single)); + } } - } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java index 063fefdf3..34b765dbb 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java @@ -25,8 +25,11 @@ public SwapRandomMobAction(String name) { @Override public void execute(ChallengeExecutionData executionData, Map subActions) { - List targets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions); - List swapTargets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions, "swap_targets"); + IEntityTargetAction.getTargets(executionData.getEntity(), subActions) + .thenAcceptBoth(IEntityTargetAction.getTargets(executionData.getEntity(), subActions, "swap_targets"), this::swap); + } + + private void swap(List targets, List swapTargets) { swapTargets.removeIf(entity -> !(entity instanceof LivingEntity)); long seed = random.nextLong(); Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java index 2507c013c..b5fad2851 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java @@ -1,9 +1,11 @@ package net.cyperia.challenges.plugin.challenges.custom.settings.action.impl; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.cyperia.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.cyperia.challenges.plugin.challenges.implementation.challenge.extraworld.WaterMLGChallenge; import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.cyperia.commons.bukkit.utils.misc.Regions; import java.util.Map; @@ -17,7 +19,7 @@ public WaterMLGAction(String name) { public void execute( ChallengeExecutionData executionData, Map subActions) { - AbstractChallenge.getFirstInstance(WaterMLGChallenge.class).startWorldChallenge(); + Regions.global(Challenges.getInstance(), () -> AbstractChallenge.getFirstInstance(WaterMLGChallenge.class).startWorldChallenge()); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java index 55871e6fe..1cdec852a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java @@ -1,19 +1,21 @@ package net.cyperia.challenges.plugin.challenges.custom.settings.action.impl; -import com.google.common.collect.Lists; import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.cyperia.challenges.plugin.challenges.custom.settings.action.PlayerTargetAction; import net.cyperia.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Player; import java.util.List; import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; public class WinChallengeAction extends PlayerTargetAction { - private final List winner = Lists.newLinkedList(); + private final List winner = new CopyOnWriteArrayList<>(); public WinChallengeAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); @@ -22,8 +24,10 @@ public WinChallengeAction(String name) { @Override public void execute(ChallengeExecutionData executionData, Map subActions) { super.execute(executionData, subActions); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> winner); - winner.clear(); + Regions.global(Challenges.getInstance(), () -> { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> winner); + winner.clear(); + }); } @Override diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java index aefaeeddc..f8c3a2fab 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java @@ -8,7 +8,7 @@ import net.cyperia.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.cyperia.challenges.plugin.utils.misc.MapUtils; import net.cyperia.commons.bukkit.utils.chat.ChatInputHandler; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -83,12 +83,12 @@ public class TextInputHandler implements ChatInputHandler { @Override public void handleChatInput(@NotNull AsyncChatEvent event, @NotNull String input) { if (!isValid.test(event.getPlayer(), input)) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Regions.nextTick(Challenges.getInstance(), event.getPlayer(), () -> { parentGenerator.decline(event.getPlayer()); }); return; } - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Regions.nextTick(Challenges.getInstance(), event.getPlayer(), () -> { parentGenerator.accept(event.getPlayer(), null, MapUtils.createStringArrayMap(getKey(), input)); }); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java index 88c7fda27..ac2f98a7c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java @@ -8,7 +8,6 @@ import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Material; -import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; @@ -44,7 +43,7 @@ public void onMove(PlayerMoveEvent event) { @ScheduledTask(ticks = 5, async = false) public void onFifthTick() { - for (Player player : Challenges.getInstance().getPlayerManager().getChallengePlayers()) { + Challenges.getInstance().getPlayerManager().forEachChallengePlayer(player -> { Material type = player.getLocation().getBlock().getType(); if (type == Material.WATER || type == Material.LAVA) { @@ -53,8 +52,7 @@ public void onFifthTick() { .data("liquid", type.name()) .execute(); } - } - + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/trigger/impl/NewChunkTrigger.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/trigger/impl/NewChunkTrigger.java index 1ed848402..d3542e57c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/trigger/impl/NewChunkTrigger.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/custom/settings/trigger/impl/NewChunkTrigger.java @@ -13,8 +13,10 @@ import net.cyperia.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnedEvent; import net.cyperia.challenges.plugin.utils.bukkit.misc.ChunkSet; import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Chunk; @@ -26,14 +28,13 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; /** * Fires when a player enters a chunk: every time, the first time anybody enters it, or the first time @@ -48,11 +49,11 @@ public class NewChunkTrigger extends ChallengeTrigger implements GamestateSaveab // Keyed by the challenge's unique name: two challenges using this trigger track "new" independently, // so a chunk another challenge already converted still counts as new for this one. - private final Map memories = new HashMap<>(); + private final Map memories = new ConcurrentHashMap<>(); // A join that also teleports fires two handlers for the same entry, each scheduling its own delayed // fire() for the same tick; without this, "every" mode would run its action for that chunk twice. - private final Map lastFired = new HashMap<>(); + private final Map lastFired = new ConcurrentHashMap<>(); public NewChunkTrigger(String name) { super(name, SubSettingsBuilder.createChooseItem(CHUNK).fill(builder -> { @@ -84,7 +85,7 @@ public void onIgnoreStatusChange(PlayerIgnoreStatusChangeEvent event) { // A respawn is an entry into the chunk it lands in, same as a move. @EventHandler(priority = EventPriority.MONITOR) - public void onRespawn(PlayerRespawnEvent event) { + public void onRespawn(PlayerRespawnedEvent event) { if (!canTrigger()) return; Player player = event.getPlayer(); if (AbstractChallenge.ignorePlayer(player)) return; @@ -113,10 +114,10 @@ public void onQuit(PlayerQuitEvent event) { public void onSecond() { if (!canTrigger()) return; - for (Player player : ChallengeAPI.getIngamePlayers()) { - if (AbstractChallenge.ignorePlayer(player)) continue; + Challenges.getInstance().getPlayerManager().forEachChallengePlayer(player -> { + if (AbstractChallenge.ignorePlayer(player)) return; createData().entity(player).data(CHUNK, NEW, NEW_PERSONAL).execute(); - } + }); } private void handleMove(@NotNull Player player, @NotNull Location from, @Nullable Location to) { @@ -135,7 +136,7 @@ private void handleMove(@NotNull Player player, @NotNull Location from, @Nullabl // The player is still standing where they came from while a move event runs, so the actions are // handed the trigger a tick later, when the player is in the chunk they entered. private void fire(@NotNull Player player, @NotNull String... chunk) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Regions.nextTick(Challenges.getInstance(), player, () -> { // A move followed by a quit in the same tick would otherwise run execute() against an offline player. if (!player.isOnline()) return; if (alreadyFiredThisTick(player)) return; @@ -183,7 +184,7 @@ public boolean isTriggerMet(@NotNull TriggerActionChallenge challenge, @NotNull if (!(data.getEntity() instanceof Player player)) return EVERY.equals(mode); Chunk chunk = player.getLocation().getChunk(); - Memory memory = memories.computeIfAbsent(challenge.getUniqueName(), name -> new Memory(new ChunkSet(), new HashMap<>())); + Memory memory = memories.computeIfAbsent(challenge.getUniqueName(), name -> new Memory(new ChunkSet(), new ConcurrentHashMap<>())); if (EVERY.equals(mode)) { memory.entered.add(chunk); @@ -280,7 +281,7 @@ public void loadGameState(@NotNull Document document) { for (String savedName : document.keys()) { Document challengeDocument = document.getDocument(savedName); String uniqueName = Challenges.getInstance().getCatalog().challenge(savedName).map(Challenge::id).orElse(savedName); - Memory memory = new Memory(new ChunkSet(), new HashMap<>()); + Memory memory = new Memory(new ChunkSet(), new ConcurrentHashMap<>()); memory.entered.loadGameState(challengeDocument, "entered-chunks"); Document playersDocument = challengeDocument.getDocument("players"); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index b1a8c0a8d..5f6557b69 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -3,6 +3,7 @@ import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; @@ -32,17 +33,19 @@ public void onDamage(@NotNull EntityDamageEvent event) { } private void handleDamage(@NotNull Player player) { - - Location location = player.getWorld().getHighestBlockAt(getRandomLocation(player.getWorld())).getLocation(); - location.setY(location.getY() + 1); - location.getChunk().load(true); - - if (getValue() == PLAYER) { - player.teleport(location); - } else { - broadcastFiltered(player1 -> player1.teleport(location)); - } - + World world = player.getWorld(); + Location random = getRandomLocation(world); + + world.getChunkAtAsync(random).thenAccept(chunk -> Regions.at(Challenges.getInstance(), random, () -> { + Location location = world.getHighestBlockAt(random).getLocation(); + location.setY(location.getY() + 1); + + if (getValue() == PLAYER) { + Regions.entity(Challenges.getInstance(), player, () -> player.teleportAsync(location)); + } else { + broadcastFiltered(player1 -> player1.teleportAsync(location)); + } + })); } public Location getRandomLocation(World world) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java index d099521de..71d704c84 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java @@ -19,7 +19,6 @@ public void onPickup(@NotNull PlayerPickupItemEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onClick(@NotNull PlayerInventoryClickEvent event) { - if (event.isCancelled()) return; // ignoreCancelled not working on own event if (!shouldExecuteEffect(event.getPlayer())) return; if (event.getAction() == InventoryAction.NOTHING) return; if (event.getCurrentItem() == null) return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index aef1f0b60..8fc40cc9b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -22,20 +22,20 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public class BlockEffectChallenge extends Setting { /* * Saving potion effect to prevent the possibility that an effect remove was somehow skipped */ - private Map currentPotionEffects = new HashMap<>(); + private Map currentPotionEffects = new ConcurrentHashMap<>(); @Override protected void onEnable() { - currentPotionEffects = new HashMap<>(); + currentPotionEffects = new ConcurrentHashMap<>(); if (!shouldExecuteEffect()) return; broadcastFiltered(player -> { addEffect(player, player.getLocation(), null); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 94fbd2b03..4ac2c039e 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -2,38 +2,59 @@ import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.NamespacedKey; import org.bukkit.World; +import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.event.world.EntitiesLoadEvent; +import org.bukkit.persistence.PersistentDataType; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; public class EntityRandomEffectChallenge extends Setting { + private static final NamespacedKey AFFECTED = new NamespacedKey(Challenges.getInstance(), "entity_random_effect"); + @Override protected void onEnable() { for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - addRandomEffect(entity); - } + Regions.forEachRegion(plugin, world, () -> world.getLivingEntities().forEach(this::addRandomEffect)); } } @Override protected void onDisable() { for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity.getType() == EntityType.PLAYER) continue; - for (PotionEffect effect : entity.getActivePotionEffects()) { - entity.removePotionEffect(effect.getType()); - } + Regions.forEachRegion(plugin, world, () -> world.getLivingEntities().forEach(EntityRandomEffectChallenge::removeEffects)); + } + } + + // Mobs in chunks nobody was near when the challenge ended lose their effects as the chunk loads + @EventHandler + public void onEntitiesLoad(@NotNull EntitiesLoadEvent event) { + if (isEnabled() || !ChallengeAPI.getGameWorlds().contains(event.getWorld())) return; + for (Entity entity : event.getEntities()) { + if (entity instanceof LivingEntity living && living.getPersistentDataContainer().has(AFFECTED)) { + Regions.nextTick(plugin, living, () -> removeEffects(living)); } } } + private static void removeEffects(@NotNull LivingEntity entity) { + if (entity.getType() == EntityType.PLAYER) return; + for (PotionEffect effect : entity.getActivePotionEffects()) { + entity.removePotionEffect(effect.getType()); + } + entity.getPersistentDataContainer().remove(AFFECTED); + } + @EventHandler(priority = EventPriority.HIGH) public void onSpawn(EntitySpawnEvent event) { if (!shouldExecuteEffect()) return; @@ -46,6 +67,7 @@ public void addRandomEffect(LivingEntity entity) { PotionEffectType[] types = PotionEffectType.values(); PotionEffectType type = globalRandom.choose(types); entity.addPotionEffect(type.createEffect(PotionEffect.INFINITE_DURATION, 255)); + entity.getPersistentDataContainer().set(AFFECTED, PersistentDataType.BOOLEAN, true); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index 3788193fc..bfcbc6eca 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -8,6 +8,7 @@ import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; import net.cyperia.challenges.plugin.utils.misc.TriConsumer; import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.pair.Tuple; import net.cyperia.commons.common.config.Document; import org.bukkit.Bukkit; @@ -80,7 +81,7 @@ public void onTimerPause() { public void onConsume(@NotNull PlayerItemConsumeEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; if (event.getItem().getType() != Material.MILK_BUCKET) return; - Bukkit.getScheduler().runTask(plugin, this::updateEffects); + Regions.nextTick(plugin, this::updateEffects); } @EventHandler(priority = EventPriority.HIGH) @@ -98,7 +99,7 @@ public void onPlayerItemConsume(@NotNull PlayerItemConsumeEvent event) { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerGameModeChange(@NotNull PlayerGameModeChangeEvent event) { if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, () -> { clearEffects(); updateEffects(); }); @@ -163,7 +164,7 @@ public void updateEffects() { }); } else { if (!ignorePlayer(player)) { - addEffect(player, effectType, amplifier); + Regions.entity(plugin, player, () -> addEffect(player, effectType, amplifier)); } } }); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index a62681796..0a0f176f6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -2,13 +2,13 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; +import org.bukkit.World; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.jetbrains.annotations.NotNull; -import java.util.Collection; - public class AllMobsToDeathPoint extends Setting { @EventHandler @@ -21,13 +21,15 @@ public void onEntityDeath(@NotNull EntityDeathByPlayerEvent event) { } private void teleportAllMobsOfType(@NotNull EntityType entityType, @NotNull Location location) { - if (location.getWorld() == null) return; - Collection entities = location.getWorld().getEntitiesByClasses(entityType.getEntityClass()); - for (Entity entity : entities) { - if (!(entity instanceof LivingEntity)) return; - ((LivingEntity) entity).setNoDamageTicks(20); - entity.teleport(location); - } + World world = location.getWorld(); + if (world == null) return; + Regions.forEachRegion(plugin, world, () -> { + for (Entity entity : world.getEntitiesByClasses(entityType.getEntityClass())) { + if (!(entity instanceof LivingEntity living)) continue; + living.setNoDamageTicks(20); + living.teleportAsync(location); + } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index b82c6922c..7817e7f75 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -4,6 +4,7 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.World; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; @@ -36,10 +37,12 @@ public void playEffects() { private void addEffectForEveryEntity() { for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity instanceof Player) continue; - addEffect(entity); - } + Regions.forEachRegion(plugin, world, () -> { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity instanceof Player) continue; + addEffect(entity); + } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 30a443821..edd806623 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -2,7 +2,6 @@ import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; -import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import org.bukkit.Location; import org.bukkit.entity.LivingEntity; @@ -18,9 +17,7 @@ public MobSightDamageChallenge() { @ScheduledTask(ticks = 1, async = false) public void onTick() { - - for (Player player : ChallengeHelper.getIngamePlayers()) { - + broadcastFiltered(player -> { RayTraceResult result = player.getWorld().rayTraceEntities( player.getEyeLocation(), player.getLocation().getDirection(), @@ -28,21 +25,20 @@ public void onTick() { 0.01, entity -> !(entity instanceof Player) && entity instanceof LivingEntity ); - if (result == null) continue; + if (result == null) return; Location location = result.getHitPosition().toLocation(player.getWorld()); LivingEntity entity = ((LivingEntity) result.getHitEntity()); - if (entity == null) continue; + if (entity == null) return; double distance = entity.getEyeLocation().distance(location) * 5; BoundingBox box = entity.getBoundingBox(); double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); - if (distance > volume) continue; + if (distance > volume) return; player.damage(getValue()); - } - + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 1b2b84fc1..2d0a618b8 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -1,9 +1,9 @@ package net.cyperia.challenges.plugin.challenges.implementation.challenge.entities; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; -import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.EnderDragon; @@ -21,9 +21,7 @@ public class StoneSightChallenge extends Setting { @ScheduledTask(ticks = 1, async = false) public void onTick() { - - for (Player player : ChallengeHelper.getIngamePlayers()) { - + broadcastFiltered(player -> { RayTraceResult result = player.getWorld().rayTraceEntities( player.getEyeLocation(), player.getLocation().getDirection(), @@ -31,24 +29,24 @@ public void onTick() { 0.01, entity -> !(entity instanceof Player) && !(entity instanceof EnderDragon) && entity instanceof LivingEntity ); - if (result == null) continue; + if (result == null) return; Location location = result.getHitPosition().toLocation(player.getWorld()); LivingEntity entity = ((LivingEntity) result.getHitEntity()); - if (entity == null) continue; + if (entity == null) return; double distance = entity.getEyeLocation().distance(location) * 5; BoundingBox box = entity.getBoundingBox(); double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); - if (distance > volume) continue; + if (distance > volume) return; - entity.getLocation().getBlock().setType(getRandomStone(), false); - entity.remove(); + Regions.entity(plugin, entity, () -> { + entity.getLocation().getBlock().setType(getRandomStone(), false); + entity.remove(); + }); SoundSample.BREAK.play(player); - - } - + }); } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index e7c6be660..f1f73ce10 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -11,6 +11,7 @@ import net.cyperia.challenges.plugin.utils.misc.BlockUtils; import net.cyperia.challenges.plugin.utils.misc.ParticleUtils; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import org.bukkit.*; import org.bukkit.block.Block; @@ -96,19 +97,22 @@ protected void startJumpAndRun() { buildNextJump(); teleportToWorld(true, (player, index) -> { player.setGameMode(player.getUniqueId().equals(currentPlayer) ? GameMode.SURVIVAL : GameMode.SPECTATOR); - player.teleport(new Location(getExtraWorld(), 0.5, 101, 0.5)); + player.teleportAsync(new Location(getExtraWorld(), 0.5, 101, 0.5)); }); } protected void buildNextJump() { - if (lastBlock != null) lastBlock.setType(Material.AIR); - - lastBlock = targetBlock != null ? targetBlock : getExtraWorld().getBlockAt(0, 100, 0); - lastBlock.setType(Material.GOLD_BLOCK); + Block previous = lastBlock; + Block start = targetBlock != null ? targetBlock : getExtraWorld().getBlockAt(0, 100, 0); + lastBlock = start; Material type = getRandomBlockType(); - targetBlock = new RandomJumpGenerator().next(globalRandom, lastBlock, type == Material.CYAN_TERRACOTTA || type == Material.EMERALD_BLOCK, type != Material.COBBLESTONE_WALL && type != Material.SPRUCE_FENCE); - targetBlock.setType(type); + Regions.at(plugin, start.getLocation(), () -> { + if (previous != null) previous.setType(Material.AIR); + start.setType(Material.GOLD_BLOCK); + targetBlock = new RandomJumpGenerator().next(globalRandom, start, type == Material.CYAN_TERRACOTTA || type == Material.EMERALD_BLOCK, type != Material.COBBLESTONE_WALL && type != Material.SPRUCE_FENCE); + targetBlock.setType(type); + }); } @NotNull @@ -157,11 +161,13 @@ protected void exitJumpAndRun() { } protected void breakJumpAndRun() { - if (lastBlock != null) lastBlock.setType(Material.AIR); - if (targetBlock != null) targetBlock.setType(Material.AIR); - + Block last = lastBlock; + Block target = targetBlock; lastBlock = null; targetBlock = null; + + if (last != null) Regions.at(plugin, last.getLocation(), () -> last.setType(Material.AIR)); + if (target != null) Regions.at(plugin, target.getLocation(), () -> target.setType(Material.AIR)); } @Override @@ -178,11 +184,13 @@ public void loadGameState(@NotNull Document document) { jumpAndRunsDone = document.getInt("jumpsDone", jumpAndRunsDone); } - @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.USED) + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.USED) public void spawnParticles() { - if (targetBlock == null) return; - ParticleUtils.spawnParticleCircle(targetBlock.getLocation().add(0.5, 1.05, 0.5), - Particle.INSTANT_EFFECT, Color.WHITE, 13, 0.35); + Block target = targetBlock; + if (target == null) return; + Location center = target.getLocation().add(0.5, 1.05, 0.5); + Regions.at(plugin, center, () -> ParticleUtils.spawnParticleCircle(center, + Particle.INSTANT_EFFECT, Color.WHITE, 13, 0.35)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java index eeb6e2ae0..79fa55fa1 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java @@ -4,9 +4,10 @@ import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.cyperia.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -24,16 +25,15 @@ public WaterMLGChallenge() { @Override public void startWorldChallenge() { - Location currentLocation = new Location(getExtraWorld(), 0, 150, 0); + World world = getExtraWorld(); teleportToWorld(false, (player, index) -> { - currentLocation.add(100, 0, 0); player.getInventory().setHeldItemSlot(4); player.getInventory().setItem(4, new ItemStack(Material.WATER_BUCKET)); - player.teleport(currentLocation); + player.teleportAsync(new Location(world, 100 * (index + 1), 150, 0)); }); - Bukkit.getScheduler().runTaskLater(plugin, () -> { + Regions.later(plugin, () -> { teleportBack(); restartTimer(); }, 10 * 20); @@ -43,9 +43,9 @@ public void startWorldChallenge() { public void onPlayerBucketEmpty(@NotNull PlayerBucketEmptyEvent event) { if (!isInExtraWorld()) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> { + Regions.later(plugin, event.getBlock().getLocation(), () -> { event.getBlock().setType(Material.AIR); - Bukkit.getScheduler().runTaskLater(plugin, () -> { + Regions.later(plugin, event.getPlayer(), () -> { teleportBack(event.getPlayer()); }, 40); }, 10); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 2b64abea6..76f612018 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -7,13 +7,11 @@ import net.cyperia.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.cyperia.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.cyperia.challenges.plugin.spigot.events.PlayerPickupItemEvent; +import net.cyperia.challenges.plugin.utils.item.CollectableItem; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; -import net.cyperia.challenges.plugin.utils.misc.ExperimentalUtils; -import net.cyperia.commons.bukkit.utils.item.ItemUtils; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import net.kyori.adventure.bossbar.BossBar; -import org.bukkit.Bukkit; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -22,13 +20,12 @@ import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; public class ForceItemChallenge extends CompletableForceChallenge { - private Material item; + private CollectableItem item; public ForceItemChallenge() { super(2, 15); @@ -46,26 +43,24 @@ protected BiConsumer setupBossbar() { bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(getChallengeMessageKey("bossbar-instruction"), item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); + bossbar.setTitle(getChallengeMessageKey("bossbar-instruction"), item.displayName(), ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @Override protected void broadcastFailedMessage() { - getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, item); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, item.displayName()); } @Override protected void broadcastSuccessMessage(@NotNull Player player) { - getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, player, item); + getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, player, item.displayName()); } @Override protected void chooseForcing() { - List items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - items.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); - items.removeIf(material -> !material.isItem()); - items.removeIf(BlockUtils::isTooHardToGet); + List items = new ArrayList<>(CollectableItem.obtainableInSurvival(false)); + items.removeIf(item -> BlockUtils.isTooHardToGet(item.material())); item = globalRandom.choose(items); } @@ -78,24 +73,21 @@ protected int getForcingTime() { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onClick(@NotNull PlayerInventoryClickEvent event) { ItemStack item = event.getCurrentItem(); - if (item == null) return; - if (item.getType() != this.item) return; + if (item == null || this.item == null || !this.item.matches(item)) return; completeForcing(event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPickUp(@NotNull PlayerPickupItemEvent event) { - Material material = event.getItem().getItemStack().getType(); - if (material != item) return; + if (item == null || !item.matches(event.getItem().getItemStack())) return; completeForcing(event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInteract(@NotNull PlayerInteractEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> { + Regions.later(plugin, event.getPlayer(), () -> { ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); - Material material = item.getType(); - if (material != this.item) return; + if (this.item == null || !this.item.matches(item)) return; completeForcing(event.getPlayer()); }, 1); } @@ -104,7 +96,8 @@ public void onInteract(@NotNull PlayerInteractEvent event) { public void loadGameState(@NotNull Document document) { super.loadGameState(document); if (document.contains("target")) { - item = document.getEnum("target", Material.class); + String target = document.getString("target"); + item = target == null ? null : CollectableItem.parse(target); setState(item == null ? WAITING : COUNTDOWN); } } @@ -112,7 +105,7 @@ public void loadGameState(@NotNull Document document) { @Override public void writeGameState(@NotNull Document document) { super.writeGameState(document); - document.set("target", item); + document.set("target", item == null ? null : item.id()); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index 1ca3b4a93..798caee91 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -22,6 +22,7 @@ import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; import net.cyperia.commons.bukkit.utils.menu.MenuPosition; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -77,7 +78,7 @@ protected void onEnable() { @Override protected void onDisable() { - games.values().forEach(Game::end); // hand every hidden item back instead of losing it + games.values().forEach(game -> Regions.entity(plugin, game.player, game::end)); // hand every hidden item back instead of losing it bossbar.hide(); } @@ -91,7 +92,7 @@ protected void onTimeActivation() { @ScheduledTask(ticks = 20, async = false, challengePolicy = ChallengeStatusPolicy.ENABLED) public void handleGuessSecond() { if (games.isEmpty()) return; // the waiting bossbar is refreshed by the scoreboard manager - games.values().forEach(Game::tick); + games.values().forEach(game -> Regions.entity(plugin, game.player, game::tick)); bossbar.update(); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index aeb9b534f..a60124092 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -5,20 +5,25 @@ import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.cyperia.challenges.plugin.spigot.events.PlayerPickupItemEvent; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.pair.Triple; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; -import java.util.HashMap; +import java.util.EnumSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public class NoDupedItemsChallenge extends Setting { @@ -26,17 +31,20 @@ public NoDupedItemsChallenge() { setUsesGlobalPunish(true); } + // What each player holds, kept by that player's own thread: an inventory can only be read there + private final Map> held = new ConcurrentHashMap<>(); + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; - checkInventories(); + refresh(event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityPickUpItem(@NotNull PlayerPickupItemEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> { + Regions.later(plugin, event.getPlayer(), () -> { if (!shouldExecuteEffect(event.getPlayer())) return; - checkInventories(); + refresh(event.getPlayer()); }, 1); } @@ -44,14 +52,30 @@ public void onEntityPickUpItem(@NotNull PlayerPickupItemEvent event) { public void onInteract(@NotNull PlayerInteractEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; if (event.getClickedBlock() == null) return; - checkInventories(); + refresh(event.getPlayer()); + } + + @EventHandler + public void onQuit(@NotNull PlayerQuitEvent event) { + held.remove(event.getPlayer().getUniqueId()); + } + + // Runs on the player's thread + private void refresh(@NotNull Player player) { + Set types = EnumSet.noneOf(Material.class); + for (ItemStack item : player.getInventory().getContents()) { + if (item != null) types.add(item.getType()); + } + held.put(player.getUniqueId(), types); + Regions.global(plugin, this::checkInventories); } private void checkInventories() { - Map> blackList = new HashMap<>(); + List checked = new ArrayList<>(); for (Player player : ChallengeHelper.getIngamePlayers()) { - Triple result = checkInventory(player, blackList); + Triple result = findDuplicate(player, checked); + checked.add(player); if (result != null) { getChallengeMessageKey("failed").broadcast( Prefix.CHALLENGES, @@ -59,34 +83,26 @@ private void checkInventories() { result.getSecond(), result.getThird() ); + // Both are rebuilt from their next inventory change, so a punished player is not reported again + held.remove(result.getFirst().getUniqueId()); + held.remove(result.getSecond().getUniqueId()); ChallengeHelper.punish(result.getFirst()); ChallengeHelper.punish(result.getSecond()); } - } - } - private Triple checkInventory(@NotNull Player player, Map> blacklist) { - List localBlacklist = new ArrayList<>(); - List playerBlacklist = blacklist.getOrDefault(player, new ArrayList<>()); - blacklist.put(player, playerBlacklist); - - for (ItemStack item : player.getInventory().getContents()) { - if (item == null) continue; - if (localBlacklist.contains(item.getType())) continue; - localBlacklist.add(item.getType()); - - for (Map.Entry> entry : blacklist.entrySet()) { - List currentBlacklist = entry.getValue(); - if (currentBlacklist.contains(item.getType())) { - return new Triple<>(player, entry.getKey(), item.getType()); - } + @Nullable + private Triple findDuplicate(@NotNull Player player, @NotNull List others) { + Set types = held.get(player.getUniqueId()); + if (types == null) return null; + for (Material type : types) { + for (Player other : others) { + Set otherTypes = held.get(other.getUniqueId()); + if (otherTypes != null && otherTypes.contains(type)) return new Triple<>(player, other, type); } - playerBlacklist.add(item.getType()); } - return null; } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 8298d48fa..eebc7f750 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -4,6 +4,7 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -37,9 +38,10 @@ private void teleportRandom(@NotNull Player player) { Entity targetEntity = list.get(globalRandom.nextInt(list.size())); Location playerLocation = player.getLocation().clone(); - player.teleport(targetEntity.getLocation()); - getChallengeMessageKey("teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); - targetEntity.teleport(playerLocation); + player.teleportAsync(targetEntity.getLocation()).thenAccept(success -> { + getChallengeMessageKey("teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); + Regions.entity(plugin, targetEntity, () -> targetEntity.teleportAsync(playerLocation)); + }); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 9374c255b..daeb0c43b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -7,7 +7,7 @@ public class AlwaysRunningChallenge extends Setting { - @ScheduledTask(ticks = 1) + @ScheduledTask(ticks = 1, async = false) public void setVelocity() { broadcastFiltered(player -> { if (player.isSprinting()) return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 0034bddc0..666b73e57 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -14,14 +14,14 @@ import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class DontStopRunningChallenge extends SettingModifier { private static final int YELLOW = 5, RED = 3; - private final Map playerStandingCount = new HashMap<>(); + private final Map playerStandingCount = new ConcurrentHashMap<>(); public DontStopRunningChallenge() { super(3, 30, 10); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 58e2e3e23..c9be85340 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -5,8 +5,8 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; @@ -21,14 +21,14 @@ import org.bukkit.event.world.LootGenerateEvent; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public class FiveHundredBlocksChallenge extends SettingModifier { - private final Map blocksWalked = new HashMap<>(); + private final Map blocksWalked = new ConcurrentHashMap<>(); public FiveHundredBlocksChallenge() { super(1, 5, 5); @@ -122,7 +122,7 @@ private boolean updateOrReset(@NotNull Player player) { this.blocksWalked.put(uuid, blocksWalked); - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + Regions.async(plugin, () -> { bossbar.update(player); }); return reached; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index 35307e2cc..e51decd62 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -5,36 +5,36 @@ import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; -import org.bukkit.entity.Player; import java.util.AbstractMap.SimpleEntry; -import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public class MoveMouseDamage extends SettingModifier { - private final Map> lastView = new HashMap<>(); + private final Map> lastView = new ConcurrentHashMap<>(); public MoveMouseDamage() { super(60); setValueUnit(ValueUnit.DAMAGE); } - @ScheduledTask(ticks = 1, timerPolicy = TimerPolicy.ALWAYS) + @ScheduledTask(ticks = 1, async = false, timerPolicy = TimerPolicy.ALWAYS) public void onTick() { if (!shouldExecuteEffect()) { lastView.clear(); return; } - for (Player player : Bukkit.getOnlinePlayers()) { + plugin.getPlayerManager().forEachOnOwnThread(Bukkit.getOnlinePlayers(), player -> { if (ignorePlayer(player)) { lastView.remove(player.getUniqueId()); - continue; + return; } - if (player.getNoDamageTicks() > 0) continue; + if (player.getNoDamageTicks() > 0) return; float yaw = player.getLocation().getYaw(); float pitch = player.getLocation().getPitch(); @@ -42,15 +42,15 @@ public void onTick() { lastView.put(player.getUniqueId(), pair); if (yaw != pair.getKey() || pitch != pair.getValue()) { - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, player, () -> { if (player.getNoDamageTicks() > 0) return; getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, player); player.damage(getValue()); player.setNoDamageTicks(5); - Bukkit.getScheduler().runTaskLater(plugin, () -> lastView.remove(player.getUniqueId()), 3); + Regions.later(plugin, () -> lastView.remove(player.getUniqueId()), 3); }); } - } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 5da2e0380..31899dc0c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -21,6 +21,7 @@ import net.cyperia.challenges.plugin.spigot.events.PlayerJumpEvent; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.IRandom; import net.cyperia.commons.common.config.Document; import net.kyori.adventure.bossbar.BossBar; @@ -211,7 +212,7 @@ public void handleQuestionSecond() { if (active.getSecondsLeft() <= 1) { messageKey("time-up").broadcast(Prefix.QUIZ); revealSolution(player, active.getQuestion()); - punish(player); + Regions.entity(plugin, player, () -> punish(player)); endQuestion(); return; } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 2f1047b34..4cd3a4926 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -6,7 +6,7 @@ import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; import net.cyperia.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; @@ -55,7 +55,7 @@ protected void onTimeActivation() { @TimerTask(status = TimerStatus.RUNNING) public void onStart() { // Execute after hotbar items are removed - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, () -> { broadcastFiltered(player -> { addItems(player, false); }); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index 7e55f8a1a..5e05cc75f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -8,7 +8,7 @@ import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; import net.cyperia.challenges.plugin.utils.misc.ExperimentalUtils; import net.cyperia.challenges.plugin.utils.misc.ListBuilder; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -35,7 +35,8 @@ public class MobRandomizerChallenge extends RandomizerSetting { private final Map entityRandomizer = new LinkedHashMap<>(); - private boolean inSpawn = false; + // spawn events fire synchronously on the spawning thread, and spawns run on several region threads + private final ThreadLocal inSpawn = ThreadLocal.withInitial(() -> false); @Override protected void onEnable() { @@ -71,16 +72,16 @@ public void onEntitiesLoad(@NotNull EntitiesLoadEvent event) { List entities = event.getEntities(); // replacing entities while the chunk is still loading them is not safe - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - for (Entity entity : entities) { + for (Entity entity : entities) { + Regions.nextTick(Challenges.getInstance(), entity, () -> { if (entity instanceof LivingEntity living && living.isValid()) action.accept(living); - } - }); + }); + } } private void forEachLoadedEntity(@NotNull Consumer action) { for (World world : ChallengeAPI.getGameWorlds()) { - world.getLivingEntities().forEach(action); + Regions.forEachRegion(plugin, world, () -> world.getLivingEntities().forEach(action)); } } @@ -106,13 +107,13 @@ private void replace(@NotNull Entity entity, @NotNull EntityType type, @Nullable } private void spawn(@NotNull Location location, @NotNull EntityType type, @Nullable EntityType original) { - inSpawn = true; + inSpawn.set(true); try { Entity spawned = location.getWorld().spawnEntity(location, type); if (original != null) spawned.getPersistentDataContainer().set(ORIGINAL_TYPE, PersistentDataType.STRING, original.getKey().toString()); } finally { - inSpawn = false; + inSpawn.set(false); } } @@ -153,7 +154,7 @@ public List getSpawnAbleEntities() { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onEntitySpawn(@NotNull EntitySpawnEvent event) { if (!shouldExecuteEffect()) return; - if (inSpawn) return; + if (inSpawn.get()) return; EntityType type = entityRandomizer.get(event.getEntityType()); if (type == null) return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index 897fb92ce..9dee99b6e 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -1,6 +1,7 @@ package net.cyperia.challenges.plugin.challenges.implementation.challenge.randomizer; import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.challenges.plugin.challenges.type.EntryAccess; import net.cyperia.challenges.plugin.challenges.type.IChallenge; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; @@ -66,8 +67,10 @@ protected void onTimeActivation() { challenges.remove(this); challenges.removeIf(challenge -> challenge.getMenu() != MenuType.CHALLENGES); challenges.removeIf(challenge -> !(challenge instanceof AbstractChallenge)); + // a pick turns the challenge on for everyone, past the permission of one that names one challenges.removeIf(challenge -> challenge instanceof LockedEntry - || ((AbstractChallenge) challenge).getCatalogEntry().excludeFromRandom()); + || ((AbstractChallenge) challenge).getCatalogEntry().excludeFromRandom() + || EntryAccess.hasPermission(challenge)); challenges.removeIf(IChallenge::isEnabled); if (challenges.isEmpty()) return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index e09278da3..e8d4836d8 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -6,7 +6,7 @@ import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.commons.bukkit.utils.logging.Logger; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World.Environment; @@ -120,15 +120,14 @@ public ReplaceOresEvent() { @Override public void run(@NotNull Player player) { Location location = player.getLocation(); - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + Regions.async(plugin, () -> { for (int x = -100; x <= 100; x++) { for (int z = -100; z <= 100; z++) { - int finalZ = z; - int finalX = x; - Bukkit.getScheduler().runTask(plugin, () -> { + Location column = location.clone().add(x, 0, z); + Regions.nextTick(plugin, column, () -> { if (location.getWorld() == null) return; for (int y = location.getWorld().getMinHeight(); y < 80; y++) { - Location current = location.clone().add(finalX, 0, finalZ); + Location current = column.clone(); current.setY(y); Block block = current.getBlock(); if (block.getType().name().contains("ORE")) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index 42b613acb..e724f9f41 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -3,7 +3,7 @@ import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -36,7 +36,7 @@ public static void dropRandomItem(@NotNull Location location, @NotNull Inventory protected void onTimeActivation() { restartTimer(); - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, () -> { broadcastFiltered(RandomItemDroppingChallenge::dropRandomItem); }); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index 090f4ebd4..2927d9a02 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -2,10 +2,8 @@ import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.TimedChallenge; -import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; +import net.cyperia.commons.bukkit.utils.misc.Regions; public class RandomItemRemovingChallenge extends TimedChallenge { @@ -18,13 +16,13 @@ public RandomItemRemovingChallenge() { protected void onTimeActivation() { restartTimer(); - for (Player player : ChallengeHelper.getIngamePlayers()) { - if (player.getInventory().getContents().length == 0) continue; + broadcastFiltered(player -> { + if (player.getInventory().getContents().length == 0) return; - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, player, () -> { InventoryUtils.removeRandomItem(player.getInventory()); }); - } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 90c40be99..3e114b417 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -3,7 +3,7 @@ import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; @@ -39,7 +39,7 @@ private static void swapItemToRandomSlot(@NotNull Inventory inventory, int slot1 protected void onTimeActivation() { restartTimer(); - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, () -> { broadcastFiltered(RandomItemSwappingChallenge::swapRandomItems); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index 1f76774d6..42d0dea35 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -2,6 +2,7 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.LivingEntity; @@ -9,19 +10,21 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; public class RandomTeleportOnHitChallenge extends Setting { public static void switchEntityLocations(LivingEntity entity1, LivingEntity entity2) { - entity1.setInvisible(true); - entity2.setInvisible(false); + Regions.entity(plugin, entity1, () -> entity1.setInvisible(true)); + Regions.entity(plugin, entity2, () -> entity2.setInvisible(false)); Location entity2Location = entity2.getLocation().clone(); - entity2.teleport(entity1.getLocation()); - entity1.teleport(entity2Location); - entity2.setInvisible(false); - entity1.setInvisible(false); + entity2.teleportAsync(entity1.getLocation()) + .thenCompose(success -> entity1.teleportAsync(entity2Location)) + .thenRun(() -> { + Regions.entity(plugin, entity2, () -> entity2.setInvisible(false)); + Regions.entity(plugin, entity1, () -> entity1.setInvisible(false)); + }); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -29,11 +32,13 @@ public void onEntityDamageByPlayer(EntityDamageByPlayerEvent event) { if (!shouldExecuteEffect(event.getDamager())) return; World world = event.getDamager().getWorld(); - List livingEntities = new ArrayList<>(world.getLivingEntities()); - livingEntities.removeIf(entity -> entity == event.getDamager() || entity instanceof Player && ignorePlayer((Player) entity)); - LivingEntity entity = globalRandom.choose(livingEntities); - - switchEntityLocations(entity, event.getDamager()); + List livingEntities = new CopyOnWriteArrayList<>(); + // The candidates of every region are gathered before one is chosen, the swap then runs on the global region + Regions.forEachRegion(plugin, world, () -> livingEntities.addAll(world.getLivingEntities())).thenRun(() -> { + livingEntities.removeIf(entity -> entity == event.getDamager() || entity instanceof Player && ignorePlayer((Player) entity)); + if (livingEntities.isEmpty()) return; + switchEntityLocations(globalRandom.choose(livingEntities), event.getDamager()); + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index afc7c40d2..2f94e2379 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -5,26 +5,30 @@ import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.cyperia.challenges.plugin.utils.item.DefaultItems; -import org.bukkit.Location; +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.NamespacedKey; import org.bukkit.World; -import org.bukkit.World.Environment; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.event.world.EntitiesLoadEvent; import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; -import java.util.Map; import java.util.Random; +import java.util.function.Consumer; public class RandomizedHPChallenge extends SettingModifier { + private static final NamespacedKey ORIGINAL_HEALTH = new NamespacedKey(Challenges.getInstance(), "randomized_hp_original"); + private final Random random = new Random(); public RandomizedHPChallenge() { @@ -61,50 +65,51 @@ private void randomizeEntityHealth(@NotNull LivingEntity entity) { AttributeInstance attribute = entity.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return; - if (!isEnabled()) { - attribute.setBaseValue(attribute.getDefaultValue()); - entity.setHealth(attribute.getDefaultValue()); - return; - } + // The health the mob had before, kept on the mob so it can be restored even when it is far from every player + PersistentDataContainer data = entity.getPersistentDataContainer(); + if (!data.has(ORIGINAL_HEALTH)) data.set(ORIGINAL_HEALTH, PersistentDataType.DOUBLE, attribute.getBaseValue()); int health = random.nextInt(getValue() * 100) + 1; attribute.setBaseValue(health); entity.setHealth(health); } - private void randomizeExistingEntityHealth() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - randomizeEntityHealth(entity); - } + private void restoreEntityHealth(@NotNull LivingEntity entity) { + Double original = entity.getPersistentDataContainer().get(ORIGINAL_HEALTH, PersistentDataType.DOUBLE); + if (original == null) return; + entity.getPersistentDataContainer().remove(ORIGINAL_HEALTH); + + AttributeInstance attribute = entity.getAttribute(Attribute.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(original); + entity.setHealth(original); + } + + // Mobs in chunks nobody was near when the challenge ended get their health back as the chunk loads + @EventHandler + public void onEntitiesLoad(@NotNull EntitiesLoadEvent event) { + if (isEnabled() || !ChallengeAPI.getGameWorlds().contains(event.getWorld())) return; + for (Entity entity : event.getEntities()) { + if (entity instanceof LivingEntity living) Regions.nextTick(plugin, living, () -> restoreEntityHealth(living)); } } + // A disabled challenge leaves no randomized health behind, which also cleans up mobs saved by an earlier run + private void randomizeExistingEntityHealth() { + forEachMob(entity -> { + if (isEnabled()) randomizeEntityHealth(entity); + else restoreEntityHealth(entity); + }); + } + private void resetExistingEntityHealth() { - Map entityDefaultHealth = new HashMap<>(); - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity instanceof Player) continue; - EntityType type = entity.getType(); - double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); - entityDefaultHealth.put(type, health); - - AttributeInstance attribute = entity.getAttribute(Attribute.MAX_HEALTH); - if (attribute == null) return; - attribute.setBaseValue(health); - entity.setHealth(health); - } - } + forEachMob(this::restoreEntityHealth); } - private double getDefaultHealth(@NotNull EntityType entityType) { - World world = ChallengeAPI.getGameWorld(Environment.NORMAL); - Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); - entity.remove(); - if (!(entity instanceof LivingEntity)) return 0; - AttributeInstance attribute = ((LivingEntity) entity).getAttribute(Attribute.MAX_HEALTH); - if (attribute == null) return 10; - return attribute.getBaseValue(); + private void forEachMob(@NotNull Consumer action) { + for (World world : ChallengeAPI.getGameWorlds()) { + Regions.forEachRegion(plugin, world, () -> world.getLivingEntities().forEach(action)); + } } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index 11d4b2c00..a285a29a9 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -5,8 +5,8 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.kyori.adventure.bossbar.BossBar; -import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; @@ -47,7 +47,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; if (event.getTo() == null) return; if (event.getFrom().getBlockY() == event.getTo().getBlockY()) return; - Bukkit.getScheduler().runTask(plugin, () -> bossbar.update(event.getPlayer())); + Regions.nextTick(plugin, event.getPlayer(), () -> bossbar.update(event.getPlayer())); } @ScheduledTask(ticks = 20) diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index 302e19c3a..e7299d2b9 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -1,11 +1,12 @@ package net.cyperia.challenges.plugin.challenges.implementation.challenge.world; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; -import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.management.scheduler.task.TimerTask; import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.*; @@ -19,6 +20,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; public class AnvilRainChallenge extends MenuSetting { @@ -61,12 +64,14 @@ public void onPause() { private void removeAnvils() { for (World world : Bukkit.getWorlds()) { - for (FallingBlock entity : world.getEntitiesByClass(FallingBlock.class)) { - // TODO: SWITCH CASE - String name = entity.getBlockData().getMaterial().name(); - if (!name.contains("ANVIL")) continue; - entity.remove(); - } + Regions.forEachRegion(plugin, world, () -> { + for (FallingBlock entity : world.getEntitiesByClass(FallingBlock.class)) { + // TODO: SWITCH CASE + String name = entity.getBlockData().getMaterial().name(); + if (!name.contains("ANVIL")) continue; + entity.remove(); + } + }); } } @@ -82,24 +87,25 @@ public void onSecond() { } private void handleTimeActivation() { - List chunks = new ArrayList<>(); - for (Player player : ChallengeHelper.getIngamePlayers()) { + Set chunks = ConcurrentHashMap.newKeySet(); + Challenges.getInstance().getPlayerManager().forEachChallengePlayer(player -> { List targetChunks = getTargetChunks(player.getLocation().getChunk()); for (Chunk targetChunk : targetChunks) { - if (chunks.contains(targetChunk)) continue; - chunks.add(targetChunk); + if (!chunks.add(targetChunk)) continue; spawnAnvils(targetChunk, getAnvilHeight(player.getLocation().getBlockY())); } - } + }); } private void spawnAnvils(@NotNull Chunk chunk, int height) { - for (int i = 0; i < getCount(); i++) { - Block block = getRandomBlockInChunk(chunk, height); - Location location = block.getLocation().add(0.5, 0, 0.5); - block.getWorld().spawnFallingBlock(location, Material.ANVIL, ((byte) 0)); - } + Regions.at(plugin, new Location(chunk.getWorld(), chunk.getX() * 16 + 8, height, chunk.getZ() * 16 + 8), () -> { + for (int i = 0; i < getCount(); i++) { + Block block = getRandomBlockInChunk(chunk, height); + Location location = block.getLocation().add(0.5, 0, 0.5); + block.getWorld().spawnFallingBlock(location, Material.ANVIL, ((byte) 0)); + } + }); } private List getTargetChunks(@NotNull Chunk origin) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java index 7166ab5cc..f730c14b7 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java @@ -1,9 +1,9 @@ package net.cyperia.challenges.plugin.challenges.implementation.challenge.world; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; -import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; @@ -20,9 +20,7 @@ public class BedrockPathChallenge extends Setting { // jumps can last a single tick that the moves of a lagging client arrive around. @ScheduledTask(ticks = 1, async = false) public void checkGround() { - for (Player player : Bukkit.getOnlinePlayers()) { - pave(player, player.getLocation()); - } + Challenges.getInstance().getPlayerManager().forEachAudience(player -> pave(player, player.getLocation())); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index bca429564..1169d8b6b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -3,6 +3,7 @@ import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; @@ -29,7 +30,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { if (location == null) return; if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + Regions.asyncLater(plugin, () -> { World world = event.getPlayer().getWorld(); List blocks = new ArrayList<>(); @@ -39,7 +40,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { blocks.add(blockLocation.getBlock()); } - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, location, () -> { for (Block block : blocks) { block.setType(Material.BEDROCK, false); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index 0267fcf4d..b9aca9582 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -2,7 +2,7 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.FallingBlock; @@ -22,7 +22,7 @@ public void onMove(PlayerMoveEvent event) { if (blockBelow == null) return; if (!blockBelow.getType().isSolid()) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> { + Regions.later(plugin, blockBelow.getLocation(), () -> { boostBlockInAir(blockBelow); }, 20); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index d779136a6..27d60382b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -1,23 +1,23 @@ package net.cyperia.challenges.plugin.challenges.implementation.challenge.world; +import io.papermc.paper.threadedregions.scheduler.ScheduledTask; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class BlocksDisappearAfterTimeChallenge extends SettingModifier { - private final Map tasks = new HashMap<>(); + private final Map tasks = new ConcurrentHashMap<>(); public BlocksDisappearAfterTimeChallenge() { super(60, 300); @@ -28,7 +28,7 @@ public BlocksDisappearAfterTimeChallenge() { public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; - BukkitTask oldTask = tasks.remove(event.getBlock()); + ScheduledTask oldTask = tasks.remove(event.getBlock()); if (oldTask != null) oldTask.cancel(); tasks.put(event.getBlock(), runTask(event.getBlock())); @@ -38,12 +38,12 @@ public void onBlockPlace(@NotNull BlockPlaceEvent event) { public void onBlockPlace(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; - BukkitTask oldTask = tasks.remove(event.getBlock()); + ScheduledTask oldTask = tasks.remove(event.getBlock()); if (oldTask != null) oldTask.cancel(); } - private BukkitTask runTask(@NotNull Block block) { - return Bukkit.getScheduler().runTaskLater(plugin, () -> block.setType(Material.AIR), getValue() * 20L); + private ScheduledTask runTask(@NotNull Block block) { + return Regions.later(plugin, block.getLocation(), () -> block.setType(Material.AIR), getValue() * 20L); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index 453ae7ef2..b94ee49fc 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -3,13 +3,14 @@ import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.TimedChallenge; -import net.cyperia.challenges.plugin.utils.misc.ListBuilder; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.*; import org.bukkit.block.Block; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; public class ChunkDeconstructionChallenge extends TimedChallenge { @@ -22,19 +23,22 @@ public ChunkDeconstructionChallenge() { protected void onTimeActivation() { if (ChallengeAPI.isWorldInUse()) return; - for (Chunk chunk : getChunksToDeconstruct()) { - if (!chunk.isLoaded()) continue; + Set chunks = ConcurrentHashMap.newKeySet(); + broadcastFiltered(player -> { + Chunk chunk = player.getLocation().getChunk(); + if (!chunks.add(chunk) || !chunk.isLoaded()) return; deconstructChunk(chunk); - } + }); restartTimer(); } private void deconstructChunk(@NotNull Chunk chunk) { + Location center = new Location(chunk.getWorld(), chunk.getX() * 16 + 8, 0, chunk.getZ() * 16 + 8); for (int x = 0; x < 16; x++) { int finalX = x; - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, center, () -> { for (int z = 0; z < 16; z++) { deconstructAtLocation(chunk.getBlock(finalX, 0, z)); } @@ -67,10 +71,4 @@ private boolean isBreakable(@NotNull Block block) { return block.getType() != Material.BEDROCK && !block.getType().isAir() && !block.isLiquid(); } - private List getChunksToDeconstruct() { - return new ListBuilder().fill(builder -> - broadcastFiltered(player -> builder.addIfNotContains(player.getLocation().getChunk())) - ).build(); - } - } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index 7afbd5ea0..105e91524 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -6,10 +6,11 @@ import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.utils.bukkit.misc.ChunkFillQueue; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.pair.Tuple; import net.kyori.adventure.bossbar.BossBar; -import org.bukkit.Bukkit; import org.bukkit.Chunk; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; @@ -17,7 +18,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -26,7 +26,7 @@ public class ChunkDeletionChallenge extends SettingModifier { private final ChunkFillQueue fills = new ChunkFillQueue(); - private final Map> chunks = new ConcurrentHashMap<>(); // access from concurrent threads + private final Map> chunks = new ConcurrentHashMap<>(); // access from concurrent threads public ChunkDeletionChallenge() { super(10, 120, 60); @@ -39,7 +39,7 @@ protected void onEnable() { MessageKey message = getChallengeMessageKey("bossbar"); bossbar.setColor(BossBar.Color.PINK); if (!checkIfAllowed(player)) { - Tuple taskTuple = chunks.get(player.getLocation().getChunk()); + Tuple taskTuple = chunks.get(player.getLocation().getChunk()); if (taskTuple != null) { long remainingTime = calculateRemainingTime(taskTuple.getSecond()); bossbar.setTitle(message, ChallengeAPI.formatTime(remainingTime)); @@ -101,15 +101,16 @@ private boolean checkIfAllowed(@NotNull Player player) { private void scheduleChunkDeletion(Chunk chunk) { chunks.computeIfAbsent(chunk, key -> { long timer = getValue() * 20L; - BukkitTask bukkitTask = Bukkit.getScheduler().runTaskLater(plugin, () -> { + Location center = new Location(chunk.getWorld(), chunk.getX() * 16 + 8, 0, chunk.getZ() * 16 + 8); + io.papermc.paper.threadedregions.scheduler.ScheduledTask bukkitTask = Regions.later(plugin, center, () -> { if (!shouldExecuteEffect()) { - BukkitTask task = chunks.remove(chunk).getFirst(); + io.papermc.paper.threadedregions.scheduler.ScheduledTask task = chunks.remove(chunk).getFirst(); if (task != null) { task.cancel(); } return; } - BukkitTask task = chunks.remove(chunk).getFirst(); + io.papermc.paper.threadedregions.scheduler.ScheduledTask task = chunks.remove(chunk).getFirst(); if (task != null) { task.cancel(); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java index 048ab6fb0..b6e6533e7 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java @@ -1,10 +1,11 @@ package net.cyperia.challenges.plugin.challenges.implementation.challenge.world; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; @@ -16,13 +17,13 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public class FloorIsLavaChallenge extends SettingModifier { - private final Map standingOn = new HashMap<>(); + private final Map standingOn = new ConcurrentHashMap<>(); public FloorIsLavaChallenge() { super(1, 60, 30); @@ -39,9 +40,7 @@ protected void onDisable() { // jumps can last a single tick that the moves of a lagging client arrive around. @ScheduledTask(ticks = 1, async = false) public void checkGround() { - for (Player player : Bukkit.getOnlinePlayers()) { - step(player, player.getLocation()); - } + Challenges.getInstance().getPlayerManager().forEachAudience(player -> step(player, player.getLocation())); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -61,9 +60,10 @@ private void step(@NotNull Player player, @NotNull Location at) { Block ground = BlockUtils.getSolidGround(player, at); if (ground == null || ground.equals(standingOn.put(player.getUniqueId(), ground))) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> { + Location groundLocation = ground.getLocation(); + Regions.later(plugin, groundLocation, () -> { BlockUtils.setBlockNatural(ground, Material.MAGMA_BLOCK, true); - Bukkit.getScheduler().runTaskLater(plugin, () -> BlockUtils.setBlockNatural(ground, Material.LAVA, true), getValue() * 20L); + Regions.later(plugin, groundLocation, () -> BlockUtils.setBlockNatural(ground, Material.LAVA, true), getValue() * 20L); }, getValue() * 20L); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 433105917..29411633a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -8,6 +8,7 @@ import net.cyperia.challenges.plugin.management.scheduler.task.TimerTask; import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; import net.cyperia.challenges.plugin.management.server.BorderManager; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -80,14 +81,14 @@ public void onLevelChange(@NotNull PlayerLevelChangeEvent event) { public void onPlayerJoin(@NotNull PlayerJoinEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); + Regions.later(plugin, () -> checkBorderSize(false), 1); } @EventHandler(priority = EventPriority.HIGH) public void onPlayerLeave(@NotNull PlayerQuitEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); + Regions.later(plugin, () -> checkBorderSize(false), 1); } /** diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 66e8aba74..1bb17fed7 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.challenges.implementation.challenge.world; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.content.i18n.Prefix; @@ -10,6 +11,7 @@ import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.item.ItemUtils; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; @@ -37,11 +39,12 @@ import org.jetbrains.annotations.NotNull; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; public class LoopChallenge extends Setting { - private static final Map loops = new HashMap<>(); + private static final Map loops = new ConcurrentHashMap<>(); @ScheduledTask(ticks = 1, async = false) public void onTick() { @@ -50,8 +53,9 @@ public void onTick() { for (Map.Entry entry : new ArrayList<>(loops.entrySet())) { if (entry.getValue() + 1000 <= currentTimeMillis) { - entry.getKey().execute(); - loops.put(entry.getKey(), currentTimeMillis); + Loop loop = entry.getKey(); + loop.schedule(loop::execute); + loops.put(loop, currentTimeMillis); } } @@ -129,6 +133,8 @@ private interface Loop { void execute(); + void schedule(@NotNull Runnable task); + default void cancel() { loops.remove(this); } @@ -147,6 +153,11 @@ public ProjectileLaunchLoop(ProjectileLaunchEvent event) { this.entityType = event.getEntityType(); } + @Override + public void schedule(@NotNull Runnable task) { + Regions.at(Challenges.getInstance(), launchLocation, task); + } + @Override public void execute() { if (launchLocation.getWorld() == null) return; @@ -169,6 +180,11 @@ public EntityDamageLoop(LivingEntity entity, DamageCause cause, double damage) { this.damage = damage; } + @Override + public void schedule(@NotNull Runnable task) { + Regions.entity(Challenges.getInstance(), entity, task, this::cancel); + } + @Override public void execute() { if (entity.isDead()) { @@ -194,6 +210,11 @@ public BlockPlaceLoop(Material material, Player player, BlockFace blockFace, Blo this.currentBlock = currentBlock; } + @Override + public void schedule(@NotNull Runnable task) { + Regions.at(Challenges.getInstance(), currentBlock.getLocation(), task); + } + @Override public void execute() { if (ignorePlayer(player)) return; @@ -237,6 +258,11 @@ public BlockBreakLoop(ItemStack itemStack, Player player, BlockFace blockFace, B this.currentBlock = currentBlock; } + @Override + public void schedule(@NotNull Runnable task) { + Regions.at(Challenges.getInstance(), currentBlock.getLocation(), task); + } + @Override public void execute() { if (ignorePlayer(player)) return; @@ -314,6 +340,11 @@ public DropLoop(ItemStack itemStack, Player player) { this.player = player; } + @Override + public void schedule(@NotNull Runnable task) { + Regions.entity(Challenges.getInstance(), player, task, this::cancel); + } + @Override public void execute() { if (ignorePlayer(player)) return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index aacdb84f9..91054b106 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -1,15 +1,17 @@ package net.cyperia.challenges.plugin.challenges.implementation.challenge.world; import com.google.common.collect.Lists; -import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.pair.Triple; import net.cyperia.commons.common.config.Document; import net.cyperia.commons.common.config.document.GsonDocument; import org.bukkit.Bukkit; import org.bukkit.Chunk; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; @@ -27,11 +29,12 @@ import org.jetbrains.annotations.NotNull; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; public class RepeatInChunkChallenge extends Setting { - private final Map, BlockData>> changedBlocks = new HashMap<>(); - private final Set updatedChunks = new HashSet<>(); + private final Map, BlockData>> changedBlocks = new ConcurrentHashMap<>(); + private final Set updatedChunks = ConcurrentHashMap.newKeySet(); @Override public void writeGameState(@NotNull Document document) { @@ -67,7 +70,7 @@ public void loadGameState(@NotNull Document document) { for (World world : Bukkit.getWorlds()) { List list = changedDocument.getDocumentList(world.getName()); - Map, BlockData> blockMap = changedBlocks.getOrDefault(world.getName(), new HashMap<>()); + Map, BlockData> blockMap = changedBlocks.getOrDefault(world.getName(), new ConcurrentHashMap<>()); changedBlocks.putIfAbsent(world.getName(), blockMap); for (Document blockDocument : list) { @@ -107,31 +110,30 @@ public void loadGameState(@NotNull Document document) { @Override protected void onEnable() { - for (Player player : ChallengeAPI.getIngamePlayers()) { - updateSurroundingChunks(player.getLocation().getChunk(), false); - } + Challenges.getInstance().getPlayerManager().forEachChallengePlayer(player -> + updateSurroundingChunks(player.getLocation().getChunk(), false)); } private void changeBlockInEveryChunk(World world, int x, int y, int z, BlockData data, Block exception) { updatedChunks.clear(); - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, () -> { Map, BlockData> map = changedBlocks - .getOrDefault(world.getName(), new HashMap<>()); + .getOrDefault(world.getName(), new ConcurrentHashMap<>()); changedBlocks.putIfAbsent(world.getName(), map); map.put(new Triple<>(x, y, z), data); - for (Player player : ChallengeAPI.getIngamePlayers()) { + Challenges.getInstance().getPlayerManager().forEachChallengePlayer(player -> { for (Chunk chunk : getSurroundingChunks(player.getLocation().getChunk(), false)) { Block block = chunk.getBlock(x, y, z); if (!Objects.equals(exception, block)) { - setBlockData(block, data, true); + Regions.at(plugin, block.getLocation(), () -> setBlockData(block, data, true)); } } - } + }); }); } @@ -179,19 +181,19 @@ private void updateSurroundingChunks(Chunk center, boolean onlyBorder) { private void updateChunk(Chunk chunk) { updatedChunks.add(chunk); - Map, BlockData> dataMap = changedBlocks.getOrDefault(chunk.getWorld().getName(), new HashMap<>()); + Map, BlockData> dataMap = changedBlocks.getOrDefault(chunk.getWorld().getName(), new ConcurrentHashMap<>()); + Location center = new Location(chunk.getWorld(), chunk.getX() * 16 + 8, 0, chunk.getZ() * 16 + 8); - for (Map.Entry, BlockData> blockEntry : dataMap.entrySet()) { - Triple pos = blockEntry.getKey(); - BlockData blockData = blockEntry.getValue(); - Block block = chunk.getBlock(pos.getFirst(), pos.getSecond(), pos.getThird()); - if (!block.getBlockData().matches(blockData)) { - setBlockData(block, blockData, false); + Regions.at(plugin, center, () -> { + for (Map.Entry, BlockData> blockEntry : dataMap.entrySet()) { + Triple pos = blockEntry.getKey(); + BlockData blockData = blockEntry.getValue(); + Block block = chunk.getBlock(pos.getFirst(), pos.getSecond(), pos.getThird()); + if (!block.getBlockData().matches(blockData)) { + setBlockData(block, blockData, false); + } } - - } - - + }); } private void setBlockData(Block block, BlockData blockData, boolean update) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 21840d1b4..b00a78319 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -16,12 +16,12 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; public class SnakeChallenge extends Setting { - private final ArrayList blocks = new ArrayList<>(); + private final List blocks = new CopyOnWriteArrayList<>(); public SnakeChallenge() { setUsesGlobalPunish(true); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 0e650f4ae..4d9926c5c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -3,6 +3,7 @@ import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; @@ -29,7 +30,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { if (location == null) return; if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + Regions.asyncLater(plugin, () -> { if (!shouldExecuteEffect()) return; World world = event.getPlayer().getWorld(); @@ -41,7 +42,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { blocks.add(blockLocation.getBlock()); } - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, location, () -> { for (Block block : blocks) { block.setType(Material.AIR, false); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 6b123d2a7..1ce0545a9 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -22,13 +22,14 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; public class TsunamiChallenge extends TimedChallenge { public static final int RANGE = 5; private final ChunkFillQueue fills = new ChunkFillQueue(); - private final Set floodedChunks = new HashSet<>(); + private final Set floodedChunks = ConcurrentHashMap.newKeySet(); private int waterHeight = Integer.MAX_VALUE, lavaHeight = 0; @@ -97,9 +98,11 @@ protected void onTimeActivation() { Set previouslyFlooded = new HashSet<>(floodedChunks); bossbar.update(); floodedChunks.clear(); - for (Chunk chunk : getChunksToFlood()) { - floodChunk(chunk, !previouslyFlooded.contains(chunk)); - } + broadcastFiltered(player -> { + for (Chunk chunk : getChunksAroundChunk(player.getLocation().getChunk())) { + floodChunk(chunk, !previouslyFlooded.contains(chunk)); + } + }); } @@ -160,13 +163,6 @@ private boolean isFloodable(@NotNull Block block, boolean overworld) { return type != Material.WATER && type != Material.LAVA && block.isPassable(); } - @NotNull - private Set getChunksToFlood() { - Set chunks = new LinkedHashSet<>(); - broadcastFiltered(player -> chunks.addAll(getChunksAroundChunk(player.getLocation().getChunk()))); - return chunks; - } - @NotNull private Set getChunksAroundChunk(@NotNull Chunk origin) { World world = origin.getWorld(); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index 180b5c013..154726099 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -7,6 +7,7 @@ import net.cyperia.challenges.plugin.challenges.type.helper.GoalLeaderboard; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; import org.bukkit.advancement.Advancement; import org.bukkit.advancement.AdvancementProgress; @@ -20,10 +21,8 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.LinkedList; import java.util.List; import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; public class AllAdvancementGoal extends PointsGoal implements ChecklistGoal { @@ -31,19 +30,29 @@ public class AllAdvancementGoal extends PointsGoal implements ChecklistGoal { private final int advancementCount; public AllAdvancementGoal() { - allAdvancements = new LinkedList<>(); + allAdvancements = loadAdvancements(); + advancementCount = allAdvancements.size(); + } + + @NotNull + static List loadAdvancements() { + List advancements = new ArrayList<>(); Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { - if (!advancement.getKey().toString().contains(":recipes/")) { - allAdvancements.add(advancement); + if (!isRecipe(advancement)) { + advancements.add(advancement); } }); - advancementCount = allAdvancements.size(); + return advancements; + } + + static boolean isRecipe(@NotNull Advancement advancement) { + return advancement.getKey().toString().contains(":recipes/"); } @Override protected void onEnable() { updateAdvancements(); - scoreboard.setContent(GoalLeaderboard.scoreboardContent(() -> getPoints(new AtomicInteger(), true), + scoreboard.setContent(GoalLeaderboard.scoreboardContent(this::getLeaderboard, _ -> Collections.singletonList(getChallengeMessageKey("bossbar").withArgs(advancementCount)))); scoreboard.show(); } @@ -55,16 +64,15 @@ protected void onDisable() { @Override public void getWinnersOnEnd(@NotNull List winners) { - broadcastFiltered(player -> { - if (hasWon(player)) { - winners.add(player); - } - }); + // From the points, read on this thread: the winners are used as soon as this returns + for (Player player : plugin.getPlayerManager().getChallengePlayers()) { + if (hasWon(player)) winners.add(player); + } } @EventHandler(priority = EventPriority.HIGH) public void onAdvancement(PlayerAdvancementDoneEvent event) { - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + if (isRecipe(event.getAdvancement())) return; if (!shouldExecuteEffect(event.getPlayer())) return; updateAdvancements(event.getPlayer()); scoreboard.update(); @@ -80,7 +88,7 @@ public void onJoin(PlayerJoinEvent event) { @EventHandler(priority = EventPriority.HIGH) public void onGamemodeChange(PlayerGameModeChangeEvent event) { if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTask(plugin, (Runnable) scoreboard::update); + Regions.nextTick(plugin, (Runnable) scoreboard::update); } protected void updateAdvancements() { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index eea9825d2..60cb49ee3 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -2,27 +2,18 @@ import lombok.Getter; import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal; -import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingGoal; +import net.cyperia.challenges.plugin.challenges.type.abstraction.SharedCollectionGoal; import net.cyperia.challenges.plugin.content.i18n.MessageKey; -import net.cyperia.challenges.plugin.content.i18n.Prefix; -import net.cyperia.challenges.plugin.management.command.ChallengeCommand; -import net.cyperia.challenges.plugin.management.command.CommandInfo; -import net.cyperia.challenges.plugin.management.command.CommandProvider; import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; -import net.cyperia.challenges.plugin.permission.ChallengesPermissions; -import net.cyperia.challenges.plugin.spigot.command.ShortcutCommand; import net.cyperia.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.cyperia.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.cyperia.challenges.plugin.utils.misc.ExperimentalUtils; -import net.cyperia.challenges.plugin.utils.misc.Utils; +import net.cyperia.challenges.plugin.utils.item.CollectableItem; +import net.cyperia.challenges.plugin.utils.misc.VariantIds; import net.cyperia.commons.bukkit.utils.animation.SoundSample; -import net.cyperia.commons.bukkit.utils.item.ItemUtils; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; -import net.kyori.adventure.bossbar.BossBar; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -32,59 +23,54 @@ import org.jetbrains.annotations.Nullable; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; -public class CollectAllItemsGoal extends SettingGoal implements CommandProvider, ChecklistGoal { +public class CollectAllItemsGoal extends SharedCollectionGoal implements ChecklistGoal { private static final String SEED_KEY = "seed"; private static final String FOUND_ITEMS_KEY = "found-items"; private static final String FOUND_COUNT_KEY = "found"; private static final String FINDERS_KEY = "finders"; + private static final String FOUND_AT_KEY = "found-at"; private static final String FOUND_IN_ORDER_KEY = "found-in-order"; private static final String CURRENT_ITEM_KEY = "current"; - @Getter - private final List allItemsToFind; - @Getter - private final int totalItemsCount; + private final BooleanSubSetting itemVariantsSetting; + private List allItemsToFind; + private Set allIds; - private final Set collectedItems = EnumSet.noneOf(Material.class); + private final Set collectedItems = ConcurrentHashMap.newKeySet(); /** - * Every collected item by name, in the order it was found. Kept by name so that neither a server + * Every collected item by {@link CollectableItem#id()}, in the order it was found. Kept by id so that neither a server * version change nor a reshuffled remaining order can alter it, and so that items unknown to this * version are written back untouched when the server is downgraded temporarily. */ - private final List foundOrder = new ArrayList<>(); - private final Map finders = new HashMap<>(); + private final List foundOrder = new CopyOnWriteArrayList<>(); + private final Map finders = new ConcurrentHashMap<>(); + // Timer seconds per collected item, by id like the found order + private final Map foundAt = new ConcurrentHashMap<>(); - private List itemsToFind; + private List itemsToFind; private long seed; @Getter - private Material currentItem; + private CollectableItem currentItem; public CollectAllItemsGoal() { - allItemsToFind = loadItemsObtainableInSurvival(); - totalItemsCount = allItemsToFind.size(); + super(true); + itemVariantsSetting = registerItemVariantsSetting(false, this::onItemVariantsChange); + setItemsToFind(); reset(ThreadLocalRandom.current().nextLong()); } - @NotNull - private static List loadItemsObtainableInSurvival() { - Material[] materials = ExperimentalUtils.getMaterials(); - List items = new ArrayList<>(materials.length); - for (Material material : materials) { - if (!material.isItem()) continue; - if (!ItemUtils.isObtainableInSurvival(material)) continue; - items.add(material); - } - return List.copyOf(items); - } - private void reset(long seed) { this.seed = seed; collectedItems.clear(); foundOrder.clear(); finders.clear(); + foundAt.clear(); rebuildItemsToFind(); currentItem = pollNextItem(); } @@ -103,10 +89,39 @@ private void rebuildItemsToFind() { } @NotNull - private List getSeededOrder() { - List order = new ArrayList<>(allItemsToFind); - Collections.shuffle(order, new Random(seed)); - return order; + private List getSeededOrder() { + return seededOrder(allItemsToFind, seed); + } + + // Collected items are kept by id, so a book found with variants off still counts once they are off again + private void onItemVariantsChange() { + setItemsToFind(); + inheritBaseFinds(); + CollectableItem previous = currentItem; + rebuildItemsToFind(); + currentItem = previous != null && itemsToFind.remove(previous) ? previous : pollNextItem(); + if (!isEnabled()) return; + bossbar.update(); + updateRanking(); + if (currentItem == null && ChallengeAPI.isStarted()) ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + + private void setItemsToFind() { + allItemsToFind = CollectableItem.obtainableInSurvival(itemVariantsSetting.getAsBoolean()); + allIds = allItemsToFind.stream().map(CollectableItem::id).collect(Collectors.toSet()); + } + + // A book found with variants on is an enchanted book all the same once they are off + private void inheritBaseFinds() { + VariantIds.forEachCovered(foundOrder, allIds, (id, target) -> { + if (foundOrder.contains(target)) return; + CollectableItem item = CollectableItem.parse(target); + if (item == null) return; + collectedItems.add(item); + foundOrder.add(target); + if (finders.containsKey(id)) finders.put(target, finders.get(id)); + if (foundAt.containsKey(id)) foundAt.put(target, foundAt.get(id)); + }); } /** @@ -115,7 +130,7 @@ private List getSeededOrder() { private void nextItem() { if (currentItem != null) { collectedItems.add(currentItem); - foundOrder.add(currentItem.name()); + foundOrder.add(currentItem.id()); } currentItem = pollNextItem(); if (currentItem == null) { @@ -124,66 +139,56 @@ private void nextItem() { } @Nullable - private Material pollNextItem() { + private CollectableItem pollNextItem() { return itemsToFind.isEmpty() ? null : itemsToFind.removeFirst(); } @Override - protected void onEnable() { + protected void enableGoal() { bossbar.setContent((bossbar, _) -> { if (currentItem == null) { + styleBossbar(bossbar, false, 1); bossbar.setTitle(getChallengeMessageKey("bossbar-finished")); - bossbar.setColor(BossBar.Color.GREEN); return; } - int currentItemNumber = totalItemsCount - itemsToFind.size(); - bossbar.setTitle(getChallengeMessageKey("bossbar-current"), - currentItem, currentItemNumber, totalItemsCount); + int collected = allItemsToFind.size() - itemsToFind.size() - 1; + styleBossbar(bossbar, isRandomOrder(), (float) collected / allItemsToFind.size()); + if (!isRandomOrder()) { + bossbar.setTitle(getChallengeMessageKey("bossbar"), collected, allItemsToFind.size()); + return; + } + int currentItemNumber = allItemsToFind.size() - itemsToFind.size(); + bossbar.setTitle(getChallengeMessageKey("bossbar-next"), + currentItem.displayName(), currentItemNumber, allItemsToFind.size()); }); bossbar.show(); } @Override - protected void onDisable() { + protected void disableGoal() { bossbar.hide(); } - @NotNull + @Nullable @Override - public List getCommands() { - return List.of(ShortcutCommand.forSender(CommandInfo.command("skipitem", ChallengesPermissions.COMMAND_SKIPITEM), - (sender, context) -> skipItem(sender))); - } - - private void skipItem(@NotNull CommandSender sender) { - if (!isEnabled()) { - MessageKey.of("challenge.generic.disabled").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - if (currentItem == null) { - getChallengeMessageKey("already-finished").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - - getChallengeMessageKey("skipped").broadcast(Prefix.CHALLENGES, currentItem); - SoundSample.PLING.broadcast(); + protected Object skipCurrentTarget() { + CollectableItem skipped = currentItem; + if (skipped == null) return null; + foundAt.put(skipped.id(), Challenges.getInstance().getChallengeTimer().getTime()); nextItem(); - bossbar.update(); + return skipped.displayName(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onClick(@NotNull PlayerInventoryClickEvent event) { - if (event.isCancelled()) return; ItemStack item = event.getCurrentItem(); if (item == null) return; - handleNewItem(item.getType(), event.getPlayer()); + handleNewItem(item, event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPickUp(@NotNull PlayerPickupItemEvent event) { - handleNewItem(event.getItem().getItemStack().getType(), event.getPlayer()); + handleNewItem(event.getItem().getItemStack(), event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -191,24 +196,52 @@ public void onInteract(@NotNull PlayerInteractEvent event) { Player player = event.getPlayer(); if (!shouldExecuteEffect(player)) return; // The held item may only change once the interaction has been processed (buckets, bottles, ...) - Bukkit.getScheduler().runTaskLater(plugin, () -> - handleNewItem(player.getInventory().getItemInMainHand().getType(), player), 1); + Regions.later(plugin, player, () -> + handleNewItem(player.getInventory().getItemInMainHand(), player), 1); + } + + // A book with several enchantments collects every one of them + private void handleNewItem(@NotNull ItemStack stack, @NotNull Player player) { + for (CollectableItem item : CollectableItem.of(stack)) { + handleNewItem(item, player); + } } - protected void handleNewItem(@Nullable Material material, @NotNull Player player) { - if (material == null || material != currentItem) return; + private void handleNewItem(@NotNull CollectableItem item, @NotNull Player player) { + if (currentItem == null) return; + boolean current = item.equals(currentItem); + if (!current && (isRandomOrder() || collectedItems.contains(item) || !itemsToFind.contains(item))) return; if (!shouldExecuteEffect(player)) return; - getChallengeMessageKey("found").broadcast(Prefix.CHALLENGES, currentItem, player); + announceFind(FindType.ITEM, item.displayName(), player); SoundSample.PLING.broadcast(); - finders.put(currentItem.name(), player.getUniqueId()); - nextItem(); + finders.put(item.id(), player.getUniqueId()); + foundAt.put(item.id(), Challenges.getInstance().getChallengeTimer().getTime()); + if (current) { + nextItem(); + } else { + // Found out of order: the seeded order skips it from now on, the current item stays + itemsToFind.remove(item); + collectedItems.add(item); + foundOrder.add(item.id()); + } bossbar.update(); + updateRanking(); } @Override public void getWinnersOnEnd(@NotNull List winners) { } + @NotNull + @Override + protected Collection getFinders() { + List inPool = new ArrayList<>(); + finders.forEach((id, finder) -> { + if (allIds.contains(id)) inPool.add(finder); + }); + return inPool; + } + @Override public void loadGameState(@NotNull Document document) { super.loadGameState(document); @@ -222,14 +255,15 @@ public void loadGameState(@NotNull Document document) { collectedItems.clear(); foundOrder.clear(); finders.clear(); + foundAt.clear(); if (document.contains(FOUND_ITEMS_KEY)) { - List names = document.getStringList(FOUND_ITEMS_KEY); + List ids = document.getStringList(FOUND_ITEMS_KEY).stream().map(CollectAllItemsGoal::normalizeId).toList(); if (!document.getBoolean(FOUND_IN_ORDER_KEY)) { // Written before the found order was kept, the list is in declaration order instead - names = sortBySeededOrder(names, getSeededOrder()); + ids = sortBySeededOrder(ids, getSeededOrder()); } - readCollectedItems(names); + readCollectedItems(ids); rebuildItemsToFind(); } else { // Gamestates written before 2.4 only stored how many items were found, not which ones. Those @@ -237,34 +271,48 @@ public void loadGameState(@NotNull Document document) { // change since the gamestate was written. rebuildItemsToFind(); int foundCount = Math.clamp(document.getInt(FOUND_COUNT_KEY), 0, itemsToFind.size()); - readCollectedItems(itemsToFind.subList(0, foundCount).stream().map(Material::name).toList()); + readCollectedItems(itemsToFind.subList(0, foundCount).stream().map(CollectableItem::id).toList()); rebuildItemsToFind(); // Now that the collected items are known, drop them from the order } Document finderDocument = document.getDocument(FINDERS_KEY); - for (String name : foundOrder) { - UUID finder = finderDocument.getUUID(name); - if (finder != null) finders.put(name, finder); + Document foundAtDocument = document.getDocument(FOUND_AT_KEY); + for (String key : finderDocument.keys()) { + UUID finder = finderDocument.getUUID(key); + if (finder != null) finders.put(normalizeId(key), finder); + } + for (String key : foundAtDocument.keys()) { + foundAt.put(normalizeId(key), foundAtDocument.getLong(key)); } + inheritBaseFinds(); + rebuildItemsToFind(); // A version change reshuffles the remaining order, which must not swap the item players are looking for - Material savedCurrentItem = Utils.getMaterial(document.getString(CURRENT_ITEM_KEY)); + String savedCurrentId = document.getString(CURRENT_ITEM_KEY); + CollectableItem savedCurrentItem = savedCurrentId == null ? null : CollectableItem.parse(savedCurrentId); currentItem = savedCurrentItem != null && itemsToFind.remove(savedCurrentItem) ? savedCurrentItem : pollNextItem(); } /** - * Restores the collected items by name instead of by position, so that progress survives a server - * version change: neither reordered nor added nor removed materials can shift an item into or out + * Restores the collected items by id instead of by position, so that progress survives a server + * version change: neither reordered nor added nor removed items can shift an item into or out * of the collected items. */ - private void readCollectedItems(@NotNull List names) { - for (String name : names) { - foundOrder.add(name); - Material item = Utils.getMaterial(name); + private void readCollectedItems(@NotNull List ids) { + for (String id : ids) { + foundOrder.add(id); + CollectableItem item = CollectableItem.parse(id); if (item != null) collectedItems.add(item); } } + // Gamestates written before item variants existed key everything by material name + @NotNull + static String normalizeId(@NotNull String id) { + CollectableItem item = CollectableItem.parse(id); + return item == null ? id : item.id(); + } + @Override public void writeGameState(@NotNull Document document) { super.writeGameState(document); @@ -273,35 +321,48 @@ public void writeGameState(@NotNull Document document) { document.set(FOUND_ITEMS_KEY, foundOrder); document.set(FOUND_IN_ORDER_KEY, true); document.set(FOUND_COUNT_KEY, foundOrder.size()); // Only read by versions before 2.4 - document.set(CURRENT_ITEM_KEY, currentItem == null ? null : currentItem.name()); + document.set(CURRENT_ITEM_KEY, currentItem == null ? null : currentItem.id()); Document finderDocument = document.getDocument(FINDERS_KEY); finders.forEach((name, uuid) -> finderDocument.set(name, uuid.toString())); + Document foundAtDocument = document.getDocument(FOUND_AT_KEY); + foundAt.forEach(foundAtDocument::set); } - // The future order stays hidden: only the current item and the ones already found are listed + // In a random order the future order stays hidden: only the current item and the ones already found are listed @NotNull @Override public List getChecklist(@NotNull Player viewer) { + if (!isRandomOrder()) { + return allItemsToFind.stream() + .map(item -> checklistEntry(item, collectedItems.contains(item))) + .toList(); + } List entries = new ArrayList<>(foundOrder.size() + 1); if (currentItem != null) { - entries.add(ChecklistEntry.of(currentItem, false, List.of())); + entries.add(checklistEntry(currentItem, false)); } - for (String name : foundOrder.reversed()) { - Material item = Utils.getMaterial(name); - if (item == null) continue; - entries.add(ChecklistEntry.of(item, true, Optional.ofNullable(finders.get(name)).stream().toList())); + for (String id : foundOrder.reversed()) { + if (!allIds.contains(id)) continue; + CollectableItem item = CollectableItem.parse(id); + if (item != null) entries.add(checklistEntry(item, true)); } return entries; } + @NotNull + private ChecklistEntry checklistEntry(@NotNull CollectableItem item, boolean done) { + return new ChecklistEntry(item.displayName(), item.icon(), done, + Optional.ofNullable(finders.get(item.id())).stream().toList(), foundAt.get(item.id())); + } + // Items are found strictly in the seeded order, so sorting by it restores the found order as long as the item pool did not change @NotNull - static List sortBySeededOrder(@NotNull List names, @NotNull List seededOrder) { + static List sortBySeededOrder(@NotNull List ids, @NotNull List seededOrder) { Map positions = new HashMap<>(); for (int i = 0; i < seededOrder.size(); i++) { - positions.put(seededOrder.get(i).name(), i); + positions.put(seededOrder.get(i).id(), i); } - return names.stream().sorted(Comparator.comparingInt(name -> positions.getOrDefault(name, -1))).toList(); + return ids.stream().sorted(Comparator.comparingInt(id -> positions.getOrDefault(id, -1))).toList(); } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index 2c7a676de..06c4389a6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -91,7 +91,6 @@ public void onPickupItem(@NotNull PlayerPickupItemEvent event) { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (!shouldExecuteEffect()) return; - if (event.isCancelled()) return; if (event.getClickedInventory() == null) return; if (event.getClickedInventory().getHolder() != event.getPlayer()) return; if (event.getCurrentItem() == null) return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index 4811101f6..19399f1ea 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -3,7 +3,7 @@ import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -28,7 +28,7 @@ public void onInteract(PlayerInteractEvent event) { if (event.getClickedBlock().getType() != Material.CAKE) return; if (event.getPlayer().getFoodLevel() >= 20) return; // Execute on next tick to prevent hunger bar not filling up - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, () -> { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); }); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index eb7478abb..f008cad86 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -1,11 +1,11 @@ package net.cyperia.challenges.plugin.challenges.implementation.goal; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.attribute.Attribute; import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; -import org.bukkit.Bukkit; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -52,9 +52,10 @@ public void getWinnersOnEnd(@NotNull List winners) { public void onHealthChange(EntityRegainHealthEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect((Player) event.getEntity())) return; - Bukkit.getScheduler().runTask(plugin, () -> { - AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(Attribute.MAX_HEALTH); - if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { + Player player = (Player) event.getEntity(); + Regions.nextTick(plugin, player, () -> { + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + if (attribute != null && player.getHealth() >= attribute.getBaseValue()) { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); } }); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index b2f970085..823e08b5f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -10,7 +10,7 @@ public class KillAllMobsGoal extends KillMobsGoal { public KillAllMobsGoal() { - super(getAllMobsToKill()); + super(getAllMobsToKill(), true); } static List getAllMobsToKill() { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index 52cb16d3f..35b3dfe72 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -11,7 +11,7 @@ public class KillAllMonsterGoal extends KillMobsGoal { public KillAllMonsterGoal() { - super(getAllMobsToKill()); + super(getAllMobsToKill(), true); } static List getAllMobsToKill() { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index 17e7591d7..38904d4e6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -2,7 +2,7 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.cyperia.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -22,7 +22,7 @@ protected void onEnable() { } private void updatePoints(@NotNull Player player) { - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, player, () -> { int count = getEmeraldsCount(player); setPoints(player.getUniqueId(), count); }); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 164c6ea60..a3a2efe81 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -2,6 +2,7 @@ import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.implementation.goal.forcebattle.targets.*; +import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.cyperia.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; @@ -11,6 +12,7 @@ import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -31,7 +33,7 @@ public class ExtremeForceBattleGoal extends ForceBattleDisplayGoal> { - private final BooleanSubSetting giveItemSetting, giveBlockSetting; + private final BooleanSubSetting giveItemSetting, giveBlockSetting, itemVariantsSetting; public ExtremeForceBattleGoal() { @@ -43,6 +45,11 @@ public ExtremeForceBattleGoal() { new ItemStack(Material.CHEST), MessageKeySpace.of("challenge.force-block-battle.sub.give-block"), false )); + itemVariantsSetting = registerItemVariantsSetting(false, () -> {}); + } + + private boolean hasItemVariants() { + return itemVariantsSetting.getAsBoolean(); } @Override @@ -57,11 +64,14 @@ public void checkTargets() { UUID uuid = entry.getKey(); ForceTarget target = entry.getValue(); Player player = Bukkit.getPlayer(uuid); - if (player == null || ignorePlayer(player)) continue; - - if (target.check(player)) { - handleTargetFound(player); - } + if (player == null) continue; + + Regions.entity(plugin, player, () -> { + if (ignorePlayer(player)) return; + if (target.check(player)) { + handleTargetFound(player); + } + }); } } @@ -84,7 +94,8 @@ public List> getListFromDocument(Document document, String path) Object value = targetDocument.getObject("value"); TargetType targetType = TargetType.valueOf(targetTypeString); - targets.add(targetType.parse().apply(value)); + ForceTarget target = targetType.parse().apply(value); + if (target != null) targets.add(target); } return targets; } @@ -137,7 +148,7 @@ protected boolean shouldRegisterDupedTargetsSetting() { public void handleJokerUse(Player player) { ForceTarget target = currentTarget.get(player.getUniqueId()); if (shouldGiveItemOnSkip() && target instanceof ItemTarget itemTarget) { - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), itemTarget.getTarget()); + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), itemTarget.getTarget().icon()); } else if (shouldBlockOnSkip() && target instanceof BlockTarget blockTarget) { InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), blockTarget.getTarget()); } @@ -146,9 +157,10 @@ public void handleJokerUse(Player player) { public enum TargetType { ITEM(object -> { - return new ItemTarget(Material.valueOf((String) object)); + return ItemTarget.parse((String) object); }, player -> { - return new ItemTarget(globalRandom.choose(ItemTarget.getPossibleItems())); + boolean variants = AbstractChallenge.getFirstInstance(ExtremeForceBattleGoal.class).hasItemVariants(); + return new ItemTarget(globalRandom.choose(ItemTarget.getPossibleItems(variants))); }), BLOCK(object -> { return new BlockTarget(Material.valueOf((String) object)); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index 0ec105955..a82630af2 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -13,11 +13,13 @@ import org.bukkit.inventory.ItemStack; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; public class ForceItemBattleGoal extends ForceBattleDisplayGoal { private final BooleanSubSetting giveItemSetting; + private final BooleanSubSetting itemVariantsSetting; public ForceItemBattleGoal() { @@ -25,28 +27,31 @@ public ForceItemBattleGoal() { new ItemStack(Material.CHEST), getSubSettingSpace("give-item"), false )); + // Only future targets change, the current ones stay + itemVariantsSetting = registerItemVariantsSetting(false, () -> { + if (isEnabled()) targetsPossibleToFind = getTargetsPossibleToFind(); + }); } @Override protected ItemTarget[] getTargetsPossibleToFind() { - List materials = ItemTarget.getPossibleItems(); - return materials.stream().map(ItemTarget::new).toArray(ItemTarget[]::new); + return ItemTarget.getPossibleItems(itemVariantsSetting.getAsBoolean()).stream().map(ItemTarget::new).toArray(ItemTarget[]::new); } @Override public ItemTarget getTargetFromDocument(Document document, String path) { - return new ItemTarget(document.getEnum(path, Material.class)); + return ItemTarget.parse(document.getString(path)); } @Override public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, Material.class).stream().map(ItemTarget::new).collect(Collectors.toList()); + return document.getStringList(path).stream().map(ItemTarget::parse).filter(Objects::nonNull).collect(Collectors.toList()); } @Override public void handleJokerUse(Player player) { if (shouldGiveItemOnSkip()) { - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget().icon()); } super.handleJokerUse(player); } @@ -56,9 +61,8 @@ public void onClick(PlayerInventoryClickEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; if (event.getClickedInventory() == null) return; if (event.getCurrentItem() == null) return; - Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); - if (material == null) return; - if (material == event.getCurrentItem().getType()) { + ItemTarget target = currentTarget.get(event.getPlayer().getUniqueId()); + if (target != null && target.matches(event.getCurrentItem())) { handleTargetFound(event.getPlayer()); } } @@ -66,9 +70,8 @@ public void onClick(PlayerInventoryClickEvent event) { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPickup(PlayerPickupItemEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; - Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); - if (material == null) return; - if (material == event.getItem().getItemStack().getType()) { + ItemTarget target = currentTarget.get(event.getPlayer().getUniqueId()); + if (target != null && target.matches(event.getItem().getItemStack())) { handleTargetFound(event.getPlayer()); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java index 19531cca3..5d5994799 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java @@ -1,31 +1,55 @@ package net.cyperia.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.cyperia.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.cyperia.challenges.plugin.utils.misc.ExperimentalUtils; -import net.cyperia.commons.bukkit.utils.item.ItemUtils; -import org.bukkit.Material; +import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; +import net.cyperia.challenges.plugin.utils.item.CollectableItem; +import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; +import java.util.Objects; -public class ItemTarget extends ForceTarget { +public class ItemTarget extends ForceTarget { - public ItemTarget(Material target) { + public ItemTarget(CollectableItem target) { super(target); } + // Saves written before item variants hold the bare material name, which parse() still reads + @Nullable + public static ItemTarget parse(@Nullable String saved) { + CollectableItem item = saved == null ? null : CollectableItem.parse(saved); + return item == null ? null : new ItemTarget(item); + } + @Override public boolean check(Player player) { - return player.getInventory().contains(target); + for (ItemStack item : player.getInventory().getContents()) { + if (item != null && target.matches(item)) return true; + } + return false; + } + + public boolean matches(@NotNull ItemStack item) { + return target.matches(item); + } + + public static List getPossibleItems(boolean variants) { + return CollectableItem.obtainableInSurvival(variants); } - public static List getPossibleItems() { - List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - materials.removeIf(material -> !material.isItem()); - materials.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); - return materials; + @NotNull + @Override + public LocalizableMessage getDisplayName() { + return target.displayName(); + } + + @Override + public void updateDisplayStand(@NotNull ArmorStand armorStand) { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(target.icon()); } @Override @@ -34,8 +58,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public String toString() { - return target.name(); + public Object getTargetSaveObject() { + return target.id(); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index 5987b2724..83615be57 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -16,6 +16,7 @@ import net.cyperia.challenges.plugin.spigot.command.ShortcutCommand; import net.cyperia.challenges.plugin.utils.bukkit.container.BukkitSerialization; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; @@ -26,18 +27,18 @@ import org.jetbrains.annotations.NotNull; import java.io.IOException; -import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public class BackpackSetting extends SettingModifier implements CommandProvider { public static final int SHARED = 1, PLAYER = 2; private final int size; - private final Map backpacks = new HashMap<>(); + private final Map backpacks = new ConcurrentHashMap<>(); private final Inventory sharedBackpack; public BackpackSetting() { @@ -77,7 +78,7 @@ private void openBackpack(@NotNull Player player) { if (getValue() == SHARED || getValue() == PLAYER) { getChallengeMessageKey("opened").send(player, Prefix.BACKPACK, getBackpackName()); - player.openInventory(getCurrentBackpack(player)); + Regions.entity(Challenges.getInstance(), player, () -> player.openInventory(getCurrentBackpack(player))); SoundSample.OPEN.play(player); } else { getChallengeMessageKey("disabled").send(player, Prefix.BACKPACK); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index 9fbaa3231..de0bce196 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -12,7 +12,7 @@ import net.cyperia.challenges.plugin.utils.misc.Utils; import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.item.ItemUtils; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; @@ -176,7 +176,7 @@ private void breakBlockVein(@NotNull Player player, @NotNull Block block, @NotNu } AtomicInteger index = new AtomicInteger(); - Bukkit.getScheduler().runTaskTimer(plugin, timer -> { + Regions.timer(plugin, block.getLocation(), timer -> { SoundSample.LOW_PLOP.play(player); for (int i = 0; i < 2; i++) { @@ -193,7 +193,7 @@ private void breakBlockVein(@NotNull Player player, @NotNull Block block, @NotNu index.getAndIncrement(); } - }, 0, 2); + }, 1, 2); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java index 39ead3db9..ec45650f8 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java @@ -20,13 +20,19 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import java.util.Collection; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + public class DeathMessageSetting extends Modifier { public static final int ENABLED = 2, VANILLA = 3; - private boolean hide; + // Players whose next death message is not shown; a set, since kills in several regions overlap + private final Set hidden = ConcurrentHashMap.newKeySet(); public DeathMessageSetting() { super(1, 3, VANILLA); @@ -49,7 +55,7 @@ public ItemStack getSettingsItemPreset() { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onDeath(@NotNull PlayerDeathEvent event) { - if (hide) { + if (hidden.contains(event.getEntity().getUniqueId())) { event.deathMessage(null); return; } @@ -77,8 +83,12 @@ public void onDeath(@NotNull PlayerDeathEvent event) { event.deathMessage(null); } - public void setHideMessagesTemporarily(boolean hide) { - this.hide = hide; + public void hideMessagesOf(@NotNull Collection players) { + hidden.addAll(players); + } + + public void showMessagesOf(@NotNull Collection players) { + hidden.removeAll(players); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 30caf1427..a6a3ec636 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -2,6 +2,7 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.abstraction.Modifier; import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; @@ -11,6 +12,7 @@ import net.cyperia.challenges.plugin.management.command.CommandNodes; import net.cyperia.challenges.plugin.management.command.CommandProvider; import net.cyperia.challenges.plugin.permission.ChallengesPermissions; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; @@ -50,10 +52,12 @@ protected void onValueChange() { } private void setDifficulty(Difficulty difficulty) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "minecraft:difficulty " + difficulty.name().toLowerCase()); - for (World world : Bukkit.getWorlds()) { - world.setDifficulty(difficulty); - } + Regions.global(Challenges.getInstance(), () -> { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "minecraft:difficulty " + difficulty.name().toLowerCase()); + for (World world : Bukkit.getWorlds()) { + world.setDifficulty(difficulty); + } + }); } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index abb9b94cc..af582b6eb 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -9,6 +9,7 @@ import net.cyperia.challenges.plugin.management.command.CommandProvider; import net.cyperia.challenges.plugin.permission.ChallengesPermissions; import net.cyperia.challenges.plugin.spigot.command.ShortcutCommand; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -29,7 +30,7 @@ private void openEnderChest(@NotNull Player player) { return; } - player.openInventory(player.getEnderChest()); + Regions.entity(plugin, player, () -> player.openInventory(player.getEnderChest())); getChallengeMessageKey("opened").send(player, Prefix.CHALLENGES); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index ce55eba7d..f3cf9432f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -2,7 +2,7 @@ import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; -import org.bukkit.Bukkit; +import net.cyperia.challenges.plugin.management.server.scoreboard.PlayerScoreboards; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -38,41 +38,36 @@ public void onJoin(@NotNull PlayerJoinEvent event) { } private void show(@NotNull Player player) { - Scoreboard scoreboard = player.getScoreboard(); - ScoreboardManager manager = Bukkit.getScoreboardManager(); - if (manager == null) return; - if (player.getScoreboard() == manager.getMainScoreboard()) - player.setScoreboard(scoreboard = manager.getNewScoreboard()); - - Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); - if (objective == null) - objective = scoreboard.registerNewObjective(OBJECTIVE_NAME, "health", OBJECTIVE_NAME); - objective.setDisplaySlot(DisplaySlot.PLAYER_LIST); - - objective.setRenderType(RenderType.HEARTS); - objective.setAutoUpdateDisplay(true); - - try { - for (Player current : plugin.getPlayerManager().getAudience()) { - objective.getScore(current.getName()).setScore((int) current.getHealth()); + PlayerScoreboards.use(player, scoreboard -> { + Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); + if (objective == null) + objective = scoreboard.registerNewObjective(OBJECTIVE_NAME, "health", OBJECTIVE_NAME); + objective.setDisplaySlot(DisplaySlot.PLAYER_LIST); + + objective.setRenderType(RenderType.HEARTS); + objective.setAutoUpdateDisplay(true); + + try { + for (Player current : plugin.getPlayerManager().getAudience()) { + objective.getScore(current.getName()).setScore((int) current.getHealth()); + } + } catch (IllegalStateException _) { + // the health objective can be read-only } - } catch (IllegalStateException _) { - // the health objective can be read-only - } + }); } private void hide(@NotNull Player player) { - - Scoreboard scoreboard = player.getScoreboard(); - Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); - if (objective == null) return; - - try { - objective.unregister(); - } catch (Exception ex) { - Challenges.getInstance().getILogger().severe("Error while unregistering tablist hearts objective"); - } - + PlayerScoreboards.useExisting(player, scoreboard -> { + Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); + if (objective == null) return; + + try { + objective.unregister(); + } catch (Exception ex) { + Challenges.getInstance().getILogger().severe("Error while unregistering tablist hearts objective"); + } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index c10c96f78..4396409f1 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.challenges.implementation.setting; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.GameRule; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import org.bukkit.Bukkit; @@ -9,16 +10,20 @@ public class ImmediateRespawnSetting extends Setting { @Override protected void onEnable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, true); - } + Regions.global(plugin, () -> { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, true); + } + }); } @Override protected void onDisable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, false); - } + Regions.global(plugin, () -> { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, false); + } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java index ae2e336fc..7e3641434 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java @@ -1,6 +1,7 @@ package net.cyperia.challenges.plugin.challenges.implementation.setting; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; import org.bukkit.GameRule; import org.bukkit.World; @@ -9,15 +10,19 @@ public class KeepInventorySetting extends Setting { @Override protected void onEnable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.KEEP_INVENTORY, true); - } + Regions.global(plugin, () -> { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.KEEP_INVENTORY, true); + } + }); } @Override protected void onDisable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.KEEP_INVENTORY, false); - } + Regions.global(plugin, () -> { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.KEEP_INVENTORY, false); + } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/LocatorBarSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/LocatorBarSetting.java index 8a0c4330f..c39c6259d 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/LocatorBarSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/LocatorBarSetting.java @@ -2,6 +2,7 @@ import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.*; public class LocatorBarSetting extends Setting { @@ -20,16 +21,19 @@ protected void onDisable() { setLocatorBar(false); } - // the game rule is stored in the world itself, restore the vanilla state instead of leaving it disabled + // the game rule is stored in the world itself, restore the vanilla state instead of leaving it disabled. + // A regionised server disables plugins on its shutdown thread, where game rules cannot change. @Override public void handleShutdown() { - setLocatorBar(true); + if (Bukkit.isGlobalTickThread()) setLocatorBar(true); } private void setLocatorBar(boolean enabled) { - for (World world : ChallengeAPI.getGameWorlds()) { - world.setGameRule(GameRules.LOCATOR_BAR, enabled); - } + Regions.global(plugin, () -> { + for (World world : ChallengeAPI.getGameWorlds()) { + world.setGameRule(GameRules.LOCATOR_BAR, enabled); + } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java index 1d5cb6c9a..ba8d6b723 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java @@ -1,6 +1,7 @@ package net.cyperia.challenges.plugin.challenges.implementation.setting; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; import org.bukkit.GameRule; import org.bukkit.World; @@ -9,15 +10,19 @@ public class MobGriefingSetting extends Setting { @Override protected void onEnable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.MOB_GRIEFING, false); - } + Regions.global(plugin, () -> { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.MOB_GRIEFING, false); + } + }); } @Override protected void onDisable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.MOB_GRIEFING, true); - } + Regions.global(plugin, () -> { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.MOB_GRIEFING, true); + } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java index 5a364dda8..46f6c08e9 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java @@ -2,7 +2,7 @@ import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -13,11 +13,9 @@ public class NoHitDelaySetting extends Setting { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onDamageByEntity(@NotNull EntityDamageEvent event) { - if (!(event.getEntity() instanceof LivingEntity)) return; + if (!(event.getEntity() instanceof LivingEntity entity)) return; if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { - ((LivingEntity) event.getEntity()).setNoDamageTicks(0); - }, 1); + Regions.later(Challenges.getInstance(), entity, () -> entity.setNoDamageTicks(0), 1); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java index 79c9b5882..a10c55208 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java @@ -3,16 +3,23 @@ import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.jetbrains.annotations.NotNull; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + public class OneTeamLifeSetting extends Setting { - private boolean isKilling = false; + // The players this setting is killing, whose deaths must not start another round of kills + private final Set killing = ConcurrentHashMap.newKeySet(); public OneTeamLifeSetting() { super(true); @@ -21,21 +28,35 @@ public OneTeamLifeSetting() { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onDeath(@NotNull PlayerDeathEvent event) { if (!shouldExecuteEffect()) return; - if (isKilling) return; - - Bukkit.getScheduler().runTask(plugin, () -> { - try { - AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = true); - for (Player player : ChallengeHelper.getIngamePlayers()) { - if (player == event.getEntity()) continue; - ChallengeHelper.kill(player); - } - AbstractChallenge.getFirstInstance(RespawnSetting.class).checkAllPlayersDead(); - } finally { - AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = false); - } - }); + if (killing.contains(event.getEntity().getUniqueId())) return; + Player dead = event.getEntity(); + Regions.nextTick(plugin, () -> killOthers(dead)); + } + + // Runs on the global region. The kills happen on the threads of the players, so the round is only + // over once every one of them reported back. + private void killOthers(@NotNull Player dead) { + DeathMessageSetting messages = AbstractChallenge.getFirstInstance(DeathMessageSetting.class); + List victims = ChallengeHelper.getIngamePlayers().stream().filter(player -> player != dead).toList(); + List ids = victims.stream().map(Player::getUniqueId).toList(); + if (victims.isEmpty()) { + AbstractChallenge.getFirstInstance(RespawnSetting.class).checkAllPlayersDead(); + return; + } + + killing.addAll(ids); + messages.hideMessagesOf(ids); + AtomicInteger remaining = new AtomicInteger(victims.size()); + Runnable killed = () -> { + if (remaining.decrementAndGet() != 0) return; + Regions.global(plugin, () -> { + killing.removeAll(ids); + messages.showMessagesOf(ids); + AbstractChallenge.getFirstInstance(RespawnSetting.class).checkAllPlayersDead(); + }); + }; + for (Player victim : victims) ChallengeHelper.kill(victim, killed); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/PositionSetting.java index df02c00e7..f439eaf74 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -17,6 +17,7 @@ import net.cyperia.challenges.plugin.permission.ChallengesPermissions; import net.cyperia.challenges.plugin.utils.misc.ParticleUtils; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import org.bukkit.*; import org.bukkit.Particle.DustOptions; @@ -25,11 +26,12 @@ import org.jetbrains.annotations.NotNull; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.ToDoubleFunction; public class PositionSetting extends Setting implements CommandProvider { - private final Map positions = new HashMap<>(); + private final Map positions = new ConcurrentHashMap<>(); private final boolean particleLines; public PositionSetting() { @@ -145,12 +147,12 @@ private void playParticleLine(@NotNull Player player, @NotNull Location position Location target = position.clone().add(0, 0.3, 0); final int[] current = {0}; - Bukkit.getScheduler().runTaskTimer(plugin, task -> { + Regions.timer(plugin, player, task -> { current[0]++; if (current[0] >= 10) task.cancel(); ParticleUtils.drawLine(player, player.getLocation(), target, Particle.DUST, new DustOptions(Color.LIME, 1), 1, 0.5, 50); - }, 0, 10); + }, 1, 10); } @Override diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index 12f033384..0760be6ef 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.challenges.implementation.setting; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnLocationEvent; import org.bukkit.Particle; import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.Challenges; @@ -13,7 +14,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; -import org.bukkit.event.player.PlayerRespawnEvent; import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -49,7 +49,7 @@ public void checkAllPlayersDead() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onRespawn(@NotNull PlayerRespawnEvent event) { + public void onRespawn(@NotNull PlayerRespawnLocationEvent event) { if (isEnabled()) return; Player player = event.getPlayer(); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 575cd9aad..b3beda51f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -7,8 +7,9 @@ import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; import net.cyperia.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.cyperia.challenges.plugin.spigot.events.PlayerInventoryClickEvent; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnedEvent; import net.cyperia.challenges.plugin.utils.item.DefaultItems; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -16,7 +17,6 @@ import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerDropItemEvent; -import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @@ -40,7 +40,7 @@ protected void onValueChange() { @TimerTask(status = {TimerStatus.RUNNING}) public void updateDelayed() { - Bukkit.getScheduler().runTaskLater(plugin, this::update, 1); + Regions.later(plugin, this::update, 1); } @TimerTask(status = {TimerStatus.PAUSED}, async = false) @@ -77,13 +77,7 @@ private boolean isBlocked(int slot) { private void blockSlot(@NotNull Player player, int slot) { ItemStack item = player.getInventory().getItem(slot); if (item != null && !item.isSimilar(DefaultItems.BLOCKED_ITEM)) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(plugin, () -> { - player.getWorld().dropItemNaturally(player.getLocation(), item); - }); - } else { - player.getWorld().dropItemNaturally(player.getLocation(), item); - } + Regions.entity(plugin, player, () -> player.getWorld().dropItemNaturally(player.getLocation(), item)); } player.getInventory().setItem(slot, DefaultItems.BLOCKED_ITEM); } @@ -136,15 +130,14 @@ public void onPlayerDeath(@NotNull PlayerDeathEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void onRespawn(PlayerRespawnEvent event) { + public void onRespawn(PlayerRespawnedEvent event) { updateSlots(event.getPlayer()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerIgnoreStatusChange(PlayerIgnoreStatusChangeEvent event) { - Bukkit.getScheduler().runTask(plugin, () -> { - updateSlots(event.getPlayer()); - }); + Player player = event.getPlayer(); + Regions.nextTick(plugin, player, () -> updateSlots(player)); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 25b7875dd..b46327f09 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -1,10 +1,9 @@ package net.cyperia.challenges.plugin.challenges.implementation.setting; -import org.bukkit.attribute.Attribute; -import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.Setting; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -15,11 +14,36 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Everybody shares one health value. It is owned by the global region: a player whose health changed + * reports it there, where the change is added to the shared value, so damage that two regions deal at + * the same time adds up instead of one overwriting the other. Each player is then set to the shared value + * on their own thread. + */ public class SplitHealthSetting extends Setting { + private static final double EPSILON = 1e-6; + + // Written on the global region only + private volatile double shared = Double.NaN; + private volatile EntityDamageEvent lethalDamage; + // The health each player had when last merged or set; a player's thread compares against it to notice + // a change that was not reported yet + private final Map known = new ConcurrentHashMap<>(); + @Override protected void onEnable() { - setHealth(); + Regions.global(plugin, this::initialize); + } + + @Override + protected void onDisable() { + known.clear(); + shared = Double.NaN; } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -27,55 +51,82 @@ public void onEntityRegainHealth(@NotNull EntityRegainHealthEvent event) { if (!(event.getEntity() instanceof Player player)) return; if (!shouldExecuteEffect(player)) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> setHealth(player, null), 1); + report(player, null); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamage(EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (!(event.getEntity() instanceof Player player)) return; if (!shouldExecuteEffect(player)) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> setHealth(player, event), 1); + report(player, event); } @EventHandler(priority = EventPriority.HIGH) public void onJoin(@NotNull PlayerJoinEvent event) { if (ignorePlayer(event.getPlayer())) return; - setHealth(); + Regions.global(plugin, this::initialize); } - /** - * Calls {@link SplitHealthSetting#setHealth(Player, EntityDamageEvent)} for the player with the lowest health - */ - private void setHealth() { - Player player = null; - - for (Player currentPlayer : ChallengeHelper.getIngamePlayers()) { - if (player == null || player.getHealth() > currentPlayer.getHealth()) { - player = currentPlayer; - } - } - if (player == null) return; - setHealth(player, null); + // The health after the change is read a tick later, once the server applied it + private void report(@NotNull Player player, @Nullable EntityDamageEvent damage) { + Regions.later(plugin, player, () -> { + double health = player.getHealth(); + Regions.global(plugin, () -> merge(player, health, damage)); + }, 1); } - public void setHealth(@NotNull Player player, @Nullable EntityDamageEvent damageEvent) { + // The lowest health of everybody becomes the shared one + private void initialize() { if (!shouldExecuteEffect()) return; - AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); - if (attribute == null) return; - double health = Math.min(player.getHealth(), attribute.getValue()); + double lowest = Double.MAX_VALUE; + for (Player player : ChallengeHelper.getIngamePlayers()) lowest = Math.min(lowest, player.getHealth()); + if (lowest == Double.MAX_VALUE) return; + + shared = lowest; + lethalDamage = null; + known.clear(); + applyToAll(); + } - for (Player currentPlayer : ChallengeHelper.getIngamePlayers()) { - if (currentPlayer.equals(player)) continue; + private void merge(@NotNull Player player, double health, @Nullable EntityDamageEvent damage) { + if (!shouldExecuteEffect()) return; + if (Double.isNaN(shared)) { + initialize(); + return; + } - if (health <= 0 && damageEvent != null) { - applyLastDamageCause(currentPlayer, damageEvent); - } + double before = known.getOrDefault(player.getUniqueId(), shared); + shared = Math.max(0, shared + health - before); + known.put(player.getUniqueId(), health); + if (shared <= 0 && damage != null) lethalDamage = damage; + applyToAll(); + } - currentPlayer.setHealth(health); + private void applyToAll() { + plugin.getPlayerManager().forEachChallengePlayer(this::apply); + } + + // Runs on the player's thread + private void apply(@NotNull Player player) { + double current = player.getHealth(); + Double last = known.get(player.getUniqueId()); + if (last != null && Math.abs(current - last) > EPSILON) { + // Changed since the last merge and not reported yet: merging it re-applies the sum afterwards + Regions.global(plugin, () -> merge(player, current, null)); + return; } + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + if (attribute == null) return; + double target = Math.min(shared, attribute.getValue()); + if (Math.abs(current - target) > EPSILON) { + EntityDamageEvent lethal = lethalDamage; + if (target <= 0 && lethal != null) applyLastDamageCause(player, lethal); + player.setHealth(target); + } + known.put(player.getUniqueId(), target); } @SuppressWarnings({"removal"}) diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 82560f0ce..9173e5716 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -4,7 +4,7 @@ import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.utils.misc.WoodSpecies; import net.cyperia.commons.bukkit.utils.item.ItemUtils; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.data.type.Leaves; @@ -137,7 +137,7 @@ private static List searchTree(@NotNull Block origin, @NotNull WoodSpecie */ private void fellTree(@NotNull Player player, @NotNull WoodSpecies species, @NotNull List tree) { Iterator blocks = tree.iterator(); - Bukkit.getScheduler().runTaskTimer(plugin, task -> { + Regions.timer(plugin, tree.getFirst().getLocation(), task -> { if (!player.isOnline()) { task.cancel(); return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 4692d5f97..4d1d56386 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -11,6 +11,7 @@ import net.cyperia.challenges.plugin.spigot.command.ShortcutCommand; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.World.Environment; @@ -44,31 +45,32 @@ private void teleportUp(@NotNull Player player) { Location location = player.getWorld().getHighestBlockAt(playerLocation).getLocation().add(0.5, 1, 0.5); location.setYaw(playerLocation.getYaw()); location.setPitch(playerLocation.getPitch()); - player.setFallDistance(0); - player.teleport(location); + teleport(player, location); } else { getChallengeMessageKey("overworld").send(player, Prefix.CHALLENGES); if (environment == Environment.NETHER) { - Location location = playerLocation.clone(); - world = ChallengeAPI.getGameWorld(Environment.NORMAL); - location.setWorld(world); - location.multiply(8); - location = world.getHighestBlockAt(location).getLocation().add(0.5, 1, 0.5); - player.setFallDistance(0); - player.teleport(location); + Location target = playerLocation.clone(); + World overworld = ChallengeAPI.getGameWorld(Environment.NORMAL); + target.setWorld(overworld); + target.multiply(8); + overworld.getChunkAtAsync(target).thenAccept(chunk -> Regions.at(plugin, target, () -> + teleport(player, overworld.getHighestBlockAt(target).getLocation().add(0.5, 1, 0.5)))); } else { - world = ChallengeAPI.getGameWorld(Environment.NORMAL); Location location = player.getBedSpawnLocation(); - if (location == null) location = BlockUtils.getCenteredSpawn(world); - player.setFallDistance(0); - player.teleport(location); + if (location == null) location = BlockUtils.getCenteredSpawn(ChallengeAPI.getGameWorld(Environment.NORMAL)); + teleport(player, location); } } - SoundSample.TELEPORT.play(player); + } + private void teleport(@NotNull Player player, @NotNull Location location) { + Regions.entity(plugin, player, () -> { + player.setFallDistance(0); + player.teleportAsync(location).thenAccept(success -> SoundSample.TELEPORT.play(player)); + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ChecklistGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ChecklistGoal.java index 1199682aa..16870ee3c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ChecklistGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ChecklistGoal.java @@ -5,6 +5,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; @@ -19,11 +20,24 @@ public interface ChecklistGoal extends IGoal { @NotNull MessageKey getFinderMessage(); - record ChecklistEntry(@NotNull Object name, @NotNull ItemStack icon, boolean done, @NotNull List finders) { + /** + * @param foundAt timer time in seconds when the entry was done, {@code null} if not done or not known + */ + record ChecklistEntry(@NotNull Object name, @NotNull ItemStack icon, boolean done, @NotNull List finders, + @Nullable Long foundAt) { + + public ChecklistEntry(@NotNull Object name, @NotNull ItemStack icon, boolean done, @NotNull List finders) { + this(name, icon, done, finders, null); + } @NotNull public static ChecklistEntry of(@NotNull Object value, boolean done, @NotNull Collection finders) { - return new ChecklistEntry(value, new ItemStack(ItemUtils.getIcon(value)), done, List.copyOf(finders)); + return of(value, done, finders, null); + } + + @NotNull + public static ChecklistEntry of(@NotNull Object value, boolean done, @NotNull Collection finders, @Nullable Long foundAt) { + return new ChecklistEntry(value, new ItemStack(ItemUtils.getIcon(value)), done, List.copyOf(finders), foundAt); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/EntryAccess.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/EntryAccess.java new file mode 100644 index 000000000..f3a7b8161 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/EntryAccess.java @@ -0,0 +1,50 @@ +package net.cyperia.challenges.plugin.challenges.type; + +import net.cyperia.challenges.catalog.Challenge; +import net.cyperia.challenges.plugin.challenges.custom.CustomChallenge; +import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import org.bukkit.permissions.Permissible; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +// A catalog entry may name a permission: without it a player sees the entry locked, or not at all when it is hidden +public final class EntryAccess { + + private EntryAccess() { + } + + public static boolean isLocked(@NotNull IChallenge challenge, @NotNull Permissible viewer) { + Challenge entry = entryOf(challenge); + return entry != null && isLocked(entry, viewer); + } + + public static boolean isListed(@NotNull IChallenge challenge, @NotNull Permissible viewer) { + Challenge entry = entryOf(challenge); + return entry == null || isListed(entry, viewer); + } + + public static boolean isHidden(@NotNull IChallenge challenge) { + Challenge entry = entryOf(challenge); + return entry != null && entry.hidden(); + } + + public static boolean hasPermission(@NotNull IChallenge challenge) { + Challenge entry = entryOf(challenge); + return entry != null && entry.permission() != null; + } + + static boolean isLocked(@NotNull Challenge entry, @NotNull Permissible viewer) { + return entry.permission() != null && !viewer.hasPermission(entry.permission()); + } + + static boolean isListed(@NotNull Challenge entry, @NotNull Permissible viewer) { + return !entry.hidden() || !isLocked(entry, viewer); + } + + @Nullable + private static Challenge entryOf(@NotNull IChallenge challenge) { + if (challenge instanceof CustomChallenge || !(challenge instanceof AbstractChallenge abstractChallenge)) return null; + return abstractChallenge.getCatalogEntry(); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/IChallenge.java index ff4bfcbb0..d7be7f131 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/IChallenge.java @@ -10,6 +10,7 @@ import net.cyperia.challenges.plugin.management.menu.search.SearchFindable; import net.cyperia.challenges.plugin.management.menu.generator.types.IChallengesMenuGenerator; import net.cyperia.commons.common.config.Document; +import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public interface IChallenge extends GamestateSaveable, SearchFindable { @@ -80,6 +81,15 @@ default boolean isVisible() { return true; } + /** + * @return whether this challenge is {@link #isVisible() visible} and not hidden from this player by its permission + * @see EntryAccess + */ + @Override + default boolean isVisibleTo(@NotNull Player viewer) { + return isVisible() && EntryAccess.isListed(this, viewer); + } + /** * The category this challenge is grouped under, which also decides the {@link #getMenu() menu} it lives in. * diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ReleaseInfo.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ReleaseInfo.java index f761eb85b..8b99ac015 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ReleaseInfo.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/ReleaseInfo.java @@ -1,13 +1,16 @@ package net.cyperia.challenges.plugin.challenges.type; +import net.cyperia.challenges.catalog.Challenge; import net.cyperia.challenges.catalog.Release; import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.custom.CustomChallenge; import net.cyperia.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.cyperia.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; import net.cyperia.challenges.plugin.challenges.type.annotation.Since; import net.cyperia.commons.common.version.Version; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; // A challenge, trigger or action has its release in the catalog; anything else shown in a menu may carry @Since public final class ReleaseInfo { @@ -20,12 +23,25 @@ private ReleaseInfo() { @NotNull public static Release of(@NotNull Object menuEntry) { if (menuEntry instanceof CustomChallenge) return NONE; - if (menuEntry instanceof AbstractChallenge challenge) return challenge.getCatalogEntry().release(); + if (menuEntry instanceof AbstractChallenge challenge) { + Challenge entry = challenge.getCatalogEntry(); + return challenge instanceof MenuSetting setting ? withSubSettings(entry.release(), setting.getNewestSubSettingSince()) : entry.release(); + } if (menuEntry instanceof ChallengeSetting setting) return setting.getCatalogEntry().release(); + if (menuEntry instanceof MenuSetting.SubSetting subSetting) return new Release(subSetting.getSince(), null, false); Since since = menuEntry.getClass().getAnnotation(Since.class); return since == null ? NONE : new Release(since.value(), null, false); } + // A sub setting that came with its setting is no update of it + @NotNull + static Release withSubSettings(@NotNull Release release, @Nullable String newestSubSetting) { + if (newestSubSetting == null) return release; + Version subSetting = Version.parse(newestSubSetting); + if (!subSetting.isNewerThan(parse(release.since())) || !subSetting.isNewerThan(parse(release.updated()))) return release; + return new Release(release.since(), newestSubSetting, release.beta()); + } + @NotNull public static Version getSince(@NotNull Object menuEntry) { return parse(of(menuEntry).since()); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index d82fa9591..afae3623b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -8,15 +8,18 @@ import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; import net.cyperia.commons.bukkit.utils.logging.Logger; import net.cyperia.commons.common.config.Document; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; public abstract class CollectionGoal extends SettingGoal implements ChecklistGoal { - private final Map> collections = new HashMap<>(); + private final Map> collections = new ConcurrentHashMap<>(); protected Object[] target; private Set targetKeys; @@ -31,7 +34,7 @@ public CollectionGoal(boolean enabledByDefault, @NotNull Object[] target) { @Override protected void onEnable() { - scoreboard.setContent(GoalLeaderboard.scoreboardContent(() -> getPoints(new AtomicInteger(), true))); + scoreboard.setContent(GoalLeaderboard.scoreboardContent(this::getLeaderboard)); scoreboard.show(); } @@ -43,7 +46,7 @@ protected void onDisable() { @Override public void getWinnersOnEnd(@NotNull List winners) { AtomicInteger mostPoints = new AtomicInteger(); - Map points = getPoints(mostPoints, false); + Map points = getPoints(mostPoints); if (mostPoints.get() == 0) return; // Nobody won, nobody has anything for (Map.Entry entry : points.entrySet()) { @@ -53,8 +56,13 @@ public void getWinnersOnEnd(@NotNull List winners) { } @NotNull - protected Map getPoints(@NotNull AtomicInteger mostPoints, boolean zeros) { - return GoalHelper.createPointsFromValues(mostPoints, collections, (uuid, strings) -> getCollectedCount(uuid), zeros); + protected Map getPoints(@NotNull AtomicInteger mostPoints) { + return GoalHelper.createPointsFromValues(mostPoints, collections, (uuid, strings) -> getCollectedCount(uuid)); + } + + @NotNull + protected Map getLeaderboard() { + return GoalHelper.createLeaderboardFromValues(collections, (uuid, strings) -> getCollectedCount(uuid)); } protected void collect(@NotNull Player player, @NotNull Object item, @NotNull Runnable success) { @@ -76,7 +84,7 @@ protected int getCollectedCount(@NotNull UUID uuid) { } protected List getCollectionRaw(@NotNull UUID uuid) { - return collections.computeIfAbsent(uuid, key -> new ArrayList<>()); + return collections.computeIfAbsent(uuid, key -> new CopyOnWriteArrayList<>()); } protected void checkCollects() { @@ -99,7 +107,7 @@ public void loadGameState(@NotNull Document document) { try { UUID uuid = UUID.fromString(key); List collection = scores.getStringList(key); - collections.put(uuid, collection); + collections.put(uuid, new CopyOnWriteArrayList<>(collection)); } catch (Exception ex) { Logger.error("Could not load scores for {}", key); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index 9425a25a8..139d7794a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -1,13 +1,16 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; public abstract class EndingForceChallenge extends AbstractForceChallenge { @@ -32,13 +35,31 @@ protected final void handleCountdownEnd() { } private void checkAllPlayers() { - List failed = new ArrayList<>(); - for (Player player : ChallengeAPI.getIngamePlayers()) { - if (isFailing(player)) { - broadcastFailedMessage(player); - failed.add(player); + List players = ChallengeAPI.getIngamePlayers(); + List failed = new CopyOnWriteArrayList<>(); + if (players.isEmpty()) { + finishCheck(failed); + return; + } + + AtomicInteger remaining = new AtomicInteger(players.size()); + Runnable checked = () -> { + if (remaining.decrementAndGet() == 0) { + Regions.global(Challenges.getInstance(), () -> finishCheck(failed)); } + }; + for (Player player : players) { + Regions.entity(Challenges.getInstance(), player, () -> { + if (isFailing(player)) { + broadcastFailedMessage(player); + failed.add(player); + } + checked.run(); + }, checked); } + } + + private void finishCheck(@NotNull List failed) { if (!failed.isEmpty()) { killFailedPlayers(failed); return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index 0a64e7210..d3d0039a7 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -1,22 +1,25 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.cyperia.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; +import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; public abstract class ForceBattleDisplayGoal> extends ForceBattleGoal { @@ -24,7 +27,7 @@ public abstract class ForceBattleDisplayGoal> extends F @Override protected void onEnable() { - displayStands = new HashMap<>(); + displayStands = new ConcurrentHashMap<>(); broadcastFiltered(this::updateDisplayStand); super.onEnable(); } @@ -32,7 +35,7 @@ protected void onEnable() { @Override protected void onDisable() { super.onDisable(); - displayStands.values().forEach(Entity::remove); + displayStands.values().forEach(this::removeStand); displayStands = null; } @@ -49,10 +52,18 @@ public void updateDisplayStand(Player player) { entity.setSmall(true); return entity; }); - armorStand.setVelocity(player.getVelocity().clone().multiply(2)); - armorStand.teleport(player.getLocation().clone().add(0, 2, 0)); + Vector velocity = player.getVelocity().clone().multiply(2); + Location target = player.getLocation().clone().add(0, 2, 0); + Regions.entity(Challenges.getInstance(), armorStand, () -> { + armorStand.setVelocity(velocity); + armorStand.teleportAsync(target); - handleDisplayStandUpdate(player, armorStand); + handleDisplayStandUpdate(player, armorStand); + }); + } + + private void removeStand(@NotNull ArmorStand stand) { + Regions.entity(Challenges.getInstance(), stand, stand::remove); } public void handleDisplayStandUpdate(@NotNull Player player, @NotNull ArmorStand armorStand) { @@ -92,7 +103,7 @@ public void onStatusChange(PlayerIgnoreStatusChangeEvent event) { } else { ArmorStand stand = displayStands.remove(event.getPlayer()); if (stand != null) { - stand.remove(); + removeStand(stand); } } } @@ -100,9 +111,7 @@ public void onStatusChange(PlayerIgnoreStatusChangeEvent event) { @Override public void onTick() { super.onTick(); - for (Player player : displayStands.keySet()) { - updateDisplayStand(player); - } + Challenges.getInstance().getPlayerManager().forEachOnOwnThread(displayStands.keySet(), this::updateDisplayStand); } @EventHandler(priority = EventPriority.HIGH) @@ -110,7 +119,7 @@ public void onQuit(PlayerQuitEvent event) { if (!shouldExecuteEffect()) return; ArmorStand stand = displayStands.remove(event.getPlayer()); if (stand != null) { - stand.remove(); + removeStand(stand); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index b1c0fa433..255d07653 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -10,14 +10,16 @@ import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.management.scheduler.task.TimerTask; import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnedEvent; import net.cyperia.challenges.plugin.utils.misc.InventoryUtils; import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.item.ItemBuilder; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import net.cyperia.commons.common.config.document.GsonDocument; import net.kyori.adventure.bossbar.BossBar; -import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -27,21 +29,21 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; public abstract class ForceBattleGoal> extends MenuGoal { - protected final Map jokerUsed = new HashMap<>(); - protected final Map> foundTargets = new HashMap<>(); - protected final Map currentTarget = new HashMap<>(); + protected final Map jokerUsed = new ConcurrentHashMap<>(); + protected final Map> foundTargets = new ConcurrentHashMap<>(); + protected final Map currentTarget = new ConcurrentHashMap<>(); protected T[] targetsPossibleToFind; private ItemStack jokerItem; @@ -255,7 +257,7 @@ protected MessageKey getTargetCompletedMessage(T target) { public void handleTargetFound(Player player) { T foundTarget = currentTarget.get(player.getUniqueId()); if (foundTarget != null) { - List list = foundTargets.computeIfAbsent(player.getUniqueId(), _ -> new LinkedList<>()); + List list = foundTargets.computeIfAbsent(player.getUniqueId(), _ -> new CopyOnWriteArrayList<>()); list.add(foundTarget); getTargetCompletedMessage(foundTarget).send(player, Prefix.CHALLENGES, foundTarget.getDisplayName()); } @@ -264,11 +266,11 @@ public void handleTargetFound(Player player) { @Override public void getWinnersOnEnd(@NotNull List winners) { - Bukkit.getScheduler().runTask(plugin, () -> sendLeaderboard(null)); + Regions.nextTick(plugin, () -> sendLeaderboard(null)); } public void sendResult(@NotNull Player player) { - Bukkit.getScheduler().runTask(plugin, () -> sendLeaderboard(player)); + Regions.nextTick(plugin, player, () -> sendLeaderboard(player)); } /** @@ -288,8 +290,8 @@ protected MessageKey getLeaderboardTitleMessage() { * One point per target found, so that the sidebar ranks the same way the result leaderboard does. */ @NotNull - protected Map getPoints(@NotNull AtomicInteger mostPoints, boolean zeros) { - return GoalHelper.createPointsFromValues(mostPoints, foundTargets, (_, targets) -> targets.size(), zeros); + protected Map getLeaderboard() { + return GoalHelper.createLeaderboardFromValues(foundTargets, (_, targets) -> targets.size()); } private int getUsableJokers(UUID uuid) { @@ -316,7 +318,7 @@ public void handleJokerUse(Player player) { } protected void setScoreboardContent() { - scoreboard.setContent(GoalLeaderboard.scoreboardContent(() -> getPoints(new AtomicInteger(), true))); + scoreboard.setContent(GoalLeaderboard.scoreboardContent(this::getLeaderboard)); bossbar.setContent((bar, player) -> { bar.setColor(BossBar.Color.WHITE); LocalizableMessage target = getCurrentTargetDisplay(player); @@ -390,9 +392,9 @@ public void onDeath(PlayerDeathEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onRespawn(PlayerRespawnEvent event) { + public void onRespawn(PlayerRespawnedEvent event) { if (!shouldExecuteEffect(event.getPlayer())) return; - Bukkit.getScheduler().runTask(plugin, () -> { + Regions.nextTick(plugin, event.getPlayer(), () -> { updateJokersInInventory(event.getPlayer()); }); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index 4dcd1ff8d..a5d2c8ca4 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -13,7 +13,6 @@ import org.jetbrains.annotations.NotNull; import java.util.Collections; -import java.util.concurrent.atomic.AtomicInteger; public abstract class ItemCollectionGoal extends CollectionGoal { @@ -34,7 +33,7 @@ protected void handleCollect(@NotNull Player player, @NotNull Material material) @Override protected void onEnable() { - scoreboard.setContent(GoalLeaderboard.scoreboardContent(() -> getPoints(new AtomicInteger(), true), + scoreboard.setContent(GoalLeaderboard.scoreboardContent(this::getLeaderboard, _ -> Collections.singletonList(MessageKey.of("challenge.generic.items-to-collect").withArgs(target.length)))); scoreboard.show(); } @@ -50,7 +49,6 @@ public void onPickupItem(@NotNull PlayerPickupItemEvent event) { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (!shouldExecuteEffect()) return; - if (event.isCancelled()) return; if (event.getClickedInventory() == null) return; if (event.getClickedInventory().getHolder() != event.getPlayer()) return; if (event.getCurrentItem() == null) return; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index dc7404fbc..644420c8f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -1,36 +1,129 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; import net.cyperia.challenges.plugin.ChallengeAPI; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal; import net.cyperia.challenges.plugin.content.i18n.MessageKey; -import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; +import net.cyperia.challenges.plugin.utils.entity.KillableMob; +import net.cyperia.challenges.plugin.utils.misc.VariantIds; import net.cyperia.commons.common.config.Document; -import net.kyori.adventure.bossbar.BossBar; import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDeathEvent; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.EnumMap; -import java.util.LinkedList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; -public abstract class KillMobsGoal extends SettingGoal implements ChecklistGoal { +public abstract class KillMobsGoal extends SharedCollectionGoal implements ChecklistGoal { - protected static List entitiesKilled; - private static Map killers; + // Shared by every mob goal, by KillableMob id, so switching between them keeps the kills + private static Set killed; + private static Map killers; + // Timer seconds per kill + private static Map killedAt; - protected final List entitiesToKill; + private final List types; + @Nullable + private final BooleanSubSetting mobAttributesSetting; + @Nullable + private final BooleanSubSetting mobEquipmentSetting; + private List mobsToKill; + private Map> mobsByType; + private Map mobsById; + // The random order's target from before the pool changed, kept until it is killed + @Nullable + private String keptTarget; + private long seed; + private List order; - public KillMobsGoal(@NotNull List entitiesKilled) { - this.entitiesToKill = entitiesKilled; - resetEntitiesToKill(); + public KillMobsGoal(@NotNull List types) { + this(types, false); + } + + /** + * @param variantsSetting whether the goal offers the settings to kill every variant of its mobs + */ + public KillMobsGoal(@NotNull List types, boolean variantsSetting) { + super(false); + this.types = types; + mobAttributesSetting = variantsSetting ? registerMobAttributesSetting(false, this::onMobVariantsChange) : null; + mobEquipmentSetting = variantsSetting ? registerMobEquipmentSetting(false, this::onMobVariantsChange) : null; + loadMobs(); + resetKills(); + reseed(ThreadLocalRandom.current().nextLong()); + } + + private void loadMobs() { + mobsToKill = KillableMob.pool(types, mobAttributesSetting != null && mobAttributesSetting.getAsBoolean(), + mobEquipmentSetting != null && mobEquipmentSetting.getAsBoolean()); + mobsByType = KillableMob.byType(mobsToKill); + mobsById = new HashMap<>(); + mobsToKill.forEach(mob -> mobsById.put(mob.id(), mob)); + } + + // A baby zombie killed with variants on is a zombie all the same once they are off + private void inheritBaseKills() { + VariantIds.forEachCovered(killed, mobsById.keySet(), (id, target) -> { + if (!killed.add(target)) return; + if (killers.containsKey(id)) killers.put(target, killers.get(id)); + if (killedAt.containsKey(id)) killedAt.put(target, killedAt.get(id)); + }); + } + + // Kills are kept by id, so a variant killed before still counts once the setting brings it back + private void onMobVariantsChange() { + KillableMob previous = getCurrentTarget(); + loadMobs(); + inheritBaseKills(); + reseed(seed); + keptTarget = previous == null ? null : previous.id(); + if (!isEnabled()) return; + bossbar.update(); + updateRanking(); + if (killedCount() == mobsToKill.size() && ChallengeAPI.isStarted()) { + resetKills(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + } + + private void reseed(long seed) { + this.seed = seed; + order = seededOrder(mobsToKill, seed); + } + + @Nullable + private KillableMob getCurrentTarget() { + if (keptTarget != null) { + KillableMob kept = mobsById.get(keptTarget); + if (kept != null && !isKilled(kept)) return kept; + keptTarget = null; + } + for (KillableMob mob : order) { + if (!isKilled(mob)) return mob; + } + return null; + } + + private boolean isKilled(@NotNull KillableMob mob) { + return killed.contains(mob.id()); + } + + private int killedCount() { + return (int) mobsToKill.stream().filter(this::isKilled).count(); } @NotNull @@ -38,9 +131,10 @@ protected MessageKey getBossbarMessage() { return getChallengeMessageKey("bossbar"); } - private void resetEntitiesToKill() { - entitiesKilled = new LinkedList<>(); - killers = new EnumMap<>(EntityType.class); + private static void resetKills() { + killed = new LinkedHashSet<>(); + killers = new HashMap<>(); + killedAt = new HashMap<>(); } @Override @@ -49,79 +143,122 @@ public void getWinnersOnEnd(@NotNull List winners) { } @Override - protected void onEnable() { + protected void enableGoal() { bossbar.setContent((bar, _) -> { - float i = 1 - ((float) getEntitiesLeftToKill().size() / (float) entitiesToKill.size()); - bar.setProgress(i); - bar.setColor(BossBar.Color.GREEN); - bar.setTitle(getBossbarMessage(), getEntitiesKilled().size(), entitiesToKill.size()); + int killedCount = killedCount(); + KillableMob current = getCurrentTarget(); + boolean showsNextTarget = isRandomOrder() && current != null; + styleBossbar(bar, showsNextTarget, (float) killedCount / mobsToKill.size()); + if (showsNextTarget) { + bar.setTitle(getChallengeMessageKey("bossbar-next"), current.displayName(), killedCount + 1, mobsToKill.size()); + } else { + bar.setTitle(getBossbarMessage(), killedCount, mobsToKill.size()); + } }); bossbar.show(); } @Override - protected void onDisable() { + protected void disableGoal() { bossbar.hide(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onDeath(@NotNull EntityDeathEvent event) { if (!shouldExecuteEffect()) return; - if (event.getEntityType() != EntityType.WITHER && event.getEntityType() != EntityType.ENDER_DRAGON && event.getEntityType() != EntityType.ELDER_GUARDIAN) { - if (event.getEntity().getKiller() == null) return; + LivingEntity entity = event.getEntity(); + EntityType type = entity.getType(); + Player killer = entity.getKiller(); + // Bosses often die to an explosion or a trident nobody threw last, they count all the same + if (killer == null && type != EntityType.WITHER && type != EntityType.ENDER_DRAGON && type != EntityType.ELDER_GUARDIAN) return; + + KillableMob current = isRandomOrder() ? getCurrentTarget() : null; + boolean found = false; + for (KillableMob mob : KillableMob.killed(entity, mobsByType)) { + if (isKilled(mob) || (isRandomOrder() && !mob.equals(current))) continue; + killed.add(mob.id()); + if (killer != null) killers.put(mob.id(), killer.getUniqueId()); + killedAt.put(mob.id(), Challenges.getInstance().getChallengeTimer().getTime()); + announceFind(FindType.MOB, mob.displayName(), killer); + found = true; } - if (entitiesKilled.contains(event.getEntityType())) return; - entitiesKilled.add(event.getEntityType()); - Player killer = event.getEntity().getKiller(); - if (killer != null) killers.put(event.getEntityType(), killer.getUniqueId()); - if (entitiesToKill.contains(event.getEntityType())) { - MessageKey.of("challenge.generic.mob-killed").broadcast(Prefix.CHALLENGES, event.getEntityType(), getEntitiesKilled().size(), entitiesToKill.size()); - bossbar.update(); - if (!getEntitiesLeftToKill().isEmpty()) return; - resetEntitiesToKill(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + // A mob this goal does not ask for is kept as well, so it counts after switching to a goal that does + String typeId = KillableMob.of(type).id(); + if (!mobsById.containsKey(typeId) && killed.add(typeId)) { + if (killer != null) killers.put(typeId, killer.getUniqueId()); + killedAt.put(typeId, Challenges.getInstance().getChallengeTimer().getTime()); } + if (!found) return; + bossbar.update(); + updateRanking(); + if (killedCount() < mobsToKill.size()) return; + resetKills(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); } @Override public void writeGameState(@NotNull Document document) { super.writeGameState(document); - document.set("entities", entitiesKilled); + document.set("entities", List.copyOf(killed)); + document.set("seed", seed); Document killerDocument = document.getDocument("killers"); - killers.forEach((type, uuid) -> killerDocument.set(type.name(), uuid.toString())); + killers.forEach((id, uuid) -> killerDocument.set(id, uuid.toString())); + Document killedAtDocument = document.getDocument("killed-at"); + killedAt.forEach(killedAtDocument::set); } @Override public void loadGameState(@NotNull Document document) { super.loadGameState(document); - entitiesKilled = document.getEnumList("entities", EntityType.class); - killers = new EnumMap<>(EntityType.class); + resetKills(); + document.getStringList("entities").stream().map(KillableMob::normalizeId).forEach(killed::add); + reseed(document.contains("seed") ? document.getLong("seed") : ThreadLocalRandom.current().nextLong()); + keptTarget = null; Document killerDocument = document.getDocument("killers"); - for (EntityType type : entitiesKilled) { - UUID killer = killerDocument.getUUID(type.name()); - if (killer != null) killers.put(type, killer); + for (String key : killerDocument.keys()) { + UUID killer = killerDocument.getUUID(key); + if (killer != null) killers.put(KillableMob.normalizeId(key), killer); } + Document killedAtDocument = document.getDocument("killed-at"); + for (String key : killedAtDocument.keys()) { + killedAt.put(KillableMob.normalizeId(key), killedAtDocument.getLong(key)); + } + inheritBaseKills(); } - public List getEntitiesKilled() { - LinkedList entityTypes = new LinkedList<>(entitiesKilled); - entityTypes.removeIf(type -> !entitiesToKill.contains(type)); - return entityTypes; + @Nullable + @Override + protected Object skipCurrentTarget() { + KillableMob skipped = getCurrentTarget(); + if (skipped == null) return null; + killed.add(skipped.id()); + killedAt.put(skipped.id(), Challenges.getInstance().getChallengeTimer().getTime()); + if (killedCount() == mobsToKill.size()) { + resetKills(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + return skipped.displayName(); } - public List getEntitiesLeftToKill() { - LinkedList entityTypes = new LinkedList<>(entitiesToKill); - entityTypes.removeAll(entitiesKilled); - return entityTypes; + @NotNull + @Override + protected Collection getFinders() { + List finders = new ArrayList<>(); + for (KillableMob mob : mobsToKill) { + UUID killer = killers.get(mob.id()); + if (killer != null) finders.add(killer); + } + return finders; } @NotNull @Override public List getChecklist(@NotNull Player viewer) { - return entitiesToKill.stream() - .map(type -> ChecklistEntry.of(type, entitiesKilled.contains(type), Optional.ofNullable(killers.get(type)).stream().toList())) + return mobsToKill.stream() + .map(mob -> new ChecklistEntry(mob.displayName(), mob.icon(), isKilled(mob), + Optional.ofNullable(killers.get(mob.id())).stream().toList(), killedAt.get(mob.id()))) .toList(); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/LocationEffectChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/LocationEffectChallenge.java index c72e09036..441446ae8 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/LocationEffectChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/LocationEffectChallenge.java @@ -16,14 +16,14 @@ import org.bukkit.potion.PotionEffect; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public abstract class LocationEffectChallenge extends Setting { // Only effects this challenge gave are taken away again, never a potion the player drank themselves - private Map givenEffects = new HashMap<>(); + private Map givenEffects = new ConcurrentHashMap<>(); private long worldSeed; @NotNull @@ -38,7 +38,7 @@ protected long worldSeed() { @Override protected void onEnable() { - givenEffects = new HashMap<>(); + givenEffects = new ConcurrentHashMap<>(); worldSeed = ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed(); broadcastFiltered(player -> update(player, player.getLocation())); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/Modifier.java index fe35e136f..8dc400cfa 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.jetbrains.annotations.Nullable; import net.cyperia.challenges.catalog.Challenge; import net.cyperia.challenges.plugin.Challenges; @@ -105,11 +106,13 @@ public void setValue(int value) { if (value < min) throw new IllegalArgumentException("value < min"); this.value = value; - try { - if (isEnabled()) onValueChange(); - } catch (Exception exception) { - Challenges.getInstance().getILogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); - } + Regions.global(Challenges.getInstance(), () -> { + try { + if (isEnabled()) onValueChange(); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); + } + }); updateItems(); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index e26c2c203..cc13b84dc 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -1,5 +1,7 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.challenges.plugin.challenges.type.IModifier; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -96,7 +98,9 @@ public void setValue(int value) { if (value < min) throw new IllegalArgumentException("value < min"); this.value = value; - if (isEnabled()) onValueChange(); + Regions.global(Challenges.getInstance(), () -> { + if (isEnabled()) onValueChange(); + }); updateItems(); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/PointsGoal.java index 5359a9b67..25734b39e 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -4,6 +4,7 @@ import net.cyperia.challenges.plugin.challenges.type.helper.GoalLeaderboard; import net.cyperia.commons.bukkit.utils.logging.Logger; import net.cyperia.commons.common.config.Document; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -27,7 +28,7 @@ public PointsGoal(boolean enabledByDefault) { @Override protected void onEnable() { super.onEnable(); - scoreboard.setContent(GoalLeaderboard.scoreboardContent(() -> getPoints(new AtomicInteger(), true))); + scoreboard.setContent(GoalLeaderboard.scoreboardContent(this::getLeaderboard)); scoreboard.show(); } @@ -63,12 +64,17 @@ public void writeGameState(@NotNull Document document) { @Override public void getWinnersOnEnd(@NotNull List winners) { - GoalHelper.getWinnersOnEnd(winners, getPoints(new AtomicInteger(), false)); + GoalHelper.getWinnersOnEnd(winners, getPoints(new AtomicInteger())); } @NotNull - protected Map getPoints(@NotNull AtomicInteger mostPoints, boolean zeros) { - return GoalHelper.createPointsFromValues(mostPoints, points, (uuid, integer) -> integer, zeros); + protected Map getPoints(@NotNull AtomicInteger mostPoints) { + return GoalHelper.createPointsFromValues(mostPoints, points, (uuid, integer) -> integer); + } + + @NotNull + protected Map getLeaderboard() { + return GoalHelper.createLeaderboardFromValues(points, (uuid, integer) -> integer); } protected void collect(@NotNull Player player) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/Setting.java index 08850af3b..a3445b0f9 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/Setting.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.jetbrains.annotations.Nullable; import net.cyperia.challenges.catalog.Challenge; import net.cyperia.challenges.plugin.Challenges; @@ -101,15 +102,17 @@ public void setEnabled(boolean enabled) { if (this.enabled == enabled) return; this.enabled = enabled; - try { - if (enabled) onEnable(); - else onDisable(); - } catch (Exception exception) { - Challenges.getInstance().getILogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); - } - - // Sync, a Bukkit event must not be called from the threads settings are loaded on - ChallengeHelper.runSync(() -> Bukkit.getPluginManager().callEvent(new SettingToggleEvent(this))); + // A menu click runs on the clicker's thread, but what a setting does belongs to the global region. + // A Bukkit event must not be called from the threads settings are loaded on either. + Regions.global(Challenges.getInstance(), () -> { + try { + if (enabled) onEnable(); + else onDisable(); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); + } + Bukkit.getPluginManager().callEvent(new SettingToggleEvent(this)); + }); updateItems(); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 1c3184a5c..4b7102d73 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -1,5 +1,7 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.challenges.catalog.Challenge; import net.cyperia.challenges.plugin.challenges.type.ISetting; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; @@ -114,8 +116,10 @@ public void setEnabled(boolean enabled) { if (this.enabled == enabled) return; this.enabled = enabled; - if (enabled) onEnable(); - else onDisable(); + Regions.global(Challenges.getInstance(), () -> { + if (enabled) onEnable(); + else onDisable(); + }); updateItems(); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SharedCollectionGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SharedCollectionGoal.java new file mode 100644 index 000000000..b9a8577a0 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/SharedCollectionGoal.java @@ -0,0 +1,169 @@ +package net.cyperia.challenges.plugin.challenges.type.abstraction; + +import net.cyperia.challenges.plugin.challenges.type.abstraction.menu.MenuGoal; +import net.cyperia.challenges.plugin.challenges.type.helper.GoalHelper; +import net.cyperia.challenges.plugin.challenges.type.helper.GoalLeaderboard; +import net.cyperia.challenges.plugin.content.i18n.MessageKey; +import net.cyperia.challenges.plugin.content.i18n.MessageKeySpace; +import net.cyperia.challenges.plugin.content.i18n.Prefix; +import net.cyperia.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; +import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.kyori.adventure.bossbar.BossBar; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +/** + * A goal everyone completes together, in any order or one target after another in a random order, with an + * optional sidebar ranking players by how much of it they found first. + */ +public abstract class SharedCollectionGoal extends MenuGoal { + + private final BooleanSubSetting rankingSetting; + private final BooleanSubSetting randomOrderSetting; + + public SharedCollectionGoal(boolean randomOrderByDefault) { + rankingSetting = registerSetting("ranking", "3.1", new BooleanSubSetting( + new ItemStack(Material.BOOK), MessageKeySpace.of("challenge.generic.sub.ranking") + ) { + @Override + protected void onEnable() { + updateRankingVisibility(); + } + + @Override + protected void onDisable() { + updateRankingVisibility(); + } + }); + randomOrderSetting = registerSetting("randomOrder", "3.1", new BooleanSubSetting( + new ItemStack(Material.COMPASS), MessageKeySpace.of("challenge.generic.sub.random-order"), randomOrderByDefault + ) { + @Override + protected void onEnable() { + onOrderChange(); + } + + @Override + protected void onDisable() { + onOrderChange(); + } + }); + } + + protected enum FindType { + ITEM, MOB, ADVANCEMENT + } + + // A mob is the only find without a finder: a boss dying to an explosion nobody caused + protected final void announceFind(@NotNull FindType type, @NotNull Object target, @Nullable Player finder) { + String key = "challenge.generic.found." + type.name().toLowerCase(Locale.ROOT); + if (finder == null) { + MessageKey.of(key + "-without-finder").broadcast(Prefix.CHALLENGES, target); + } else { + MessageKey.of(key).broadcast(Prefix.CHALLENGES, target, finder); + } + } + + // Marks the current target of the random order as done without a finder, null when everything is done + @Nullable + protected abstract Object skipCurrentTarget(); + + public final void skip(@NotNull CommandSender sender) { + if (!isRandomOrder()) { + MessageKey.of("command.goal.skip-any-order").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + Object skipped = skipCurrentTarget(); + if (skipped == null) { + MessageKey.of("command.goal.skip-finished").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + MessageKey.of("challenge.generic.skipped").broadcast(Prefix.CHALLENGES, skipped); + SoundSample.PLING.broadcast(); + bossbar.update(); + } + + // One entry per find, finds without a player left out + @NotNull + protected abstract Collection getFinders(); + + protected abstract void enableGoal(); + + protected abstract void disableGoal(); + + @Override + protected final void onEnable() { + enableGoal(); + scoreboard.setContent(GoalLeaderboard.sharedScoreboardContent(this::getRanking)); + updateRankingVisibility(); + } + + @Override + protected final void onDisable() { + scoreboard.hide(); + disableGoal(); + } + + protected final boolean isRandomOrder() { + return randomOrderSetting.getAsBoolean(); + } + + // Runs while the settings load too, before the goal itself may be enabled + protected void onOrderChange() { + if (isEnabled()) bossbar.update(); + } + + // The Cyperia texture pack draws only the green bar: green for a progress count, white while a next target is shown + protected static void styleBossbar(@NotNull BossBarInstance bar, boolean showsNextTarget, float progress) { + bar.setColor(showsNextTarget ? BossBar.Color.WHITE : BossBar.Color.GREEN); + bar.setProgress(progress); + } + + protected void updateRanking() { + if (!scoreboard.isShown()) return; + scoreboard.update(); + } + + private void updateRankingVisibility() { + if (isEnabled() && rankingSetting.getAsBoolean()) { + scoreboard.show(); + } else { + scoreboard.hide(); + } + } + + @NotNull + private Map getRanking() { + Map finds = new HashMap<>(); + for (UUID finder : getFinders()) { + finds.merge(finder, 1, Integer::sum); + } + return GoalHelper.createLeaderboardFromValues(finds, (_, count) -> count); + } + + // The same seed gives the same order as long as the targets do not change, so a restart keeps it + @NotNull + protected static List seededOrder(@NotNull Collection targets, long seed) { + List order = new ArrayList<>(targets); + Collections.shuffle(order, new Random(seed)); + return order; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index cb7fe5c13..88c2fd029 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -1,12 +1,13 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.SkippableTimer; import net.cyperia.challenges.plugin.challenges.type.ValueUnit; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.IRandom; import net.cyperia.commons.common.config.Document; -import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; public abstract class TimedChallenge extends SettingModifier implements SkippableTimer { @@ -56,7 +57,7 @@ public TimedChallenge(int min, int max, int defaultValue, boolean runAsync) { public void setValue(int value) { super.setValue(value); if (!timerStatus) { - restartTimer(); + Regions.global(Challenges.getInstance(), this::restartTimer); } } @@ -92,9 +93,9 @@ public final void handleTimedChallengeSecond() { public final void executeTimeActivation() { if (runAsync) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, this::onTimeActivation); + Regions.async(plugin, this::onTimeActivation); } else { - Bukkit.getScheduler().runTask(plugin, this::onTimeActivation); + Regions.nextTick(plugin, this::onTimeActivation); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index 8106f5042..3529d99d6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -5,6 +5,7 @@ import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.management.server.WorldManager.WorldSettings; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.GameMode; import org.bukkit.World; import org.bukkit.entity.Player; @@ -17,13 +18,14 @@ import org.jetbrains.annotations.Nullable; import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; public abstract class WorldDependentChallenge extends TimedChallenge { - private boolean inExtraWorld; - private BiConsumer lastTeleport; - private int teleportIndex; + private volatile boolean inExtraWorld; + private volatile BiConsumer lastTeleport; + private final AtomicInteger teleportIndex = new AtomicInteger(); public WorldDependentChallenge() { super(false); @@ -65,7 +67,7 @@ protected void teleportToWorld(boolean allowJoinCatchUp, @NotNull BiConsumer teleport(player, action)); broadcastIgnored(player -> { teleport(player, null); @@ -77,7 +79,7 @@ protected void teleportBack() { if (!Challenges.getInstance().getWorldManager().isWorldInUse()) return; Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = false); lastTeleport = null; - teleportIndex = 0; + teleportIndex.set(0); } protected void teleportBack(@NotNull Player player) { @@ -96,7 +98,7 @@ private void teleport(@NotNull Player player, @Nullable BiConsumer ingamePlayers = ChallengeHelper.getIngamePlayers(); if (ingamePlayers.isEmpty()) return; Player target = ingamePlayers.get(0); - player.teleport(target); - player.setSpectatorTarget(target); + player.teleportAsync(target.getLocation()).thenAccept(success -> + Regions.entity(Challenges.getInstance(), player, () -> player.setSpectatorTarget(target))); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onJoin(@NotNull PlayerJoinEvent event) { - if (isInExtraWorld()) { - if (lastTeleport == null) return; - if (Challenges.getInstance().getWorldManager().hasPlayerData(event.getPlayer())) return; - teleport(event.getPlayer(), lastTeleport); - } else { - Challenges.getInstance().getWorldManager().restorePlayerData(event.getPlayer()); - } + Player player = event.getPlayer(); + // Both paths teleport, which Canvas refuses while the player is still logging in + Regions.nextTick(Challenges.getInstance(), player, () -> { + if (isInExtraWorld()) { + if (lastTeleport == null) return; + if (Challenges.getInstance().getWorldManager().hasPlayerData(player)) return; + teleport(player, lastTeleport); + } else { + Challenges.getInstance().getWorldManager().restorePlayerData(player); + } + }); } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/WorldGeneratorChallenge.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/WorldGeneratorChallenge.java index 1dd79be35..ef256bc0b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/WorldGeneratorChallenge.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/WorldGeneratorChallenge.java @@ -3,22 +3,22 @@ import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.management.server.GameWorldStorage; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnLocationEvent; +import net.cyperia.challenges.plugin.spigot.events.PortalTravelEvent; import net.cyperia.challenges.plugin.spigot.generator.ConvertingWorldGenerator; import net.cyperia.challenges.plugin.spigot.generator.VoidMapGenerator; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.PortalType; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerPortalEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.world.AsyncStructureSpawnEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.generator.ChunkGenerator; @@ -100,42 +100,32 @@ public void onJoin(@NotNull PlayerJoinEvent event) { if (!isEnabled()) return; Player player = event.getPlayer(); World replacement = getStorage().getReplacement(player.getWorld()); - if (replacement != null) player.teleport(BlockUtils.getCenteredSpawn(replacement)); + // Canvas refuses a teleport while the player is still logging in + if (replacement != null) { + Regions.nextTick(Challenges.getInstance(), player, () -> player.teleportAsync(BlockUtils.getCenteredSpawn(replacement))); + } } @EventHandler(priority = EventPriority.LOW) - public void onRespawn(@NotNull PlayerRespawnEvent event) { + public void onRespawn(@NotNull PlayerRespawnLocationEvent event) { if (!isEnabled()) return; World replacement = getStorage().getReplacement(event.getRespawnLocation().getWorld()); if (replacement != null) event.setRespawnLocation(BlockUtils.getCenteredSpawn(replacement)); } + // The server resolves every portal against its own worlds, so a destination in a replaced one has to be moved over @EventHandler - public void onPlayerPortal(@NotNull PlayerPortalEvent event) { - if (!isEnabled()) return; - Location to = event.getTo(); - World replacement = getReplacement(to); - if (replacement != null) event.setTo(redirectPortalTravel(to, replacement, event.getCause() == TeleportCause.END_PORTAL, true)); - } - - @EventHandler - public void onEntityPortal(@NotNull EntityPortalEvent event) { + public void onPortalTravel(@NotNull PortalTravelEvent event) { if (!isEnabled()) return; - Location to = event.getTo(); - World replacement = getReplacement(to); + World replacement = getStorage().getReplacement(event.getTargetWorld()); if (replacement == null) return; - // The event carries no cause, but only an end portal leads into or out of the end - boolean endPortal = replacement.getEnvironment() == Environment.THE_END - || event.getFrom().getWorld().getEnvironment() == Environment.THE_END; - event.setTo(redirectPortalTravel(to, replacement, endPortal, false)); - } - - // The server resolves every portal against its own worlds, so a destination in a replaced one has to be moved over - @Nullable - private static World getReplacement(@Nullable Location to) { - if (to == null || to.getWorld() == null) return null; - return getStorage().getReplacement(to.getWorld()); + event.setTargetWorld(replacement); + Location destination = event.getDestination(); + // Only a server that hands out the destination lets it be rebuilt, elsewhere it follows the world + if (destination == null) return; + boolean endPortal = event.getPortalType() == PortalType.ENDER; + event.setDestination(redirectPortalTravel(destination, replacement, endPortal, event.getEntity() instanceof Player)); } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java index 73437117d..aa3f3121a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java @@ -3,20 +3,61 @@ import net.cyperia.challenges.plugin.challenges.type.IGoal; import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.challenges.type.helper.GoalHelper; +import net.cyperia.challenges.plugin.content.i18n.MessageKeySpace; import net.cyperia.challenges.plugin.management.menu.format.Interaction; import net.cyperia.challenges.plugin.management.menu.format.InteractionTooltips; import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class MenuGoal extends MenuSetting implements IGoal { + // Whether the item pool has every enchanted book level and potion on its own, see CollectableItem. + // onChange also runs while the settings load, before the goal may be enabled + @NotNull + protected final BooleanSubSetting registerItemVariantsSetting(boolean enabledByDefault, @NotNull Runnable onChange) { + return registerPoolToggle("itemVariants", Material.ENCHANTED_BOOK, "item-variants", enabledByDefault, onChange); + } + + // Whether the mob pool has the variants of a mob by its attributes, like coat or age, see KillableMob + @NotNull + protected final BooleanSubSetting registerMobAttributesSetting(boolean enabledByDefault, @NotNull Runnable onChange) { + return registerPoolToggle("mobAttributes", Material.ZOMBIE_HEAD, "mob-attributes", enabledByDefault, onChange); + } + + // Whether the mob pool has the variants of a mob by what it holds, wears and rides with + @NotNull + protected final BooleanSubSetting registerMobEquipmentSetting(boolean enabledByDefault, @NotNull Runnable onChange) { + return registerPoolToggle("mobEquipment", Material.IRON_SWORD, "mob-equipment", enabledByDefault, onChange); + } + + @NotNull + private BooleanSubSetting registerPoolToggle(@NotNull String key, @NotNull Material icon, @NotNull String name, + boolean enabledByDefault, @NotNull Runnable onChange) { + return registerSetting(key, "3.1", new BooleanSubSetting( + new ItemStack(icon), MessageKeySpace.of("challenge.generic.sub." + name), enabledByDefault + ) { + @Override + protected void onEnable() { + onChange.run(); + } + + @Override + protected void onDisable() { + onChange.run(); + } + }); + } + + // Once enabled the settings item opens the sub menu, see MenuSetting#handleClick @NotNull @Override protected InteractionTooltips getSettingsTooltips() { return new InteractionTooltips() - .on(MenuClickType.LEFT, isEnabled() ? Interaction.DISABLE : Interaction.ENABLE_GOAL); + .on(MenuClickType.LEFT, isEnabled() ? Interaction.OPEN : Interaction.ENABLE_GOAL); } @Override diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index 3f2f0411d..22342e9a5 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.challenges.type.abstraction.menu; +import net.cyperia.commons.bukkit.utils.misc.Regions; import lombok.Getter; import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.IModifier; @@ -13,7 +14,6 @@ import net.cyperia.challenges.plugin.management.menu.format.Interaction; import net.cyperia.challenges.plugin.management.menu.format.InteractionTooltips; import net.cyperia.challenges.plugin.management.menu.format.ItemFormatter; -import net.cyperia.challenges.plugin.management.menu.generator.VersionedContentContainer; import net.cyperia.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.cyperia.challenges.plugin.management.menu.search.SearchCategory; import net.cyperia.challenges.plugin.management.menu.search.SearchFindable; @@ -22,6 +22,7 @@ import net.cyperia.commons.bukkit.utils.item.ItemBuilder; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; import net.cyperia.commons.common.config.Document; +import net.cyperia.commons.common.version.Version; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; @@ -30,7 +31,7 @@ import java.util.*; -public abstract class MenuSetting extends Setting implements SearchCategory, VersionedContentContainer.FromList { +public abstract class MenuSetting extends Setting implements SearchCategory { @Getter private final SubSettingsMenuGenerator menuGenerator; @@ -56,6 +57,12 @@ protected final T registerSetting(@NotNull String key, @N } @NotNull + // A sub setting newer than this setting shows this setting as updated in that version + protected final T registerSetting(@NotNull String key, @NotNull String since, @NotNull T setting) { + ((SubSetting) setting).since = since; + return registerSetting(key, setting); + } + protected final T registerSetting(@NotNull String key, @NotNull OneEnabledGroup group, @NotNull T setting) { group.add(setting); return registerSetting(key, setting); @@ -149,10 +156,13 @@ public boolean isDefaultSettings() { return super.isDefaultSettings() && settings.values().stream().allMatch(SubSetting::isDefaultSettings); } - @NotNull - @Override - public List getVersionedContent() { - return Arrays.asList(settings.values().toArray(new SubSetting[0])); // cheaper than new ArrayList + @Nullable + public final String getNewestSubSettingSince() { + String newest = null; + for (SubSetting setting : settings.values()) { + if (setting.since != null && (newest == null || Version.parse(setting.since).isNewerThan(Version.parse(newest)))) newest = setting.since; + } + return newest; } // TODO extract duplicate logic with AbstractChallenge @@ -165,6 +175,9 @@ public abstract class SubSetting implements Listener, ISetting, SearchFindable { private final boolean enabledByDefault; private OneEnabledGroup group; + @Getter + @Nullable + private String since; /** The own state, {@link #isEnabled()} respects the setting this belongs to as well. */ protected boolean enabled; @@ -190,6 +203,7 @@ public ItemBuilder getDisplayItem(@NotNull Locale locale) { .name(getName()) .description(getDescription()) .tooltips(getDisplayTooltips()) + .suffixIfNewUpdated(this) .builder(locale); } @@ -265,6 +279,11 @@ public boolean isVisible() { return MenuSetting.this.isVisible(); } + @Override + public boolean isVisibleTo(@NotNull Player viewer) { + return MenuSetting.this.isVisibleTo(viewer); + } + @Override public boolean isEnabled() { return MenuSetting.this.isEnabled() && enabled; @@ -284,8 +303,10 @@ public void setEnabled(boolean enabled) { private void applyEnabled(boolean enabled) { this.enabled = enabled; - if (enabled) this.onEnable(); - else this.onDisable(); + Regions.global(Challenges.getInstance(), () -> { + if (enabled) this.onEnable(); + else this.onDisable(); + }); this.updateItems(); } @@ -477,7 +498,7 @@ public void setValue(int value) { this.value = value; updateItems(); - onValueChange(); + Regions.global(Challenges.getInstance(), this::onValueChange); } @Override diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java index 4d2c81f60..33182a967 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java @@ -4,6 +4,7 @@ import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; import net.cyperia.challenges.plugin.content.i18n.MessageKey; +import net.cyperia.challenges.plugin.management.menu.MenuManager; import net.cyperia.challenges.plugin.management.menu.generator.IDynamicMenuGenerator; import net.cyperia.challenges.plugin.management.menu.generator.MultiPageMenuGenerator; import net.cyperia.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; @@ -12,6 +13,7 @@ import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -77,7 +79,8 @@ public void resetCache() { } @Override - public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Player viewer) { + Locale locale = localeOf(viewer); List settings = getSubSettingsForPage(page); int[] slots = getSlots(settings.size()); @@ -113,6 +116,11 @@ public void showFinable(@NotNull Player player, @NotNull MenuSetting.SubSetting public void setSubSettingItemsAt(@NotNull MenuSetting.SubSetting setting, @NotNull Inventory inventory, int displaySlot, @NotNull Locale locale) { inventory.setItem(displaySlot + ChallengeListMenuGenerator.SLOT_OFFSET_DISPLAY, setting.getDisplayItem(locale).build()); inventory.setItem(displaySlot + ChallengeListMenuGenerator.SLOT_OFFSET_SETTINGS, setting.getSettingsItem(locale).build()); + MenuManager manager = Challenges.getInstance().getMenuManager(); + ItemStack pane = ChallengeListMenuGenerator.releasePane(setting, manager.isNewSuffix(), manager.isUpdatedSuffix()); + if (pane == null) return; + inventory.setItem(displaySlot + ChallengeListMenuGenerator.SLOT_OFFSET_UPPER, pane); + inventory.setItem(displaySlot + ChallengeListMenuGenerator.SLOT_OFFSET_LOWER, pane); } @NotNull @@ -145,7 +153,7 @@ protected int getDisplaySlotOfSubSetting(int indexOfSetting) { } @Override - public int getPageCount() { + public int getPageCount(@NotNull Player viewer) { // must have at least one page return Math.max(1, Math.ceilDiv(subSettingsCache.size(), MAX_SLOTS_PER_PAGE)); } @@ -183,7 +191,8 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { int slot = slots[i]; if (info.getSlot() != slot && info.getSlot() != slot + 9) continue; MenuSetting.SubSetting setting = settings.get(i); - if (Challenges.getInstance().getMenuManager().denySettingsChange(info.getPlayer())) return true; + MenuManager menuManager = Challenges.getInstance().getMenuManager(); + if (menuManager.denySettingsChange(info.getPlayer()) || menuManager.denyLockedChange(info.getPlayer(), challenge)) return true; setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == slot)); return true; } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/ChallengeHelper.java index f922bc0f0..04cd02b06 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -19,7 +19,7 @@ import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -42,8 +42,8 @@ public final class ChallengeHelper { /** amount a shift click adds to / subtracts from a modifier value */ public static final int SHIFT_STEP = 10; - @Getter - private static volatile boolean inInstantKill = false; + // Set while the kill's damage is dealt, and read by the handlers that damage calls on the same thread + private static final ThreadLocal inInstantKill = ThreadLocal.withInitial(() -> false); @Getter @Setter @@ -53,19 +53,33 @@ private ChallengeHelper() { } public static void punish(@NotNull Player player) { - runSync(() -> penalty.punish(player)); + Regions.entity(Challenges.getInstance(), player, () -> penalty.punish(player)); } public static void punish(@NotNull Player player, int delay) { - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> punish(player), delay); + Regions.later(Challenges.getInstance(), player, () -> punish(player), delay); + } + + public static boolean isInInstantKill() { + return inInstantKill.get(); } /** use {@link #punish(Player)} where applicable instead */ @ApiStatus.Internal public static void kill(@NotNull Player player) { - runSync(() -> { + kill(player, () -> { + }); + } + + /** + * Kills the player on their own thread. {@code finished} runs there afterwards, or on this thread when + * the player is gone before the kill could be scheduled. + */ + @ApiStatus.Internal + public static void kill(@NotNull Player player, @NotNull Runnable finished) { + Regions.entity(Challenges.getInstance(), player, () -> { try { - inInstantKill = true; + inInstantKill.set(true); player.setNoDamageTicks(0); player.damage(Integer.MAX_VALUE); @@ -76,32 +90,30 @@ public static void kill(@NotNull Player player) { player.setHealth(0); } } finally { - inInstantKill = false; + inInstantKill.set(false); + finished.run(); } - }); + }, finished); } /** use {@link #punish(Player, int)} where applicable instead */ @ApiStatus.Internal public static void kill(@NotNull Player player, int delay) { - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> kill(player), delay); + Regions.later(Challenges.getInstance(), player, () -> kill(player), delay); } @CheckReturnValue public static boolean runSyncIfConcurrent(Runnable task) { - if (Bukkit.isPrimaryThread()) { + if (Regions.isGlobalThread()) { return false; } - Bukkit.getScheduler().runTask(Challenges.getInstance(), task); + Regions.global(Challenges.getInstance(), task); return true; } + /** Runs on the global region, where game state and world settings are owned */ public static void runSync(@NotNull Runnable task) { - if (Bukkit.isPrimaryThread()) { - task.run(); - return; - } - Bukkit.getScheduler().runTask(Challenges.getInstance(), task); + Regions.global(Challenges.getInstance(), task); } public static void openPunishmentMenu(@NotNull Player player) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalHelper.java index 4c18d07af..059c6a154 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -7,6 +7,7 @@ import net.cyperia.challenges.plugin.management.challenges.ChallengeManager; import org.bukkit.Bukkit; import org.bukkit.GameMode; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -32,33 +33,50 @@ public static void handleSetEnabled(@NotNull IGoal goal, boolean enabled) { } @NotNull - public static Map createPointsFromValues(@NotNull AtomicInteger mostPoints, @NotNull Map map, @NotNull ToIntBiFunction mapper, boolean zeros) { + public static Map createPointsFromValues(@NotNull AtomicInteger mostPoints, @NotNull Map map, @NotNull ToIntBiFunction mapper) { Map result = new HashMap<>(); - if (zeros) { - for (Player player : ChallengeAPI.getIngamePlayers()) { - result.put(player, 0); - } - } for (Entry entry : map.entrySet()) { Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) + if (player == null || !countsPoints(player)) + continue; + int points = mapper.applyAsInt(entry.getKey(), entry.getValue()); + if (points == 0) continue; - // Ignore spectators when playing but show spectators after challenge end - boolean isSpectator = player.getGameMode() == GameMode.SPECTATOR; - if (!AbstractChallenge.ignorePlayer(player) || (ChallengeAPI.isPaused() && isSpectator)) { - int points = mapper.applyAsInt(entry.getKey(), entry.getValue()); - if (points == 0) - continue; - result.put(player, points); + result.put(player, points); + + if (points >= mostPoints.get()) + mostPoints.set(points); + } + return result; + } - if (points >= mostPoints.get()) - mostPoints.set(points); + /** + * Every playing player, with 0 points too, and every player who left with at least one point. + */ + @NotNull + public static Map createLeaderboardFromValues(@NotNull Map map, @NotNull ToIntBiFunction mapper) { + Map result = new HashMap<>(); + for (Player player : ChallengeAPI.getIngamePlayers()) { + result.put(player, 0); + } + for (Entry entry : map.entrySet()) { + int points = mapper.applyAsInt(entry.getKey(), entry.getValue()); + Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) { + if (points >= 1) result.put(Bukkit.getOfflinePlayer(entry.getKey()), points); + } else if (points != 0 && countsPoints(player)) { + result.put(player, points); } } return result; } + // Spectators do not count while playing, but are shown again after the challenge ended + private static boolean countsPoints(@NotNull Player player) { + return !AbstractChallenge.ignorePlayer(player) || (ChallengeAPI.isPaused() && player.getGameMode() == GameMode.SPECTATOR); + } + public static void getWinnersOnEnd(@NotNull List winners, @NotNull Map points) { int mostPoints = 0; List currentWinners = new LinkedList<>(); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboard.java b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboard.java index 994c018c3..0354e76cc 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboard.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboard.java @@ -16,12 +16,16 @@ import org.jetbrains.annotations.Nullable; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.ToIntFunction; @@ -30,7 +34,10 @@ */ public final class GoalLeaderboard { - public static final int SCOREBOARD_ENTRIES = 9; + // Top places, then a skipped line and the viewer with this many either side: at most nine lines + private static final int TOP_PLACES = 5; + private static final int AROUND = 1; + static final int SKIPPED = -1; private static final TextColor GOLD = TextColor.color(0xFFD700); private static final TextColor SILVER = TextColor.color(0xC0C0C0); @@ -40,6 +47,9 @@ public final class GoalLeaderboard { // the sidebar is rebuilt on every update, so every place it can reach is precomputed private static final Component[] PLACES = new Component[16]; + // name() shows an offline player's rank only once it is loaded, and players who left drop out of that cache + private static final Set loadedOfflineNames = ConcurrentHashMap.newKeySet(); + static { for (int i = 0; i < PLACES.length; i++) { PLACES[i] = buildPlace(i + 1); @@ -81,14 +91,20 @@ public static Component nameComponent(@NotNull OfflinePlayer player, @Nullable P } @NotNull - public static BiConsumer scoreboardContent(@NotNull Supplier> points) { + public static BiConsumer scoreboardContent(@NotNull Supplier> points) { return scoreboardContent(points, null); } @NotNull - public static BiConsumer scoreboardContent(@NotNull Supplier> points, + public static BiConsumer scoreboardContent(@NotNull Supplier> points, @Nullable Function> additionalLines) { - return content(points, null, additionalLines); + return content(points, null, additionalLines, true); + } + + // Everyone plays together, so there is no own placement to show above the ranking + @NotNull + public static BiConsumer sharedScoreboardContent(@NotNull Supplier> points) { + return content(points, null, null, false); } /** @@ -96,27 +112,35 @@ public static BiConsumer scoreboardContent(@NotNull * currently up to (force battles put the target they are hunting there). */ @NotNull - public static BiConsumer scoreboardContentWithDetail(@NotNull Supplier> points, - @NotNull Function entryDetail) { - return content(points, entryDetail, null); + public static BiConsumer scoreboardContentWithDetail(@NotNull Supplier> points, + @NotNull Function entryDetail) { + return content(points, entryDetail, null, true); } @NotNull - private static BiConsumer content(@NotNull Supplier> points, - @Nullable Function entryDetail, - @Nullable Function> additionalLines) { + private static BiConsumer content(@NotNull Supplier> points, + @Nullable Function entryDetail, + @Nullable Function> additionalLines, + boolean showPlacement) { return (board, viewer) -> { - Ranking ranking = rank(points.get(), Integer::intValue); + Map values = points.get(); + loadOfflineNames(values.keySet()); + Ranking ranking = rank(values, Integer::intValue); board.addEmptyLine(); - board.addLine(MessageKey.of("scoreboard.leaderboard.placement"), placeComponent(ranking.placeOf(viewer))); - board.addEmptyLine(); + if (showPlacement) { + board.addLine(MessageKey.of("scoreboard.leaderboard.placement"), placeComponent(ranking.placeOf(viewer))); + board.addEmptyLine(); + } MessageKey entryKey = MessageKey.of(entryDetail == null ? "scoreboard.leaderboard.entry" : "scoreboard.leaderboard.entry-detail"); - int entries = Math.min(ranking.size(), SCOREBOARD_ENTRIES); - for (int i = 0; i < entries; i++) { - Player ranked = ranking.keyAt(i); + for (int i : sidebarRows(ranking.size(), ranking.indexOf(player -> player.getUniqueId().equals(viewer.getUniqueId())), TOP_PLACES, AROUND)) { + if (i == SKIPPED) { + board.addLine(MessageKey.of("scoreboard.leaderboard.skipped")); + continue; + } + OfflinePlayer ranked = ranking.keyAt(i); Component place = placeComponent(ranking.placeAt(i)); Component name = nameComponent(ranked, viewer); String score = NumberFormatter.MIDDLE_NUMBER.format(ranking.scoreAt(i)); @@ -138,6 +162,36 @@ private static BiConsumer content(@NotNull Supplier< }; } + /** + * The ranking indices a sidebar shows: the top {@code places}, and where the viewer sits below them, {@link #SKIPPED} + * and the viewer with {@code around} entries either side. A viewer just below the top gets the whole run instead. + * + * @param own index of the viewer, -1 if unranked + */ + @NotNull + static List sidebarRows(int size, int own, int places, int around) { + List rows = new ArrayList<>(); + if (own <= places + around) { + for (int i = 0; i < Math.min(places + 2 * around + 1, size); i++) rows.add(i); + return rows; + } + for (int i = 0; i < places; i++) rows.add(i); + rows.add(SKIPPED); + for (int i = own - around; i <= Math.min(own + around, size - 1); i++) rows.add(i); + return rows; + } + + private static void loadOfflineNames(@NotNull Collection players) { + List missing = players.stream() + .filter(player -> !(player instanceof Player)) + .map(OfflinePlayer::getUniqueId) + .filter(loadedOfflineNames::add) + .toList(); + if (missing.isEmpty()) return; + Challenges.getInstance().getPlayerManager().getNameProvider().load(missing) + .thenRun(() -> ChallengeHelper.runSync(() -> Challenges.getInstance().getScoreboardManager().updateAll())); + } + /** * Writes the same ranking into chat, for goals that show a result once instead of a live sidebar. * Offline players stay listed, so leaving right before the end does not erase a score. @@ -217,6 +271,14 @@ public int placeAt(int index) { return places[index]; } + // -1 if no key matches + public int indexOf(@NotNull Predicate key) { + for (int i = 0; i < keys.length; i++) { + if (key.test(keyAt(i))) return i; + } + return -1; + } + /** * @return the place of {@code key}, or the place right behind the last ranked one if it is not ranked */ diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeLoader.java index 418c11ce0..31bb59e3b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeLoader.java @@ -55,9 +55,9 @@ private void register(@NotNull Challenge entry, @NotNull Definition.Implementati try { type = Class.forName(implementation.className(), true, loader); } catch (ClassNotFoundException ex) { - // The public release ships without beta classes and shows their entries locked + // The public release ships without beta classes and shows their entries locked, a hidden one not at all if (entry.release().beta()) { - register(new LockedChallenge(entry)); + if (!entry.hidden()) register(new LockedChallenge(entry)); } else { Logger.error("The class {} of challenge {} does not exist", implementation.className(), entry.id()); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeManager.java index d1eb3be28..1ac7ea6c4 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/challenges/ChallengeManager.java @@ -6,6 +6,8 @@ import net.cyperia.challenges.plugin.challenges.type.IGoal; import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.cyperia.challenges.plugin.management.challenges.entities.GamestateSaveable; +import net.cyperia.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; +import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.commons.bukkit.utils.logging.Logger; import net.cyperia.commons.common.config.Document; import net.cyperia.commons.common.config.FileDocument; @@ -127,6 +129,7 @@ public void enable() { // After the settings: a generator setting creates its worlds on enable, and a location saved in one // deserializes to null while that world does not exist loadGamestate(Challenges.getInstance().getConfigManager().getGamestateConfig().readonly()); + Challenges.getInstance().getScheduler().register(this); } public synchronized void loadSettings(@NotNull Document config) { @@ -211,6 +214,13 @@ public void saveGameStateInto(@NotNull Document config) { } } + // Without it a crash loses everything since the last clean stop. A reset stops the scheduler before it clears the file + @ScheduledTask(ticks = 5 * 60 * 20, async = false, playerPolicy = PlayerCountPolicy.ALWAYS) + public void autosave() { + saveGamestate(false); + Challenges.getInstance().getChallengeTimer().saveSession(false); + } + public synchronized void saveGamestate(boolean async) { FileDocument config = Challenges.getInstance().getConfigManager().getGamestateConfig(); saveGameStateInto(config); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/files/ConfigManager.java index 2fc3062fa..eda8ba09b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/files/ConfigManager.java @@ -118,7 +118,6 @@ public class Keys { // type safety public final String CUSTOM_CHALLENGE_ALLOWED_COMMANDS = "custom-challenge-settings.allowed-commands-to-execute"; public final String JOIN_QUIT_MESSAGES = "join-quit-messages"; - public final String PLUGIN_INFO_ON_JOIN = "plugin-info-on-join"; public final String UNSUPPORTED_VERSION_CHAT_WARNING = "unsupported-version-chat-warning"; public final String TIMER_COLORS = "timer-colors"; public final String TIMER_IS_PAUSED_INFO = "timer-is-paused-info"; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/inventory/HotbarManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/inventory/HotbarManager.java index 9bdfc7c48..87fcf3d5e 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/inventory/HotbarManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/inventory/HotbarManager.java @@ -2,15 +2,16 @@ import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.Challenges; -import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.content.loader.LanguageLoader; import net.cyperia.challenges.plugin.management.scheduler.policy.ExtraWorldPolicy; import net.cyperia.challenges.plugin.management.scheduler.task.TimerTask; import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; import net.cyperia.challenges.plugin.permission.ChallengesPermissions; import net.cyperia.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnedEvent; import net.cyperia.challenges.plugin.spigot.events.SettingToggleEvent; import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import net.cyperia.commons.common.config.FileDocument; import org.bukkit.Bukkit; @@ -123,7 +124,7 @@ public boolean isLobbyInventory(@NotNull Player player) { * language are watched already. */ public void refreshAll() { - ChallengeHelper.runSync(() -> Bukkit.getOnlinePlayers().forEach(this::refresh)); + Challenges.getInstance().getPlayerManager().forEachAudience(this::refresh); } public void refresh(@NotNull Player player) { @@ -270,7 +271,9 @@ private void putSlot(@NotNull String layout, @NotNull Map slots } public void handleDisable() { - Bukkit.getOnlinePlayers().forEach(player -> removeItems(player, HotbarItemTag::isTagged)); + // Nothing can be scheduled once the plugin is disabling. The disabling thread passes every ownership + // check, so each player is cleaned inline. + Bukkit.getOnlinePlayers().forEach(player -> Regions.entity(Challenges.getInstance(), player, () -> removeItems(player, HotbarItemTag::isTagged))); } // The default world policy would skip a timer change made while an extra world is in use @@ -283,7 +286,7 @@ public void onTimerStatusChange() { public void onJoin(@NotNull PlayerJoinEvent event) { // Next tick, once join handling elsewhere (game mode, cosmetics) has settled Player player = event.getPlayer(); - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> refresh(player, true)); + Regions.nextTick(Challenges.getInstance(), player, () -> refresh(player, true)); } @EventHandler @@ -298,7 +301,7 @@ public void onGameModeChange(@NotNull PlayerGameModeChangeEvent event) { } @EventHandler(priority = EventPriority.MONITOR) - public void onRespawn(@NotNull PlayerRespawnEvent event) { + public void onRespawn(@NotNull PlayerRespawnedEvent event) { refreshLater(event.getPlayer()); } @@ -325,7 +328,7 @@ public void onSettingToggle(@NotNull SettingToggleEvent event) { } private void refreshLater(@NotNull Player player) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> refresh(player)); + Regions.nextTick(Challenges.getInstance(), player, () -> refresh(player)); } @EventHandler(priority = EventPriority.HIGH) diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/MenuManager.java index 51936e470..916ae86b0 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/MenuManager.java @@ -3,6 +3,7 @@ import lombok.Getter; import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.challenges.plugin.challenges.type.EntryAccess; import net.cyperia.challenges.plugin.challenges.type.IChallenge; import net.cyperia.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; import net.cyperia.challenges.plugin.content.i18n.MessageKey; @@ -21,7 +22,6 @@ import org.bukkit.permissions.Permissible; import org.jetbrains.annotations.NotNull; -import java.util.Locale; public final class MenuManager { @@ -70,15 +70,9 @@ public void generateMenus() { } } - Locale language = Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).getConfigLanguage(); - // seed the config language, then refresh every already-cached locale so a visibility change - // (e.g. LanguageSetting hiding itself for a non-default provider) reaches all players, not just - // those viewing in the config language mainMenu.updatePages(); - mainMenu.updateOrGeneratePages(language); for (MenuType value : MenuType.values()) { value.getMenuGenerator().updatePages(); - value.getMenuGenerator().updateOrGeneratePages(language); } generated = true; @@ -139,6 +133,14 @@ public boolean denySettingsChange(@NotNull Player player) { return true; } + // true means the rejection effect has already been played and the click must not be handled + public boolean denyLockedChange(@NotNull Player player, @NotNull IChallenge challenge) { + if (!EntryAccess.isLocked(challenge, player)) return false; + SoundSample.BASS_OFF.play(player); + MessageKey.of("menu.restricted.click").send(player, Prefix.CHALLENGES); + return true; + } + static boolean maySettingsChange(boolean permissionRequired, @NotNull Permissible player) { return !permissionRequired || player.hasPermission(ChallengesPermissions.MANAGE); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/format/ItemFormatter.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/format/ItemFormatter.java index 8694f5fec..52670bdd5 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/format/ItemFormatter.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/format/ItemFormatter.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.management.menu.format; +import org.bukkit.permissions.Permissible; import lombok.Getter; import lombok.RequiredArgsConstructor; import net.cyperia.challenges.plugin.Challenges; @@ -173,15 +174,31 @@ public ItemFormatter suffixIf(boolean condition, @NotNull String messageKey, @No @NotNull public ItemFormatter suffixIfNewUpdated(@NotNull Object annotationHolder) { - if (annotationHolder instanceof VersionedContentContainer container) { - int betaCount = container.getBetaCount(); - int updatedCount = container.getUpdatedCount(); - int newCount = container.getNewCount(); - if (betaCount > 0 || updatedCount > 0 || newCount > 0) { - return suffixIfNewUpdated(betaCount, newCount, updatedCount); - } + if (annotationHolder instanceof VersionedContentContainer container + && suffixCounts(container.getBetaCount(), container.getNewCount(), container.getUpdatedCount())) { + return this; } + return suffixOwnRelease(annotationHolder); + } + + // A container counts only the entries the viewer sees + @NotNull + public ItemFormatter suffixIfNewUpdated(@NotNull Object annotationHolder, @NotNull Permissible viewer) { + if (annotationHolder instanceof VersionedContentContainer container + && suffixCounts(container.getBetaCount(viewer), container.getNewCount(viewer), container.getUpdatedCount(viewer))) { + return this; + } + return suffixOwnRelease(annotationHolder); + } + + private boolean suffixCounts(int betaCount, int newCount, int updatedCount) { + if (betaCount <= 0 && updatedCount <= 0 && newCount <= 0) return false; + suffixIfNewUpdated(betaCount, newCount, updatedCount); + return true; + } + @NotNull + private ItemFormatter suffixOwnRelease(@NotNull Object annotationHolder) { if (ReleaseInfo.isBeta(annotationHolder)) { return suffix(MessageKey.of("suffix.beta")); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java index 5d0e035c6..1a0985f91 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java @@ -16,6 +16,7 @@ import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; import net.cyperia.commons.bukkit.utils.menu.MenuPosition; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -28,6 +29,7 @@ import java.util.Collection; import java.util.List; import java.util.Locale; +import java.util.function.BiConsumer; public abstract class AbstractMenuGenerator implements IMenuGenerator { @@ -45,7 +47,12 @@ public abstract class AbstractMenuGenerator implements IMenuGenerator { public abstract GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player); @NotNull - public abstract Inventory getOrInitInventory(@NotNull Locale locale, int page); + public abstract Inventory createInventory(@NotNull Player viewer, int page); + + /** + * Draws a page into an inventory again, the one the viewer has open when a menu changes. + */ + public abstract void renderPage(@NotNull Inventory inventory, int page, @NotNull Player viewer); /** * @implSpec multiple of 9 @@ -77,10 +84,11 @@ public void openMenu(@NotNull Player player, int page) { * menu history the position carries intact. */ public void openMenuWithPositionOverwrite(@NotNull Player player, int page, @NotNull GeneratorMenuPosition menuPosition) { - Locale locale = findLanguageProvider().getPlayerLanguage(player); - Inventory inventory = getOrInitInventory(locale, page); - MenuPosition.set(player, menuPosition); - player.openInventory(inventory); + Regions.entity(Challenges.getInstance(), player, () -> { + Inventory inventory = createInventory(player, page); + MenuPosition.set(player, menuPosition); + player.openInventory(inventory); + }); } protected int getNavigateNextSlot() { @@ -95,8 +103,62 @@ protected int getNavigateBackSlot() { return getNavigateHomeSlot() + 1; } - protected void setNavigationItems(@NotNull Inventory inventory, int page, @NotNull Locale locale) { - int lastPage = getPageCount() - 1; + @Override + public void updatePages() { + for (Player viewer : retrieveViewers()) { + int page = openPageOf(viewer); + int pageCount = getPageCount(viewer); + if (page < pageCount) { + renderOpenPage(viewer, page); + } else { + openMenu(viewer, pageCount - 1); + } + } + } + + @Override + public void updatePage(int page) { + for (Player viewer : retrieveViewers()) { + if (openPageOf(viewer) == page) { + renderOpenPage(viewer, page); + } + } + } + + protected void updatePage(int page, @NotNull BiConsumer updateAction) { + for (Player viewer : retrieveViewers()) { + Inventory inventory = openMenuInventory(viewer); + if (inventory != null && openPageOf(viewer) == page) { + updateAction.accept(inventory, localeOf(viewer)); + } + } + } + + private void renderOpenPage(@NotNull Player viewer, int page) { + Inventory inventory = openMenuInventory(viewer); + if (inventory != null) { + renderPage(inventory, page, viewer); + } + } + + @Nullable + private static Inventory openMenuInventory(@NotNull Player viewer) { + Inventory inventory = viewer.getOpenInventory().getTopInventory(); + return inventory.getHolder() == MenuPosition.HOLDER ? inventory : null; + } + + private static int openPageOf(@NotNull Player viewer) { + return MenuPosition.get(viewer) instanceof GeneratorMenuPosition position ? position.getPage() : -1; + } + + @NotNull + protected Locale localeOf(@NotNull Player viewer) { + return findLanguageProvider().getPlayerLanguage(viewer); + } + + protected void setNavigationItems(@NotNull Inventory inventory, int page, @NotNull Player viewer) { + Locale locale = localeOf(viewer); + int lastPage = getPageCount(viewer) - 1; if (page < lastPage) { boolean canSkipPages = page + SHIFT_NAVIGATE_PAGES <= lastPage; @@ -104,7 +166,7 @@ protected void setNavigationItems(@NotNull Inventory inventory, int page, @NotNu .name(MessageKey.of("menu.generic.navigate.next")) .tooltip(MenuClickType.LEFT, Interaction.NEXT) .tooltipIf(canSkipPages, MenuClickType.LEFT_SHIFT, Interaction.NEXT_SHIFT.withArgs(SHIFT_NAVIGATE_PAGES)) - .tooltipIf(!canSkipPages && page < lastPage - 1, MenuClickType.LEFT_SHIFT, Interaction.NEXT_LAST.withArgs(getPageCount())) + .tooltipIf(!canSkipPages && page < lastPage - 1, MenuClickType.LEFT_SHIFT, Interaction.NEXT_LAST.withArgs(lastPage + 1)) .build(locale)); } @@ -125,18 +187,18 @@ protected void setNavigationItems(@NotNull Inventory inventory, int page, @NotNu } } - protected boolean isSlotUnoccupied(int page, int slot) { + protected boolean isSlotUnoccupied(int page, int slot, @NotNull Player viewer) { if (page > 0 && slot == getNavigateBackSlot()) { return false; } - if (page < getPageCount() - 1 && slot == getNavigateNextSlot()) { + if (page < getPageCount(viewer) - 1 && slot == getNavigateNextSlot()) { return false; } return slot != getNavigateHomeSlot(); } - protected void setItemSafely(@NotNull Inventory inventory, int slot, @NotNull ItemStack item, int page) { - if (isSlotUnoccupied(page, slot)) { + protected void setItemSafely(@NotNull Inventory inventory, int slot, @NotNull ItemStack item, int page, @NotNull Player viewer) { + if (isSlotUnoccupied(page, slot, viewer)) { inventory.setItem(slot, item); } } @@ -170,7 +232,7 @@ public abstract class GeneratorMenuPosition implements MenuPosition { @Override public void handleClick(@NotNull MenuClickInfo info) { - int pageCount = getPageCount(); + int pageCount = getPageCount(info.getPlayer()); if (page >= pageCount) { // should not happen; dynamically calculated page count changed SoundSample.CLICK.play(info.getPlayer()); return; @@ -268,7 +330,7 @@ protected void handleNavigateOutOfMenu(@NotNull Player player) { AbstractMenuGenerator previousMenu = previousPosition.getGenerator(); int previousPage = previousPosition.getPage(); - int previousMenuPageCount = previousMenu.getPageCount(); + int previousMenuPageCount = previousMenu.getPageCount(player); if (previousPage < previousMenuPageCount) { // dynamic page count might have changed previousMenu.openMenuWithPositionOverwrite(player, previousPage, previousPosition); } else { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/DialogMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/DialogMenuGenerator.java index 7b9287d8b..163b0d4e3 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/DialogMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/DialogMenuGenerator.java @@ -30,22 +30,18 @@ public void openMenu(@NotNull Player player, @NotNull S state) { @NotNull protected Dialog createNewDialog(@NotNull Player player, @NotNull S state) { Locale locale = TranslationManager.getLocaleOf(player); - return Dialog.create(factory -> this.setupDialog(factory, state, locale)); + return Dialog.create(factory -> this.setupDialog(factory, state, player, locale)); } - protected void setupDialog(@NotNull RegistryBuilderFactory factory, @NotNull S state, @NotNull Locale locale) { - setupDialog(factory.empty(), state, locale); + protected void setupDialog(@NotNull RegistryBuilderFactory factory, @NotNull S state, + @NotNull Player viewer, @NotNull Locale locale) { + setupDialog(factory.empty(), state, viewer, locale); } @NotNull protected abstract S createDefaultState(@NotNull Player player); - protected abstract void setupDialog(@NotNull DialogRegistryEntry.Builder dialog, @NotNull S state, @NotNull Locale locale); - - @Override - public void updateOrGeneratePages(@NotNull Locale locale) { - // noop; nothing to cache; generated dynamically - } + protected abstract void setupDialog(@NotNull DialogRegistryEntry.Builder dialog, @NotNull S state, @NotNull Player viewer, @NotNull Locale locale); @Override public void updatePages() { @@ -58,7 +54,7 @@ public void updatePage(int page) { } @Override - public final int getPageCount() { + public final int getPageCount(@NotNull Player viewer) { return 1; } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/IMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/IMenuGenerator.java index b89252929..bc5cffd02 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/IMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/IMenuGenerator.java @@ -3,8 +3,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Locale; - public interface IMenuGenerator { void openMenu(@NotNull Player player, int page); @@ -13,19 +11,16 @@ default void openMenu(@NotNull Player player) { openMenu(player, 0); } - void updateOrGeneratePages(@NotNull Locale locale); - /** - * @implSpec regenerates all pages (only for locales already generated!) - * use {@link #updateOrGeneratePages(Locale)} to create the menu for a new locale + * @implSpec re-renders the menu for everyone who has it open; a page is rendered for its viewer when it is opened */ void updatePages(); void updatePage(int page); /** - * @implSpec must be at least {@code 1} + * @implSpec must be at least {@code 1}; may differ between viewers when entries are hidden from some of them */ - int getPageCount(); + int getPageCount(@NotNull Player viewer); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 7880bc633..1e620771f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -4,32 +4,25 @@ import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Bukkit; -import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; -import java.util.*; -import java.util.function.BiConsumer; +import java.util.Locale; public abstract class MultiPageMenuGenerator extends AbstractMenuGenerator { - // thread-safety: reads/writes only triggered by Player interaction Events on the main thread - // if any async computation is done, the write access should be handed over to the main thread - // org.bukkit.Inventory operations are also not thread-safe! - protected final Map> inventoriesCache = new HashMap<>(); - - public abstract void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale); + public abstract void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Player viewer); public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { MenuBackground.fill(inventory); } @NotNull - public Inventory createEmptyInventory(@NotNull Locale locale, int page) { + public Inventory createEmptyInventory(@NotNull Player viewer, int page) { + MessageKey title = getPageCount(viewer) == 1 ? MessageKey.of("menu.title-format") : MessageKey.of("menu.title-format-page"); return Bukkit.createInventory(MenuPosition.HOLDER, getInventorySize(), - getMenuTitleKey().asComponent(locale, getMenuName(), getMenuTitlePageArg(page))); + title.asComponent(localeOf(viewer), getMenuName(), getMenuTitlePageArg(page))); } @NotNull @@ -37,104 +30,22 @@ protected Object getMenuTitlePageArg(int page) { return page + 1; } - @NotNull - private MessageKey getMenuTitleKey() { - if (getPageCount() == 1) return MessageKey.of("menu.title-format"); - return MessageKey.of("menu.title-format-page"); - } - - @NotNull - @CheckReturnValue - protected final List generateInventories(@NotNull Locale locale) { - int pageCount = getPageCount(); - List inventories = new ArrayList<>(pageCount); - for (int page = 0; page < pageCount; page++) { - Inventory inventory = createEmptyInventory(locale, page); - setInventoryDecoration(inventory, page, locale); - setNavigationItems(inventory, page, locale); - updateInventoryContent(inventory, page, locale); - inventories.add(inventory); - } - return inventories; - } - @NotNull @Override - public final Inventory getOrInitInventory(@NotNull Locale locale, int page) { - Preconditions.checkArgument(page >= 0 && page < getPageCount(), "Invalid page number: %s; page count: %s", page, getPageCount()); - List inventories = inventoriesCache.computeIfAbsent(locale, this::generateInventories); - return inventories.get(page); + public final Inventory createInventory(@NotNull Player viewer, int page) { + int pageCount = getPageCount(viewer); + Preconditions.checkArgument(page >= 0 && page < pageCount, "Invalid page number: %s; page count: %s", page, pageCount); + Inventory inventory = createEmptyInventory(viewer, page); + renderPage(inventory, page, viewer); + return inventory; } + // The decoration goes first, so a slot whose item is gone since the last render is cleared @Override - public final void updatePages() { - Collection locales = new ArrayList<>(inventoriesCache.keySet()); // might get modified - for (Locale locale : locales) { - updateOrGeneratePages(locale); - } - } - - @Override - public void updateOrGeneratePages(@NotNull Locale locale) { - List inventories = inventoriesCache.get(locale); - if (inventories == null) { - // locale not generated yet: build every page from scratch - getOrInitInventory(locale, 0); - return; - } - - int pageCount = getPageCount(); // dynamically calculated, might have changed - - // drop surplus pages if the visible item set shrank across a page boundary - while (inventories.size() > pageCount) { - removeLastPage(inventories); - } - - // Re-render every still-existing page. The visible item set may have changed without the page - // count changing (e.g. a setting hiding itself once a non-default LanguageProvider is installed), - // so stale slots must be rebuilt in place rather than left untouched. Refilling the decoration - // first clears slots whose item was removed. - for (int page = 0; page < inventories.size(); page++) { - Inventory inventory = inventories.get(page); - setInventoryDecoration(inventory, page, locale); - setNavigationItems(inventory, page, locale); - updateInventoryContent(inventory, page, locale); - } - - // append missing pages if the visible item set grew across a page boundary - for (int page = inventories.size(); page < pageCount; page++) { - Inventory inventory = createEmptyInventory(locale, page); - setInventoryDecoration(inventory, page, locale); - setNavigationItems(inventory, page, locale); - updateInventoryContent(inventory, page, locale); - inventories.add(inventory); - } - } - - private void removeLastPage(@NotNull List inventories) { - Inventory removed = inventories.removeLast(); - int newLastPage = inventories.size() - 1; - // relocate anyone viewing the dropped page onto the new last page (or close if none remains) - for (HumanEntity viewer : new ArrayList<>(removed.getViewers())) { - if (viewer instanceof Player player && newLastPage >= 0) { - openMenu(player, newLastPage); - } else { - viewer.closeInventory(); - } - } - } - - @Override - public final void updatePage(int page) { - updatePage(page, (inventory, locale) -> updateInventoryContent(inventory, page, locale)); - } - - protected void updatePage(int page, @NotNull BiConsumer updateAction) { - Preconditions.checkArgument(page >= 0 && page < getPageCount(), "Invalid page number: %s; page count: %s", page, getPageCount()); - for (Map.Entry> entry : inventoriesCache.entrySet()) { - List inventories = entry.getValue(); - updateAction.accept(inventories.get(page), entry.getKey()); - } + public void renderPage(@NotNull Inventory inventory, int page, @NotNull Player viewer) { + setInventoryDecoration(inventory, page, localeOf(viewer)); + setNavigationItems(inventory, page, viewer); + updateInventoryContent(inventory, page, viewer); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/UncachedMultiPageSelectMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/MultiPageSelectMenuGenerator.java similarity index 58% rename from plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/UncachedMultiPageSelectMenuGenerator.java rename to plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/MultiPageSelectMenuGenerator.java index 1cc42fcd0..c04a455f8 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/UncachedMultiPageSelectMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/MultiPageSelectMenuGenerator.java @@ -1,10 +1,7 @@ package net.cyperia.challenges.plugin.management.menu.generator; -import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; -import net.cyperia.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; @@ -12,7 +9,7 @@ import java.util.Locale; -public abstract class UncachedMultiPageSelectMenuGenerator extends AbstractMenuGenerator { +public abstract class MultiPageSelectMenuGenerator extends MultiPageMenuGenerator { public static int[] calcSlots(int rows, int cols, int size) { if (rows * cols > size) @@ -39,63 +36,19 @@ public static int[] calcSlots(int padding, int size) { protected final T[] elements; - public UncachedMultiPageSelectMenuGenerator(@NotNull T[] elements) { + public MultiPageSelectMenuGenerator(@NotNull T[] elements) { this.elements = elements; } - @Override - public void updateOrGeneratePages(@NotNull Locale locale) { - // because pages are not cached, there is noting to update or pregenerate - } - - @Override - public void updatePages() { - // because pages are not cached, there is noting to update - } - - @Override - public void updatePage(int page) { - // because pages are not cached, there is noting to update - } - @NotNull @Override public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { - return new UncachedMultiPageMenuPosition(page, player); + return new MultiPageSelectMenuPosition(page, player); } - @NotNull @Override - public Inventory getOrInitInventory(@NotNull Locale locale, int page) { - Inventory inventory = createEmptyInventory(locale, page); - setInventoryDecoration(inventory, page, locale); - setNavigationItems(inventory, page, locale); - updateInventoryContent(inventory, page, locale); - return inventory; - } - - public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { - MenuBackground.fill(inventory); - } - - @NotNull - protected Inventory createEmptyInventory(@NotNull Locale locale, int page) { - return Bukkit.createInventory(MenuPosition.HOLDER, getInventorySize(), - getMenuTitleKey().asComponent(locale, getMenuName(), getMenuTitlePageArg(page))); - } - - @NotNull - protected Object getMenuTitlePageArg(int page) { - return page + 1; - } - - @NotNull - private MessageKey getMenuTitleKey() { - if (getPageCount() == 1) return MessageKey.of("menu.title-format"); - return MessageKey.of("menu.title-format-page"); - } - - public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Player viewer) { + Locale locale = localeOf(viewer); int startIndex = page * getMaxEntriesPerPage(); int endIndex = Math.min(startIndex + getMaxEntriesPerPage(), elements.length); int[] slots = getSlots(); @@ -118,17 +71,17 @@ protected void setElementItemsAt(@NotNull T element, @NotNull Inventory inventor public abstract int[] getSlots(); @Override - public int getPageCount() { - return Math.ceilDiv(elements.length, getMaxEntriesPerPage()); + public int getPageCount(@NotNull Player viewer) { + return Math.max(1, Math.ceilDiv(elements.length, getMaxEntriesPerPage())); } public int getMaxEntriesPerPage() { return getSlots().length; } - public class UncachedMultiPageMenuPosition extends HistoryAwareGeneratorMenuPosition { + public class MultiPageSelectMenuPosition extends HistoryAwareGeneratorMenuPosition { - public UncachedMultiPageMenuPosition(int page, @NotNull Player player) { + public MultiPageSelectMenuPosition(int page, @NotNull Player player) { super(page, player); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/NoOpMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/NoOpMenuGenerator.java index 7d1e0febd..b2cef35fe 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/NoOpMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/NoOpMenuGenerator.java @@ -5,8 +5,6 @@ import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; -import java.util.Locale; - public class NoOpMenuGenerator extends AbstractMenuGenerator { public void playDenyEffect(@NotNull Player player) { @@ -26,32 +24,22 @@ public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player @NotNull @Override - public Inventory getOrInitInventory(@NotNull Locale locale, int page) { + public Inventory createInventory(@NotNull Player viewer, int page) { throw new UnsupportedOperationException("NoOpMenuGenerator does not support inventory generation"); } @Override - public int getInventorySize() { - return 0; - } - - @Override - public void updateOrGeneratePages(@NotNull Locale locale) { + public void renderPage(@NotNull Inventory inventory, int page, @NotNull Player viewer) { // noop } @Override - public void updatePages() { - // noop - } - - @Override - public void updatePage(int page) { - // noop + public int getInventorySize() { + return 0; } @Override - public int getPageCount() { + public int getPageCount(@NotNull Player viewer) { return 0; } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/SingleAnimatedMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/SingleAnimatedMenuGenerator.java index ac19454d9..357812106 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/SingleAnimatedMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/SingleAnimatedMenuGenerator.java @@ -9,6 +9,7 @@ import net.cyperia.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.*; @@ -17,7 +18,7 @@ public abstract class SingleAnimatedMenuGenerator implements IMenuGenerator { protected final boolean animated; - private final Map inventoryCache = new HashMap<>(); + private final Map inventoryCache = new HashMap<>(); private volatile boolean stale; @NotNull @@ -25,7 +26,13 @@ public abstract class SingleAnimatedMenuGenerator implements IMenuGenerator { // TODO impl dynamic formatting as in Multi-/SinglePageMenuGenerator @NotNull - public abstract AnimatedInventory createAnimatedInventory(@NotNull Locale locale); + public abstract AnimatedInventory createAnimatedInventory(@NotNull Locale locale, @NotNull Player viewer); + + // Viewers of one language share an inventory unless this differs between them + @Nullable + protected Object variantOf(@NotNull Player viewer) { + return null; + } @NotNull protected AnimatedInventory createEmptyInventory(@NotNull Locale locale) { @@ -41,12 +48,13 @@ public void markStale() { } @NotNull - public AnimatedInventory getOrCreateInventory(@NotNull Locale locale) { + private AnimatedInventory getOrCreateInventory(@NotNull Player viewer) { if (stale) { stale = false; inventoryCache.clear(); } - return inventoryCache.computeIfAbsent(locale, this::createAnimatedInventory); + Locale locale = findLanguageProvider().getPlayerLanguage(viewer); + return inventoryCache.computeIfAbsent(new CacheKey(locale, variantOf(viewer)), _ -> createAnimatedInventory(locale, viewer)); } @Override @@ -56,31 +64,22 @@ public void openMenu(@NotNull Player player, int page) { return; } - Locale locale = findLanguageProvider().getPlayerLanguage(player); - AnimatedInventory inventory = getOrCreateInventory(locale); + AnimatedInventory inventory = getOrCreateInventory(player); MenuPosition.set(player, createMenuPosition()); inventory.open(player); } public void openMenuInstantly(@NotNull Player player, boolean playSound) { - Locale locale = findLanguageProvider().getPlayerLanguage(player); - AnimatedInventory inventory = getOrCreateInventory(locale); + AnimatedInventory inventory = getOrCreateInventory(player); MenuPosition.set(player, createMenuPosition()); inventory.openNotAnimated(player, playSound); } - @Override - public void updateOrGeneratePages(@NotNull Locale locale) { - inventoryCache.put(locale, createAnimatedInventory(locale)); - } - + // Updating every frame of the animation is tedious, the next open builds it again @Override public void updatePages() { - // updating every frame of the animation is tedious, just recreate it stale = false; - List locales = new ArrayList<>(inventoryCache.keySet()); inventoryCache.clear(); - locales.forEach(locale -> inventoryCache.put(locale, createAnimatedInventory(locale))); } @Override @@ -89,7 +88,7 @@ public void updatePage(int page) { } @Override - public final int getPageCount() { + public final int getPageCount(@NotNull Player viewer) { return 1; } @@ -99,4 +98,7 @@ public final int getPageCount() { protected LanguageProvider findLanguageProvider() { return Challenges.getInstance().getTranslationManager().getLanguageProvider(); } + + private record CacheKey(@NotNull Locale locale, @Nullable Object variant) { + } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java index 15317c2ca..4df5e15c5 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java @@ -5,20 +5,12 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; import java.util.Locale; -import java.util.Map; public abstract class SinglePageMenuGenerator extends AbstractMenuGenerator { - // thread-safety: reads/writes only triggered by Player interaction Events on the main thread - // if any async computation is done, the write access should be handed over to the main thread - // org.bukkit.Inventory operations are also not thread-safe! - protected final Map inventoryCache = new HashMap<>(); - @NotNull public abstract GeneratorMenuPosition createMenuPosition(@NotNull Player player); @@ -28,11 +20,6 @@ public void setInventoryDecoration(@NotNull Inventory inventory, @NotNull Locale public abstract void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale locale); - @NotNull - protected Inventory createEmptyInventory(@NotNull Locale locale) { - return Bukkit.createInventory(MenuPosition.HOLDER, getInventorySize(), MessageKey.of("menu.title-format").asComponent(locale, getMenuName())); - } - @NotNull @Override public final GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { @@ -41,47 +28,23 @@ public final GeneratorMenuPosition createMenuPosition(int page, @NotNull Player @NotNull @Override - public final Inventory getOrInitInventory(@NotNull Locale locale, int page) { - return inventoryCache.computeIfAbsent(locale, this::createAndInitInventory); - } - - @Override - public final void updatePages() { - for (Map.Entry entry : inventoryCache.entrySet()) { - updateInventoryContent(entry.getValue(), entry.getKey()); - } + public final Inventory createInventory(@NotNull Player viewer, int page) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getInventorySize(), + MessageKey.of("menu.title-format").asComponent(localeOf(viewer), getMenuName())); + renderPage(inventory, 0, viewer); + return inventory; } @Override - public void updateOrGeneratePages(@NotNull Locale locale) { - Inventory inventory = inventoryCache.get(locale); - if (inventory != null) { - updateInventoryContent(inventory, locale); - } else { - getOrInitInventory(locale, 0); // will generate and cache the inventory - } - } - - @NotNull - @CheckReturnValue - protected Inventory createAndInitInventory(@NotNull Locale locale) { - Inventory inventory = createEmptyInventory(locale); + public void renderPage(@NotNull Inventory inventory, int page, @NotNull Player viewer) { + Locale locale = localeOf(viewer); setInventoryDecoration(inventory, locale); - setNavigationItems(inventory, 0, locale); + setNavigationItems(inventory, 0, viewer); updateInventoryContent(inventory, locale); - return inventory; - } - - @Override - public void updatePage(int page) { - if (page != 0) { - throw new IllegalArgumentException("Invalid page number for SinglePageMenuGenerator: " + page); - } - updatePages(); } @Override - public final int getPageCount() { + public final int getPageCount(@NotNull Player viewer) { return 1; } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/VersionedContentContainer.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/VersionedContentContainer.java index 008026bd8..698f1986e 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/VersionedContentContainer.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/VersionedContentContainer.java @@ -1,6 +1,7 @@ package net.cyperia.challenges.plugin.management.menu.generator; import net.cyperia.challenges.plugin.challenges.type.ReleaseInfo; +import org.bukkit.permissions.Permissible; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -27,6 +28,19 @@ default int getBetaCount() { return 0; } + // The counts a viewer sees, which leave out entries hidden from them + default int getNewCount(@NotNull Permissible viewer) { + return getNewCount(); + } + + default int getUpdatedCount(@NotNull Permissible viewer) { + return getUpdatedCount(); + } + + default int getBetaCount(@NotNull Permissible viewer) { + return getBetaCount(); + } + interface FromList extends VersionedContentContainer { @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java index 6dc3f8cc9..ddaedf03a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java @@ -1,5 +1,8 @@ package net.cyperia.challenges.plugin.management.menu.generator.impl; +import org.bukkit.entity.Player; +import java.util.stream.Collectors; +import net.cyperia.challenges.plugin.challenges.type.EntryAccess; import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; import net.cyperia.challenges.plugin.content.i18n.MessageKey; @@ -57,7 +60,7 @@ public LocalizableMessage getMenuName() { @NotNull @Override - public AnimatedInventory createAnimatedInventory(@NotNull Locale locale) { + public AnimatedInventory createAnimatedInventory(@NotNull Locale locale, @NotNull Player viewer) { AnimatedInventory gui = createEmptyInventory(locale); gui.createAndAdd().fill(DefaultItems.FILL_ITEM); gui.cloneLastAndAdd().setContrast( @@ -83,19 +86,19 @@ public AnimatedInventory createAnimatedInventory(@NotNull Locale locale) { for (int i = 0; i < SLOT_MAPPING.length; i += 2) { AnimationFrame frame = gui.cloneLastAndAdd(); - frame.setItem(GUI_SLOTS[i], createDisplayItem(locale, SLOT_MAPPING[i])); - frame.setItem(GUI_SLOTS[i + 1], createDisplayItem(locale, SLOT_MAPPING[i + 1])); + frame.setItem(GUI_SLOTS[i], createDisplayItem(locale, viewer, SLOT_MAPPING[i])); + frame.setItem(GUI_SLOTS[i + 1], createDisplayItem(locale, viewer, SLOT_MAPPING[i + 1])); } return gui; } @NotNull - protected ItemStack createDisplayItem(@NotNull Locale locale, @NotNull MenuType menuType) { + protected ItemStack createDisplayItem(@NotNull Locale locale, @NotNull Player viewer, @NotNull MenuType menuType) { ItemFormatter item = new ItemFormatter(menuType.getDisplayItemMaterial()) .name(menuType.getName()) .description(menuType.getDescription()) - .suffixIfNewUpdated(menuType.getMenuGenerator()) + .suffixIfNewUpdated(menuType.getMenuGenerator(), viewer) .tooltip(MenuClickType.LEFT, Interaction.OPEN); ChallengesMenuGenerator generator = findChallengesGenerator(menuType); @@ -113,6 +116,15 @@ private static ChallengesMenuGenerator findChallengesGenerator(@NotNull MenuType return generator instanceof ChallengesMenuGenerator challenges ? challenges : null; } + // Who may see a hidden entry sees it in the counts on the menu items + @NotNull + @Override + protected Object variantOf(@NotNull Player viewer) { + return Challenges.getInstance().getChallengeManager().getChallenges().stream() + .filter(challenge -> EntryAccess.isHidden(challenge) && EntryAccess.isListed(challenge, viewer)) + .collect(Collectors.toSet()); + } + @Override public int getInventorySize() { return SIZE; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java index 972289f24..23a46ed5f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java @@ -1,10 +1,15 @@ package net.cyperia.challenges.plugin.management.menu.generator.impl.challenge; +import java.util.function.Predicate; +import org.bukkit.permissions.Permissible; import lombok.Getter; import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.challenges.plugin.challenges.type.EntryAccess; import net.cyperia.challenges.plugin.challenges.type.IChallenge; import net.cyperia.challenges.plugin.challenges.type.ReleaseInfo; +import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.management.files.ConfigManager; +import net.cyperia.challenges.plugin.management.menu.MenuManager; import net.cyperia.challenges.plugin.management.menu.generator.VersionedContentContainer; import net.cyperia.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.cyperia.commons.bukkit.utils.item.ItemBuilder; @@ -34,7 +39,7 @@ public class ChallengeListMenuGenerator extends ChallengesMenuGenerator { public static final ItemStack NEW_CHALLENGE_ITEM = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, Component.empty()).build(); public static final ItemStack BETA_CHALLENGE_ITEM = new ItemBuilder(Material.PURPLE_STAINED_GLASS_PANE, Component.empty()).build(); - protected final List assignedChallengesCache = new LinkedList<>(); + protected final List assignedChallengesCache = new ArrayList<>(); @Getter protected final boolean newSuffix; @@ -126,42 +131,48 @@ public boolean executeChallengeClickAction(@NotNull IChallenge challenge, int sl } @Override - public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { - List challengesForPage = getChallengesForPage(page); - Iterator iterator = challengesForPage.iterator(); // LinkedList: poor performance for random access - for (int i = 0; iterator.hasNext(); i++) { - IChallenge challenge = iterator.next(); - updateChallengeDisplayAt(challenge, inventory, i, page, locale); + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Player viewer) { + Locale locale = localeOf(viewer); + List challengesForPage = getChallengesForPage(viewer, page); + for (int i = 0; i < challengesForPage.size(); i++) { + IChallenge challenge = challengesForPage.get(i); + if (EntryAccess.isLocked(challenge, viewer)) { + setLockedChallengeItemsAt(challenge, inventory, i, locale); + } else { + setChallengeItemsAt(challenge, inventory, i, locale); + } + setChallengeUpdateItemsAt(challenge, inventory, i, page, viewer); } } + // Where a challenge sits differs between viewers once some are hidden, so every open page is drawn again @Override public void updateElementDisplay(@NotNull IChallenge challenge) { - int challengeIndex = assignedChallengesCache.indexOf(challenge); - if (challengeIndex == -1) return; // not registered here? - - int page = getPageOfChallenge(challengeIndex); - int slotIndex = challengeIndex % DISPLAY_SLOTS.length; + if (assignedChallengesCache.contains(challenge)) { + updatePages(); + } + } - updatePage(page, (inventory, locale) -> setChallengeItemsAt(challenge, inventory, slotIndex, locale)); + protected void setChallengeUpdateItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotIndex, int page, @NotNull Player viewer) { + ItemStack pane = releasePane(challenge, newSuffix, updatedSuffix); + if (pane == null) return; + setItemSafely(inventory, DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, pane, page, viewer); + setItemSafely(inventory, DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, pane, page, viewer); } - protected void updateChallengeDisplayAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotsIndex, int page, @NotNull Locale locale) { - setChallengeItemsAt(challenge, inventory, slotsIndex, locale); - setChallengeUpdateItemsAt(challenge, inventory, slotsIndex, page, locale); + // The pane above and below an entry that marks it beta, new or updated + @Nullable + public static ItemStack releasePane(@NotNull Object entry, boolean newSuffix, boolean updatedSuffix) { + if (ReleaseInfo.isBeta(entry)) return BETA_CHALLENGE_ITEM; + if (newSuffix && ReleaseInfo.isNew(entry)) return NEW_CHALLENGE_ITEM; + if (updatedSuffix && ReleaseInfo.isUpdated(entry)) return UPDATED_CHALLENGE_ITEM; + return null; } - protected void setChallengeUpdateItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotIndex, int page, @NotNull Locale locale) { - if (ReleaseInfo.isBeta(challenge)) { - setItemSafely(inventory, DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, BETA_CHALLENGE_ITEM, page); - setItemSafely(inventory, DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, BETA_CHALLENGE_ITEM, page); - } else if (newSuffix && ReleaseInfo.isNew(challenge)) { - setItemSafely(inventory, DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, NEW_CHALLENGE_ITEM, page); - setItemSafely(inventory, DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, NEW_CHALLENGE_ITEM, page); - } else if (updatedSuffix && ReleaseInfo.isUpdated(challenge)) { - setItemSafely(inventory, DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, UPDATED_CHALLENGE_ITEM, page); - setItemSafely(inventory, DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, UPDATED_CHALLENGE_ITEM, page); - } + protected void setLockedChallengeItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotsIndex, @NotNull Locale locale) { + MessageKey locked = MessageKey.of("menu.restricted.state"); + inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_DISPLAY, challenge.getDisplayItem().state(locked).build(locale)); + inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_SETTINGS, challenge.getSettingsItem().state(locked).build(locale)); } protected void setChallengeItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotsIndex, @NotNull Locale locale) { @@ -179,32 +190,35 @@ protected ItemStack createChallengeSettingsItem(@NotNull IChallenge challenge, @ return challenge.getSettingsItem().build(locale); } + // Every challenge of this menu the viewer may see, in menu order @NotNull - protected List getChallengesForPage(int page) { + public List getListedChallenges(@NotNull Player viewer) { + return assignedChallengesCache.stream().filter(challenge -> challenge.isVisibleTo(viewer)).toList(); + } + + @NotNull + protected List getChallengesForPage(@NotNull Player viewer, int page) { + List listed = getListedChallenges(viewer); int startIndex = page * DISPLAY_SLOTS.length; - int endIndex = Math.min(startIndex + DISPLAY_SLOTS.length, assignedChallengesCache.size()); - return assignedChallengesCache.subList(startIndex, endIndex); + int endIndex = Math.min(startIndex + DISPLAY_SLOTS.length, listed.size()); + return startIndex >= endIndex ? List.of() : listed.subList(startIndex, endIndex); } - public int getDisplaySlotOfChallenge(IChallenge challenge) { - int index = assignedChallengesCache.indexOf(challenge); + public int getDisplaySlotOfChallenge(@NotNull Player viewer, @NotNull IChallenge challenge) { + int index = getListedChallenges(viewer).indexOf(challenge); if (index == -1) return -1; // challenge not registered here? return DISPLAY_SLOTS[index % DISPLAY_SLOTS.length]; } - public int getPageOfChallenge(IChallenge challenge) { - int index = assignedChallengesCache.indexOf(challenge); - return getPageOfChallenge(index); - } - - protected int getPageOfChallenge(int indexOfChallenge) { - if (indexOfChallenge == -1) return -1; // challenge not registered here? - return (indexOfChallenge / DISPLAY_SLOTS.length); + public int getPageOfChallenge(@NotNull Player viewer, @NotNull IChallenge challenge) { + int index = getListedChallenges(viewer).indexOf(challenge); + if (index == -1) return -1; // challenge not registered here? + return index / DISPLAY_SLOTS.length; } @Override public void openPageOf(@NotNull Player player, @NotNull IChallenge challenge) { - int page = getPageOfChallenge(challenge); + int page = getPageOfChallenge(player, challenge); if (page == -1) return; // challenge not registered here? openMenu(player, page); } @@ -217,9 +231,30 @@ public ChallengeListMenuGenerator getChallengeListMenuGenerator(@NotNull IChalle } @Override - public int getPageCount() { + public int getPageCount(@NotNull Player viewer) { // must have at least one page! - return Math.max(1, Math.ceilDiv(assignedChallengesCache.size(), DISPLAY_SLOTS.length)); + return Math.max(1, Math.ceilDiv(getListedChallenges(viewer).size(), DISPLAY_SLOTS.length)); + } + + @Override + public int getNewCount(@NotNull Permissible viewer) { + return countListed(viewer, ReleaseInfo::isNew); + } + + @Override + public int getUpdatedCount(@NotNull Permissible viewer) { + return countListed(viewer, ReleaseInfo::isUpdated); + } + + @Override + public int getBetaCount(@NotNull Permissible viewer) { + return countListed(viewer, ReleaseInfo::isBeta); + } + + private int countListed(@NotNull Permissible viewer, @NotNull Predicate filter) { + return (int) assignedChallengesCache.stream() + .filter(challenge -> filter.test(challenge) && EntryAccess.isListed(challenge, viewer)) + .count(); } @Override @@ -265,11 +300,12 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { int offset = findSlotOffset(info.getSlot(), slot); if (offset == -1) continue; - int challengeIndex = page * DISPLAY_SLOTS.length + i; - if (challengeIndex >= assignedChallengesCache.size()) return false; // page not full + List challengesForPage = getChallengesForPage(info.getPlayer(), page); + if (i >= challengesForPage.size()) return false; // page not full - IChallenge challenge = assignedChallengesCache.get(challengeIndex); // TODO slow LinkedList random access - if (Challenges.getInstance().getMenuManager().denySettingsChange(info.getPlayer())) return true; + IChallenge challenge = challengesForPage.get(i); + MenuManager menuManager = Challenges.getInstance().getMenuManager(); + if (menuManager.denySettingsChange(info.getPlayer()) || menuManager.denyLockedChange(info.getPlayer(), challenge)) return true; return executeChallengeClickAction(challenge, offset, info); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java index 97c6aee3f..7b22b40bc 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java @@ -46,8 +46,8 @@ public LocalizableMessage formatInfo(@NotNull MessageKey info) { public void showFinable(@NotNull Player player, @NotNull IChallenge challenge) { ChallengeListMenuGenerator listGenerator = getChallengeListMenuGenerator(challenge); if (listGenerator != null) { - int page = listGenerator.getPageOfChallenge(challenge); - int slot = listGenerator.getDisplaySlotOfChallenge(challenge); + int page = listGenerator.getPageOfChallenge(player, challenge); + int slot = listGenerator.getDisplaySlotOfChallenge(player, challenge); SearchResultHighlightMenuGenerator viewGenerator = new SearchResultHighlightMenuGenerator(listGenerator, page, slot); viewGenerator.openMenu(player); } else { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java index 3afc0e1ac..5a614b445 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.management.menu.generator.impl.challenge.categorised; +import org.bukkit.permissions.Permissible; import net.cyperia.challenges.plugin.challenges.type.IChallenge; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.management.menu.SettingCategory; @@ -103,53 +104,44 @@ public void updateElementDisplay(@NotNull IChallenge challenge) { CategorisedListMenuGenerator generator = categoryGenerators.get(category); if (generator != null) { generator.updateElementDisplay(challenge); - - int index = orderedCategories.indexOf(category); - int[] slots = getSlots(); - int page = index / slots.length; - int slotIndex = index % slots.length; - updatePage(page, (inventory, locale) -> setCategoryItemsAt(category, inventory, slots, slotIndex, locale)); + updatePages(); } } @Override - public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Player viewer) { int[] slots = getSlots(); - List categories = getCategoriesForPage(page, slots); + List categories = getCategoriesForPage(viewer, page, slots); int len = categories.size(); for (int i = 0; i < len; i++) { SettingCategory category = categories.get(i); - setCategoryDisplayAt(category, inventory, slots, i, locale); + setCategoryDisplayAt(category, inventory, slots, i, viewer); } } - private void setCategoryDisplayAt(@NotNull SettingCategory category, @NotNull Inventory inventory, int[] slots, int slotIndex, @NotNull Locale locale) { - setCategoryItemsAt(category, inventory, slots, slotIndex, locale); - setCategoryUpdateItemsAt(category, inventory, slots, slotIndex, locale); - } - - private void setCategoryItemsAt(@NotNull SettingCategory category, @NotNull Inventory inventory, int[] slots, int slotIndex, @NotNull Locale locale) { - inventory.setItem(slots[slotIndex], createCategoryDisplayItem(locale, category)); + private void setCategoryDisplayAt(@NotNull SettingCategory category, @NotNull Inventory inventory, int[] slots, int slotIndex, @NotNull Player viewer) { + inventory.setItem(slots[slotIndex], createCategoryDisplayItem(viewer, category)); + setCategoryUpdateItemsAt(category, inventory, slots, slotIndex, viewer); } - private void setCategoryUpdateItemsAt(@NotNull SettingCategory category, @NotNull Inventory inventory, int[] slots, int slotIndex, @NotNull Locale locale) { + private void setCategoryUpdateItemsAt(@NotNull SettingCategory category, @NotNull Inventory inventory, int[] slots, int slotIndex, @NotNull Player viewer) { CategorisedListMenuGenerator generator = categoryGenerators.get(category); if (generator != null) { // This will break if there are more than 2 rows! int row = slotIndex / getMaxItemsPerRow(); int offset = row == 0 ? -9 : +9; - if (generator.getBetaCount() > 0) { + if (generator.getBetaCount(viewer) > 0) { inventory.setItem(slots[slotIndex] + offset, ChallengeListMenuGenerator.BETA_CHALLENGE_ITEM); - } else if (generator.isNewSuffix() && generator.getNewCount() > 0) { + } else if (generator.isNewSuffix() && generator.getNewCount(viewer) > 0) { inventory.setItem(slots[slotIndex] + offset, ChallengeListMenuGenerator.NEW_CHALLENGE_ITEM); - } else if (generator.isUpdatedSuffix() && generator.getUpdatedCount() > 0) { + } else if (generator.isUpdatedSuffix() && generator.getUpdatedCount(viewer) > 0) { inventory.setItem(slots[slotIndex] + offset, ChallengeListMenuGenerator.UPDATED_CHALLENGE_ITEM); } } } @NotNull - protected ItemStack createCategoryDisplayItem(@NotNull Locale locale, @NotNull SettingCategory category) { + protected ItemStack createCategoryDisplayItem(@NotNull Player viewer, @NotNull SettingCategory category) { ItemFormatter item = new ItemFormatter() .item(category.getDisplayItemPreset()) .name(category.getName()) @@ -158,19 +150,28 @@ protected ItemStack createCategoryDisplayItem(@NotNull Locale locale, @NotNull S CategorisedListMenuGenerator generator = categoryGenerators.get(category); if (generator != null) { - item.suffixIfNewUpdated(generator); + item.suffixIfNewUpdated(generator, viewer); item.state(generator.formatInfo(category.getDescriptionInfo())); } - return item.build(locale); + return item.build(localeOf(viewer)); } + // A category of which the viewer may see nothing is left out for them @NotNull - protected List getCategoriesForPage(int page, @NotNull int[] slots) { + protected List getListedCategories(@NotNull Player viewer) { + return orderedCategories.stream() + .filter(category -> !categoryGenerators.get(category).getListedChallenges(viewer).isEmpty()) + .toList(); + } + + @NotNull + protected List getCategoriesForPage(@NotNull Player viewer, int page, @NotNull int[] slots) { + List listed = getListedCategories(viewer); int startIndex = page * slots.length; - int endIndex = Math.min(startIndex + slots.length, orderedCategories.size()); - return orderedCategories.subList(startIndex, endIndex); + int endIndex = Math.min(startIndex + slots.length, listed.size()); + return startIndex >= endIndex ? List.of() : listed.subList(startIndex, endIndex); } @NotNull @@ -206,6 +207,21 @@ public int getUpdatedCount() { return count; } + @Override + public int getNewCount(@NotNull Permissible viewer) { + return categoryGenerators.values().stream().mapToInt(generator -> generator.getNewCount(viewer)).sum(); + } + + @Override + public int getBetaCount(@NotNull Permissible viewer) { + return categoryGenerators.values().stream().mapToInt(generator -> generator.getBetaCount(viewer)).sum(); + } + + @Override + public int getUpdatedCount(@NotNull Permissible viewer) { + return categoryGenerators.values().stream().mapToInt(generator -> generator.getUpdatedCount(viewer)).sum(); + } + @Override public void openPageOf(@NotNull Player player, @NotNull IChallenge challenge) { SettingCategory category = challenge.getCategory(); @@ -242,8 +258,8 @@ public int getInventorySize() { } @Override - public int getPageCount() { - return Math.max(1, Math.ceilDiv(categoryGenerators.size(), getSlots().length)); + public int getPageCount(@NotNull Player viewer) { + return Math.max(1, Math.ceilDiv(getListedCategories(viewer).size(), getSlots().length)); } public class CategorisedOverviewMenuPosition extends GeneratorMenuPosition { @@ -258,7 +274,7 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { for (int i = 0; i < slots.length; i++) { if (info.getSlot() != slots[i]) continue; - List categories = getCategoriesForPage(page, slots); + List categories = getCategoriesForPage(info.getPlayer(), page, slots); if (i >= categories.size()) return false; // empty slot; page not full SettingCategory category = categories.get(i); CategorisedListMenuGenerator generator = categoryGenerators.get(category); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java index 086f4a1d1..9ec7a9820 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java @@ -20,8 +20,8 @@ import net.cyperia.commons.bukkit.utils.chat.ChatInputHandler; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.IRandom; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; @@ -194,7 +194,7 @@ private void navigateToChallengeList(@NotNull Player player) { return; } CustomListMenuGenerator list = home.getListGenerator(); - int page = Math.clamp(list.getPageOfChallenge(challenge), 0, list.getPageCount() - 1); + int page = Math.clamp(list.getPageOfChallenge(player, challenge), 0, list.getPageCount(player) - 1); list.openMenu(player, page); } @@ -281,7 +281,7 @@ public void handleChatInput(@NotNull AsyncChatEvent event, @NotNull String input MessageKey.of("custom.chars-exceeded").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); return; } - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Regions.nextTick(Challenges.getInstance(), event.getPlayer(), () -> { setName(input); openMenu(event.getPlayer()); }); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java index 76c72d7f7..03503eca0 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java @@ -59,7 +59,7 @@ protected ItemStack createChallengeCustomizeItem(@NotNull IChallenge challenge, } @Override - protected void setChallengeUpdateItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotIndex, int page, @NotNull Locale locale) { + protected void setChallengeUpdateItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotIndex, int page, @NotNull Player viewer) { // remove update/new indicator items as they would collide with display items and are not appropriate for custom challenges } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java index a68cfb824..b8373514a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java @@ -5,7 +5,7 @@ import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.management.menu.MenuType; import net.cyperia.challenges.plugin.management.menu.format.ItemFormatter; -import net.cyperia.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; +import net.cyperia.challenges.plugin.management.menu.generator.MultiPageSelectMenuGenerator; import net.cyperia.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.cyperia.challenges.plugin.utils.misc.ExperimentalUtils; import net.cyperia.challenges.plugin.utils.misc.MapUtils; @@ -19,7 +19,7 @@ import java.util.ArrayList; import java.util.Locale; -public class CustomChooseMaterialMenuGenerator extends UncachedMultiPageSelectMenuGenerator { +public class CustomChooseMaterialMenuGenerator extends MultiPageSelectMenuGenerator { public static final int SIZE = CustomChooseOptionMenuGenerator.SIZE; public static final int[] SLOTS = CustomChooseOptionMenuGenerator.SLOTS; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleOptionsMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleOptionsMenuGenerator.java index abd4bb0ad..b8a440208 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleOptionsMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleOptionsMenuGenerator.java @@ -74,7 +74,7 @@ public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player return new CustomChooseMultipleOptionsMenuPosition(page, player); } - public class CustomChooseMultipleOptionsMenuPosition extends UncachedMultiPageMenuPosition { + public class CustomChooseMultipleOptionsMenuPosition extends MultiPageSelectMenuPosition { public CustomChooseMultipleOptionsMenuPosition(int page, @NotNull Player player) { super(page, player); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseOptionMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseOptionMenuGenerator.java index 92c28e968..3b2ae554c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseOptionMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseOptionMenuGenerator.java @@ -10,7 +10,7 @@ import net.cyperia.challenges.plugin.management.menu.MenuType; import net.cyperia.challenges.plugin.management.menu.format.Interaction; import net.cyperia.challenges.plugin.management.menu.format.ItemFormatter; -import net.cyperia.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; +import net.cyperia.challenges.plugin.management.menu.generator.MultiPageSelectMenuGenerator; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; import org.bukkit.Material; @@ -21,7 +21,7 @@ import java.util.Locale; import java.util.Map; -public abstract class CustomChooseOptionMenuGenerator extends UncachedMultiPageSelectMenuGenerator { +public abstract class CustomChooseOptionMenuGenerator extends MultiPageSelectMenuGenerator { public static final int SIZE = 5 * 9; public static final int[] SLOTS = calcSlots(3, 7, SIZE); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java index 1b5b9f265..9d89cf754 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java @@ -4,7 +4,7 @@ import net.cyperia.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; import net.cyperia.challenges.plugin.management.menu.MenuType; -import net.cyperia.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; +import net.cyperia.challenges.plugin.management.menu.generator.MultiPageSelectMenuGenerator; import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.entity.Player; @@ -19,7 +19,7 @@ * Displays adjustable {@link ValueSetting} rows with a finish button. * Replaces the legacy {@code ValueMenuGenerator}. */ -public abstract class CustomChooseValueMenuGenerator extends UncachedMultiPageSelectMenuGenerator { +public abstract class CustomChooseValueMenuGenerator extends MultiPageSelectMenuGenerator { public static final int SIZE = 4 * 9; public static final int[] SLOTS = {10, 11, 12, 13}; // settings item at +9 each diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistMenuGenerator.java index f8e33edd9..17a64433c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistMenuGenerator.java @@ -1,5 +1,7 @@ package net.cyperia.challenges.plugin.management.menu.generator.impl.goal; +import org.jetbrains.annotations.Nullable; +import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistEntry; import net.cyperia.challenges.plugin.challenges.type.helper.GoalLeaderboard; @@ -7,7 +9,7 @@ import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.management.menu.MenuType; import net.cyperia.challenges.plugin.management.menu.format.ItemFormatter; -import net.cyperia.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; +import net.cyperia.challenges.plugin.management.menu.generator.MultiPageSelectMenuGenerator; import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.kyori.adventure.text.Component; @@ -16,6 +18,11 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import java.util.concurrent.ConcurrentHashMap; +import java.util.Map; +import org.bukkit.inventory.Inventory; +import org.bukkit.Material; +import net.cyperia.commons.bukkit.utils.menu.MenuClickType; import java.util.Arrays; import java.util.Comparator; @@ -25,22 +32,38 @@ import java.util.UUID; import java.util.stream.Collectors; -public class GoalChecklistMenuGenerator extends UncachedMultiPageSelectMenuGenerator { +public class GoalChecklistMenuGenerator extends MultiPageSelectMenuGenerator { private static final int COLUMNS = 7; private static final int MAX_ROWS = 4; + private static final Map SORT_ITEMS = Map.of( + GoalChecklistView.Sort.DEFAULT, Material.REPEATER, + GoalChecklistView.Sort.TIME, Material.CLOCK, + GoalChecklistView.Sort.FINDER, Material.PLAYER_HEAD); + private static final Map FILTER_ITEMS = Map.of( + GoalChecklistView.Filter.ALL, Material.ENDER_EYE, + GoalChecklistView.Filter.MISSING, Material.GRAY_DYE, + GoalChecklistView.Filter.FOUND, Material.LIME_DYE); + + // Kept while the server runs, so /goal opens the way it was left + private static final Map views = new ConcurrentHashMap<>(); private final ChecklistGoal goal; private final Player viewer; + private final GoalChecklistView view; private final int size; private final int[] slots; public GoalChecklistMenuGenerator(@NotNull ChecklistGoal goal, @NotNull Player viewer) { - super(goal.getChecklist(viewer).stream() - .sorted(Comparator.comparing(ChecklistEntry::done)) // stable, so each goal's own order holds within missing and done + this(goal, viewer, views.getOrDefault(viewer.getUniqueId(), GoalChecklistView.DEFAULT)); + } + + private GoalChecklistMenuGenerator(@NotNull ChecklistGoal goal, @NotNull Player viewer, @NotNull GoalChecklistView view) { + super(view.apply(goal.getChecklist(viewer), uuid -> Bukkit.getOfflinePlayer(uuid).getName()) .toArray(ChecklistEntry[]::new)); this.goal = goal; this.viewer = viewer; + this.view = view; int rows = Math.clamp(Math.ceilDiv(elements.length, COLUMNS), 1, MAX_ROWS); this.size = (rows + 2) * 9; this.slots = calcSlots(rows, COLUMNS, size); @@ -67,10 +90,20 @@ public ItemStack createDisplayItem(@NotNull ChecklistEntry element, @NotNull Loc return new ItemFormatter(element.icon()) .name(MessageKey.of("menu.goal.entry").withArgs(element.name())) .suffix(MessageKey.of(element.done() ? "suffix.selected" : "suffix.unselected")) - .description(element.finders().isEmpty() ? null : goal.getFinderMessage().withArgs(finderNames(element))) + .description(describe(element)) .build(locale); } + @Nullable + private LocalizableMessage describe(@NotNull ChecklistEntry element) { + LocalizableMessage finders = element.finders().isEmpty() ? null : goal.getFinderMessage().withArgs(finderNames(element)); + if (element.foundAt() == null) return finders; + LocalizableMessage time = ChallengeAPI.formatTime(element.foundAt()); + return finders == null + ? MessageKey.of("menu.goal.found-at").withArgs(time) + : MessageKey.of("menu.goal.found-by-at").withArgs(finders, time); + } + // rank colors for online players and the viewer underlined, like the goal leaderboards @NotNull private Component finderNames(@NotNull ChecklistEntry element) { @@ -81,6 +114,46 @@ private Component finderNames(@NotNull ChecklistEntry element) { .toList()); } + @Override + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Player viewer) { + super.updateInventoryContent(inventory, page, viewer); + Locale locale = localeOf(viewer); + String sort = view.sort().name().toLowerCase(Locale.ROOT); + inventory.setItem(getSortSlot(), new ItemFormatter(SORT_ITEMS.get(view.sort())) + .name(MessageKey.of("menu.goal.view.sort." + sort)) + .tooltip(MenuClickType.LEFT, MessageKey.of("menu.goal.view.switch-sort").withArgs( + MessageKey.of("menu.goal.view.sort-name." + view.sort().next().name().toLowerCase(Locale.ROOT)))) + .build(locale)); + inventory.setItem(getDirectionSlot(), new ItemFormatter(view.descending() ? Material.HOPPER : Material.DROPPER) + .name(MessageKey.of(view.descending() ? "menu.goal.view.descending" : "menu.goal.view.ascending")) + .tooltip(MenuClickType.LEFT, MessageKey.of(view.descending() ? "menu.goal.view.switch-ascending" : "menu.goal.view.switch-descending")) + .build(locale)); + String filter = view.filter().name().toLowerCase(Locale.ROOT); + inventory.setItem(getFilterSlot(), new ItemFormatter(FILTER_ITEMS.get(view.filter())) + .name(MessageKey.of("menu.goal.view.filter." + filter)) + .tooltip(MenuClickType.LEFT, MessageKey.of("menu.goal.view.switch-filter").withArgs( + MessageKey.of("menu.goal.view.filter-name." + view.filter().next().name().toLowerCase(Locale.ROOT)))) + .build(locale)); + } + + private int getSortSlot() { + return getInventorySize() - 6; + } + + private int getDirectionSlot() { + return getInventorySize() - 5; + } + + private int getFilterSlot() { + return getInventorySize() - 4; + } + + private void changeView(@NotNull Player player, @NotNull GoalChecklistView changed) { + views.put(player.getUniqueId(), changed); + SoundSample.CLICK.play(player); + new GoalChecklistMenuGenerator(goal, player, changed).openMenu(player, 0); + } + @Override public int[] getSlots() { return slots; @@ -95,15 +168,23 @@ public int getInventorySize() { @NotNull @Override public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { - return new UncachedMultiPageMenuPosition(page, player) { + return new MultiPageSelectMenuPosition(page, player) { @Override public void handleClick(@NotNull MenuClickInfo info) { - if (info.getSlot() != getNavigateHomeSlot()) { + Player player = info.getPlayer(); + int slot = info.getSlot(); + if (slot == getSortSlot()) { + changeView(player, new GoalChecklistView(view.filter(), view.sort().next(), view.descending())); + } else if (slot == getDirectionSlot()) { + changeView(player, new GoalChecklistView(view.filter(), view.sort(), !view.descending())); + } else if (slot == getFilterSlot()) { + changeView(player, new GoalChecklistView(view.filter().next(), view.sort(), view.descending())); + } else if (slot == getNavigateHomeSlot()) { + SoundSample.OPEN.play(player); + player.closeInventory(); + } else { super.handleClick(info); - return; } - SoundSample.OPEN.play(info.getPlayer()); - info.getPlayer().closeInventory(); } }; } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistView.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistView.java new file mode 100644 index 000000000..0d60b10e7 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistView.java @@ -0,0 +1,66 @@ +package net.cyperia.challenges.plugin.management.menu.generator.impl.goal; + +import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistEntry; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Comparator; +import java.util.List; +import java.util.UUID; +import java.util.function.Function; + +record GoalChecklistView(@NotNull Filter filter, @NotNull Sort sort, boolean descending) { + + static final GoalChecklistView DEFAULT = new GoalChecklistView(Filter.ALL, Sort.DEFAULT, false); + + enum Filter { + ALL, MISSING, FOUND; + + @NotNull + Filter next() { + return values()[(ordinal() + 1) % values().length]; + } + } + + enum Sort { + DEFAULT, TIME, FINDER; + + @NotNull + Sort next() { + return values()[(ordinal() + 1) % values().length]; + } + } + + /** + * @param names name of a finder, {@code null} if unknown + */ + @NotNull + List apply(@NotNull List entries, @NotNull Function names) { + // Entries without a time or finder stay at the end in both directions + Comparator order = switch (sort) { + // stable, so each goal's own order holds within missing and done + case DEFAULT -> descending ? Comparator.comparing(ChecklistEntry::done).reversed() : Comparator.comparing(ChecklistEntry::done); + case TIME -> Comparator.comparing(ChecklistEntry::foundAt, Comparator.nullsLast(direction(Comparator.naturalOrder()))); + case FINDER -> Comparator.comparing(entry -> firstFinder(entry, names), Comparator.nullsLast(direction(String.CASE_INSENSITIVE_ORDER))); + }; + return entries.stream() + .filter(entry -> switch (filter) { + case ALL -> true; + case MISSING -> !entry.done(); + case FOUND -> entry.done(); + }) + .sorted(order) + .toList(); + } + + @NotNull + private Comparator direction(@NotNull Comparator ascending) { + return descending ? ascending.reversed() : ascending; + } + + @Nullable + private static String firstFinder(@NotNull ChecklistEntry entry, @NotNull Function names) { + return entry.finders().stream().map(names).filter(name -> name != null).min(String.CASE_INSENSITIVE_ORDER).orElse(null); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/randomizer/RandomizerMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/randomizer/RandomizerMenuGenerator.java index e1e3ea6f8..7c60cf685 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/randomizer/RandomizerMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/randomizer/RandomizerMenuGenerator.java @@ -4,7 +4,7 @@ import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; import net.cyperia.challenges.plugin.management.menu.SettingCategory; import net.cyperia.challenges.plugin.management.menu.format.Interaction; -import net.cyperia.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; +import net.cyperia.challenges.plugin.management.menu.generator.MultiPageSelectMenuGenerator; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; import org.bukkit.inventory.ItemStack; @@ -12,7 +12,7 @@ import java.util.Locale; -public class RandomizerMenuGenerator extends UncachedMultiPageSelectMenuGenerator { +public class RandomizerMenuGenerator extends MultiPageSelectMenuGenerator { private static final int SIZE = 3 * 9; private static final int[] SLOTS = calcSlots(1, 7, SIZE); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/randomizer/RandomizerPairingsMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/randomizer/RandomizerPairingsMenuGenerator.java index 36d063e26..dcba2fdf2 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/randomizer/RandomizerPairingsMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/randomizer/RandomizerPairingsMenuGenerator.java @@ -6,7 +6,7 @@ import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.management.menu.SettingCategory; import net.cyperia.challenges.plugin.management.menu.format.ItemFormatter; -import net.cyperia.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; +import net.cyperia.challenges.plugin.management.menu.generator.MultiPageSelectMenuGenerator; import net.cyperia.challenges.plugin.management.menu.generator.impl.randomizer.RandomizerPairingsMenuGenerator.Entry; import net.cyperia.commons.bukkit.utils.item.ItemUtils; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; @@ -15,7 +15,7 @@ import java.util.Locale; -public class RandomizerPairingsMenuGenerator extends UncachedMultiPageSelectMenuGenerator { +public class RandomizerPairingsMenuGenerator extends MultiPageSelectMenuGenerator { private static final int SIZE = 6 * 9; private static final int[] SLOTS = calcSlots(4, 7, SIZE); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/search/SearchDialogMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/search/SearchDialogMenuGenerator.java index 2cd0c7fc1..526d13e83 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/search/SearchDialogMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/search/SearchDialogMenuGenerator.java @@ -74,13 +74,13 @@ protected String createDefaultState(@NotNull Player player) { } @Override - protected void setupDialog(@NotNull DialogRegistryEntry.Builder dialog, @NotNull String query, @NotNull Locale locale) { + protected void setupDialog(@NotNull DialogRegistryEntry.Builder dialog, @NotNull String query, @NotNull Player viewer, @NotNull Locale locale) { query = query.trim(); // the state may come from outside the dialog (e.g. /search ), where nothing enforces the // limit of the input field; an initial value longer than maxLength fails to serialize if (query.length() > MAX_INPUT_LENGTH) query = query.substring(0, MAX_INPUT_LENGTH); - List matches = findResults(query, locale); + List matches = findResults(query, viewer, locale); List results = matches.stream().limit(RESULT_LIMIT).toList(); // search button first -> it lands in the first grid cell, directly under the input @@ -204,7 +204,7 @@ private ActionButton buildResultButton(@NotNull SearchFindable findable, @NotNul if (!(audience instanceof Player player)) return; // results outlive the search that built them, so a findable that hid itself since then is // not opened; the query is run again instead, which rebuilds the dialog without it - if (!findable.isVisible()) { + if (!findable.isVisibleTo(player)) { SoundSample.BASS_OFF.play(player); openMenu(player, query); return; @@ -220,9 +220,9 @@ private ActionButton buildResultButton(@NotNull SearchFindable findable, @NotNul * so a short query never dumps the whole challenge list. */ @NotNull - private List findResults(@NotNull String query, @NotNull Locale locale) { + private List findResults(@NotNull String query, @NotNull Player viewer, @NotNull Locale locale) { if (query.length() < MIN_QUERY_LENGTH) return List.of(); - return Challenges.getInstance().getSearchRegistry().search(query, locale); + return Challenges.getInstance().getSearchRegistry().search(query, viewer, locale); } @RequiredArgsConstructor diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/search/SearchResultHighlightMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/search/SearchResultHighlightMenuGenerator.java index 3c7f287c3..033abb8c3 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/search/SearchResultHighlightMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/search/SearchResultHighlightMenuGenerator.java @@ -1,7 +1,7 @@ package net.cyperia.challenges.plugin.management.menu.generator.impl.search; +import io.papermc.paper.threadedregions.scheduler.ScheduledTask; import net.cyperia.challenges.plugin.Challenges; -import net.cyperia.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.cyperia.challenges.plugin.management.menu.generator.AbstractMenuGenerator; import net.cyperia.challenges.plugin.management.menu.generator.MultiPageMenuGenerator; import net.cyperia.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; @@ -9,17 +9,15 @@ import net.cyperia.commons.bukkit.utils.item.ItemBuilder; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.cyperia.commons.bukkit.utils.menu.MenuPosition; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.kyori.adventure.text.Component; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Locale; import java.util.Set; /** @@ -43,9 +41,10 @@ public class SearchResultHighlightMenuGenerator extends AbstractMenuGenerator { private int durationCounter; private boolean flashPresent; + private Player viewer; private Inventory parentInventory; private Inventory viewInventory; - private BukkitTask updateTask; + private volatile ScheduledTask updateTask; /** * @param parentPage the page the result is displayed on @@ -70,46 +69,35 @@ public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player @NotNull @Override - public Inventory getOrInitInventory(@NotNull Locale locale, int page) { + public Inventory createInventory(@NotNull Player viewer, int page) { if (viewInventory != null && parentInventory != null) return viewInventory; - - parentInventory = parentGenerator.getOrInitInventory(locale, page); - viewInventory = parentGenerator.createEmptyInventory(locale, page); // copied title + this.viewer = viewer; + parentInventory = parentGenerator.createInventory(viewer, page); + viewInventory = parentGenerator.createEmptyInventory(viewer, page); // copied title copyContents(parentInventory, viewInventory); startUpdateTask(); - return viewInventory; } @Override - public int getInventorySize() { - return parentGenerator.getInventorySize(); - } - - @Override - public void updateOrGeneratePages(@NotNull Locale locale) { - // noop - } - - @Override - public void updatePages() { - // noop + public void renderPage(@NotNull Inventory inventory, int page, @NotNull Player viewer) { + updateFlashContents(); } @Override - public void updatePage(int page) { - // noop + public int getInventorySize() { + return parentGenerator.getInventorySize(); } @Override - public int getPageCount() { - return parentGenerator.getPageCount(); + public int getPageCount(@NotNull Player viewer) { + return parentGenerator.getPageCount(viewer); } private void startUpdateTask() { if (updateTask != null) return; durationCounter = 0; - updateTask = Bukkit.getScheduler().runTaskTimerAsynchronously(Challenges.getInstance(), this::updateViewCounter, 1, UPDATE_INTERVAL); + updateTask = Regions.timer(Challenges.getInstance(), viewer, _ -> updateViewCounter(), 1, UPDATE_INTERVAL); } private void updateViewCounter() { @@ -123,7 +111,7 @@ private void updateViewCounter() { if (durationCounter >= MAX_HIGHLIGHT_DURATION) { kill(); - ChallengeHelper.runSync(this::restoreParentMenu); + restoreParentMenu(); return; } @@ -142,8 +130,10 @@ private void restoreParentMenu() { } } + // The viewer's position is this highlight, so the parent never updates its copy itself; it is drawn again every flash private void updateFlashContents() { if (parentInventory == null || viewInventory == null) return; + parentGenerator.renderPage(parentInventory, parentPage, viewer); copyContents(parentInventory, viewInventory); if (flashPresent) { @@ -177,6 +167,7 @@ private void kill() { viewInventory = null; parentInventory = null; + viewer = null; } private void copyContents(@NotNull Inventory parentInventory, @NotNull Inventory viewInventory) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/timer/TimerTimeMenuGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/timer/TimerTimeMenuGenerator.java index 8bfb50846..df20e01a6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/timer/TimerTimeMenuGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/generator/impl/timer/TimerTimeMenuGenerator.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.management.menu.generator.impl.timer; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.content.i18n.ArgumentFormat; import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; import net.cyperia.challenges.plugin.content.i18n.MessageKey; @@ -11,6 +12,7 @@ import net.cyperia.commons.bukkit.utils.animation.SoundSample; import net.cyperia.commons.bukkit.utils.menu.MenuClickInfo; import net.cyperia.commons.bukkit.utils.menu.MenuClickType; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -105,7 +107,10 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { SoundSample.PLOP.play(info.getPlayer()); } - updatePages(); // the clicker should not have to wait for the periodic refresh + // The timer changes on the global region, so the refresh queues up behind that change there, + // and the clicker should not have to wait for the periodic refresh + Player clicker = info.getPlayer(); + Regions.global(Challenges.getInstance(), () -> Regions.entity(Challenges.getInstance(), clicker, () -> updatePages())); return true; } return false; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/search/SearchFindable.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/search/SearchFindable.java index fba00d0c3..524854bed 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/search/SearchFindable.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/search/SearchFindable.java @@ -61,6 +61,13 @@ default boolean isVisible() { return true; } + /** + * @return whether this findable is offered to this player; the same constraints as {@link #isVisible()} apply + */ + default boolean isVisibleTo(@NotNull Player viewer) { + return isVisible(); + } + @NotNull default LocalizableMessage getFindableInteraction() { return Interaction.SEARCH_SELECT; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/search/SearchRegistry.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/search/SearchRegistry.java index f817f939f..88dbbe159 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/search/SearchRegistry.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/menu/search/SearchRegistry.java @@ -4,6 +4,7 @@ import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.TranslationManager; import net.cyperia.challenges.plugin.content.i18n.impl.format.ComponentFormatter; +import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -19,7 +20,7 @@ * and how well; this class decides what is searched and how the hits are ordered. * *

Visibility

- * A findable stays registered for its whole lifetime, but {@link SearchFindable#isVisible()} may flip + * A findable stays registered for its whole lifetime, but {@link SearchFindable#isVisibleTo(org.bukkit.entity.Player)} may flip * at any point, so it is asked once per search rather than cached anywhere. * *

Ranking

@@ -78,13 +79,13 @@ public synchronized void registerAll(@NotNull SearchFindable... findable) { * them to show and may use the full size as the hit count. */ @NotNull - public synchronized List search(@NotNull String query, @NotNull Locale locale) { + public synchronized List search(@NotNull String query, @NotNull Player viewer, @NotNull Locale locale) { SearchQuery searchQuery = new SearchQuery(query); if (searchQuery.isEmpty() || findables.isEmpty()) return List.of(); SearchFindable[] entries = snapshot(); long[] hits = new long[entries.length]; - boolean[] skipped = hidden(entries); + boolean[] skipped = hidden(entries, viewer); Locale playerLocale = TranslationManager.normalizeLocale(locale); int count = collect(searchQuery, playerLocale, entries, hits, skipped, 0, true); @@ -149,10 +150,10 @@ private int collect(@NotNull SearchQuery query, @NotNull Locale locale, @NotNull * @return which findables this search leaves out, indexed like {@code entries} */ @NotNull - private static boolean[] hidden(@NotNull SearchFindable[] entries) { + private static boolean[] hidden(@NotNull SearchFindable[] entries, @NotNull Player viewer) { boolean[] hidden = new boolean[entries.length]; for (int i = 0; i < entries.length; i++) { - hidden[i] = !entries[i].isVisible(); + hidden[i] = !entries[i].isVisibleTo(viewer); } return hidden; } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/AbstractTaskExecutor.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/AbstractTaskExecutor.java index f9eb4b042..fc6e2bffa 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/AbstractTaskExecutor.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/AbstractTaskExecutor.java @@ -4,12 +4,13 @@ import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; public abstract class AbstractTaskExecutor implements Runnable { - protected final List functions = new ArrayList<>(1); + // registered from any thread while the executor's own thread iterates + protected final List functions = new CopyOnWriteArrayList<>(); @Override public void run() { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/ScheduleManager.java index 968840a62..ef9c387de 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/ScheduleManager.java @@ -5,6 +5,7 @@ import net.cyperia.challenges.plugin.management.scheduler.task.TimerTask; import net.cyperia.commons.bukkit.utils.logging.Logger; import net.cyperia.commons.common.misc.ReflectionUtils; +import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Method; @@ -13,9 +14,14 @@ public final class ScheduleManager { + private final Plugin plugin; private final Map scheduledTaskExecutorsByConfig = new ConcurrentHashMap<>(); private final Map timerTaskExecutorsByConfig = new ConcurrentHashMap<>(); - private boolean started = false; + private volatile boolean started = false; + + public ScheduleManager(@NotNull Plugin plugin) { + this.plugin = plugin; + } public void register(@NotNull Object... schedulers) { for (Object scheduler : schedulers) { @@ -78,7 +84,7 @@ private ScheduledTaskExecutor getOrCreateScheduledTaskExecutor(@NotNull Schedule if (executor != null) return executor; // Create a new task - executor = new ScheduledTaskExecutor(config); + executor = new ScheduledTaskExecutor(plugin, config); if (started) executor.start(); scheduledTaskExecutorsByConfig.put(config, executor); return executor; @@ -90,7 +96,7 @@ private TimerTaskExecutor getOrCreateTimerTaskExecutor(@NotNull TimerTaskConfig if (executor != null) return executor; // Create a new task - executor = new TimerTaskExecutor(config); + executor = new TimerTaskExecutor(plugin, config); timerTaskExecutorsByConfig.put(config, executor); return executor; } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java index 96aecbfb9..0cbf83ee9 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java @@ -1,32 +1,35 @@ package net.cyperia.challenges.plugin.management.scheduler; -import net.cyperia.challenges.plugin.Challenges; -import org.bukkit.Bukkit; -import org.bukkit.scheduler.BukkitScheduler; -import org.bukkit.scheduler.BukkitTask; +import io.papermc.paper.threadedregions.scheduler.ScheduledTask; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; +// A sync executor ticks on the global region and an async one on the async scheduler. Handlers that +// work on players or blocks hop to the owning thread themselves. final class ScheduledTaskExecutor extends AbstractTaskExecutor { + private final Plugin plugin; private final ScheduledTaskConfig config; - private BukkitTask task; + private volatile ScheduledTask task; - ScheduledTaskExecutor(@NotNull ScheduledTaskConfig config) { + ScheduledTaskExecutor(@NotNull Plugin plugin, @NotNull ScheduledTaskConfig config) { + this.plugin = plugin; this.config = config; } public void stop() { - if (task != null && !task.isCancelled()) { - task.cancel(); + ScheduledTask running = task; + if (running != null && !running.isCancelled()) { + running.cancel(); task = null; } } public void start() { - BukkitScheduler scheduler = Bukkit.getScheduler(); - Challenges plugin = Challenges.getInstance(); - task = config.isAsync() ? scheduler.runTaskTimerAsynchronously(plugin, this, 0, config.getRate()) : - scheduler.runTaskTimer(plugin, this, 0, config.getRate()); + task = config.isAsync() + ? Regions.asyncTimer(plugin, _ -> run(), 1, config.getRate()) + : Regions.timer(plugin, _ -> run(), 1, config.getRate()); } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/TimerTaskExecutor.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/TimerTaskExecutor.java index 1822f0c1b..b3d8d1002 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/TimerTaskExecutor.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/TimerTaskExecutor.java @@ -1,23 +1,23 @@ package net.cyperia.challenges.plugin.management.scheduler; -import net.cyperia.challenges.plugin.Challenges; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; final class TimerTaskExecutor extends AbstractTaskExecutor { + private final Plugin plugin; private final TimerTaskConfig config; - TimerTaskExecutor(@NotNull TimerTaskConfig config) { + TimerTaskExecutor(@NotNull Plugin plugin, @NotNull TimerTaskConfig config) { + this.plugin = plugin; this.config = config; } + // Sync handlers run on the global region, inline when the caller already is on it public void execute() { - if (config.isAsync()) - Bukkit.getScheduler().runTaskAsynchronously(Challenges.getInstance(), this); - else if (!Bukkit.isPrimaryThread()) - Bukkit.getScheduler().runTask(Challenges.getInstance(), this); - else this.run(); + if (config.isAsync()) Regions.async(plugin, this); + else Regions.global(plugin, this); } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index ceb55b9b2..12243c7d4 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -17,6 +17,7 @@ import net.cyperia.challenges.plugin.management.server.ChallengeEndCause; import net.cyperia.challenges.plugin.management.server.scoreboard.ChallengeActionBar; import net.cyperia.commons.bukkit.utils.animation.SoundSample; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import net.cyperia.commons.common.config.FileDocument; import net.kyori.adventure.text.Component; @@ -43,22 +44,23 @@ public final class ChallengeTimer { private TimerActionBarUpdateScheduler updateActionbarScheduler; private Object pausedParticleScheduler; + // Changed on the global region, read from every region @Getter - private boolean playPausedParticled; + private volatile boolean playPausedParticled; @Getter - private long time = 0; + private volatile long time = 0; @Getter - private int countdown; + private volatile int countdown; @Getter - private int initialCountdown; + private volatile int initialCountdown; @Getter - private boolean countdownRunning = false; + private volatile boolean countdownRunning = false; @Getter - private boolean countingUp = true; + private volatile boolean countingUp = true; @Getter - private boolean paused = true; + private volatile boolean paused = true; @Getter - private boolean hidden = false; + private volatile boolean hidden = false; public ChallengeTimer() { Document pluginConfig = Challenges.getInstance().getConfigDocument(); @@ -93,9 +95,11 @@ public void setUpdateActionbarScheduler(@NotNull TimerActionBarUpdateScheduler u } public void setPlayPausedParticled(boolean play) { - if (this.playPausedParticled == play) return; - setPlayPausedParticleScheduler(pausedParticleScheduler); - this.playPausedParticled = play; + onGlobal(() -> { + if (this.playPausedParticled == play) return; + setPlayPausedParticleScheduler(pausedParticleScheduler); + this.playPausedParticled = play; + }); } public void setPlayPausedParticleScheduler(@Nullable Object pausedParticleScheduler) { @@ -131,9 +135,15 @@ public void enable() { // A paused world stands still, so a server waiting in a pool neither turns to night nor starts raining public void applyPauseRules(@NotNull World world) { - // overhaul post-1.21: DO_DAYLIGHT_CYCLE -> ADVANCE_TIME - world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !paused); - world.setGameRule(GameRule.DO_WEATHER_CYCLE, !paused); + Regions.global(Challenges.getInstance(), () -> { + // overhaul post-1.21: DO_DAYLIGHT_CYCLE -> ADVANCE_TIME + world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !paused); + world.setGameRule(GameRule.DO_WEATHER_CYCLE, !paused); + }); + } + + private static void onGlobal(@NotNull Runnable task) { + Regions.global(Challenges.getInstance(), task); } private void updatePauseRules() { @@ -187,64 +197,71 @@ private void handleHitZero() { } public void resume() { - if (!paused) return; - paused = false; - countdownRunning = false; - - updateActionbar(); - updatePauseRules(); - - MessageKey.of("timer.messages.started").broadcast(Prefix.TIMER); - Challenges.getInstance().getScheduler().fireTimerStatusChange(); - Challenges.getInstance().getTitleManager().sendTimerStatusTitle(MessageKey.of("title.timer-started")); - Challenges.getInstance().getServerManager().setNotFresh(); - Challenges.getInstance().getAutoResetManager().handleTimerStart(); - - // Spectators are explicitly included: whoever died in the previous run is a spectator now and has - // to be able to play again. Creative is exempt because it is how the server is set up, not how a - // run is played, and vanished players are not part of the run at all. - for (Player player : Challenges.getInstance().getPlayerManager().getPlayers()) { - if (player.getGameMode() == GameMode.CREATIVE) continue; - player.setGameMode(GameMode.SURVIVAL); - } - - IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); - if (currentGoal != null && specificStartSounds) { - currentGoal.getStartSound().broadcast(); - } else if (defaultStartSound) { - SoundSample.DRAGON_BREATH.broadcast(); - } + onGlobal(() -> { + if (!paused) return; + paused = false; + countdownRunning = false; + updateActionbar(); + updatePauseRules(); + + MessageKey.of("timer.messages.started").broadcast(Prefix.TIMER); + Challenges.getInstance().getScheduler().fireTimerStatusChange(); + Challenges.getInstance().getTitleManager().sendTimerStatusTitle(MessageKey.of("title.timer-started")); + Challenges.getInstance().getServerManager().setNotFresh(); + Challenges.getInstance().getAutoResetManager().handleTimerStart(); + + // Spectators are explicitly included: whoever died in the previous run is a spectator now and has + // to be able to play again. Creative is exempt because it is how the server is set up, not how a + // run is played, and vanished players are not part of the run at all. + Challenges.getInstance().getPlayerManager().forEachOnOwnThread(Challenges.getInstance().getPlayerManager().getPlayers(), player -> { + if (player.getGameMode() == GameMode.CREATIVE) return; + player.setGameMode(GameMode.SURVIVAL); + }); + + IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); + if (currentGoal != null && specificStartSounds) { + currentGoal.getStartSound().broadcast(); + } else if (defaultStartSound) { + SoundSample.DRAGON_BREATH.broadcast(); + } + }); } public void pause(boolean playInGameEffects) { - if (paused) return; - paused = true; - - updateActionbar(); - updatePauseRules(); - - Challenges.getInstance().getScheduler().fireTimerStatusChange(); - if (playInGameEffects) { - Challenges.getInstance().getTitleManager().sendTimerStatusTitle(MessageKey.of("title.timer-paused")); - MessageKey.of("timer.messages.paused").broadcast(Prefix.TIMER); - SoundSample.BASS_OFF.broadcast(); - } + onGlobal(() -> { + if (paused) return; + paused = true; + + updateActionbar(); + updatePauseRules(); + + Challenges.getInstance().getScheduler().fireTimerStatusChange(); + if (playInGameEffects) { + Challenges.getInstance().getTitleManager().sendTimerStatusTitle(MessageKey.of("title.timer-paused")); + MessageKey.of("timer.messages.paused").broadcast(Prefix.TIMER); + SoundSample.BASS_OFF.broadcast(); + } + }); } public void toggle() { - if (isStarted()) { - pause(true); - } else { - resume(); - } + onGlobal(() -> { + if (isStarted()) { + pause(true); + } else { + resume(); + } + }); } public void reset() { - if (!countingUp) pause(true); - time = 0; - countingUp = true; - updateActionbar(); + onGlobal(() -> { + if (!countingUp) pause(true); + time = 0; + countingUp = true; + updateActionbar(); + }); } @NotNull @@ -278,62 +295,74 @@ public synchronized void saveSession(boolean async) { } public void addSeconds(int amount) { - setSeconds(time + amount); + onGlobal(() -> setSeconds(time + amount)); } public void setSeconds(long seconds) { - this.time = Math.max(seconds, 0); - updateActionbar(); + onGlobal(() -> { + this.time = Math.max(seconds, 0); + updateActionbar(); + }); } public void addCountdownSeconds(int amount) { - setCountdown(countdown + amount); + onGlobal(() -> setCountdown(countdown + amount)); } public void setCountdown(int seconds) { - this.countdown = Math.max(seconds, 0); - this.initialCountdown = this.countdown; - updateActionbar(); + onGlobal(() -> { + this.countdown = Math.max(seconds, 0); + this.initialCountdown = this.countdown; + updateActionbar(); + }); } public void resumeCountdown() { - if (!paused || countdownRunning) return; - countdownRunning = true; - updateActionbar(); + onGlobal(() -> { + if (!paused || countdownRunning) return; + countdownRunning = true; + updateActionbar(); - Challenges.getInstance().getScheduler().fireTimerStatusChange(); + Challenges.getInstance().getScheduler().fireTimerStatusChange(); - MessageKey.of("timer.messages.countdown.started").broadcast(Prefix.TIMER, ArgumentFormat.TIME.apply(countdown)); - SoundSample.PLING.broadcast(); + MessageKey.of("timer.messages.countdown.started").broadcast(Prefix.TIMER, ArgumentFormat.TIME.apply(countdown)); + SoundSample.PLING.broadcast(); + }); } public void pauseCountdown() { - if (!countdownRunning) return; - countdownRunning = false; + onGlobal(() -> { + if (!countdownRunning) return; + countdownRunning = false; - updateActionbar(); + updateActionbar(); - Challenges.getInstance().getScheduler().fireTimerStatusChange(); + Challenges.getInstance().getScheduler().fireTimerStatusChange(); - MessageKey.of("timer.messages.countdown.paused").broadcast(Prefix.TIMER); - SoundSample.BASS_OFF.broadcast(); + MessageKey.of("timer.messages.countdown.paused").broadcast(Prefix.TIMER); + SoundSample.BASS_OFF.broadcast(); + }); } public void toggleCountdown() { - if (countdownRunning) { - pauseCountdown(); - } else { - resumeCountdown(); - } + onGlobal(() -> { + if (countdownRunning) { + pauseCountdown(); + } else { + resumeCountdown(); + } + }); } public void setHidden(boolean hide) { - if (this.hidden == hide) return; + onGlobal(() -> { + if (this.hidden == hide) return; - this.hidden = hide; - updateActionbar(); - MessageKey.of("timer.messages." + (hide ? "hidden" : "shown")).broadcast(Prefix.TIMER); - SoundSample.BASS_ON.broadcast(); + this.hidden = hide; + updateActionbar(); + MessageKey.of("timer.messages." + (hide ? "hidden" : "shown")).broadcast(Prefix.TIMER); + SoundSample.BASS_ON.broadcast(); + }); } @NotNull @@ -366,29 +395,34 @@ public boolean isStarted() { } public void setCountingUp(boolean countingUp) { - if (this.countingUp == countingUp) return; + onGlobal(() -> { + if (this.countingUp == countingUp) return; - this.countingUp = countingUp; - updateActionbar(); - MessageKey.of("timer.messages.counting-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); // TODO - SoundSample.BASS_ON.broadcast(); + this.countingUp = countingUp; + updateActionbar(); + MessageKey.of("timer.messages.counting-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); // TODO + SoundSample.BASS_ON.broadcast(); + }); } public float getCountdownProgress() { - if (!countdownRunning || countdown > initialCountdown - 1) return 0; - if (initialCountdown <= 0) return 0; - return 1f - (float) countdown / initialCountdown; + // Both are read once, they change on another thread + int remaining = countdown; + int initial = initialCountdown; + if (!countdownRunning || remaining > initial - 1) return 0; + if (initial <= 0) return 0; + return 1f - (float) remaining / initial; } public static class PausedParticleScheduler { - @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.PAUSED) + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.PAUSED) public void playPausedParticles() { - for (Player player : ChallengeAPI.getIngamePlayers()) { + Challenges.getInstance().getPlayerManager().forEachChallengePlayer(player -> { Location location = player.getLocation(); - if (location.getWorld() == null) continue; + if (location.getWorld() == null) return; location.getWorld().playEffect(location, Effect.ENDER_SIGNAL, 1); - } + }); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/AutoResetManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/AutoResetManager.java index a9bfa78e7..acf09db29 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/AutoResetManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/AutoResetManager.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.management.server; +import io.papermc.paper.threadedregions.scheduler.ScheduledTask; import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.abstraction.AbstractChallenge; @@ -7,6 +8,7 @@ import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.management.files.ConfigManager; import net.cyperia.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.GameMode; @@ -16,7 +18,6 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; import java.util.HashSet; @@ -48,7 +49,7 @@ public final class AutoResetManager implements Listener { private static final Set COUNTDOWN_ANNOUNCED_AT = Set.of(120, 60, 30, 10, 5, 3, 2, 1); - private BukkitTask pendingReset; + private volatile ScheduledTask pendingReset; private boolean cancelPendingResetOnJoin; private int secondsUntilReset; @@ -148,8 +149,7 @@ private void startEmptyCountdown() { cancelPendingReset(); cancelPendingResetOnJoin = true; secondsUntilReset = afterEmptySeconds; - pendingReset = Bukkit.getScheduler().runTaskTimer(Challenges.getInstance(), - this::countDownToReset, 20L, 20L); + pendingReset = Regions.timer(Challenges.getInstance(), _ -> countDownToReset(), 20L, 20L); } private void countDownToReset() { @@ -206,7 +206,7 @@ public void handleChallengeEnd(@NotNull ChallengeEndCause endCause) { private void scheduleReset(int seconds) { cancelPendingReset(); cancelPendingResetOnJoin = false; - pendingReset = Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), + pendingReset = Regions.later(Challenges.getInstance(), () -> Challenges.getInstance().getWorldManager().prepareWorldReset(Bukkit.getConsoleSender()), seconds * 20L); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java index 614739c3f..8777a8c19 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/BorderManager.java @@ -8,6 +8,8 @@ import net.cyperia.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.cyperia.challenges.plugin.management.scheduler.task.ScheduledTask; import net.cyperia.challenges.plugin.management.server.scoreboard.ChallengeBossBar; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnedEvent; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import net.cyperia.commons.common.config.document.GsonDocument; import org.bukkit.Bukkit; @@ -25,14 +27,14 @@ import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; /** * The one world border every challenge shares. @@ -51,17 +53,17 @@ public final class BorderManager implements GamestateSaveable, Listener { private static final double MIN_SIZE = 1; private static final double START_SIZE = 1; - private final Map apiBorders = new HashMap<>(); - private final Map centers = new HashMap<>(); + private final Map apiBorders = new ConcurrentHashMap<>(); + private final Map centers = new ConcurrentHashMap<>(); // Players a challenge has given a border of their own. The shared border leaves them alone until it // is handed back, so a challenge that traps somebody is not undone by one that shrinks the border. - private final Map overrides = new HashMap<>(); + private final Map overrides = new ConcurrentHashMap<>(); // How far each challenge whose border starts small has grown it, by unique challenge name. Not saved: // each of them restores its own on load, and a reset loads this manager after the challenges. - private final Map growth = new HashMap<>(); - private double offset; + private final Map growth = new ConcurrentHashMap<>(); + private volatile double offset; // One bar for every challenge that drives the border, so two of them never stack two bars private final ChallengeBossBar bossbar = new ChallengeBossBar(); @@ -174,8 +176,8 @@ public void teleportInside(@NotNull Player player) { location.setX(Math.clamp(location.getX(), center.getX() - radius + margin, center.getX() + radius - margin)); location.setZ(Math.clamp(location.getZ(), center.getZ() - radius + margin, center.getZ() + radius - margin)); Location spot = standingSpot(location); - player.teleport(spot != null ? spot : surface(center, player.getWorld())); player.setFallDistance(0); + player.teleportAsync(spot != null ? spot : surface(center, player.getWorld())); } @NotNull @@ -275,7 +277,7 @@ private void updateBossBar() { @EventHandler(priority = EventPriority.MONITOR) public void onJoin(@NotNull PlayerJoinEvent event) { // the server sends the world's own border again after the join event, over whatever was sent during it - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> sendTo(event.getPlayer())); + Regions.nextTick(Challenges.getInstance(), event.getPlayer(), () -> sendTo(event.getPlayer())); contain(event.getPlayer()); } @@ -292,9 +294,9 @@ public void onWorldChange(@NotNull PlayerChangedWorldEvent event) { } @EventHandler(priority = EventPriority.MONITOR) - public void onRespawn(@NotNull PlayerRespawnEvent event) { + public void onRespawn(@NotNull PlayerRespawnedEvent event) { // the client drops its border on respawn, so it has to be told again - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Regions.nextTick(Challenges.getInstance(), event.getPlayer(), () -> { sendTo(event.getPlayer()); // a bed refuses a respawn outside the border, the random spawn around the world spawn does not contain(event.getPlayer()); @@ -326,9 +328,7 @@ public void onDamageAcrossBorder(@NotNull EntityDamageByEntityEvent event) { // Before the start too: a new player spawns scattered around the world spawn, outside a small border @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS) public void containPlayers() { - for (Player player : Bukkit.getOnlinePlayers()) { - contain(player); - } + Challenges.getInstance().getPlayerManager().forEachAudience(this::contain); } private void contain(@NotNull Player player) { @@ -340,14 +340,20 @@ private void contain(@NotNull Player player) { private void updateBorder(@NotNull World world, boolean animate) { if (!isActive()) { - world.getPlayers().forEach(this::resetFor); + forEachPlayerIn(world, this::resetFor); return; } // apply once for the whole world: re-applying per player would overwrite the animated transition // with an instant resize before anyone is told about it applyTo(world, animate); - world.getPlayers().forEach(this::bind); + forEachPlayerIn(world, this::bind); + } + + private void forEachPlayerIn(@NotNull World world, @NotNull Consumer action) { + Challenges.getInstance().getPlayerManager().forEachAudience(player -> { + if (player.getWorld() == world) action.accept(player); + }); } /** diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/GameWorldStorage.java index 5e6cd1031..ac15722bd 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/GameWorldStorage.java @@ -7,7 +7,6 @@ import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.WorldCreator; -import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -113,13 +112,13 @@ private static void copyGameRule(@NotNull GameRule rule, @NotNull World f } private void moveOutOfFormerGameWorlds(@NotNull List previousGameWorlds) { - for (Player player : Bukkit.getOnlinePlayers()) { + Challenges.getInstance().getPlayerManager().forEachAudience(player -> { World world = player.getWorld(); - if (!previousGameWorlds.contains(world) || gameWorlds.contains(world)) continue; + if (!previousGameWorlds.contains(world) || gameWorlds.contains(world)) return; World target = getWorld(world.getEnvironment()); - if (target != null) player.teleport(BlockUtils.getCenteredSpawn(target)); - } + if (target != null) player.teleportAsync(BlockUtils.getCenteredSpawn(target)); + }); } @NotNull diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/PlayerManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/PlayerManager.java index 3a9b4ef3c..ff0144ca5 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/PlayerManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/PlayerManager.java @@ -10,6 +10,7 @@ import net.cyperia.challenges.plugin.management.server.player.PlayerVisibilityProvider; import net.cyperia.challenges.plugin.management.server.player.ServerPlayerNameProvider; import net.cyperia.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.GameMode; @@ -127,22 +128,29 @@ public boolean isVanished(@NotNull Player player) { return visibilityProvider.isPlayerVanished(player); } + // The action runs on each player's own thread, inline on a server without regions public void forEachAudience(@NotNull Consumer action) { - getAudience().forEach(action); + forEachOnOwnThread(getAudience(), action); } public void forEachChallengePlayer(@NotNull Consumer action) { - getChallengePlayers().forEach(action); + forEachOnOwnThread(getChallengePlayers(), action); } public void forEachIgnoredPlayer(@NotNull Consumer action) { for (Player player : getAudience()) { if (isIgnored(player)) { - action.accept(player); + Regions.entity(Challenges.getInstance(), player, () -> action.accept(player)); } } } + public void forEachOnOwnThread(@NotNull Collection players, @NotNull Consumer action) { + for (Player player : players) { + Regions.entity(Challenges.getInstance(), player, () -> action.accept(player)); + } + } + /** * @param challengePlayersOnly whether to drop the players ignored by {@code ignore-players} as well * @implNote Built fresh, deliberately not cached per tick. Both halves of the filter are a field read diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/ScoreboardManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/ScoreboardManager.java index 872df7407..973a6fc50 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/ScoreboardManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/ScoreboardManager.java @@ -10,19 +10,20 @@ import net.cyperia.challenges.plugin.management.server.scoreboard.ChallengeActionBar; import net.cyperia.challenges.plugin.management.server.scoreboard.ChallengeBossBar; import net.cyperia.challenges.plugin.management.server.scoreboard.ChallengeScoreboard; -import org.bukkit.Bukkit; +import net.cyperia.challenges.plugin.management.server.scoreboard.PlayerScoreboards; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; public final class ScoreboardManager { - private final List bossbars = new ArrayList<>(); - private ChallengeScoreboard currentScoreboard; - private ChallengeActionBar currentActionBar; + private final List bossbars = new CopyOnWriteArrayList<>(); + private volatile ChallengeScoreboard currentScoreboard; + private volatile ChallengeActionBar currentActionBar; public ScoreboardManager() { ChallengeAPI.subscribeLoader(LanguageLoader.class, this::updateAll); @@ -35,8 +36,9 @@ public void handleQuit(@NotNull Player player) { } if (currentScoreboard != null) { currentScoreboard.applyHide(player); - Bukkit.getScheduler().runTaskLaterAsynchronously(Challenges.getInstance(), () -> currentScoreboard.update(), 1); + Regions.later(Challenges.getInstance(), () -> currentScoreboard.update(), 1); } + PlayerScoreboards.forget(player); } public void handleJoin(@NotNull Player player) { @@ -44,7 +46,7 @@ public void handleJoin(@NotNull Player player) { } @ScheduledTask(timerPolicy = TimerPolicy.COUNTDOWN, ticks = 20, async = false) - @TimerTask(status = {TimerStatus.RUNNING, TimerStatus.PAUSED, TimerStatus.COUNTDOWN}) + @TimerTask(status = {TimerStatus.RUNNING, TimerStatus.PAUSED, TimerStatus.COUNTDOWN}, async = false) public void updateAll() { for (ChallengeBossBar bossbar : bossbars) { bossbar.update(); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/ServerManager.java index 576370b77..f5acb587f 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/ServerManager.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.management.server; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.entity.EntityType; import net.cyperia.challenges.plugin.ChallengeAPI; import net.cyperia.challenges.plugin.Challenges; @@ -63,14 +64,10 @@ public boolean hasCheated() { } public void endChallenge(@NotNull ChallengeEndCause endCause, Supplier> winnerGetter) { - if (!Bukkit.isPrimaryThread()) { - // calling end challenge logic async results in all kinds of issues as bukkit/paper does not allow certain actions - // to be performed async (in some versions): PlayerGameModeChangeEvent may only be triggered synchronously - Logger.debug("End challenge called from async thread, scheduling sync task (Caller: {}", ReflectionUtils.getCallerName(1)); - Bukkit.getScheduler().callSyncMethod(Challenges.getInstance(), () -> { - endChallenge(endCause, winnerGetter); - return null; - }); + if (!Regions.isGlobalThread()) { + // The game state is owned by the global region, and PlayerGameModeChangeEvent may only be triggered synchronously + Logger.debug("End challenge called off the global region, scheduling task (Caller: {}", ReflectionUtils.getCallerName(1)); + Regions.global(Challenges.getInstance(), () -> endChallenge(endCause, winnerGetter)); return; } @@ -96,7 +93,7 @@ public void endChallenge(@NotNull ChallengeEndCause endCause, Supplier dropItems(player)); } } @@ -113,7 +110,7 @@ public void endChallenge(@NotNull ChallengeEndCause endCause, Supplier { player.setGameMode(GameMode.SPECTATOR); SoundSample.BLAST.play(player); @@ -122,7 +119,7 @@ private void setSpectator() { } catch (IllegalArgumentException ex) { // We cant spawn fireworks like that in some versions of spigot } - } + }); } private void dropItems(@NotNull Player player) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java index fc1435c94..639cb9262 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/WorldManager.java @@ -9,6 +9,7 @@ import net.cyperia.challenges.plugin.utils.bukkit.container.PlayerData; import net.cyperia.challenges.plugin.utils.misc.BlockUtils; import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.IRandom; import net.cyperia.commons.common.config.Document; import net.cyperia.commons.common.config.FileDocument; @@ -24,6 +25,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; public final class WorldManager { @@ -34,7 +36,7 @@ public final class WorldManager { private final boolean configUseCustomSeed; private final String levelName; private final String[] worlds; - private final Map playerData = new HashMap<>(); + private final Map playerData = new ConcurrentHashMap<>(); @Getter private boolean shutdownBecauseOfReset = false; private WorldSettings settings = new WorldSettings(); @@ -86,11 +88,9 @@ public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Lon Object requester = requestedBy instanceof Player ? requestedBy : MessageKey.of("generic.console"); MessageKey disconnectKey = MessageKey.of(restartOnReset ? "server.reset.restart" : "server.reset.stop"); - for (Player player : Bukkit.getOnlinePlayers()) { - player.kick(disconnectKey.asComponent(player, requester)); - } + Challenges.getInstance().getPlayerManager().forEachAudience(player -> player.kick(disconnectKey.asComponent(player, requester))); - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::stopOrRestartServerNow, 3); + Regions.later(Challenges.getInstance(), this::stopOrRestartServerNow, 3); } private void resetConfigs(@Nullable Long seed) { @@ -136,8 +136,8 @@ private void loadExtraWorld() { } private void teleportPlayersOutOfExtraWorld() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getWorld() != flatWorld) continue; + Challenges.getInstance().getPlayerManager().forEachAudience(player -> { + if (player.getWorld() != flatWorld) return; Location location = player.getRespawnLocation(); if (location == null) { @@ -148,8 +148,8 @@ private void teleportPlayersOutOfExtraWorld() { location = BlockUtils.getCenteredSpawn(world); } - player.teleport(location); - } + player.teleportAsync(location); + }); } @SafeVarargs @@ -323,7 +323,7 @@ public void setWorldInUse(boolean worldInUse) { } private void cachePlayerData() { - Bukkit.getOnlinePlayers().forEach(this::cachePlayerData); + Challenges.getInstance().getPlayerManager().forEachAudience(this::cachePlayerData); } public void cachePlayerData(@NotNull Player player) { @@ -331,7 +331,7 @@ public void cachePlayerData(@NotNull Player player) { } public void restorePlayerData() { - Bukkit.getOnlinePlayers().forEach(this::restorePlayerData); + Challenges.getInstance().getPlayerManager().forEachAudience(this::restorePlayerData); } public void restorePlayerData(@NotNull Player player) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index 10b42de0d..7b02be2d8 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -9,8 +9,9 @@ import net.cyperia.challenges.plugin.content.i18n.hook.LanguageProvider; import net.cyperia.challenges.plugin.content.i18n.impl.format.ComponentArguments; import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.kyori.adventure.text.Component; -import org.bukkit.Bukkit; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.entity.Player; import org.bukkit.scoreboard.Criteria; import org.bukkit.scoreboard.DisplaySlot; @@ -22,6 +23,7 @@ import java.util.ArrayList; import java.util.LinkedList; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -40,7 +42,9 @@ public void setContent(@NotNull BiConsumer content) } public void applyHide(@NotNull Player player) { - unregister(objectives.remove(player)); + Objective objective = objectives.remove(player); + if (objective == null) return; + Regions.global(Challenges.getInstance(), () -> unregister(objective)); } public void update() { @@ -49,10 +53,13 @@ public void update() { } } - public synchronized void update(@NotNull Player player) { - // synchronized method lock: prevent race condition resulting in client error/crash: by sending the objective - // with the same name at the same time twice as the name is constant (1d2b97b) - // java.lang.IllegalArgumentException: An objective with the name 'xxx' already exists! (client-side) + // Runs on the global region, so two updates of one player never overlap: the objective name is + // constant and sending it twice at once crashes the client ("An objective with the name 'xxx' already exists!") + public void update(@NotNull Player player) { + Regions.global(Challenges.getInstance(), () -> updateOnGlobal(player)); + } + + private void updateOnGlobal(@NotNull Player player) { if (!isShown()) { Logger.warn("Tried to update scoreboard which is not shown"); return; @@ -73,36 +80,57 @@ public synchronized void update(@NotNull Player player) { if (lines.isEmpty()) { return; } - - Scoreboard scoreboard = player.getScoreboard(); - if (scoreboard == Bukkit.getScoreboardManager().getMainScoreboard()) { - player.setScoreboard(scoreboard = Bukkit.getScoreboardManager().getNewScoreboard()); - } - - String name = String.valueOf(player.getUniqueId().hashCode()); - // Unregister any old objective existing - Objective oldObjective = scoreboard.getObjective(name); - if (oldObjective != null) { - unregister(oldObjective); - } - - Objective objective = registerDummyObjective(scoreboard, name, instance.getTitle().asComponent(locale)); - for (int i = 0; i < lines.size(); i++) { - Component line = lines.get(i); - Score entry = objective.getScore(String.valueOf(i)); - entry.customName(line); - entry.setScore(MAX_LINES - i); - entry.numberFormat(NumberFormat.blank()); + Component title = instance.getTitle().asComponent(locale); + // Empty unless a server sets it, e.g. to its address + Component footer = MessageKey.of("scoreboard.footer").asComponent(locale); + if (!isBlank(footer) && lines.size() + 2 <= MAX_LINES) { + if (!isBlank(lines.getLast())) lines.add(Component.empty()); + lines.add(centered(footer, title, lines)); } - objective.setDisplaySlot(DisplaySlot.SIDEBAR); - objectives.put(player, objective); + PlayerScoreboards.use(player, scoreboard -> show(scoreboard, player, title, lines)); } catch (Exception ex) { Logger.error("Unable to update scoreboard for player '{}'", player.getName(), ex); } } + private void show(@NotNull Scoreboard scoreboard, @NotNull Player player, @NotNull Component title, @NotNull List lines) { + String name = String.valueOf(player.getUniqueId().hashCode()); + // Unregister any old objective existing + Objective oldObjective = scoreboard.getObjective(name); + if (oldObjective != null) { + unregister(oldObjective); + } + + Objective objective = registerDummyObjective(scoreboard, name, title); + for (int i = 0; i < lines.size(); i++) { + Component line = lines.get(i); + Score entry = objective.getScore(String.valueOf(i)); + entry.customName(line); + entry.setScore(MAX_LINES - i); + entry.numberFormat(NumberFormat.blank()); + } + + objective.setDisplaySlot(DisplaySlot.SIDEBAR); + objectives.put(player, objective); + } + + private static boolean isBlank(@NotNull Component line) { + return PlainTextComponentSerializer.plainText().serialize(line).isBlank(); + } + + // Pads the line with spaces to the middle of the widest line, the sidebar's width + @NotNull + static Component centered(@NotNull Component line, @NotNull Component title, @NotNull List lines) { + int widest = MinecraftFont.widthOf(title); + for (Component other : lines) { + widest = Math.max(widest, MinecraftFont.widthOf(other)); + } + int spaces = (widest - MinecraftFont.widthOf(line)) / 2 / MinecraftFont.SPACE_WIDTH; + return spaces <= 0 ? line : Component.text(" ".repeat(spaces)).append(line); + } + public void show() { Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(this); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/MinecraftFont.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/MinecraftFont.java new file mode 100644 index 000000000..eed567a68 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/MinecraftFont.java @@ -0,0 +1,63 @@ +package net.cyperia.challenges.plugin.management.server.scoreboard; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.TextDecoration; +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; + +/** + * Glyph advances of the vanilla {@code minecraft:default} font, in gui pixels: the glyph plus the one pixel of + * spacing the client draws after it. + */ +final class MinecraftFont { + + static final int SPACE_WIDTH = 4; + + // Most glyphs of the unicode pages, small caps included + private static final int FALLBACK_WIDTH = 6; + private static final int BOLD_EXTRA_WIDTH = 1; + private static final int[] ASCII_WIDTHS = new int[128]; + + static { + Arrays.fill(ASCII_WIDTHS, FALLBACK_WIDTH); + fill(2, "!'.,:;i|"); + fill(3, "`l"); + fill(4, " *I[]t\""); + fill(5, "(){}<>fk"); + fill(7, "@"); + } + + private MinecraftFont() { + } + + private static void fill(int width, @NotNull String characters) { + for (char character : characters.toCharArray()) { + ASCII_WIDTHS[character] = width; + } + } + + // Only text is measured: a translated name has no width here, as its text is only known to the client + static int widthOf(@NotNull Component component) { + return widthOf(component, false); + } + + private static int widthOf(@NotNull Component component, boolean parentBold) { + TextDecoration.State state = component.decoration(TextDecoration.BOLD); + boolean bold = state == TextDecoration.State.TRUE || state == TextDecoration.State.NOT_SET && parentBold; + int width = 0; + if (component instanceof TextComponent text) { + String content = text.content(); + for (int i = 0; i < content.length(); i++) { + char character = content.charAt(i); + width += (character < ASCII_WIDTHS.length ? ASCII_WIDTHS[character] : FALLBACK_WIDTH) + (bold ? BOLD_EXTRA_WIDTH : 0); + } + } + for (Component child : component.children()) { + width += widthOf(child, bold); + } + return width; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/PlayerScoreboards.java b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/PlayerScoreboards.java new file mode 100644 index 000000000..0f3981505 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/management/server/scoreboard/PlayerScoreboards.java @@ -0,0 +1,61 @@ +package net.cyperia.challenges.plugin.management.server.scoreboard; + +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Scoreboard; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; + +/** + * The one private scoreboard of each player, shared by everything that shows objectives to them. Creating a + * scoreboard and registering, displaying or unregistering objectives has to happen on the global region of a + * regionised server, so the map is owned by it. Only {@link Player#setScoreboard} runs on the player's thread. + */ +public final class PlayerScoreboards { + + // Owned by the global region + private static final Map boards = new HashMap<>(); + + private PlayerScoreboards() { + } + + /** + * Runs the task on the global region with the player's board, then puts the board on the player + * unless they are on a scoreboard another plugin set. + */ + public static void use(@NotNull Player player, @NotNull Consumer task) { + Challenges plugin = Challenges.getInstance(); + Regions.global(plugin, () -> { + if (!player.isOnline()) return; + Scoreboard board = boards.computeIfAbsent(player.getUniqueId(), _ -> Bukkit.getScoreboardManager().getNewScoreboard()); + task.accept(board); + Regions.entity(plugin, player, () -> install(player, board)); + }); + } + + // Skips players who never got a board, there is nothing of ours to remove from theirs + public static void useExisting(@NotNull Player player, @NotNull Consumer task) { + Regions.global(Challenges.getInstance(), () -> { + Scoreboard board = boards.get(player.getUniqueId()); + if (board != null) task.accept(board); + }); + } + + public static void forget(@NotNull Player player) { + UUID id = player.getUniqueId(); + Regions.global(Challenges.getInstance(), () -> boards.remove(id)); + } + + private static void install(@NotNull Player player, @NotNull Scoreboard board) { + if (player.getScoreboard() == Bukkit.getScoreboardManager().getMainScoreboard()) { + player.setScoreboard(board); + } + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java b/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java index fa83eda48..f2b53bfa5 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/permission/ChallengesPermissions.java @@ -68,9 +68,9 @@ public final class ChallengesPermissions { public static final String COMMAND_SKIPTIMER = COMMAND + "skiptimer"; public static final String COMMAND_RANDOMIZER = COMMAND + "randomizer"; public static final String COMMAND_SETLANGUAGE = COMMAND + "setlanguage"; - public static final String COMMAND_SKIPITEM = COMMAND + "skipitem"; public static final String COMMAND_SETPOSITION = COMMAND + "setposition"; public static final String COMMAND_DELPOSITION = COMMAND + "delposition"; + public static final String COMMAND_GOAL_SKIP = COMMAND + "goal.skip"; // Player commands, granted to everybody by default public static final String COMMAND_GOAL = COMMAND + "goal"; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/BackCommand.java index 4a2e793aa..bbf5faad7 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/BackCommand.java @@ -23,14 +23,15 @@ import org.jetbrains.annotations.NotNull; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; public class BackCommand implements ChallengeCommand, Listener { - private final Map> lastLocations = new HashMap<>(); + private final Map> lastLocations = new ConcurrentHashMap<>(); // To check if the current teleportation is from the command - private boolean inTeleport = false; + private final Set inTeleport = ConcurrentHashMap.newKeySet(); @NotNull @Override @@ -64,16 +65,15 @@ private void back(@NotNull Player player, int count) { .send(player, Prefix.CHALLENGES, countToTeleport); Location location = list.get(countToTeleport - 1); - inTeleport = true; - player.teleport(location); - inTeleport = false; - list.subList(0, countToTeleport).clear(); + + inTeleport.add(player.getUniqueId()); + player.teleportAsync(location).whenComplete((success, error) -> inTeleport.remove(player.getUniqueId())); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { - if (inTeleport) return; + if (inTeleport.contains(event.getPlayer().getUniqueId())) return; // Don't save the teleports of the pregame movement setting if (!AbstractChallenge.getFirstInstance(PregameMovementSetting.class).isEnabled()) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/GoalCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/GoalCommand.java index 20020b23f..355e32c3b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/GoalCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/GoalCommand.java @@ -4,6 +4,7 @@ import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal; import net.cyperia.challenges.plugin.challenges.type.IGoal; +import net.cyperia.challenges.plugin.challenges.type.abstraction.SharedCollectionGoal; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.management.command.ChallengeCommand; @@ -12,9 +13,11 @@ import net.cyperia.challenges.plugin.management.menu.generator.impl.goal.GoalChecklistMenuGenerator; import net.cyperia.challenges.plugin.permission.ChallengesPermissions; import net.cyperia.commons.bukkit.utils.animation.SoundSample; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class GoalCommand implements ChallengeCommand { @@ -27,14 +30,13 @@ public CommandInfo info() { @Override public void define(@NotNull LiteralArgumentBuilder root, @NotNull CommandNodes nodes) { root.executes(nodes.runAsPlayer((player, context) -> openChecklist(player))); + root.then(nodes.literal("skip").requires(nodes.permission(ChallengesPermissions.COMMAND_GOAL_SKIP)) + .executes(nodes.run((sender, context) -> skip(sender)))); } private static void openChecklist(@NotNull Player player) { - IGoal goal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); - if (goal == null) { - MessageKey.of("command.goal.none").send(player, Prefix.CHALLENGES); - return; - } + IGoal goal = currentGoal(player); + if (goal == null) return; if (!(goal instanceof ChecklistGoal checklist)) { MessageKey.of("command.goal.no-checklist").send(player, Prefix.CHALLENGES, goal.getName()); return; @@ -44,11 +46,30 @@ private static void openChecklist(@NotNull Player player) { // a finder's name may need a lookup to be shown properly, so the menu opens once those are done Challenges.getInstance().getPlayerManager().getNameProvider().load(menu.getFinders()) .exceptionally(_ -> null) - .thenRun(() -> Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + .thenRun(() -> Regions.nextTick(Challenges.getInstance(), player, () -> { if (!player.isOnline()) return; SoundSample.PLOP.play(player); menu.openMenu(player, 0); })); } + private static void skip(@NotNull CommandSender sender) { + IGoal goal = currentGoal(sender); + if (goal == null) return; + if (!(goal instanceof SharedCollectionGoal shared)) { + MessageKey.of("command.goal.no-skip").send(sender, Prefix.CHALLENGES, goal.getName()); + return; + } + shared.skip(sender); + } + + @Nullable + private static IGoal currentGoal(@NotNull CommandSender sender) { + IGoal goal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); + if (goal == null) { + MessageKey.of("command.goal.none").send(sender, Prefix.CHALLENGES); + } + return goal; + } + } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/InvseeCommand.java index 95ba050b1..ac11d46d7 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/InvseeCommand.java @@ -14,7 +14,9 @@ import net.cyperia.challenges.plugin.utils.misc.CommandHelper; import net.cyperia.commons.bukkit.utils.menu.MenuPosition; import net.cyperia.commons.bukkit.utils.menu.positions.SlottedMenuPosition; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; +import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -26,8 +28,9 @@ import org.bukkit.inventory.PlayerInventory; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class InvseeCommand implements ChallengeCommand, Listener { @@ -40,7 +43,7 @@ public class InvseeCommand implements ChallengeCommand, Listener { bootsSlot = 49, offHandSlot = 52; - private final Map inventories = new HashMap<>(); + private final Map inventories = new ConcurrentHashMap<>(); @NotNull @Override @@ -59,9 +62,15 @@ public void define(@NotNull LiteralArgumentBuilder root, @NotNull Command return; } - player.openInventory(getInventory(target)); - MenuPosition.set(player, new SlottedMenuPosition()); - MessageKey.of("command.invsee.open").send(player, Prefix.CHALLENGES, target); + // The target's inventory is read on the target's thread, the viewer opens it on theirs + Regions.entity(Challenges.getInstance(), target, () -> { + Inventory inventory = getInventory(target); + Regions.entity(Challenges.getInstance(), player, () -> { + player.openInventory(inventory); + MenuPosition.set(player, new SlottedMenuPosition()); + MessageKey.of("command.invsee.open").send(player, Prefix.CHALLENGES, target); + }); + }); }))); } @@ -105,25 +114,28 @@ public void updateInventory(@NotNull Player player) { public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (event.getClickedInventory() == null) return; if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); + Regions.later(Challenges.getInstance(), event.getPlayer(), () -> updateInventory(event.getPlayer()), 1); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerDropItem(@NotNull PlayerDropItemEvent event) { - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); + Regions.later(Challenges.getInstance(), event.getPlayer(), () -> updateInventory(event.getPlayer()), 1); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerQuit(@NotNull PlayerQuitEvent event) { Inventory inventory = inventories.remove(event.getPlayer()); if (inventory == null) return; - inventory.close(); + // Viewers sit in other regions than the quitting target, a window is closed on its viewer's thread + for (HumanEntity viewer : List.copyOf(inventory.getViewers())) { + Regions.entity(Challenges.getInstance(), viewer, viewer::closeInventory); + } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onClose(@NotNull InventoryCloseEvent event) { if (event.getInventory().getHolder() != MenuPosition.HOLDER) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::pruneStaleInventories, 1); + Regions.later(Challenges.getInstance(), this::pruneStaleInventories, 1); } private void pruneStaleInventories() { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/PlayerTargetCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/PlayerTargetCommand.java index 6b0a16874..6afc9c5b6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/PlayerTargetCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/PlayerTargetCommand.java @@ -3,12 +3,14 @@ import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.ArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.management.command.ChallengeCommand; import net.cyperia.challenges.plugin.management.command.CommandInfo; import net.cyperia.challenges.plugin.management.command.CommandNodes; import net.cyperia.challenges.plugin.utils.misc.CommandHelper; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -60,7 +62,7 @@ static > T withTargets(@NotNull T node, @NotN action.run(sender, CommandHelper.getPlayers(sender, StringArgumentType.getString(context, "player").trim()))))); } - // True when one of the targets is somebody other than the sender + // Each change runs on its target's thread. True when one of the targets is somebody other than the sender static boolean changeAll(@NotNull CommandSender sender, @NotNull List targets, @NotNull Consumer change) { if (targets.isEmpty()) { MessageKey.of("command.no-target").send(sender, Prefix.CHALLENGES); @@ -69,7 +71,7 @@ static boolean changeAll(@NotNull CommandSender sender, @NotNull List ta boolean otherPlayers = false; for (Player target : targets) { - change.accept(target); + Regions.entity(Challenges.getInstance(), target, () -> change.accept(target)); if (target != sender) otherPlayers = true; } return otherPlayers; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/TimeCommand.java index 4d0ac24d2..de7efb5fe 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/TimeCommand.java @@ -2,12 +2,14 @@ import com.mojang.brigadier.arguments.LongArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.management.command.ChallengeCommand; import net.cyperia.challenges.plugin.management.command.CommandInfo; import net.cyperia.challenges.plugin.management.command.CommandNodes; import net.cyperia.challenges.plugin.permission.ChallengesPermissions; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.NumberFormatter; import org.bukkit.World; import org.bukkit.entity.Player; @@ -58,7 +60,7 @@ public static ShortcutCommand shortcut(@NotNull String name) { // World#setTime moves on to the next time it is that time of day, so a negative time or one past the day works too private static void set(@NotNull Player player, long time) { World world = player.getWorld(); - world.setTime(time); + Regions.global(Challenges.getInstance(), () -> world.setTime(time)); long timeOfDay = Math.floorMod(time, DAY_LENGTH); NAMED_TIMES.entrySet().stream() .filter(entry -> entry.getValue() == timeOfDay) diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java index c39dd9383..2a81828c6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/VillageCommand.java @@ -9,9 +9,10 @@ import net.cyperia.challenges.plugin.management.command.CommandNodes; import net.cyperia.challenges.plugin.permission.ChallengesPermissions; import net.cyperia.commons.bukkit.utils.animation.SoundSample; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Location; import org.bukkit.StructureType; +import org.bukkit.World; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -31,21 +32,21 @@ public void define(@NotNull LiteralArgumentBuilder root, @NotNull Command private static void teleportToVillage(@NotNull Player player) { player.setNoDamageTicks(10); MessageKey.of("command.village.searching").send(player, Prefix.CHALLENGES); - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - Location village = player.getWorld().locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true); + Regions.nextTick(Challenges.getInstance(), player, () -> { + World world = player.getWorld(); + Location village = world.locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true); if (village == null) { MessageKey.of("command.village.none").send(player, Prefix.CHALLENGES); return; } - village = player.getWorld().getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5); - village.getChunk().load(true); - Location finalVillage = village; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { - player.teleport(finalVillage); - SoundSample.TELEPORT.play(player); - MessageKey.of("command.village.done").send(player, Prefix.CHALLENGES); - }, 20 /* run after 1 second to give the chunks/world time to load/generate */); + world.getChunkAtAsync(village).thenAccept(chunk -> Regions.at(Challenges.getInstance(), village, () -> { + Location target = world.getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5); + Regions.later(Challenges.getInstance(), player, () -> player.teleportAsync(target).thenAccept(success -> { + SoundSample.TELEPORT.play(player); + MessageKey.of("command.village.done").send(player, Prefix.CHALLENGES); + }), 20 /* run after 1 second to give the chunks/world time to load/generate */); + })); }); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WeatherCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WeatherCommand.java index a6115c97e..66a8b57f5 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WeatherCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WeatherCommand.java @@ -1,12 +1,14 @@ package net.cyperia.challenges.plugin.spigot.command; import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.content.i18n.MessageKey; import net.cyperia.challenges.plugin.content.i18n.Prefix; import net.cyperia.challenges.plugin.management.command.ChallengeCommand; import net.cyperia.challenges.plugin.management.command.CommandInfo; import net.cyperia.challenges.plugin.management.command.CommandNodes; import net.cyperia.challenges.plugin.permission.ChallengesPermissions; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.World; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -43,8 +45,10 @@ public static ShortcutCommand shortcut(@NotNull String literal, @NotNull Weather private static void set(@NotNull Player player, @NotNull Weather weather) { World world = player.getWorld(); - world.setStorm(weather != Weather.CLEAR); - world.setThundering(weather == Weather.THUNDER); + Regions.global(Challenges.getInstance(), () -> { + world.setStorm(weather != Weather.CLEAR); + world.setThundering(weather == Weather.THUNDER); + }); MessageKey.of("command.weather." + weather.name().toLowerCase(Locale.ROOT)).send(player, Prefix.CHALLENGES); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldCommand.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldCommand.java index 8bd7a2186..4e550cf6b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldCommand.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/command/WorldCommand.java @@ -38,7 +38,7 @@ public void define(@NotNull LiteralArgumentBuilder root, @NotNull Command Location location = getSpawn(world, player); MessageKey.of("command.world.done").send(player, Prefix.CHALLENGES, getWorldName(location)); - player.teleport(location); + player.teleportAsync(location); }))); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/InventoryClickEventWrapper.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/InventoryClickEventWrapper.java index 9c0a4c5a1..f43e90e1c 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/InventoryClickEventWrapper.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/InventoryClickEventWrapper.java @@ -1,6 +1,7 @@ package net.cyperia.challenges.plugin.spigot.events; import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.InventoryAction; @@ -14,7 +15,7 @@ import java.util.List; -public abstract class InventoryClickEventWrapper extends Event { +public abstract class InventoryClickEventWrapper extends Event implements Cancellable { private final InventoryClickEvent event; @@ -102,10 +103,12 @@ public InventoryClickEvent getEvent() { return event; } + @Override public boolean isCancelled() { return event.isCancelled(); } + @Override public void setCancelled(boolean cancel) { event.setCancelled(cancel); } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PlayerRespawnLocationEvent.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PlayerRespawnLocationEvent.java new file mode 100644 index 000000000..c41c39195 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PlayerRespawnLocationEvent.java @@ -0,0 +1,43 @@ +package net.cyperia.challenges.plugin.spigot.events; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; +import org.jetbrains.annotations.NotNull; + +// Only the location may be changed here, the player is not respawned yet +public class PlayerRespawnLocationEvent extends PlayerEvent { + + private static final HandlerList handlers = new HandlerList(); + + private Location respawnLocation; + + // Bukkit accepts a sync event on a region thread only, and an async one everywhere else + public PlayerRespawnLocationEvent(@NotNull Player who, @NotNull Location respawnLocation) { + super(who, !Bukkit.isPrimaryThread()); + this.respawnLocation = respawnLocation; + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } + + @NotNull + public Location getRespawnLocation() { + return respawnLocation; + } + + public void setRespawnLocation(@NotNull Location respawnLocation) { + this.respawnLocation = respawnLocation; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PlayerRespawnedEvent.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PlayerRespawnedEvent.java new file mode 100644 index 000000000..0e557eab8 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PlayerRespawnedEvent.java @@ -0,0 +1,29 @@ +package net.cyperia.challenges.plugin.spigot.events; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; +import org.jetbrains.annotations.NotNull; + +public class PlayerRespawnedEvent extends PlayerEvent { + + private static final HandlerList handlers = new HandlerList(); + + // Bukkit accepts a sync event on a region thread only, and an async one everywhere else + public PlayerRespawnedEvent(@NotNull Player who) { + super(who, !Bukkit.isPrimaryThread()); + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PortalArrivedEvent.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PortalArrivedEvent.java new file mode 100644 index 000000000..90e2e4f8a --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PortalArrivedEvent.java @@ -0,0 +1,57 @@ +package net.cyperia.challenges.plugin.spigot.events; + +import org.bukkit.Bukkit; +import org.bukkit.PortalType; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Event; +import org.jetbrains.annotations.NotNull; + +/** + * An entity that has arrived in another world through a portal. Called on the thread that owns the + * entity at its destination, where it can be moved on. + */ +public class PortalArrivedEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + + private final Entity entity; + private final World from; + private final PortalType portalType; + + // Bukkit accepts a sync event on a region thread only, and an async one everywhere else + public PortalArrivedEvent(@NotNull Entity entity, @NotNull World from, @NotNull PortalType portalType) { + super(!Bukkit.isPrimaryThread()); + this.entity = entity; + this.from = from; + this.portalType = portalType; + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } + + @NotNull + public Entity getEntity() { + return entity; + } + + @NotNull + public World getFrom() { + return from; + } + + @NotNull + public PortalType getPortalType() { + return portalType; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PortalTravelEvent.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PortalTravelEvent.java new file mode 100644 index 000000000..60e5ffede --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/events/PortalTravelEvent.java @@ -0,0 +1,103 @@ +package net.cyperia.challenges.plugin.spigot.events; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.PortalType; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * A player or entity about to travel through a portal. The destination in the target world is only + * known on servers that hand it out (Paper); elsewhere the server picks it once the world is settled, + * and {@link #getDestination()} is null. + */ +public class PortalTravelEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private final Entity entity; + private final World from; + private final PortalType portalType; + private World targetWorld; + private Location destination; + private boolean cancelled; + + // Bukkit accepts a sync event on a region thread only, and an async one everywhere else + public PortalTravelEvent(@NotNull Entity entity, @NotNull World from, @NotNull World targetWorld, @NotNull PortalType portalType, @Nullable Location destination) { + super(!Bukkit.isPrimaryThread()); + this.entity = entity; + this.from = from; + this.targetWorld = targetWorld; + this.portalType = portalType; + this.destination = destination; + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } + + @NotNull + public Entity getEntity() { + return entity; + } + + @NotNull + public World getFrom() { + return from; + } + + @NotNull + public PortalType getPortalType() { + return portalType; + } + + @NotNull + public World getTargetWorld() { + return targetWorld; + } + + // An existing destination is rescaled from the coordinates of the world it led to into the new one's + public void setTargetWorld(@NotNull World targetWorld) { + if (destination != null) { + double ratio = this.targetWorld.getCoordinateScale() / targetWorld.getCoordinateScale(); + destination = destination.clone(); + destination.setWorld(targetWorld); + destination.setX(destination.getX() * ratio); + destination.setZ(destination.getZ() * ratio); + } + this.targetWorld = targetWorld; + } + + @Nullable + public Location getDestination() { + return destination; + } + + public void setDestination(@NotNull Location destination) { + this.destination = destination; + this.targetWorld = destination.getWorld(); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/generator/ConvertingWorldGenerator.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/generator/ConvertingWorldGenerator.java index 32f413bed..715feea32 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/generator/ConvertingWorldGenerator.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/generator/ConvertingWorldGenerator.java @@ -1,9 +1,10 @@ package net.cyperia.challenges.plugin.spigot.generator; import net.cyperia.challenges.plugin.Challenges; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Chunk; import org.bukkit.ChunkSnapshot; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; @@ -104,7 +105,7 @@ public void cleanUp(@NotNull Chunk chunk, boolean newChunk) { Challenges.getInstance().runAsync(() -> { int[] leftovers = leftovers(snapshot, minY, world.getMaxHeight()); if (!Challenges.getInstance().isEnabled()) return; - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Regions.nextTick(Challenges.getInstance(), new Location(world, chunk.getX() << 4, 0, chunk.getZ() << 4), () -> { if (!chunk.isLoaded()) return; for (int position : leftovers) { chunk.getBlock(position & 15, minY + (position >> 8), position >> 4 & 15).setType(replacement, false); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/HelpListener.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/HelpListener.java index 6255724c6..b8b3460b2 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/HelpListener.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/HelpListener.java @@ -53,6 +53,8 @@ public static void sendPluginSummary(@NotNull CommandSender sender) { send(sender, (german ? "Entwickelt von " : "Made by ") + link(german, "cyperia.net") + " (" + link(german, "domiirl.svrt.dev", "DomiIRL") + " & " + link(german, "github.com/anweisen", "anweisen") + ")"); + send(sender, (german ? "Lizenz: " : "License: ") + link(german, "github.com/cyperia/Challenges/blob/main/LICENSE", "AGPL-3.0") + + (german ? ", ohne Gewährleistung" : ", without any warranty")); } public static void sendFirstInstallWelcome(@NotNull CommandSender sender) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 3d0d3704f..8224d801a 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -13,6 +13,7 @@ import net.cyperia.challenges.plugin.utils.misc.DatabaseHelper; import net.cyperia.challenges.plugin.utils.misc.ParticleUtils; import net.cyperia.commons.bukkit.utils.misc.MinecraftVersion; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -33,7 +34,6 @@ public class PlayerConnectionListener implements Listener { private final boolean startTimerOnJoin; private final boolean resetOnLastQuit; private final boolean restoreDefaultsOnLastQuit; - private final boolean pluginInfoOnJoin; private final boolean unsupportedVersionWarning; public PlayerConnectionListener() { @@ -43,8 +43,6 @@ public PlayerConnectionListener() { startTimerOnJoin = config.getBoolean(ConfigManager.Keys.START_ON_FIRST_JOIN); resetOnLastQuit = config.getBoolean(ConfigManager.Keys.RESET_ON_LAST_LEAVE); restoreDefaultsOnLastQuit = config.getBoolean(ConfigManager.Keys.RESTORE_DEFAULTS_ON_LAST_LEAVE); - // Defaults to true so a config.yml predating the key behaves like a fresh one - pluginInfoOnJoin = config.getBoolean(ConfigManager.Keys.PLUGIN_INFO_ON_JOIN, true); unsupportedVersionWarning = !Challenges.getInstance().isVersionSupported() && config.getBoolean(ConfigManager.Keys.UNSUPPORTED_VERSION_CHAT_WARNING, true); } @@ -62,13 +60,7 @@ public void onJoin(@NotNull PlayerJoinEvent event) { // First thing in chat, so it reads as a banner the rest of the join messages follow rather // than something interrupting them. No separator needed: each of those prepends its own. - if (pluginInfoOnJoin) { - if (Challenges.getInstance().isFirstInstall()) { - HelpListener.sendPluginInfo(player); - } else { - HelpListener.sendPluginSummary(player); - } - } + sendPluginInfo(player); if (Challenges.getInstance().isFirstInstall() && !player.hasPermission(ChallengesPermissions.COMMAND_CHALLENGES)) { MessageKey.of("server.not-op").send(player, Prefix.CHALLENGES); @@ -143,7 +135,7 @@ public void onJoin(@NotNull PlayerJoinEvent event) { if (unsupportedVersionWarning) { // A tick later, after the join messages of every other plugin, so it is the last thing in chat - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Regions.nextTick(Challenges.getInstance(), player, () -> { player.sendMessage(""); MessageKey.of("server.unsupported-version").send(player, Prefix.CHALLENGES, Challenges.getInstance().getDescription().getVersion(), @@ -166,6 +158,15 @@ private static boolean isLastVisiblePlayer(@NotNull Player quitting) { return true; } + // The public release cannot turn the credits off, its license forbids hiding them + private void sendPluginInfo(@NotNull Player player) { + if (Challenges.getInstance().isFirstInstall()) { + HelpListener.sendPluginInfo(player); + } else { + HelpListener.sendPluginSummary(player); + } + } + // A late joiner still reports a playing game mode here: AutoResetManager applies spectator at // MONITOR, after this listener, so they have to be asked about rather than looked at. private static boolean isWatching(@NotNull Player player) { diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java index ac0980cee..0515514c5 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java @@ -3,7 +3,7 @@ import net.cyperia.challenges.plugin.Challenges; import net.cyperia.challenges.plugin.management.server.scoreboard.ChallengeScoreboard; import net.cyperia.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; -import org.bukkit.Bukkit; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -12,7 +12,7 @@ public class ScoreboardUpdateListener implements Listener { @EventHandler public void onIgnoredChange(PlayerIgnoreStatusChangeEvent event) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Regions.nextTick(Challenges.getInstance(), () -> { ChallengeScoreboard currentScoreboard = Challenges.getInstance().getScoreboardManager().getCurrentScoreboard(); if (currentScoreboard != null) { currentScoreboard.update(); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/BukkitRespawnPortalAdapter.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/BukkitRespawnPortalAdapter.java new file mode 100644 index 000000000..c4d876b87 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/BukkitRespawnPortalAdapter.java @@ -0,0 +1,69 @@ +package net.cyperia.challenges.plugin.spigot.region; + +import com.destroystokyo.paper.event.player.PlayerPostRespawnEvent; +import net.cyperia.challenges.plugin.spigot.events.PortalTravelEvent; +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.misc.Regions; +import org.bukkit.Location; +import org.bukkit.PortalType; +import org.bukkit.entity.Entity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityPortalEvent; +import org.bukkit.event.player.PlayerPortalEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.jetbrains.annotations.NotNull; +import java.util.function.Consumer; + + +public final class BukkitRespawnPortalAdapter implements Listener { + + // RespawnSetting used to settle the location at MONITOR, so it outranks every other plugin's change + @EventHandler(priority = EventPriority.HIGHEST) + public void onRespawn(@NotNull PlayerRespawnEvent event) { + Location original = event.getRespawnLocation(); + Location settled = RespawnPortalEvents.respawnLocation(event.getPlayer(), original); + if (settled != original) event.setRespawnLocation(settled); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPostRespawn(@NotNull PlayerPostRespawnEvent event) { + RespawnPortalEvents.respawned(event.getPlayer()); + } + + @EventHandler + public void onPlayerPortal(@NotNull PlayerPortalEvent event) { + travel(event.getPlayer(), event.getFrom(), event.getTo(), portalType(event.getCause()), event.isCancelled(), event::setCancelled, event::setTo); + } + + @EventHandler + public void onEntityPortal(@NotNull EntityPortalEvent event) { + travel(event.getEntity(), event.getFrom(), event.getTo(), event.getPortalType(), event.isCancelled(), event::setCancelled, event::setTo); + } + + private static void travel(@NotNull Entity entity, @NotNull Location from, Location to, @NotNull PortalType type, + boolean cancelled, @NotNull Consumer setCancelled, @NotNull Consumer setTo) { + if (to == null || to.getWorld() == null || from.getWorld() == null) return; + + PortalTravelEvent travel = RespawnPortalEvents.portalTravel(entity, from.getWorld(), to.getWorld(), type, to, cancelled); + if (travel.isCancelled() != cancelled) setCancelled.accept(travel.isCancelled()); + if (travel.getDestination() != to) setTo.accept(travel.getDestination()); + // The server moves the entity once this handler is through, so it has arrived by its next tick + if (!travel.isCancelled()) { + Regions.later(Challenges.getInstance(), entity, () -> RespawnPortalEvents.portalArrived(entity, from.getWorld(), type), 1); + } + } + + @NotNull + static PortalType portalType(@NotNull TeleportCause cause) { + return switch (cause) { + case NETHER_PORTAL -> PortalType.NETHER; + case END_PORTAL -> PortalType.ENDER; + case END_GATEWAY -> PortalType.END_GATEWAY; + default -> PortalType.CUSTOM; + }; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalAdapters.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalAdapters.java new file mode 100644 index 000000000..6e260de78 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalAdapters.java @@ -0,0 +1,35 @@ +package net.cyperia.challenges.plugin.spigot.region; + +import org.bukkit.event.Listener; +import org.jetbrains.annotations.NotNull; + +public final class RespawnPortalAdapters { + + static final String CANVAS_EVENT = "io.canvasmc.canvas.event.PlayerRespawnAsyncEvent"; + static final String CANVAS_ADAPTER = "net.cyperia.challenges.plugin.spigot.region.CanvasRespawnPortalAdapter"; + + private RespawnPortalAdapters() { + } + + // Canvas never fires the Bukkit respawn and portal events, Paper and Purpur never fire the Canvas ones + @NotNull + public static Listener create() { + if (!isClassPresent(CANVAS_EVENT)) return new BukkitRespawnPortalAdapter(); + + try { + return (Listener) Class.forName(CANVAS_ADAPTER).getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException ex) { + throw new IllegalStateException("Canvas was detected but its adapter could not be created", ex); + } + } + + static boolean isClassPresent(@NotNull String name) { + try { + Class.forName(name, false, RespawnPortalAdapters.class.getClassLoader()); + return true; + } catch (ClassNotFoundException ex) { + return false; + } + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalEvents.java b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalEvents.java new file mode 100644 index 000000000..011532c31 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalEvents.java @@ -0,0 +1,52 @@ +package net.cyperia.challenges.plugin.spigot.region; + +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnLocationEvent; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnedEvent; +import net.cyperia.challenges.plugin.spigot.events.PortalArrivedEvent; +import net.cyperia.challenges.plugin.spigot.events.PortalTravelEvent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.PortalType; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Fires the plugin's own respawn and portal events for whichever platform events an adapter is bound to. + * Bukkit events are never fired a second time, so other plugins see each one once. + */ +public final class RespawnPortalEvents { + + private RespawnPortalEvents() { + } + + /** + * @return the location the listeners settled on, the same instance when none changed it + */ + @NotNull + public static Location respawnLocation(@NotNull Player player, @NotNull Location location) { + PlayerRespawnLocationEvent event = new PlayerRespawnLocationEvent(player, location); + Bukkit.getPluginManager().callEvent(event); + return event.getRespawnLocation(); + } + + public static void respawned(@NotNull Player player) { + Bukkit.getPluginManager().callEvent(new PlayerRespawnedEvent(player)); + } + + @NotNull + public static PortalTravelEvent portalTravel(@NotNull Entity entity, @NotNull World from, @NotNull World targetWorld, + @NotNull PortalType type, @Nullable Location destination, boolean cancelled) { + PortalTravelEvent event = new PortalTravelEvent(entity, from, targetWorld, type, destination); + event.setCancelled(cancelled); + Bukkit.getPluginManager().callEvent(event); + return event; + } + + public static void portalArrived(@NotNull Entity entity, @NotNull World from, @NotNull PortalType type) { + Bukkit.getPluginManager().callEvent(new PortalArrivedEvent(entity, from, type)); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/container/PlayerData.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/container/PlayerData.java index a19988645..9268e51a6 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/container/PlayerData.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/container/PlayerData.java @@ -1,6 +1,8 @@ package net.cyperia.challenges.plugin.utils.bukkit.container; import lombok.Data; +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -68,13 +70,13 @@ public PlayerData( this.flying = allowedFlight && flying; } + // Runs on the player's thread. Everything but the position is restored before the teleport, so a player who + // leaves while it is under way has already got their state back and the teleport is all that is lost. public void apply(@NotNull Player player) { for (PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } player.setGameMode(gamemode); - player.teleport(location); - player.setFallDistance(0); // a teleport keeps it, so a fall in the extra world would land here player.setHealth(health); player.setFoodLevel(food); player.setSaturation(saturation); @@ -84,6 +86,9 @@ public void apply(@NotNull Player player) { player.addPotionEffects(effects); player.setAllowFlight(allowedFlight); player.setFlying(flying); + player.teleportAsync(location).thenRun(() -> + // a teleport keeps the fall distance, so a fall in the extra world would land here + Regions.entity(Challenges.getInstance(), player, () -> player.setFallDistance(0))); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueue.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueue.java index 1cea25762..8b2f7116e 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueue.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueue.java @@ -1,5 +1,7 @@ package net.cyperia.challenges.plugin.utils.bukkit.misc; +import net.cyperia.challenges.plugin.Challenges; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; @@ -15,10 +17,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; import java.util.Deque; import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; @@ -28,6 +34,11 @@ * Replaces matching blocks of whole chunks a few columns per tick. A chunk holds up to ~100k blocks, * which is a visible freeze when done in one tick, so callers submit the work and drain it from a * one tick task instead. + *

+ * Several regions may drain at once. A fill is worked on by whichever thread owns its chunk: a drain + * on another thread hands out slices to the chunk's region instead, each limited to a share of the + * drain's time. Such a slice, and the fill's {@code done}, run on the chunk's thread. The queues are + * only locked to take a fill out or put it back, never while blocks are placed. */ public final class ChunkFillQueue { @@ -37,8 +48,46 @@ public final class ChunkFillQueue { private static final int COLUMNS = 16 * 16; static final int TIME_CHECK_INTERVAL = 64; + // Slices a single drain hands to other regions, so one call cannot flood the schedulers + private static final int MAX_DISPATCHES = 8; + private static final long MIN_SLICE_NANOS = 1_000_000; + + /** Decides which thread works on a chunk. */ + interface Owner { + + boolean owns(@NotNull Chunk chunk); + + void run(@NotNull Chunk chunk, @NotNull Runnable task); + + } + + private static final Owner SERVER = new Owner() { + @Override + public boolean owns(@NotNull Chunk chunk) { + return Bukkit.isOwnedByCurrentRegion(chunk.getWorld(), chunk.getX(), chunk.getZ()); + } + + @Override + public void run(@NotNull Chunk chunk, @NotNull Runnable task) { + Regions.at(Challenges.getInstance(), new Location(chunk.getWorld(), chunk.getX() << 4, 0, chunk.getZ() << 4), task); + } + }; + + private final Owner owner; + // All three are guarded by lock. A fill that is being worked on is in none of the queues but in inFlight, + // which is how forget() and clear() reach it. + private final Object lock = new Object(); private final Deque urgent = new ArrayDeque<>(); - private final Deque queue = new ArrayDeque<>(); + private final LinkedHashSet queue = new LinkedHashSet<>(); + private final Set inFlight = new HashSet<>(); + + public ChunkFillQueue() { + this(SERVER); + } + + ChunkFillQueue(@NotNull Owner owner) { + this.owner = owner; + } /** * Queues every block between {@code fromY} and {@code toY} (both inclusive) that the filter accepts @@ -78,9 +127,17 @@ public void submit(@NotNull Chunk chunk, int fromY, int toY, @NotNull BlockData public void submit(@NotNull Chunk chunk, int fromY, int toY, @NotNull Function replacement, @NotNull Predicate physics, @NotNull Supplier order, boolean urgent, @NotNull Runnable done) { if (fromY > toY) return; - Fill fill = new Fill(chunk, fromY, toY, replacement, physics, order, done); - if (urgent) this.urgent.addFirst(fill); - else queue.add(fill); + Fill fill = new Fill(chunk, fromY, toY, replacement, physics, order, done, urgent); + synchronized (lock) { + if (urgent) this.urgent.addFirst(fill); + else queue.add(fill); + } + } + + public boolean isEmpty() { + synchronized (lock) { + return urgent.isEmpty() && queue.isEmpty() && inFlight.isEmpty(); + } } public void drain() { @@ -107,75 +164,118 @@ public void drainUntil(long deadline) { * {@code radius} chunk rings of a player runs to completion before a farther one starts. */ public void drainUntil(long deadline, @NotNull ToIntFunction ring, int radius) { - if (!drainUrgent(deadline)) return; - if (queue.isEmpty() || System.nanoTime() >= deadline) return; - - List ordered = new ArrayList<>(queue); - queue.clear(); - for (Fill fill : ordered) fill.ring = ring.applyAsInt(fill.chunk); - ordered.sort((a, b) -> Integer.compare(a.ring, b.ring)); // stable: ties keep the queue order above - queue.addAll(ordered); - - // Sorted near-first, so popping the queue from the front runs every fill within radius to completion - // before a farther one is reached; a farther fill that has not finished its slice re-enters at the - // back, never the front, so it never overtakes a nearer one. Every fill stays in this queue, so - // forget() and clear() reach it regardless of ring. - while (!queue.isEmpty() && System.nanoTime() < deadline) { - Fill fill = queue.poll(); - if (!fill.chunk.isLoaded()) continue; - if (fill.ring <= radius) { - if (!runToCompletion(fill, deadline)) { - queue.addFirst(fill); - return; + Dispatch dispatch = new Dispatch(deadline); + if (!drainUrgent(deadline, dispatch)) return; + + // Sorted near-first on a copy, so no lock is held for it. Taking the fills in that order runs every + // fill within radius to completion before a farther one is reached; a farther fill that has not + // finished its slice re-enters at the back, never the front, so it never overtakes a nearer one. + // Repeated until the queue is empty, so far fills take turns slice by slice within the deadline. + while (System.nanoTime() < deadline) { + List ordered; + synchronized (lock) { + if (queue.isEmpty()) return; + ordered = new ArrayList<>(queue); + } + Map rings = new HashMap<>(); + for (Fill fill : ordered) rings.put(fill, ring.applyAsInt(fill.chunk)); + ordered.sort(Comparator.comparingInt(rings::get)); // stable: ties keep the queue order + + for (Fill fill : ordered) { + if (System.nanoTime() >= deadline) return; + if (!claim(queue, fill)) continue; + + if (!fill.chunk.isLoaded()) { + release(fill, Requeue.NO); + } else if (!owner.owns(fill.chunk)) { + if (!handOff(fill, Integer.MAX_VALUE, dispatch)) { + release(fill, Requeue.FRONT); + return; + } + } else if (rings.get(fill) <= radius) { + if (!runToCompletion(fill, deadline)) { + release(fill, Requeue.FRONT); + return; + } + } else if (advance(fill, TIME_CHECK_INTERVAL)) { + release(fill, Requeue.NO); + fill.done.run(); + } else { + release(fill, Requeue.BACK); } - } else if (advance(fill, TIME_CHECK_INTERVAL)) { - fill.done.run(); - } else { - queue.addLast(fill); } } } private void drain(int budget, long deadline) { + Dispatch dispatch = new Dispatch(deadline); + // Under a deadline the time limits the work, otherwise the block budget does + boolean timed = deadline != Long.MAX_VALUE; while (budget > 0 && System.nanoTime() < deadline) { - Deque source = urgent.isEmpty() ? queue : urgent; - Fill fill = source.peek(); + Fill fill = claimNext(); if (fill == null) return; if (!fill.chunk.isLoaded()) { - source.poll(); + release(fill, Requeue.NO); + continue; + } + if (!owner.owns(fill.chunk)) { + int slice = timed ? Integer.MAX_VALUE : Math.min(budget, DEFAULT_BUDGET); + if (!handOff(fill, slice, dispatch)) { + release(fill, Requeue.FRONT); + return; + } + if (!timed) budget -= slice; continue; } int before = fill.cursor; boolean done = advance(fill, Math.min(budget, TIME_CHECK_INTERVAL)); budget -= fill.cursor - before; - if (done) { - source.poll(); - fill.done.run(); - } + release(fill, done ? Requeue.NO : Requeue.FRONT); + if (done) fill.done.run(); } } // Drains the urgent deque to completion, newest first, one fill at a time. False means the deadline // passed with fills still pending; the head fill, if any, keeps its progress for the next call. - private boolean drainUrgent(long deadline) { - while (!urgent.isEmpty()) { - Fill fill = urgent.poll(); + private boolean drainUrgent(long deadline, @NotNull Dispatch dispatch) { + while (true) { + Fill fill; + synchronized (lock) { + fill = urgent.poll(); + if (fill != null) inFlight.add(fill); + } + if (fill == null) return true; + + if (!owner.owns(fill.chunk)) { + if (!fill.chunk.isLoaded()) { + release(fill, Requeue.NO); + continue; + } + if (!handOff(fill, Integer.MAX_VALUE, dispatch)) { + release(fill, Requeue.FRONT); + return false; + } + continue; + } if (!runToCompletion(fill, deadline)) { - urgent.addFirst(fill); + release(fill, Requeue.FRONT); return false; } } - return true; } // Runs a fill in TIME_CHECK_INTERVAL slices until it finishes or the deadline passes. The fill must - // already be polled from its deque: done runs after that removal, so a done that resubmits urgently - // never collides with the fill that is finishing. A chunk that unloads is dropped without running - // done, same as forget(). + // already be claimed: done runs after it is released, so a done that resubmits urgently never collides + // with the fill that is finishing. A chunk that unloads is dropped without running done, same as forget(). + // True when the fill is through, and released; false leaves it claimed for the caller to put back. private boolean runToCompletion(@NotNull Fill fill, long deadline) { while (System.nanoTime() < deadline) { - if (!fill.chunk.isLoaded()) return true; + if (!fill.chunk.isLoaded()) { + release(fill, Requeue.NO); + return true; + } if (advance(fill, TIME_CHECK_INTERVAL)) { + release(fill, Requeue.NO); fill.done.run(); return true; } @@ -183,6 +283,88 @@ private boolean runToCompletion(@NotNull Fill fill, long deadline) { return false; } + // Takes the next fill, an urgent one first + @Nullable + private Fill claimNext() { + synchronized (lock) { + Fill fill = !urgent.isEmpty() ? urgent.poll() : queue.isEmpty() ? null : queue.removeFirst(); + if (fill != null) inFlight.add(fill); + return fill; + } + } + + // False when another drain took the fill, or it was forgotten, since the caller looked at the queue + private boolean claim(@NotNull Set from, @NotNull Fill fill) { + synchronized (lock) { + if (!from.remove(fill)) return false; + inFlight.add(fill); + return true; + } + } + + private enum Requeue {FRONT, BACK, NO} + + private void release(@NotNull Fill fill, @NotNull Requeue requeue) { + synchronized (lock) { + inFlight.remove(fill); + if (requeue == Requeue.NO || fill.cancelled) return; + if (fill.urgent) { + urgent.addFirst(fill); + } else if (requeue == Requeue.FRONT) { + queue.addFirst(fill); + } else { + queue.add(fill); + } + } + } + + // Hands a slice of the fill to the chunk's region, which puts the fill back at the front of its queue + // when the slice did not finish it. The slice stops after its share of the drain's remaining time. False + // once this drain has handed out as much as it may; the fill stays claimed then. + private boolean handOff(@NotNull Fill fill, int blocks, @NotNull Dispatch dispatch) { + if (dispatch.count >= MAX_DISPATCHES) return false; + dispatch.count++; + long timeBox = dispatch.timeBox(); + owner.run(fill.chunk, () -> work(fill, blocks, timeBox)); + return true; + } + + private void work(@NotNull Fill fill, int blocks, long timeBox) { + long end = timeBox == Long.MAX_VALUE ? Long.MAX_VALUE : System.nanoTime() + timeBox; + boolean finished = true; + if (!fill.cancelled && fill.chunk.isLoaded()) { + finished = false; + int left = blocks; + while (!finished && left > 0 && System.nanoTime() < end && !fill.cancelled && fill.chunk.isLoaded()) { + int before = fill.cursor; + finished = advance(fill, Math.min(left, TIME_CHECK_INTERVAL)); + left -= fill.cursor - before; + } + if (!fill.chunk.isLoaded()) finished = true; + } + + boolean runDone = finished && !fill.cancelled && fill.chunk.isLoaded(); + release(fill, finished ? Requeue.NO : Requeue.FRONT); + if (runDone) fill.done.run(); + } + + // One drain's hand-outs: how many it made, and the time it has left to share between them + private static final class Dispatch { + + private final long deadline; + private int count; + + private Dispatch(long deadline) { + this.deadline = deadline; + } + + private long timeBox() { + if (deadline == Long.MAX_VALUE) return Long.MAX_VALUE; + return Math.max(MIN_SLICE_NANOS, (deadline - System.nanoTime()) / MAX_DISPATCHES); + } + + } + // Visits up to `blocks` more cells of the fill, continuing from where the last call left off. Returns // whether the fill is now finished. private static boolean advance(@NotNull Fill fill, int blocks) { @@ -206,7 +388,7 @@ private static boolean advance(@NotNull Fill fill, int blocks) { public static ToIntFunction playerRing() { Map chunksByWorld = new HashMap<>(); for (World world : Bukkit.getWorlds()) { - List players = world.getPlayers(); + List players = Bukkit.getOnlinePlayers().stream().filter(player -> player.getWorld() == world).map(Player.class::cast).toList(); if (players.isEmpty()) continue; int[] xs = new int[players.size()]; int[] zs = new int[players.size()]; @@ -262,13 +444,21 @@ public static int[] orderByDistance(@NotNull int[] cells, @NotNull List chunk.equals(fill.chunk)); - queue.removeIf(fill -> chunk.equals(fill.chunk)); + synchronized (lock) { + urgent.removeIf(fill -> chunk.equals(fill.chunk)); + queue.removeIf(fill -> chunk.equals(fill.chunk)); + for (Fill fill : inFlight) { + if (chunk.equals(fill.chunk)) fill.cancelled = true; + } + } } public void clear() { - urgent.clear(); - queue.clear(); + synchronized (lock) { + urgent.clear(); + queue.clear(); + for (Fill fill : inFlight) fill.cancelled = true; + } } @NotNull @@ -299,13 +489,14 @@ private static final class Fill { private final Predicate physics; private final Supplier orderSupplier; private final Runnable done; + private final boolean urgent; private int[] order; private int cursor; - // Set for every queued fill when a ring-mode drain starts; a fill submitted during one counts as far. - private int ring = Integer.MAX_VALUE; + private volatile boolean cancelled; private Fill(Chunk chunk, int fromY, int toY, Function replacement, Predicate physics, - Supplier orderSupplier, Runnable done) { + Supplier orderSupplier, Runnable done, boolean urgent) { + this.urgent = urgent; this.chunk = chunk; this.fromY = fromY; this.toY = toY; diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkSet.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkSet.java index ec66a5a30..7c8f16a78 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkSet.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkSet.java @@ -6,10 +6,9 @@ import org.bukkit.Chunk; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; /** * A set of chunks that can be written into the game state. Keys are kept per world, because a chunk key @@ -17,7 +16,7 @@ */ public final class ChunkSet { - private final Map> chunks = new HashMap<>(); + private final Map> chunks = new ConcurrentHashMap<>(); /** * Adds the chunk and answers whether it was not in the set yet. @@ -51,7 +50,7 @@ public void loadGameState(@NotNull Document document, @NotNull String key) { // Read by the names the document holds, not by the worlds that exist right now: a game world can be // created after the game state is loaded, and its chunks would be dropped on the next save. for (String world : stored.keys()) { - Set keys = new HashSet<>(); + Set keys = ConcurrentHashMap.newKeySet(); for (String chunkKey : stored.getStringList(world)) { try { @@ -67,7 +66,7 @@ public void loadGameState(@NotNull Document document, @NotNull String key) { @NotNull private Set chunksIn(@NotNull String world) { - return chunks.computeIfAbsent(world, name -> new HashSet<>()); + return chunks.computeIfAbsent(world, name -> ConcurrentHashMap.newKeySet()); } } diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/KillableMob.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/KillableMob.java new file mode 100644 index 000000000..43d0ecd27 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/KillableMob.java @@ -0,0 +1,125 @@ +package net.cyperia.challenges.plugin.utils.entity; + +import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; +import net.cyperia.challenges.plugin.content.i18n.MessageKey; +import net.cyperia.commons.bukkit.utils.item.ItemUtils; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * A mob to kill: a type, and with variants a type with every one of its {@link MobTrait traits}. A kill counts for + * every killable mob it matches, so a baby zombie on a chicken is a zombie, a baby zombie and a chicken jockey at once. + */ +public record KillableMob(@NotNull EntityType type, @NotNull List traits) { + + @NotNull + public static KillableMob of(@NotNull EntityType type) { + return new KillableMob(type, List.of()); + } + + /** + * Every type first on its own, followed by its attribute or equipment variants that are asked for; on its own only + * where the variants leave some of it out. + */ + @NotNull + public static List pool(@NotNull Collection types, boolean attributes, boolean equipment) { + List mobs = new ArrayList<>(); + for (EntityType type : types) { + // Only the attribute variants of a type add up to every mob of it, a mob may hold nothing + if (!attributes || !MobVariants.coversEveryMob(type)) mobs.add(of(type)); + for (KillableMob variant : MobVariants.of(type)) { + if (variant.isEquipment() ? equipment : attributes) mobs.add(variant); + } + } + return List.copyOf(mobs); + } + + boolean isEquipment() { + return traits.stream().anyMatch(MobTrait::isEquipment); + } + + @NotNull + public static Map> byType(@NotNull List mobs) { + Map> byType = new EnumMap<>(EntityType.class); + for (KillableMob mob : mobs) { + byType.computeIfAbsent(mob.type(), _ -> new ArrayList<>()).add(mob); + } + return byType; + } + + /** + * What the death of {@code dying} counts for: every mob of the pool it matches, and the pairs it was part of, so + * killing the pillager on a ravager counts the ravager ridden by a pillager as well. + */ + @NotNull + public static List killed(@NotNull Entity dying, @NotNull Map> pool) { + List killed = new ArrayList<>(); + for (KillableMob mob : pool.getOrDefault(dying.getType(), List.of())) { + if (mob.matches(dying)) killed.add(mob); + } + List partners = new ArrayList<>(dying.getPassengers()); + if (dying.getVehicle() != null) partners.add(dying.getVehicle()); + for (Entity partner : partners) { + for (KillableMob mob : pool.getOrDefault(partner.getType(), List.of())) { + if (mob.isPair() && mob.matches(partner)) killed.add(mob); + } + } + return killed; + } + + private boolean isPair() { + return traits.stream().anyMatch(MobTrait::pairsWithAnotherMob); + } + + public boolean matches(@NotNull Entity entity) { + if (entity.getType() != type) return false; + for (MobTrait trait : traits) { + if (!trait.test().test(entity)) return false; + } + return true; + } + + /** + * {@code minecraft:zombie} or {@code minecraft:zombie[baby,riding=chicken]}, the bare type the same as before + * variants existed. + */ + @NotNull + public String id() { + String id = type.getKey().toString(); + if (traits.isEmpty()) return id; + return id + traits.stream().map(MobTrait::id).collect(Collectors.joining(",", "[", "]")); + } + + // Gamestates written before variants kept a bare type by its enum name + @NotNull + public static String normalizeId(@NotNull String id) { + return id.contains(":") ? id : "minecraft:" + id.toLowerCase(Locale.ROOT); + } + + @NotNull + public LocalizableMessage displayName() { + List args = new ArrayList<>(); + args.add(type); + for (MobTrait trait : traits) { + if (trait.label() != null) args.add(trait.label().get()); + } + if (args.size() == 1) return LocalizableMessage.wrap(type); + return MessageKey.of("challenge.generic.mob-variant." + (args.size() - 1)).withArgs(args.toArray()); + } + + @NotNull + public ItemStack icon() { + return new ItemStack(ItemUtils.getIcon(type)); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/MobTrait.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/MobTrait.java new file mode 100644 index 000000000..95c692b64 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/MobTrait.java @@ -0,0 +1,169 @@ +package net.cyperia.challenges.plugin.utils.entity; + +import net.cyperia.challenges.plugin.content.i18n.MessageKey; +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.entity.AbstractCubeMob; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.Bee; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Goat; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Mob; +import org.bukkit.entity.Raider; +import org.bukkit.entity.Shearable; +import org.bukkit.entity.Snowman; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Locale; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; + +/** + * One property a mob has to have to count as a {@link KillableMob}: the id is part of the mob's id, the label part of + * its name, {@code null} for a property the name leaves out. Labels are made on demand, as messages need the plugin. + */ +public record MobTrait(@NotNull String id, @Nullable Supplier label, @NotNull Predicate test) { + + private static final String KEY = "challenge.generic.mob-trait."; + + // Tells a grown mob apart from its baby without naming it + public static final MobTrait ADULT = new MobTrait("adult", null, entity -> !(entity instanceof Ageable ageable) || ageable.isAdult()); + public static final MobTrait BABY = flag("baby", entity -> entity instanceof Ageable ageable && !ageable.isAdult()); + public static final MobTrait LEFT_HANDED = flag("left-handed", entity -> entity instanceof Mob mob && mob.isLeftHanded()); + public static final MobTrait RIGHT_HANDED = flag("right-handed", entity -> entity instanceof Mob mob && !mob.isLeftHanded()); + public static final MobTrait CHARGED = flag("charged", entity -> entity instanceof Creeper creeper && creeper.isPowered()); + public static final MobTrait RAID_CAPTAIN = flag("raid-captain", entity -> entity instanceof Raider raider && raider.isPatrolLeader()); + public static final MobTrait SHEARED = flag("sheared", entity -> entity instanceof Shearable shearable && shearable.isSheared()); + public static final MobTrait NO_PUMPKIN = flag("no-pumpkin", entity -> entity instanceof Snowman snowman && snowman.isDerp()); + public static final MobTrait SCREAMING = flag("screaming", entity -> entity instanceof Goat goat && goat.isScreaming()); + public static final MobTrait LEFT_HORN_MISSING = flag("left-horn-missing", entity -> entity instanceof Goat goat && !goat.hasLeftHorn()); + public static final MobTrait RIGHT_HORN_MISSING = flag("right-horn-missing", entity -> entity instanceof Goat goat && !goat.hasRightHorn()); + public static final MobTrait NECTAR = flag("nectar", entity -> entity instanceof Bee bee && bee.hasNectar()); + public static final MobTrait ANGRY = flag("angry", entity -> entity instanceof Bee bee && bee.getAnger() > 0); + + // A rider or mount: the pair counts when either of the two dies + public boolean pairsWithAnotherMob() { + return id.startsWith("riding=") || id.startsWith("ridden-by="); + } + + // What the mob holds, wears or rides with, as opposed to an attribute of the mob itself + public boolean isEquipment() { + return id.startsWith("holding=") || id.startsWith("off-hand=") || id.startsWith("armor=") || pairsWithAnotherMob(); + } + + @NotNull + private static MobTrait flag(@NotNull String id, @NotNull Predicate test) { + return new MobTrait(id, () -> MessageKey.of(KEY + id), test); + } + + /** + * One value of a property every mob of the type has, like a wolf's coat: {@code challenge.generic.mob-trait..} + * names it. + */ + @NotNull + public static MobTrait property(@NotNull String group, @NotNull String value, @NotNull Predicate test) { + return property(group, value, () -> MessageKey.of(KEY + group + "." + value), test); + } + + @NotNull + public static MobTrait property(@NotNull String group, @NotNull String value, @NotNull Supplier label, @NotNull Predicate test) { + return new MobTrait(group + "=" + value, label, test); + } + + // The value is compared lower case, so registry keys and enum names both work + @NotNull + public static MobTrait property(@NotNull String group, @NotNull Class type, @NotNull Function getter, + @NotNull String value) { + return property(group, value, entity -> type.isInstance(entity) && value.equals(keyOf(getter.apply(type.cast(entity))))); + } + + @NotNull + static String keyOf(@Nullable Object value) { + if (value instanceof org.bukkit.Keyed keyed) return keyed.getKey().getKey(); + if (value instanceof Enum constant) return constant.name().toLowerCase(Locale.ROOT); + return String.valueOf(value); + } + + @NotNull + public static MobTrait holding(@NotNull Material item) { + return new MobTrait("holding=" + item.getKey().getKey(), () -> Component.translatable(item.getItemTranslationKey()), + entity -> equipment(entity) != null && equipment(entity).getItemInMainHand().getType() == item); + } + + @NotNull + public static MobTrait offHand(@NotNull Material item) { + return new MobTrait("off-hand=" + item.getKey().getKey(), () -> Component.translatable(item.getItemTranslationKey()), + entity -> equipment(entity) != null && equipment(entity).getItemInOffHand().getType() == item); + } + + /** + * Any piece of armor of one material, as mobs rarely spawn with all four. + * + * @param material the prefix of the item names, like {@code GOLDEN} + */ + @NotNull + public static MobTrait armor(@NotNull String material) { + String name = material.toLowerCase(Locale.ROOT); + return new MobTrait("armor=" + name, () -> MessageKey.of(KEY + "armor." + name), entity -> { + EntityEquipment equipment = equipment(entity); + if (equipment == null) return false; + return isPiece(equipment.getHelmet(), material, "HELMET") || isPiece(equipment.getChestplate(), material, "CHESTPLATE") + || isPiece(equipment.getLeggings(), material, "LEGGINGS") || isPiece(equipment.getBoots(), material, "BOOTS"); + }); + } + + private static boolean isPiece(@Nullable ItemStack item, @NotNull String material, @NotNull String piece) { + return item != null && item.getType().name().equals(material + "_" + piece); + } + + @NotNull + public static MobTrait riding(@NotNull EntityType vehicle) { + return new MobTrait("riding=" + vehicle.getKey().getKey(), () -> MessageKey.of(KEY + "riding").withArgs(name(vehicle)), + entity -> entity.getVehicle() != null && entity.getVehicle().getType() == vehicle); + } + + @NotNull + public static MobTrait riddenBy(@NotNull EntityType rider) { + return new MobTrait("ridden-by=" + rider.getKey().getKey(), () -> MessageKey.of(KEY + "ridden-by").withArgs(name(rider)), + entity -> entity.getPassengers().stream().anyMatch(passenger -> passenger.getType() == rider)); + } + + @NotNull + public static MobTrait riddenByCaptain(@NotNull EntityType rider) { + return new MobTrait("ridden-by=" + rider.getKey().getKey() + "+captain", () -> MessageKey.of(KEY + "ridden-by-captain").withArgs(name(rider)), + entity -> entity.getPassengers().stream().anyMatch(passenger -> passenger.getType() == rider && RAID_CAPTAIN.test().test(passenger))); + } + + // By key: the effect constants need a running server, the variant list does not + @NotNull + public static MobTrait effect(@NotNull String effect) { + return new MobTrait("effect=" + effect, () -> Component.translatable("effect.minecraft." + effect), + entity -> entity instanceof LivingEntity living + && living.getActivePotionEffects().stream().anyMatch(active -> active.getType().getKey().getKey().equals(effect))); + } + + @NotNull + public static MobTrait size(int size, @NotNull String name) { + return new MobTrait("size=" + size, () -> MessageKey.of(KEY + "size." + name), + entity -> entity instanceof AbstractCubeMob cube && cube.getSize() == size); + } + + // Without the mob icon an EntityType argument brings along, which looks out of place inside the brackets + @NotNull + private static Component name(@NotNull EntityType type) { + return Component.translatable(type.translationKey()); + } + + @Nullable + private static EntityEquipment equipment(@NotNull Entity entity) { + return entity instanceof LivingEntity living ? living.getEquipment() : null; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/MobVariants.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/MobVariants.java new file mode 100644 index 000000000..02494da89 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/entity/MobVariants.java @@ -0,0 +1,352 @@ +package net.cyperia.challenges.plugin.utils.entity; + +import net.cyperia.challenges.plugin.content.i18n.MessageKey; +import net.kyori.adventure.text.Component; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.entity.Axolotl; +import org.bukkit.entity.Cat; +import org.bukkit.entity.Chicken; +import org.bukkit.entity.CopperGolem; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fox; +import org.bukkit.entity.Frog; +import org.bukkit.entity.Horse; +import org.bukkit.entity.Llama; +import org.bukkit.entity.MushroomCow; +import org.bukkit.entity.Panda; +import org.bukkit.entity.Parrot; +import org.bukkit.entity.Pig; +import org.bukkit.entity.Rabbit; +import org.bukkit.entity.Salmon; +import org.bukkit.entity.Sheep; +import org.bukkit.entity.TropicalFish; +import org.bukkit.entity.Villager; +import org.bukkit.entity.Wolf; +import org.bukkit.entity.ZombieNautilus; +import org.bukkit.entity.ZombieVillager; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static net.cyperia.challenges.plugin.utils.entity.MobTrait.*; + +/** + * Every variant of a mob that can come up in survival, from the Minecraft wiki: coats, colours, biomes, professions, + * babies, what a mob holds or wears, what it rides. A type on its own is not one of them, see {@link KillableMob#pool}. + * A variant is about either the mob itself or its equipment and riders, never both: a mob matching both would hardly ever spawn. + */ +final class MobVariants { + + private static final List BIOMES = List.of("plains", "desert", "jungle", "savanna", "snow", "swamp", "taiga"); + private static final List PROFESSIONS = List.of("none", "armorer", "butcher", "cartographer", "cleric", "farmer", + "fisherman", "fletcher", "leatherworker", "librarian", "mason", "nitwit", "shepherd", "toolsmith", "weaponsmith"); + private static final List CLIMATES = List.of("temperate", "warm", "cold"); + private static final List ARMOR = List.of("LEATHER", "COPPER", "IRON", "CHAINMAIL", "DIAMOND", "GOLDEN"); + private static final List ZOMBIE_WEAPONS = List.of(Material.IRON_SHOVEL, Material.IRON_SWORD, Material.IRON_SPEAR); + private static final List FOX_ITEMS = List.of(Material.EMERALD, Material.RABBIT_FOOT, Material.RABBIT_HIDE, + Material.EGG, Material.WHEAT, Material.LEATHER, Material.FEATHER); + // The named tropical fish in the order of their vanilla names entity.minecraft.tropical_fish.predefined. + private static final List NAMED_FISH = List.of( + new FishLook(TropicalFish.Pattern.STRIPEY, DyeColor.ORANGE, DyeColor.GRAY), + new FishLook(TropicalFish.Pattern.FLOPPER, DyeColor.GRAY, DyeColor.GRAY), + new FishLook(TropicalFish.Pattern.FLOPPER, DyeColor.GRAY, DyeColor.BLUE), + new FishLook(TropicalFish.Pattern.CLAYFISH, DyeColor.WHITE, DyeColor.GRAY), + new FishLook(TropicalFish.Pattern.SUNSTREAK, DyeColor.BLUE, DyeColor.GRAY), + new FishLook(TropicalFish.Pattern.KOB, DyeColor.ORANGE, DyeColor.WHITE), + new FishLook(TropicalFish.Pattern.SPOTTY, DyeColor.PINK, DyeColor.LIGHT_BLUE), + new FishLook(TropicalFish.Pattern.BLOCKFISH, DyeColor.PURPLE, DyeColor.YELLOW), + new FishLook(TropicalFish.Pattern.CLAYFISH, DyeColor.WHITE, DyeColor.RED), + new FishLook(TropicalFish.Pattern.SPOTTY, DyeColor.WHITE, DyeColor.YELLOW), + new FishLook(TropicalFish.Pattern.GLITTER, DyeColor.WHITE, DyeColor.GRAY), + new FishLook(TropicalFish.Pattern.CLAYFISH, DyeColor.WHITE, DyeColor.ORANGE), + new FishLook(TropicalFish.Pattern.DASHER, DyeColor.CYAN, DyeColor.PINK), + new FishLook(TropicalFish.Pattern.BRINELY, DyeColor.LIME, DyeColor.LIGHT_BLUE), + new FishLook(TropicalFish.Pattern.BETTY, DyeColor.RED, DyeColor.WHITE), + new FishLook(TropicalFish.Pattern.SNOOPER, DyeColor.GRAY, DyeColor.RED), + new FishLook(TropicalFish.Pattern.BLOCKFISH, DyeColor.RED, DyeColor.WHITE), + new FishLook(TropicalFish.Pattern.FLOPPER, DyeColor.WHITE, DyeColor.YELLOW), + new FishLook(TropicalFish.Pattern.KOB, DyeColor.RED, DyeColor.WHITE), + new FishLook(TropicalFish.Pattern.SUNSTREAK, DyeColor.GRAY, DyeColor.WHITE), + new FishLook(TropicalFish.Pattern.DASHER, DyeColor.CYAN, DyeColor.YELLOW), + new FishLook(TropicalFish.Pattern.FLOPPER, DyeColor.YELLOW, DyeColor.YELLOW) + ); + + private record FishLook(@NotNull TropicalFish.Pattern pattern, @NotNull DyeColor body, @NotNull DyeColor patternColor) { + + boolean matches(@NotNull Entity entity) { + return entity instanceof TropicalFish fish + && fish.getPattern() == pattern && fish.getBodyColor() == body && fish.getPatternColor() == patternColor; + } + } + + // Types whose variants cover every mob of the type, so the type on its own would be found twice + private static final Set COVERED = EnumSet.of(EntityType.SALMON, EntityType.SLIME, EntityType.MAGMA_CUBE, + EntityType.SULFUR_CUBE, EntityType.COW, EntityType.PIG, EntityType.CHICKEN, EntityType.SHEEP, EntityType.MOOSHROOM, + EntityType.WOLF, EntityType.CAT, EntityType.HORSE, EntityType.LLAMA, EntityType.TRADER_LLAMA, EntityType.PARROT, + EntityType.RABBIT, EntityType.FOX, EntityType.PANDA, EntityType.AXOLOTL, EntityType.FROG, EntityType.COPPER_GOLEM, + EntityType.VILLAGER, EntityType.ZOMBIE_VILLAGER, EntityType.TROPICAL_FISH, EntityType.ZOMBIE_NAUTILUS); + + private static Map> variants; + + private MobVariants() { + } + + @NotNull + static List of(@NotNull EntityType type) { + if (variants == null) variants = load(); + return variants.getOrDefault(type, List.of()); + } + + static boolean coversEveryMob(@NotNull EntityType type) { + return COVERED.contains(type); + } + + @NotNull + static Map> load() { + Map> mobs = new EnumMap<>(EntityType.class); + + // Villagers + for (String profession : PROFESSIONS) { + for (String biome : BIOMES) { + add(mobs, EntityType.VILLAGER, ADULT, profession(profession), biome(biome)); + add(mobs, EntityType.ZOMBIE_VILLAGER, ADULT, profession(profession), biome(biome)); + } + } + for (String biome : BIOMES) { + add(mobs, EntityType.VILLAGER, BABY, biome(biome)); + add(mobs, EntityType.ZOMBIE_VILLAGER, BABY, biome(biome)); + } + add(mobs, EntityType.ZOMBIE_VILLAGER, riding(EntityType.CHICKEN)); + + // Zombies + for (EntityType zombie : List.of(EntityType.ZOMBIE, EntityType.HUSK)) { + add(mobs, zombie, BABY); + add(mobs, zombie, riding(EntityType.CHICKEN)); + add(mobs, zombie, RIGHT_HANDED); + add(mobs, zombie, LEFT_HANDED); + for (Material weapon : ZOMBIE_WEAPONS) add(mobs, zombie, holding(weapon)); + for (String armor : ARMOR) add(mobs, zombie, armor(armor)); + } + add(mobs, EntityType.DROWNED, BABY); + add(mobs, EntityType.DROWNED, RIGHT_HANDED); + add(mobs, EntityType.DROWNED, LEFT_HANDED); + add(mobs, EntityType.DROWNED, holding(Material.TRIDENT)); + add(mobs, EntityType.DROWNED, holding(Material.FISHING_ROD)); + add(mobs, EntityType.DROWNED, offHand(Material.NAUTILUS_SHELL)); + add(mobs, EntityType.ZOMBIFIED_PIGLIN, BABY); + add(mobs, EntityType.ZOMBIFIED_PIGLIN, riding(EntityType.CHICKEN)); + add(mobs, EntityType.ZOMBIFIED_PIGLIN, riding(EntityType.STRIDER)); + add(mobs, EntityType.ZOMBIFIED_PIGLIN, holding(Material.GOLDEN_SWORD)); + add(mobs, EntityType.ZOMBIFIED_PIGLIN, holding(Material.GOLDEN_SPEAR)); + + // Skeletons + for (EntityType skeleton : List.of(EntityType.SKELETON, EntityType.STRAY, EntityType.WITHER_SKELETON, EntityType.BOGGED, EntityType.PARCHED)) { + add(mobs, skeleton, RIGHT_HANDED); + add(mobs, skeleton, LEFT_HANDED); + } + for (EntityType skeleton : List.of(EntityType.SKELETON, EntityType.STRAY)) { + for (String armor : ARMOR) add(mobs, skeleton, armor(armor)); + } + add(mobs, EntityType.SKELETON, riding(EntityType.SPIDER)); + add(mobs, EntityType.BOGGED, SHEARED, RIGHT_HANDED); + add(mobs, EntityType.BOGGED, SHEARED, LEFT_HANDED); + + // Other monsters + for (String effect : List.of("speed", "strength", "regeneration", "invisibility")) add(mobs, EntityType.SPIDER, effect(effect)); + add(mobs, EntityType.SPIDER, riddenBy(EntityType.SKELETON)); + add(mobs, EntityType.CREEPER, CHARGED); + add(mobs, EntityType.EVOKER, RAID_CAPTAIN); + add(mobs, EntityType.VINDICATOR, RAID_CAPTAIN); + add(mobs, EntityType.PILLAGER, LEFT_HANDED); + add(mobs, EntityType.PILLAGER, RAID_CAPTAIN); + add(mobs, EntityType.PILLAGER, LEFT_HANDED, RAID_CAPTAIN); + for (EntityType raider : List.of(EntityType.PILLAGER, EntityType.VINDICATOR, EntityType.EVOKER)) { + add(mobs, EntityType.RAVAGER, riddenBy(raider)); + add(mobs, EntityType.RAVAGER, riddenByCaptain(raider)); + } + add(mobs, EntityType.PIGLIN, BABY); + for (Material weapon : List.of(Material.CROSSBOW, Material.GOLDEN_SWORD, Material.GOLDEN_SPEAR)) { + add(mobs, EntityType.PIGLIN, holding(weapon)); + } + add(mobs, EntityType.PIGLIN, armor("GOLDEN")); + for (EntityType cube : List.of(EntityType.SLIME, EntityType.MAGMA_CUBE)) { + add(mobs, cube, size(1, "small")); + add(mobs, cube, size(2, "medium")); + add(mobs, cube, size(4, "large")); + } + add(mobs, EntityType.SULFUR_CUBE, size(1, "small")); + add(mobs, EntityType.SULFUR_CUBE, size(2, "large")); + for (EntityType baby : List.of(EntityType.HOGLIN, EntityType.ZOGLIN)) add(mobs, baby, BABY); + + // Farm animals + for (DyeColor color : DyeColor.values()) { + String key = color.name().toLowerCase(Locale.ROOT); + MobTrait wool = property("color", key, () -> Component.translatable("color.minecraft." + key), + entity -> entity instanceof Sheep sheep && sheep.getColor() == color); + withBaby(mobs, EntityType.SHEEP, wool); + } + for (String climate : CLIMATES) { + withBaby(mobs, EntityType.COW, property("climate", climate, entity -> entity.getType() == EntityType.COW && climate.equals(keyOf(cowVariant(entity))))); + withBaby(mobs, EntityType.PIG, property("climate", Pig.class, Pig::getVariant, climate)); + withBaby(mobs, EntityType.CHICKEN, property("climate", Chicken.class, Chicken::getVariant, climate)); + add(mobs, EntityType.FROG, property("climate", Frog.class, Frog::getVariant, climate)); + } + for (String variant : List.of("red", "brown")) { + withBaby(mobs, EntityType.MOOSHROOM, property("mooshroom", MushroomCow.class, MushroomCow::getVariant, variant)); + } + + // Pets and horses + for (String variant : List.of("ashen", "black", "chestnut", "pale", "rusty", "snowy", "spotted", "striped", "woods")) { + withBaby(mobs, EntityType.WOLF, property("wolf", Wolf.class, Wolf::getVariant, variant)); + } + for (String type : List.of("all_black", "black", "british_shorthair", "calico", "jellie", "persian", "ragdoll", "red", + "siamese", "tabby", "white")) { + withBaby(mobs, EntityType.CAT, property("cat", Cat.class, Cat::getCatType, type)); + } + for (Horse.Color color : Horse.Color.values()) { + for (Horse.Style style : Horse.Style.values()) { + withBaby(mobs, EntityType.HORSE, property("horse-color", Horse.class, Horse::getColor, keyOf(color)), + property("horse-marking", Horse.class, Horse::getStyle, keyOf(style))); + } + } + for (Llama.Color color : Llama.Color.values()) { + for (EntityType llama : List.of(EntityType.LLAMA, EntityType.TRADER_LLAMA)) { + withBaby(mobs, llama, property("llama", Llama.class, Llama::getColor, keyOf(color))); + } + } + for (Parrot.Variant variant : Parrot.Variant.values()) { + add(mobs, EntityType.PARROT, property("parrot", Parrot.class, Parrot::getVariant, keyOf(variant))); + } + for (Rabbit.Type type : Rabbit.Type.values()) { + if (type == Rabbit.Type.THE_KILLER_BUNNY) continue; // only from commands + withBaby(mobs, EntityType.RABBIT, property("rabbit", Rabbit.class, Rabbit::getRabbitType, keyOf(type))); + } + + // Wild animals + for (Fox.Type type : Fox.Type.values()) { + MobTrait coat = property("fox", Fox.class, Fox::getFoxType, keyOf(type)); + add(mobs, EntityType.FOX, ADULT, coat); + add(mobs, EntityType.FOX, BABY, coat); + } + for (Material item : FOX_ITEMS) add(mobs, EntityType.FOX, holding(item)); + for (Panda.Gene gene : Panda.Gene.values()) { + withBaby(mobs, EntityType.PANDA, property("panda", Panda.class, Panda::getCombinedGene, keyOf(gene))); + } + for (Axolotl.Variant variant : Axolotl.Variant.values()) { + withBaby(mobs, EntityType.AXOLOTL, property("axolotl", Axolotl.class, Axolotl::getVariant, keyOf(variant))); + } + for (MobTrait[] state : List.of(new MobTrait[]{}, new MobTrait[]{NECTAR}, new MobTrait[]{ANGRY}, new MobTrait[]{ANGRY, NECTAR})) { + if (state.length > 0) add(mobs, EntityType.BEE, concat(ADULT, state)); + add(mobs, EntityType.BEE, concat(BABY, state)); + } + add(mobs, EntityType.GOAT, ADULT, LEFT_HORN_MISSING); + add(mobs, EntityType.GOAT, ADULT, RIGHT_HORN_MISSING); + add(mobs, EntityType.GOAT, ADULT, SCREAMING); + add(mobs, EntityType.GOAT, ADULT, SCREAMING, LEFT_HORN_MISSING); + add(mobs, EntityType.GOAT, ADULT, SCREAMING, RIGHT_HORN_MISSING); + add(mobs, EntityType.GOAT, BABY); + add(mobs, EntityType.GOAT, BABY, SCREAMING); + for (EntityType baby : List.of(EntityType.DONKEY, EntityType.MULE, EntityType.OCELOT, EntityType.POLAR_BEAR, EntityType.TURTLE, + EntityType.DOLPHIN, EntityType.SQUID, EntityType.GLOW_SQUID, EntityType.ARMADILLO, EntityType.CAMEL, EntityType.SNIFFER, + EntityType.STRIDER, EntityType.NAUTILUS, EntityType.HAPPY_GHAST)) { + add(mobs, baby, BABY); + } + add(mobs, EntityType.STRIDER, riding(EntityType.STRIDER)); + add(mobs, EntityType.CAMEL_HUSK, riddenBy(EntityType.HUSK)); + add(mobs, EntityType.CAMEL_HUSK, riddenBy(EntityType.PARCHED)); + for (String variant : List.of("temperate", "warm")) { + MobTrait shell = property("zombie-nautilus", ZombieNautilus.class, ZombieNautilus::getVariant, variant); + add(mobs, EntityType.ZOMBIE_NAUTILUS, shell); + } + add(mobs, EntityType.ZOMBIE_NAUTILUS, riddenBy(EntityType.DROWNED)); + + // Fish + for (Salmon.Variant size : Salmon.Variant.values()) { + add(mobs, EntityType.SALMON, property("size", Salmon.class, Salmon::getVariant, keyOf(size))); + } + for (TropicalFish.Pattern pattern : TropicalFish.Pattern.values()) { + add(mobs, EntityType.TROPICAL_FISH, property("pattern", keyOf(pattern), + () -> Component.translatable("entity.minecraft.tropical_fish.type." + keyOf(pattern)), + entity -> entity instanceof TropicalFish fish && fish.getPattern() == pattern)); + } + for (int i = 0; i < NAMED_FISH.size(); i++) { + FishLook look = NAMED_FISH.get(i); + int index = i; + add(mobs, EntityType.TROPICAL_FISH, property("named", String.valueOf(i), + () -> Component.translatable("entity.minecraft.tropical_fish.predefined." + index), look::matches)); + } + + // Golems + for (String state : List.of("unaffected", "exposed", "weathered", "oxidized")) { + add(mobs, EntityType.COPPER_GOLEM, property("copper", CopperGolem.class, CopperGolem::getWeatheringState, state)); + } + add(mobs, EntityType.SNOW_GOLEM, NO_PUMPKIN); + + mobs.replaceAll((_, list) -> List.copyOf(list)); + return mobs; + } + + private static void add(@NotNull Map> mobs, @NotNull EntityType type, @NotNull MobTrait... traits) { + mobs.computeIfAbsent(type, _ -> new ArrayList<>()).add(new KillableMob(type, List.of(traits))); + } + + // The grown mob and its baby, each with the traits + private static void withBaby(@NotNull Map> mobs, @NotNull EntityType type, @NotNull MobTrait... traits) { + add(mobs, type, concat(ADULT, traits)); + add(mobs, type, concat(BABY, traits)); + } + + @NotNull + private static MobTrait[] concat(@NotNull MobTrait first, @NotNull MobTrait... rest) { + return Stream.concat(Stream.of(first), Stream.of(rest)).toArray(MobTrait[]::new); + } + + @NotNull + private static MobTrait biome(@NotNull String biome) { + return property("biome", biome, entity -> biome.equals(keyOf(villagerType(entity)))); + } + + @NotNull + private static MobTrait profession(@NotNull String profession) { + Supplier label = profession.equals("none") + ? () -> MessageKey.of("challenge.generic.mob-trait.profession.none") + : () -> Component.translatable("entity.minecraft.villager." + profession); + return property("profession", profession, label, entity -> profession.equals(keyOf(villagerProfession(entity)))); + } + + // With the plugin's old api-version Paper rewrites Cow to AbstractCow, which has no variant, so it is looked up by name + @Nullable + private static Object cowVariant(@NotNull Entity entity) { + try { + return entity.getClass().getMethod("getVariant").invoke(entity); + } catch (ReflectiveOperationException ex) { + return null; + } + } + + @Nullable + private static Object villagerType(@NotNull Entity entity) { + if (entity instanceof Villager villager) return villager.getVillagerType(); + if (entity instanceof ZombieVillager zombie) return zombie.getVillagerType(); + return null; + } + + @Nullable + private static Object villagerProfession(@NotNull Entity entity) { + if (entity instanceof Villager villager) return villager.getProfession(); + if (entity instanceof ZombieVillager zombie) return zombie.getVillagerProfession(); + return null; + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/item/CollectableItem.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/item/CollectableItem.java new file mode 100644 index 000000000..e6685b53a --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/item/CollectableItem.java @@ -0,0 +1,215 @@ +package net.cyperia.challenges.plugin.utils.item; + +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import net.cyperia.challenges.plugin.content.i18n.LocalizableMessage; +import net.cyperia.challenges.plugin.content.i18n.MessageKey; +import net.cyperia.challenges.plugin.utils.misc.ExperimentalUtils; +import net.cyperia.commons.bukkit.utils.item.ItemUtils; +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * An item to find, once per material. With variants, enchanted books count once per enchantment and level + * instead, and potions, splash and lingering potions and tipped arrows once per potion type. + */ +public record CollectableItem(@NotNull Material material, @Nullable Enchantment enchantment, int level, + @Nullable PotionType potion) { + + private static final Set POTION_FORMS = EnumSet.of( + Material.POTION, Material.SPLASH_POTION, Material.LINGERING_POTION, Material.TIPPED_ARROW); + // Only obtainable through the creative inventory and commands + private static final Set UNOBTAINABLE_POTIONS = EnumSet.of(PotionType.LUCK); + + private static List obtainableInSurvival, obtainableInSurvivalWithVariants; + + @NotNull + public static CollectableItem of(@NotNull Material material) { + return new CollectableItem(material, null, 0, null); + } + + /** + * Every item that can be obtained in survival in a fixed order: the material order, with the variants of + * one material sorted by key. + */ + @NotNull + public static List obtainableInSurvival(boolean variants) { + if (variants) { + if (obtainableInSurvivalWithVariants == null) obtainableInSurvivalWithVariants = load(true); + return obtainableInSurvivalWithVariants; + } + if (obtainableInSurvival == null) obtainableInSurvival = load(false); + return obtainableInSurvival; + } + + @NotNull + private static List load(boolean variants) { + List items = new ArrayList<>(); + for (Material material : ExperimentalUtils.getMaterials()) { + if (!material.isItem() || !ItemUtils.isObtainableInSurvival(material)) continue; + if (!variants) { + items.add(of(material)); + } else if (material == Material.ENCHANTED_BOOK) { + for (Enchantment enchantment : enchantments()) { + for (int level = enchantment.getStartLevel(); level <= enchantment.getMaxLevel(); level++) { + items.add(new CollectableItem(material, enchantment, level, null)); + } + } + } else if (POTION_FORMS.contains(material)) { + for (PotionType potion : potions()) { + items.add(new CollectableItem(material, null, 0, potion)); + } + } else { + items.add(of(material)); + } + } + return List.copyOf(items); + } + + @NotNull + private static List enchantments() { + return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENCHANTMENT).stream() + .filter(enchantment -> enchantment.getKey().getNamespace().equals(NamespacedKey.MINECRAFT)) + .sorted(Comparator.comparing(enchantment -> enchantment.getKey().toString())) + .toList(); + } + + @NotNull + private static List potions() { + return EnumSet.complementOf(EnumSet.copyOf(UNOBTAINABLE_POTIONS)).stream() + .sorted(Comparator.comparing(potion -> potion.getKey().toString())) + .toList(); + } + + /** + * Every collectable item this stack counts as, with and without variants: a book with several enchantments + * counts as one book per enchantment and as a plain enchanted book. + */ + @NotNull + public static List of(@NotNull ItemStack item) { + Material material = item.getType(); + List items = new ArrayList<>(); + if (material == Material.ENCHANTED_BOOK && item.getItemMeta() instanceof EnchantmentStorageMeta meta) { + for (Map.Entry stored : meta.getStoredEnchants().entrySet()) { + items.add(new CollectableItem(material, stored.getKey(), stored.getValue(), null)); + } + } else if (POTION_FORMS.contains(material) && item.getItemMeta() instanceof PotionMeta meta && meta.getBasePotionType() != null) { + items.add(new CollectableItem(material, null, 0, meta.getBasePotionType())); + } + items.add(of(material)); + return items; + } + + public boolean matches(@NotNull ItemStack item) { + if (item.getType() != material) return false; + if (enchantment != null) { + return item.getItemMeta() instanceof EnchantmentStorageMeta meta && meta.getStoredEnchantLevel(enchantment) == level; + } + if (potion != null) { + return item.getItemMeta() instanceof PotionMeta meta && meta.getBasePotionType() == potion; + } + return true; + } + + /** + * {@code minecraft:stone}, {@code minecraft:enchanted_book[minecraft:protection=4]} or + * {@code minecraft:potion[minecraft:long_swiftness]}, read back by {@link #parse(String)}. + */ + @NotNull + public String id() { + String id = material.getKey().toString(); + if (enchantment != null) return id + "[" + enchantment.getKey() + "=" + level + "]"; + if (potion != null) return id + "[" + potion.getKey() + "]"; + return id; + } + + /** + * Reads an {@link #id()}, and the bare material names ({@code STONE}) saved before variants existed. + * + * @return {@code null} if the material, enchantment or potion is unknown to this version + */ + @Nullable + public static CollectableItem parse(@NotNull String id) { + int variantStart = id.indexOf('['); + Material material = Material.matchMaterial(variantStart < 0 ? id : id.substring(0, variantStart)); + if (material == null) return null; + if (variantStart < 0 || !id.endsWith("]")) return of(material); + + String variant = id.substring(variantStart + 1, id.length() - 1); + int levelStart = variant.lastIndexOf('='); + if (levelStart >= 0) { + NamespacedKey key = NamespacedKey.fromString(variant.substring(0, levelStart)); + Enchantment enchantment = key == null ? null : RegistryAccess.registryAccess().getRegistry(RegistryKey.ENCHANTMENT).get(key); + if (enchantment == null) return null; + try { + return new CollectableItem(material, enchantment, Integer.parseInt(variant.substring(levelStart + 1)), null); + } catch (NumberFormatException ex) { + return null; + } + } + NamespacedKey key = NamespacedKey.fromString(variant); + for (PotionType potion : PotionType.values()) { + if (potion.getKey().equals(key)) return new CollectableItem(material, null, 0, potion); + } + return null; + } + + @NotNull + public ItemStack icon() { + ItemStack icon = new ItemStack(material); + if (enchantment != null && icon.getItemMeta() instanceof EnchantmentStorageMeta meta) { + meta.addStoredEnchant(enchantment, level, true); + icon.setItemMeta(meta); + } else if (potion != null && icon.getItemMeta() instanceof PotionMeta meta) { + meta.setBasePotionType(potion); + icon.setItemMeta(meta); + } + return icon; + } + + // Translated by the viewer's own client, so the name follows their language + @NotNull + public LocalizableMessage displayName() { + if (enchantment != null) { + return MessageKey.of("challenge.generic.item-variant.enchanted-book").withArgs(material, enchantmentName()); + } + if (potion == null) return LocalizableMessage.wrap(material); + + String key = potion.getKey().getKey(); + String base = key.replaceFirst("^(long|strong)_", ""); + Component name = Component.translatable("item.minecraft." + material.getKey().getKey() + ".effect." + base); + if (key.startsWith("long_")) return MessageKey.of("challenge.generic.item-variant.long").withArgs(name); + if (key.startsWith("strong_")) return MessageKey.of("challenge.generic.item-variant.strong").withArgs(name); + return LocalizableMessage.wrap(name); + } + + // Enchantment#displayName comes coloured like item lore; this one takes the colour of the text around it + @NotNull + private Component enchantmentName() { + Component name = Component.translatable(enchantment.translationKey()); + if (enchantment.getMaxLevel() == 1) return name; + return name.append(Component.space()).append(Component.translatable("enchantment.level." + level)); + } + + @Override + public String toString() { + return id().toLowerCase(Locale.ROOT); + } + +} diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/misc/ParticleUtils.java index 37657b860..9caafb77b 100644 --- a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/misc/ParticleUtils.java @@ -1,6 +1,7 @@ package net.cyperia.challenges.plugin.utils.misc; import net.cyperia.commons.bukkit.utils.logging.Logger; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.common.collection.IRandom; import org.bukkit.*; import org.bukkit.entity.Entity; @@ -47,7 +48,7 @@ private static void spawnParticleCylinder(@NotNull JavaPlugin plugin, @NotNull L @NotNull BiConsumer playParticle) { for (double y = 0, i = 0; y < height; y += cylinderParticleVerticalStep, i++) { final double Y = y; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + Regions.later(plugin, location, () -> { spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, playParticle); }, (long) i); } @@ -78,7 +79,7 @@ public static void spawnParticleCylinder(@NotNull JavaPlugin plugin, @NotNull Lo for (double y = 0, i = 0; y < height; y += .25, i++) { final double Y = y; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> spawnParticleCircle( + Regions.later(plugin, location, () -> spawnParticleCircle( location.clone().add(0, Y, 0), points, radius, (world, loc) -> doSpawnParticleWithData(loc, particle, 1, overrideColor) ), (long) i); diff --git a/plugin/src/main/java/net/cyperia/challenges/plugin/utils/misc/VariantIds.java b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/misc/VariantIds.java new file mode 100644 index 000000000..b8474ba71 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/challenges/plugin/utils/misc/VariantIds.java @@ -0,0 +1,57 @@ +package net.cyperia.challenges.plugin.utils.misc; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; + +/** + * Ids of item and mob variants are their base id with the variant parts in brackets, like + * {@code minecraft:zombie[baby,holding=iron_sword]}. A find of a variant counts for every less specific id of the + * same base as well: the base itself and every variant made of some of its parts. + */ +public final class VariantIds { + + private VariantIds() { + } + + // The base id, which is the whole id for one without variant parts + @NotNull + public static String baseOf(@NotNull String id) { + int variantStart = id.indexOf('['); + return variantStart < 0 ? id : id.substring(0, variantStart); + } + + public static boolean covers(@NotNull String found, @NotNull String target) { + if (found.equals(target) || !baseOf(found).equals(baseOf(target))) return false; + return parts(found).containsAll(parts(target)); + } + + /** + * Calls {@code action} with every id of {@code found} and each other id of {@code pool} it {@link #covers covers}. + */ + public static void forEachCovered(@NotNull Collection found, @NotNull Collection pool, + @NotNull BiConsumer action) { + Map> poolByBase = new HashMap<>(); + for (String id : pool) poolByBase.computeIfAbsent(baseOf(id), _ -> new ArrayList<>()).add(id); + for (String id : List.copyOf(found)) { + for (String target : poolByBase.getOrDefault(baseOf(id), List.of())) { + if (covers(id, target)) action.accept(id, target); + } + } + } + + @NotNull + private static Set parts(@NotNull String id) { + int variantStart = id.indexOf('['); + if (variantStart < 0 || !id.endsWith("]")) return Set.of(); + return Set.of(id.substring(variantStart + 1, id.length() - 1).split(",")); + } + +} diff --git a/plugin/src/main/java/net/cyperia/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/cyperia/commons/bukkit/core/BukkitModule.java index c2810369e..441fd48df 100644 --- a/plugin/src/main/java/net/cyperia/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/cyperia/commons/bukkit/core/BukkitModule.java @@ -4,6 +4,7 @@ import net.cyperia.commons.bukkit.utils.menu.MenuPosition; import net.cyperia.commons.bukkit.utils.menu.MenuPositionListener; import net.cyperia.commons.bukkit.utils.misc.MinecraftVersion; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.cyperia.commons.bukkit.utils.wrapper.ActionListener; import net.cyperia.commons.bukkit.utils.wrapper.SimpleEventExecutor; import net.cyperia.commons.common.annotations.ReplaceWith; @@ -111,7 +112,7 @@ public void onJoin(@NotNull PlayerJoinEvent event) { } if (!versionSupported) { // Paper runs the tasks scheduled during startup right before "Done", so the warning is repeated at the end of the startup log - getServer().getScheduler().runTask(this, () -> new RequirementsChecker(this).checkVersion(getPluginDocument().getDocument("require"))); + Regions.nextTick(this, () -> new RequirementsChecker(this).checkVersion(getPluginDocument().getDocument("require"))); } listenersQueue.forEach(this::registerListener); @@ -141,7 +142,9 @@ public final void onDisable() { if (executorService != null) executorService.shutdown(); + // No task can be scheduled anymore, so only the players this thread owns are closed for (Player player : Bukkit.getOnlinePlayers()) { + if (!Bukkit.isOwnedByCurrentRegion(player)) continue; if (player.getOpenInventory().getTopInventory().getHolder() == MenuPosition.HOLDER) player.getOpenInventory().close(); } diff --git a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/animation/AnimatedInventory.java b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/animation/AnimatedInventory.java index 953ce50f0..8876f0295 100644 --- a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/animation/AnimatedInventory.java +++ b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/animation/AnimatedInventory.java @@ -1,6 +1,7 @@ package net.cyperia.commons.bukkit.utils.animation; import net.cyperia.commons.bukkit.core.BukkitModule; +import net.cyperia.commons.bukkit.utils.misc.Regions; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -48,17 +49,16 @@ public void open(@NotNull Player player) { } public void open(@NotNull Player player, @NotNull JavaPlugin plugin) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(plugin, () -> open(player, plugin)); - return; - } + Regions.entity(plugin, player, () -> openOnOwnThread(player, plugin)); + } + private void openOnOwnThread(@NotNull Player player, @NotNull JavaPlugin plugin) { Inventory inventory = createInventory(); applyFrame(inventory, 0, player); player.openInventory(inventory); AtomicInteger index = new AtomicInteger(1); - Bukkit.getScheduler().runTaskTimer(plugin, task -> { + Regions.timer(plugin, player, task -> { boolean opened = inventory.getViewers().contains(player); if (index.get() >= frames.size() || !opened) { @@ -79,22 +79,18 @@ public void openNotAnimated(@NotNull Player player, boolean playSound) { } public void openNotAnimated(@NotNull Player player, boolean playSound, @NotNull JavaPlugin plugin) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(plugin, () -> openNotAnimated(player, playSound, plugin)); - return; - } - - Inventory inventory = createInventory(); + Regions.entity(plugin, player, () -> { + Inventory inventory = createInventory(); - if (!frames.isEmpty()) { - AnimationFrame frame = getLastFrame(); - inventory.setContents(frame.getContent()); - } - - player.openInventory(inventory); + if (!frames.isEmpty()) { + AnimationFrame frame = getLastFrame(); + inventory.setContents(frame.getContent()); + } - if (playSound && endSound != null) endSound.play(player); + player.openInventory(inventory); + if (playSound && endSound != null) endSound.play(player); + }); } private void applyFrame(@NotNull Inventory inventory, int index, @NotNull Player viewer) { diff --git a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/bstats/Metrics.java b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/bstats/Metrics.java index 0d0abf19f..7348c3f0d 100644 --- a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/bstats/Metrics.java +++ b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/bstats/Metrics.java @@ -1,6 +1,7 @@ package net.cyperia.commons.bukkit.utils.bstats; import net.cyperia.commons.bukkit.utils.bstats.chart.CustomChart; +import net.cyperia.commons.bukkit.utils.misc.Regions; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; @@ -74,7 +75,7 @@ public Metrics(JavaPlugin plugin, int serviceId) { true, this::appendPlatformData, this::appendServiceData, - submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + submitDataTask -> Regions.nextTick(plugin, submitDataTask), plugin::isEnabled, (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), (message) -> this.plugin.getLogger().log(Level.INFO, message), diff --git a/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java new file mode 100644 index 000000000..c468cd653 --- /dev/null +++ b/plugin/src/main/java/net/cyperia/commons/bukkit/utils/misc/Regions.java @@ -0,0 +1,196 @@ +package net.cyperia.commons.bukkit.utils.misc; + +import io.papermc.paper.threadedregions.scheduler.ScheduledTask; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Level; +import java.util.stream.Collectors; +import java.util.function.Consumer; + +/** + * Runs code on the thread that owns what it touches. On Paper and Purpur every check is true on the + * main thread, so the immediate variants run inline exactly as the code did before regionised servers. + * A retired entity runs neither the task nor its scheduler's retired callback when the schedule call + * reports it, so the retired fallback is run here. Once the plugin is disabled nothing can be scheduled: + * a task then only runs when the calling thread owns its target, otherwise it is dropped. + */ +public final class Regions { + + // Only Folia based servers have a regionised server + private static final boolean REGIONIZED = isClassPresent("io.papermc.paper.threadedregions.RegionizedServer"); + + private Regions() { + } + + private static boolean isClassPresent(@NotNull String name) { + try { + Class.forName(name, false, Regions.class.getClassLoader()); + return true; + } catch (ClassNotFoundException ex) { + return false; + } + } + + public static void global(@NotNull Plugin plugin, @NotNull Runnable task) { + // A regionised server halts the global scheduler before it disables plugins on its shutdown thread + if (Bukkit.isGlobalTickThread() || (Bukkit.isPrimaryThread() && Bukkit.isStopping())) task.run(); + else if (plugin.isEnabled()) Bukkit.getGlobalRegionScheduler().execute(plugin, task); + } + + public static void entity(@NotNull Plugin plugin, @NotNull Entity entity, @NotNull Runnable task) { + entity(plugin, entity, task, null); + } + + public static void entity(@NotNull Plugin plugin, @NotNull Entity entity, @NotNull Runnable task, @Nullable Runnable retired) { + if (Bukkit.isOwnedByCurrentRegion(entity)) task.run(); + else if (!plugin.isEnabled() || !entity.getScheduler().execute(plugin, task, retired, 1)) { + if (retired != null) retired.run(); + } + } + + public static void at(@NotNull Plugin plugin, @NotNull Location location, @NotNull Runnable task) { + if (Bukkit.isOwnedByCurrentRegion(location)) task.run(); + else if (plugin.isEnabled()) Bukkit.getRegionScheduler().execute(plugin, location, task); + } + + /** + * Runs {@code scan} once in every region that has a player in {@code world}, for scans over + * {@code World#getEntities()} and the like, which only see the entities of the calling region. + * The future completes on the global region once every region is done. Regions without a player are + * not visited. On Paper and Purpur this is one scan of the whole world. + */ + @NotNull + public static CompletableFuture forEachRegion(@NotNull Plugin plugin, @NotNull World world, @NotNull Runnable scan) { + CompletableFuture done = new CompletableFuture<>(); + global(plugin, () -> { + if (!plugin.isEnabled()) { + runScan(plugin, world, scan); + done.complete(null); + return; + } + + List players = Bukkit.getOnlinePlayers().stream().filter(player -> player.getWorld() == world).collect(Collectors.toList()); + if (players.isEmpty()) { + if (!REGIONIZED) runScan(plugin, world, scan); + done.complete(null); + return; + } + + List claimed = new CopyOnWriteArrayList<>(); + AtomicInteger remaining = new AtomicInteger(players.size()); + Runnable finished = () -> { + if (remaining.decrementAndGet() == 0) global(plugin, () -> done.complete(null)); + }; + for (Player player : players) { + entity(plugin, player, () -> { + try { + if (claim(claimed, player)) runScan(plugin, world, scan); + } finally { + finished.run(); + } + }, finished); + } + }); + return done; + } + + // Players standing in one region run one after another, so the first claims the region for the others + private static boolean claim(@NotNull List claimed, @NotNull Player player) { + for (Location other : claimed) { + if (Bukkit.isOwnedByCurrentRegion(other)) return false; + } + claimed.add(player.getLocation()); + return true; + } + + private static void runScan(@NotNull Plugin plugin, @NotNull World world, @NotNull Runnable scan) { + try { + scan.run(); + } catch (RuntimeException ex) { + plugin.getLogger().log(Level.SEVERE, "A scan of world " + world.getName() + " failed", ex); + } + } + + public static boolean isGlobalThread() { + return Bukkit.isGlobalTickThread(); + } + + @NotNull + public static ScheduledTask nextTick(@NotNull Plugin plugin, @NotNull Runnable task) { + return Bukkit.getGlobalRegionScheduler().run(plugin, _ -> task.run()); + } + + @NotNull + public static ScheduledTask later(@NotNull Plugin plugin, @NotNull Runnable task, long delayTicks) { + if (delayTicks < 1) return nextTick(plugin, task); + return Bukkit.getGlobalRegionScheduler().runDelayed(plugin, _ -> task.run(), delayTicks); + } + + @NotNull + public static ScheduledTask timer(@NotNull Plugin plugin, @NotNull Consumer task, long delayTicks, long periodTicks) { + return Bukkit.getGlobalRegionScheduler().runAtFixedRate(plugin, task, Math.max(delayTicks, 1), periodTicks); + } + + // Null when the entity is gone before the task could be queued + @Nullable + public static ScheduledTask nextTick(@NotNull Plugin plugin, @NotNull Entity entity, @NotNull Runnable task) { + return entity.getScheduler().run(plugin, _ -> task.run(), null); + } + + @Nullable + public static ScheduledTask later(@NotNull Plugin plugin, @NotNull Entity entity, @NotNull Runnable task, long delayTicks) { + if (delayTicks < 1) return nextTick(plugin, entity, task); + return entity.getScheduler().runDelayed(plugin, _ -> task.run(), null, delayTicks); + } + + @Nullable + public static ScheduledTask timer(@NotNull Plugin plugin, @NotNull Entity entity, @NotNull Consumer task, long delayTicks, long periodTicks) { + return entity.getScheduler().runAtFixedRate(plugin, task, null, Math.max(delayTicks, 1), periodTicks); + } + + @NotNull + public static ScheduledTask nextTick(@NotNull Plugin plugin, @NotNull Location location, @NotNull Runnable task) { + return Bukkit.getRegionScheduler().run(plugin, location, _ -> task.run()); + } + + @NotNull + public static ScheduledTask later(@NotNull Plugin plugin, @NotNull Location location, @NotNull Runnable task, long delayTicks) { + if (delayTicks < 1) return nextTick(plugin, location, task); + return Bukkit.getRegionScheduler().runDelayed(plugin, location, _ -> task.run(), delayTicks); + } + + @NotNull + public static ScheduledTask timer(@NotNull Plugin plugin, @NotNull Location location, @NotNull Consumer task, long delayTicks, long periodTicks) { + return Bukkit.getRegionScheduler().runAtFixedRate(plugin, location, task, Math.max(delayTicks, 1), periodTicks); + } + + public static void async(@NotNull Plugin plugin, @NotNull Runnable task) { + Bukkit.getAsyncScheduler().runNow(plugin, _ -> task.run()); + } + + @NotNull + public static ScheduledTask asyncLater(@NotNull Plugin plugin, @NotNull Runnable task, long delayTicks) { + if (delayTicks < 1) { + return Bukkit.getAsyncScheduler().runNow(plugin, _ -> task.run()); + } + return Bukkit.getAsyncScheduler().runDelayed(plugin, _ -> task.run(), delayTicks * 50, TimeUnit.MILLISECONDS); + } + + @NotNull + public static ScheduledTask asyncTimer(@NotNull Plugin plugin, @NotNull Consumer task, long delayTicks, long periodTicks) { + return Bukkit.getAsyncScheduler().runAtFixedRate(plugin, task, Math.max(delayTicks, 1) * 50, periodTicks * 50, TimeUnit.MILLISECONDS); + } + +} diff --git a/plugin/src/main/java/net/cyperia/commons/common/config/Document.java b/plugin/src/main/java/net/cyperia/commons/common/config/Document.java index dbabbc508..061ef14f7 100644 --- a/plugin/src/main/java/net/cyperia/commons/common/config/Document.java +++ b/plugin/src/main/java/net/cyperia/commons/common/config/Document.java @@ -15,7 +15,10 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; @@ -163,19 +166,23 @@ default Document setIfAbsent(@NotNull String path, @NotNull Object defaultValue) void write(@NotNull Writer writer) throws IOException; default void saveToFile(@NotNull File file) throws IOException { - FileUtils.createFilesIfNecessary(file); - Writer writer = FileUtils.newBufferedWriter(file); - write(writer); - writer.flush(); - writer.close(); + saveToFile(file.toPath()); } + // Written next to the file and moved over it, so a server killed mid-write keeps the previous file default void saveToFile(@NotNull Path file) throws IOException { - FileUtils.createFile(file); - Writer writer = FileUtils.newBufferedWriter(file); - write(writer); - writer.flush(); - writer.close(); + Path target = file.toAbsolutePath(); + Files.createDirectories(target.getParent()); + // Not Files.createTempFile, which creates the file readable by its owner only + Path temp = target.resolveSibling(target.getFileName() + "." + UUID.randomUUID() + ".tmp"); + try { + try (Writer writer = Files.newBufferedWriter(temp, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { + write(writer); + } + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } finally { + Files.deleteIfExists(temp); + } } @NotNull diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index 7f808cdff..65d79d45a 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -84,9 +84,6 @@ custom-challenge-settings: # These can be edited in the corresponding language file join-quit-messages: true -# Shows every player the plugin credits when they join - the same lines /help prints -plugin-info-on-join: true - # Send players a permission info message when they join the server when noone with the permission 'challenges.command.challenges' has joined before permission-info: true diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index 5d6c42902..b13e98dd9 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -45,3 +45,4 @@ permissions: default: true challenges.command.guess: default: true +canvas-supported: true diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoalTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoalTest.java index fab1e5060..316af83d2 100644 --- a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoalTest.java +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoalTest.java @@ -1,5 +1,6 @@ package net.cyperia.challenges.plugin.challenges.implementation.goal; +import net.cyperia.challenges.plugin.utils.item.CollectableItem; import org.bukkit.Material; import org.junit.jupiter.api.Test; @@ -11,16 +12,25 @@ class CollectAllItemsGoalTest { @Test void legacyListIsSortedIntoTheSeededOrder() { - List seededOrder = List.of(Material.DIRT, Material.STONE, Material.OAK_LOG, Material.DIAMOND); + List seededOrder = List.of(CollectableItem.of(Material.DIRT), CollectableItem.of(Material.STONE), + CollectableItem.of(Material.OAK_LOG), CollectableItem.of(Material.DIAMOND)); - assertEquals(List.of("DIRT", "STONE", "DIAMOND"), - CollectAllItemsGoal.sortBySeededOrder(List.of("DIAMOND", "DIRT", "STONE"), seededOrder)); + assertEquals(List.of("minecraft:dirt", "minecraft:stone", "minecraft:diamond"), + CollectAllItemsGoal.sortBySeededOrder(List.of("minecraft:diamond", "minecraft:dirt", "minecraft:stone"), seededOrder)); } @Test - void namesMissingFromTheSeededOrderComeFirst() { - assertEquals(List.of("REMOVED_ITEM", "DIRT", "STONE"), - CollectAllItemsGoal.sortBySeededOrder(List.of("STONE", "REMOVED_ITEM", "DIRT"), List.of(Material.DIRT, Material.STONE))); + void idsMissingFromTheSeededOrderComeFirst() { + assertEquals(List.of("REMOVED_ITEM", "minecraft:dirt", "minecraft:stone"), + CollectAllItemsGoal.sortBySeededOrder(List.of("minecraft:stone", "REMOVED_ITEM", "minecraft:dirt"), + List.of(CollectableItem.of(Material.DIRT), CollectableItem.of(Material.STONE)))); + } + + @Test + void legacyMaterialNamesBecomeIds() { + assertEquals("minecraft:stone", CollectAllItemsGoal.normalizeId("STONE")); + assertEquals("minecraft:stone", CollectAllItemsGoal.normalizeId("minecraft:stone")); + assertEquals("REMOVED_ITEM", CollectAllItemsGoal.normalizeId("REMOVED_ITEM")); } } diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/EntryAccessTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/EntryAccessTest.java new file mode 100644 index 000000000..4f8b5816f --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/EntryAccessTest.java @@ -0,0 +1,61 @@ +package net.cyperia.challenges.plugin.challenges.type; + +import net.cyperia.challenges.catalog.Challenge; +import net.cyperia.challenges.catalog.Definition; +import net.cyperia.challenges.catalog.Icon; +import net.cyperia.challenges.catalog.Release; +import org.bukkit.permissions.Permissible; +import org.junit.jupiter.api.Test; + + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class EntryAccessTest { + + private static final String PERMISSION = "challenges.play.test"; + + @Test + void anEntryWithoutPermissionIsOpenToEveryone() { + Challenge open = entry(null, false); + Permissible player = mock(Permissible.class); + + assertFalse(EntryAccess.isLocked(open, player)); + assertTrue(EntryAccess.isListed(open, player)); + } + + @Test + void anEntryIsLockedWithoutItsPermission() { + Challenge gated = entry(PERMISSION, false); + + assertTrue(EntryAccess.isLocked(gated, mock(Permissible.class))); + assertFalse(EntryAccess.isLocked(gated, withPermission())); + } + + @Test + void aLockedEntryIsStillListedUnlessHidden() { + Permissible player = mock(Permissible.class); + + assertTrue(EntryAccess.isListed(entry(PERMISSION, false), player)); + assertFalse(EntryAccess.isListed(entry(PERMISSION, true), player)); + } + + @Test + void aHiddenEntryIsListedForWhoHasThePermission() { + assertTrue(EntryAccess.isListed(entry(PERMISSION, true), withPermission())); + } + + private static Permissible withPermission() { + Permissible player = mock(Permissible.class); + when(player.hasPermission(PERMISSION)).thenReturn(true); + return player; + } + + private static Challenge entry(String permission, boolean hidden) { + return new Challenge("test", java.util.List.of(), "test", "misc_goal", new Icon("STONE", null), + new Definition.Implementation("Test", null), null, false, false, true, new Release(null, null, false), permission, hidden); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/ReleaseInfoTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/ReleaseInfoTest.java new file mode 100644 index 000000000..10f5e85df --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/ReleaseInfoTest.java @@ -0,0 +1,34 @@ +package net.cyperia.challenges.plugin.challenges.type; + +import net.cyperia.challenges.catalog.Release; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ReleaseInfoTest { + + @Test + void newerSubSettingUpdatesTheSetting() { + assertEquals(new Release("2.0", "3.1", false), ReleaseInfo.withSubSettings(new Release("2.0", null, false), "3.1")); + assertEquals(new Release("2.0", "3.1", false), ReleaseInfo.withSubSettings(new Release("2.0", "3.0", false), "3.1")); + } + + @Test + void subSettingOfTheSameReleaseIsNoUpdate() { + Release release = new Release("3.1", null, false); + assertEquals(release, ReleaseInfo.withSubSettings(release, "3.1")); + } + + @Test + void laterOwnUpdateStays() { + Release release = new Release("2.0", "3.2", false); + assertEquals(release, ReleaseInfo.withSubSettings(release, "3.1")); + } + + @Test + void withoutVersionedSubSettingsTheReleaseStays() { + Release release = new Release("2.0", null, true); + assertEquals(release, ReleaseInfo.withSubSettings(release, null)); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboardTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboardTest.java new file mode 100644 index 000000000..b2b30e0b5 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/challenges/type/helper/GoalLeaderboardTest.java @@ -0,0 +1,37 @@ +package net.cyperia.challenges.plugin.challenges.type.helper; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static net.cyperia.challenges.plugin.challenges.type.helper.GoalLeaderboard.SKIPPED; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GoalLeaderboardTest { + + @Test + void aViewerAtTheTopSeesTheWholeRun() { + assertEquals(List.of(0, 1, 2, 3, 4, 5, 6, 7), GoalLeaderboard.sidebarRows(20, 2, 5, 1)); + } + + @Test + void anUnrankedViewerSeesTheTop() { + assertEquals(List.of(0, 1, 2), GoalLeaderboard.sidebarRows(3, -1, 5, 1)); + } + + @Test + void aViewerJustBelowTheTopGetsNoGapOfOneLine() { + assertEquals(List.of(0, 1, 2, 3, 4, 5, 6, 7), GoalLeaderboard.sidebarRows(20, 6, 5, 1)); + } + + @Test + void aViewerFurtherDownSeesTheTopAndTheirNeighbours() { + assertEquals(List.of(0, 1, 2, 3, 4, SKIPPED, 11, 12, 13), GoalLeaderboard.sidebarRows(20, 12, 5, 1)); + } + + @Test + void theLastPlaceHasNobodyBelow() { + assertEquals(List.of(0, 1, 2, 3, 4, SKIPPED, 18, 19), GoalLeaderboard.sidebarRows(20, 19, 5, 1)); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java new file mode 100644 index 000000000..0fa0068df --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/menu/generator/impl/goal/GoalChecklistViewTest.java @@ -0,0 +1,62 @@ +package net.cyperia.challenges.plugin.management.menu.generator.impl.goal; + +import net.cyperia.challenges.plugin.challenges.type.ChecklistGoal.ChecklistEntry; +import org.bukkit.inventory.ItemStack; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GoalChecklistViewTest { + + private static final UUID ANNA = UUID.randomUUID(); + private static final UUID BEN = UUID.randomUUID(); + private static final Map NAMES = Map.of(ANNA, "anna", BEN, "Ben"); + + private static final ChecklistEntry MISSING = entry("missing", false, List.of(), null); + private static final ChecklistEntry EARLY_BY_BEN = entry("early", true, List.of(BEN), 10L); + private static final ChecklistEntry LATE_BY_ANNA = entry("late", true, List.of(ANNA), 20L); + private static final ChecklistEntry SKIPPED = entry("skipped", true, List.of(), 15L); + private static final List ENTRIES = List.of(EARLY_BY_BEN, MISSING, LATE_BY_ANNA, SKIPPED); + + private static ChecklistEntry entry(String name, boolean done, List finders, Long foundAt) { + return new ChecklistEntry(name, Mockito.mock(ItemStack.class), done, finders, foundAt); + } + + private static List apply(GoalChecklistView.Filter filter, GoalChecklistView.Sort sort, boolean descending) { + return new GoalChecklistView(filter, sort, descending).apply(ENTRIES, NAMES::get); + } + + @Test + void defaultKeepsTheGoalOrderWithMissingFirst() { + assertEquals(List.of(MISSING, EARLY_BY_BEN, LATE_BY_ANNA, SKIPPED), + apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.DEFAULT, false)); + assertEquals(List.of(EARLY_BY_BEN, LATE_BY_ANNA, SKIPPED, MISSING), + apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.DEFAULT, true)); + } + + @Test + void filtersMissingAndFound() { + assertEquals(List.of(MISSING), apply(GoalChecklistView.Filter.MISSING, GoalChecklistView.Sort.DEFAULT, false)); + assertEquals(List.of(EARLY_BY_BEN, LATE_BY_ANNA, SKIPPED), apply(GoalChecklistView.Filter.FOUND, GoalChecklistView.Sort.DEFAULT, false)); + } + + @Test + void sortsByTimeWithEntriesWithoutTimeLastInBothDirections() { + assertEquals(List.of(EARLY_BY_BEN, SKIPPED, LATE_BY_ANNA, MISSING), + apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.TIME, false)); + assertEquals(List.of(LATE_BY_ANNA, SKIPPED, EARLY_BY_BEN, MISSING), + apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.TIME, true)); + } + + @Test + void sortsByFinderNameIgnoringCase() { + assertEquals(List.of(LATE_BY_ANNA, EARLY_BY_BEN, MISSING, SKIPPED), + apply(GoalChecklistView.Filter.ALL, GoalChecklistView.Sort.FINDER, false)); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/scheduler/TaskExecutorThreadTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/scheduler/TaskExecutorThreadTest.java new file mode 100644 index 000000000..ddda27ae5 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/scheduler/TaskExecutorThreadTest.java @@ -0,0 +1,111 @@ +package net.cyperia.challenges.plugin.management.scheduler; + +import io.papermc.paper.threadedregions.scheduler.AsyncScheduler; +import io.papermc.paper.threadedregions.scheduler.GlobalRegionScheduler; +import net.cyperia.challenges.plugin.management.scheduler.timer.TimerStatus; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import java.util.concurrent.TimeUnit; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class TaskExecutorThreadTest { + + private final Plugin plugin = mock(Plugin.class); + private final GlobalRegionScheduler global = mock(GlobalRegionScheduler.class); + private final AsyncScheduler async = mock(AsyncScheduler.class); + private MockedStatic bukkit; + + @BeforeEach + void mockServer() { + bukkit = org.mockito.Mockito.mockStatic(Bukkit.class); + bukkit.when(Bukkit::getGlobalRegionScheduler).thenReturn(global); + bukkit.when(Bukkit::getAsyncScheduler).thenReturn(async); + when(plugin.isEnabled()).thenReturn(true); + } + + @AfterEach + void closeServer() { + bukkit.close(); + } + + @Test + void syncScheduledTask_ticksOnTheGlobalRegionStartingAtTheNextTick() { + new ScheduledTaskExecutor(plugin, new ScheduledTaskConfig(20, false)).start(); + + verify(global).runAtFixedRate(eq(plugin), any(), eq(1L), eq(20L)); + verify(async, never()).runAtFixedRate(any(), any(), org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), any()); + } + + @Test + void asyncScheduledTask_ticksOnTheAsyncSchedulerWithTheSameRate() { + new ScheduledTaskExecutor(plugin, new ScheduledTaskConfig(20, true)).start(); + + verify(async).runAtFixedRate(eq(plugin), any(), eq(50L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + verify(global, never()).runAtFixedRate(any(), any(), org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong()); + } + + @Test + void stop_cancelsTheRunningTask() { + io.papermc.paper.threadedregions.scheduler.ScheduledTask running = mock(io.papermc.paper.threadedregions.scheduler.ScheduledTask.class); + when(global.runAtFixedRate(any(), any(), org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(running); + ScheduledTaskExecutor executor = new ScheduledTaskExecutor(plugin, new ScheduledTaskConfig(20, false)); + executor.start(); + + executor.stop(); + + verify(running).cancel(); + } + + @Test + void syncTimerTask_runsInlineOnTheGlobalThread() { + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(true); + TimerTaskExecutor executor = executor(false); + + executor.execute(); + + verify(executor).run(); + verify(global, never()).execute(any(), any()); + } + + @Test + void syncTimerTask_hopsToTheGlobalRegionFromAnyOtherThread() { + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(false); + TimerTaskExecutor executor = executor(false); + + executor.execute(); + + verify(executor, never()).run(); + verify(global).execute(plugin, executor); + } + + @Test + void asyncTimerTask_alwaysGoesToTheAsyncScheduler() { + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(true); + TimerTaskExecutor executor = executor(true); + + executor.execute(); + + verify(async).runNow(eq(plugin), any()); + verify(executor, never()).run(); + } + + private TimerTaskExecutor executor(boolean async) { + TimerTaskExecutor executor = spy(new TimerTaskExecutor(plugin, new TimerTaskConfig(new TimerStatus[]{TimerStatus.RUNNING}, async))); + doNothing().when(executor).run(); + return executor; + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java index de9ce87a2..f09541947 100644 --- a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/BorderManagerTest.java @@ -100,7 +100,7 @@ void aPlayerOutsideIsPutJustInsideWhereTheyCrossed() { border.teleportInside(player); ArgumentCaptor target = ArgumentCaptor.forClass(Location.class); - verify(player).teleport(target.capture()); + verify(player).teleportAsync(target.capture()); // a size of 10 around 0.5 is drawn up to 5.5, and half the player's width stays clear of it assertEquals(5.2, target.getValue().getX(), 1e-9); assertEquals(2, target.getValue().getZ(), 1e-9); @@ -127,7 +127,7 @@ void overTheVoidAPlayerIsPutOnTheCenterInstead() { border.teleportInside(player); ArgumentCaptor target = ArgumentCaptor.forClass(Location.class); - verify(player).teleport(target.capture()); + verify(player).teleportAsync(target.capture()); assertEquals(0.5, target.getValue().getX(), 1e-9); assertEquals(0.5, target.getValue().getZ(), 1e-9); } diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/scoreboard/ScoreboardFooterTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/scoreboard/ScoreboardFooterTest.java new file mode 100644 index 000000000..f8b8d2e7f --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/management/server/scoreboard/ScoreboardFooterTest.java @@ -0,0 +1,38 @@ +package net.cyperia.challenges.plugin.management.server.scoreboard; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.TextDecoration; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ScoreboardFooterTest { + + @Test + void textIsMeasuredPerGlyph() { + assertEquals(6 + 2 + 3, MinecraftFont.widthOf(Component.text("a.l"))); + } + + @Test + void boldAddsAPixelPerGlyphAndIsInherited() { + Component bold = Component.text("a").decorate(TextDecoration.BOLD).append(Component.text("b")); + assertEquals(7 + 7, MinecraftFont.widthOf(bold)); + } + + @Test + void theFooterIsPaddedToTheMiddleOfTheWidestLine() { + Component title = Component.text("x".repeat(20)); // 120 px + Component footer = Component.text("y".repeat(10)); // 60 px, 30 px either side + Component centered = ChallengeScoreboard.centered(footer, title, List.of(Component.text("short"))); + assertEquals(Component.text(" ".repeat(7)).append(footer), centered); + } + + @Test + void aFooterWiderThanEveryLineStaysAsItIs() { + Component footer = Component.text("y".repeat(10)); + assertEquals(footer, ChallengeScoreboard.centered(footer, Component.text("x"), List.of())); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java index 56bb7a2c4..01f5ecaed 100644 --- a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/command/CommandTreesTest.java @@ -119,6 +119,15 @@ void genericCommandsAreTheOnesANetworkToolboxProvides() { assertFalse(new BackCommand().info().isGeneric()); } + @Test + void goalSkipNeedsItsOwnPermission() { + register(new GoalCommand()); + + assertTrue(runs("goal", senderWith(ChallengesPermissions.COMMAND_GOAL))); + assertFalse(runs("goal skip", senderWith(ChallengesPermissions.COMMAND_GOAL))); + assertTrue(runs("goal skip", senderWith(ChallengesPermissions.COMMAND_GOAL, ChallengesPermissions.COMMAND_GOAL_SKIP))); + } + @Test void resetConfirmWorksWithAndWithoutTheConfirmStep() { CommandSender sender = senderWith(ChallengesPermissions.COMMAND_RESET); diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/region/BukkitRespawnPortalAdapterTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/region/BukkitRespawnPortalAdapterTest.java new file mode 100644 index 000000000..784a1efef --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/region/BukkitRespawnPortalAdapterTest.java @@ -0,0 +1,237 @@ +package net.cyperia.challenges.plugin.spigot.region; + +import com.destroystokyo.paper.event.player.PlayerPostRespawnEvent; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnLocationEvent; +import net.cyperia.challenges.plugin.spigot.events.PlayerRespawnedEvent; +import io.papermc.paper.threadedregions.scheduler.EntityScheduler; +import io.papermc.paper.threadedregions.scheduler.ScheduledTask; +import net.cyperia.challenges.plugin.spigot.events.PortalArrivedEvent; +import net.cyperia.challenges.plugin.spigot.events.PortalTravelEvent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.PortalType; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityPortalEvent; +import org.bukkit.event.player.PlayerPortalEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.plugin.PluginManager; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class BukkitRespawnPortalAdapterTest { + + private final BukkitRespawnPortalAdapter adapter = new BukkitRespawnPortalAdapter(); + private final PluginManager pluginManager = mock(PluginManager.class); + private final List fired = new ArrayList<>(); + private final World overworld = mock(World.class); + private final World nether = mock(World.class); + private final World replacement = mock(World.class); + private final Player player = mock(Player.class); + private final List nextTicks = new ArrayList<>(); + private MockedStatic bukkit; + private Consumer listener = _ -> { + }; + + @BeforeEach + void mockServer() { + bukkit = org.mockito.Mockito.mockStatic(Bukkit.class); + bukkit.when(Bukkit::getPluginManager).thenReturn(pluginManager); + bukkit.when(Bukkit::isPrimaryThread).thenReturn(true); + doAnswer(invocation -> { + Event event = invocation.getArgument(0); + fired.add(event); + listener.accept(event); + return null; + }).when(pluginManager).callEvent(org.mockito.ArgumentMatchers.any(Event.class)); + EntityScheduler playerScheduler = scheduler(); + when(player.getScheduler()).thenReturn(playerScheduler); + } + + // Runs what an entity schedules for later by hand + private EntityScheduler scheduler() { + EntityScheduler scheduler = mock(EntityScheduler.class); + when(scheduler.runDelayed(any(), any(), any(), org.mockito.ArgumentMatchers.anyLong())).thenAnswer(call -> { + Consumer task = call.getArgument(1); + nextTicks.add(() -> task.accept(null)); + return null; + }); + return scheduler; + } + + @AfterEach + void closeServer() { + bukkit.close(); + } + + @Test + void respawn_firesTheOwnEventAndAppliesTheChangedLocation() { + Location original = new Location(overworld, 1, 64, 1); + Location moved = new Location(replacement, 5, 70, 5); + listener = event -> { + if (event instanceof PlayerRespawnLocationEvent respawn) respawn.setRespawnLocation(moved); + }; + PlayerRespawnEvent event = new PlayerRespawnEvent(player, original, false); + + adapter.onRespawn(event); + + assertEquals(1, fired.size()); + assertInstanceOf(PlayerRespawnLocationEvent.class, fired.getFirst()); + assertEquals(moved, event.getRespawnLocation()); + } + + @Test + void respawn_leavesTheLocationAloneWhenNobodyChangesIt() { + Location original = new Location(overworld, 1, 64, 1); + PlayerRespawnEvent event = spy(new PlayerRespawnEvent(player, original, false)); + + adapter.onRespawn(event); + + verify(event, never()).setRespawnLocation(any()); + } + + @Test + void postRespawn_firesTheOwnEventForThePlayer() { + adapter.onPostRespawn(new PlayerPostRespawnEvent(player, new Location(overworld, 0, 64, 0), false, false, false, PlayerRespawnEvent.RespawnReason.DEATH)); + + PlayerRespawnedEvent respawned = assertInstanceOf(PlayerRespawnedEvent.class, fired.getFirst()); + assertSame(player, respawned.getPlayer()); + } + + @Test + void playerPortal_carriesTheDestinationAndTheTypeOfThePortal() { + Location from = new Location(overworld, 10, 64, 10); + Location to = new Location(nether, 1, 64, 1); + + adapter.onPlayerPortal(new PlayerPortalEvent(player, from, to, TeleportCause.NETHER_PORTAL)); + + PortalTravelEvent travel = assertInstanceOf(PortalTravelEvent.class, fired.getFirst()); + assertSame(overworld, travel.getFrom()); + assertSame(nether, travel.getTargetWorld()); + assertSame(to, travel.getDestination()); + assertEquals(PortalType.NETHER, travel.getPortalType()); + } + + @Test + void playerPortal_endPortalIsTheEnderType() { + adapter.onPlayerPortal(new PlayerPortalEvent(player, new Location(overworld, 0, 64, 0), new Location(nether, 0, 64, 0), TeleportCause.END_PORTAL)); + + assertEquals(PortalType.ENDER, assertInstanceOf(PortalTravelEvent.class, fired.getFirst()).getPortalType()); + } + + @Test + void playerPortal_appliesARedirectedDestinationAndCancel() { + Location redirected = new Location(replacement, 3, 64, 3); + listener = event -> { + if (event instanceof PortalTravelEvent travel) { + travel.setDestination(redirected); + travel.setCancelled(true); + } + }; + PlayerPortalEvent event = new PlayerPortalEvent(player, new Location(overworld, 10, 64, 10), new Location(nether, 1, 64, 1), TeleportCause.NETHER_PORTAL); + + adapter.onPlayerPortal(event); + + assertEquals(redirected, event.getTo()); + assertTrue(event.isCancelled()); + } + + @Test + void entityPortal_usesThePortalTypeOfTheEvent() { + Entity entity = mock(Entity.class); + EntityScheduler entityScheduler = scheduler(); + when(entity.getScheduler()).thenReturn(entityScheduler); + EntityPortalEvent event = new EntityPortalEvent(entity, new Location(overworld, 10, 64, 10), new Location(nether, 1, 64, 1), 128, true, 16, PortalType.NETHER); + + adapter.onEntityPortal(event); + + PortalTravelEvent travel = assertInstanceOf(PortalTravelEvent.class, fired.getFirst()); + assertSame(entity, travel.getEntity()); + assertEquals(PortalType.NETHER, travel.getPortalType()); + assertFalse(event.isCancelled()); + } + + @Test + void portal_firesTheArrivalOnTheEntitysNextTick() { + adapter.onPlayerPortal(new PlayerPortalEvent(player, new Location(overworld, 10, 64, 10), new Location(nether, 1, 64, 1), TeleportCause.NETHER_PORTAL)); + assertEquals(1, fired.size()); + + nextTicks.getFirst().run(); + + PortalArrivedEvent arrived = assertInstanceOf(PortalArrivedEvent.class, fired.get(1)); + assertSame(player, arrived.getEntity()); + assertSame(overworld, arrived.getFrom()); + assertEquals(PortalType.NETHER, arrived.getPortalType()); + } + + @Test + void cancelledPortal_firesNoArrival() { + listener = event -> { + if (event instanceof PortalTravelEvent travel) travel.setCancelled(true); + }; + + adapter.onPlayerPortal(new PlayerPortalEvent(player, new Location(overworld, 10, 64, 10), new Location(nether, 1, 64, 1), TeleportCause.NETHER_PORTAL)); + + assertTrue(nextTicks.isEmpty()); + } + + @Test + void respawnLocationIsSettledAtHighest() throws NoSuchMethodException { + EventHandler handler = BukkitRespawnPortalAdapter.class.getMethod("onRespawn", PlayerRespawnEvent.class).getAnnotation(EventHandler.class); + + assertEquals(EventPriority.HIGHEST, handler.priority()); + } + + @Test + void portalWithoutADestinationFiresNothing() { + adapter.onPlayerPortal(new PlayerPortalEvent(player, new Location(overworld, 0, 64, 0), null, TeleportCause.NETHER_PORTAL)); + + assertTrue(fired.isEmpty()); + } + + @Test + void portalType_mapsEveryCause() { + assertEquals(PortalType.NETHER, BukkitRespawnPortalAdapter.portalType(TeleportCause.NETHER_PORTAL)); + assertEquals(PortalType.ENDER, BukkitRespawnPortalAdapter.portalType(TeleportCause.END_PORTAL)); + assertEquals(PortalType.END_GATEWAY, BukkitRespawnPortalAdapter.portalType(TeleportCause.END_GATEWAY)); + assertEquals(PortalType.CUSTOM, BukkitRespawnPortalAdapter.portalType(TeleportCause.PLUGIN)); + } + + @Test + void retargetingAWorldRescalesTheDestination() { + when(nether.getCoordinateScale()).thenReturn(8.0); + when(overworld.getCoordinateScale()).thenReturn(1.0); + PortalTravelEvent travel = new PortalTravelEvent(player, overworld, overworld, PortalType.NETHER, new Location(overworld, 80, 64, 160)); + + travel.setTargetWorld(nether); + + assertSame(nether, travel.getDestination().getWorld()); + assertEquals(10, travel.getDestination().getX()); + assertEquals(20, travel.getDestination().getZ()); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalAdaptersTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalAdaptersTest.java new file mode 100644 index 000000000..bc0cbbe12 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/spigot/region/RespawnPortalAdaptersTest.java @@ -0,0 +1,16 @@ +package net.cyperia.challenges.plugin.spigot.region; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +class RespawnPortalAdaptersTest { + + @Test + void withoutCanvasTheBukkitAdapterIsUsed() { + assertFalse(RespawnPortalAdapters.isClassPresent(RespawnPortalAdapters.CANVAS_EVENT)); + assertInstanceOf(BukkitRespawnPortalAdapter.class, RespawnPortalAdapters.create()); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueueRegionTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueueRegionTest.java new file mode 100644 index 000000000..15741eb98 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueueRegionTest.java @@ -0,0 +1,145 @@ +package net.cyperia.challenges.plugin.utils.bukkit.misc; + +import org.bukkit.Chunk; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.Test; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +// The draining thread owns no chunk here, as the global region on a regionised server: slices are handed +// to the chunk's region, which the test runs by hand +class ChunkFillQueueRegionTest { + + private final Deque regionTasks = new ArrayDeque<>(); + private final List log = new ArrayList<>(); + private final ChunkFillQueue queue = new ChunkFillQueue(new ChunkFillQueue.Owner() { + @Override + public boolean owns(@NotNull Chunk chunk) { + return false; + } + + @Override + public void run(@NotNull Chunk chunk, @NotNull Runnable task) { + regionTasks.add(task); + } + }); + + @Test + void drain_placesNothingItself() { + queue.submit(chunk(), 0, 0, mock(BlockData.class), block -> log.add("visited"), block -> false, () -> new int[]{0, 1, 2}, false, () -> {}); + + queue.drain(); + + assertEquals(List.of(), log); + assertEquals(1, regionTasks.size()); + } + + @Test + void slice_runsOnTheRegionAndFinishesWithDone() { + submit(chunk(), "a", 3, false); + queue.drain(); + + regionTasks.poll().run(); + + assertEquals(List.of("a", "a", "a", "a-done"), log); + } + + @Test + void partialSlice_isQueuedAgainForTheNextDrain() { + submit(chunk(), "a", 3, false); + queue.drain(2); + regionTasks.poll().run(); + assertEquals(List.of("a", "a"), log); + + queue.drain(2); + regionTasks.poll().run(); + + assertEquals(List.of("a", "a", "a", "a-done"), log); + } + + @Test + void fillInFlight_isNotHandedOutTwice() { + submit(chunk(), "a", 3, false); + + queue.drain(); + queue.drain(); + + assertEquals(1, regionTasks.size()); + } + + @Test + void forgetWhileInFlight_dropsTheFillWithoutDone() { + Chunk chunk = chunk(); + submit(chunk, "a", 3, false); + queue.drain(); + + queue.forget(chunk); + regionTasks.poll().run(); + + assertFalse(log.contains("a-done")); + queue.drain(); + assertEquals(0, regionTasks.size()); + } + + @Test + void oneDrain_handsOutAtMostEightSlices() { + for (int i = 0; i < 12; i++) submit(chunk(), "fill" + i, 1, false); + + queue.drainUntil(System.nanoTime() + 60_000_000_000L); + + assertEquals(8, regionTasks.size()); + } + + @Test + void handedOffSlice_stopsAfterItsShareOfTheDrainTime() { + Chunk chunk = chunk(); + int[] order = new int[1000]; + for (int i = 0; i < order.length; i++) order[i] = i; + queue.submit(chunk, 0, 0, mock(BlockData.class), block -> { + log.add("cell"); + try { + Thread.sleep(1); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + return true; + }, block -> false, () -> order, false, () -> log.add("done")); + + queue.drainUntil(System.nanoTime() + 80_000_000L); + regionTasks.poll().run(); + + assertTrue(log.size() < 200); + assertFalse(log.contains("done")); + queue.drainUntil(System.nanoTime() + 80_000_000L); + assertEquals(1, regionTasks.size()); + } + + private void submit(Chunk chunk, String tag, int cells, boolean urgent) { + int[] order = new int[cells]; + for (int i = 0; i < cells; i++) order[i] = i; + queue.submit(chunk, 0, 0, mock(BlockData.class), block -> { + log.add(tag); + return true; + }, block -> false, () -> order, urgent, () -> log.add(tag + "-done")); + } + + private static Chunk chunk() { + Chunk chunk = mock(Chunk.class); + when(chunk.isLoaded()).thenReturn(true); + when(chunk.getBlock(anyInt(), anyInt(), anyInt())).thenReturn(mock(Block.class)); + return chunk; + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueueTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueueTest.java index f8756949b..c5c30908e 100644 --- a/plugin/src/test/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueueTest.java +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/bukkit/misc/ChunkFillQueueTest.java @@ -4,6 +4,7 @@ import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; +import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -15,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -28,7 +30,17 @@ class ChunkFillQueueTest { private static final long FAR_DEADLINE = System.nanoTime() + 60_000_000_000L; - private final ChunkFillQueue queue = new ChunkFillQueue(); + private final ChunkFillQueue queue = new ChunkFillQueue(new ChunkFillQueue.Owner() { + @Override + public boolean owns(@NotNull Chunk chunk) { + return true; + } + + @Override + public void run(@NotNull Chunk chunk, @NotNull Runnable task) { + task.run(); + } + }); private final List log = new ArrayList<>(); @Test @@ -163,6 +175,35 @@ void forgetFromDone_removesQueuedBackgroundFillDuringRingDrain() { assertFalse(log.contains("b-done")); } + @Test + void submitAndForget_doNotWaitForBlocksBeingPlaced() throws Exception { + java.util.concurrent.CountDownLatch placing = new java.util.concurrent.CountDownLatch(1); + java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); + Chunk slow = chunk(); + queue.submit(slow, 0, 0, mock(BlockData.class), block -> { + placing.countDown(); + try { + release.await(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + return true; + }, block -> false, () -> new int[]{0}, false, () -> {}); + Thread drain = new Thread(() -> queue.drainUntil(FAR_DEADLINE)); + drain.start(); + assertTrue(placing.await(5, java.util.concurrent.TimeUnit.SECONDS)); + + java.util.concurrent.CompletableFuture other = java.util.concurrent.CompletableFuture.runAsync(() -> { + submit(chunk(), "other", 1, false); + queue.forget(chunk()); + }); + other.get(5, java.util.concurrent.TimeUnit.SECONDS); + + release.countDown(); + drain.join(); + assertEquals(tagged("other", 1), log); + } + @Test void pastDeadline_placesNothingLosesNothing() { submit(chunk(), "urgent", 10, true); diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/utils/entity/MobVariantsTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/entity/MobVariantsTest.java new file mode 100644 index 000000000..276b32d3e --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/entity/MobVariantsTest.java @@ -0,0 +1,95 @@ +package net.cyperia.challenges.plugin.utils.entity; + +import org.bukkit.entity.EntityType; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MobVariantsTest { + + @Test + void everyVariantHasItsOwnId() { + Set ids = new HashSet<>(); + MobVariants.load().values().forEach(mobs -> mobs.forEach(mob -> assertTrue(ids.add(mob.id()), mob.id()))); + } + + @Test + void everyVariantBelongsToItsType() { + MobVariants.load().forEach((type, mobs) -> mobs.forEach(mob -> assertEquals(type, mob.type()))); + } + + @Test + void villagersComeInEveryProfessionAndBiome() { + Map> variants = MobVariants.load(); + // 15 professions in 7 biomes, and a baby per biome + assertEquals(15 * 7 + 7, variants.get(EntityType.VILLAGER).size()); + } + + @Test + void aTypeOnItsOwnKeepsTheIdItHadBeforeVariants() { + assertEquals("minecraft:zombie", KillableMob.of(EntityType.ZOMBIE).id()); + assertEquals("minecraft:zombie", KillableMob.normalizeId("ZOMBIE")); + assertEquals("minecraft:zombie[baby]", KillableMob.normalizeId("minecraft:zombie[baby]")); + } + + @Test + void thePoolListsEachTypeBeforeItsVariants() { + List pool = KillableMob.pool(List.of(EntityType.CREEPER), true, true); + assertEquals(List.of("minecraft:creeper", "minecraft:creeper[charged]"), pool.stream().map(KillableMob::id).toList()); + assertEquals(1, KillableMob.pool(List.of(EntityType.CREEPER), false, false).size()); + } + + @Test + void aTypeTheVariantsCoverIsNotListedOnItsOwn() { + assertEquals(List.of("minecraft:salmon[size=small]", "minecraft:salmon[size=medium]", "minecraft:salmon[size=large]"), + KillableMob.pool(List.of(EntityType.SALMON), true, true).stream().map(KillableMob::id).toList()); + assertEquals(List.of("minecraft:salmon"), KillableMob.pool(List.of(EntityType.SALMON), false, false).stream().map(KillableMob::id).toList()); + } + + @Test + void noVariantMixesAttributesWithEquipment() { + MobVariants.load().values().forEach(mobs -> mobs.forEach(mob -> + assertTrue(mob.traits().stream().allMatch(MobTrait::isEquipment) || mob.traits().stream().noneMatch(MobTrait::isEquipment), mob.id()))); + } + + @Test + void equipmentAloneKeepsOnlyWhatTheMobHoldsAndWears() { + List ids = KillableMob.pool(List.of(EntityType.ZOMBIE), false, true).stream().map(KillableMob::id).toList(); + assertTrue(ids.contains("minecraft:zombie")); + assertTrue(ids.contains("minecraft:zombie[holding=iron_sword]")); + assertTrue(ids.contains("minecraft:zombie[armor=diamond]")); + assertTrue(ids.contains("minecraft:zombie[riding=chicken]")); + assertTrue(ids.stream().noneMatch(id -> id.contains("handed") || id.contains("baby")), ids.toString()); + assertEquals(ids.size(), Set.copyOf(ids).size()); + } + + @Test + void attributesAloneLeaveTheEquipmentOut() { + List ids = KillableMob.pool(List.of(EntityType.ZOMBIE), true, false).stream().map(KillableMob::id).toList(); + assertTrue(ids.contains("minecraft:zombie[baby]")); + assertTrue(ids.contains("minecraft:zombie[left-handed]")); + assertTrue(ids.stream().noneMatch(id -> id.contains("holding") || id.contains("armor")), ids.toString()); + } + + @Test + void equipmentAloneListsACoveredTypeOnItsOwn() { + List ids = KillableMob.pool(List.of(EntityType.FOX), false, true).stream().map(KillableMob::id).toList(); + assertEquals("minecraft:fox", ids.getFirst()); + assertTrue(ids.contains("minecraft:fox[holding=emerald]"), ids.toString()); + } + + @Test + void everyCoveredTypeHasVariants() { + Map> variants = MobVariants.load(); + for (EntityType type : EntityType.values()) { + if (MobVariants.coversEveryMob(type)) assertTrue(variants.containsKey(type), type.name()); + } + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/utils/item/CollectableItemTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/item/CollectableItemTest.java new file mode 100644 index 000000000..a1c6046ab --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/item/CollectableItemTest.java @@ -0,0 +1,28 @@ +package net.cyperia.challenges.plugin.utils.item; + +import org.bukkit.Material; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class CollectableItemTest { + + @Test + void plainItemRoundTrips() { + CollectableItem stone = CollectableItem.of(Material.STONE); + assertEquals("minecraft:stone", stone.id()); + assertEquals(stone, CollectableItem.parse(stone.id())); + } + + @Test + void legacyMaterialNameIsRead() { + assertEquals(CollectableItem.of(Material.OAK_LOG), CollectableItem.parse("OAK_LOG")); + } + + @Test + void unknownMaterialIsNull() { + assertNull(CollectableItem.parse("minecraft:not_an_item")); + } + +} diff --git a/plugin/src/test/java/net/cyperia/challenges/plugin/utils/misc/VariantIdsTest.java b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/misc/VariantIdsTest.java new file mode 100644 index 000000000..0a7ecf85d --- /dev/null +++ b/plugin/src/test/java/net/cyperia/challenges/plugin/utils/misc/VariantIdsTest.java @@ -0,0 +1,41 @@ +package net.cyperia.challenges.plugin.utils.misc; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VariantIdsTest { + + @Test + void aVariantCoversItsBaseAndEveryVariantOfFewerParts() { + String found = "minecraft:zombie[left-handed,holding=iron_sword]"; + assertTrue(VariantIds.covers(found, "minecraft:zombie")); + assertTrue(VariantIds.covers(found, "minecraft:zombie[holding=iron_sword]")); + assertTrue(VariantIds.covers(found, "minecraft:zombie[left-handed]")); + } + + @Test + void aVariantCoversNothingElse() { + String found = "minecraft:zombie[left-handed,holding=iron_sword]"; + assertFalse(VariantIds.covers(found, found)); + assertFalse(VariantIds.covers(found, "minecraft:zombie[baby]")); + assertFalse(VariantIds.covers(found, "minecraft:husk")); + assertFalse(VariantIds.covers("minecraft:zombie", "minecraft:zombie[baby]")); + assertFalse(VariantIds.covers("mob/minecraft:zombie[baby]", "minecraft:zombie")); + } + + @Test + void forEachCoveredPairsFindsWithThePoolIdsTheyCount() { + List pairs = new ArrayList<>(); + VariantIds.forEachCovered(List.of("item/minecraft:enchanted_book[minecraft:sharpness=5]"), + Set.of("item/minecraft:enchanted_book", "item/minecraft:stick"), (id, target) -> pairs.add(target)); + assertEquals(List.of("item/minecraft:enchanted_book"), pairs); + } + +} diff --git a/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java b/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java new file mode 100644 index 000000000..d2f855d61 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/commons/bukkit/utils/misc/RegionsTest.java @@ -0,0 +1,284 @@ +package net.cyperia.commons.bukkit.utils.misc; + +import io.papermc.paper.threadedregions.scheduler.AsyncScheduler; +import io.papermc.paper.threadedregions.scheduler.EntityScheduler; +import io.papermc.paper.threadedregions.scheduler.GlobalRegionScheduler; +import io.papermc.paper.threadedregions.scheduler.RegionScheduler; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class RegionsTest { + + private final Plugin plugin = mock(Plugin.class); + private final GlobalRegionScheduler global = mock(GlobalRegionScheduler.class); + private final RegionScheduler region = mock(RegionScheduler.class); + private final AsyncScheduler async = mock(AsyncScheduler.class); + private final Entity entity = mock(Entity.class); + private final EntityScheduler entityScheduler = mock(EntityScheduler.class); + private final Location location = mock(Location.class); + private MockedStatic bukkit; + + @BeforeEach + void mockServer() { + bukkit = org.mockito.Mockito.mockStatic(Bukkit.class); + bukkit.when(Bukkit::getGlobalRegionScheduler).thenReturn(global); + bukkit.when(Bukkit::getRegionScheduler).thenReturn(region); + bukkit.when(Bukkit::getAsyncScheduler).thenReturn(async); + when(entity.getScheduler()).thenReturn(entityScheduler); + when(plugin.isEnabled()).thenReturn(true); + } + + @AfterEach + void closeServer() { + bukkit.close(); + } + + @Test + void global_runsInlineOnTheGlobalThread() { + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(true); + AtomicInteger runs = new AtomicInteger(); + + Regions.global(plugin, runs::incrementAndGet); + + assertEquals(1, runs.get()); + verify(global, never()).execute(any(), any()); + } + + @Test + void global_isScheduledFromAnyOtherThread() { + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(false); + Runnable task = () -> { + }; + + Regions.global(plugin, task); + + verify(global).execute(plugin, task); + } + + @Test + void entity_runsInlineWhenTheThreadOwnsIt() { + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(true); + AtomicInteger runs = new AtomicInteger(); + + Regions.entity(plugin, entity, runs::incrementAndGet); + + assertEquals(1, runs.get()); + } + + @Test + void entity_isScheduledOnTheEntityOtherwise() { + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(false); + when(entityScheduler.execute(any(), any(), any(), anyLong())).thenReturn(true); + Runnable task = () -> { + }; + + Regions.entity(plugin, entity, task); + + verify(entityScheduler).execute(plugin, task, null, 1); + } + + @Test + void entity_runsTheRetiredFallbackWhenTheEntityIsGone() { + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(false); + when(entityScheduler.execute(any(), any(), any(), anyLong())).thenReturn(false); + AtomicInteger retired = new AtomicInteger(); + + Regions.entity(plugin, entity, () -> { + }, retired::incrementAndGet); + + assertEquals(1, retired.get()); + } + + @Test + void at_isScheduledOnTheRegionOfTheLocationOtherwise() { + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(location)).thenReturn(false); + Runnable task = () -> { + }; + + Regions.at(plugin, location, task); + + verify(region).execute(plugin, location, task); + } + + @Test + void timers_neverStartBeforeTheFirstTick() { + Regions.timer(plugin, _ -> { + }, 0, 20); + Regions.asyncTimer(plugin, _ -> { + }, 0, 20); + + verify(global).runAtFixedRate(eq(plugin), any(), eq(1L), eq(20L)); + verify(async).runAtFixedRate(eq(plugin), any(), eq(50L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void later_withoutDelayRunsOnTheNextTick() { + Regions.later(plugin, () -> { + }, 0); + + verify(global).run(eq(plugin), any()); + } + + @Test + void disabledPlugin_dropsTasksForTargetsTheThreadDoesNotOwn() { + when(plugin.isEnabled()).thenReturn(false); + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(false); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(false); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(location)).thenReturn(false); + AtomicInteger runs = new AtomicInteger(); + AtomicInteger retired = new AtomicInteger(); + + Regions.global(plugin, runs::incrementAndGet); + Regions.entity(plugin, entity, runs::incrementAndGet, retired::incrementAndGet); + Regions.at(plugin, location, runs::incrementAndGet); + + assertEquals(0, runs.get()); + assertEquals(1, retired.get()); + verify(global, never()).execute(any(), any()); + verify(entityScheduler, never()).execute(any(), any(), any(), anyLong()); + verify(region, never()).execute(any(), any(), any()); + } + + @Test + void disabledPlugin_runsTasksForTargetsTheThreadOwns() { + when(plugin.isEnabled()).thenReturn(false); + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(false); + bukkit.when(Bukkit::isPrimaryThread).thenReturn(true); + bukkit.when(Bukkit::isStopping).thenReturn(true); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(entity)).thenReturn(true); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(location)).thenReturn(true); + AtomicInteger runs = new AtomicInteger(); + + Regions.global(plugin, runs::incrementAndGet); + Regions.entity(plugin, entity, runs::incrementAndGet); + Regions.at(plugin, location, runs::incrementAndGet); + + assertEquals(3, runs.get()); + } + + private Player playerIn(World world, Location location, EntityScheduler scheduler) { + Player player = mock(Player.class); + when(player.getWorld()).thenReturn(world); + when(player.getLocation()).thenReturn(location); + when(player.getScheduler()).thenReturn(scheduler); + return player; + } + + @Test + void forEachRegion_scansOnceWhenAllPlayersShareTheRegion() { + World world = mock(World.class); + Player first = playerIn(world, location, entityScheduler); + Player second = playerIn(world, location, entityScheduler); + bukkit.when(Bukkit::getOnlinePlayers).thenAnswer(_ -> List.of(first, second)); + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(true); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(any(Entity.class))).thenReturn(true); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(any(Location.class))).thenReturn(true); + AtomicInteger scans = new AtomicInteger(); + + CompletableFuture done = Regions.forEachRegion(plugin, world, scans::incrementAndGet); + + assertEquals(1, scans.get()); + assertTrue(done.isDone()); + } + + @Test + void forEachRegion_scansEveryRegionOnceAndCompletesAfterTheLast() { + World world = mock(World.class); + Map regionOf = new HashMap<>(); + AtomicReference current = new AtomicReference<>(); + List players = new ArrayList<>(); + for (String region : List.of("a", "b", "a")) { + Location at = mock(Location.class); + regionOf.put(at, region); + EntityScheduler scheduler = mock(EntityScheduler.class); + when(scheduler.execute(any(), any(), any(), anyLong())).thenAnswer(call -> { + current.set(region); + ((Runnable) call.getArgument(1)).run(); + return true; + }); + players.add(playerIn(world, at, scheduler)); + } + bukkit.when(Bukkit::getOnlinePlayers).thenAnswer(_ -> players); + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(true); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(any(Entity.class))).thenReturn(false); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(any(Location.class))) + .thenAnswer(call -> regionOf.get(call.getArgument(0)).equals(current.get())); + AtomicInteger scans = new AtomicInteger(); + + CompletableFuture done = Regions.forEachRegion(plugin, world, scans::incrementAndGet); + + assertEquals(2, scans.get()); + assertTrue(done.isDone()); + } + + @Test + void forEachRegion_countsAPlayerWhoLeftBeforeTheTaskRan() { + World world = mock(World.class); + Player gone = playerIn(world, location, entityScheduler); + bukkit.when(Bukkit::getOnlinePlayers).thenAnswer(_ -> List.of(gone)); + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(true); + bukkit.when(() -> Bukkit.isOwnedByCurrentRegion(any(Entity.class))).thenReturn(false); + when(entityScheduler.execute(any(), any(), any(), anyLong())).thenReturn(false); + AtomicInteger scans = new AtomicInteger(); + + CompletableFuture done = Regions.forEachRegion(plugin, world, scans::incrementAndGet); + + assertEquals(0, scans.get()); + assertTrue(done.isDone()); + } + + @Test + void forEachRegion_scansInlineOnceTheWorldHasNoPlayersOutsideRegionizedServers() { + World world = mock(World.class); + bukkit.when(Bukkit::getOnlinePlayers).thenAnswer(_ -> List.of()); + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(true); + AtomicInteger scans = new AtomicInteger(); + + CompletableFuture done = Regions.forEachRegion(plugin, world, scans::incrementAndGet); + + assertEquals(1, scans.get()); + assertTrue(done.isDone()); + } + + @Test + void forEachRegion_scansInlineWhenThePluginIsDisabledOnShutdown() { + when(plugin.isEnabled()).thenReturn(false); + bukkit.when(Bukkit::isGlobalTickThread).thenReturn(false); + bukkit.when(Bukkit::isPrimaryThread).thenReturn(true); + bukkit.when(Bukkit::isStopping).thenReturn(true); + AtomicInteger scans = new AtomicInteger(); + + CompletableFuture done = Regions.forEachRegion(plugin, mock(World.class), scans::incrementAndGet); + + assertEquals(1, scans.get()); + assertTrue(done.isDone()); + } + +} diff --git a/plugin/src/test/java/net/cyperia/commons/common/config/DocumentSaveTest.java b/plugin/src/test/java/net/cyperia/commons/common/config/DocumentSaveTest.java new file mode 100644 index 000000000..f65d90e93 --- /dev/null +++ b/plugin/src/test/java/net/cyperia/commons/common/config/DocumentSaveTest.java @@ -0,0 +1,31 @@ +package net.cyperia.commons.common.config; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DocumentSaveTest { + + @TempDir + Path directory; + + @Test + void savingReplacesTheFileAndLeavesNothingElse() throws IOException { + Path file = directory.resolve("data").resolve("gamestate.json"); + + Document.create().set("round", 1).saveToFile(file); + Document.create().set("round", 2).saveToFile(file.toFile()); + + assertEquals(2, Document.parseJson(Files.readString(file)).getInt("round")); + try (var files = Files.list(file.getParent())) { + assertEquals(List.of(file), files.toList()); + } + } + +}