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