commit 7fe5ab4e24e72f9ef60b58dc017387c203b50a3d Author: fretuks Date: Mon Jun 29 15:59:48 2026 +0200 Initial commit diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..0a37a01 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,7 @@ +{ + "permissions": { + "allow": [ + "WebSearch" + ] + } +} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f811f6a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Disable autocrlf on generated files, they always generate with LF +# Add any extra files or paths here to make git stop saying they +# are changed when only line endings change. +src/generated/**/.cache/cache text eol=lf +src/generated/**/*.json text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12f8644 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# eclipse +bin +*.launch +.settings +.metadata +.classpath +.project + +# idea +out +*.ipr +*.iws +*.iml +.idea + +# gradle +build +.gradle + +# other +eclipse +run + +# Files from Forge MDK +forge*changelog.txt diff --git a/CREDITS.txt b/CREDITS.txt new file mode 100644 index 0000000..a70c53d --- /dev/null +++ b/CREDITS.txt @@ -0,0 +1,65 @@ +Minecraft Forge: Credits/Thank You + +Forge is a set of tools and modifications to the Minecraft base game code to assist +mod developers in creating new and exciting content. It has been in development for +several years now, but I would like to take this time thank a few people who have +helped it along it's way. + +First, the people who originally created the Forge projects way back in Minecraft +alpha. Eloraam of RedPower, and SpaceToad of Buildcraft, without their acceptiance +of me taking over the project, who knows what Minecraft modding would be today. + +Secondly, someone who has worked with me, and developed some of the core features +that allow modding to be as functional, and as simple as it is, cpw. For developing +FML, which stabelized the client and server modding ecosystem. As well as the base +loading system that allows us to modify Minecraft's code as elegently as possible. + +Mezz, who has stepped up as the issue and pull request manager. Helping to keep me +sane as well as guiding the community into creating better additions to Forge. + +Searge, Bspks, Fesh0r, ProfMobious, and all the rest over on the MCP team {of which +I am a part}. For creating some of the core tools needed to make Minecraft modding +both possible, and as stable as can be. + On that note, here is some specific information of the MCP data we use: + * Minecraft Coder Pack (MCP) * + Forge Mod Loader and Minecraft Forge have permission to distribute and automatically + download components of MCP and distribute MCP data files. This permission is not + transitive and others wishing to redistribute the Minecraft Forge source independently + should seek permission of MCP or remove the MCP data files and request their users + to download MCP separately. + +And lastly, the countless community members who have spent time submitting bug reports, +pull requests, and just helping out the community in general. Thank you. + +--LexManos + +========================================================================= + +This is Forge Mod Loader. + +You can find the source code at all times at https://github.com/MinecraftForge/MinecraftForge/tree/1.12.x/src/main/java/net/minecraftforge/fml + +This minecraft mod is a clean open source implementation of a mod loader for minecraft servers +and minecraft clients. + +The code is authored by cpw. + +It began by partially implementing an API defined by the client side ModLoader, authored by Risugami. +http://www.minecraftforum.net/topic/75440- +This support has been dropped as of Minecraft release 1.7, as Risugami no longer maintains ModLoader. + +It also contains suggestions and hints and generous helpings of code from LexManos, author of MinecraftForge. +http://www.minecraftforge.net/ + +Additionally, it contains an implementation of topological sort based on that +published at http://keithschwarz.com/interesting/code/?dir=topological-sort + +It also contains code from the Maven project for performing versioned dependency +resolution. http://maven.apache.org/ + +It also contains a partial repackaging of the javaxdelta library from http://sourceforge.net/projects/javaxdelta/ +with credit to it's authors. + +Forge Mod Loader downloads components from the Minecraft Coder Pack +(http://mcp.ocean-labs.de/index.php/Main_Page) with kind permission from the MCP team. + diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..249debe --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,523 @@ +Unless noted below, Minecraft Forge, Forge Mod Loader, and all +parts herein are licensed under the terms of the LGPL 2.1 found +here http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt and +copied below. + +Homepage: http://minecraftforge.net/ + https://github.com/MinecraftForge/MinecraftForge + + +A note on authorship: +All source artifacts are property of their original author, with +the exclusion of the contents of the patches directory and others +copied from it from time to time. Authorship of the contents of +the patches directory is retained by the Minecraft Forge project. +This is because the patches are partially machine generated +artifacts, and are changed heavily due to the way forge works. +Individual attribution within them is impossible. + +Consent: +All contributions to Forge must consent to the release of any +patch content to the Forge project. + +A note on infectivity: +The LGPL is chosen specifically so that projects may depend on Forge +features without being infected with its license. That is the +purpose of the LGPL. Mods and others using this code via ordinary +Java mechanics for referencing libraries are specifically not bound +by Forge's license for the Mod code. + + +=== MCP Data === +This software includes data from the Minecraft Coder Pack (MCP), with kind permission +from them. The license to MCP data is not transitive - distribution of this data by +third parties requires independent licensing from the MCP team. This data is not +redistributable without permission from the MCP team. + +=== Sharing === +I grant permission for some parts of FML to be redistributed outside the terms of the LGPL, for the benefit of +the minecraft modding community. All contributions to these parts should be licensed under the same additional grant. + +-- Runtime patcher -- +License is granted to redistribute the runtime patcher code (src/main/java/net/minecraftforge/fml/common/patcher +and subdirectories) under any alternative open source license as classified by the OSI (http://opensource.org/licenses) + +-- ASM transformers -- +License is granted to redistribute the ASM transformer code (src/main/java/net/minecraftforge/common/asm/ and subdirectories) +under any alternative open source license as classified by the OSI (http://opensource.org/licenses) + +========================================================================= +This software includes portions from the Apache Maven project at +http://maven.apache.org/ specifically the ComparableVersion.java code. It is +included based on guidelines at +http://www.softwarefreedom.org/resources/2007/gpl-non-gpl-collaboration.html +with notices intact. The only change is a non-functional change of package name. + +This software contains a partial repackaging of javaxdelta, a BSD licensed program for generating +binary differences and applying them, sourced from the subversion at http://sourceforge.net/projects/javaxdelta/ +authored by genman, heikok, pivot. +The only changes are to replace some Trove collection types with standard Java collections, and repackaged. + +This software includes the Monocraft font from https://github.com/IdreesInc/Monocraft/ for use in the early loading +display. +========================================================================= + + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/MOB_ADAPTATIONS.md b/MOB_ADAPTATIONS.md new file mode 100644 index 0000000..6477d14 --- /dev/null +++ b/MOB_ADAPTATIONS.md @@ -0,0 +1,464 @@ +# Mob Adaptations + +This file describes how Adaptive Mobs changes each supported vanilla hostile mob or mob family. The mod does not add new mobs, models, variants, items, or assets. It adapts existing mobs through progression tiers, attribute modifiers, vanilla equipment changes, spawn pressure, and server-side goal injection. + +## Shared Progression + +Adaptive tiers run from 0 to 5. Tier 0 is vanilla behavior. By default, tiers increase from world day or total hostile kills: + +- Tier 1: day 5 or 25 hostile kills. +- Tier 2: day 15 or 100 hostile kills. +- Tier 3: day 30 or 250 hostile kills. +- Tier 4: day 60 or 600 hostile kills. +- Tier 5: day 100 or 1200 hostile kills. + +Each mob type can also gain an extra tier bonus from repeated kills of that same registry entity type. The default per-type threshold is 150 kills per bonus tier. + +## Shared Scaling + +When stat scaling is enabled, participating hostile mobs can receive: + +- More max health. +- More attack damage when the mob has an attack damage attribute. +- Small movement speed bonuses at higher tiers. +- More follow range. +- Flat armor. +- Knockback resistance. +- A heal to the new maximum health when scaling is first applied. + +Scaling is applied once per mob instance and stored in the mob's persistent data so it does not stack after chunk reloads. + +## Shared Spawn Pressure + +Natural and chunk-generation hostile spawns can occasionally add one extra mob of the same type nearby. The chance scales by tier and defaults to 40% at tier 5. + +Extra spawns: + +- Use the same vanilla entity type. +- Resolve candidate positions to a nearby ground surface before vanilla spawn checks. +- Respect collision, obstruction, light, biome, and vanilla spawn rules. +- Are capped by local hostile density. +- Cannot recursively create more extra spawns. + +Tier 5 spawn pressure is intentionally more noticeable than earlier tiers. The local density cap still prevents runaway swarms, but high-tier areas should feel actively occupied instead of merely containing tougher individual mobs. + +## Shared AI Systems + +Several adaptive AI systems can apply across many mobs: + +- Shared targets: tier 4+ mobs can help nearby hostile allies focus a target. This does not create a permanent pack brain; it is a short-range goal that encourages nearby mobs to converge on a player already being pressured. +- Target priority: tier 3+ mobs can occasionally switch to a better target instead of blindly keeping the first target they saw. A player scores as more attractive if they are low health, eating, drawing or using a ranged weapon, lightly armored, already committed to attacking another mob, or exposed to skeleton fire without a shield. +- Threat memory: mobs can briefly remember the player who damaged them. This helps prevent trivial line-of-sight resets where a player hits a mob, steps behind a corner, and immediately drops all pressure. +- Sound investigation: tier 2+ mobs can move toward recent server-side sound events tracked by the mod: block breaking, eating, bow shots, and explosions. This is not full hearing AI; it is a short-lived point of interest that nearby mobs can investigate on cooldown. +- Morale: tier 3+ mobs compare nearby hostile allies to nearby non-creative, non-spectator players. If hostile allies outnumber players, they can move into darker or side-pressure positions more confidently. If a mob is isolated and below 35% health, it can briefly move defensively instead. +- Support: tier 3+ mobs can react to nearby allies. Melee mobs can move toward a player who is attacking a ranged ally such as a skeleton, pillager, or witch. Ranged mobs can step back when multiple melee allies are already attacking the same target, which helps avoid crowding. +- Escape denial: tier 3+ zombies and spiders can move toward where the player is looking, roughly three blocks ahead of the player, to pressure likely exits. If that position is not usable ground, they fall back to a nearby darker side position. This is intentionally imperfect and does not pathfind to every possible escape route. +- Anti-cheese behavior: tier 3+ selected mobs react to common static tactics that often trivialize vanilla mobs. "Cheese" here means repeatable low-risk setups such as pillaring above zombies, shooting skeletons through tiny blocked angles, baiting creepers across open visible ground, or standing in/near water to neutralize endermen. The mod does not break blocks or hard-counter the player; it nudges movement or target behavior: + - Hostile pathfinder mobs avoid nearby trap vehicles such as boats and minecarts, dismount if caught in one, and step away from nearby trap blocks such as cobwebs, powder snow, and sweet berry bushes. + - Zombies under a pillared player gather near the player instead of wandering away, and can stack onto nearby zombies to climb toward pillared players or get over simple wall setups. + - Skeletons and pillagers with blocked line of sight reposition to a side or darker angle instead of staring at a wall. + - Creepers in open ground with the player watching them stop swelling and try a side approach rather than walking straight forward. Creepers also cancel swelling against an actively blocking shield and try to move around the shield instead. +- Endermen near water, or fighting a player in water, retreat to safer ground. +- Biome tactics: tier 3+ mobs can make small terrain-specific decisions. Nether mobs are more aggressive in the Nether at close range, with shorter tactical cooldowns and stronger pressure at tiers 4-5. Drowned press harder when both they and the target are in water. Spiders in caves prefer elevated movement. Skeletons in open sky terrain try to keep wider side spacing. +- Ranged cover: tier 3+ ranged mobs can sometimes move sideways or backward after attacking. The "cover" is deliberately imperfect: the goal picks a reasonable retreat or side position rather than searching for a perfect protected bunker. + +## Common Terms + +Some repeated terms in the mob sections have specific meanings: + +- Flanking: the mob moves to a side position around the target instead of always taking the shortest direct path. +- Side pressure: similar to flanking, but usually closer and less dramatic. It makes groups spread around the target instead of stacking in one line. +- Adaptive melee positioning: melee mobs choose a nearby side or pressure position and move there at a modest speed instead of always walking straight at the target. Conservative melee mobs use slower, safer pressure. +- Airborne repositioning: flying mobs choose a side position around the target, add a vertical offset, and use move control to drift there. At tier 5, they can include a small amount of target movement prediction. +- Target prediction: at higher tiers, some movement or projectile logic aims partly toward where the target is moving, not only where the target is now. +- Low-health retreat: a mob with low health can briefly back away or reposition, but it does not become permanently passive. +- Re-engage: after a short retreat or reposition, the mob continues attacking. +- Conservative behavior: the goal is intentionally limited so it does not override the vanilla mob's core identity or remove normal counterplay. + +## Unique Late-Tier Abilities + +Several hostile families also have identity-specific pressure tools. These use vanilla effects, movement, targeting, temporary blocks, or projectile metadata; the mod still does not add new items, entities, models, or permanent terrain changes. + +- Zombies, husks, and zombie villagers - Corpse Ladder: the existing zombie stacking behavior remains the main anti-pillar tool. At tier 5, a stacked zombie can briefly surge upward when several zombies are under a player who is only slightly above them. This makes short pillars and low walls unreliable without letting zombies break blocks. +- Drowned - Dragging Grip: tier 4+ drowned that hit a player while both are in water apply brief Slowness and pull the player downward. This makes oceans, ruins, and flooded caves less automatically safe. +- Zombified piglins - Blood Call: at tier 5, damaging one zombified piglin can briefly grant nearby zombified piglins Speed and Strength against the attacker. +- Skeletons - Venom Shot: tier 4+ skeleton arrows have an uncommon Poison I roll for 4-6 seconds. At tier 5, skeletons can also add short Weakness against shielding targets or Slowness against sprinting targets. +- Strays - Frostbite Shot: tier 4+ stray arrows apply a stronger Slowness pulse, with occasional Mining Fatigue at tier 5. +- Wither skeletons - Execution Swing: tier 4+ wither skeletons refresh Wither and add extra shove pressure when hitting a target below 40% health. +- Creepers - Blink Shroud: tier 5 creepers near detonation range can briefly turn invisible for about half a second before pressure resumes. A primed creeper sound plays as the cue. +- Spiders - Web Retreat: tier 4+ spiders can place a temporary cobweb at or near the player after taking damage or landing a hit. The cobweb decays after roughly 5-8 seconds. +- Cave spiders - Venom Pounce: cave spiders keep their lunge behavior against ranged/eating players and refresh short Poison on hits against players using bows, crossbows, or items. +- Witches - Brewed Combo: witches already support allies with regeneration and punish rushes with Slowness, Weakness, or Harming. At tier 5 these potion opportunities happen earlier and make witches priority targets. +- Pillagers - Pinning Bolt: tier 5 pillager arrows can carry a short pinned effect: Slowness and a one-second shield disable on hit. +- Endermen - Backstep Ambush: tier 4+ endermen hit in melee can teleport behind or diagonally behind the attacker and immediately re-engage, with a shorter cooldown at tier 5. +- Endermites - Swarm Mark: endermite hits mark the target for nearby endermites and endermen, causing them to prioritize the same player. +- Silverfish - Burrow Burst: tier 4+ low-health silverfish can briefly vanish, then reappear beside their attacker after a short delay. +- Evokers - Vex Relay: tier 4+ evokers that are rushed can redirect nearby vexes onto the attacker while the evoker backs away. +- Vindicators - Armor Breaker: tier 5 vindicator axe hits add a small armor-piercing damage component and briefly disable an active shield. +- Ravagers - Crushing Charge: tier 4+ ravager hits can deliver heavy sideways/upward knockback on cooldown, with bonus damage if the player is slammed into a wall. +- Guardians - Focused Beam: tier 4+ guardian beam damage increases slightly when multiple guardians are already focused on the same player. +- Elder guardians - Drowning Pressure: elder guardian beam hits add brief Slowness and a sinking pull. +- Shulkers - Gravity Chain: tier 4+ shulker hits against an already levitating player extend Levitation and apply brief Slowness. +- Slimes - Recombine: tier 5 small slimes gain short damage and jump pressure when they successfully hit, helping split slimes remain relevant. +- Magma cubes - Molten Recombine: tier 5 small magma cubes use the same short damage and jump pressure as slimes, and briefly ignite the player on hit. +- Piglins - Gold Frenzy: piglin-family Nether pressure is stronger at tier 5, while gold still remains valid counterplay rather than a hard immunity bypass. +- Piglin brutes - Guard Break: tier 5 brute hits add a small armor-piercing damage component and briefly disable shields. +- Hoglins - Gore Toss: tier 4+ hoglin hits can toss the player upward and backward on cooldown. +- Zoglins - Frenzied Rampage: tier 5 low-health zoglins gain a short Speed and Resistance burst. +- Ghasts - Splitting Fireball: treated as future work; current tier 5 ghasts already use stronger target prediction through airborne positioning and projectile aim adjustment. +- Blazes - Overheat Volley: tier 5 blazes that take ranged damage briefly gain Speed and Strength pressure to punish static bow farming. +- Phantoms - Bleeding Dive: tier 5 phantom hits apply brief Hunger as a vanilla bleeding-style damage-over-time pressure. +- Vexes - Phase Cut: tier 5 vexes that hit while phasing gain bonus hit pressure and apply brief Weakness. +- Wardens - Echo Mark: tier 5 wardens remember repeated ranged attackers longer. The next sonic boom against a marked player adds extra knockback and briefly suppresses sprint escape with Slowness, without increasing sonic boom frequency. + +## Zombies, Husks, Drowned, Zombie Villagers, and Zombified Piglins + +Participation toggle: `mobs.zombies` +AI toggles: `ai.zombies`, `ai.enableMeleeAI`, `ai.enableEscapeDenialAI`, `ai.enableAntiCheeseAI` + +These mobs receive the shared scaling and spawn pressure systems. They can also receive armor and melee weapon upgrades. At tier 5, armor coverage and diamond/iron rolls are much more common, and melee weapon enchantments can become meaningfully dangerous. The gear system respects existing gear and does not replace unrecognized held items, so drowned with tridents are left alone. + +AI changes: + +- Basic flanking from tier 1+ when zombie AI is enabled. +- Adaptive melee positioning, with small side pressure and target prediction at high tiers. +- Escape-denial movement toward the direction the player appears to be moving or looking, so zombies sometimes pressure an exit instead of trailing directly behind. +- Anti-cheese movement against pillared players: if the player is more than 2.5 blocks above the zombie and still nearby horizontally, the zombie moves toward a close side position under or around the pillar. +- Zombies can stack by riding nearby zombies when a player is above them on a pillar or behind a simple vertical obstacle. This gives groups a way to build pressure upward without breaking blocks. +- Tier 4+ shared targeting with nearby hostile mobs. + +Zombified piglins also count as zombies for gear and participation, but Nether-family melee AI settings affect some piglin-family movement behavior elsewhere. + +## Skeletons, Strays, and Wither Skeletons + +Participation toggle: `mobs.skeletons` +AI toggles: `ai.skeletons`, `ai.enableRangedAI`, `ai.enableRangedCoverAI`, `ai.enableAntiCheeseAI`, `ai.enableBiomeTacticsAI` + +These mobs receive shared scaling and spawn pressure. Skeletons and strays can receive armor and bow enchantments. Late-tier bows are allowed to matter through stronger Power rolls and occasional Punch or Flame at tier 5. Wither skeletons can receive armor and melee weapon upgrades if they do not use a bow. + +AI changes: + +- Shield-aware behavior that softens or adjusts pressure against blocking targets. +- Flanking and spacing goals. +- Improved ranged attack positioning and small projectile aim correction. +- Possible upward aim bias at high tiers. +- Low-health retreat behavior. +- Ranged-cover repositioning after attacks: the skeleton may step backward or to a side angle if the target is within 16 blocks. +- Open-terrain spacing through biome tactics. +- Anti-cheese repositioning against blocked or tiny-window shots: if a skeleton or pillager cannot see its target, it periodically tries a side or darker angle instead of standing still. +- Tier 4+ shared targeting. + +## Creepers + +Participation toggle: `mobs.creepers` +AI toggles: `ai.creepers`, `ai.enableCreeperAI`, `ai.enableAntiCheeseAI` + +Creepers receive shared scaling and spawn pressure. + +AI changes: + +- Tier 2+ creepers cancel premature swelling if they are still too far away. +- Tier 3+ creepers use pressure logic around when to start swelling. +- Tier 4+ creepers can commit when another nearby attacker is already pressuring the target. +- Tier 5 creepers can briefly retreat and re-engage instead of always walking directly forward. +- Anti-cheese behavior can make open-ground approaches less predictable: if a creeper is visible to the target, under open sky, and still more than 4 blocks away, it cancels swelling and tries to reposition sideways. +- Creepers do not intentionally explode into an actively blocking shield. They cancel swelling at close range and path to a side angle before trying to pressure again. +- Tier 4+ shared targeting applies. + +## Spiders and Cave Spiders + +Participation toggle: `mobs.spiders` +AI toggles: `ai.spiders`, `ai.enableSpiderAI`, `ai.enableMeleeAI`, `ai.enableEscapeDenialAI`, `ai.enableBiomeTacticsAI` + +Spiders receive shared scaling and spawn pressure. Cave spiders use the same family logic with faster and earlier tactical movement. + +AI changes: + +- Flanking with close-range side pressure. +- Tier 2+ cave spiders and tier 3+ spiders use tactical side movement. +- Tier 3+ spiders can lunge at nearby players using ranged weapons. +- Tier 4+ spiders prefer elevated positions when practical. +- Cave or underground spiders can use vertical terrain pressure. +- Retreat and re-engage behavior after damage. When spiders disengage, they gain invisibility and regeneration 5 for 5 seconds while repositioning before re-engaging. +- Low-health retreat behavior. +- Escape-denial movement toward likely player exits, based on the direction the player is looking. +- Tier 4+ shared targeting. + +## Witches + +Participation toggle: `mobs.witches` +AI toggles: `ai.witches`, `ai.enableWitchAI`, `ai.enableWitchAdvancedPotionAI`, `ai.enableRangedAI`, `ai.enableRangedCoverAI` + +Witches receive shared scaling and spawn pressure. + +AI changes: + +- Flanking and spacing when players get close. +- Extra potion opportunities against moving, close, or weakened targets. +- Earlier self-healing thresholds at higher tiers. +- Regeneration support potions for wounded nearby hostile allies. +- Slowness against sprinting or fast-moving targets. +- Weakness against melee threats. +- Harming pressure against low-health targets at tier 5. +- Low-health retreat behavior. +- Ranged-cover repositioning: the witch may step backward or to a side angle if the target is within 16 blocks. +- Tier 4+ shared targeting. + +## Pillagers + +Participation toggle: `mobs.pillagers` +AI toggles: `ai.pillagers`, `ai.enablePillagerAI`, `ai.enableRangedAI`, `ai.enableRangedCoverAI`, `ai.enableRaidMobAI`, `ai.enableAntiCheeseAI` + +Pillagers receive shared scaling and spawn pressure. Their crossbows can gain Quick Charge at tier 3+ and occasional Multishot or Piercing at tier 5. + +AI changes: + +- Flanking and ranged repositioning. +- Projectile aim correction at higher tiers. +- Ranged-cover movement after attacks: the pillager may step backward or to a side angle if the target is within 16 blocks. +- Low-health retreat behavior. +- Anti-cheese ranged behavior when line of sight is blocked, using the same side-angle repositioning as skeletons. +- Tier 4+ shared targeting. + +## Endermen + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.endermen`, `ai.enableEndermanAI`, `ai.enableAntiCheeseAI` + +Endermen receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Tier 2+ tactical teleport checks. +- Tier 3+ angular side teleports around a target. +- Water-aware teleporting away from unsafe positions. +- Tier 5 wider side repositioning against close melee pressure. +- In the End, tier 4+ endermen can coordinate nearby endermen onto the same target, with wider coordination and more teleport attempts at tier 5. +- Anti-cheese response for water traps: if the enderman or target is in water, the enderman tries to retreat to a safer position instead of staying in a bad spot. +- Tier 4+ shared targeting. + +## Endermites + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.silverfishAndEndermites`, `ai.enableEndermiteAI`, `ai.enableMeleeAI` + +Endermites receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Tier 2+ side pursuit. +- Remembered target persistence over short distances. +- Faster movement at tier 5. +- Target prediction at tier 5. +- Tier 4+ shared targeting. + +## Silverfish + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.silverfishAndEndermites`, `ai.enableMeleeAI` + +Silverfish receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Adaptive melee positioning. +- Slightly faster melee pressure than larger generic melee mobs. +- Tier 4+ shared targeting. + +## Evokers + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.evokers`, `ai.enableEvokerAI`, `ai.enableRaidMobAI`, `ai.enableRangedCoverAI` + +Evokers receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Tier 2+ repositioning after spell casts, after standing still, or when rushed by melee players. +- Tier 4+ use nearby illagers as pressure support while repositioning. +- Ranged-cover movement: the evoker may step backward or to a side angle if the target is within 16 blocks. +- Tier 4+ shared targeting. + +## Vindicators + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.enableMeleeAI`, `ai.enableRaidMobAI`, `ai.ravagers` + +Vindicators receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Adaptive melee positioning when raid melee AI is enabled. +- Conservative melee pressure as part of the raid-mob path. +- Tier 4+ shared targeting. + +## Ravagers + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.ravagers`, `ai.enableRaidMobAI`, `ai.enableRavagerAdvancedAI`, `ai.enableMeleeAI` + +Ravagers receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Tier 3+ target persistence. +- Deliberate pressure movement instead of only direct pursuit. +- Short retreat positioning when too close. +- Tier 4+ coordination with nearby illagers. +- Tier 5 stronger pressure when the target is visible and within range. +- Conservative adaptive melee positioning. +- Tier 4+ shared targeting. + +## Guardians and Elder Guardians + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.guardians`, `ai.enableAquaticHostileAI`, `ai.enableGuardianAdvancedAI`, `ai.enableRangedAI` + +Guardians and elder guardians receive shared scaling and spawn pressure through the generic hostile toggle. Elder guardian tactics are intentionally slower and more conservative. + +AI changes: + +- Tier 2+ repositioning when line of sight is blocked. +- Tier 4+ non-elder guardians can coordinate pressure with nearby attackers. +- Tier 5 non-elder guardians can retarget toward more vulnerable visible targets. +- Ranged positioning support. +- Tier 4+ shared targeting. + +## Shulkers + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.shulkers`, `ai.enableEndMobAI`, `ai.enableShulkerAdvancedAI`, `ai.enableRangedAI` + +Shulkers receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Tier 2+ line-of-sight checks that stop pressure if the target stays blocked. +- Tier 4+ nearby shulkers can coordinate onto the same target. +- Tier 5 uses shorter tactical cooldown windows, especially in the End, and coordinates over a wider local radius. +- Ranged positioning support. +- Tier 4+ shared targeting. + +## Slimes + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.slimes`, `ai.enableSlimeAdvancedAI`, `ai.enableMeleeAI` + +Slimes receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Tier 2+ angled jump pressure instead of only direct movement. +- Side positioning based on entity id so repeated slimes naturally spread. +- Larger tier 5 slimes move and leap more aggressively. +- Adaptive melee positioning. +- Tier 4+ shared targeting. + +## Magma Cubes + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.slimes`, `ai.enableMagmaCubeAdvancedAI`, `ai.enableMeleeAI`, `ai.enableBiomeTacticsAI` + +Magma cubes receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- The same angled jump pressure as slimes, controlled by magma-cube advanced AI. +- Adaptive melee positioning. +- Nether biome tactics make them bolder in the Nether. +- Tier 4+ shared targeting. + +## Piglins, Piglin Brutes, Hoglins, Zoglins, and Zombified Piglins + +Participation toggle: `mobs.otherHostiles` for piglins, brutes, hoglins, and zoglins; `mobs.zombies` for zombified piglins +AI toggles: `ai.piglinFamily`, `ai.enableNetherMobAI`, `ai.enableMeleeAI`, `ai.enableBiomeTacticsAI` + +These mobs receive shared scaling and spawn pressure when their participation toggle allows it. Piglin gear is intentionally left alone to avoid disturbing bartering behavior. + +AI changes: + +- Adaptive melee positioning. +- Conservative pressure for piglin brutes. +- Nether biome tactics make the family bolder in the Nether. +- Tier 4+ shared targeting. + +## Ghasts + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.ghasts`, `ai.enableNetherMobAI`, `ai.enableRangedAI` + +Ghasts receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Ranged positioning support with a longer preferred range. +- Airborne repositioning around targets. +- Larger vertical offset than other airborne mobs. +- Tier 5 target prediction for airborne positioning. +- Nether biome tactics identify them as Nether mobs where applicable. +- Tier 4+ shared targeting. + +## Blazes + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.blazes`, `ai.enableNetherMobAI`, `ai.enableRangedAI` + +Blazes receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Ranged positioning support. +- Airborne side repositioning around targets. +- Tier 5 target prediction for airborne positioning. +- Nether biome tactics make them bolder in the Nether. +- Tier 4+ shared targeting. + +## Phantoms + +Participation toggle: `mobs.otherHostiles` +AI toggle: `ai.phantoms` + +Phantoms receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Airborne repositioning around targets. +- Higher vertical offset than most non-ghast airborne mobs. +- Tier 5 target prediction for airborne positioning. +- Tier 4+ shared targeting. + +## Vexes + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.vexes`, `ai.enableRaidMobAI` + +Vexes receive shared scaling and spawn pressure through the generic hostile toggle. + +AI changes: + +- Airborne repositioning around targets. +- Retreat and re-engage behavior. +- Low-health retreat behavior. +- Tier 5 target prediction for airborne positioning. +- Tier 4+ shared targeting. + +## Wardens + +Participation toggle: `mobs.otherHostiles` +AI toggles: `ai.warden`, `ai.enableWardenAI`, `ai.enableWardenAdvancedAI`, `ai.enableMeleeAI` + +Wardens receive shared scaling and spawn pressure only if generic hostiles are enabled. Their adaptive AI is intentionally conservative. + +AI changes: + +- Conservative adaptive melee positioning. +- Tier 4+ target persistence if a recent target remains nearby. +- Tier 5 response to repeated ranged attackers. + +The mod does not intentionally increase the Warden's default speed, damage, tracking, or sonic boom frequency through custom Warden AI. + +## Bosses + +Boss AI toggle: `ai.enableBossAI` + +The Ender Dragon and Wither are excluded by default. Boss support is treated as future-facing and should remain off unless explicitly enabled and tested. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c06cb28 --- /dev/null +++ b/README.md @@ -0,0 +1,164 @@ +# Adaptive Mobs + +Adaptive Mobs is a Minecraft Forge 1.20.1 server-side gameplay mod that makes existing vanilla hostile mobs scale with world progression. It does not add new mobs, variants, models, entity types, or assets. + +## What Changes + +- Tracks global world progression with saved data. +- Counts total hostile mob kills by players. +- Counts hostile kills per entity type. +- Uses world day plus kill thresholds to compute adaptive tiers 0-5. +- Scales hostile mob attributes on spawn: health, damage, follow range, small speed bonuses, armor, and knockback resistance. +- Improves vanilla equipment for eligible mobs with vanilla items only. +- Adds capped spawn pressure by occasionally spawning one extra vanilla mob of the same type near natural hostile spawns. +- Injects lightweight AI goals for vanilla hostile mobs where practical. +- Adds small tactical responses for group morale, vulnerable target priority, low-health retreats, dark approach paths, and common cheese patterns. +- Does not add new mobs, variants, models, entity types, or assets. +- Does not modify bosses by default. + +## Default Tiers + +- Tier 0: vanilla behavior. +- Tier 1: day 5 or 25 hostile kills. +- Tier 2: day 15 or 100 hostile kills. +- Tier 3: day 30 or 250 hostile kills. +- Tier 4: day 60 or 600 hostile kills. +- Tier 5: day 100 or 1200 hostile kills. + +Mob-specific tiers can rise further when players repeatedly kill the same mob type. The global tier remains the main progression source. + +## Tier 5 Defaults + +At the highest default tier, eligible hostile mobs receive: + +- `+75%` max health. +- `+45%` attack damage when the mob has an attack damage attribute. +- `+5%` movement speed. +- `+25%` follow range. +- `+4` armor. +- `+0.10` knockback resistance. +- A heal to the new maximum health after scaling is applied. + +Spawn pressure is also at its highest default value: natural and chunk-generation hostile spawns have a `25%` chance to add one extra mob of the same type nearby. Extra spawns are capped at one per spawn event, obey normal spawn/collision checks, cannot recursively trigger more extras, and are skipped when the local hostile density cap is already reached. + +## Mob-Specific Tier 5 Behavior + +- Zombies, husks, drowned, zombie villagers, and zombified piglins can receive upgraded vanilla armor and melee weapons. Drowned holding unrecognized weapons such as tridents are left alone. +- Skeletons and strays can receive armor, bow enchantments, shield-counter movement, flanking, smarter ranged positioning, and improved projectile aim. +- Wither skeletons can receive armor and melee weapon upgrades. +- Pillagers can receive Quick Charge, possible Multishot, smarter ranged positioning, and improved projectile aim. +- Creepers pressure from farther away, flank, react to nearby attackers, and can briefly retreat before re-engaging. +- Spiders and cave spiders flank, lunge toward ranged targets, seek elevated angles, and can retreat/re-engage after damage. +- Witches keep spacing, use ally-aware movement, heal earlier at high tiers, and add cooldown-based slowness, weakness, and harming potion opportunities. +- Endermen use tactical side teleports and stronger spacing against close melee pressure. +- Endermites get fast side-approach melee pressure, pursuit persistence, and shared targeting at tier 4+ through the shared target goal. +- Evokers keep distance from melee players, reposition after spell casting, avoid standing still too long, and use nearby melee illagers as cover at tier 4+. +- Guardians reposition when line of sight is blocked, coordinate pressure with nearby guardians at tier 4+, and can prioritize exposed lower-health targets at tier 5. Elder guardian changes stay slower and conservative. +- Shulkers avoid continuing pressure through blocked line of sight, coordinate targets with nearby shulkers at tier 4+, and use slightly tighter cooldowns at tier 5. +- Slimes and magma cubes use better angled jump pressure, lightweight hazard checks, and stronger large-mob pressure at tier 5. +- Ravagers get target persistence, more deliberate pressure movement, close-range punishment positioning, and nearby raider coordination at tier 4+. +- Wardens only get conservative target persistence at tier 4+ and a conservative response to repeated ranged attackers at tier 5. Their default speed, damage, tracking, and sonic boom frequency are not increased. +- Ghasts, blazes, phantoms, and vexes use airborne positioning with target prediction at tier 5. +- Piglins, piglin brutes, hoglins, zoglins, vindicators, silverfish, and similar melee mobs use adaptive melee positioning when enabled. + +## Shared Tactical AI + +These systems are intentionally small tactical nudges, not hard counters: + +- Group morale: mobs press more boldly when nearby allies outnumber nearby players, and isolated low-health mobs can briefly move defensively. +- Threat memory: mobs briefly remember the last player who damaged them so breaking line of sight does not instantly clear pressure. +- Sound investigation: tier 2+ mobs can move toward nearby recent block breaking, eating, bow shots, and explosions on cooldown. +- Target priority: mobs occasionally prefer low-health players, eating players, players drawing bows, lightly armored players, or players already attacking another mob. +- Equipment awareness: skeletons value unshielded players more, melee mobs value low-armor players more, and witches use weakness more readily against high-damage melee weapons. +- Light awareness: adaptive movement can prefer darker side-approach positions when both sides are otherwise viable. +- Retreat thresholds: witches, skeletons, pillagers, spiders, and vexes can briefly retreat at low health. Zombies mostly do not retreat. +- Anti-cheese movement: zombies gather under pillared players instead of wandering randomly, ranged mobs reposition against blocked/tiny-window shots, creepers hesitate across exposed visible ground, and endermen disengage from water traps. +- Support behavior: witches can support wounded nearby hostile mobs, melee mobs can peel toward players attacking ranged allies, and ranged mobs can hold back when melee allies are already pressuring. +- Escape denial: zombies and spiders imperfectly bias toward likely player exits and movement routes instead of always taking the shortest direct path. +- Biome and terrain tactics: Nether mobs are a little bolder in the Nether, drowned press better in water, spiders prefer vertical movement in caves, and skeletons space more in open terrain. +- Ranged cover: skeletons, pillagers, witches, and evokers can sometimes move toward imperfect cover after attacking. +- Pack roles: repeated mobs naturally spread by using side approaches based on entity id; no new entity types or variants are added. +- Fairness: dangerous behaviors keep vanilla warning windows and are implemented as movement/targeting goals with cooldowns. + +## Commands + +All commands require permission level 2 or higher. + +- `/adaptivemobs get` shows current tier, world day, total hostile kills, and manual override status. +- `/adaptivemobs setglobaltier <0-5>` sets a manual global tier override. +- `/adaptivemobs reset` clears progression and manual tier override. +- `/adaptivemobs debug` prints current config/runtime summary. + +## Configuration + +Forge common config is generated at `config/adaptivemobs-common.toml`. + +Important options include: + +- `general.enableAdaptiveMobs` +- `general.maxTier` +- `mobs.zombies` +- `mobs.skeletons` +- `mobs.creepers` +- `mobs.spiders` +- `mobs.witches` +- `mobs.pillagers` +- `mobs.otherHostiles` +- `progression.dayThresholds` +- `progression.killThresholds` +- `progression.perTypeKillsPerTier` +- `scaling.enabled` +- `scaling.healthPerTier` +- `scaling.damagePerTier` +- `scaling.speedPerTier` +- `scaling.followRangePerTier` +- `scaling.armorPerTier` +- `scaling.knockbackResistPerTier` +- `gear.enabled` +- `gear.enchantChancePerTier` +- `spawnPressure.enabled` +- `spawnPressure.extraChancePerTier` +- `spawnPressure.densityRadius` +- `spawnPressure.densityCap` +- `ai.enabled` +- `ai.enableAdvancedAI` +- `ai.enableRangedAI` +- `ai.enableMeleeAI` +- `ai.enableEndermiteAI` +- `ai.enableEvokerAI` +- `ai.enableWitchAdvancedPotionAI` +- `ai.enableGuardianAdvancedAI` +- `ai.enableShulkerAdvancedAI` +- `ai.enableSlimeAdvancedAI` +- `ai.enableMagmaCubeAdvancedAI` +- `ai.enableRavagerAdvancedAI` +- `ai.enableWardenAdvancedAI` +- `ai.enableMoraleAI` +- `ai.enableTargetPriorityAI` +- `ai.enableAntiCheeseAI` +- `ai.enableDarkApproachAI` +- `ai.enableThreatMemoryAI` +- `ai.enableSoundInvestigationAI` +- `ai.enableSupportAI` +- `ai.enableEscapeDenialAI` +- `ai.enableBiomeTacticsAI` +- `ai.enableRangedCoverAI` +- `ai.skeletons`, `ai.zombies`, `ai.creepers`, `ai.spiders`, `ai.witches`, `ai.pillagers` +- `ai.endermen`, `ai.slimes`, `ai.ghasts`, `ai.blazes`, `ai.guardians`, `ai.phantoms` +- `ai.ravagers`, `ai.evokers`, `ai.vexes`, `ai.piglinFamily`, `ai.silverfishAndEndermites`, `ai.shulkers`, `ai.warden` + +The defaults are intentionally moderate. Speed scaling is kept low to avoid unfair mobs. + +## Compatibility Notes + +The mod uses Forge events, saved data, attributes, vanilla equipment, and goal injection. It avoids mixins and client-only code. Spawn pressure is guarded against recursion, limited to one extra mob per natural spawn event, and capped by nearby hostile density. + +Some advanced behavior is intentionally conservative. For example, skeleton shield response and mob flanking are implemented as small movement goals rather than full vanilla AI replacement. + +## Not Yet Implemented + +The following ideas require persisted state or broader balancing and are not currently active: + +- Difficulty decay after repeated player deaths. +- Per-dimension or per-region progression, such as Nether mobs evolving primarily from Nether activity. +- Long-term player habit memory across sessions. diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..46add15 --- /dev/null +++ b/README.txt @@ -0,0 +1,46 @@ + +Source installation information for modders +------------------------------------------- +This code follows the Minecraft Forge installation methodology. It will apply +some small patches to the vanilla MCP source code, giving you and it access +to some of the data and functions you need to build a successful mod. + +Note also that the patches are built against "un-renamed" MCP source code (aka +SRG Names) - this means that you will not be able to read them directly against +normal code. + +Setup Process: +============================== + +Step 1: Open your command-line and browse to the folder where you extracted the zip file. + +Step 2: You're left with a choice. +If you prefer to use Eclipse: +1. Run the following command: `./gradlew genEclipseRuns` +2. Open Eclipse, Import > Existing Gradle Project > Select Folder + or run `gradlew eclipse` to generate the project. + +If you prefer to use IntelliJ: +1. Open IDEA, and import project. +2. Select your build.gradle file and have it import. +3. Run the following command: `./gradlew genIntellijRuns` +4. Refresh the Gradle Project in IDEA if required. + +If at any point you are missing libraries in your IDE, or you've run into problems you can +run `gradlew --refresh-dependencies` to refresh the local cache. `gradlew clean` to reset everything +(this does not affect your code) and then start the process again. + +Mapping Names: +============================= +By default, the MDK is configured to use the official mapping names from Mojang for methods and fields +in the Minecraft codebase. These names are covered by a specific license. All modders should be aware of this +license, if you do not agree with it you can change your mapping names to other crowdsourced names in your +build.gradle. For the latest license text, refer to the mapping file itself, or the reference copy here: +https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md + +Additional Resources: +========================= +Community Documentation: https://docs.minecraftforge.net/en/1.20.1/gettingstarted/ +LexManos' Install Video: https://youtu.be/8VEdtQLuLO0 +Forge Forums: https://forums.minecraftforge.net/ +Forge Discord: https://discord.minecraftforge.net/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..f0fb5a7 --- /dev/null +++ b/build.gradle @@ -0,0 +1,207 @@ +plugins { + id 'eclipse' + id 'idea' + id 'maven-publish' + id 'net.minecraftforge.gradle' version '[6.0,6.2)' +} + +version = mod_version +group = mod_group_id + +base { + archivesName = mod_id +} + +// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. +java.toolchain.languageVersion = JavaLanguageVersion.of(17) + +println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" +minecraft { + // The mappings can be changed at any time and must be in the following format. + // Channel: Version: + // official MCVersion Official field/method names from Mojang mapping files + // parchment YYYY.MM.DD-MCVersion Open community-sourced parameter names and javadocs layered on top of official + // + // You must be aware of the Mojang license when using the 'official' or 'parchment' mappings. + // See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md + // + // Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge + // Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started + // + // Use non-default mappings at your own risk. They may not always work. + // Simply re-run your setup task after changing the mappings to update your workspace. + mappings channel: mapping_channel, version: mapping_version + + // When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game. + // In most cases, it is not necessary to enable. + // enableEclipsePrepareRuns = true + // enableIdeaPrepareRuns = true + + // This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game. + // It is REQUIRED to be set to true for this template to function. + // See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html + copyIdeResources = true + + // When true, this property will add the folder name of all declared run configurations to generated IDE run configurations. + // The folder name can be set on a run configuration using the "folderName" property. + // By default, the folder name of a run configuration is the name of the Gradle project containing it. + // generateRunFolders = true + + // This property enables access transformers for use in development. + // They will be applied to the Minecraft artifact. + // The access transformer file can be anywhere in the project. + // However, it must be at "META-INF/accesstransformer.cfg" in the final mod jar to be loaded by Forge. + // This default location is a best practice to automatically put the file in the right place in the final jar. + // See https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ for more information. + accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') + + // Default run configurations. + // These can be tweaked, removed, or duplicated as needed. + runs { + // applies to all the run configs below + configureEach { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + property 'forge.logging.markers', 'REGISTRIES' + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + property 'forge.logging.console.level', 'debug' + + mods { + "${mod_id}" { + source sourceSets.main + } + } + } + + client { + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + property 'forge.enabledGameTestNamespaces', mod_id + } + + server { + property 'forge.enabledGameTestNamespaces', mod_id + args '--nogui' + } + + // This run config launches GameTestServer and runs all registered gametests, then exits. + // By default, the server will crash when no gametests are provided. + // The gametest system is also enabled by default for other run configs under the /test command. + gameTestServer { + property 'forge.enabledGameTestNamespaces', mod_id + } + + data { + // example of overriding the workingDirectory set in configureEach above + workingDirectory project.file('run-data') + + // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. + args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') + } + } +} + +// Include resources generated by data generators. +sourceSets.main.resources { srcDir 'src/generated/resources' } + +repositories { + // Put repositories for dependencies here + // ForgeGradle automatically adds the Forge maven and Maven Central for you + + // If you have mod jar dependencies in ./libs, you can declare them as a repository like so. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver + // flatDir { + // dir 'libs' + // } +} + +dependencies { + // Specify the version of Minecraft to use. + // Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact. + // The "userdev" classifier will be requested and setup by ForgeGradle. + // If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"], + // then special handling is done to allow a setup of a vanilla dependency without the use of an external repository. + minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" + + // Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings + // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime + // compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}") + // compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}") + // runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}") + + // Example mod dependency using a mod jar from ./libs with a flat dir repository + // This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar + // The group id is ignored when searching -- in this case, it is "blank" + // implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}") + + // For more info: + // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html + // http://www.gradle.org/docs/current/userguide/dependency_management.html +} + +// This block of code expands all declared replace properties in the specified resource targets. +// A missing property will result in an error. Properties are expanded using ${} Groovy notation. +// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments. +// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html +tasks.named('processResources', ProcessResources).configure { + var replaceProperties = [ + minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range, + forge_version: forge_version, forge_version_range: forge_version_range, + loader_version_range: loader_version_range, + mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version, + mod_authors: mod_authors, mod_description: mod_description, + ] + inputs.properties replaceProperties + + filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { + expand replaceProperties + [project: project] + } +} + +// Example for how to get properties into the manifest for reading at runtime. +tasks.named('jar', Jar).configure { + manifest { + attributes([ + 'Specification-Title' : mod_id, + 'Specification-Vendor' : mod_authors, + 'Specification-Version' : '1', // We are version 1 of ourselves + 'Implementation-Title' : project.name, + 'Implementation-Version' : project.jar.archiveVersion, + 'Implementation-Vendor' : mod_authors, + 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + ]) + } + + // This is the preferred method to reobfuscate your jar file + finalizedBy 'reobfJar' +} + +// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing: +// tasks.named('publish').configure { +// dependsOn 'reobfJar' +// } + +// Example configuration to allow publishing using the maven-publish plugin +publishing { + publications { + register('mavenJava', MavenPublication) { + artifact jar + } + } + repositories { + maven { + url "file://${project.projectDir}/mcmodsrepo" + } + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation +} diff --git a/changelog.txt b/changelog.txt new file mode 100644 index 0000000..a32e932 --- /dev/null +++ b/changelog.txt @@ -0,0 +1,1049 @@ +1.20.1 Changelog +47.4 +==== + - 47.4.0 1.20.1 RB 4 + https://forums.minecraftforge.net/topic/154387-forge-474-minecraft-1201/ + +47.3 +==== + - 47.3.39 Fix ForgeDev's test runs not working due to dead test mod (#10483) + - 47.3.38 Cache this.useItem before running item break logic, Fixes #10344 (#10376) + - 47.3.37 Speed up mod annotation scanning by ~30% (#10470) + Co-authored-by: LexManos + - 47.3.36 Add missed license headers (#10479) + - 47.3.35 Add '#forge:chorus_additionally_grows_on' tag for similar mechanics to '#minecraft:azalea_grows_on' but for chorus (#10456) + - 47.3.34 Fix cancelling ProjectileImpactEvent still firing onBlockHit (#10481) + - 47.3.33 Honor attacker shield disabling status (#10321) + - 47.3.32 Add fast graphics render type to block model jsons (#10393) + Make modded leaves behave like vanilla leaves by default (Fixes #10389) + - 47.3.31 Fix invalidly symlinked worlds crashing on level select (#10439) + - 47.3.30 Backport even more future ResourceLocation methods (#10428) + - 47.3.29 Ensure NetworkConstants is loaded before mod construction (#10407) + - 47.3.28 Account for problematic mixins in VillagerTrades.EmeraldsForVillagerTypeItem (#10402) + - 47.3.27 Fix incorrect method reference in TntBlock.explode() + - 47.3.26 Fix issues in VillagerTrades.EmeraldsForVillagerTypeItem related to custom Villager Types (#10315) + Add VillagerType#registerBiomeType + - 47.3.25 Add `clientSideOnly` feature to mods.toml (#10085) (backport of #9804 to 1.20.1) + Co-authored-by: Jonathing + - 47.3.24 Fix non-passengers being tickable without checking canUpdate() (#10304) + - 47.3.23 Fix finalizeSpawn's return value not being used correctly (#10301) + - 47.3.22 Bump CoreMods to 5.2.4 (#10263) + - 47.3.21 Allow mipmap lowering to be disabled (#10252) + - 47.3.20 Add optional fix of use item duration, disabled by default (#10246) + - 47.3.19 Backport some Vanilla 1.21 `ResourceLocation` methods (#10241) + Co-authored-by: Paint_Ninja + - 47.3.18 Simplify memory usage display on loading screen (#10233) + Co-authored-by: Paint_Ninja + - 47.3.17 Deprecate `@ObjectHolder`, add a couple of fast-paths (#10228) + Co-authored-by: Paint_Ninja + - 47.3.16 Skip Vanilla classes for the `CapabilityTokenSubclass` transformer (#10221) + Co-authored-by: Paint_Ninja + - 47.3.15 Skip Forge classes in the RuntimeEnumExtender transformer (#10216) + Mod classes are still transformed as usual + Co-authored-by: Paint_Ninja + - 47.3.14 Skip processing Forge classes in `RuntimeDistCleaner` (#10208) + Co-authored-by: Paint_Ninja + - 47.3.13 Disable clean on TeamCity (#10258) + - 47.3.12 Bump CoreMods to 5.2 (#10130) + Full Changelog: + https://gist.github.com/Jonathing/c3ad28b2a048ac839a7baba5417ee870 + The key features are: + - ES6 language support + - Thoroughly updated ASMAPI, with full documentation + - Bug fixes (some optional for backwards-compatibility) + - Partial internal code cleanup + - Request CoreMods to not apply fix for ASMAPI.findFirstInstructionBefore by default + - Updated ASM to 9.7.1 + - Updated Nashorn to 15.4 + - 47.3.11 Remove unneeded boat patch (backport of #10061 to 1.20.1) (#10096) + Co-authored-by: andan42 <49289986+andan42@users.noreply.github.com> + - 47.3.10 Optionally supply FMLJavaModLoadingContext as a param to mod constructors (backport of #10074 to 1.20.1) (#10100) + Co-authored-by: RealMangoRage + - 47.3.9 Minor cleanup to ModListScreen and VersionChecker (backport of #9988 to 1.20.1) (#10095) + - 47.3.8 Cleanup FML Bindings (backport of #10004 to 1.20.1) (#10094) + - 47.3.7 Early display fixes/workarounds for buggy drivers. Backport of #9921 to 1.20.1 (#10073) + - 47.3.6 Add a way to render tooltips from Formatted text and TooltipComponents elements (#10055) + Backport of #10056 for 1.20.1 + - 47.3.5 Make HangingSignBlockEntity useable with custom BlockEntityTypes. #10038 + - 47.3.4 Unlock wrapped registries when firing register events. (#10035) + Co-authored-by: LexManos + - 47.3.3 Choose default JarJar mod file type based on parent JAR (#10023) + Co-authored-by: thedarkcolour <30441001+thedarkcolour@users.noreply.github.com> + - 47.3.2 Fixed falling block entities not rendering as moving blocks (#10006) (#10018) + Co-authored-by: Ven + - 47.3.1 Fix boat travel distance being incorrect. Closes #9997 #9999 + - 47.3.0 1.20.1 RB 3 + https://forums.minecraftforge.net/topic/139825-forge-473-minecraft-1201/ + +47.2 +==== + - 47.2.36 Bump gradle to 8.8 + - 47.2.35 Bump gradle and java runtime version on team city + - 47.2.34 Fix LevelSettings ignoring data configuration. Close #9938 + - 47.2.33 Fix erroneous patch in FireBlock. Closes #9996 + - 47.2.32 Fix early window crash when parsing options.txt (#9934) + Backport of #9933 + - 47.2.31 Prevent mixins from crashing the game when there are missing mods (#9916) + 1.20.1 backport of 49.0.14 + - 47.2.30 Fix NPE when acceptableValues in defineInList() does not allow nulls, backport of #9903 (#9907) + Co-authored-by: J-RAP + - 47.2.29 Fix Crowdin (#9929) + - 47.2.28 Optimise capabilities a tad, backport of #9886 (#9911) + - 47.2.27 Add helper method to `OnDatapackSyncEvent`, backport of #9901 (#9919) + - 47.2.26 Add CPU usage config option to early window, hide by default, backport of #9866 (#9915) + - 47.2.25 Fix slightly offset mods screen link positioning, backport of #9860 (#9861) + Co-authored-by: Dennis C <11262040+XFactHD@users.noreply.github.com> + - 47.2.24 Make common config screen registration tasks easier, backport of #9884 (#9912) + - 47.2.23 Add Leaves method to ModelProvider.java (#9889) + - 47.2.22 [1.20.1] Bump CoreMods and ASM (#9897) + - CoreMods 5.1.2 -> 5.1.6 + - ASM 9.6 -> 9.7 + - 47.2.21 Bump some deps (#9880) + - CoreMods 5.0.1 -> 5.1.2 + - ASM 9.5 -> 9.6 + - Installer 2.1 -> 2.2 + - Installer tools 1.3.0 -> 1.4.1 + - 47.2.20 Fix missing patch for Item.onInventoryTick. Closes #9812 + - 47.2.19 Make common DisplayTest registration tasks easier (#9823) + - 47.2.18 Optimise ForgeConfigSpec and make Range public (#9824) + Backport of #9810 to 1.20.1 + - 47.2.17 Datagen addOptionalTag/s methods that allow passing the TagKey itself instead of passing the location (#9807) (#9808) + - 47.2.16 Update VersionSupportMatrix.java (#9805) + - 47.2.15 Backport of Registries optimization, now uses fastutils collections to minimize boxing + - 47.2.14 Fix patch offset + - 47.2.13 Fix fire related mobs not taking enough freezing damage. Closes #9686 + - 47.2.12 Fix TagLoader error not printing tag name correctly. Closes #9693 + - 47.2.11 Fix LoadingErrorScreen inner headers are not centered. Closes #9687 + - 47.2.10 Rework KeyModifiers system to properly allow keybinds to be triggered when multiple modifiers are pressed. + Fix setting keybinds whel using keyboard inputs to select the menu. Closes #9793 + - 47.2.9 Fix KeyModifiers not being properly taken into account. Closes #9806 + - 47.2.8 Don't turn off VSync when rendering from Minecraft context (#9801) + Co-authored-by: embeddedt <42941056+embeddedt@users.noreply.github.com> + - 47.2.7 Fix rare crash with early display window, fixes MinecraftForge#9673 (#9799) + - 47.2.6 Fix tag loading being unordered. Closes #9774 + - 47.2.5 Fix misaligned patch in RegistryDataLoader + - 47.2.4 Backport CrashReportAnalyser to 1.20.1 (#9757) + - 47.2.3 Minor MDK changes (#9752) + - 47.2.2 Improve mod description formatting in mods screen (#9769) + Co-authored-by: Su5eD + - 47.2.1 [1.20.1] Improve mod loading error message for errors inside mod constructors (#9707) + - 47.2.0 1.20.1 RB + +47.1 +==== + - 47.1.47 Keep order of sources in PackRepository (#9702) + Co-authored-by: dhyces <10985914+dhyces@users.noreply.github.com> + - 47.1.46 Fix DelegatingPackResources searching resource path twice (#9697) + - 47.1.45 Fix `Level` leak in debug HUD (#9699) + Co-authored-by: malte0811 + - 47.1.44 Fix PlayerSpawnPhantomsEvent not being fired (#9689) + - 47.1.43 Enhance LivingBreathEvent and LivingDrownEvent. Closes #9680 + Also remove 3.5MB of useless data from the installer. + - 47.1.42 Partially revert LazyOptional changes, now no longer internally uses weak references. + - 47.1.41 Make LazyOptional's internal references to invalidation listeners use WeakReference, and allow modders to unregister themselves. Closes #8805 + - 47.1.40 Revert EntityEvent.Size changes to before #9018 was called. (#9679) + Kept newly added methods for binary compatibility but deprecated them all for removal. + The entire pose/eye/size system needs to be reevaluated and address some of Mojang's changes. + However this should fix any bugs that pulling that PR may of caused. + - 47.1.39 Add a config option to restore the calculate all normals behavior in case some setups require old broken behavior. (#9670) + - 47.1.38 Fix rounding errors on models with 45 degree normals by favoring one Direction (#9669) + Should fix flickering issues when breaking custom models and having our vanilla solution disabled. + - 47.1.37 Moved ForgeHooksClient.onCreativeModeTabBuildContents to ForgeHooks to fix #9662 + - 47.1.36 Fix tag removal functionality that broke during the 1.19 update. Closes #9053 and #8949 + - 47.1.35 Replace string with forge tag in vanilla recipes. Closes #9062 + - 47.1.34 Fix new brain hooks not persisting active activities. + - 47.1.33 Fix breaking overlay flickering on campfires by using vanilla method to calculate block normals. (#9664) + - 47.1.32 Cleanup usages of static imports and build script so that our build doesn't spam useless error like messages. + So that it is easier to see real errors. + Add compatibility checking to standard testing tasks. + - 47.1.31 Added Action value to PlayerInteractEvent.LeftClickEvent to expose what action fired the event. #9175 + - 47.1.30 Fix parameter names in IForgeDimensionSpecialEffects.adjustLightmapColors to better describe what they are. (#9656) + - 47.1.29 Re-add EntityEvent.Size methods to maintain bincompat + - 47.1.28 Added LivingMakeBrainEvent, to allow a consistent way for modders to manipulate entity Brains. #9292 + - 47.1.27 Add LivingSwapHandItemsEvent + - 47.1.26 Fixed FluidUtil#tryFillContainer returning invalid result when simulating #9358 + - 47.1.25 Re-add in-game mod menu (#9652) + - 47.1.24 Fix Entity eye height for multipart entities. + - 47.1.23 Fix conflicting keybindings not having the correct click count set. #9360 + - 47.1.22 Fix the Emissive Rendering for Experimental Light Pipeline (#9651) + - 47.1.21 Fixed AdvancementsScreen.java.patch buttons not rendering (#9649) + - 47.1.20 Properly Handle Fluid Updates while in a Boat #9428 + - 47.1.19 New hook in IClientBlockExtensions to handle enabling tinting on breaking particles. #9446 + - 47.1.18 Fix invalid index when ticking itemstacks in a player nventory by adding a new onInventoryTick event. Closes #9453 + - 47.1.17 Make the FireworkShapes enum extensible (Closes #9486) + - 47.1.16 Add `EmptyEnergyStorage` (#9487) + - 47.1.15 Support IPv6 address compression for logged IPs + - 47.1.14 Make item name rendering and status bar rendering respect additional gui overlays being rendered by mods (#9648) + - 47.1.13 Fix EyeHeight event being fired twice (#9647) + - 47.1.12 Add PlayerSpawnPhantomsEvent, utilized to block or forcefully allow PhantomSpawner to spawn phantoms (#9644) + - 47.1.11 Fix creative mode screen not correctly using CreativeModeTab::getTabsImage (#9627) + - 47.1.10 Add option to advertise dedicated servers to LAN. + - 47.1.9 Fix entity eye height loop. + - 47.1.8 Particle Description Data Provider. + - 47.1.7 Add LivingBreatheEvent and LivingDrownEvent (#9525) + - 47.1.6 Fix entity size event not being fired, changed it to split eye height and size calculations. (#9535) + - 47.1.5 AlterGroundEvent for modifying block placement performed by AlterGroundDecorator (#9637) + - 47.1.4 Change ProjectileHitEvent to return a result instead of being cancelable. Closes #9642 + - 47.1.3 Replace static import with regular one to fix S2S and non-official mappings. (#9633) + - 47.1.2 Add missing null check for TagsProvider#existingFileHelper (#9638) + - 47.1.1 Add GuiGraphics helpers for blitNineSliced and blitRepeating that support specifying a custom texture size (#9641) + - 47.1.0 1.20.1 Recommended Build + +47.0 +==== + - 47.0.50 Fix FMLOnly loading. Closes #9609 + - 47.0.49 Improve logging for server connections (#9618) + - 47.0.48 Fix placing fluids into waterlogged blocks with FluidUtil::tryPlaceFluid. To behave more like vanilla MC-127110 (#9586) + - 47.0.47 Expose loaded RegistryAccess through AddReloadListenerEvent (#9613) + - 47.0.46 Fix GLM applying to entities when killed. Closes #9551 + - 47.0.45 Add unordered creative tabs after vanilla and perform a second level sorting of tabs by registry name to ensure tabs are ordered the same between game restarts (#9612) + - 47.0.44 Fix Early Loading window FPS snafu where it could spam (#9619) + unlimited screen updates. Probably a good way to gently toast an ancient laptop. + - 47.0.43 Make overloads consistent for defineListAllowEmpty in ForgeConfigSpec.Builder (#9604) + - 47.0.42 Moved GameShuttingDownEvent hook to DedicatedServer class. Fixes #9601 + - 47.0.41 Fix PitcherCropBlock not calling canSustainPlant, not allowing it to be placed on custom farmland. Close #9611 + - 47.0.40 Add null check to NetworkHooks.openScreen. Closes #9597 + - 47.0.39 Fix ShieldBlockEvent not correctly performing damaged functions when not all damage is blocked. (#9615) + - 47.0.38 Add IP address to client disconnect message. Closes #9603 + - 47.0.37 Fix hotbar items not dimming when sleeping in bed. Closes #9616 + - 47.0.36 Bump Eventbus to address NullPointerException when classloading things on some threads. Closes #9570 + - 47.0.35 Try and be a bit nicer about handling bad [feature] definitions (#9606) + * Try and be a bit nicer about handling bad [feature] definitions - they're single square bracket defined and require strings for feature bound values. + * Some more tweaks to the feature system to output useful and well formatted error messages when bounds fail. Requires SPI 7.0.1 and the language string "fml.modloading.feature.missing" has changed. + * Use immutable lists where possible and generally tidy things a bit + - 47.0.34 [HotFix]: Somehow not caught by CI, but there was an issue in the SpawnUtils to handle. + - 47.0.33 Remove amount from FluidStack hashCode to fix the equal/hashCode java contract (#9602) + - 47.0.32 Add example usage for configs to the MDK (#9596) + Demonstrates proper usage of different config value types, validation, transformation/parsing, load/reload handling and direct field access. + - 47.0.31 Demonstrate configureEach in run configs (#9594) + - 47.0.30 Reduce verbosity of prepareRuns doc in MDK (#9593) + - 47.0.29 Lazily configure MDK tasks, improve IDE support (#9592) + - 47.0.28 Fix not dropping xp for player sourced explosions and various other cases when xp should drop (#9588) + - 47.0.27 add item handler capability to chiseled bookshelf (#9587) + - 47.0.26 Fix ignoring maxUpStep method overrides on entities (#9583) + - 47.0.25 Add missing damage type tag provider modid, existing file helper constructor overload (#9581) + - 47.0.24 Expose holder lookup registry provider as a helper in RegistriesDatapackGenerator (#9580) + - 47.0.23 Fix gametest collection causing secondary crash in loading error state (#9568) + - 47.0.22 Fix SpriteCoordinateExpander not working with chained methods (MC-263524) (#9564) + - 47.0.21 Expose EntityRendererProvider.Context to AddLayers event (#9562) + - 47.0.20 [1.20] Add events for checking spawn conditions (SpawnPlacementCheck and PositionCheck) (#9469) + - 47.0.19 Another tweak to the early display. We start a timer process while we create the window, in case it hangs. Also add a skip version config, to try and help in cases where the driver is stupid. (#9595) + - 47.0.18 Auto generate names for modded loot pools. Fixes #9589 (#9591) + - 47.0.17 More tweaks to the mod loading callbacks to make loading bars work better (#9585) + - 47.0.16 Reimplement LootPool name patches and hooks (#9573) + - 47.0.15 Fix experimental lighting pipeline breaking vanilla's emissive rendering. Closes #9552 (#9582) + - 47.0.14 Update early loading default configs to match standard expectations. (#9577) + Also allow a global override env variable for darkmode always. "FML_EARLY_WINDOW_DARK" + - 47.0.13 Add proper duplicate mod error message that includes the mod id(s) and mod files. (#9474) + - 47.0.12 Add missing stack tooltip rendering hooks (#9533) + Fix automatic tooltip wrapping discarding empty lines used as spacers + - 47.0.11 Add piston push reaction overrides to Block class (#9538) + - 47.0.10 Fix missing calls to level-sensitive block SoundType getter (#9553) + - 47.0.9 Fix forge registries that have wrappers/support tags not being in the HolderLookup Provider that is provided to the GatherDataEvent (#9566) + - 47.0.8 Make IItemDecorator a functional interface again. Fixes #9563 (#9574) + - 47.0.7 Make 1.20.x the main TC branch. + - 47.0.6 Fix custom geometry in parent models not being resolved (#9572) + - 47.0.5 Make the scheduled thread factory setDaemon on it's threads. Should allow things to close properly if something deadly happens early on. (#9575) + - 47.0.4 This is an early display window system for forge. (#9558) + - 47.0.3 fix the JIJ break by bumping SJH. apologies. + - 47.0.2 update libs (#9565) + - 47.0.1 Update Armor Layer Implementation to Match Vanilla (#9547) + - 47.0.0 1.20.1 Update + +46.0 +==== + - 46.0.14 Fix JAR compatibility checks for 1.20 (#9556) + - 46.0.13 [1.20] Add `AFTER_LEVEL` render level stage (#9555) + - 46.0.12 Reorder overlay layers to match vanilla (#9550) + - 46.0.11 Re-implement missing level-sensitive block light hook in ChunkAccess (#9536) + - 46.0.10 Fix issues in the deserialization of empty ingredients (#9537) + - 46.0.9 Fix wrong variable passed into EnchantmentClue lookup Fixes #9543 (#9544) + - 46.0.8 Fix incorrect depth test state in debug graph rendering Fixes #9534 (#9539) + - 46.0.7 Fix initCapabilities patch location in ServerLevel Fixes #9526 (#9531) + - 46.0.6 Use Spinning Effect Intensity instead of Partial Tick for Portal Overlay Fixes #9529 (#9530) + - 46.0.5 Fix getArmorModelHook patch, Fixex #9523 (#9528) + - 46.0.4 Fix duplicate Map writes in PlayerList patch. (#9521) + - 46.0.3 Fix Forge Version including MC version in MDK. + - 46.0.2 Fix patch in light propagation (#9532) + - 46.0.1 Attempt to fix jar signing + Gradle 8 is stupid and doesn't (easily) allow in-place tasks, so a temporary fix has been made in ForgeGradle 6 + - 46.0.0 Forge 1.20 + - Creative mode tabs are now a registry; the `BuildContents` event was renamed to `BuildCreativeModeTabContentsEvent` and moved it to its own class + - The pack format is now 15 for both resource packs and data packs + - `ScreenUtils` was deprecated in favor of a `GuiGraphics` extension + - Forge and the MDK were updated to Gradle 8 and FG6 + - The Forge common config file was removed (it only contained the deprecated old fields for resource caching, which was removed in 1.19.3) + - Registry dummy entries were removed + - `RemappingVertexPipeline` was fixed to forward the `endVertex()` call + - Forge tool tags were removed in favor of vanilla ones + Co-authored-by: ChampionAsh5357 + Co-authored-by: coehlrich + Co-authored-by: Dennis C <11262040+XFactHD@users.noreply.github.com> + Co-authored-by: Matyrobbrt + +45.1 +==== + - 45.1.0 1.19.4 Recommended Build + +45.0 +==== + - 45.0.66 Add method to GatherDataEvent to obtain collection of all input paths. (#9499) + - 45.0.65 Log error when Sheets is class-loaded before registration is completed (#9475) + - 45.0.64 [1.19.x] Re-implement RenderTooltipEvent.Color (#9497) + * Reimplement RenderTooltipEvent.Color + * Formatting, comments, EXC + * Deprecate instead of replacing + - 45.0.63 Add API for registering custom world preset editors (#9436) + - 45.0.62 Remove unneeded extra reload of datapacks on world creation screen (#9454) + - 45.0.61 Bump ASM to 9.5 + - 45.0.60 Fix crash when running server from root directory + Fixes #9498 + - 45.0.59 Fix root transform matrix format, allow using all four root transform formats (#9496) + - 45.0.58 Add missing AT lines to allow registering custom game rule boolean/integer types (#9489) + - 45.0.57 [1.19.x] Fix SaplingGrowTreeEvent#setFeature being ignored in FungusBlock (#9485) + Co-authored-by: Brennan Ward <3682588+Shadows-of-Fire@users.noreply.github.com> + - 45.0.56 Restore AccessibilityOnboardingScreen + Fixes #9488 + - 45.0.55 Update documentation on FinalizeSpawn (#9467) + - 45.0.54 Fix fluids without sound event causing exception in tryFillContainer and tryEmptyContainer (#9445) + - 45.0.53 Make FakePlayerFactory respect the given ServerLevel (#9479) + - 45.0.52 Collect and log exceptions occurring in DeferredWorkQueue tasks (#9449) + - 45.0.51 Fix `NamespacedWrapper#wrapAsHolder` (#9450) + - 45.0.50 Fixes ChatScreen calling .setScreen (#9443) + Fix test compile failures also. + - 45.0.49 Determine the Forge version the PR was built against when running PR compat checks (#9374) + - 45.0.48 Add buildscript test to error on deprecated members that should of been removed. (#9460) + - 45.0.47 Remove erroneous brace patch in Inventory (#9462) + Fixes #9459 + - 45.0.46 [1.19.4] Move root transform builder to ModelBuilder to allow use in ItemModelBuilder (#9456) + - 45.0.45 Fix forge grindstone hooks allowing stacks of non-stackable items (#9457) + - 45.0.44 [1.19.4] Fix FMLOnly (#9415) + - 45.0.43 Fix ItemLayerModel erroneously adding particle texture to layer texture list (#9441) + - 45.0.42 Temporary fix for Canceling ProjectileImpactEvents of Piercing ammo. + Event needs to be re-worked to have finer control. #9370 + - 45.0.41 Fix dummy air blocks not being marked as air (#9440) + - 45.0.40 Add support for splitting the login packet (#9367) + It contains full copies of data registries and can easily surpass vanilla's limits + - 45.0.39 Remove Attack Range and Reach Distance and add Block Reach and Entity Reach (#9361) + - 45.0.38 Add default bucket sounds for milk (#9432) + - 45.0.37 Deprecate Item.onUsingTick, as vanilla provides the same function in Item.onUseTick now. Closes #9342 + - 45.0.36 Fix ScreenEvent.Init.[Pre/Post] not working correctly (#9431) + - 45.0.35 Allow FenceGateBlock to be used without a WoodType. Closes #9392 + - 45.0.34 Deprecate duplicate tool tags that vanilla added in 1.19.4 + We will maintain a seperate 'tools' tag until Mojang adds all relevent tool tags. + Closes #9393 + - 45.0.33 Fix BlockEvent.Break not using ItemStack enchantment hooks. + - 45.0.32 Move Block.onCatchFire to above block removal to allow usage of BlockEntity data. Closes #9400 + - 45.0.31 Fix FinalizeSpawn not blocking spawns during worldgen (#9420) + - 45.0.30 Fixed issue with MutableHashedLinkedMap when removing multiple sequential entries in the middle of the map. + Added Unit tests for MutableHashLinkedMap + Added support for removing using the iterator + Added concurrent modification detection to the iterator + Added default constructor with basic hashing strategy. + Closes #9426 + - 45.0.29 Loosen access for BucketItem's canBlockContainFluid (#9421) + - 45.0.28 Update and Regenerate Datapacks (#9419) + Add generation for pack.mcmeta + - 45.0.27 Restore ability to change message in ClientChatEvent (#9377) + - 45.0.26 Remove duplicate line in FoodData patch (#9424) + The line was accidentally duplicated in the 1.19.4 update and patching + process. + Fixes #9422 + - 45.0.25 Rename RegisterParticleProviderEvent's register methods to describe what kind of particle providers they register (deprecating old methods to avoid breaking) and minor docs tweaks (#9388) + - 45.0.24 Update pack versions (#9414) + - 45.0.23 [1.19.4] Revamp and fix spawn events (#9133) + - 45.0.22 [1.19.4] Replace blitOffset parameter with PoseStack in IItemDecorator (#9409) + * Replace blitOffset with PoseStack in IItemDecorator + * Circumvent breaking changes + * Fix blitOffset type + - 45.0.21 Fix JSON model root transforms (#9410) + - 45.0.20 Fix tossed items not being able to be picked up by other players. Closes #9412 (#9404) + - 45.0.19 Fix infinite BE render bounds failing frustum intersection test. Closes #9321 (#9407) + - 45.0.18 Make ForgeSlider use the new vanilla texture (#9406) + - 45.0.17 Add BlockSetType#register to accesstransformer.cfg (#9386) + - 45.0.16 Add option to completely hide a crash-callable depending on a runtime value (#9372) + - 45.0.15 Add isNewChunk to ChunkEvent.Load (#9369) + - 45.0.14 Remove DistExecutor calls in PistonEventTest (#9348) + - 45.0.13 Fix hardcoded precipitation in ClimateSettingsBuilder (#9402) + This effectively caused all biomes to have precipitation, such as + minecraft:desert. + Fixes #9397 + - 45.0.12 Fix incorrect variable used for swimming check (#9403) + Because of the incorrect variable, the check to stop sprinting (and stop + swimming) never fired correctly. + 1.19.3's `flag5` variable was renamed to `flag7` in 1.19.4; however, + this was not caught during patching because of the fuzzy patcher. + Fixes #9399 + - 45.0.11 Fix incorrect boolean used for glint effect (#9401) + The `flag1` variable is ultimately controlled by whether the armor slot + being rendered is for the leggings, which explains this bug where the + leggings always had the enchantment glint but not any other armor piece. + Fixes #9394 + - 45.0.10 Fixed ModMismatchDisconnectedScreen displaying missing mods wrongly (#9398) + - 45.0.9 Fix misaligned text render type patch (#9391) + - 45.0.8 Remove thread filter from processing clientside custom payloads. Closes @9390 + - 45.0.7 Fix LivingEntity patch which caused crash while entities got hurt. Closes #9389 + - 45.0.6 Fix wrong parameters in `Screen#renderTooltipInternal` patch (#9387) + - 45.0.5 Fix misaligned patch in LevelRenderer. Closes #9385 + - 45.0.4 Remove our fix for MC-121048 as it has been fixed by Vanilla (#9381) + - 45.0.3 Fix advancements not loading, bug seems to be fixed by vanilla now. Closes #9384 + - 45.0.2 Fixed patch verifier for cases where patches lowered access levels. Closes #9383 + - 45.0.1 Fix crouching while sprinting stopping the player when step height is modified. Closes #9376 + - 45.0.0 Forge 1.19.4 + Properly move `ServerStatusPing` to codec + Reimplement custom display contexts + Co-authored-by: Matyrobbrt + Co-authored-by: coehlrich + +44.1 +==== + - 44.1.23 Fix experimental world warning screen appearing everytime (#9375) + - 44.1.22 Fix continuing to use items after dropping or when a shield breaks (MC-231097, MC-168573) (#9344) + - 44.1.21 Add onStopUsing hook to IForgeItem (#9343) + - 44.1.20 Document RegisterParticleProvidersEvent's APIs (#9346) + - 44.1.19 Fix incorrect ListTag.getLongArray result (MC-260378) (#9351) + - 44.1.18 Fix missing patch that left TagBuilder#replace unused (#9354) + - 44.1.17 Add 2 new RenderLevelStageEvent.Stage for After Entities and After Block Entities (#9259) + - 44.1.16 Cleanup StemBlock Patch (#9337) + - 44.1.15 Cleanup ItemProperties patch (#9332) + - 44.1.14 Make IForgeIntrinsicHolderTagAppender methods properly chainable (#9331) + - 44.1.13 Fix in custom fluids not respecting max height correctly. (#9319) + - 44.1.12 Fix inconsistent vaporization in BucketItem & FluidType (#9269) + - 44.1.11 Fix reloading event firing during server shutdown and add explicit unloading event instead (#9016) + - 44.1.10 Homogenize and/or holdersets when serializing to prevent serializing to NBT from crashing (#9048) Fixes #9043 + - 44.1.9 [1.19.x] Fix `ForgeSlider` not respecting custom height (#9237) + - 44.1.8 Fix stepsound for blocks in the inside_step_sound_blocks tag. (#9318) + - 44.1.7 Fix missing hanging sign material for modded wood type (#9303) + - 44.1.6 Fire TickEvent.LevelTickEvent on ClientLevel tick (#9299) + - 44.1.5 Add ClientChatReceivedEvent for system messages (#9284) + - 44.1.4 PR Action update (#9274) + - 44.1.3 fix HangingSignEditScreen crash when using custom wood types using modid (#9294) + - 44.1.2 Bump SecureJarHandler version, to help identify invalid mods. + - 44.1.1 [1.19.3] Hotfix missing null check in createUnbakedItemElements (#9285) + - 44.1.0 Mark 1.19.3 Recommended Build + +44.0 +==== + - 44.0.49 [1.19.3] Allow Item and Elements models to specify static color, sky light, and block light values. (#9106) + - 44.0.48 Fix StemBlock not checking canSustainPlant for the correct block, it now checks for Melons/Pumpkins instead of the stem itself. (#9270) + - 44.0.47 Add github shared actions for automation purposes. (#9251) + - 44.0.46 Add translate key for Forge pack.mcmeta description (#9260) + - 44.0.45 Fix broken link for update checker docs in mdk (#9271) + - 44.0.44 Remove duplicate updateNeighbourForOutputSignal call Fixes #9169 (#9234) + - 44.0.43 Add helper methods to access the set of loaded sprite locations (#9223) + - 44.0.42 Disable guiLight3d for generated item models (#9230) + - 44.0.41 Remove resource caching (#9254) + - 44.0.40 Add TradeWithVillagerEvent (#9244) + - 44.0.39 Update link for Parchment "Getting Started" (#9243) + - 44.0.38 Allows DatapackBuiltinEntriesProvider to datagen LevelStems (#9247) + - 44.0.37 Add a method to LootContext.Builder that allows changing the queried loot table id (#9084) + - 44.0.36 [1.19.3] Fix Datagen Tests and Providers (#9212) + - 44.0.35 Fix concrete powder not being hydrated by singular water sources (#9236) + - 44.0.34 [1.19.3] Fix LootTableLoadEvent not getting fired (#9239) + - 44.0.33 Allow using custom factories in button builders (#9238) + - 44.0.32 Fix logspam when a root resource is requested from DelegatingPackResources, fixes #9197 (#9227) + - 44.0.31 [1.19.3] Fix `retrieveRegistryLookup` attempting to get the registry lookup from a `HolderGetter` (#9225) + - 44.0.30 [1.19.3] Add ability to datagen forge specific values in pack.mcmeta (#9221) + Co-authored-by: sciwhiz12 + - 44.0.29 Add block atlas config to register forge:white texture (#9187) + - 44.0.28 Fix ExtendedButton not being highlighted when focused (#9144) + - 44.0.27 Separate checkAndFix from the check* tasks. (#9213) + - 44.0.26 Fix forge resources overriding vanilla ones (#9222) + - 44.0.25 Fix tooltip customization not working for creative inventory (#9218) + - 44.0.24 Fix glowing item frame entity's texture (#9126) + Fixes #9123 + - 44.0.23 Fix datapack registries not being synced to clients (#9219) + - 44.0.22 Fix creatives tabs rendering overlapping tabs if the selected tab isn't on the current page. (#9214) + - 44.0.21 Fix `SidedInvWrapper` not accounting for vanilla stacking special cases in brewing stands and furnaces (#9189) + - 44.0.20 Update to the latest JarJar. (#9217) + - 44.0.19 Specify NetworkHooks#getEntitySpawningPacket Generic Return Type (#9220) + - 44.0.18 Fix using a DeferredRegister on a non-forge wrapped registry. Closes #9199 + - 44.0.17 Add support for custom CreativeModeTab implementations (#9210) + - 44.0.16 Simplify tree grower patches (#9209) + - 44.0.15 Replace AdvancementProvider patch with Forge helper (#9188) + - 44.0.14 Allow using `PackOutput`s in Forge-added datagen classes (#9182) + - 44.0.13 Add simpleBlockWithItem for data gens (#9170) + - 44.0.12 Fix running test mods (#9211) + - 44.0.11 [1.19.3] Fix models nested in custom geometries not resolving parents (#9200) + - 44.0.10 Fix OBJ Loader caches not being thread-safe. (#9204) + - 44.0.9 [1.19.3] Add event before baked models are cached by the BlockModelShaper (#9190) + - 44.0.8 Fix compatibility checker task configuration (#9202) + - 44.0.7 Fix chat offset (#9184) + - 44.0.6 Redesign CreativeTab collection event to be a lot more straight forward. (#9198) + - 44.0.5 Move ICondition patch placement to before MC throws an error. + Disable the explicitly erroring test biome modifier. + - 44.0.4 Fix BlockStateProvider not waiting for models before finishing. (#9196) Fixes #9195: + - 44.0.3 Fix tooltips not rendering on screens. Closes #9191 + - 44.0.2 Fix merged mod resource pack not returning all resources with the same name when asked. Closes #9194 + - 44.0.1 Fix searching using the wrong prefix for items or tags. Fixes #9176 Fixes #9179 (#9177) + - 44.0.0 Forge 1.19.3 + Created a CreativeModeTabEvent to register creative mode tabs and populate entries per tab + Moved datapack registries to DataPackRegistryEvent.NewRegistry event instead of tying them to ForgeRegistry + Made it easier for mods to datagen datapack builtin entries with DatapackBuiltinEntriesProvider + Provided access to lookupProvider for datagen + Updated dependencies to match versions used by vanilla and update JarJar to 0.3.18 + Added a test mod for the new CreativeModeTabEvent + Throws better error message for Forge registries in tag datagen + Deleted ForgeRegistryTagsProvider + Updated ClientChatReceivedEvent and ServerChatEvent for Mojang changes + Added patches for both sign related methods in ModelLayers + Changed RegisterShadersEvent to use ResourceProvider + Migrated old Mojang math types to JOML + Co-authored-by: Marc Hermans + Co-authored-by: LexManos + Co-authored-by: sciwhiz12 + Co-authored-by: coehlrich + +43.2 +==== + - 43.2.0 43.2 Recommended Build. + +43.1 +==== + - 43.1.65 Allow discovering services from the mods folder that use java's modular definition. (#9143) + - 43.1.64 Make Datapack Registries support ICondition(s) (#9113) + - 43.1.63 Enable additional build types to handle pull request validation. (#9159) + - 43.1.62 Check source permission level before selector permission (#9147) + In some situations, such as execution of a function by an advancement as + part of its reward, a command source stack may have a backing source of + a ServerPlayer which may lack the entity selector permission and have an + explicit permission level that should allow the use of entity selectors, + through CommandSourceStack#withPermission. + We now check if the permission level of the command source stack is + sufficient for entity selectors _before_ checking if the source is a + player and if they have the requisite permission. + This means that an operator permission level of 2 will always override + the Forge entity selector permission. + Fixes #9137 + - 43.1.61 Fix fires spreading too/igniting custom portal frames. (#9142) + - 43.1.60 Add supplier to FlowerBlock so it works with custom MobEffects (#9139) + - 43.1.59 Fix some logical bugs related to the Grindstone Event (#9089) + - 43.1.58 Call baked model's `getModelData` before `getRenderTypes` (#9163) + - 43.1.57 Make Util.memoize thread-safe (#9155) + - 43.1.56 Rendering tweaks and fixes: Part 4 (#9065) + - 43.1.55 Fix `Transformation` loading `PoseStack` (#9083) + - 43.1.54 Add simple block appearance API (#9066) + - 43.1.53 Fix invalidated modded packets when on LAN (#9157) + - 43.1.52 Improve extensibility of DetectorRailBlock and PoweredRailBlock (#9130) + - 43.1.51 Fix launch handler minecraft classpath locator (#9120) + - 43.1.50 Add HitResult to `EntityTeleportEvent$EnderPearl` (#9135) + - 43.1.49 Throw aggregate exception for erroneous registry event dispatch (#9111) + This means that exceptions occurring during the dispatch of the registry + events, such as those from the suppliers of RegistryObjects, properly + cause a crash rather than merely being logged and allowing the game to + reach the main menu. + Fixes #8720 + - 43.1.48 Add missing semi-colon near the Dist import statement in example mod. + - 43.1.47 Fix ClientModEvents example not subscribing to client-sided events (#9097) + - 43.1.46 Use GitHub action to lock issues with the `spam` label (#9087) + - 43.1.45 Remove structures slave map to Feature registry (#9091) + - 43.1.44 Improve logging of missing or unsupported dependencies (#9104) + - 43.1.43 [1.19.x] Fix ValueSpec caching the return value incorrectly (#9046) + - 43.1.42 [1.19.x] Add event for registering spawn placements, and modifying existing (#9024) + - 43.1.41 [1.19.x] Add event for items being stacked or swapped in a GUI. (#9050) + - 43.1.40 [1.19.x] Fix PlayerInteractEvent.EntityInteractSpecific not cancelling on a server (#9079) + - 43.1.39 Fix canceling phantom spawns preventing any further attempts that tick. (#9041) + - 43.1.38 Rename fluid type milk translation keys (#9077) + - 43.1.37 Fix minecart speed with water (#9076) + - 43.1.36 Add a cancellable event that gets fired when a Totem of Undying is used (#9069) + - 43.1.35 Fix performance issue and logging when resource caching is enabled (#9029) + - 43.1.34 Fix NPE when feeding wolves and cats (#9074) + - 43.1.33 Fix logically breaking change to ForgeConfigSpec.Builder#comment where modders could not add a empty line to the start of comments. (#9061) + - 43.1.32 Fix ServiceLoader bug + - 43.1.31 Fix ClientChatReceivedEvent for system messages + - 43.1.30 Make ForgeConfigSpec$Builder.comment able to be called multiple times for the same entry. (#9056) + - 43.1.29 Fix control modifier for mac with `KeyMapping`s using Alt instead of Super (#9057) + - 43.1.28 Fix is_desert tag not being applied correctly. (#9051) + - 43.1.27 Fix mob griefing event for SmallFireballs not using owner entity. (#9038) + - 43.1.26 Fix minecarts on rails not properly slowing down in water (#9033) + - 43.1.25 Change codestyle for BookShelves tag. Closes #9027 + Add IS_CAVE tag Closes #8885 + Add IS_DESERT tag Closes #8979 + Simplify Mangrove Swamp tags Closes #8980 + - 43.1.24 Allow faces of an "elements" model to have disabled ambient occlusion (#9019) + - 43.1.23 [1.19.x] Recipe ID-based grouping between modded and vanilla recipes. (#8876) + - 43.1.22 Update fence_gates/wooden (#8936) + - 43.1.21 [1.19.x] Added event for growing fungus (#8981) + - 43.1.20 Added Bookshelves block tag (#8991) + - 43.1.19 Create a Forge EntityType Tag for Bosses (#9017) + - 43.1.18 Allow mods to specify shader import namespace (#9021) + - 43.1.17 Grindstone Events (#8934) + One to modify the output, and one to modify the input. + - 43.1.16 Fix the serialized names of the enum (#9014) + - 43.1.15 Fix `tryEmptyContainerAndStow` duping fluids with stackable containers (#9004) + - 43.1.14 Add mod mismatch event (#8989) + - 43.1.13 [1.19.x] add methods with more context to tree growers (#8956) + - 43.1.12 [1.19.X] Adding more precise events for Advancements (#8360) + - 43.1.11 Default IItemHandler capability for shulker box itemstacks (#8827) + Co-authored-by: LexManos + - 43.1.10 [1.19] Add hook for items to remain in the hotbar when picking blocks/entities (#8872) + - 43.1.9 [1.19.x] Block Model Builder Root Transform Support (#8860) + Co-authored-by: sciwhiz12 + - 43.1.8 [1.19.x] Make LivingSetAttackTargetEvent compatible with the Brain/Behavior system. (Port of PR #8918) (#8954) + - 43.1.7 [1.19.x] Add IForgeBlock#onTreeGrow to replace IForgeBlock#onPlantGrow from 1.16 (#8999) + - 43.1.6 [1.19.x] Moved Player.resetAttackStrengthTicker() to the end of Player.attack() (#9000) + - 43.1.5 fix misplaced patch in sapling block (#9005) + - 43.1.4 Fix failed entity interactions consuming the click. (#9007) + - 43.1.3 Fix entity selector permission check to check original source (#8995) + Permission checks should be against the command source and not the + target entity, as is done in vanilla. + Fixes #8994 + - 43.1.2 Hotfix for 1.19.2 item animation bug (#8987) + * [HOT FIX]: Fixes #8985 by no-oping for vanilla models instead of throwing error + - 43.1.1 Add ability to Auto register capabilities via annotation (#8972) + - 43.1.0 1.19.2 RB + +43.0 +==== + - 43.0.22 Added ItemDecorator API (#8794) + - 43.0.21 [1.19.x] Custom usage animations for items (#8932) + - 43.0.20 Allow registering custom `ColorResolver`s (#8880) + - 43.0.19 [1.19] Allow custom outline rendering on EntityRenderers and BlockEntityRenderers (#8938) + - 43.0.18 Redirect checks for entity selector use to a permission (#8947) + This allows greater flexibility for configuring servers with + operator-like permissions to user groups through the permissions API and + their permissions handler of choice without needing to grant the + vanilla operator permission to any player. + The new permission is "forge:use_entity_selectors", which is granted by + default to players with permission level 2 (GAMEMASTERS) and above. + The hook falls back to checking the permission level if the source of + the command is not a ServerPlayer, such as for command blocks and + functions. + - 43.0.17 Allow FakePlayer to report its position (#8963) + - 43.0.16 Add alternate version of renderEntityInInventory to allow for directly specifying the angles (#8961) + - 43.0.15 Add cancellable ToastAddEvent (#8952) + - 43.0.14 Modify ScreenEvent.RenderInventoryMobEffects to allow moving the effect stack left or right (#8951) + - 43.0.13 Fix Enchantment#doPostHurt and Enchantment#doPostAttack being called twice for players. Fixes MC-248272 (#8948) + - 43.0.12 Remove reflective implementation of ICustomPacket. (#8973) + Make vanilla custom packets able to be sent multiple times. Closes #8969 + - 43.0.11 Filter name spaces to directories only. Closes #8413 + - 43.0.10 Fix a corner case where the UMLB can not extract a version from a library. (#8967) + - 43.0.9 Fix worlds with removed dimension types unable to load. (#8959) Closes #8800 + - 43.0.8 Fix issue where unknown chunk generators would cause DFU to fail. (#8957) + - 43.0.7 Fix comments and documentation that were missed during the review of #8712 (#8945) + - 43.0.6 Make AnvilUpdateEvent fire even if the second input is empty, which means it fires even if only changing the item name. (#8905) + - 43.0.5 Fix `LivingEntity#isBlocking` to use `ToolActions#SHIELD_BLOCK` instead of `UseAnim#BLOCK` (#8933) + - 43.0.4 Add Custom HolderSet Types allowing for logical combining of sets. (#8928) + - 43.0.3 Add values to VersionSupportMatrix to support loading mods that restrict versions to 1.19.1 on 1.19.2 (#8946) + - 43.0.2 Fix certain particles not updating their bounding box when their position changes (#8925) + - 43.0.1 Update EventBus to address concurrency issue in ModLauncher Factory. Closes #8924 + - 43.0.0 1.19.2 + +42.0 +==== + - 42.0.9 Remove calls to getStepHeight in Player#maybeBackOffFromEdge (#8927) + - 42.0.8 Add forge tags for tools and armors, these DO NOT replace ToolActions, and are designed just for Recipes. (#8914) + - 42.0.7 Add Biomes.BEACH to Tags (#8892) + - 42.0.6 Let NetworkInstance.isRemotePresent check minecraft:register for channel IDs. (#8921) + - 42.0.5 Add an event for when the chunk ticket level is updated (#8909) + - 42.0.4 Re-add PotentialSpawns event (#8712) + - 42.0.3 Fix misplaced patch in ItemEntityRenderer breaking ItemEntityRenderer#shouldBob() (#8919) + - 42.0.2 [1.19] [HotFix] Fix the dedicated server not having access to the JiJ filesystems. (#8931) + - 42.0.1 Match Mojang's action bar fix for MC-72687 (#8917) + - 42.0.0 Forge 1.19.1 + Load natives from classpath + Make command argument types a forge registry + Add `EntityMobGriefingEvent` to `Allay#wantsToPickUp` + Overhaul `ServerChatEvent` to use `ChatDecorator` system + Remove `ClientChatEvent#setMessage` for now + Gradle 7.5 + +41.1 +==== + - 41.1.0 Mark 1.19 RB + +41.0 +==== + - 41.0.113 Allow faces of an "elements" model to be made emissive (#8890) + - 41.0.112 Fix invalid channel names sent from the server causing the network thread to error. (#8902) + - 41.0.111 Fix PlayerEvent.BreakSpeed using magic block position to signify invalid position. Closes #8906 + - 41.0.110 Fix cases where URIs would not work properly with JarInJar (#8900) + - 41.0.109 Add new hook to allow modification of lightmap via Dimension special effects (#8863) + - 41.0.108 Fix Forge's packet handling on play messages. (#8875) + - 41.0.107 Add API for tab list header/footer (#8803) + - 41.0.106 Allow modded blocks overriding canStickTo prevent sticking to vanilla blocks/other modded blocks (#8837) + - 41.0.105 Multiple tweaks and fixes to the recent changes in the client refactor PR: Part 3 (#8864) + Fix weighted baked models not respecting children render types + Allow fluid container model to use base texture as particle + Fix inverted behavior in composite model building. Fixes #8871 + - 41.0.104 Fix crossbows not firing ArrowLooseEvent (#8887) + - 41.0.103 Add User-Agent header to requests made by the update checker (#8881) + Format: Java-http-client/ MinecraftForge/ / + - 41.0.102 Output the full path in a crash report so it is easier to find the outer mod when a crash in Jar-In-Jar occurs. (#8856) + - 41.0.101 Clean up the pick item ("middle mouse click") patches (#8870) + - 41.0.100 [1.19.x] Hotfix for test mods while the refactor is ongoing + - 41.0.99 add event to SugarCaneBlock (#8877) + - 41.0.98 Fix Global Loot Modifiers not using Dispatch Codec (#8859) + - 41.0.97 Allow block render types to be set in datagen (#8852) + - 41.0.96 Fix renderBreakingTexture not using the target's model data (#8849) + - 41.0.95 Multiple tweaks and fixes to the recent changes in the client refactor PR: Part 2 (#8854) + * Add getter for the component names in an unbaked geometry + * Fix render type hint not being copied in BlockGeometryBakingContext + * Ensure BlockRenderDispatches's renderSingleBlock uses the correct buffer + - 41.0.94 [1.19.x] Apply general renames, A SRG is provided for modders. (#8840) + See https://gist.github.com/SizableShrimp/882a671ff74256d150776da08c89ef72 + - 41.0.93 Fix mob block breaking AI not working correctly when chunk 0,0 is unloaded. Closes #8853 + - 41.0.92 Fix crash when breaking blocks with multipart models and remove caching. Closes #8850 + - 41.0.91 Fixed `CompositeModel.Baked.Builder.build()` passing arguments in the wrong order (#8846) + - 41.0.90 Make cutout mipmaps explicitly opt-in for item/entity rendering (#8845) + * Make cutout mipmaps explicitly opt-in for item/entity rendering + * Default render type domain to "minecraft" in model datagens + - 41.0.89 Fixed multipart block models not using the new model driven render type system. (#8844) + - 41.0.88 Update to the latest JarJar to fix a collision issue where multiple jars could provide an exact match. (#8847) + - 41.0.87 Add FML config to disable DFU optimizations client-side. (#8842) + * Add client-side command line argument to disable DFU optimizations. + * Switch to using FMLConfig value instead. + - 41.0.86 [1.19] Fixed broken BufferBuilder.putBulkData(ByteBuffer) added by Forge (#8819) + * Fixes BufferBuilder.putBulkData(ByteBuffer) + * use nextElementByte + * Fixed merge conflict + - 41.0.85 [1.19.x] Fix shulker boxes allowing input of items, that return false for Item#canFitInsideContainerItems, through hoppers. (#8823) + * Make ShulkerBoxBlockEntity#canPlaceItemThroughFace delegate to Item#canFitInsideContainerItems. + * Switch to using Or and add comment. + * Switch Or to And. + - 41.0.84 [1.19.x] Added RenderLevelStageEvent to replace RenderLevelLastEvent (#8820) + * Ported RenderLevelStageEvent from 1.18.2 + * Updated to fix merge conflicts + - 41.0.83 [1.19.x] Fix door datagenerator (#8821) + * Fix door datagenerator + Fix datagenerator for door blocks. Successor to #8687, addresses comments made there about statement complexity. + * Fix extra space around parameter + Fix extra space before comma around a parameter. + - 41.0.82 Create PieceBeardifierModifier to re-enable piecewise beardifier definitions (#8798) + - 41.0.81 Allow blocks to provide a dynamic MaterialColor for display on maps (#8812) + - 41.0.80 [1.19.x] BiomeTags Fixes/Improvements (#8711) + * dimension specific tag fix + * remove forge:is_beach cause vanilla has it already + * remove forge tags for new 1.19 vanilla tags (savanna, beach, overworld, end) + Co-authored-by: Flemmli97 + - 41.0.79 1.19 - Remove GlobalLootModifierSerializer and move to Codecs (#8721) + * convert GLM serializer class to codec + * cleanup + * GLM list needs to be sorted + * datagen + * simplify serialization + * fix test mods (oops) + * properly use suppliers for codec as they are registry obj + - 41.0.78 Implement item hooks for potions and enchantments (#8718) + * Implement item hooks for potions and enchantments + * code style fixes + - 41.0.77 Re-apply missing patch to ServerLevel.EntityCallbacks#onTrackingEnd() (#8828) + - 41.0.76 Double Bar Rendering fixed (#8806) (#8807) + * Double Bar Rendering fixed (#8806) + * Added requested changes by sciwhiz12 + - 41.0.75 Multiple tweaks and fixes to the recent changes in the client refactor PR (#8836) + * Add an easy way to get the NamedGuiOverlay from a vanilla overlay + * Fix static member ordering crash in UnitTextureAtlasSprite + * Allow boss bar rendering to be cancelled + * Make fluid container datagen use the new name + - 41.0.74 Add FogMode to ViewportEvent.RenderFog (#8825) + - 41.0.73 Provide additional context to the getFieldOfView event (#8830) + - 41.0.72 Pass renderType to IForgeBakedModel.useAmbientOcclusion (#8834) + - 41.0.71 Load custom ITransformationServices from the classpath in dev (#8818) + * Add a classpath transformer discoverer to load custom transformation services from the classpath + * Update ClasspathTransformerDiscoverer to 1.18 + * Update license year + * Update license header + * Fix the other license headers + * Update ClasspathTransformerDiscoverer to 1.19 + - 41.0.70 Handle modded packets on the network thread (#8703) + * Handle modded packets on the network thread + - On the server we simply need to remove the call to + ensureRunningOnSameThread. + - On the client side, we now handle the packet at the very start of the + call. We make sure we're running from a network thread to prevent + calling the handling code twice. + While this does mean we no longer call .release(), in practice this + doesn't cause any leaks as ClientboundCustomPayloadPacket releases + for us. + * Clarify behaviour a little in the documentation + * Javadoc formatting + * Add a helper method for handling packets on the main thread + Also rename the network thread one. Should make it clearer the expected + behaviour of the two, and make it clearer there's a potentially breaking + change. + * Add back consumer() methods + Also document EventNetworkChannel, to clarify the thread behaviour + there. + * Add since = "1.19" to deprecated annotations + - 41.0.69 Cache resource listing calls in resource packs (#8829) + * Make the resource lookups cached. + * Include configurability and handle patch cleanup. + * Document and comment the cache manager. + * Make thread selection configurable. + * Implement a configurable loading mechanic that falls back to default behaviour when the config is not bound yet. + * Use boolean supplier and fix wildcard import. + * Clean up the VPR since this is more elegant. + * Clean up the VPR since this is more elegant. + * Address review comments. + * Address more review comments. + * Fix formatting on `getSource` + * Address comments by ichtt + * Adapt to pups requests. + * Stupid idea. + * Attempt this again with a copy on write list. + * Fix a concurrency and loading issue. + * Fix #8813 + Checks if the paths are valid resource paths. + * Move the new methods on vanilla Patch. + - 41.0.68 Update SJH and JIJ + - 41.0.67 Fix #8833 (#8835) + - 41.0.66 Fix backwards fabulous check in SimpleBakedModel (#8832) + Yet another blunder we missed during the review of #8786. + - 41.0.65 Make texture atlas in StandaloneGeometryBakingContext configurable (#8831) + - 41.0.64 [1.19.X] Client code cleanup, updates, and other refactors (#8786) + * Revert "Allow safely registering RenderType predicates at any time (#8685)" + This reverts commit be7275443fd939db9c58bcad47079c3767789ac1. + * Renderable API refactors + - Rename "render values" to "context" + - Rename SimpleRenderable to CompositeRenderable to better reflect its use + - Remove IMultipartRenderValues since it doesn't have any real use + - Add extensive customization options to BakedModelRenderable + * ClientRegistry and MinecraftForgeClient refactors + - Add sprite loader manager and registration event + - Add spectator shader manager and registration event + - Add client tooltip factory manager and registration event + - Add recipe book manager and registration event + - Add key mapping registration event + - Remove ClientRegistry, as everything has been moved out of it + - Remove registration methods from MinecraftForgeClient, as they have dedicated events now + * Dimension special effects refactors + - Fold handlers into an extension class and remove public mutable fields + - Add dimension special effects manager and registration event + * HUD overlay refactors + - Rename to IGuiOverlay match vanilla (instead of Ingame) + - Add overlay manager and registration event + - Move vanilla overlays to a standalone enum + * Model loader refactors + - Rename IModelLoader to IGeometryLoader + - Add loader manager and registration event + - Fold all model events into one + - Move registration of additionally loaded models to an event + - Remove ForgeModelBakery and related classes as they served no purpose anymore + * Render properties refactors + - Rename all render properties to client extensions and relocate accordingly + - Move lookups to the respective interfaces + * Model data refactors + - Convert model data to a final class backed by an immutable map and document mutability requirements. This addresses several thread-safety issues in the current implementation which could result in race conditions + - Transfer ownership of the data manager to the client level. This addresses several issues that arise when multiple levels are used at once + * GUI and widget refactors + - Move all widgets to the correct package + - Rename GuiUtils and children to match vanilla naming + * New vertex pipeline API + - Move to vanilla's VertexConsumer + - Roll back recent PR making VertexConsumer format-aware. This is the opposite of what vanilla does, and should not be relevant with the updated lighting pipeline + * Lighting pipeline refactors + - Move to dedicated lighting package + - Separate flat and smooth lighters + - Convert from a vertex pipeline transformer to a pure vertex source (input is baked quads) + * Model geometry API refactors + - Rename IModelGeometry to IUnbakedGeometry + - Rename IModelConfiguration to IGeometryBakingContext + - Rename other elements to match vanilla naming + - Remove current changes to ModelState, as they do not belong there. Transforms should be specified through vanilla's system. ModelState is intended to transfer state from the blockstate JSON + - Remove multipart geometries and geometry parts. After some discussion, these should not be exposed. Instead, geometries should be baked with only the necessary parts enabled + * Make render types a first-class citizen in baked models + - Add named render types (block + entity + fabulous entity) + - Add named render type manager + registration event + - Make BakedModel aware of render types and transfer control over which ones are used to it instead of ItemBlockRenderTypes (fallback) + - (additional) Add concatenated list view. A wrapper for multiple lists that iterates through them in order without the cost of merging them. Useful for merging lists of baked quads + * General event refactors + - Several renames to either match vanilla or improve clarity + - Relocate client chat event dispatching out of common code + * Forge model type refactors + - Rename SeparatePerspectiveModel to SeparateTransformsModel + - Rename ItemModelMesherForge to ForgeItemModelShaper + - Rename DynamicBucketModel to DynamicFluidContainerModel + - Prefix all OBJ-related classes with "Obj" and decouple parsing from construction + - Extract ElementsModel from model loader registry + - Add EmptyModel (baked, unbaked and loader) + - Refactor CompositeModel to take over ItemMultiLayerBakedModel + - Remove FluidModel as it's not used and isn't compatible with the new fluid rendering in modern versions + - Move model loader registration to a proper event handler + - Update names of several JSON fields (backwards-compatible) + - Update datagens to match + * Miscellaneous changes and overlapping patches + - Dispatch all new registration events + - Convert ExtendedServerListData to a record + - Add/remove hooks from ForgeHooksClient as necessary + * Update test mods + * Fix VertexConsumerWrapper returning parent instead of itself + * Additional event cleanup pass + As discussed on Discord: + - Remove "@hidden" and "@see " javadoc annotations from all client events and replace them with @ApiStatus.Internal annotation + - Make all events that shouldn't be fired directly into abstract classes with protected constructors + - Another styling pass, just in case (caught some missed classes) + * Add proper deprecation javadocs and de-dupe some vertex consumer code + * Replace sets of chunk render types with a faster BitSet-backed collection + This largely addresses potential performance concerns that using a plain HashSet might involve by making lookups and iteration as linear as they can likely be (aside from using a plain byte/int/long for bit storage). Further performance concerns related to the implementation may be addressed separately, as all the implementation details are hidden from the end user + * Requested changes + - Remove MinecraftForgeClient and move members to Minecraft, IForgeMinecraft and StencilManager + - Allow non-default elements to be passed into VertexConsumer and add support to derived classes + - Move array instantiation out of quad processing in lighting pipeline + - Fix flipped fluid container model + - Set default UV1 to the correct values in the remapping pipeline + - Minor documentation changes + * Add/update EXC entries and fix AT comment + * Add test mod as per Orion's request + * Additional requested changes + * Allow custom model types to request the particle texture to be loaded + * Even more requested changes + * Improve generics in ConcatenatedListView and add missing fallbacks + * Fix fluid render types being bound to the fluid and not its holder + * Remove non-contractual nullability in ChunkRenderTypeSet and add isEmpty + Additionally, introduce chunk render type checks in ItemBlockRenderTypes + Co-authored-by: Dennis C + - 41.0.63 Implement full support for IPv6 (#8742) + - 41.0.62 Fix certain user-configured options being overwritten incorrectly due to validators. (#8780) + - 41.0.61 Allow safely registering RenderType predicates at any time (#8685) + - 41.0.60 Fix crash after loading error due to fluid texture gathering and config lookup (#8802) + - 41.0.59 Remove the configuration option for handling empty tags in ingredients. (#8799) + Now empty tags are considered broken in all states. + - 41.0.58 Fix MC-105317 Structure blocks do not rotate entities correctly when loading (#8792) + - 41.0.57 Fire ChunkWatchEvents after sending packets (#8747) + - 41.0.56 Add item handler capability to chest boats (#8787) + - 41.0.55 Add getter for correct BiomeSpecialEffectsBuilder to BiomeInfo$Builder (#8781) + - 41.0.54 Fix BlockToolModificationEvent missing cancelable annotation (#8778) + - 41.0.53 Fix ticking chunk tickets from forge's chunk manager not causing chunks to fully tick (#8775) + - 41.0.52 Fix default audio device config loading string comparison issue (#8767) + - 41.0.51 Fix missed vanilla method overrides in ForgeRegistry (#8766) + - 41.0.50 Add MinecraftServer reference to ServerTickEvent (#8765) + - 41.0.49 Fix TagsProviders for datapack registries not recognizing existing files (#8761) + - 41.0.48 Add callback after a BlockState was changed and the neighbors were updated (#8686) + - 41.0.47 Add biome tag entries for 1.19 biomes (#8684) + - 41.0.46 Make fishing rods use tool actions for relevant logic (#8681) + - 41.0.45 Update BootstrapLauncher to 1.1.1 and remove the forced + merge of text2speech since new BSL does it. + - 41.0.44 Merge text2speech libs together so the natives are part of the jar + - 41.0.43 Make Forge ConfigValues implement Supplier. (#8776) + - 41.0.42 Fix merge derp in AbstractModProvider and logic derp in ModDiscoverer + - 41.0.41 Add "send to mods in order" method to ModList and use it (#8759) + * Add "send to mods in order" method to ModList and use it in RegistryEvents and DataGen.. + * Also preserve order in runAll + * Do better comparator thanks @pupnewfster + * postEvent as well. + - 41.0.40 Update SJH to 2.0.2.. (#8774) + * Update SJH to 2.0.3.. + - 41.0.39 Sanity check the version specified in the mod file (#8749) + * Sanity check the version specified in the mod file to + make sure it's compatible with JPMS standards for + version strings. + Closes #8748 + Requires SPI 6 + - 41.0.38 Fix SP-Devtime world loading crash due to missing server configs (#8757) + - 41.0.37 Remove ForgeWorldPreset and related code (#8756) + Vanilla has a working replacement. + - 41.0.36 Change ConfigValue#get() to throw if called before config loaded (#8236) + This prevents silent issues where a mod gets the value of the setting + before configs are loaded, which means the default value is always + returned. + As there may be situations where the getting the config setting before + configs are loaded is needed, and it is not preferable to hardcode the + default value, the original behavior is made available through #getRaw. + Implements and closes #7716 + * Remove getRaw() method + This is effectively replaced with the expression `spec.isLoaded() ? + configValue.get() : configValue.getDefault()`. + * Remove forceSystemNanoTime config setting + As implemented, it never had any effect as any place where the config + value would be queried happens before the configs are loaded. + - 41.0.35 Fix EnumArgument to use enum names for suggestions (#8728) + Previously, the suggestions used the string representation of the enum + through Enum#toString, which can differ from the name of the enum as + required by Enum#valueOf, causing invalid suggestions (both in gui and + through the error message). + - 41.0.34 Jar-In-Jar (#8715) + - 41.0.33 [1.19] Fix data-gen output path of custom data-pack registries (#8724) + - 41.0.32 Fix player dive and surface animations in custom fluids (#8738) + - 41.0.31 [1.19.x] Affect ItemEntity Motion in Custom Fluids (#8737) + - 41.0.30 [1.19] Add support for items to add enchantments without setting them in NBT (#8719) + - 41.0.29 [1.19.x] Add stock biome modifier types for adding features and spawns (#8697) + - 41.0.28 [1.19.x] Fluid API Overhaul (#8695) + - 41.0.27 Replace StructureSpawnListGatherEvent with StructureModifiers (#8717) + - 41.0.26 Use stack sensitive translation key by default for FluidAttributes. (#8707) + - 41.0.25 Delete LootItemRandomChanceCondition which added looting bonus enchantment incorrectly. (#8733) + - 41.0.24 Update EventBus to 6.0, ModLauncher to 10.0.1 and BootstrapLauncher to 1.1 (#8725) + - 41.0.23 Replace support bot with support action (#8700) + - 41.0.22 Fix Reach Distance / Attack Range being clamped at 6.0 (#8699) + - 41.0.21 [1.19.x] Fix mods' worldgen data not being loaded when creating new singleplayer worlds (#8693) + - 41.0.20 [1.19.x] Fix experimental confirmation screen (#8727) + - 41.0.19 Move is_mountain to forge's tag instead of vanilla's (#8726) + - 41.0.18 [1.19.x] Add CommandBuildContext to Register Command Events (#8716) + - 41.0.17 Only rewrite datagen cache when needed (#8709) + - 41.0.16 Implement a simple feature system for Forge (#8670) + * Implement a simple feature system for Forge. Allows mods to demand certain features are available in the loading system. An example for java_version is provided, but not expected to be used widely. This is more targeted to properties of the display, such as GL version and glsl profile. + Requires https://github.com/MinecraftForge/ForgeSPI/pull/13 to be merged first in ForgeSPI, and the SPI to be updated appropriately in build.gradle files. + * rebase onto 1.19 and add in SPI update + - 41.0.15 displayTest option in mods.toml (#8656) + * displayTest option in mods.toml + * "MATCH_VERSION" (or none) is existing match version string behaviour + * "IGNORE_SERVER_VERSION" accepts anything and sends special SERVERONLY string + * "IGNORE_ALL_VERSION" accepts anything and sends an empty string + * "NONE" allows the mod to supply their own displaytest using the IExtensionPoint mechanism. + * Update display test with feedback and added the mods.toml discussion in mdk. + - 41.0.14 Update forgeSPI to v5 (#8696) + - 41.0.13 Make IVertexConsumers such as the lighting pipeline, be aware of which format they are dealing with. (#8692) + Also fix Lighting pipeline ignoring the overlay coords from the block renderer. + - 41.0.12 Fixed misaligned patch to invalidateCaps in Entity (#8705) + - 41.0.11 Fix readAdditionalLevelSaveData (#8704) + - 41.0.10 Fixes setPos to syncPacketPositionCodec (#8702) + - 41.0.9 Fix wrong param passed to PlayLevelSoundEvent.AtEntity (#8688) + - 41.0.8 Override initialize in SlotItemHandler, so it uses the itemhandler instead of container (#8679) + - 41.0.7 Update MDK for 1.19 changes (#8675) + - 41.0.6 Add helper to RecipeType, and fix eclipse compiler error in test class. + - 41.0.5 Update modlauncher to latest (#8691) + - 41.0.4 Fix getting entity data serializer id crashing due to improper port to new registry system (#8678) + - 41.0.3 Fire registry events in the order vanilla registers to registries (#8677) + Custom registries are still fired in alphabetical order, after all vanilla registries. + Move forge's data_serializers registry to forge namespace. + - 41.0.2 Add method with pre/post wrap to allow setting/clearing mod context. (#8682) + Fixes ActiveContainer in ModContext not being present in registry events. Closes #8680 + - 41.0.1 Fix the Curlie oopsie + - 41.0.0 Forge 1.19 + * Bump pack.mcmeta formats + * 1.19 biome modifiers + * Mark ClientPlayerNetworkEvent.LoggedOutEvent's getters as nullable + * Add docs and package-info to client extension interfaces package + * Move RenderBlockOverlayEvent hooks to ForgeHooksClient + * Add package-infos to client events package + * Rename SoundLoadEvent to SoundEngineLoadEvent + This reduces confusion from consumers which may think the + name SoundLoadEvent refers to an individual sound being loaded rather + than the sound engine. + * Document and change SoundLoadEvent to fire on mod bus + Previously, it fired on both the mod bus and the Forge bus, which is + confusing for consumers. + * Delete SoundSetupEvent + Looking at its original implementation shows that there isn't an + appropriate place in the new sound code to reinsert the event, and the + place of 'sound engine/manager initialization event' is taken already by SoundLoadEvent. + * Perform some cleanup on client events + - Removed nullable annotations from ClientPlayerNetworkEvent + - Renamed #getPartialTicks methods to #getPartialTick, to be consistent + with vanilla's naming of the partial tick + - Cleanup documentation to remove line breaks, use the + spelling 'cancelled' over + 'canceled', and improve docs on existing and + new methods. + * Remove EntityEvent.CanUpdate + Closes MinecraftForge/MinecraftForge#6394 + * Switch to Jetbrains nullability annotations + * New PlayLevelSoundEvent; replaces old PlaySoundAtEntityEvent + * Remove ForgeWorldPresetScreens + * Remove IForgeRegistryEntry + * Remove use of List in FML's CompletableFutures + * Add docs to mod loading stages, stages, and phases + * Gradle 7.4.2 + * Use SLF4J in FMLLoader and other subprojects + * Switch dynamic versions in subprojects to pinned ones + * Switch ForgeRoot and MDK to FG plugin markers + * Configure Forge javadoc task + The task now uses a custom stylesheet with MCForge elements, and + configured to combine the generation from the four FML subprojects + (fmlloader, fmlcore, javafmllanguage, mclanguage) and the Forge project + into the javadoc output. + * Update docs/md files, for 1.19 update and the move away from IRC to Discord. + * Make "Potentially dangerous alternative prefix" a debug warning, not info. + Co-authored-by: Curle + Co-authored-by: sciwhiz12 + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..3ad5a55 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,59 @@ +# Sets default memory used for gradle commands. Can be overridden by user or command line properties. +# This is required to provide enough memory for the Minecraft decompilation process. +org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=false + + +## Environment Properties + +# The Minecraft version must agree with the Forge version to get a valid artifact +minecraft_version=1.20.1 +# The Minecraft version range can use any release version of Minecraft as bounds. +# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly +# as they do not follow standard versioning conventions. +minecraft_version_range=[1.20.1,1.21) +# The Forge version must agree with the Minecraft version to get a valid artifact +forge_version=47.4.0 +# The Forge version range can use any version of Forge as bounds or match the loader version range +forge_version_range=[47,) +# The loader version range can only use the major version of Forge/FML as bounds +loader_version_range=[47,) +# The mapping channel to use for mappings. +# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"]. +# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin. +# +# | Channel | Version | | +# |-----------|----------------------|--------------------------------------------------------------------------------| +# | official | MCVersion | Official field/method names from Mojang mapping files | +# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official | +# +# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings. +# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md +# +# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge. +# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started +mapping_channel=official +# The mapping version to query from the mapping channel. +# This must match the format required by the mapping channel. +mapping_version=1.20.1 + + +## Mod Properties + +# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63} +# Must match the String constant located in the main mod class annotated with @Mod. +mod_id=adaptivemobs +# The human-readable display name for the mod. +mod_name=Adaptive Mobs +# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. +mod_license=MIT +# The mod version. See https://semver.org/ +mod_version=1.0.0 +# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository. +# This should match the base package used for the mod sources. +# See https://maven.apache.org/guides/mini/guide-naming-conventions.html +mod_group_id=net.fretux.adaptivemobs +# The authors of the mod. This is a simple text string that is used for display purposes in the mod list. +mod_authors=Fretux +# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list. +mod_description=Hostile vanilla mobs become progressively stronger and smarter as the world progresses. \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..c1962a7 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2617362 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..aeb74cb --- /dev/null +++ b/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..93f1b80 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,13 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { + name = 'MinecraftForge' + url = 'https://maven.minecraftforge.net/' + } + } +} + +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0' +} \ No newline at end of file diff --git a/src/main/java/net/fretux/adaptivemobs/AdaptiveMobs.java b/src/main/java/net/fretux/adaptivemobs/AdaptiveMobs.java new file mode 100644 index 0000000..1edc49f --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/AdaptiveMobs.java @@ -0,0 +1,22 @@ +package net.fretux.adaptivemobs; + +import com.mojang.logging.LogUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.fretux.adaptivemobs.event.AdaptiveMobsEvents; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.ModLoadingContext; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.config.ModConfig; +import org.slf4j.Logger; + +@Mod(AdaptiveMobs.MODID) +public class AdaptiveMobs { + + public static final String MODID = "adaptivemobs"; + public static final Logger LOGGER = LogUtils.getLogger(); + + public AdaptiveMobs() { + ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, AMConfig.SPEC); + MinecraftForge.EVENT_BUS.register(new AdaptiveMobsEvents()); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveAIGoalUtils.java b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveAIGoalUtils.java new file mode 100644 index 0000000..c79a7b7 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveAIGoalUtils.java @@ -0,0 +1,117 @@ +package net.fretux.adaptivemobs.ai; + +import net.fretux.adaptivemobs.AdaptiveMobs; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.monster.AbstractSkeleton; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +import java.util.function.IntSupplier; + +public final class AdaptiveAIGoalUtils { + + private AdaptiveAIGoalUtils() { + } + + public static boolean advancedEnabled(int tier) { + return AMConfig.AI_ENABLED.get() && AMConfig.ENABLE_ADVANCED_AI.get() && tier > 0; + } + + public static boolean isBlockingShield(LivingEntity entity) { + if (entity == null || !entity.isUsingItem()) { + return false; + } + ItemStack stack = entity.getUseItem(); + return !stack.isEmpty() && stack.is(Items.SHIELD); + } + + public static boolean isUsingRangedWeapon(LivingEntity entity) { + if (entity == null || !entity.isUsingItem()) { + return false; + } + ItemStack stack = entity.getUseItem(); + return stack.is(Items.BOW) || stack.is(Items.CROSSBOW) || stack.is(Items.TRIDENT); + } + + public static boolean isEating(LivingEntity entity) { + if (entity == null || !entity.isUsingItem()) { + return false; + } + ItemStack stack = entity.getUseItem(); + return stack.isEdible(); + } + + public static boolean isLikelyMeleeWeapon(ItemStack stack) { + return stack.is(Items.WOODEN_SWORD) || stack.is(Items.STONE_SWORD) || stack.is(Items.IRON_SWORD) + || stack.is(Items.GOLDEN_SWORD) || stack.is(Items.DIAMOND_SWORD) || stack.is(Items.NETHERITE_SWORD) + || stack.is(Items.WOODEN_AXE) || stack.is(Items.STONE_AXE) || stack.is(Items.IRON_AXE) + || stack.is(Items.GOLDEN_AXE) || stack.is(Items.DIAMOND_AXE) || stack.is(Items.NETHERITE_AXE); + } + + public static int armorPieces(LivingEntity entity) { + int pieces = 0; + for (ItemStack stack : entity.getArmorSlots()) { + if (!stack.isEmpty()) { + pieces++; + } + } + return pieces; + } + + public static double playerPriorityScore(Mob mob, Player player) { + double score = 0.0D; + score += (1.0D - healthFraction(player)) * 5.0D; + if (isEating(player)) { + score += 2.0D; + } + if (isUsingRangedWeapon(player)) { + score += 1.5D; + } + score += Math.max(0, 4 - armorPieces(player)) * 0.7D; + if (mob instanceof AbstractSkeleton && !isBlockingShield(player)) { + score += 1.2D; + } + if (!(mob instanceof AbstractSkeleton) && armorPieces(player) <= 2) { + score += 0.8D; + } + if (player.getLastHurtMob() instanceof Mob && player.getLastHurtMob() != mob) { + score += 1.0D; + } + score -= Math.sqrt(mob.distanceToSqr(player)) * 0.08D; + return score; + } + + public static double healthFraction(LivingEntity entity) { + if (entity == null || entity.getMaxHealth() <= 0.0F) { + return 1.0D; + } + return entity.getHealth() / entity.getMaxHealth(); + } + + public static double followRange(Mob mob, double fallback) { + if (mob.getAttribute(Attributes.FOLLOW_RANGE) == null) { + return fallback; + } + return mob.getAttributeValue(Attributes.FOLLOW_RANGE); + } + + public static int nextCooldown(Mob mob) { + return AMConfig.aiScanCooldown(mob.getRandom()); + } + + public static boolean hasServerLevel(Mob mob) { + return mob.level() instanceof ServerLevel; + } + + public static void debug(Mob mob, IntSupplier tier, String message) { + if (!AMConfig.DEBUG_AI_LOGGING.get()) { + return; + } + AdaptiveMobs.LOGGER.info("[AdaptiveMobs AI] {} tier {}: {}", mob.getType(), tier.getAsInt(), message); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveGoalInjector.java b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveGoalInjector.java new file mode 100644 index 0000000..fb26500 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveGoalInjector.java @@ -0,0 +1,347 @@ +package net.fretux.adaptivemobs.ai; + +import net.fretux.adaptivemobs.ai.goals.AdaptiveCreeperPressureGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveAirbornePositioningGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveAntiCheeseGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveBiomeTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveCreeperTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveEndermanTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveEndermiteTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveEvokerTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveEscapeDenialGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveFlankGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveGuardianTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveLowHealthRetreatGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveMeleePositioningGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveMoraleGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveRavagerTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveRangedAttackGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveRangedCoverGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveRetreatAndReengageGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveSkeletonShieldGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveSharedTargetGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveShulkerTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveSlimeTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveSoundInvestigationGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveSpiderDisengageGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveSpiderTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveSupportGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveTargetPriorityGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveThreatMemoryGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveWardenTacticsGoal; +import net.fretux.adaptivemobs.ai.goals.AdaptiveWitchTacticsGoal; +import net.fretux.adaptivemobs.config.AMConfig; +import net.fretux.adaptivemobs.difficulty.AdaptiveDifficultyManager; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.monster.AbstractSkeleton; +import net.minecraft.world.entity.monster.Blaze; +import net.minecraft.world.entity.monster.CaveSpider; +import net.minecraft.world.entity.monster.Creeper; +import net.minecraft.world.entity.monster.Drowned; +import net.minecraft.world.entity.monster.ElderGuardian; +import net.minecraft.world.entity.monster.Endermite; +import net.minecraft.world.entity.monster.EnderMan; +import net.minecraft.world.entity.monster.Evoker; +import net.minecraft.world.entity.monster.Ghast; +import net.minecraft.world.entity.monster.Guardian; +import net.minecraft.world.entity.monster.Husk; +import net.minecraft.world.entity.monster.MagmaCube; +import net.minecraft.world.entity.monster.Phantom; +import net.minecraft.world.entity.monster.Pillager; +import net.minecraft.world.entity.monster.Ravager; +import net.minecraft.world.entity.monster.Shulker; +import net.minecraft.world.entity.monster.Silverfish; +import net.minecraft.world.entity.monster.Slime; +import net.minecraft.world.entity.monster.Spider; +import net.minecraft.world.entity.monster.Stray; +import net.minecraft.world.entity.monster.Vex; +import net.minecraft.world.entity.monster.Vindicator; +import net.minecraft.world.entity.monster.WitherSkeleton; +import net.minecraft.world.entity.monster.Witch; +import net.minecraft.world.entity.monster.Zombie; +import net.minecraft.world.entity.monster.ZombieVillager; +import net.minecraft.world.entity.monster.ZombifiedPiglin; +import net.minecraft.world.entity.monster.hoglin.Hoglin; +import net.minecraft.world.entity.monster.piglin.Piglin; +import net.minecraft.world.entity.monster.piglin.PiglinBrute; +import net.minecraft.world.entity.monster.warden.Warden; +import net.minecraft.world.entity.monster.Zoglin; + +import java.util.Collections; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.function.IntSupplier; + +public final class AdaptiveGoalInjector { + + private static final Set INJECTED = Collections.newSetFromMap(new WeakHashMap<>()); + + private AdaptiveGoalInjector() { + } + + public static void inject(Mob mob, ServerLevel level, int initialTier) { + if (!AMConfig.AI_ENABLED.get() || initialTier <= 0 || isBoss(mob)) { + return; + } + if (!INJECTED.add(mob)) { + return; + } + PathfinderMob pathfinder = mob instanceof PathfinderMob pf ? pf : null; + IntSupplier tier = () -> AdaptiveDifficultyManager.getMobTier(level, mob.getType()); + + if (tier.getAsInt() >= 4) { + mob.targetSelector.addGoal(2, new AdaptiveSharedTargetGoal(mob, tier, 4, 12.0D)); + } + + if (pathfinder != null && mob instanceof AbstractSkeleton && AMConfig.AI_SKELETON.get()) { + mob.goalSelector.addGoal(3, new AdaptiveSkeletonShieldGoal(pathfinder, tier)); + mob.goalSelector.addGoal(4, new AdaptiveFlankGoal(pathfinder, tier, 2, 8.0D, 1.0D, true)); + } else if (pathfinder != null && mob instanceof Zombie && AMConfig.AI_ZOMBIE.get()) { + mob.goalSelector.addGoal(3, new AdaptiveFlankGoal(pathfinder, tier, 2, 2.5D, 1.05D, true)); + } else if (pathfinder != null && mob instanceof Creeper creeper && AMConfig.AI_CREEPER.get()) { + mob.goalSelector.addGoal(2, new AdaptiveCreeperPressureGoal(creeper, tier)); + mob.goalSelector.addGoal(4, new AdaptiveFlankGoal(pathfinder, tier, 2, 3.0D, 1.0D, false)); + } else if (pathfinder != null && mob instanceof Spider && AMConfig.AI_SPIDER.get()) { + mob.goalSelector.addGoal(4, new AdaptiveFlankGoal(pathfinder, tier, 2, 2.0D, 1.15D, false)); + } else if (pathfinder != null && ((mob instanceof Witch && AMConfig.AI_WITCH.get()) + || (mob instanceof Pillager && AMConfig.AI_PILLAGER.get()))) { + mob.goalSelector.addGoal(4, new AdaptiveFlankGoal(pathfinder, tier, 2, 7.0D, 1.0D, false)); + } + + if (AMConfig.ENABLE_ADVANCED_AI.get()) { + injectAdvanced(mob, pathfinder, tier); + AdaptiveAIGoalUtils.debug(mob, tier, "injected adaptive goals"); + } + } + + private static void injectAdvanced(Mob mob, PathfinderMob pathfinder, IntSupplier tier) { + if (AMConfig.ENABLE_TARGET_PRIORITY_AI.get()) { + mob.targetSelector.addGoal(3, new AdaptiveTargetPriorityGoal(mob, tier)); + } + if (pathfinder != null && AMConfig.ENABLE_MORALE_AI.get() && !(mob instanceof Warden)) { + mob.goalSelector.addGoal(8, new AdaptiveMoraleGoal(pathfinder, tier)); + } + if (pathfinder != null && AMConfig.ENABLE_THREAT_MEMORY_AI.get()) { + mob.goalSelector.addGoal(2, new AdaptiveThreatMemoryGoal(pathfinder, tier)); + } + if (pathfinder != null && AMConfig.ENABLE_SOUND_INVESTIGATION_AI.get()) { + mob.goalSelector.addGoal(9, new AdaptiveSoundInvestigationGoal(pathfinder, tier)); + } + if (pathfinder != null && AMConfig.ENABLE_SUPPORT_AI.get() && !(mob instanceof Warden)) { + mob.goalSelector.addGoal(8, new AdaptiveSupportGoal(pathfinder, tier)); + } + if (pathfinder != null && AMConfig.ENABLE_ESCAPE_DENIAL_AI.get() + && (mob instanceof Zombie || mob instanceof Spider)) { + mob.goalSelector.addGoal(6, new AdaptiveEscapeDenialGoal(pathfinder, tier)); + } + if (pathfinder != null && AMConfig.ENABLE_BIOME_TACTICS_AI.get()) { + mob.goalSelector.addGoal(8, new AdaptiveBiomeTacticsGoal(pathfinder, tier)); + } + if (pathfinder != null && AMConfig.ENABLE_ANTI_CHEESE_AI.get()) { + mob.goalSelector.addGoal(7, new AdaptiveAntiCheeseGoal(pathfinder, tier)); + } + if (pathfinder != null && isRangedMob(mob) && rangedEnabled(mob)) { + mob.goalSelector.addGoal(3, new AdaptiveRangedAttackGoal(pathfinder, tier, rangedOptimalRange(mob), 1.0D)); + if (AMConfig.ENABLE_RANGED_COVER_AI.get() + && (mob instanceof AbstractSkeleton || mob instanceof Pillager || mob instanceof Witch || mob instanceof Evoker)) { + mob.goalSelector.addGoal(6, new AdaptiveRangedCoverGoal(pathfinder, tier)); + } + } + if (pathfinder != null && isMeleeMob(mob) && meleeEnabled(mob)) { + mob.goalSelector.addGoal(5, new AdaptiveMeleePositioningGoal(pathfinder, tier, meleeSpeed(mob), conservativeMelee(mob))); + } + if (mob instanceof Creeper creeper && AMConfig.ENABLE_CREEPER_AI.get() && AMConfig.AI_CREEPER.get()) { + mob.goalSelector.addGoal(3, new AdaptiveCreeperTacticsGoal(creeper, tier)); + } + if (pathfinder != null && mob instanceof Spider && AMConfig.ENABLE_SPIDER_AI.get() && AMConfig.AI_SPIDER.get()) { + mob.goalSelector.addGoal(3, new AdaptiveSpiderTacticsGoal(pathfinder, tier, mob instanceof CaveSpider)); + mob.goalSelector.addGoal(6, new AdaptiveSpiderDisengageGoal(pathfinder, tier, mob instanceof CaveSpider ? 4 : 5, 0.25D, 1.2D)); + mob.goalSelector.addGoal(7, new AdaptiveLowHealthRetreatGoal(pathfinder, tier, 4, 0.28D, 1.15D)); + } + if (mob instanceof Witch witch && AMConfig.ENABLE_WITCH_AI.get() && AMConfig.AI_WITCH.get()) { + mob.goalSelector.addGoal(3, new AdaptiveWitchTacticsGoal(witch, tier)); + mob.goalSelector.addGoal(7, new AdaptiveLowHealthRetreatGoal(witch, tier, 3, 0.35D, 1.0D)); + } + if (mob instanceof EnderMan enderman && AMConfig.ENABLE_ENDERMAN_AI.get() && AMConfig.AI_ENDERMAN.get()) { + mob.goalSelector.addGoal(2, new AdaptiveEndermanTacticsGoal(enderman, tier)); + } + if (pathfinder != null && mob instanceof Endermite && AMConfig.ENABLE_ENDERMITE_AI.get() && AMConfig.AI_SMALL_SWARM.get()) { + mob.goalSelector.addGoal(4, new AdaptiveEndermiteTacticsGoal(pathfinder, tier)); + } + if (mob instanceof Evoker evoker && AMConfig.ENABLE_RAID_MOB_AI.get() + && AMConfig.ENABLE_EVOKER_AI.get() && AMConfig.AI_EVOKER.get()) { + mob.goalSelector.addGoal(3, new AdaptiveEvokerTacticsGoal(evoker, tier)); + } + if (mob instanceof Guardian guardian && AMConfig.ENABLE_AQUATIC_HOSTILE_AI.get() + && AMConfig.ENABLE_GUARDIAN_ADVANCED_AI.get() && AMConfig.AI_GUARDIAN.get()) { + mob.goalSelector.addGoal(4, new AdaptiveGuardianTacticsGoal(guardian, tier)); + } + if (mob instanceof Shulker shulker && AMConfig.ENABLE_END_MOB_AI.get() + && AMConfig.ENABLE_SHULKER_ADVANCED_AI.get() && AMConfig.AI_SHULKER.get()) { + mob.goalSelector.addGoal(4, new AdaptiveShulkerTacticsGoal(shulker, tier)); + } + if (mob instanceof Slime slime && AMConfig.AI_SLIME.get() + && ((mob instanceof MagmaCube && AMConfig.ENABLE_MAGMA_CUBE_ADVANCED_AI.get()) + || (!(mob instanceof MagmaCube) && AMConfig.ENABLE_SLIME_ADVANCED_AI.get()))) { + mob.goalSelector.addGoal(4, new AdaptiveSlimeTacticsGoal(slime, tier)); + } + if (mob instanceof Ravager ravager && AMConfig.ENABLE_RAID_MOB_AI.get() + && AMConfig.ENABLE_RAVAGER_ADVANCED_AI.get() && AMConfig.AI_RAVAGER.get()) { + mob.goalSelector.addGoal(4, new AdaptiveRavagerTacticsGoal(ravager, tier)); + } + if (isAirborneMob(mob) && airborneEnabled(mob)) { + mob.goalSelector.addGoal(4, new AdaptiveAirbornePositioningGoal(mob, tier, airborneRange(mob), airborneVerticalOffset(mob))); + } + if (pathfinder != null && mob instanceof Vex && AMConfig.ENABLE_RAID_MOB_AI.get() && AMConfig.AI_VEX.get()) { + mob.goalSelector.addGoal(4, new AdaptiveRetreatAndReengageGoal(pathfinder, tier, 5, 0.10D, 1.2D)); + mob.goalSelector.addGoal(7, new AdaptiveLowHealthRetreatGoal(pathfinder, tier, 4, 0.30D, 1.2D)); + } + if (pathfinder != null && mob instanceof AbstractSkeleton && AMConfig.AI_SKELETON.get()) { + mob.goalSelector.addGoal(7, new AdaptiveLowHealthRetreatGoal(pathfinder, tier, 4, 0.25D, 1.0D)); + } + if (pathfinder != null && mob instanceof Pillager && AMConfig.AI_PILLAGER.get()) { + mob.goalSelector.addGoal(7, new AdaptiveLowHealthRetreatGoal(pathfinder, tier, 4, 0.28D, 1.0D)); + } + if (pathfinder != null && mob instanceof Warden && AMConfig.ENABLE_WARDEN_AI.get() && AMConfig.AI_WARDEN.get()) { + mob.goalSelector.addGoal(7, new AdaptiveMeleePositioningGoal(pathfinder, tier, 0.9D, true)); + if (AMConfig.ENABLE_WARDEN_ADVANCED_AI.get()) { + mob.goalSelector.addGoal(8, new AdaptiveWardenTacticsGoal((Warden) mob, tier)); + } + } + } + + private static boolean isBoss(Mob mob) { + return !AMConfig.ENABLE_BOSS_AI.get() + && (mob.getType() == EntityType.ENDER_DRAGON || mob.getType() == EntityType.WITHER); + } + + private static boolean isRangedMob(Mob mob) { + return mob instanceof AbstractSkeleton || mob instanceof Pillager || mob instanceof Piglin + || mob instanceof Witch || mob instanceof Ghast || mob instanceof Blaze + || mob instanceof Guardian || mob instanceof Shulker; + } + + private static boolean rangedEnabled(Mob mob) { + if (!AMConfig.ENABLE_RANGED_AI.get()) { + return false; + } + if (mob instanceof Pillager) { + return AMConfig.ENABLE_PILLAGER_AI.get() && AMConfig.AI_PILLAGER.get(); + } + if (mob instanceof AbstractSkeleton) { + return AMConfig.AI_SKELETON.get(); + } + if (mob instanceof Witch) { + return AMConfig.ENABLE_WITCH_AI.get() && AMConfig.AI_WITCH.get(); + } + if (mob instanceof Guardian) { + return AMConfig.ENABLE_AQUATIC_HOSTILE_AI.get() && AMConfig.AI_GUARDIAN.get(); + } + if (mob instanceof Shulker) { + return AMConfig.ENABLE_END_MOB_AI.get() && AMConfig.AI_SHULKER.get(); + } + return !(mob instanceof Piglin) || (AMConfig.ENABLE_NETHER_MOB_AI.get() && AMConfig.AI_PIGLIN_FAMILY.get()); + } + + private static double rangedOptimalRange(Mob mob) { + if (mob instanceof Pillager || mob instanceof Piglin) { + return 10.0D; + } + if (mob instanceof Guardian || mob instanceof Shulker) { + return 12.0D; + } + if (mob instanceof Ghast) { + return 24.0D; + } + return 8.0D; + } + + private static boolean isMeleeMob(Mob mob) { + return mob instanceof Zombie || mob instanceof Husk || mob instanceof Drowned + || mob instanceof ZombieVillager || mob instanceof ZombifiedPiglin + || mob instanceof Piglin || mob instanceof PiglinBrute || mob instanceof Vindicator + || mob instanceof WitherSkeleton || mob instanceof Hoglin || mob instanceof Zoglin + || mob instanceof Silverfish || mob instanceof Endermite || mob instanceof Slime || mob instanceof MagmaCube + || mob instanceof Ravager || mob instanceof Warden; + } + + private static boolean meleeEnabled(Mob mob) { + if (!AMConfig.ENABLE_MELEE_AI.get()) { + return false; + } + if (mob instanceof Piglin || mob instanceof PiglinBrute || mob instanceof ZombifiedPiglin + || mob instanceof Hoglin || mob instanceof Zoglin) { + return AMConfig.ENABLE_NETHER_MOB_AI.get() && AMConfig.AI_PIGLIN_FAMILY.get(); + } + if (mob instanceof Vindicator || mob instanceof Ravager) { + return AMConfig.ENABLE_RAID_MOB_AI.get() && AMConfig.AI_RAVAGER.get(); + } + if (mob instanceof Silverfish) { + return AMConfig.AI_SMALL_SWARM.get(); + } + if (mob instanceof Endermite) { + return AMConfig.ENABLE_ENDERMITE_AI.get() && AMConfig.AI_SMALL_SWARM.get(); + } + if (mob instanceof Warden) { + return AMConfig.ENABLE_WARDEN_AI.get() && AMConfig.AI_WARDEN.get(); + } + return AMConfig.AI_ZOMBIE.get() || mob instanceof WitherSkeleton || mob instanceof Slime || mob instanceof MagmaCube; + } + + private static double meleeSpeed(Mob mob) { + if (mob instanceof Silverfish) { + return 1.15D; + } + if (mob instanceof Ravager || mob instanceof Warden) { + return 0.9D; + } + return 1.05D; + } + + private static boolean conservativeMelee(Mob mob) { + return mob instanceof PiglinBrute || mob instanceof Ravager || mob instanceof Warden || mob instanceof ElderGuardian; + } + + private static boolean isAirborneMob(Mob mob) { + return mob instanceof Ghast || mob instanceof Blaze || mob instanceof Phantom || mob instanceof Vex; + } + + private static boolean airborneEnabled(Mob mob) { + if (mob instanceof Ghast) { + return AMConfig.ENABLE_NETHER_MOB_AI.get() && AMConfig.AI_GHAST.get(); + } + if (mob instanceof Blaze) { + return AMConfig.ENABLE_NETHER_MOB_AI.get() && AMConfig.AI_BLAZE.get(); + } + if (mob instanceof Phantom) { + return AMConfig.AI_PHANTOM.get(); + } + if (mob instanceof Vex) { + return AMConfig.ENABLE_RAID_MOB_AI.get() && AMConfig.AI_VEX.get(); + } + return true; + } + + private static double airborneRange(Mob mob) { + if (mob instanceof Ghast) { + return 22.0D; + } + if (mob instanceof Phantom) { + return 8.0D; + } + return 7.0D; + } + + private static double airborneVerticalOffset(Mob mob) { + if (mob instanceof Ghast) { + return 6.0D; + } + if (mob instanceof Phantom) { + return 5.0D; + } + return 2.0D; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveMemory.java b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveMemory.java new file mode 100644 index 0000000..1832f5c --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveMemory.java @@ -0,0 +1,105 @@ +package net.fretux.adaptivemobs.ai; + +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.phys.Vec3; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.WeakHashMap; + +public final class AdaptiveMemory { + + private static final int MAX_SOUND_ENTRIES_PER_LEVEL = 256; + + private static final Map THREATS = new WeakHashMap<>(); + private static final Map> SOUNDS = new WeakHashMap<>(); + + private AdaptiveMemory() { + } + + public static void rememberThreat(Mob mob, ServerPlayer player, int ticks) { + if (!(mob.level() instanceof ServerLevel level)) { + return; + } + THREATS.put(mob, new ThreatEntry(player.getUUID(), level.getGameTime() + ticks)); + } + + public static Optional rememberedThreat(Mob mob) { + if (!(mob.level() instanceof ServerLevel level)) { + return Optional.empty(); + } + ThreatEntry entry = THREATS.get(mob); + if (entry == null || entry.expiresAt < level.getGameTime()) { + THREATS.remove(mob); + return Optional.empty(); + } + ServerPlayer player = level.getServer().getPlayerList().getPlayer(entry.playerId); + return player != null && player.isAlive() ? Optional.of(player) : Optional.empty(); + } + + public static void rememberSound(ServerLevel level, BlockPos pos, SoundKind kind, int ticks) { + rememberSound(level, Vec3.atCenterOf(pos), kind, ticks); + } + + public static void rememberSound(ServerLevel level, Vec3 pos, SoundKind kind, int ticks) { + List entries = SOUNDS.computeIfAbsent(level, ignored -> new ArrayList<>()); + pruneExpired(entries, level.getGameTime()); + if (entries.size() >= MAX_SOUND_ENTRIES_PER_LEVEL) { + entries.remove(0); + } + entries.add(new SoundEntry(pos, kind, level.getGameTime() + ticks)); + } + + public static Optional nearestSound(ServerLevel level, Mob mob, double radius) { + List entries = SOUNDS.get(level); + if (entries == null || entries.isEmpty()) { + return Optional.empty(); + } + long now = level.getGameTime(); + double maxSqr = radius * radius; + SoundEntry best = null; + double bestSqr = Double.MAX_VALUE; + Iterator iterator = entries.iterator(); + while (iterator.hasNext()) { + SoundEntry entry = iterator.next(); + if (entry.expiresAt < now) { + iterator.remove(); + continue; + } + double dist = mob.distanceToSqr(entry.pos); + if (dist < maxSqr && dist < bestSqr) { + best = entry; + bestSqr = dist; + } + } + return Optional.ofNullable(best); + } + + public static void clear(ServerLevel level) { + SOUNDS.remove(level); + } + + private static void pruneExpired(List entries, long now) { + entries.removeIf(entry -> entry.expiresAt < now); + } + + public enum SoundKind { + BLOCK_BREAK, + EATING, + BOW_SHOT, + EXPLOSION + } + + private record ThreatEntry(UUID playerId, long expiresAt) { + } + + public record SoundEntry(Vec3 pos, SoundKind kind, long expiresAt) { + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveMobHooks.java b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveMobHooks.java new file mode 100644 index 0000000..7618731 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveMobHooks.java @@ -0,0 +1,71 @@ +package net.fretux.adaptivemobs.ai; + +import net.fretux.adaptivemobs.config.AMConfig; +import net.fretux.adaptivemobs.difficulty.AdaptiveDifficultyManager; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.monster.AbstractSkeleton; +import net.minecraft.world.entity.monster.Pillager; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.phys.Vec3; +import net.minecraftforge.event.entity.EntityJoinLevelEvent; + +public final class AdaptiveMobHooks { + + private AdaptiveMobHooks() { + } + + public static void onProjectileJoin(EntityJoinLevelEvent event) { + if (!AMConfig.enabled || !AMConfig.AI_ENABLED.get() || !AMConfig.ENABLE_ADVANCED_AI.get() + || !AMConfig.ENABLE_RANGED_AI.get() || !(event.getLevel() instanceof ServerLevel level)) { + return; + } + Entity entity = event.getEntity(); + if (!(entity instanceof Projectile projectile) || !(projectile.getOwner() instanceof Mob mob)) { + return; + } + LivingEntity target = mob.getTarget(); + if (target == null || !target.isAlive()) { + return; + } + int tier = AdaptiveDifficultyManager.getMobTier(level, mob.getType()); + if (tier <= 1) { + return; + } + + if (tier >= 3 && AdaptiveAIGoalUtils.isBlockingShield(target) && mob.getRandom().nextFloat() < 0.45F) { + projectile.setDeltaMovement(projectile.getDeltaMovement().scale(0.94D)); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "shield-blocked shot softened"); + return; + } + if (tier >= 4 && AdaptiveTargetingUtils.hasAllyBetween(mob, target, 0.8D)) { + projectile.setDeltaMovement(projectile.getDeltaMovement().scale(0.90D)); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "ally in ranged line"); + return; + } + + double accuracy = AMConfig.tierValue(AMConfig.AI_ACCURACY_BONUS.get(), tier); + if (accuracy <= 0.0D) { + return; + } + double lead = tier >= 5 ? AMConfig.tierValue(AMConfig.AI_INTERCEPTION_STRENGTH.get(), tier) : 0.0D; + Vec3 aim = AdaptivePositioningUtils.predictedPosition(target, lead) + .add(0.0D, target.getBbHeight() * aimHeight(mob, target, tier), 0.0D); + Vec3 wanted = aim.subtract(projectile.position()).normalize().scale(projectile.getDeltaMovement().length()); + Vec3 blended = projectile.getDeltaMovement().scale(1.0D - accuracy).add(wanted.scale(accuracy)); + projectile.setDeltaMovement(blended); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "projectile aim adjusted"); + } + + private static double aimHeight(Mob mob, LivingEntity target, int tier) { + if ((mob instanceof AbstractSkeleton || mob instanceof Pillager) && tier >= 4) { + double chance = AMConfig.tierValue(AMConfig.AI_HEADSHOT_CHANCE.get(), tier); + if (mob.getRandom().nextDouble() < chance) { + return 0.82D; + } + } + return 0.55D; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/AdaptivePositioningUtils.java b/src/main/java/net/fretux/adaptivemobs/ai/AdaptivePositioningUtils.java new file mode 100644 index 0000000..36bb7d7 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/AdaptivePositioningUtils.java @@ -0,0 +1,97 @@ +package net.fretux.adaptivemobs.ai; + +import net.minecraft.core.BlockPos; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +public final class AdaptivePositioningUtils { + + private AdaptivePositioningUtils() { + } + + public static Vec3 predictedPosition(LivingEntity target, double strength) { + if (target == null || strength <= 0.0D) { + return target == null ? Vec3.ZERO : target.position(); + } + return target.position().add(target.getDeltaMovement().scale(8.0D * strength)); + } + + public static Vec3 sidePosition(Mob mob, LivingEntity target, double radius, double side, double leadStrength) { + Vec3 aim = predictedPosition(target, leadStrength); + Vec3 away = mob.position().subtract(aim); + double len = Math.sqrt(away.x * away.x + away.z * away.z); + if (len < 1.0E-3D) { + away = new Vec3(1.0D, 0.0D, 0.0D); + len = 1.0D; + } + double angle = Math.toRadians(55.0D * side); + double nx = away.x * Math.cos(angle) - away.z * Math.sin(angle); + double nz = away.x * Math.sin(angle) + away.z * Math.cos(angle); + double scale = radius / len; + return new Vec3(aim.x + nx * scale, aim.y, aim.z + nz * scale); + } + + public static Vec3 darkerSidePosition(Mob mob, LivingEntity target, double radius, double leadStrength) { + Vec3 left = sidePosition(mob, target, radius, 1.0D, leadStrength); + Vec3 right = sidePosition(mob, target, radius, -1.0D, leadStrength); + if (!AMConfig.ENABLE_DARK_APPROACH_AI.get()) { + return mob.getRandom().nextBoolean() ? left : right; + } + int leftLight = localLight(mob, left); + int rightLight = localLight(mob, right); + if (leftLight == rightLight) { + return mob.getRandom().nextBoolean() ? left : right; + } + return leftLight < rightLight ? left : right; + } + + public static Vec3 retreatPosition(Mob mob, LivingEntity target, double distance) { + Vec3 away = mob.position().subtract(target.position()); + double len = Math.sqrt(away.x * away.x + away.z * away.z); + if (len < 1.0E-3D) { + away = new Vec3(mob.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.0D, 0.0D); + len = 1.0D; + } + Vec3 dir = new Vec3(away.x / len, 0.0D, away.z / len); + return mob.position().add(dir.scale(distance)); + } + + public static boolean hasLineOfSight(Mob mob, LivingEntity target) { + if (target == null) { + return false; + } + HitResult hit = mob.level().clip(new ClipContext(mob.getEyePosition(), target.getEyePosition(), + ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, mob)); + return hit.getType() == HitResult.Type.MISS; + } + + public static boolean isReasonableGround(Mob mob, Vec3 pos) { + BlockPos block = BlockPos.containing(pos); + return mob.level().getWorldBorder().isWithinBounds(block) + && !mob.level().getBlockState(block).liquid() + && mob.level().getBlockState(block).getCollisionShape(mob.level(), block).isEmpty(); + } + + public static boolean isOpenToSky(Mob mob) { + return mob.level().canSeeSky(mob.blockPosition()); + } + + public static int localLight(Mob mob, Vec3 pos) { + return mob.level().getMaxLocalRawBrightness(BlockPos.containing(pos)); + } + + public static Vec3 elevatedPosition(Mob mob, LivingEntity target, double radius) { + Vec3 base = sidePosition(mob, target, radius, mob.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.0D); + for (int y = 2; y >= 0; y--) { + Vec3 candidate = base.add(0.0D, y, 0.0D); + if (isReasonableGround(mob, candidate)) { + return candidate; + } + } + return base; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveSpecialAbilities.java b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveSpecialAbilities.java new file mode 100644 index 0000000..2129ef2 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveSpecialAbilities.java @@ -0,0 +1,345 @@ +package net.fretux.adaptivemobs.ai; + +import net.fretux.adaptivemobs.config.AMConfig; +import net.fretux.adaptivemobs.difficulty.AdaptiveDifficultyManager; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.damagesource.DamageTypes; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.monster.AbstractSkeleton; +import net.minecraft.world.entity.monster.Blaze; +import net.minecraft.world.entity.monster.CaveSpider; +import net.minecraft.world.entity.monster.Drowned; +import net.minecraft.world.entity.monster.ElderGuardian; +import net.minecraft.world.entity.monster.EnderMan; +import net.minecraft.world.entity.monster.Endermite; +import net.minecraft.world.entity.monster.Evoker; +import net.minecraft.world.entity.monster.Guardian; +import net.minecraft.world.entity.monster.MagmaCube; +import net.minecraft.world.entity.monster.Phantom; +import net.minecraft.world.entity.monster.Pillager; +import net.minecraft.world.entity.monster.Ravager; +import net.minecraft.world.entity.monster.Shulker; +import net.minecraft.world.entity.monster.Silverfish; +import net.minecraft.world.entity.monster.Slime; +import net.minecraft.world.entity.monster.Spider; +import net.minecraft.world.entity.monster.Stray; +import net.minecraft.world.entity.monster.Vex; +import net.minecraft.world.entity.monster.Vindicator; +import net.minecraft.world.entity.monster.WitherSkeleton; +import net.minecraft.world.entity.monster.Zoglin; +import net.minecraft.world.entity.monster.ZombifiedPiglin; +import net.minecraft.world.entity.monster.hoglin.Hoglin; +import net.minecraft.world.entity.monster.piglin.PiglinBrute; +import net.minecraft.world.entity.monster.warden.Warden; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.entity.projectile.Arrow; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.entity.projectile.ShulkerBullet; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.Vec3; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.entity.EntityJoinLevelEvent; +import net.minecraftforge.event.entity.living.LivingHurtEvent; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public final class AdaptiveSpecialAbilities { + + private static final String COOLDOWN_PREFIX = "am_special_cd_"; + private static final List TEMPORARY_BLOCKS = new ArrayList<>(); + private static final List DELAYED_REAPPEARS = new ArrayList<>(); + + private AdaptiveSpecialAbilities() { + } + + public static void onProjectileJoin(EntityJoinLevelEvent event) { + if (!AMConfig.enabled || !(event.getLevel() instanceof ServerLevel level)) { + return; + } + Entity entity = event.getEntity(); + if (!(entity instanceof Projectile projectile) || !(projectile.getOwner() instanceof Mob mob)) { + return; + } + int tier = tier(level, mob); + if (tier < 4 || !(projectile instanceof Arrow arrow)) { + return; + } + LivingEntity target = mob.getTarget(); + if (mob instanceof Stray) { + arrow.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, tier >= 5 ? 100 : 70, tier >= 5 ? 1 : 0)); + if (tier >= 5 && mob.getRandom().nextFloat() < 0.22F) { + arrow.addEffect(new MobEffectInstance(MobEffects.DIG_SLOWDOWN, 70, 0)); + } + return; + } + if (mob instanceof AbstractSkeleton) { + float poisonChance = tier >= 5 ? 0.16F : 0.09F; + if (mob.getRandom().nextFloat() < poisonChance) { + arrow.addEffect(new MobEffectInstance(MobEffects.POISON, 80 + mob.getRandom().nextInt(41), 0)); + } + if (tier >= 5 && target != null && AdaptiveAIGoalUtils.isBlockingShield(target) && mob.getRandom().nextFloat() < 0.18F) { + arrow.addEffect(new MobEffectInstance(MobEffects.WEAKNESS, 60, 0)); + } else if (tier >= 5 && target != null && target.isSprinting() && mob.getRandom().nextFloat() < 0.18F) { + arrow.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 60, 0)); + } + return; + } + if (mob instanceof Pillager && tier >= 5 && mob.getRandom().nextFloat() < 0.18F) { + arrow.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 40, 1)); + arrow.getPersistentData().putBoolean("am_pinning_bolt", true); + } + } + + public static void onLivingHurt(LivingHurtEvent event) { + if (!AMConfig.enabled || !(event.getEntity().level() instanceof ServerLevel level)) { + return; + } + LivingEntity victim = event.getEntity(); + Entity sourceEntity = event.getSource().getEntity(); + Entity directEntity = event.getSource().getDirectEntity(); + + if (victim instanceof Mob damagedMob && sourceEntity instanceof LivingEntity attacker) { + onMobDamaged(level, damagedMob, attacker, directEntity); + } + if (victim instanceof ServerPlayer player && sourceEntity instanceof Mob attackerMob) { + onPlayerHurt(level, player, attackerMob, directEntity, event); + } + } + + public static void onServerTick(TickEvent.ServerTickEvent event) { + if (event.phase != TickEvent.Phase.END || event.getServer() == null) { + return; + } + long now = event.getServer().overworld().getGameTime(); + Iterator blockIterator = TEMPORARY_BLOCKS.iterator(); + while (blockIterator.hasNext()) { + TemporaryBlock block = blockIterator.next(); + if (now < block.expireTick) { + continue; + } + ServerLevel level = event.getServer().getLevel(block.dimension); + if (level != null && level.getBlockState(block.pos).is(Blocks.COBWEB)) { + level.removeBlock(block.pos, false); + } + blockIterator.remove(); + } + + Iterator reappearIterator = DELAYED_REAPPEARS.iterator(); + while (reappearIterator.hasNext()) { + DelayedReappear pending = reappearIterator.next(); + if (now < pending.tick) { + continue; + } + ServerLevel level = event.getServer().getLevel(pending.dimension); + if (level != null && pending.mob.isAlive() && pending.target.isAlive()) { + Vec3 side = AdaptivePositioningUtils.sidePosition(pending.mob, pending.target, 1.6D, + pending.mob.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.0D); + pending.mob.moveTo(side.x, side.y, side.z, pending.mob.getYRot(), pending.mob.getXRot()); + pending.mob.removeEffect(MobEffects.INVISIBILITY); + pending.mob.setTarget(pending.target); + AdaptiveAIGoalUtils.debug(pending.mob, () -> pending.tier, "silverfish burrow burst"); + } + reappearIterator.remove(); + } + } + + private static void onMobDamaged(ServerLevel level, Mob mob, LivingEntity attacker, Entity directEntity) { + int tier = tier(level, mob); + if (tier <= 0) { + return; + } + if (tier >= 5 && mob instanceof ZombifiedPiglin && ready(mob, "blood_call", 160)) { + for (Mob ally : AdaptiveTargetingUtils.nearbyHostiles(mob, 12.0D, other -> other instanceof ZombifiedPiglin)) { + ally.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SPEED, 100, 1)); + ally.addEffect(new MobEffectInstance(MobEffects.DAMAGE_BOOST, 100, 0)); + ally.setTarget(attacker); + } + AdaptiveAIGoalUtils.debug(mob, () -> tier, "zombified piglin blood call"); + } + if (tier >= 4 && mob instanceof Spider && ready(mob, "web_retreat", 150)) { + placeTemporaryCobweb(level, attacker.blockPosition(), level.getGameTime() + 100 + mob.getRandom().nextInt(61)); + } + if (tier >= 4 && mob instanceof EnderMan enderman && directEntity == attacker && ready(mob, "backstep_ambush", tier >= 5 ? 80 : 130)) { + Vec3 behind = attacker.position().subtract(attacker.getLookAngle().normalize().scale(2.2D)); + if (enderman.randomTeleport(behind.x, behind.y, behind.z, true)) { + enderman.setTarget(attacker); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "enderman backstep ambush"); + } + } + if (tier >= 4 && mob instanceof Silverfish silverfish + && AdaptiveAIGoalUtils.healthFraction(silverfish) < 0.45D + && ready(mob, "burrow_burst", 220)) { + silverfish.addEffect(new MobEffectInstance(MobEffects.INVISIBILITY, 35, 0)); + silverfish.getNavigation().stop(); + DELAYED_REAPPEARS.add(new DelayedReappear(level.dimension(), level.getGameTime() + 24, silverfish, attacker, tier)); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "silverfish burrow vanish"); + } + if (tier >= 4 && mob instanceof Evoker evoker && ready(mob, "vex_relay", 120)) { + for (Mob vex : AdaptiveTargetingUtils.nearbyHostiles(evoker, 14.0D, other -> other instanceof Vex)) { + vex.setTarget(attacker); + } + Vec3 retreat = AdaptivePositioningUtils.retreatPosition(evoker, attacker, 5.0D); + evoker.getNavigation().moveTo(retreat.x, retreat.y, retreat.z, 1.0D); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "evoker vex relay"); + } + if (tier >= 5 && mob instanceof Blaze && eventWasRanged(directEntity) && ready(mob, "overheat", 120)) { + mob.addEffect(new MobEffectInstance(MobEffects.DAMAGE_BOOST, 80, 0)); + mob.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SPEED, 80, 0)); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "blaze overheat volley"); + } + if (tier >= 5 && mob instanceof Zoglin && AdaptiveAIGoalUtils.healthFraction(mob) < 0.50D && ready(mob, "rampage", 180)) { + mob.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SPEED, 100, 1)); + mob.addEffect(new MobEffectInstance(MobEffects.DAMAGE_RESISTANCE, 100, 0)); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "zoglin frenzied rampage"); + } + if (tier >= 5 && mob instanceof Warden && eventWasRanged(directEntity) && attacker instanceof ServerPlayer player) { + AdaptiveMemory.rememberThreat(mob, player, 20 * 30); + mob.getPersistentData().putLong(COOLDOWN_PREFIX + "echo_mark", level.getGameTime() + 20 * 30L); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "warden echo mark"); + } + } + + private static void onPlayerHurt(ServerLevel level, ServerPlayer player, Mob mob, Entity directEntity, LivingHurtEvent event) { + int tier = tier(level, mob); + if (tier <= 0) { + return; + } + if (tier >= 4 && mob instanceof Drowned && mob.isInWater() && player.isInWater() && ready(mob, "dragging_grip", 160)) { + player.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 60, 1)); + player.setDeltaMovement(player.getDeltaMovement().add(0.0D, -0.22D, 0.0D)); + AdaptiveAIGoalUtils.debug(mob, () -> tier, "drowned dragging grip"); + } + if (mob instanceof WitherSkeleton && tier >= 4 && AdaptiveAIGoalUtils.healthFraction(player) < 0.40D) { + player.addEffect(new MobEffectInstance(MobEffects.WITHER, tier >= 5 ? 140 : 100, 0)); + shove(player, mob.position(), tier >= 5 ? 0.55D : 0.35D, 0.08D); + } + if (mob instanceof Spider && tier >= 4 && ready(mob, "web_hit", mob instanceof CaveSpider ? 100 : 140)) { + placeTemporaryCobweb(level, player.blockPosition(), level.getGameTime() + 100 + mob.getRandom().nextInt(61)); + } + if (mob instanceof CaveSpider && tier >= 3 + && (AdaptiveAIGoalUtils.isUsingRangedWeapon(player) || player.isUsingItem())) { + player.addEffect(new MobEffectInstance(MobEffects.POISON, 60, 0)); + } + if (mob instanceof Pillager && tier >= 5 && directEntity instanceof AbstractArrow arrow + && arrow.getPersistentData().getBoolean("am_pinning_bolt")) { + player.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 30, 1)); + disableShield(player); + } + if ((mob instanceof Vindicator || mob instanceof PiglinBrute) && tier >= 5) { + event.setAmount(event.getAmount() + 2.0F); + disableShield(player); + } + if ((mob instanceof Ravager || mob instanceof Hoglin) && tier >= 4 && ready(mob, "crushing_charge", 120)) { + shove(player, mob.position(), mob instanceof Ravager ? 1.15D : 0.85D, 0.35D); + if (player.horizontalCollision) { + event.setAmount(event.getAmount() + 3.0F); + } + } + if (mob instanceof Guardian && tier >= 4) { + int focused = AdaptiveTargetingUtils.nearbyHostiles(mob, 12.0D, + other -> other instanceof Guardian && other.getTarget() == player).size(); + if (focused >= 2) { + event.setAmount(event.getAmount() * (tier >= 5 ? 1.25F : 1.15F)); + } + if (mob instanceof ElderGuardian) { + player.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 50, 0)); + player.setDeltaMovement(player.getDeltaMovement().add(0.0D, -0.12D, 0.0D)); + } + } + if (mob instanceof Shulker && tier >= 4 && player.hasEffect(MobEffects.LEVITATION)) { + player.addEffect(new MobEffectInstance(MobEffects.LEVITATION, 80, 0)); + player.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 50, 0)); + } + if ((mob instanceof Slime || mob instanceof MagmaCube) && tier >= 5 && mob.getBbWidth() <= 1.5F) { + mob.addEffect(new MobEffectInstance(MobEffects.DAMAGE_BOOST, 80, 0)); + mob.addEffect(new MobEffectInstance(MobEffects.JUMP, 80, 1)); + if (mob instanceof MagmaCube) { + player.setSecondsOnFire(2); + } + } + if (mob instanceof Phantom && tier >= 5) { + player.addEffect(new MobEffectInstance(MobEffects.HUNGER, 100, 0)); + } + if (mob instanceof Vex && tier >= 5 && mob.noPhysics) { + event.setAmount(event.getAmount() + 1.5F); + player.addEffect(new MobEffectInstance(MobEffects.WEAKNESS, 50, 0)); + } + if (mob instanceof Endermite && tier >= 3) { + for (Mob ally : AdaptiveTargetingUtils.nearbyHostiles(mob, 10.0D, + other -> other instanceof Endermite || other instanceof EnderMan)) { + ally.setTarget(player); + } + } + if (mob.getPersistentData().getLong(COOLDOWN_PREFIX + "echo_mark") > level.getGameTime() + && event.getSource().is(DamageTypes.SONIC_BOOM)) { + player.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 80, 1)); + shove(player, mob.position(), 0.65D, 0.10D); + } + } + + private static int tier(ServerLevel level, Mob mob) { + if (!AMConfig.isMobEnabled(mob.getType())) { + return 0; + } + return AdaptiveDifficultyManager.getMobTier(level, mob.getType()); + } + + private static boolean ready(Mob mob, String key, long cooldownTicks) { + long now = mob.level().getGameTime(); + String fullKey = COOLDOWN_PREFIX + key; + if (mob.getPersistentData().getLong(fullKey) > now) { + return false; + } + mob.getPersistentData().putLong(fullKey, now + cooldownTicks); + return true; + } + + private static void disableShield(ServerPlayer player) { + if (AdaptiveAIGoalUtils.isBlockingShield(player)) { + player.disableShield(true); + } + } + + private static void shove(LivingEntity target, Vec3 from, double horizontal, double vertical) { + Vec3 away = target.position().subtract(from); + double len = Math.max(0.001D, Math.sqrt(away.x * away.x + away.z * away.z)); + target.setDeltaMovement(target.getDeltaMovement().add(away.x / len * horizontal, vertical, away.z / len * horizontal)); + target.hurtMarked = true; + } + + private static void placeTemporaryCobweb(ServerLevel level, BlockPos requestedPos, long expireTick) { + BlockPos pos = level.getFluidState(requestedPos).is(FluidTags.WATER) ? requestedPos.above() : requestedPos; + if (!level.getBlockState(pos).isAir() || !level.getWorldBorder().isWithinBounds(pos)) { + return; + } + level.setBlock(pos, Blocks.COBWEB.defaultBlockState(), 3); + TEMPORARY_BLOCKS.add(new TemporaryBlock(level.dimension(), pos.immutable(), expireTick)); + level.playSound(null, pos, SoundEvents.SPIDER_AMBIENT, SoundSource.HOSTILE, 0.6F, 1.25F); + } + + private static boolean eventWasRanged(Entity directEntity) { + return directEntity instanceof Projectile; + } + + private record TemporaryBlock(net.minecraft.resources.ResourceKey dimension, + BlockPos pos, long expireTick) { + } + + private record DelayedReappear(net.minecraft.resources.ResourceKey dimension, + long tick, Silverfish mob, LivingEntity target, int tier) { + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveTargetingUtils.java b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveTargetingUtils.java new file mode 100644 index 0000000..3b82d28 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/AdaptiveTargetingUtils.java @@ -0,0 +1,63 @@ +package net.fretux.adaptivemobs.ai; + +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.monster.Enemy; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +public final class AdaptiveTargetingUtils { + + private AdaptiveTargetingUtils() { + } + + public static List nearbyHostiles(Mob mob, double radius, Predicate predicate) { + AABB box = mob.getBoundingBox().inflate(radius); + List found = mob.level().getEntitiesOfClass(Mob.class, box, + other -> other != mob && other instanceof Enemy && predicate.test(other)); + int max = AMConfig.AI_MAX_NEARBY_MOBS_SCANNED.get(); + if (found.size() <= max) { + return found; + } + return new ArrayList<>(found.subList(0, max)); + } + + public static int nearbyAttackers(Mob mob, LivingEntity target, double radius) { + if (target == null) { + return 0; + } + return nearbyHostiles(mob, radius, other -> other.getTarget() == target).size(); + } + + public static boolean hasAllyBetween(Mob mob, LivingEntity target, double width) { + if (target == null) { + return false; + } + Vec3 start = mob.getEyePosition(); + Vec3 end = target.getEyePosition(); + Vec3 line = end.subtract(start); + double lenSqr = line.lengthSqr(); + if (lenSqr < 1.0E-4D) { + return false; + } + List allies = nearbyHostiles(mob, Math.min(16.0D, Math.sqrt(lenSqr) + 2.0D), + other -> other.getTarget() == target || other.getTarget() == null); + for (Mob ally : allies) { + Vec3 toAlly = ally.position().add(0.0D, ally.getBbHeight() * 0.5D, 0.0D).subtract(start); + double t = toAlly.dot(line) / lenSqr; + if (t <= 0.05D || t >= 0.95D) { + continue; + } + Vec3 closest = start.add(line.scale(t)); + if (closest.distanceTo(ally.position().add(0.0D, ally.getBbHeight() * 0.5D, 0.0D)) <= width + ally.getBbWidth()) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveAirbornePositioningGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveAirbornePositioningGoal.java new file mode 100644 index 0000000..3b0bd96 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveAirbornePositioningGoal.java @@ -0,0 +1,52 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveAirbornePositioningGoal extends Goal { + + private final Mob mob; + private final IntSupplier tierSupplier; + private final double range; + private final double verticalOffset; + private int cooldown; + + public AdaptiveAirbornePositioningGoal(Mob mob, IntSupplier tierSupplier, double range, double verticalOffset) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.range = range; + this.verticalOffset = verticalOffset; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 2 && mob.getTarget() != null && mob.getTarget().isAlive() && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = AdaptiveAIGoalUtils.nextCooldown(mob); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + boolean spread = tier >= 4 && AdaptiveTargetingUtils.nearbyAttackers(mob, target, range) > 1; + double lead = tier >= 5 ? AMConfig.tierValue(AMConfig.AI_INTERCEPTION_STRENGTH.get(), tier) : 0.0D; + Vec3 dest = AdaptivePositioningUtils.sidePosition(mob, target, range, + spread && mob.getRandom().nextBoolean() ? -1.0D : 1.0D, lead).add(0.0D, verticalOffset, 0.0D); + mob.getMoveControl().setWantedPosition(dest.x, dest.y, dest.z, 1.0D); + mob.getLookControl().setLookAt(target, 30.0F, 30.0F); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "airborne reposition"); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveAntiCheeseGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveAntiCheeseGoal.java new file mode 100644 index 0000000..f8a8790 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveAntiCheeseGoal.java @@ -0,0 +1,255 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.AbstractSkeleton; +import net.minecraft.world.entity.monster.Creeper; +import net.minecraft.world.entity.monster.EnderMan; +import net.minecraft.world.entity.monster.Pillager; +import net.minecraft.world.entity.monster.Zombie; +import net.minecraft.world.entity.vehicle.AbstractMinecart; +import net.minecraft.world.entity.vehicle.Boat; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.List; +import java.util.function.IntSupplier; + +public class AdaptiveAntiCheeseGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveAntiCheeseGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_ANTI_CHEESE_AI.get() + && tierSupplier.getAsInt() >= 3 + && mob.getTarget() != null + && mob.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 55 + mob.getRandom().nextInt(80); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + mob.getLookControl().setLookAt(target, 30.0F, 30.0F); + + if (avoidTrap()) { + return; + } + if (mob instanceof Zombie && isVerticalObstacleCheese(target)) { + if (tryCorpseLadderSurge(target)) { + return; + } + if (tryZombieStack(target)) { + return; + } + Vec3 dest = AdaptivePositioningUtils.darkerSidePosition(mob, target, 2.5D, 0.0D); + moveIfReasonable(dest, 1.0D, "zombie pillar gather"); + return; + } + if ((mob instanceof AbstractSkeleton || mob instanceof Pillager) && !mob.hasLineOfSight(target)) { + Vec3 dest = AdaptivePositioningUtils.darkerSidePosition(mob, target, 7.0D, 0.0D); + moveIfReasonable(dest, 1.0D, "ranged tiny-window reposition"); + return; + } + if (mob instanceof Creeper creeper && target.hasLineOfSight(creeper) + && AdaptivePositioningUtils.isOpenToSky(mob) + && Math.sqrt(mob.distanceToSqr(target)) > 4.0D) { + creeper.setSwellDir(-1); + Vec3 dest = AdaptivePositioningUtils.darkerSidePosition(mob, target, 5.0D, 0.0D); + moveIfReasonable(dest, 1.0D, "creeper open-ground hesitation"); + return; + } + if (mob instanceof EnderMan && (mob.level().getFluidState(mob.blockPosition()).is(FluidTags.WATER) + || target.level().getFluidState(target.blockPosition()).is(FluidTags.WATER))) { + Vec3 dest = AdaptivePositioningUtils.retreatPosition(mob, target, 7.0D); + moveIfReasonable(dest, 1.0D, "enderman water disengage"); + } + } + + private boolean avoidTrap() { + Entity vehicle = mob.getVehicle(); + if (vehicle instanceof Boat || vehicle instanceof AbstractMinecart) { + mob.stopRiding(); + moveAwayFrom(vehicle.position(), 1.15D, "trap vehicle escape"); + return true; + } + Entity trapVehicle = nearestTrapVehicle(); + if (trapVehicle != null && mob.distanceToSqr(trapVehicle) < 2.9D) { + moveAwayFrom(trapVehicle.position(), 1.05D, "trap vehicle avoidance"); + return true; + } + Vec3 trapBlock = nearestTrapBlock(); + if (trapBlock != null) { + moveAwayFrom(trapBlock, 1.05D, "trap block avoidance"); + return true; + } + return false; + } + + private Entity nearestTrapVehicle() { + List vehicles = mob.level().getEntitiesOfClass(Entity.class, mob.getBoundingBox().inflate(2.5D), + entity -> entity instanceof Boat || entity instanceof AbstractMinecart); + Entity nearest = null; + double best = Double.MAX_VALUE; + for (Entity entity : vehicles) { + double dist = mob.distanceToSqr(entity); + if (dist < best) { + best = dist; + nearest = entity; + } + } + return nearest; + } + + private Vec3 nearestTrapBlock() { + Vec3 nearest = null; + double best = Double.MAX_VALUE; + for (int x = -1; x <= 1; x++) { + for (int y = -1; y <= 1; y++) { + for (int z = -1; z <= 1; z++) { + BlockState state = mob.level().getBlockState(mob.blockPosition().offset(x, y, z)); + if (!isTrapBlock(state)) { + continue; + } + Vec3 pos = Vec3.atCenterOf(mob.blockPosition().offset(x, y, z)); + double dist = mob.position().distanceToSqr(pos); + if (dist < best) { + best = dist; + nearest = pos; + } + } + } + } + return nearest; + } + + private boolean isTrapBlock(BlockState state) { + return state.is(Blocks.COBWEB) + || state.is(Blocks.POWDER_SNOW) + || state.is(Blocks.SWEET_BERRY_BUSH); + } + + private void moveAwayFrom(Vec3 threat, double speed, String debug) { + Vec3 away = mob.position().subtract(threat); + double len = Math.sqrt(away.x * away.x + away.z * away.z); + if (len < 1.0E-3D) { + away = new Vec3(mob.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.0D, 0.0D); + len = 1.0D; + } + Vec3 dest = mob.position().add(away.x / len * 4.0D, 0.0D, away.z / len * 4.0D); + moveIfReasonable(dest, speed, debug); + } + + private boolean tryZombieStack(LivingEntity target) { + if (mob.isPassenger() || mob.isVehicle()) { + return false; + } + List carriers = mob.level().getEntitiesOfClass(Zombie.class, mob.getBoundingBox().inflate(2.0D), + zombie -> zombie != mob + && zombie.isAlive() + && !zombie.isVehicle() + && zombie.getTarget() == target + && Math.abs(zombie.getY() - mob.getY()) < 1.25D); + Zombie bestCarrier = null; + double best = Double.MAX_VALUE; + for (Zombie carrier : carriers) { + double dist = mob.distanceToSqr(carrier); + if (dist < best) { + best = dist; + bestCarrier = carrier; + } + } + if (bestCarrier == null) { + return false; + } + boolean mounted = mob.startRiding(bestCarrier, true); + if (mounted) { + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "zombie stacking over obstacle"); + } + return mounted; + } + + private boolean tryCorpseLadderSurge(LivingEntity target) { + if (tierSupplier.getAsInt() < 5 || !mob.isPassenger()) { + return false; + } + double vertical = target.getY() - mob.getY(); + double horizontal = Math.sqrt((target.getX() - mob.getX()) * (target.getX() - mob.getX()) + + (target.getZ() - mob.getZ()) * (target.getZ() - mob.getZ())); + if (vertical < 0.75D || vertical > 2.25D || horizontal > 2.0D) { + return false; + } + List nearby = mob.level().getEntitiesOfClass(Zombie.class, mob.getBoundingBox().inflate(2.5D), + zombie -> zombie.isAlive() && zombie.getTarget() == target); + if (nearby.size() < 3) { + return false; + } + mob.setDeltaMovement(mob.getDeltaMovement().add(0.0D, 0.45D, 0.0D)); + mob.hurtMarked = true; + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "zombie corpse ladder surge"); + return true; + } + + private boolean isVerticalObstacleCheese(LivingEntity target) { + return isPillaring(target) || isSimpleWallBlocked(target); + } + + private boolean isPillaring(LivingEntity target) { + double vertical = target.getY() - mob.getY(); + double horizontal = Math.sqrt((target.getX() - mob.getX()) * (target.getX() - mob.getX()) + + (target.getZ() - mob.getZ()) * (target.getZ() - mob.getZ())); + return vertical > 2.5D && horizontal < 5.5D; + } + + private boolean isSimpleWallBlocked(LivingEntity target) { + double vertical = Math.abs(target.getY() - mob.getY()); + double horizontal = Math.sqrt((target.getX() - mob.getX()) * (target.getX() - mob.getX()) + + (target.getZ() - mob.getZ()) * (target.getZ() - mob.getZ())); + if (vertical > 2.0D || horizontal > 5.5D || mob.hasLineOfSight(target)) { + return false; + } + Vec3 direction = target.position().subtract(mob.position()); + int steps = Math.max(2, (int) Math.ceil(horizontal)); + for (int i = 1; i < steps; i++) { + double scale = i / (double) steps; + BlockPos base = BlockPos.containing(mob.getX() + direction.x * scale, mob.getY(), mob.getZ() + direction.z * scale); + if (isSolidObstacle(base.above()) || isSolidObstacle(base.above(2))) { + return true; + } + } + return false; + } + + private boolean isSolidObstacle(BlockPos pos) { + return !mob.level().getBlockState(pos).getCollisionShape(mob.level(), pos).isEmpty(); + } + + private void moveIfReasonable(Vec3 dest, double speed, String debug) { + if (AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, speed); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, debug); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveBiomeTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveBiomeTacticsGoal.java new file mode 100644 index 0000000..01e06e9 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveBiomeTacticsGoal.java @@ -0,0 +1,83 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.AbstractSkeleton; +import net.minecraft.world.entity.monster.Blaze; +import net.minecraft.world.entity.monster.Drowned; +import net.minecraft.world.entity.monster.Spider; +import net.minecraft.world.entity.monster.Zoglin; +import net.minecraft.world.entity.monster.hoglin.Hoglin; +import net.minecraft.world.entity.monster.piglin.Piglin; +import net.minecraft.world.entity.monster.piglin.PiglinBrute; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveBiomeTacticsGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveBiomeTacticsGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 3 && mob.getTarget() != null && mob.getTarget().isAlive() && --cooldown <= 0; + } + + @Override + public void start() { + int tier = tierSupplier.getAsInt(); + cooldown = tier >= 5 ? 45 + mob.getRandom().nextInt(55) : 80 + mob.getRandom().nextInt(90); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + if (isNetherMob() && mob.level().dimension() == Level.NETHER && mob.distanceToSqr(target) < 18.0D * 18.0D) { + double speed = tier >= 5 ? 1.25D : (tier >= 4 ? 1.18D : 1.12D); + mob.getNavigation().moveTo(target, speed); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "nether aggression"); + return; + } + if (mob instanceof Drowned && mob.isInWater() && target.isInWater()) { + mob.getNavigation().moveTo(target, 1.12D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "drowned water pressure"); + return; + } + if (mob instanceof Spider && !mob.level().canSeeSky(mob.blockPosition())) { + Vec3 elevated = AdaptivePositioningUtils.elevatedPosition(mob, target, 3.0D); + mob.getNavigation().moveTo(elevated.x, elevated.y, elevated.z, 1.12D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "cave vertical spider pressure"); + return; + } + if (mob instanceof AbstractSkeleton && mob.level().canSeeSky(mob.blockPosition())) { + Vec3 dest = AdaptivePositioningUtils.sidePosition(mob, target, 9.0D, mob.getRandom().nextBoolean() ? 1.0D : -1.0D, + AMConfig.tierValue(AMConfig.AI_INTERCEPTION_STRENGTH.get(), tierSupplier.getAsInt()) * 0.5D); + if (AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.0D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "skeleton open terrain spacing"); + } + } + } + + private boolean isNetherMob() { + return mob instanceof Piglin || mob instanceof PiglinBrute || mob instanceof Hoglin + || mob instanceof Zoglin + || mob instanceof Blaze + || mob.getType() == EntityType.GHAST + || mob.getType() == EntityType.MAGMA_CUBE; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveCreeperPressureGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveCreeperPressureGoal.java new file mode 100644 index 0000000..601ea55 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveCreeperPressureGoal.java @@ -0,0 +1,58 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.Creeper; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveCreeperPressureGoal extends Goal { + + private final Creeper creeper; + private final IntSupplier tierSupplier; + + public AdaptiveCreeperPressureGoal(Creeper creeper, IntSupplier tierSupplier) { + this.creeper = creeper; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + LivingEntity target = creeper.getTarget(); + return tierSupplier.getAsInt() >= 3 && target != null && target.isAlive(); + } + + @Override + public void tick() { + LivingEntity target = creeper.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + double startSwell = tier >= 5 ? 5.0D : 4.0D; + double stopSwell = tier >= 4 ? 7.0D : 6.0D; + double dist = Math.sqrt(creeper.distanceToSqr(target)); + creeper.getLookControl().setLookAt(target, 30.0F, 30.0F); + + if (AdaptiveAIGoalUtils.isBlockingShield(target) && dist <= stopSwell) { + creeper.setSwellDir(-1); + Vec3 dest = AdaptivePositioningUtils.sidePosition(creeper, target, Math.max(2.8D, dist), + creeper.getRandom().nextBoolean() ? 1.0D : -1.0D, tier >= 5 ? 0.25D : 0.0D); + if (AdaptivePositioningUtils.isReasonableGround(creeper, dest)) { + creeper.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.05D); + } + return; + } + if (dist <= startSwell || (tier >= 4 && target.getLastHurtMob() != null && dist <= stopSwell)) { + creeper.setSwellDir(1); + creeper.getNavigation().stop(); + } else { + creeper.setSwellDir(-1); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveCreeperTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveCreeperTacticsGoal.java new file mode 100644 index 0000000..71c9ce7 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveCreeperTacticsGoal.java @@ -0,0 +1,84 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.Creeper; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveCreeperTacticsGoal extends Goal { + + private final Creeper creeper; + private final IntSupplier tierSupplier; + private int cooldown; + private int retreatTicks; + private int blinkCooldown; + + public AdaptiveCreeperTacticsGoal(Creeper creeper, IntSupplier tierSupplier) { + this.creeper = creeper; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 2 && creeper.getTarget() != null && creeper.getTarget().isAlive(); + } + + @Override + public void tick() { + LivingEntity target = creeper.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + double dist = Math.sqrt(creeper.distanceToSqr(target)); + creeper.getLookControl().setLookAt(target, 30.0F, 30.0F); + + if (AdaptiveAIGoalUtils.isBlockingShield(target) && dist <= 7.0D) { + creeper.setSwellDir(-1); + if (cooldown-- <= 0) { + cooldown = 30 + creeper.getRandom().nextInt(35); + Vec3 dest = AdaptivePositioningUtils.sidePosition(creeper, target, Math.max(3.0D, dist), + creeper.getRandom().nextBoolean() ? 1.0D : -1.0D, tier >= 5 ? 0.25D : 0.0D); + if (AdaptivePositioningUtils.isReasonableGround(creeper, dest)) { + creeper.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.05D); + AdaptiveAIGoalUtils.debug(creeper, tierSupplier, "creeper shield sidestep"); + } + } + return; + } + if (tier >= 2 && dist > 4.5D && creeper.getSwellDir() > 0) { + creeper.setSwellDir(-1); + } + if (tier >= 3 && dist > 3.2D && creeper.getSwellDir() > 0) { + creeper.setSwellDir(-1); + } + if (tier >= 4 && AdaptiveTargetingUtils.nearbyAttackers(creeper, target, 7.0D) > 0 && dist <= 5.0D) { + creeper.setSwellDir(1); + } + if (tier >= 5 && dist <= 4.0D && blinkCooldown-- <= 0 && creeper.getSwellDir() <= 0) { + blinkCooldown = 180 + creeper.getRandom().nextInt(120); + creeper.addEffect(new MobEffectInstance(MobEffects.INVISIBILITY, 10, 0, false, false)); + creeper.level().playSound(null, creeper.blockPosition(), SoundEvents.CREEPER_PRIMED, + SoundSource.HOSTILE, 0.8F, 1.35F); + AdaptiveAIGoalUtils.debug(creeper, tierSupplier, "creeper blink shroud"); + } + if (tier >= 5 && retreatTicks-- <= 0 && cooldown-- <= 0 && target.hasLineOfSight(creeper) && dist > 5.0D) { + cooldown = 120 + creeper.getRandom().nextInt(80); + retreatTicks = 25; + Vec3 dest = AdaptivePositioningUtils.retreatPosition(creeper, target, 5.0D); + creeper.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.05D); + AdaptiveAIGoalUtils.debug(creeper, tierSupplier, "creeper brief retreat"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEndermanTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEndermanTacticsGoal.java new file mode 100644 index 0000000..a2937c4 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEndermanTacticsGoal.java @@ -0,0 +1,74 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.core.BlockPos; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.EnderMan; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveEndermanTacticsGoal extends Goal { + + private final EnderMan enderman; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveEndermanTacticsGoal(EnderMan enderman, IntSupplier tierSupplier) { + this.enderman = enderman; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_ENDERMAN_AI.get() + && tierSupplier.getAsInt() >= 2 + && enderman.getTarget() != null + && enderman.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + LivingEntity target = enderman.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + boolean inEnd = enderman.level().dimension() == Level.END; + cooldown = inEnd && tier >= 5 ? 35 + enderman.getRandom().nextInt(45) : 60 + enderman.getRandom().nextInt(80); + double dist = Math.sqrt(enderman.distanceToSqr(target)); + boolean waterNearby = enderman.level().getFluidState(enderman.blockPosition()).is(FluidTags.WATER); + boolean strongMelee = tier >= 5 && dist < 4.0D && !AdaptiveAIGoalUtils.isUsingRangedWeapon(target); + if (inEnd && tier >= 4) { + double radius = tier >= 5 ? 18.0D : 12.0D; + AdaptiveTargetingUtils.nearbyHostiles(enderman, radius, + other -> other instanceof EnderMan && (other.getTarget() == null || other.getTarget() == target)) + .forEach(other -> other.setTarget(target)); + AdaptiveAIGoalUtils.debug(enderman, tierSupplier, "enderman coordinated target"); + } + if (tier >= 3 || waterNearby || strongMelee) { + Vec3 side = AdaptivePositioningUtils.sidePosition(enderman, target, strongMelee ? 8.0D : (inEnd && tier >= 5 ? 5.0D : 3.0D), + enderman.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.0D); + int attempts = inEnd && tier >= 5 ? 6 : 4; + for (int i = 0; i < attempts; i++) { + Vec3 candidate = side.add(enderman.getRandom().nextInt(5) - 2, 0.0D, enderman.getRandom().nextInt(5) - 2); + BlockPos pos = BlockPos.containing(candidate); + if (!enderman.level().getFluidState(pos).is(FluidTags.WATER) + && AdaptivePositioningUtils.isReasonableGround(enderman, candidate) + && enderman.randomTeleport(candidate.x, candidate.y, candidate.z, true)) { + AdaptiveAIGoalUtils.debug(enderman, tierSupplier, "enderman angular teleport"); + return; + } + } + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEndermiteTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEndermiteTacticsGoal.java new file mode 100644 index 0000000..3d4f0de --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEndermiteTacticsGoal.java @@ -0,0 +1,73 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveEndermiteTacticsGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + private LivingEntity rememberedTarget; + + public AdaptiveEndermiteTacticsGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_MELEE_AI.get() + && AMConfig.ENABLE_ENDERMITE_AI.get() + && AMConfig.AI_SMALL_SWARM.get() + && tierSupplier.getAsInt() >= 2 + && currentTarget() != null + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 18 + mob.getRandom().nextInt(28); + LivingEntity target = currentTarget(); + if (target == null) { + return; + } + rememberedTarget = target; + if (mob.getTarget() == null) { + mob.setTarget(target); + } + + int tier = tierSupplier.getAsInt(); + double distance = Math.sqrt(mob.distanceToSqr(target)); + double side = mob.getId() % 2 == 0 ? 1.0D : -1.0D; + double lead = tier >= 5 ? AMConfig.tierValue(AMConfig.AI_INTERCEPTION_STRENGTH.get(), tier) : 0.0D; + Vec3 dest = AdaptivePositioningUtils.sidePosition(mob, target, Math.max(1.5D, distance * 0.45D), side, lead); + if (!AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + dest = target.position(); + } + mob.getLookControl().setLookAt(target, 35.0F, 35.0F); + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, tier >= 5 ? 1.25D : 1.15D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "endermite side pursuit"); + } + + private LivingEntity currentTarget() { + LivingEntity target = mob.getTarget(); + if (target != null && target.isAlive()) { + return target; + } + if (rememberedTarget != null && rememberedTarget.isAlive() && mob.distanceToSqr(rememberedTarget) < 16.0D * 16.0D) { + return rememberedTarget; + } + rememberedTarget = null; + return null; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEscapeDenialGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEscapeDenialGoal.java new file mode 100644 index 0000000..c0ca603 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEscapeDenialGoal.java @@ -0,0 +1,53 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.Spider; +import net.minecraft.world.entity.monster.Zombie; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveEscapeDenialGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveEscapeDenialGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 3 + && (mob instanceof Zombie || mob instanceof Spider) + && mob.getTarget() != null + && mob.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 90 + mob.getRandom().nextInt(90); + LivingEntity target = mob.getTarget(); + if (target == null || mob.distanceToSqr(target) > 12.0D * 12.0D) { + return; + } + Vec3 look = target.getLookAngle(); + Vec3 exitBias = target.position().add(look.x * 3.0D, 0.0D, look.z * 3.0D); + if (!AdaptivePositioningUtils.isReasonableGround(mob, exitBias)) { + exitBias = AdaptivePositioningUtils.darkerSidePosition(mob, target, 3.5D, 0.0D); + } + if (AdaptivePositioningUtils.isReasonableGround(mob, exitBias)) { + mob.getNavigation().moveTo(exitBias.x, exitBias.y, exitBias.z, mob instanceof Spider ? 1.15D : 1.0D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "escape route pressure"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEvokerTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEvokerTacticsGoal.java new file mode 100644 index 0000000..e4901da --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveEvokerTacticsGoal.java @@ -0,0 +1,80 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.AbstractIllager; +import net.minecraft.world.entity.monster.Evoker; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveEvokerTacticsGoal extends Goal { + + private final Evoker evoker; + private final IntSupplier tierSupplier; + private int cooldown; + private int lastSpellTicks; + private int stillTicks; + private Vec3 lastPos = Vec3.ZERO; + + public AdaptiveEvokerTacticsGoal(Evoker evoker, IntSupplier tierSupplier) { + this.evoker = evoker; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_RAID_MOB_AI.get() + && AMConfig.ENABLE_EVOKER_AI.get() + && AMConfig.AI_EVOKER.get() + && tierSupplier.getAsInt() >= 2 + && evoker.getTarget() != null + && evoker.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = evoker.isCastingSpell() ? 35 + evoker.getRandom().nextInt(35) : 55 + evoker.getRandom().nextInt(55); + LivingEntity target = evoker.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + double distance = Math.sqrt(evoker.distanceToSqr(target)); + boolean justCast = lastSpellTicks > 0 || evoker.isCastingSpell(); + lastSpellTicks = evoker.isCastingSpell() ? 60 : Math.max(0, lastSpellTicks - cooldown); + updateStillTicks(); + + boolean meleeRush = distance < 7.0D && !AdaptiveAIGoalUtils.isUsingRangedWeapon(target); + boolean exposed = evoker.hasLineOfSight(target) && !AdaptiveAIGoalUtils.isBlockingShield(target); + boolean useCover = tier >= 4 && AdaptiveTargetingUtils.nearbyHostiles(evoker, 8.0D, + other -> other instanceof AbstractIllager && other != evoker && other.getTarget() == target).size() > 0; + + if (meleeRush || justCast || stillTicks > 3 || (useCover && exposed)) { + Vec3 dest = useCover + ? AdaptivePositioningUtils.sidePosition(evoker, target, 10.0D, evoker.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.0D) + : AdaptivePositioningUtils.retreatPosition(evoker, target, meleeRush ? 6.0D : 4.0D); + if (AdaptivePositioningUtils.isReasonableGround(evoker, dest)) { + evoker.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.0D); + AdaptiveAIGoalUtils.debug(evoker, tierSupplier, "evoker reposition"); + } + } + } + + private void updateStillTicks() { + Vec3 pos = evoker.position(); + if (pos.distanceToSqr(lastPos) < 0.08D) { + stillTicks++; + } else { + stillTicks = 0; + } + lastPos = pos; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveFlankGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveFlankGoal.java new file mode 100644 index 0000000..564a50e --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveFlankGoal.java @@ -0,0 +1,129 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +/** + * A cooperative approach goal that makes a mob close on its target from an angle (flanking / + * circling) instead of marching straight in, and — at high tiers — aim at where the target is + * heading rather than where it currently is. + * + *

It only takes over movement when the mob is at medium range. Once the mob is close it yields + * (canContinueToUse returns false) so the vanilla melee/attack goal resumes and actually hits.

+ */ +public class AdaptiveFlankGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private final int minTier; + private final double minDist; + private final double speed; + private final boolean leadAtTier5; + + private int side; + private int recalcCooldown; + private Vec3 destination; + + public AdaptiveFlankGoal(PathfinderMob mob, IntSupplier tierSupplier, int minTier, + double minDist, double speed, boolean leadAtTier5) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.minTier = minTier; + this.minDist = minDist; + this.speed = speed; + this.leadAtTier5 = leadAtTier5; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + private double followRange() { + return mob.getAttributeValue(Attributes.FOLLOW_RANGE); + } + + @Override + public boolean canUse() { + if (tierSupplier.getAsInt() < minTier) { + return false; + } + LivingEntity target = mob.getTarget(); + if (target == null || !target.isAlive()) { + return false; + } + double distSqr = mob.distanceToSqr(target); + double follow = followRange(); + return distSqr > minDist * minDist && distSqr < follow * follow; + } + + @Override + public boolean canContinueToUse() { + LivingEntity target = mob.getTarget(); + if (target == null || !target.isAlive() || tierSupplier.getAsInt() < minTier) { + return false; + } + double distSqr = mob.distanceToSqr(target); + // Stop a bit before contact so the melee goal can take the final approach and the hit. + double inner = (minDist * 0.7); + double follow = followRange(); + return distSqr > inner * inner && distSqr < follow * follow; + } + + @Override + public void start() { + // Alternate sides per-entity so a group fans out instead of stacking. + this.side = (mob.getId() % 2 == 0) ? 1 : -1; + this.recalcCooldown = 0; + } + + @Override + public void stop() { + this.destination = null; + mob.getNavigation().stop(); + } + + @Override + public boolean requiresUpdateEveryTick() { + return false; + } + + @Override + public void tick() { + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + mob.getLookControl().setLookAt(target, 30.0F, 30.0F); + + if (recalcCooldown-- > 0) { + return; + } + recalcCooldown = 10; // ~0.5s, avoids per-tick pathfinding + + Vec3 aim = target.position(); + if (leadAtTier5 && tierSupplier.getAsInt() >= 5) { + // Intercept: aim where the target will be shortly. + aim = aim.add(target.getDeltaMovement().scale(8.0)); + } + + // Rotate the (target -> mob) vector toward one side to produce an angled approach. + Vec3 toMob = mob.position().subtract(aim); + double len = Math.sqrt(toMob.x * toMob.x + toMob.z * toMob.z); + if (len < 1.0E-3) { + return; + } + double angle = Math.toRadians(45.0 * side); + double nx = toMob.x * Math.cos(angle) - toMob.z * Math.sin(angle); + double nz = toMob.x * Math.sin(angle) + toMob.z * Math.cos(angle); + double radius = Math.max(minDist, len * 0.75); + double scale = radius / len; + + double dx = aim.x + nx * scale; + double dz = aim.z + nz * scale; + this.destination = new Vec3(dx, aim.y, dz); + mob.getNavigation().moveTo(dx, aim.y, dz, speed); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveGuardianTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveGuardianTacticsGoal.java new file mode 100644 index 0000000..942c729 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveGuardianTacticsGoal.java @@ -0,0 +1,73 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.ElderGuardian; +import net.minecraft.world.entity.monster.Guardian; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.List; +import java.util.function.IntSupplier; + +public class AdaptiveGuardianTacticsGoal extends Goal { + + private final Guardian guardian; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveGuardianTacticsGoal(Guardian guardian, IntSupplier tierSupplier) { + this.guardian = guardian; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_AQUATIC_HOSTILE_AI.get() + && AMConfig.ENABLE_GUARDIAN_ADVANCED_AI.get() + && AMConfig.AI_GUARDIAN.get() + && tierSupplier.getAsInt() >= 2 + && guardian.getTarget() != null + && guardian.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + boolean elder = guardian instanceof ElderGuardian; + cooldown = elder ? 90 + guardian.getRandom().nextInt(80) : AdaptiveAIGoalUtils.nextCooldown(guardian); + LivingEntity target = guardian.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + boolean blocked = !guardian.hasLineOfSight(target); + boolean coordinate = tier >= 4 && !elder && AdaptiveTargetingUtils.nearbyAttackers(guardian, target, 12.0D) > 1; + if (blocked || coordinate) { + Vec3 dest = AdaptivePositioningUtils.sidePosition(guardian, target, elder ? 9.0D : 7.0D, + guardian.getRandom().nextBoolean() ? 1.0D : -1.0D, tier >= 5 ? 0.10D : 0.0D); + guardian.getMoveControl().setWantedPosition(dest.x, dest.y, dest.z, elder ? 0.65D : 0.9D); + AdaptiveAIGoalUtils.debug(guardian, tierSupplier, "guardian pressure reposition"); + } + if (tier >= 5 && !elder) { + retargetLowHealthGuardianTarget(target); + } + } + + private void retargetLowHealthGuardianTarget(LivingEntity current) { + List candidates = guardian.level().getEntitiesOfClass(LivingEntity.class, + guardian.getBoundingBox().inflate(12.0D), + entity -> entity != guardian && entity.isAlive() && guardian.canAttack(entity) + && guardian.hasLineOfSight(entity) + && AdaptiveAIGoalUtils.healthFraction(entity) < AdaptiveAIGoalUtils.healthFraction(current)); + if (!candidates.isEmpty()) { + guardian.setTarget(candidates.get(0)); + AdaptiveAIGoalUtils.debug(guardian, tierSupplier, "guardian exposed target pressure"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveLowHealthRetreatGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveLowHealthRetreatGoal.java new file mode 100644 index 0000000..a160a9b --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveLowHealthRetreatGoal.java @@ -0,0 +1,56 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveLowHealthRetreatGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private final int minTier; + private final double healthThreshold; + private final double speed; + private int cooldown; + + public AdaptiveLowHealthRetreatGoal(PathfinderMob mob, IntSupplier tierSupplier, + int minTier, double healthThreshold, double speed) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.minTier = minTier; + this.healthThreshold = healthThreshold; + this.speed = speed; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.AI_RETREAT_ENABLED.get() + && tierSupplier.getAsInt() >= minTier + && AdaptiveAIGoalUtils.healthFraction(mob) <= healthThreshold + && mob.getTarget() != null + && mob.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 120 + mob.getRandom().nextInt(100); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + Vec3 dest = AdaptivePositioningUtils.retreatPosition(mob, target, 6.0D); + if (AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, speed); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "low health retreat"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveMeleePositioningGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveMeleePositioningGoal.java new file mode 100644 index 0000000..0345283 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveMeleePositioningGoal.java @@ -0,0 +1,72 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveMeleePositioningGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private final double speed; + private final boolean conservative; + private int cooldown; + + public AdaptiveMeleePositioningGoal(PathfinderMob mob, IntSupplier tierSupplier, double speed, boolean conservative) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.speed = speed; + this.conservative = conservative; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_MELEE_AI.get() + && tierSupplier.getAsInt() >= 2 + && mob.getTarget() != null + && mob.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = AdaptiveAIGoalUtils.nextCooldown(mob); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + double distance = Math.sqrt(mob.distanceToSqr(target)); + double follow = AdaptiveAIGoalUtils.followRange(mob, 16.0D); + if (distance > follow) { + return; + } + mob.getLookControl().setLookAt(target, 35.0F, 35.0F); + + int attackers = AdaptiveTargetingUtils.nearbyAttackers(mob, target, 5.0D); + boolean crowding = attackers >= (conservative ? 3 : 2); + boolean sideApproach = tier >= 3 && attackers >= 2; + boolean intercept = tier >= 5; + if (!crowding && !sideApproach && !intercept) { + return; + } + + double side = mob.getRandom().nextBoolean() ? 1.0D : -1.0D; + double lead = intercept ? AMConfig.tierValue(AMConfig.AI_INTERCEPTION_STRENGTH.get(), tier) : 0.0D; + double radius = Math.max(2.0D, Math.min(5.0D, distance * 0.6D)); + Vec3 dest = AdaptivePositioningUtils.sidePosition(mob, target, radius, side, lead); + if (AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, speed); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "melee reposition"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveMoraleGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveMoraleGoal.java new file mode 100644 index 0000000..64e1991 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveMoraleGoal.java @@ -0,0 +1,63 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveMoraleGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveMoraleGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_MORALE_AI.get() + && tierSupplier.getAsInt() >= 3 + && mob.getTarget() != null + && mob.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 70 + mob.getRandom().nextInt(80); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + int allies = AdaptiveTargetingUtils.nearbyHostiles(mob, 10.0D, + other -> other.getTarget() == target || other.getTarget() == null).size() + 1; + int players = Math.max(1, mob.level().getEntitiesOfClass(Player.class, mob.getBoundingBox().inflate(10.0D), + player -> player.isAlive() && !player.isCreative() && !player.isSpectator()).size()); + + if (allies > players + 1) { + Vec3 dest = AdaptivePositioningUtils.darkerSidePosition(mob, target, 2.5D + mob.getId() % 3, 0.0D); + if (AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.08D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "group morale pressure"); + } + } else if (allies <= 1 && AdaptiveAIGoalUtils.healthFraction(mob) < 0.35D) { + Vec3 dest = AdaptivePositioningUtils.retreatPosition(mob, target, 5.0D); + if (AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.0D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "isolated defensive morale"); + } + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRangedAttackGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRangedAttackGoal.java new file mode 100644 index 0000000..d44cd45 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRangedAttackGoal.java @@ -0,0 +1,68 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveRangedAttackGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private final double optimalRange; + private final double speed; + private int cooldown; + private int side; + + public AdaptiveRangedAttackGoal(PathfinderMob mob, IntSupplier tierSupplier, double optimalRange, double speed) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.optimalRange = optimalRange; + this.speed = speed; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_RANGED_AI.get() + && tierSupplier.getAsInt() >= 2 + && mob.getTarget() != null + && mob.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = AdaptiveAIGoalUtils.nextCooldown(mob); + side = mob.getRandom().nextBoolean() ? 1 : -1; + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + mob.getLookControl().setLookAt(target, 40.0F, 40.0F); + + boolean shield = tier >= 3 && AdaptiveAIGoalUtils.isBlockingShield(target); + boolean badSight = tier >= 3 && !mob.hasLineOfSight(target); + boolean allyInLine = tier >= 4 && AdaptiveTargetingUtils.hasAllyBetween(mob, target, 0.8D); + double distance = Math.sqrt(mob.distanceToSqr(target)); + + if (shield || badSight || allyInLine || distance < optimalRange * 0.65D || distance > optimalRange * 1.25D) { + double radius = distance < optimalRange * 0.75D ? optimalRange : Math.max(4.0D, optimalRange * 0.85D); + double lead = tier >= 5 ? AMConfig.tierValue(AMConfig.AI_INTERCEPTION_STRENGTH.get(), tier) : 0.0D; + Vec3 dest = AdaptivePositioningUtils.sidePosition(mob, target, radius, side, lead); + if (!AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + dest = AdaptivePositioningUtils.retreatPosition(mob, target, 4.0D); + } + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, speed); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "ranged reposition"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRangedCoverGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRangedCoverGoal.java new file mode 100644 index 0000000..f0115e7 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRangedCoverGoal.java @@ -0,0 +1,45 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveRangedCoverGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveRangedCoverGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 3 && mob.getTarget() != null && mob.getTarget().isAlive() && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 95 + mob.getRandom().nextInt(90); + LivingEntity target = mob.getTarget(); + if (target == null || mob.distanceToSqr(target) > 16.0D * 16.0D) { + return; + } + Vec3 retreat = AdaptivePositioningUtils.retreatPosition(mob, target, 4.0D); + Vec3 side = AdaptivePositioningUtils.darkerSidePosition(mob, target, 8.0D, 0.0D); + Vec3 dest = mob.getRandom().nextBoolean() ? retreat : side; + if (AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, 0.95D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "imperfect ranged cover"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRavagerTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRavagerTacticsGoal.java new file mode 100644 index 0000000..4d54c7c --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRavagerTacticsGoal.java @@ -0,0 +1,77 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.AbstractIllager; +import net.minecraft.world.entity.monster.Ravager; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveRavagerTacticsGoal extends Goal { + + private final Ravager ravager; + private final IntSupplier tierSupplier; + private int cooldown; + private LivingEntity rememberedTarget; + + public AdaptiveRavagerTacticsGoal(Ravager ravager, IntSupplier tierSupplier) { + this.ravager = ravager; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_RAID_MOB_AI.get() + && AMConfig.ENABLE_RAVAGER_ADVANCED_AI.get() + && AMConfig.AI_RAVAGER.get() + && tierSupplier.getAsInt() >= 3 + && currentTarget() != null + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 55 + ravager.getRandom().nextInt(65); + LivingEntity target = currentTarget(); + if (target == null) { + return; + } + rememberedTarget = target; + if (ravager.getTarget() == null) { + ravager.setTarget(target); + } + int tier = tierSupplier.getAsInt(); + double distance = Math.sqrt(ravager.distanceToSqr(target)); + boolean tooClose = distance < 3.5D; + boolean coordinated = tier >= 4 && AdaptiveTargetingUtils.nearbyHostiles(ravager, 10.0D, + other -> other instanceof AbstractIllager && other.getTarget() == target).size() > 0; + if (tooClose || coordinated || (tier >= 5 && distance < 10.0D && ravager.hasLineOfSight(target))) { + Vec3 dest = tooClose + ? AdaptivePositioningUtils.retreatPosition(ravager, target, 3.0D) + : AdaptivePositioningUtils.sidePosition(ravager, target, 5.0D, ravager.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.08D); + if (AdaptivePositioningUtils.isReasonableGround(ravager, dest)) { + ravager.getNavigation().moveTo(dest.x, dest.y, dest.z, tooClose ? 0.85D : 1.05D); + AdaptiveAIGoalUtils.debug(ravager, tierSupplier, "ravager deliberate pressure"); + } + } + } + + private LivingEntity currentTarget() { + LivingEntity target = ravager.getTarget(); + if (target != null && target.isAlive()) { + return target; + } + if (rememberedTarget != null && rememberedTarget.isAlive() && ravager.distanceToSqr(rememberedTarget) < 20.0D * 20.0D) { + return rememberedTarget; + } + rememberedTarget = null; + return null; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRetreatAndReengageGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRetreatAndReengageGoal.java new file mode 100644 index 0000000..3a54843 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveRetreatAndReengageGoal.java @@ -0,0 +1,59 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveRetreatAndReengageGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private final int minTier; + private final double triggerHealthLoss; + private final double speed; + private int cooldown; + private float lastHealth; + + public AdaptiveRetreatAndReengageGoal(PathfinderMob mob, IntSupplier tierSupplier, + int minTier, double triggerHealthLoss, double speed) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.minTier = minTier; + this.triggerHealthLoss = triggerHealthLoss; + this.speed = speed; + this.lastHealth = mob.getHealth(); + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + float current = mob.getHealth(); + float lost = lastHealth - current; + lastHealth = current; + return AMConfig.AI_RETREAT_ENABLED.get() + && tierSupplier.getAsInt() >= minTier + && lost >= mob.getMaxHealth() * triggerHealthLoss + && mob.getTarget() != null + && mob.getTarget().isAlive() + && cooldown-- <= 0; + } + + @Override + public void start() { + cooldown = 80 + mob.getRandom().nextInt(80); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + Vec3 dest = AdaptivePositioningUtils.retreatPosition(mob, target, 5.0D); + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, speed); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "retreat and re-engage"); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSharedTargetGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSharedTargetGoal.java new file mode 100644 index 0000000..19720f5 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSharedTargetGoal.java @@ -0,0 +1,53 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.goal.Goal; + +import java.util.EnumSet; +import java.util.List; +import java.util.function.IntSupplier; + +public class AdaptiveSharedTargetGoal extends Goal { + + private final Mob mob; + private final IntSupplier tierSupplier; + private final int minTier; + private final double radius; + private int cooldown; + + public AdaptiveSharedTargetGoal(Mob mob, IntSupplier tierSupplier, int minTier, double radius) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.minTier = minTier; + this.radius = radius; + setFlags(EnumSet.noneOf(Flag.class)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= minTier && mob.getTarget() != null && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = AdaptiveAIGoalUtils.nextCooldown(mob); + LivingEntity target = mob.getTarget(); + if (target == null || !target.isAlive()) { + return; + } + List allies = AdaptiveTargetingUtils.nearbyHostiles(mob, radius, other -> other.getTarget() == null); + int shared = 0; + for (Mob ally : allies) { + if (shared++ >= 4) { + break; + } + ally.setTarget(target); + } + if (shared > 0) { + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "shared target with " + shared + " allies"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveShulkerTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveShulkerTacticsGoal.java new file mode 100644 index 0000000..85e9b0a --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveShulkerTacticsGoal.java @@ -0,0 +1,66 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.Shulker; +import net.minecraft.world.level.Level; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveShulkerTacticsGoal extends Goal { + + private final Shulker shulker; + private final IntSupplier tierSupplier; + private int cooldown; + private int blockedTicks; + + public AdaptiveShulkerTacticsGoal(Shulker shulker, IntSupplier tierSupplier) { + this.shulker = shulker; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_END_MOB_AI.get() + && AMConfig.ENABLE_SHULKER_ADVANCED_AI.get() + && AMConfig.AI_SHULKER.get() + && tierSupplier.getAsInt() >= 2 + && shulker.getTarget() != null + && shulker.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + int tier = tierSupplier.getAsInt(); + boolean inEnd = shulker.level().dimension() == Level.END; + cooldown = inEnd && tier >= 5 ? 30 + shulker.getRandom().nextInt(35) + : 50 + shulker.getRandom().nextInt(tier >= 5 ? 45 : 70); + LivingEntity target = shulker.getTarget(); + if (target == null) { + return; + } + if (!shulker.hasLineOfSight(target)) { + blockedTicks++; + if (blockedTicks >= 2) { + shulker.setTarget(null); + blockedTicks = 0; + AdaptiveAIGoalUtils.debug(shulker, tierSupplier, "shulker held fire without line of sight"); + } + return; + } + blockedTicks = 0; + if (tier >= 4) { + double radius = inEnd && tier >= 5 ? 18.0D : 12.0D; + AdaptiveTargetingUtils.nearbyHostiles(shulker, radius, + other -> other instanceof Shulker && (other.getTarget() == null || other.getTarget() == target)) + .forEach(other -> other.setTarget(target)); + AdaptiveAIGoalUtils.debug(shulker, tierSupplier, "shulker coordinated target"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSkeletonShieldGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSkeletonShieldGoal.java new file mode 100644 index 0000000..9707296 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSkeletonShieldGoal.java @@ -0,0 +1,55 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveSkeletonShieldGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveSkeletonShieldGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + LivingEntity target = mob.getTarget(); + return tierSupplier.getAsInt() >= 3 + && target != null + && target.isAlive() + && target.isUsingItem() + && isShield(target.getUseItem()) + && mob.hasLineOfSight(target) + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 30 + mob.getRandom().nextInt(30); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + mob.getLookControl().setLookAt(target, 30.0F, 30.0F); + Vec3 away = mob.position().subtract(target.position()); + Vec3 side = new Vec3(-away.z, 0.0D, away.x).normalize() + .scale(mob.getRandom().nextBoolean() ? 5.0D : -5.0D); + Vec3 dest = mob.position().add(side).add(away.normalize().scale(2.0D)); + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.0D); + } + + private static boolean isShield(ItemStack stack) { + return !stack.isEmpty() && stack.is(Items.SHIELD); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSlimeTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSlimeTacticsGoal.java new file mode 100644 index 0000000..18b756c --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSlimeTacticsGoal.java @@ -0,0 +1,62 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.MagmaCube; +import net.minecraft.world.entity.monster.Slime; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveSlimeTacticsGoal extends Goal { + + private final Slime slime; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveSlimeTacticsGoal(Slime slime, IntSupplier tierSupplier) { + this.slime = slime; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.JUMP, Flag.LOOK)); + } + + @Override + public boolean canUse() { + boolean magma = slime instanceof MagmaCube; + return AMConfig.ENABLE_MELEE_AI.get() + && (magma ? AMConfig.ENABLE_MAGMA_CUBE_ADVANCED_AI.get() : AMConfig.ENABLE_SLIME_ADVANCED_AI.get()) + && AMConfig.AI_SLIME.get() + && tierSupplier.getAsInt() >= 2 + && slime.getTarget() != null + && slime.getTarget().isAlive() + && --cooldown <= 0; + } + + @Override + public void start() { + int tier = tierSupplier.getAsInt(); + cooldown = Math.max(16, 52 - tier * 5) + slime.getRandom().nextInt(25); + LivingEntity target = slime.getTarget(); + if (target == null) { + return; + } + double distance = Math.sqrt(slime.distanceToSqr(target)); + double side = slime.getId() % 2 == 0 ? 1.0D : -1.0D; + Vec3 dest = AdaptivePositioningUtils.sidePosition(slime, target, Math.max(2.0D, distance * 0.55D), side, 0.0D); + if (!AdaptivePositioningUtils.isReasonableGround(slime, dest)) { + dest = target.position(); + } + double speed = tier >= 5 && slime.getSize() >= 3 ? 1.25D : 1.0D; + slime.getLookControl().setLookAt(target, 30.0F, 30.0F); + slime.getMoveControl().setWantedPosition(dest.x, dest.y, dest.z, speed); + if (slime.onGround() && distance < 9.0D) { + Vec3 leap = target.position().subtract(slime.position()).normalize().scale(tier >= 5 && slime.getSize() >= 3 ? 0.34D : 0.24D); + slime.setDeltaMovement(slime.getDeltaMovement().add(leap.x, 0.28D, leap.z)); + } + AdaptiveAIGoalUtils.debug(slime, tierSupplier, "slime angled jump pressure"); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSoundInvestigationGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSoundInvestigationGoal.java new file mode 100644 index 0000000..056fe3d --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSoundInvestigationGoal.java @@ -0,0 +1,44 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptiveMemory; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; + +import java.util.EnumSet; +import java.util.Optional; +import java.util.function.IntSupplier; + +public class AdaptiveSoundInvestigationGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveSoundInvestigationGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 2 + && mob.getTarget() == null + && mob.level() instanceof ServerLevel + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 80 + mob.getRandom().nextInt(80); + ServerLevel level = (ServerLevel) mob.level(); + Optional sound = AdaptiveMemory.nearestSound(level, mob, 14.0D); + if (sound.isEmpty()) { + return; + } + mob.getNavigation().moveTo(sound.get().pos().x, sound.get().pos().y, sound.get().pos().z, 1.0D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "investigating " + sound.get().kind()); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSpiderDisengageGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSpiderDisengageGoal.java new file mode 100644 index 0000000..46ccc00 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSpiderDisengageGoal.java @@ -0,0 +1,66 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveSpiderDisengageGoal extends Goal { + + private static final int DISENGAGE_TICKS = 100; + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private final int minTier; + private final double triggerHealthLoss; + private final double speed; + private int cooldown; + private float lastHealth; + + public AdaptiveSpiderDisengageGoal(PathfinderMob mob, IntSupplier tierSupplier, + int minTier, double triggerHealthLoss, double speed) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.minTier = minTier; + this.triggerHealthLoss = triggerHealthLoss; + this.speed = speed; + this.lastHealth = mob.getHealth(); + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + float current = mob.getHealth(); + float lost = lastHealth - current; + lastHealth = current; + return AMConfig.AI_RETREAT_ENABLED.get() + && tierSupplier.getAsInt() >= minTier + && lost >= mob.getMaxHealth() * triggerHealthLoss + && mob.getTarget() != null + && mob.getTarget().isAlive() + && cooldown-- <= 0; + } + + @Override + public void start() { + cooldown = 110 + mob.getRandom().nextInt(90); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + mob.addEffect(new MobEffectInstance(MobEffects.INVISIBILITY, DISENGAGE_TICKS, 0)); + mob.addEffect(new MobEffectInstance(MobEffects.REGENERATION, DISENGAGE_TICKS, 4)); + + Vec3 dest = AdaptivePositioningUtils.retreatPosition(mob, target, 5.0D); + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, speed); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "spider invisible regeneration disengage"); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSpiderTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSpiderTacticsGoal.java new file mode 100644 index 0000000..146fe39 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSpiderTacticsGoal.java @@ -0,0 +1,57 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveSpiderTacticsGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private final boolean caveSpider; + private int cooldown; + + public AdaptiveSpiderTacticsGoal(PathfinderMob mob, IntSupplier tierSupplier, boolean caveSpider) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.caveSpider = caveSpider; + setFlags(EnumSet.of(Flag.MOVE, Flag.JUMP, Flag.LOOK)); + } + + @Override + public boolean canUse() { + int tier = tierSupplier.getAsInt(); + int min = caveSpider ? 2 : 3; + return tier >= min && mob.getTarget() != null && mob.getTarget().isAlive() && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = caveSpider ? 30 + mob.getRandom().nextInt(40) : AdaptiveAIGoalUtils.nextCooldown(mob); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + double distance = Math.sqrt(mob.distanceToSqr(target)); + if (tier >= 4) { + Vec3 elevated = AdaptivePositioningUtils.elevatedPosition(mob, target, 3.0D); + mob.getNavigation().moveTo(elevated.x, elevated.y, elevated.z, caveSpider ? 1.2D : 1.1D); + } else if (tier >= 2) { + Vec3 side = AdaptivePositioningUtils.sidePosition(mob, target, Math.max(2.0D, distance * 0.5D), + mob.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.0D); + mob.getNavigation().moveTo(side.x, side.y, side.z, caveSpider ? 1.2D : 1.1D); + } + if (tier >= 3 && distance < 7.0D && AdaptiveAIGoalUtils.isUsingRangedWeapon(target) && mob.onGround()) { + Vec3 leap = target.position().subtract(mob.position()).normalize().scale(caveSpider ? 0.42D : 0.36D); + mob.setDeltaMovement(mob.getDeltaMovement().add(leap.x, 0.35D, leap.z)); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "spider lunge"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSupportGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSupportGoal.java new file mode 100644 index 0000000..d9c5a77 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveSupportGoal.java @@ -0,0 +1,63 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.AbstractSkeleton; +import net.minecraft.world.entity.monster.Pillager; +import net.minecraft.world.entity.monster.Witch; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.List; +import java.util.function.IntSupplier; + +public class AdaptiveSupportGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveSupportGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 3 && mob.getTarget() != null && mob.getTarget().isAlive() && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 70 + mob.getRandom().nextInt(90); + LivingEntity target = mob.getTarget(); + if (target == null) { + return; + } + if (isMeleeSupporter(mob) && target.getLastHurtMob() instanceof Mob hurt + && (hurt instanceof AbstractSkeleton || hurt instanceof Pillager || hurt instanceof Witch) + && mob.distanceToSqr(target) < 12.0D * 12.0D) { + mob.getNavigation().moveTo(target, 1.08D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "peeling for ranged ally"); + return; + } + if ((mob instanceof AbstractSkeleton || mob instanceof Pillager || mob instanceof Witch) + && AdaptiveTargetingUtils.nearbyAttackers(mob, target, 7.0D) > 1) { + Vec3 dest = AdaptivePositioningUtils.retreatPosition(mob, target, 3.0D); + if (AdaptivePositioningUtils.isReasonableGround(mob, dest)) { + mob.getNavigation().moveTo(dest.x, dest.y, dest.z, 0.9D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "holding behind melee pressure"); + } + } + } + + private static boolean isMeleeSupporter(Mob mob) { + return !(mob instanceof AbstractSkeleton) && !(mob instanceof Pillager) && !(mob instanceof Witch); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveTargetPriorityGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveTargetPriorityGoal.java new file mode 100644 index 0000000..25c1411 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveTargetPriorityGoal.java @@ -0,0 +1,60 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.player.Player; + +import java.util.EnumSet; +import java.util.List; +import java.util.function.IntSupplier; + +public class AdaptiveTargetPriorityGoal extends Goal { + + private final Mob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveTargetPriorityGoal(Mob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.noneOf(Flag.class)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_TARGET_PRIORITY_AI.get() + && tierSupplier.getAsInt() >= 3 + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 80 + mob.getRandom().nextInt(80); + double radius = AdaptiveAIGoalUtils.followRange(mob, 16.0D); + List players = mob.level().getEntitiesOfClass(Player.class, mob.getBoundingBox().inflate(radius), + player -> player.isAlive() && !player.isCreative() && !player.isSpectator() + && mob.canAttack(player) && mob.hasLineOfSight(player)); + Player best = null; + double bestScore = currentScore(); + for (Player player : players) { + double score = AdaptiveAIGoalUtils.playerPriorityScore(mob, player); + if (score > bestScore + 1.0D) { + bestScore = score; + best = player; + } + } + if (best != null) { + mob.setTarget(best); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "priority target selected"); + } + } + + private double currentScore() { + if (mob.getTarget() instanceof Player player) { + return AdaptiveAIGoalUtils.playerPriorityScore(mob, player); + } + return 0.0D; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveThreatMemoryGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveThreatMemoryGoal.java new file mode 100644 index 0000000..a49d6a8 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveThreatMemoryGoal.java @@ -0,0 +1,46 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptiveMemory; +import net.minecraft.world.entity.PathfinderMob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.player.Player; + +import java.util.EnumSet; +import java.util.Optional; +import java.util.function.IntSupplier; + +public class AdaptiveThreatMemoryGoal extends Goal { + + private final PathfinderMob mob; + private final IntSupplier tierSupplier; + private int cooldown; + + public AdaptiveThreatMemoryGoal(PathfinderMob mob, IntSupplier tierSupplier) { + this.mob = mob; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 2 && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 40 + mob.getRandom().nextInt(50); + Optional remembered = AdaptiveMemory.rememberedThreat(mob); + if (remembered.isEmpty()) { + return; + } + Player player = remembered.get(); + if (mob.getTarget() == null || !mob.getTarget().isAlive()) { + mob.setTarget(player); + } + if (!mob.hasLineOfSight(player) && mob.distanceToSqr(player) < 18.0D * 18.0D) { + mob.getNavigation().moveTo(player, 1.0D); + AdaptiveAIGoalUtils.debug(mob, tierSupplier, "threat memory pursuit"); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveWardenTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveWardenTacticsGoal.java new file mode 100644 index 0000000..c8ca15b --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveWardenTacticsGoal.java @@ -0,0 +1,60 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.warden.Warden; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveWardenTacticsGoal extends Goal { + + private final Warden warden; + private final IntSupplier tierSupplier; + private int cooldown; + private LivingEntity rememberedTarget; + private LivingEntity lastHurtBy; + private int repeatedRangedTicks; + + public AdaptiveWardenTacticsGoal(Warden warden, IntSupplier tierSupplier) { + this.warden = warden; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.LOOK)); + } + + @Override + public boolean canUse() { + return AMConfig.ENABLE_WARDEN_AI.get() + && AMConfig.ENABLE_WARDEN_ADVANCED_AI.get() + && AMConfig.AI_WARDEN.get() + && tierSupplier.getAsInt() >= 4 + && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 80 + warden.getRandom().nextInt(80); + LivingEntity target = warden.getTarget(); + if (target != null && target.isAlive()) { + rememberedTarget = target; + warden.getLookControl().setLookAt(target, 25.0F, 25.0F); + return; + } + if (rememberedTarget != null && rememberedTarget.isAlive() && warden.distanceToSqr(rememberedTarget) < 24.0D * 24.0D) { + warden.setAttackTarget(rememberedTarget); + AdaptiveAIGoalUtils.debug(warden, tierSupplier, "warden conservative target persistence"); + } + + LivingEntity hurtBy = warden.getLastHurtByMob(); + if (tierSupplier.getAsInt() >= 5 && hurtBy != null && hurtBy.isAlive() && AdaptiveAIGoalUtils.isUsingRangedWeapon(hurtBy)) { + repeatedRangedTicks = hurtBy == lastHurtBy ? repeatedRangedTicks + 1 : 1; + lastHurtBy = hurtBy; + if (repeatedRangedTicks >= 2) { + warden.setAttackTarget(hurtBy); + AdaptiveAIGoalUtils.debug(warden, tierSupplier, "warden repeated ranged response"); + } + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveWitchTacticsGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveWitchTacticsGoal.java new file mode 100644 index 0000000..17243aa --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/AdaptiveWitchTacticsGoal.java @@ -0,0 +1,150 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.fretux.adaptivemobs.ai.AdaptiveAIGoalUtils; +import net.fretux.adaptivemobs.ai.AdaptivePositioningUtils; +import net.fretux.adaptivemobs.ai.AdaptiveTargetingUtils; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.Witch; +import net.minecraft.world.entity.projectile.ThrownPotion; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.alchemy.Potion; +import net.minecraft.world.item.alchemy.PotionUtils; +import net.minecraft.world.item.alchemy.Potions; +import net.minecraft.world.phys.Vec3; + +import java.util.EnumSet; +import java.util.function.IntSupplier; + +public class AdaptiveWitchTacticsGoal extends Goal { + + private final Witch witch; + private final IntSupplier tierSupplier; + private int cooldown; + private int potionCooldown; + + public AdaptiveWitchTacticsGoal(Witch witch, IntSupplier tierSupplier) { + this.witch = witch; + this.tierSupplier = tierSupplier; + setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= 2 && witch.getTarget() != null && witch.getTarget().isAlive() && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 45 + witch.getRandom().nextInt(55); + potionCooldown = Math.max(0, potionCooldown - cooldown); + LivingEntity target = witch.getTarget(); + if (target == null) { + return; + } + int tier = tierSupplier.getAsInt(); + double dist = Math.sqrt(witch.distanceToSqr(target)); + witch.getLookControl().setLookAt(target, 30.0F, 30.0F); + + if (dist < 8.0D || (tier >= 4 && AdaptiveTargetingUtils.nearbyAttackers(witch, target, 8.0D) > 0)) { + Vec3 dest = tier >= 4 + ? AdaptivePositioningUtils.sidePosition(witch, target, 9.0D, witch.getRandom().nextBoolean() ? 1.0D : -1.0D, 0.0D) + : AdaptivePositioningUtils.retreatPosition(witch, target, 5.0D); + witch.getNavigation().moveTo(dest.x, dest.y, dest.z, 1.0D); + AdaptiveAIGoalUtils.debug(witch, tierSupplier, "witch spacing"); + } + + if ((tier >= 3 && target.getDeltaMovement().horizontalDistanceSqr() > 0.05D) + || (tier >= 4 && dist < 7.0D) + || (tier >= 5 && AdaptiveAIGoalUtils.healthFraction(target) < 0.45D)) { + witch.performRangedAttack(target, 1.0F); + AdaptiveAIGoalUtils.debug(witch, tierSupplier, "witch extra potion opportunity"); + } + + if (AMConfig.ENABLE_WITCH_ADVANCED_POTION_AI.get() && potionCooldown <= 0 && !witch.isDrinkingPotion()) { + if (tryDrinkHealing(tier)) { + potionCooldown = 140 + witch.getRandom().nextInt(80); + AdaptiveAIGoalUtils.debug(witch, tierSupplier, "witch early heal"); + } else if (trySupportWoundedAlly(tier)) { + potionCooldown = 120 + witch.getRandom().nextInt(80); + } else if (tryThrowSpecificPotion(target, tier, dist)) { + potionCooldown = 90 + witch.getRandom().nextInt(70); + } + } + } + + private boolean tryDrinkHealing(int tier) { + double threshold = tier >= 5 ? 0.62D : tier >= 4 ? 0.52D : 0.42D; + if (AdaptiveAIGoalUtils.healthFraction(witch) > threshold) { + return false; + } + ItemStack potion = PotionUtils.setPotion(new ItemStack(Items.POTION), Potions.HEALING); + witch.setItemSlot(EquipmentSlot.MAINHAND, potion); + witch.setUsingItem(true); + return true; + } + + private boolean trySupportWoundedAlly(int tier) { + if (!AMConfig.ENABLE_SUPPORT_AI.get() || tier < 3) { + return false; + } + for (Mob ally : AdaptiveTargetingUtils.nearbyHostiles(witch, 8.0D, + other -> other != witch && AdaptiveAIGoalUtils.healthFraction(other) < 0.45D)) { + if (witch.hasLineOfSight(ally)) { + throwPotion(ally, Potions.REGENERATION); + AdaptiveAIGoalUtils.debug(witch, tierSupplier, "witch support potion"); + return true; + } + } + return false; + } + + private boolean tryThrowSpecificPotion(LivingEntity target, int tier, double dist) { + Potion potion = null; + String debug = null; + if (tier >= 5 && AdaptiveAIGoalUtils.healthFraction(target) < 0.40D) { + potion = Potions.HARMING; + debug = "witch harming pressure"; + } else if ((tier >= 4 && dist < 6.0D && isLikelyMelee(target.getMainHandItem())) + || (tier >= 3 && dist < 7.0D && isHighDamageMelee(target.getMainHandItem()))) { + potion = Potions.WEAKNESS; + debug = "witch weakness punish"; + } else if (tier >= 3 && (target.isSprinting() || target.getDeltaMovement().horizontalDistanceSqr() > 0.08D)) { + potion = Potions.SLOWNESS; + debug = "witch slowness punish"; + } + if (potion == null || !witch.hasLineOfSight(target)) { + return false; + } + throwPotion(target, potion); + AdaptiveAIGoalUtils.debug(witch, tierSupplier, debug); + return true; + } + + private void throwPotion(LivingEntity target, Potion potion) { + ThrownPotion thrown = new ThrownPotion(witch.level(), witch); + thrown.setItem(PotionUtils.setPotion(new ItemStack(Items.SPLASH_POTION), potion)); + double dx = target.getX() + target.getDeltaMovement().x - witch.getX(); + double dz = target.getZ() + target.getDeltaMovement().z - witch.getZ(); + double dist = Math.sqrt(dx * dx + dz * dz); + double dy = target.getY(0.5D) - thrown.getY() + dist * 0.2D; + thrown.shoot(dx, dy, dz, 0.75F, 8.0F); + witch.level().addFreshEntity(thrown); + } + + private static boolean isLikelyMelee(ItemStack stack) { + return stack.is(Items.WOODEN_SWORD) || stack.is(Items.STONE_SWORD) || stack.is(Items.IRON_SWORD) + || stack.is(Items.GOLDEN_SWORD) || stack.is(Items.DIAMOND_SWORD) || stack.is(Items.NETHERITE_SWORD) + || stack.is(Items.WOODEN_AXE) || stack.is(Items.STONE_AXE) || stack.is(Items.IRON_AXE) + || stack.is(Items.GOLDEN_AXE) || stack.is(Items.DIAMOND_AXE) || stack.is(Items.NETHERITE_AXE); + } + + private static boolean isHighDamageMelee(ItemStack stack) { + return stack.is(Items.DIAMOND_SWORD) || stack.is(Items.NETHERITE_SWORD) + || stack.is(Items.IRON_AXE) || stack.is(Items.DIAMOND_AXE) || stack.is(Items.NETHERITE_AXE); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/ai/goals/SharedTargetGoal.java b/src/main/java/net/fretux/adaptivemobs/ai/goals/SharedTargetGoal.java new file mode 100644 index 0000000..1f0e1b2 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/ai/goals/SharedTargetGoal.java @@ -0,0 +1,52 @@ +package net.fretux.adaptivemobs.ai.goals; + +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.monster.Enemy; +import net.minecraft.world.phys.AABB; + +import java.util.EnumSet; +import java.util.List; +import java.util.function.IntSupplier; + +public class SharedTargetGoal extends Goal { + + private final Mob mob; + private final IntSupplier tierSupplier; + private final int minTier; + private final double radius; + private int cooldown; + + public SharedTargetGoal(Mob mob, IntSupplier tierSupplier, int minTier, double radius) { + this.mob = mob; + this.tierSupplier = tierSupplier; + this.minTier = minTier; + this.radius = radius; + setFlags(EnumSet.noneOf(Flag.class)); + } + + @Override + public boolean canUse() { + return tierSupplier.getAsInt() >= minTier && mob.getTarget() != null && --cooldown <= 0; + } + + @Override + public void start() { + cooldown = 40 + mob.getRandom().nextInt(40); + LivingEntity target = mob.getTarget(); + if (target == null || !target.isAlive()) { + return; + } + AABB box = mob.getBoundingBox().inflate(radius); + List allies = mob.level().getEntitiesOfClass(Mob.class, box, + other -> other != mob && other instanceof Enemy && other.getTarget() == null); + int shared = 0; + for (Mob ally : allies) { + if (shared++ >= 4) { + break; + } + ally.setTarget(target); + } + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/commands/AdaptiveMobsCommands.java b/src/main/java/net/fretux/adaptivemobs/commands/AdaptiveMobsCommands.java new file mode 100644 index 0000000..be016bd --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/commands/AdaptiveMobsCommands.java @@ -0,0 +1,81 @@ +package net.fretux.adaptivemobs.commands; + +import com.mojang.brigadier.CommandDispatcher; +import net.fretux.adaptivemobs.config.AMConfig; +import net.fretux.adaptivemobs.data.AdaptiveSavedData; +import net.fretux.adaptivemobs.difficulty.AdaptiveDifficultyManager; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.EntityArgument; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.EntityType; +import net.minecraftforge.registries.ForgeRegistries; + +import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger; +import static com.mojang.brigadier.arguments.IntegerArgumentType.integer; + +public final class AdaptiveMobsCommands { + + private AdaptiveMobsCommands() { + } + + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(Commands.literal("adaptivemobs") + .requires(source -> source.hasPermission(2)) + .then(Commands.literal("get").executes(ctx -> get(ctx.getSource()))) + .then(Commands.literal("debug").executes(ctx -> debug(ctx.getSource()))) + .then(Commands.literal("reset").executes(ctx -> reset(ctx.getSource()))) + .then(Commands.literal("setglobaltier") + .then(Commands.argument("tier", integer(0, 5)) + .executes(ctx -> setTier(ctx.getSource(), getInteger(ctx, "tier"))))) + .then(Commands.literal("getmob") + .then(Commands.argument("target", EntityArgument.entity()) + .executes(ctx -> getMob(ctx.getSource(), EntityArgument.getEntity(ctx, "target").getType()))))); + } + + private static int get(CommandSourceStack source) { + ServerLevel level = source.getLevel(); + AdaptiveSavedData data = AdaptiveSavedData.get(level); + source.sendSuccess(() -> Component.literal("Adaptive Mobs: global tier " + + AdaptiveDifficultyManager.getGlobalTier(level) + + ", day " + AdaptiveDifficultyManager.getWorldDay(level) + + ", hostile kills " + data.getTotalHostileKills() + + ", manual override " + (data.getManualGlobalTier() >= 0 ? data.getManualGlobalTier() : "off")), false); + return 1; + } + + private static int getMob(CommandSourceStack source, EntityType type) { + AdaptiveSavedData data = AdaptiveSavedData.get(source.getLevel()); + ResourceLocation key = ForgeRegistries.ENTITY_TYPES.getKey(type); + String typeKey = key == null ? type.toString() : key.toString(); + source.sendSuccess(() -> Component.literal("Adaptive Mobs: " + typeKey + " kills " + + data.getKillsForType(typeKey)), false); + return 1; + } + + private static int setTier(CommandSourceStack source, int tier) { + AdaptiveSavedData.get(source.getLevel()).setManualGlobalTier(Math.min(tier, AMConfig.maxTier)); + source.sendSuccess(() -> Component.literal("Adaptive Mobs: manual global tier set to " + tier), true); + return 1; + } + + private static int reset(CommandSourceStack source) { + AdaptiveSavedData.get(source.getLevel()).resetProgression(); + source.sendSuccess(() -> Component.literal("Adaptive Mobs: progression reset"), true); + return 1; + } + + private static int debug(CommandSourceStack source) { + ServerLevel level = source.getLevel(); + AdaptiveSavedData data = AdaptiveSavedData.get(level); + source.sendSuccess(() -> Component.literal("Adaptive Mobs debug: enabled=" + AMConfig.enabled + + ", configMaxTier=" + AMConfig.maxTier + + ", worldDay=" + AdaptiveDifficultyManager.getWorldDay(level) + + ", totalKills=" + data.getTotalHostileKills() + + ", storedTypes=" + data.getKillsByType().size() + + ", dataVersion=" + data.getVersion()), false); + return 1; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/config/AMConfig.java b/src/main/java/net/fretux/adaptivemobs/config/AMConfig.java new file mode 100644 index 0000000..a7d4626 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/config/AMConfig.java @@ -0,0 +1,318 @@ +package net.fretux.adaptivemobs.config; + +import net.fretux.adaptivemobs.AdaptiveMobs; +import net.minecraftforge.common.ForgeConfigSpec; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.config.ModConfigEvent; +import net.minecraft.world.entity.EntityType; + +import java.util.List; + +/** + * Common (server-side gameplay) configuration for Adaptive Mobs. + * + *

All tier-indexed lists are 5 entries long and represent tiers 1..5. Tier 0 always means + * "vanilla / no change", so the accessors below return a neutral value for tier 0.

+ */ +@Mod.EventBusSubscriber(modid = AdaptiveMobs.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) +public final class AMConfig { + + private static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder(); + + // --- General ----------------------------------------------------------- + public static final ForgeConfigSpec.BooleanValue ENABLE_ADAPTIVE_MOBS = BUILDER + .comment("Master switch. When false the mod does nothing to mobs.") + .define("general.enableAdaptiveMobs", true); + + public static final ForgeConfigSpec.IntValue MAX_TIER = BUILDER + .comment("Highest adaptive tier that can ever be reached (0-5).") + .defineInRange("general.maxTier", 5, 0, 5); + + public static final ForgeConfigSpec.BooleanValue DEBUG_LOGGING = BUILDER + .comment("Verbose debug logging for progression, scaling and spawns.") + .define("general.debugLogging", false); + + // --- Per-mob toggles --------------------------------------------------- + public static final ForgeConfigSpec.BooleanValue ENABLE_ZOMBIES = BUILDER.define("mobs.zombies", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_SKELETONS = BUILDER.define("mobs.skeletons", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_CREEPERS = BUILDER.define("mobs.creepers", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_SPIDERS = BUILDER.define("mobs.spiders", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_WITCHES = BUILDER.define("mobs.witches", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_PILLAGERS = BUILDER.define("mobs.pillagers", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_OTHER_HOSTILES = BUILDER + .comment("Apply generic progression/scaling/spawn pressure to hostile mobs without a specific toggle.") + .define("mobs.otherHostiles", true); + + // --- Progression thresholds ------------------------------------------- + public static final ForgeConfigSpec.ConfigValue> DAY_THRESHOLDS = BUILDER + .comment("World day required to reach tiers 1..5 (whichever of day/kills hits first wins).") + .defineList("progression.dayThresholds", List.of(5, 15, 30, 60, 100), + o -> o instanceof Integer i && i >= 0); + + public static final ForgeConfigSpec.ConfigValue> KILL_THRESHOLDS = BUILDER + .comment("Total hostile kills required to reach tiers 1..5.") + .defineList("progression.killThresholds", List.of(25, 100, 250, 600, 1200), + o -> o instanceof Integer i && i >= 0); + + public static final ForgeConfigSpec.IntValue MOB_TYPE_KILL_BONUS_THRESHOLD = BUILDER + .comment("Per-mob-type kills that grant +1 tier to that mob type (set 0 to disable per-type scaling).") + .defineInRange("progression.perTypeKillsPerTier", 150, 0, Integer.MAX_VALUE); + + // --- Stat scaling ------------------------------------------------------ + public static final ForgeConfigSpec.BooleanValue STAT_SCALING_ENABLED = BUILDER + .comment("Enable attribute (health/damage/speed/etc.) scaling.") + .define("scaling.enabled", true); + + public static final ForgeConfigSpec.ConfigValue> HEALTH_SCALE = BUILDER + .comment("Extra max-health fraction per tier 1..5 (0.10 = +10%).") + .defineList("scaling.healthPerTier", List.of(0.10, 0.22, 0.40, 0.60, 0.95), + o -> isNumberInRange(o, 0.0, Double.MAX_VALUE)); + + public static final ForgeConfigSpec.ConfigValue> DAMAGE_SCALE = BUILDER + .comment("Extra attack-damage fraction per tier 1..5.") + .defineList("scaling.damagePerTier", List.of(0.06, 0.12, 0.24, 0.38, 0.60), + o -> isNumberInRange(o, 0.0, Double.MAX_VALUE)); + + public static final ForgeConfigSpec.ConfigValue> SPEED_SCALE = BUILDER + .comment("Extra movement-speed fraction per tier 1..5 (kept small on purpose).") + .defineList("scaling.speedPerTier", List.of(0.0, 0.0, 0.01, 0.04, 0.07), + o -> isNumberInRange(o, 0.0, Double.MAX_VALUE)); + + public static final ForgeConfigSpec.ConfigValue> FOLLOW_RANGE_SCALE = BUILDER + .comment("Extra follow-range fraction per tier 1..5.") + .defineList("scaling.followRangePerTier", List.of(0.0, 0.10, 0.10, 0.15, 0.25), + o -> isNumberInRange(o, 0.0, Double.MAX_VALUE)); + + public static final ForgeConfigSpec.ConfigValue> ARMOR_BONUS = BUILDER + .comment("Flat armor points added per tier 1..5.") + .defineList("scaling.armorPerTier", List.of(0.0, 1.0, 2.5, 4.0, 6.0), + o -> isNumberInRange(o, 0.0, Double.MAX_VALUE)); + + public static final ForgeConfigSpec.ConfigValue> KNOCKBACK_RESIST = BUILDER + .comment("Flat knockback-resistance added per tier 1..5 (0.0-1.0 scale).") + .defineList("scaling.knockbackResistPerTier", List.of(0.0, 0.0, 0.02, 0.08, 0.18), + o -> isNumberInRange(o, 0.0, Double.MAX_VALUE)); + + // --- Gear scaling ------------------------------------------------------ + public static final ForgeConfigSpec.BooleanValue GEAR_SCALING_ENABLED = BUILDER + .comment("Enable upgrading vanilla gear on eligible mobs (zombies, skeletons, etc.).") + .define("gear.enabled", true); + + public static final ForgeConfigSpec.DoubleValue GEAR_ENCHANT_CHANCE_PER_TIER = BUILDER + .comment("Base enchant chance multiplier applied per tier when gear scaling rolls (kept low).") + .defineInRange("gear.enchantChancePerTier", 0.08, 0.0, 1.0); + + // --- Spawn pressure ---------------------------------------------------- + public static final ForgeConfigSpec.BooleanValue SPAWN_PRESSURE_ENABLED = BUILDER + .comment("Enable occasional extra natural spawns of the same mob type.") + .define("spawnPressure.enabled", true); + + public static final ForgeConfigSpec.ConfigValue> EXTRA_SPAWN_CHANCE = BUILDER + .comment("Chance to spawn ONE extra mob on a natural spawn, per tier 1..5.") + .defineList("spawnPressure.extraChancePerTier", List.of(0.05, 0.10, 0.17, 0.25, 0.40), + o -> isNumberInRange(o, 0.0, 1.0)); + + public static final ForgeConfigSpec.IntValue SPAWN_DENSITY_RADIUS = BUILDER + .comment("Radius (blocks) checked for nearby mobs before adding an extra spawn.") + .defineInRange("spawnPressure.densityRadius", 12, 2, 64); + + public static final ForgeConfigSpec.IntValue SPAWN_DENSITY_CAP = BUILDER + .comment("If at least this many mobs are already within the density radius, skip the extra spawn.") + .defineInRange("spawnPressure.densityCap", 6, 1, 64); + + // --- AI ---------------------------------------------------------------- + public static final ForgeConfigSpec.BooleanValue AI_ENABLED = BUILDER + .comment("Master switch for all adaptive AI behaviour.") + .define("ai.enabled", true); + + public static final ForgeConfigSpec.BooleanValue ENABLE_ADVANCED_AI = BUILDER + .comment("Enable expanded adaptive AI goals beyond basic flanking/pressure behaviour.") + .define("ai.enableAdvancedAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_RANGED_AI = BUILDER.define("ai.enableRangedAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_MELEE_AI = BUILDER.define("ai.enableMeleeAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_CREEPER_AI = BUILDER.define("ai.enableCreeperAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_SPIDER_AI = BUILDER.define("ai.enableSpiderAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_WITCH_AI = BUILDER.define("ai.enableWitchAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_PILLAGER_AI = BUILDER.define("ai.enablePillagerAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_ENDERMAN_AI = BUILDER.define("ai.enableEndermanAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_NETHER_MOB_AI = BUILDER.define("ai.enableNetherMobAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_AQUATIC_HOSTILE_AI = BUILDER.define("ai.enableAquaticHostileAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_RAID_MOB_AI = BUILDER.define("ai.enableRaidMobAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_END_MOB_AI = BUILDER.define("ai.enableEndMobAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_WARDEN_AI = BUILDER.define("ai.enableWardenAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_ENDERMITE_AI = BUILDER.define("ai.enableEndermiteAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_EVOKER_AI = BUILDER.define("ai.enableEvokerAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_WITCH_ADVANCED_POTION_AI = BUILDER.define("ai.enableWitchAdvancedPotionAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_GUARDIAN_ADVANCED_AI = BUILDER.define("ai.enableGuardianAdvancedAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_SHULKER_ADVANCED_AI = BUILDER.define("ai.enableShulkerAdvancedAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_SLIME_ADVANCED_AI = BUILDER.define("ai.enableSlimeAdvancedAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_MAGMA_CUBE_ADVANCED_AI = BUILDER.define("ai.enableMagmaCubeAdvancedAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_RAVAGER_ADVANCED_AI = BUILDER.define("ai.enableRavagerAdvancedAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_WARDEN_ADVANCED_AI = BUILDER + .comment("Very conservative Warden behaviour tweaks only; does not change default speed, damage or sonic boom frequency.") + .define("ai.enableWardenAdvancedAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_MORALE_AI = BUILDER + .comment("Allow small group morale adjustments: bolder groups, defensive low-health isolated mobs.") + .define("ai.enableMoraleAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_TARGET_PRIORITY_AI = BUILDER + .comment("Allow mobs to occasionally retarget vulnerable or committed players.") + .define("ai.enableTargetPriorityAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_ANTI_CHEESE_AI = BUILDER + .comment("Allow small tactical responses to common cheese patterns without hard counters.") + .define("ai.enableAntiCheeseAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_DARK_APPROACH_AI = BUILDER + .comment("Prefer darker approach positions when an adaptive movement goal has comparable options.") + .define("ai.enableDarkApproachAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_THREAT_MEMORY_AI = BUILDER + .comment("Remember recent player attackers briefly to reduce trivial line-of-sight aggro resets.") + .define("ai.enableThreatMemoryAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_SOUND_INVESTIGATION_AI = BUILDER + .comment("Tier 2+ mobs can investigate nearby recent block breaking, eating, bow shots and explosions.") + .define("ai.enableSoundInvestigationAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_SUPPORT_AI = BUILDER + .comment("Allow small ally support behaviours such as peeling and ranged mobs holding behind melee pressure.") + .define("ai.enableSupportAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_ESCAPE_DENIAL_AI = BUILDER + .comment("Allow zombies and spiders to imperfectly bias toward likely player escape routes.") + .define("ai.enableEscapeDenialAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_BIOME_TACTICS_AI = BUILDER + .comment("Allow small dimension/terrain-specific tactics for Nether mobs, drowned, spiders and skeletons.") + .define("ai.enableBiomeTacticsAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_RANGED_COVER_AI = BUILDER + .comment("Allow ranged mobs to sometimes move toward imperfect cover after attacking.") + .define("ai.enableRangedCoverAI", true); + public static final ForgeConfigSpec.BooleanValue ENABLE_BOSS_AI = BUILDER + .comment("Future boss AI support. Ender Dragon and Wither are not altered unless this is enabled.") + .define("ai.enableBossAI", false); + + public static final ForgeConfigSpec.BooleanValue AI_SKELETON = BUILDER.define("ai.skeletons", true); + public static final ForgeConfigSpec.BooleanValue AI_ZOMBIE = BUILDER.define("ai.zombies", true); + public static final ForgeConfigSpec.BooleanValue AI_CREEPER = BUILDER.define("ai.creepers", true); + public static final ForgeConfigSpec.BooleanValue AI_SPIDER = BUILDER.define("ai.spiders", true); + public static final ForgeConfigSpec.BooleanValue AI_WITCH = BUILDER.define("ai.witches", true); + public static final ForgeConfigSpec.BooleanValue AI_PILLAGER = BUILDER.define("ai.pillagers", true); + public static final ForgeConfigSpec.BooleanValue AI_ENDERMAN = BUILDER.define("ai.endermen", true); + public static final ForgeConfigSpec.BooleanValue AI_SLIME = BUILDER.define("ai.slimes", true); + public static final ForgeConfigSpec.BooleanValue AI_GHAST = BUILDER.define("ai.ghasts", true); + public static final ForgeConfigSpec.BooleanValue AI_BLAZE = BUILDER.define("ai.blazes", true); + public static final ForgeConfigSpec.BooleanValue AI_GUARDIAN = BUILDER.define("ai.guardians", true); + public static final ForgeConfigSpec.BooleanValue AI_PHANTOM = BUILDER.define("ai.phantoms", true); + public static final ForgeConfigSpec.BooleanValue AI_RAVAGER = BUILDER.define("ai.ravagers", true); + public static final ForgeConfigSpec.BooleanValue AI_EVOKER = BUILDER.define("ai.evokers", true); + public static final ForgeConfigSpec.BooleanValue AI_VEX = BUILDER.define("ai.vexes", true); + public static final ForgeConfigSpec.BooleanValue AI_PIGLIN_FAMILY = BUILDER.define("ai.piglinFamily", true); + public static final ForgeConfigSpec.BooleanValue AI_SMALL_SWARM = BUILDER.define("ai.silverfishAndEndermites", true); + public static final ForgeConfigSpec.BooleanValue AI_SHULKER = BUILDER.define("ai.shulkers", true); + public static final ForgeConfigSpec.BooleanValue AI_WARDEN = BUILDER.define("ai.warden", true); + + public static final ForgeConfigSpec.IntValue AI_SCAN_COOLDOWN_MIN = BUILDER + .comment("Minimum cooldown in ticks for adaptive AI scans.") + .defineInRange("ai.scanCooldownMin", 20, 5, 200); + public static final ForgeConfigSpec.IntValue AI_SCAN_COOLDOWN_MAX = BUILDER + .comment("Maximum cooldown in ticks for adaptive AI scans.") + .defineInRange("ai.scanCooldownMax", 60, 10, 400); + public static final ForgeConfigSpec.IntValue AI_MAX_NEARBY_MOBS_SCANNED = BUILDER + .comment("Maximum nearby mobs considered by each adaptive AI scan.") + .defineInRange("ai.maxNearbyMobsScanned", 8, 1, 32); + public static final ForgeConfigSpec.ConfigValue> AI_ACCURACY_BONUS = BUILDER + .comment("Projectile aim correction strength per tier 1..5. Small values preserve dodge counterplay.") + .defineList("ai.accuracyBonusPerTier", List.of(0.0, 0.04, 0.08, 0.12, 0.16), + o -> isNumberInRange(o, 0.0, 0.5)); + public static final ForgeConfigSpec.ConfigValue> AI_HEADSHOT_CHANCE = BUILDER + .comment("Chance per tier 1..5 for skeleton-like archers to bias aim upward.") + .defineList("ai.headshotChancePerTier", List.of(0.0, 0.0, 0.05, 0.18, 0.25), + o -> isNumberInRange(o, 0.0, 1.0)); + public static final ForgeConfigSpec.ConfigValue> AI_INTERCEPTION_STRENGTH = BUILDER + .comment("Movement prediction strength per tier 1..5.") + .defineList("ai.interceptionStrengthPerTier", List.of(0.0, 0.0, 0.06, 0.14, 0.24), + o -> isNumberInRange(o, 0.0, 1.0)); + public static final ForgeConfigSpec.BooleanValue AI_RETREAT_ENABLED = BUILDER + .comment("Allow brief retreat/re-engage behaviour for mobs that support it.") + .define("ai.retreatBehaviorEnabled", true); + public static final ForgeConfigSpec.BooleanValue DEBUG_AI_LOGGING = BUILDER + .comment("Verbose debug logging for adaptive AI injection and special behaviour.") + .define("ai.debugAILogging", false); + + public static final ForgeConfigSpec.BooleanValue ALLOW_ZOMBIE_BLOCK_BREAK = BUILDER + .comment("If true, allow extra block-breaking behaviour for zombies (off by default; vanilla door behaviour is unaffected).") + .define("ai.allowZombieBlockBreak", false); + + public static final ForgeConfigSpec SPEC = BUILDER.build(); + + // --- Cached values ----------------------------------------------------- + public static volatile boolean enabled = true; + public static volatile int maxTier = 5; + public static volatile boolean debug = false; + + private AMConfig() { + } + + @SubscribeEvent + static void onLoad(final ModConfigEvent event) { + if (event.getConfig().getSpec() != SPEC) { + return; + } + enabled = ENABLE_ADAPTIVE_MOBS.get(); + maxTier = MAX_TIER.get(); + debug = DEBUG_LOGGING.get(); + } + + /** Reads tier-indexed list (tiers 1..5) returning neutral 0 for tier 0 or out-of-range. */ + public static double tierValue(List list, int tier) { + if (tier <= 0 || list == null || list.isEmpty()) { + return 0.0; + } + int idx = Math.min(tier, list.size()) - 1; + return list.get(idx).doubleValue(); + } + + public static int tierValueInt(List list, int tier1based) { + if (list == null || list.isEmpty()) { + return Integer.MAX_VALUE; + } + int idx = Math.min(tier1based, list.size()) - 1; + idx = Math.max(0, idx); + return list.get(idx); + } + + public static int aiScanCooldown(net.minecraft.util.RandomSource random) { + int min = AI_SCAN_COOLDOWN_MIN.get(); + int max = Math.max(min, AI_SCAN_COOLDOWN_MAX.get()); + return min + random.nextInt(max - min + 1); + } + + public static boolean isMobEnabled(EntityType type) { + if (type == EntityType.ENDER_DRAGON || type == EntityType.WITHER) { + return ENABLE_BOSS_AI.get(); + } + if (type == EntityType.ZOMBIE || type == EntityType.HUSK || type == EntityType.DROWNED + || type == EntityType.ZOMBIE_VILLAGER || type == EntityType.ZOMBIFIED_PIGLIN) { + return ENABLE_ZOMBIES.get(); + } + if (type == EntityType.SKELETON || type == EntityType.STRAY || type == EntityType.WITHER_SKELETON) { + return ENABLE_SKELETONS.get(); + } + if (type == EntityType.CREEPER) { + return ENABLE_CREEPERS.get(); + } + if (type == EntityType.SPIDER || type == EntityType.CAVE_SPIDER) { + return ENABLE_SPIDERS.get(); + } + if (type == EntityType.WITCH) { + return ENABLE_WITCHES.get(); + } + if (type == EntityType.PILLAGER) { + return ENABLE_PILLAGERS.get(); + } + return ENABLE_OTHER_HOSTILES.get(); + } + + private static boolean isNumberInRange(Object value, double min, double max) { + if (!(value instanceof Number number)) { + return false; + } + double asDouble = number.doubleValue(); + return Double.isFinite(asDouble) && asDouble >= min && asDouble <= max; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/data/AdaptiveSavedData.java b/src/main/java/net/fretux/adaptivemobs/data/AdaptiveSavedData.java new file mode 100644 index 0000000..4d41a4f --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/data/AdaptiveSavedData.java @@ -0,0 +1,103 @@ +package net.fretux.adaptivemobs.data; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.saveddata.SavedData; + +import java.util.HashMap; +import java.util.Map; + +/** + * World-scoped progression state. Stored on the overworld's data storage so it acts as a single + * global value for the whole server, regardless of which dimension a kill happened in. + */ +public class AdaptiveSavedData extends SavedData { + + public static final String DATA_NAME = "adaptivemobs_progression"; + private static final int CURRENT_VERSION = 1; + + private long totalHostileKills; + private final Map killsByType = new HashMap<>(); + private int manualGlobalTier = -1; // -1 = no manual override + private int version = CURRENT_VERSION; + + public AdaptiveSavedData() { + } + + /** Resolves the single global instance, always backed by the overworld's storage. */ + public static AdaptiveSavedData get(ServerLevel level) { + ServerLevel overworld = level.getServer().overworld(); + return overworld.getDataStorage().computeIfAbsent(AdaptiveSavedData::load, AdaptiveSavedData::new, DATA_NAME); + } + + public static AdaptiveSavedData load(CompoundTag tag) { + AdaptiveSavedData data = new AdaptiveSavedData(); + data.totalHostileKills = tag.getLong("totalHostileKills"); + data.manualGlobalTier = tag.contains("manualGlobalTier") ? tag.getInt("manualGlobalTier") : -1; + data.version = tag.contains("version") ? tag.getInt("version") : CURRENT_VERSION; + CompoundTag byType = tag.getCompound("killsByType"); + for (String key : byType.getAllKeys()) { + data.killsByType.put(key, byType.getInt(key)); + } + return data; + } + + @Override + public CompoundTag save(CompoundTag tag) { + tag.putLong("totalHostileKills", totalHostileKills); + tag.putInt("manualGlobalTier", manualGlobalTier); + tag.putInt("version", version); + CompoundTag byType = new CompoundTag(); + killsByType.forEach(byType::putInt); + tag.put("killsByType", byType); + return tag; + } + + // --- Accessors --------------------------------------------------------- + + public long getTotalHostileKills() { + return totalHostileKills; + } + + public int getKillsForType(String typeKey) { + return killsByType.getOrDefault(typeKey, 0); + } + + public Map getKillsByType() { + return killsByType; + } + + public int getManualGlobalTier() { + return manualGlobalTier; + } + + public int getVersion() { + return version; + } + + // --- Mutators (mark dirty) -------------------------------------------- + + public void addKill(String typeKey) { + totalHostileKills++; + killsByType.merge(typeKey, 1, Integer::sum); + setDirty(); + } + + public void setManualGlobalTier(int tier) { + this.manualGlobalTier = tier; + setDirty(); + } + + public void clearManualGlobalTier() { + this.manualGlobalTier = -1; + setDirty(); + } + + public void resetProgression() { + totalHostileKills = 0; + killsByType.clear(); + manualGlobalTier = -1; + version = CURRENT_VERSION; + setDirty(); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/difficulty/AdaptiveDifficultyManager.java b/src/main/java/net/fretux/adaptivemobs/difficulty/AdaptiveDifficultyManager.java new file mode 100644 index 0000000..8550eb7 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/difficulty/AdaptiveDifficultyManager.java @@ -0,0 +1,110 @@ +package net.fretux.adaptivemobs.difficulty; + +import net.fretux.adaptivemobs.AdaptiveMobs; +import net.fretux.adaptivemobs.config.AMConfig; +import net.fretux.adaptivemobs.data.AdaptiveSavedData; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.monster.Enemy; +import net.minecraftforge.registries.ForgeRegistries; + +/** + * Central authority for "how hard should mobs be right now". + * + *

The global tier is the dominant signal (world day + total hostile kills). A per-mob-type + * bonus can nudge specific mob families up once players have killed a lot of them.

+ */ +public final class AdaptiveDifficultyManager { + + private AdaptiveDifficultyManager() { + } + + /** Current world day, derived from the overworld day-time. */ + public static long getWorldDay(ServerLevel level) { + return level.getServer().overworld().getDayTime() / 24000L; + } + + /** Global progression tier in the range [0, maxTier]. */ + public static int getGlobalTier(ServerLevel level) { + if (!AMConfig.enabled) { + return 0; + } + AdaptiveSavedData data = AdaptiveSavedData.get(level); + int max = AMConfig.maxTier; + + if (data.getManualGlobalTier() >= 0) { + return clamp(data.getManualGlobalTier(), max); + } + + int dayTier = tierFromDay(getWorldDay(level)); + int killTier = tierFromKills(data.getTotalHostileKills()); + return clamp(Math.max(dayTier, killTier), max); + } + + /** Effective tier for a specific mob type (global tier plus an optional per-type bonus). */ + public static int getMobTier(ServerLevel level, EntityType type) { + if (!AMConfig.enabled) { + return 0; + } + int global = getGlobalTier(level); + int perTypeThreshold = AMConfig.MOB_TYPE_KILL_BONUS_THRESHOLD.get(); + if (perTypeThreshold <= 0) { + return global; + } + ResourceLocation key = ForgeRegistries.ENTITY_TYPES.getKey(type); + if (key == null) { + return global; + } + int typeKills = AdaptiveSavedData.get(level).getKillsForType(key.toString()); + int bonus = typeKills / perTypeThreshold; + return clamp(global + bonus, AMConfig.maxTier); + } + + /** Records a player kill if the victim is a hostile mob. */ + public static void recordKill(ServerPlayer player, LivingEntity killed) { + if (!AMConfig.enabled || player == null || killed == null) { + return; + } + if (!(killed instanceof Enemy)) { + return; // only count hostile mobs + } + ServerLevel level = player.serverLevel(); + ResourceLocation key = ForgeRegistries.ENTITY_TYPES.getKey(killed.getType()); + if (key == null) { + return; + } + AdaptiveSavedData data = AdaptiveSavedData.get(level); + data.addKill(key.toString()); + if (AMConfig.debug) { + AdaptiveMobs.LOGGER.info("[AdaptiveMobs] Recorded kill of {} (total={}, type={}, globalTier={})", + key, data.getTotalHostileKills(), data.getKillsForType(key.toString()), getGlobalTier(level)); + } + } + + private static int tierFromDay(long day) { + int tier = 0; + for (int t = 1; t <= 5; t++) { + if (day >= AMConfig.tierValueInt(AMConfig.DAY_THRESHOLDS.get(), t)) { + tier = t; + } + } + return tier; + } + + private static int tierFromKills(long kills) { + int tier = 0; + for (int t = 1; t <= 5; t++) { + if (kills >= AMConfig.tierValueInt(AMConfig.KILL_THRESHOLDS.get(), t)) { + tier = t; + } + } + return tier; + } + + private static int clamp(int tier, int max) { + return Math.max(0, Math.min(tier, max)); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/event/AdaptiveMobsEvents.java b/src/main/java/net/fretux/adaptivemobs/event/AdaptiveMobsEvents.java new file mode 100644 index 0000000..63709c2 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/event/AdaptiveMobsEvents.java @@ -0,0 +1,129 @@ +package net.fretux.adaptivemobs.event; + +import net.fretux.adaptivemobs.ai.AdaptiveGoalInjector; +import net.fretux.adaptivemobs.ai.AdaptiveMemory; +import net.fretux.adaptivemobs.ai.AdaptiveMobHooks; +import net.fretux.adaptivemobs.ai.AdaptiveSpecialAbilities; +import net.fretux.adaptivemobs.commands.AdaptiveMobsCommands; +import net.fretux.adaptivemobs.config.AMConfig; +import net.fretux.adaptivemobs.difficulty.AdaptiveDifficultyManager; +import net.fretux.adaptivemobs.gear.GearScaler; +import net.fretux.adaptivemobs.scaling.MobStatScaler; +import net.fretux.adaptivemobs.spawn.SpawnPressureHelper; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.monster.Enemy; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraftforge.event.RegisterCommandsEvent; +import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent; +import net.minecraftforge.event.entity.EntityJoinLevelEvent; +import net.minecraftforge.event.entity.living.LivingDeathEvent; +import net.minecraftforge.event.entity.living.LivingHurtEvent; +import net.minecraftforge.event.entity.living.MobSpawnEvent; +import net.minecraftforge.event.level.BlockEvent; +import net.minecraftforge.event.level.ExplosionEvent; +import net.minecraftforge.event.level.LevelEvent; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; + +public class AdaptiveMobsEvents { + + @SubscribeEvent + public void onCommands(RegisterCommandsEvent event) { + AdaptiveMobsCommands.register(event.getDispatcher()); + } + + @SubscribeEvent + public void onLivingDeath(LivingDeathEvent event) { + LivingEntity killed = event.getEntity(); + if (!(event.getSource().getEntity() instanceof ServerPlayer player)) { + return; + } + AdaptiveDifficultyManager.recordKill(player, killed); + } + + @SubscribeEvent + public void onLivingHurt(LivingHurtEvent event) { + AdaptiveSpecialAbilities.onLivingHurt(event); + if (!AMConfig.enabled || !AMConfig.ENABLE_THREAT_MEMORY_AI.get()) { + return; + } + if (event.getEntity() instanceof Mob mob && mob instanceof Enemy + && event.getSource().getEntity() instanceof ServerPlayer player) { + AdaptiveMemory.rememberThreat(mob, player, 20 * 12); + } + } + + @SubscribeEvent + public void onBlockBreak(BlockEvent.BreakEvent event) { + if (AMConfig.enabled && AMConfig.ENABLE_SOUND_INVESTIGATION_AI.get() + && event.getLevel() instanceof ServerLevel level) { + AdaptiveMemory.rememberSound(level, event.getPos(), AdaptiveMemory.SoundKind.BLOCK_BREAK, 20 * 8); + } + } + + @SubscribeEvent + public void onItemUseFinish(LivingEntityUseItemEvent.Finish event) { + if (AMConfig.enabled && AMConfig.ENABLE_SOUND_INVESTIGATION_AI.get() + && event.getEntity() instanceof ServerPlayer player && event.getItem().isEdible()) { + AdaptiveMemory.rememberSound(player.serverLevel(), player.blockPosition(), AdaptiveMemory.SoundKind.EATING, 20 * 6); + } + } + + @SubscribeEvent + public void onFinalizeSpawn(MobSpawnEvent.FinalizeSpawn event) { + if (!AMConfig.enabled || !(event.getLevel() instanceof ServerLevel level)) { + return; + } + Mob mob = event.getEntity(); + if (!(mob instanceof Enemy) || !AMConfig.isMobEnabled(mob.getType())) { + return; + } + + int tier = AdaptiveDifficultyManager.getMobTier(level, mob.getType()); + MobStatScaler.applyScaling(mob, tier); + GearScaler.applyGear(mob, tier); + AdaptiveGoalInjector.inject(mob, level, tier); + SpawnPressureHelper.maybeSpawnExtra(level, mob, tier, event.getSpawnType()); + } + + @SubscribeEvent + public void onEntityJoinLevel(EntityJoinLevelEvent event) { + AdaptiveMobHooks.onProjectileJoin(event); + AdaptiveSpecialAbilities.onProjectileJoin(event); + if (!(event.getLevel() instanceof ServerLevel level)) { + return; + } + Entity entity = event.getEntity(); + if (AMConfig.enabled && entity instanceof Mob mob && mob instanceof Enemy && AMConfig.isMobEnabled(mob.getType())) { + AdaptiveGoalInjector.inject(mob, level, AdaptiveDifficultyManager.getMobTier(level, mob.getType())); + } + if (AMConfig.enabled && AMConfig.ENABLE_SOUND_INVESTIGATION_AI.get() + && entity instanceof Projectile projectile && projectile.getOwner() instanceof ServerPlayer player) { + AdaptiveMemory.rememberSound(level, player.blockPosition(), AdaptiveMemory.SoundKind.BOW_SHOT, 20 * 6); + } + } + + @SubscribeEvent + public void onLevelUnload(LevelEvent.Unload event) { + if (event.getLevel() instanceof ServerLevel level) { + AdaptiveMemory.clear(level); + } + } + + @SubscribeEvent + public void onExplosion(ExplosionEvent.Detonate event) { + if (AMConfig.enabled && AMConfig.ENABLE_SOUND_INVESTIGATION_AI.get() + && event.getLevel() instanceof ServerLevel level) { + AdaptiveMemory.rememberSound(level, event.getExplosion().getPosition(), AdaptiveMemory.SoundKind.EXPLOSION, 20 * 10); + } + } + + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent event) { + AdaptiveSpecialAbilities.onServerTick(event); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/gear/GearScaler.java b/src/main/java/net/fretux/adaptivemobs/gear/GearScaler.java new file mode 100644 index 0000000..7146927 --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/gear/GearScaler.java @@ -0,0 +1,178 @@ +package net.fretux.adaptivemobs.gear; + +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.monster.AbstractSkeleton; +import net.minecraft.world.entity.monster.Pillager; +import net.minecraft.world.entity.monster.Zombie; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.Enchantments; + +/** + * Upgrades a mob's vanilla equipment based on its tier. Only vanilla items are used, armor is + * partial more often than full, existing/better gear is respected (never downgraded), and added + * gear is given a 0% drop chance so it stays a challenge rather than a farm. + */ +public final class GearScaler { + + // Material ranks (low -> high) used both to pick new gear and to compare against existing gear. + private static final Item[] HELMETS = {Items.LEATHER_HELMET, Items.GOLDEN_HELMET, Items.CHAINMAIL_HELMET, Items.IRON_HELMET, Items.DIAMOND_HELMET}; + private static final Item[] CHESTS = {Items.LEATHER_CHESTPLATE, Items.GOLDEN_CHESTPLATE, Items.CHAINMAIL_CHESTPLATE, Items.IRON_CHESTPLATE, Items.DIAMOND_CHESTPLATE}; + private static final Item[] LEGS = {Items.LEATHER_LEGGINGS, Items.GOLDEN_LEGGINGS, Items.CHAINMAIL_LEGGINGS, Items.IRON_LEGGINGS, Items.DIAMOND_LEGGINGS}; + private static final Item[] BOOTS = {Items.LEATHER_BOOTS, Items.GOLDEN_BOOTS, Items.CHAINMAIL_BOOTS, Items.IRON_BOOTS, Items.DIAMOND_BOOTS}; + private static final Item[] SWORDS = {Items.WOODEN_SWORD, Items.GOLDEN_SWORD, Items.STONE_SWORD, Items.IRON_SWORD, Items.DIAMOND_SWORD}; + + private GearScaler() { + } + + public static void applyGear(Mob mob, int tier) { + if (!AMConfig.GEAR_SCALING_ENABLED.get() || tier <= 0) { + return; + } + RandomSource random = mob.getRandom(); + + if (mob instanceof AbstractSkeleton skeleton) { + applyArmor(skeleton, tier, random); + upgradeBow(skeleton, tier, random); + if (!skeleton.getMainHandItem().is(Items.BOW)) { + upgradeMeleeWeapon(skeleton, tier, random); + } + } else if (mob instanceof Zombie zombie) { + // Covers zombies, husks, drowned and zombified piglins (all extend Zombie). + applyArmor(zombie, tier, random); + upgradeMeleeWeapon(zombie, tier, random); + } else if (mob instanceof Pillager pillager) { + upgradeCrossbow(pillager, tier, random); + } + // TODO: Piglin gear is intentionally left alone to avoid disturbing bartering behaviour. + } + + // --- Armor ------------------------------------------------------------- + + private static void applyArmor(Mob mob, int tier, RandomSource random) { + // Partial armor more often than full: each slot rolled independently. + double perSlotChance = tier >= 5 ? 0.78D : 0.16D + 0.11D * tier; // tier1 ~0.27 .. tier4 ~0.60 + tryArmorSlot(mob, EquipmentSlot.HEAD, HELMETS, tier, perSlotChance, random); + tryArmorSlot(mob, EquipmentSlot.CHEST, CHESTS, tier, perSlotChance, random); + tryArmorSlot(mob, EquipmentSlot.LEGS, LEGS, tier, perSlotChance, random); + tryArmorSlot(mob, EquipmentSlot.FEET, BOOTS, tier, perSlotChance, random); + } + + private static void tryArmorSlot(Mob mob, EquipmentSlot slot, Item[] ladder, int tier, + double chance, RandomSource random) { + if (random.nextDouble() > chance) { + return; + } + int newLevel = rollMaterialLevel(tier, random); + int existingLevel = materialLevel(mob.getItemBySlot(slot).getItem(), ladder); + if (existingLevel >= newLevel) { + return; // respect existing/better gear + } + ItemStack stack = new ItemStack(ladder[newLevel]); + maybeEnchant(stack, Enchantments.ALL_DAMAGE_PROTECTION, tier, random); + equip(mob, slot, stack); + } + + // --- Weapons ----------------------------------------------------------- + + private static void upgradeMeleeWeapon(Mob mob, int tier, RandomSource random) { + ItemStack current = mob.getMainHandItem(); + int existingLevel = materialLevel(current.getItem(), SWORDS); + if (!current.isEmpty() && existingLevel < 0) { + return; // holding something we don't recognise (e.g. a trident) — leave it alone + } + // Zombies trend towards iron at high tiers; bias the ladder a little lower than armor. + int newLevel = Math.max(0, rollMaterialLevel(tier, random) - (tier >= 4 ? 0 : 1)); + if (existingLevel >= newLevel && !current.isEmpty()) { + return; + } + ItemStack sword = new ItemStack(SWORDS[newLevel]); + maybeEnchant(sword, Enchantments.SHARPNESS, tier, random); + if (tier >= 5 && random.nextDouble() < 0.18D) { + sword.enchant(Enchantments.FIRE_ASPECT, 1); + } + equip(mob, EquipmentSlot.MAINHAND, sword); + } + + private static void upgradeBow(AbstractSkeleton skeleton, int tier, RandomSource random) { + ItemStack bow = skeleton.getMainHandItem(); + if (!bow.is(Items.BOW)) { + return; // wither skeletons hold swords etc. — handled by melee logic if desired + } + // Don't replace the bow item (no custom items); just occasionally enchant it at higher tiers. + if (tier >= 3) { + maybeEnchant(bow, Enchantments.POWER_ARROWS, tier, random); + } + if (tier >= 5 && random.nextDouble() < 0.35D) { + bow.enchant(Enchantments.PUNCH_ARROWS, 1); + } + if (tier >= 5 && random.nextDouble() < 0.22D) { + bow.enchant(Enchantments.FLAMING_ARROWS, 1); + } + } + + private static void upgradeCrossbow(Pillager pillager, int tier, RandomSource random) { + ItemStack crossbow = pillager.getMainHandItem(); + if (!crossbow.is(Items.CROSSBOW)) { + return; + } + if (tier >= 3) { + maybeEnchant(crossbow, Enchantments.QUICK_CHARGE, tier, random); + } + if (tier >= 5 && random.nextDouble() < 0.30D) { + crossbow.enchant(Enchantments.MULTISHOT, 1); + } else if (tier >= 5 && random.nextDouble() < 0.35D) { + crossbow.enchant(Enchantments.PIERCING, 2); + } + } + + // --- Helpers ----------------------------------------------------------- + + /** Picks a material rank (0=leather/wood .. 4=diamond) appropriate for the tier. */ + private static int rollMaterialLevel(int tier, RandomSource random) { + double r = random.nextDouble(); + return switch (tier) { + case 1 -> r < 0.70 ? 0 : 1; // leather / gold + case 2 -> r < 0.40 ? 0 : (r < 0.80 ? 2 : 1); // leather / chain / gold + case 3 -> r < 0.30 ? 0 : (r < 0.65 ? 2 : 3); // leather / chain / iron + case 4 -> r < 0.12 ? 4 : (r < 0.72 ? 3 : 2); // diamond(rare) / iron / chain + case 5 -> r < 0.35 ? 4 : (r < 0.88 ? 3 : 2); // diamond / iron / chain + default -> 0; + }; + } + + /** Returns the rank of an item within a ladder, or -1 if it isn't in the ladder. */ + private static int materialLevel(Item item, Item[] ladder) { + for (int i = 0; i < ladder.length; i++) { + if (ladder[i] == item) { + return i; + } + } + return -1; + } + + private static void maybeEnchant(ItemStack stack, Enchantment enchantment, int tier, RandomSource random) { + double chance = AMConfig.GEAR_ENCHANT_CHANCE_PER_TIER.get() * tier; + if (random.nextDouble() < chance) { + int level = enchantment == Enchantments.QUICK_CHARGE && tier >= 5 + ? 2 + random.nextInt(2) + : (tier >= 5 && random.nextBoolean() ? 2 : 1); + int existing = EnchantmentHelper.getItemEnchantmentLevel(enchantment, stack); + if (existing >= level) { + return; + } + stack.enchant(enchantment, level); + } + } + + private static void equip(Mob mob, EquipmentSlot slot, ItemStack stack) { + mob.setItemSlot(slot, stack); + mob.setDropChance(slot, 0.0F); // added gear shouldn't be farmable + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/scaling/AdaptiveMobData.java b/src/main/java/net/fretux/adaptivemobs/scaling/AdaptiveMobData.java new file mode 100644 index 0000000..50bfa1f --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/scaling/AdaptiveMobData.java @@ -0,0 +1,45 @@ +package net.fretux.adaptivemobs.scaling; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.entity.Entity; + +/** + * Helper for the small chunk of persistent NBT we keep on each adapted mob (via Forge's + * {@link Entity#getPersistentData()}). Storing the applied tier lets us avoid re-applying + * attribute scaling every time the entity is loaded from disk. + */ +public final class AdaptiveMobData { + + private static final String ROOT = "AdaptiveMobs"; + private static final String KEY_SCALED = "scaled"; + private static final String KEY_TIER = "tier"; + + private AdaptiveMobData() { + } + + private static CompoundTag root(Entity entity) { + CompoundTag data = entity.getPersistentData(); + if (!data.contains(ROOT)) { + data.put(ROOT, new CompoundTag()); + } + return data.getCompound(ROOT); + } + + public static boolean isScaled(Entity entity) { + return entity.getPersistentData().getCompound(ROOT).getBoolean(KEY_SCALED); + } + + public static void markScaled(Entity entity, int tier) { + CompoundTag root = root(entity); + root.putBoolean(KEY_SCALED, true); + root.putInt(KEY_TIER, tier); + // re-attach in case the sub-tag was freshly created + entity.getPersistentData().put(ROOT, root); + } + + /** Returns the tier stored on the mob, or -1 if it was never scaled. */ + public static int getTier(Entity entity) { + CompoundTag root = entity.getPersistentData().getCompound(ROOT); + return root.contains(KEY_TIER) ? root.getInt(KEY_TIER) : -1; + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/scaling/MobStatScaler.java b/src/main/java/net/fretux/adaptivemobs/scaling/MobStatScaler.java new file mode 100644 index 0000000..2a4e09c --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/scaling/MobStatScaler.java @@ -0,0 +1,84 @@ +package net.fretux.adaptivemobs.scaling; + +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.attributes.Attribute; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.AttributeModifier; +import net.minecraft.world.entity.ai.attributes.Attributes; + +import java.util.UUID; + +/** + * Applies moderate, attribute-based stat scaling to a mob for a given tier. Scaling is applied + * exactly once per mob instance and recorded in {@link AdaptiveMobData} so reloads don't stack it. + */ +public final class MobStatScaler { + + // Stable UUIDs so a given modifier is only ever added once per attribute instance. + private static final UUID HEALTH_UUID = UUID.fromString("9f1d0a5e-1f2a-4c3b-8a11-000000000001"); + private static final UUID DAMAGE_UUID = UUID.fromString("9f1d0a5e-1f2a-4c3b-8a11-000000000002"); + private static final UUID SPEED_UUID = UUID.fromString("9f1d0a5e-1f2a-4c3b-8a11-000000000003"); + private static final UUID FOLLOW_UUID = UUID.fromString("9f1d0a5e-1f2a-4c3b-8a11-000000000004"); + private static final UUID ARMOR_UUID = UUID.fromString("9f1d0a5e-1f2a-4c3b-8a11-000000000005"); + private static final UUID KNOCKBACK_UUID = UUID.fromString("9f1d0a5e-1f2a-4c3b-8a11-000000000006"); + + private MobStatScaler() { + } + + /** + * Applies tier scaling to the mob and heals it to its new maximum. No-op if scaling is + * disabled, the tier is 0, or the mob has already been scaled. + */ + public static void applyScaling(Mob mob, int tier) { + if (!AMConfig.STAT_SCALING_ENABLED.get() || tier <= 0) { + AdaptiveMobData.markScaled(mob, Math.max(tier, 0)); + return; + } + if (AdaptiveMobData.isScaled(mob)) { + return; + } + + addMultiplier(mob, Attributes.MAX_HEALTH, HEALTH_UUID, "am_health", + AMConfig.tierValue(AMConfig.HEALTH_SCALE.get(), tier)); + addMultiplier(mob, Attributes.ATTACK_DAMAGE, DAMAGE_UUID, "am_damage", + AMConfig.tierValue(AMConfig.DAMAGE_SCALE.get(), tier)); + addMultiplier(mob, Attributes.MOVEMENT_SPEED, SPEED_UUID, "am_speed", + AMConfig.tierValue(AMConfig.SPEED_SCALE.get(), tier)); + addMultiplier(mob, Attributes.FOLLOW_RANGE, FOLLOW_UUID, "am_follow", + AMConfig.tierValue(AMConfig.FOLLOW_RANGE_SCALE.get(), tier)); + addAddition(mob, Attributes.ARMOR, ARMOR_UUID, "am_armor", + AMConfig.tierValue(AMConfig.ARMOR_BONUS.get(), tier)); + addAddition(mob, Attributes.KNOCKBACK_RESISTANCE, KNOCKBACK_UUID, "am_kb", + AMConfig.tierValue(AMConfig.KNOCKBACK_RESIST.get(), tier)); + + // Heal to the new maximum so the health bonus is actually felt. + mob.setHealth(mob.getMaxHealth()); + + AdaptiveMobData.markScaled(mob, tier); + } + + private static void addMultiplier(Mob mob, Attribute attribute, UUID uuid, String name, double value) { + if (value <= 0.0) { + return; + } + AttributeInstance instance = mob.getAttribute(attribute); + if (instance == null || instance.getModifier(uuid) != null) { + return; + } + instance.addPermanentModifier( + new AttributeModifier(uuid, name, value, AttributeModifier.Operation.MULTIPLY_TOTAL)); + } + + private static void addAddition(Mob mob, Attribute attribute, UUID uuid, String name, double value) { + if (value <= 0.0) { + return; + } + AttributeInstance instance = mob.getAttribute(attribute); + if (instance == null || instance.getModifier(uuid) != null) { + return; + } + instance.addPermanentModifier( + new AttributeModifier(uuid, name, value, AttributeModifier.Operation.ADDITION)); + } +} diff --git a/src/main/java/net/fretux/adaptivemobs/spawn/SpawnPressureHelper.java b/src/main/java/net/fretux/adaptivemobs/spawn/SpawnPressureHelper.java new file mode 100644 index 0000000..94f789c --- /dev/null +++ b/src/main/java/net/fretux/adaptivemobs/spawn/SpawnPressureHelper.java @@ -0,0 +1,102 @@ +package net.fretux.adaptivemobs.spawn; + +import net.fretux.adaptivemobs.AdaptiveMobs; +import net.fretux.adaptivemobs.config.AMConfig; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.monster.Monster; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.phys.AABB; + +/** + * Adds modest spawn pressure: on a natural hostile spawn there is a tier-scaled chance to spawn + * one extra mob of the same type nearby. Capped at one extra per event, gated by local density, + * and guarded against recursion so extra spawns can never trigger further extra spawns. + */ +public final class SpawnPressureHelper { + + private static final ThreadLocal SPAWNING_EXTRA = ThreadLocal.withInitial(() -> Boolean.FALSE); + + private SpawnPressureHelper() { + } + + public static void maybeSpawnExtra(ServerLevel level, Mob original, int tier, MobSpawnType spawnType) { + if (!AMConfig.SPAWN_PRESSURE_ENABLED.get() || tier <= 0) { + return; + } + // Recursion guard: an extra spawn must never produce more extra spawns. + if (SPAWNING_EXTRA.get()) { + return; + } + // Natural spawns only. + if (spawnType != MobSpawnType.NATURAL && spawnType != MobSpawnType.CHUNK_GENERATION) { + return; + } + + RandomSource random = level.random; + double chance = AMConfig.tierValue(AMConfig.EXTRA_SPAWN_CHANCE.get(), tier); + if (random.nextDouble() > chance) { + return; + } + + // Respect local density so we don't snowball. + int radius = AMConfig.SPAWN_DENSITY_RADIUS.get(); + AABB box = original.getBoundingBox().inflate(radius); + int nearby = level.getEntitiesOfClass(Monster.class, box).size(); + if (nearby >= AMConfig.SPAWN_DENSITY_CAP.get()) { + return; + } + + EntityType type = original.getType(); + Entity created = type.create(level); + if (!(created instanceof Mob extra)) { + if (created != null) { + created.discard(); + } + return; + } + + SPAWNING_EXTRA.set(Boolean.TRUE); + try { + for (int attempt = 0; attempt < 6; attempt++) { + double dx = (random.nextDouble() - 0.5) * radius; + double dz = (random.nextDouble() - 0.5) * radius; + BlockPos spawnPos = surfaceSpawnPos(level, original.getX() + dx, original.getZ() + dz); + if (!level.getWorldBorder().isWithinBounds(spawnPos)) { + continue; + } + extra.moveTo(spawnPos.getX() + 0.5D, spawnPos.getY(), spawnPos.getZ() + 0.5D, + random.nextFloat() * 360.0F, 0.0F); + // Honour collision, light/biome spawn rules and obstruction checks. + if (level.noCollision(extra) + && extra.checkSpawnRules(level, MobSpawnType.NATURAL) + && extra.checkSpawnObstruction(level)) { + extra.finalizeSpawn(level, level.getCurrentDifficultyAt(extra.blockPosition()), + MobSpawnType.NATURAL, null, null); + level.addFreshEntity(extra); + if (AMConfig.debug) { + AdaptiveMobs.LOGGER.info("[AdaptiveMobs] Extra spawn ({}) at tier {} near {}", + type, tier, original.blockPosition()); + } + return; + } + } + // No valid position found. + extra.discard(); + } finally { + SPAWNING_EXTRA.set(Boolean.FALSE); + } + } + + private static BlockPos surfaceSpawnPos(ServerLevel level, double x, double z) { + int blockX = BlockPos.containing(x, 0.0D, z).getX(); + int blockZ = BlockPos.containing(x, 0.0D, z).getZ(); + int y = level.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, blockX, blockZ); + return new BlockPos(blockX, y, blockZ); + } +} diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg new file mode 100644 index 0000000..c01954b --- /dev/null +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -0,0 +1,5 @@ +# Adaptive Mobs access transformers +# Expose the goal/target selectors on Mob so we can inject and remove AI goals +# without resorting to mixins. +public net.minecraft.world.entity.Mob f_21345_ # goalSelector +public net.minecraft.world.entity.Mob f_21346_ # targetSelector diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..80795f1 --- /dev/null +++ b/src/main/resources/META-INF/mods.toml @@ -0,0 +1,73 @@ +# This is an example mods.toml file. It contains the data relating to the loading mods. +# There are several mandatory fields (#mandatory), and many more that are optional (#optional). +# The overall format is standard TOML format, v0.5.0. +# Note that there are a couple of TOML lists in this file. +# Find more information on toml format here: https://github.com/toml-lang/toml +# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml +modLoader="javafml" #mandatory +# A version range to match for said mod loader - for regular FML @Mod it will be the forge version +loaderVersion="${loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions. +# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties. +# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here. +license="${mod_license}" +# A URL to refer people to when problems occur with this mod +#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional +# If your mod is purely client-side and has no multiplayer functionality (be it dedicated servers or Open to LAN), +# set this to true, and Forge will set the correct displayTest for you and skip loading your mod on dedicated servers. +#clientSideOnly=true #optional - defaults to false if absent +# A list of mods - how many allowed here is determined by the individual mod loader +[[mods]] #mandatory +# The modid of the mod +modId="${mod_id}" #mandatory +# The version number of the mod +version="${mod_version}" #mandatory +# A display name for the mod +displayName="${mod_name}" #mandatory +# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/ +#updateJSONURL="https://change.me.example.invalid/updates.json" #optional +# A URL for the "homepage" for this mod, displayed in the mod UI +#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional +# A file name (in the root of the mod JAR) containing a logo for display +#logoFile="examplemod.png" #optional +# A text field displayed in the mod UI +#credits="" #optional +# A text field displayed in the mod UI +authors="${mod_authors}" #optional +# Display Test controls the display for your mod in the server connection screen +# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod. +# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod. +# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component. +# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value. +# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself. +#displayTest="MATCH_VERSION" # if nothing is specified, MATCH_VERSION is the default when clientSideOnly=false, otherwise IGNORE_ALL_VERSION when clientSideOnly=true (#optional) + +# The description text for the mod (multi line!) (#mandatory) +description='''${mod_description}''' +# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. +[[dependencies.${mod_id}]] #optional + # the modid of the dependency + modId="forge" #mandatory + # Does this dependency have to exist - if not, ordering below must be specified + mandatory=true #mandatory + # The version range of the dependency + versionRange="${forge_version_range}" #mandatory + # An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory + # BEFORE - This mod is loaded BEFORE the dependency + # AFTER - This mod is loaded AFTER the dependency + ordering="NONE" + # Side this dependency is applied on - BOTH, CLIENT, or SERVER + side="BOTH" +# Here's another dependency +[[dependencies.${mod_id}]] + modId="minecraft" + mandatory=true + # This version range declares a minimum of the current minecraft version up to but not including the next major version + versionRange="${minecraft_version_range}" + ordering="NONE" + side="BOTH" + +# Features are specific properties of the game environment, that you may want to declare you require. This example declares +# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't +# stop your mod loading on the server for example. +#[features.${mod_id}] +#openGLVersion="[3.2,)" diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..eca79ae --- /dev/null +++ b/src/main/resources/pack.mcmeta @@ -0,0 +1,8 @@ +{ + "pack": { + "description": { + "text": "${mod_id} resources" + }, + "pack_format": 15 + } +} \ No newline at end of file