This commit is contained in:
Ichinomiya Shirona
2026-05-21 13:51:00 +08:00
commit 956a6e515f
376 changed files with 144945 additions and 0 deletions
+5
View File
@@ -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
+25
View File
@@ -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
+65
View File
@@ -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.
+523
View File
@@ -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
+46
View File
@@ -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/
+237
View File
@@ -0,0 +1,237 @@
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
// Inject the built mod jar as a Java agent so PatchAgent.premain() runs before
// Minecraft classes are loaded. Use runClient0 (defined below) to ensure the jar is
// built first.
jvmArgs.add "-javaagent:${tasks.jar.archiveFile.get().asFile.absolutePath}".toString()
// Allow the agent to attach to itself if PatchAgent.installPatchesAndRetransform
// needs to fall back to the Attach API.
jvmArgs.add "-Djdk.attach.allowAttachSelf=true".toString()
}
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}"
compileOnly 'org.projectlombok:lombok:1.18.34'
annotationProcessor 'org.projectlombok:lombok:1.18.34'
// ASM (already on Forge classpath at runtime via Mojang deps, but declare for IDE/compile)
implementation 'org.ow2.asm:asm:9.6'
implementation 'org.ow2.asm:asm-tree:9.6'
implementation 'org.ow2.asm:asm-commons:9.6'
implementation 'org.ow2.asm:asm-util:9.6'
// 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"),
// Java-agent entry points so the jar can be passed via -javaagent:
'Premain-Class' : 'asm.patchify.loader.PatchAgent',
'Agent-Class' : 'asm.patchify.loader.PatchAgent',
'Can-Retransform-Classes' : 'true',
'Can-Redefine-Classes' : 'true'
])
}
// 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'
// }
// IZMK-style entry point: build the jar first (so the -javaagent path exists) and then launch
// the client. The client run config above already references tasks.jar via archiveFile.
tasks.register('runClient0') {
group = 'forgegradle runs'
description = 'Build the mod jar (used as -javaagent) and start the client.'
dependsOn tasks.jar
finalizedBy tasks.runClient
}
// 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
}
+1081
View File
File diff suppressed because it is too large Load Diff
+59
View File
@@ -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.20
# 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=examplemod
# The human-readable display name for the mod.
mod_name=Example Mod
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=All Rights Reserved
# 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=com.example.examplemod
# The authors of the mod. This is a simple text string that is used for display purposes in the mod list.
mod_authors=YourNameHere, OtherNameHere
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=Example mod description.\nNewline characters can be used and will be replaced properly.
Binary file not shown.
+6
View File
@@ -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
Vendored Executable
+245
View File
@@ -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" "$@"
Vendored
+92
View File
@@ -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
+13
View File
@@ -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'
}
@@ -0,0 +1,12 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Accessor {
Class<?> value();
}
@@ -0,0 +1,25 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface At {
Type value() default Type.HEAD;
String method() default "";
String remapped() default "";
String desc() default "";
enum Type {
BEFORE_INVOKE,
AFTER_INVOKE,
HEAD,
TAIL
}
}
@@ -0,0 +1,14 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FieldAccessor {
String value();
boolean getter() default true;
}
@@ -0,0 +1,11 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Final {
}
@@ -0,0 +1,18 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Inject {
String method();
String desc();
At at() default @At(At.Type.HEAD);
Slice slice() default @Slice(start = @At(At.Type.HEAD), end = @At(At.Type.TAIL));
}
@@ -0,0 +1,12 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Local {
int value();
}
@@ -0,0 +1,11 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodAccessor {
}
@@ -0,0 +1,20 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ModifyLocals {
String method();
String desc();
int[] indexes();
Class<?>[] types();
At at() default @At(At.Type.HEAD);
}
@@ -0,0 +1,14 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Overwrite {
String method();
String desc();
}
@@ -0,0 +1,12 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Patch {
Class<?> value();
}
@@ -0,0 +1,18 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface Slice {
At start() default @At(At.Type.HEAD);
At end() default @At(At.Type.TAIL);
int startIndex() default -1;
int endIndex() default -1;
}
@@ -0,0 +1,14 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Transform {
String method();
String desc();
}
@@ -0,0 +1,20 @@
package asm.patchify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface WrapInvoke {
String method();
String desc();
String target();
String targetDesc();
Slice slice() default @Slice;
}
@@ -0,0 +1,83 @@
package asm.patchify.loader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.TypeInsnNode;
/**
* Boxing / unboxing helpers used by the patchify-style transformer. Ported from
* <a href="https://github.com/xiaojiang233/izmk-reborn">izmk-reborn</a>'s {@code ASMUtil}.
*/
public final class ASMHelpers {
private ASMHelpers() {
}
/** Pops an {@code Object} off the stack and replaces it with the unboxed primitive of {@code type}. */
public static InsnList unboxFromObject(Type type) {
InsnList list = new InsnList();
switch (type.getSort()) {
case Type.INT -> {
list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Integer"));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false));
}
case Type.BOOLEAN -> {
list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Boolean"));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false));
}
case Type.CHAR -> {
list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Character"));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C", false));
}
case Type.BYTE -> {
list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Byte"));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B", false));
}
case Type.SHORT -> {
list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Short"));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S", false));
}
case Type.LONG -> {
list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Long"));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J", false));
}
case Type.FLOAT -> {
list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Float"));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F", false));
}
case Type.DOUBLE -> {
list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Double"));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D", false));
}
default -> list.add(new TypeInsnNode(Opcodes.CHECKCAST, type.getInternalName()));
}
return list;
}
/** Wraps the value currently on the stack in its boxed form (no-op for reference types). */
public static InsnList boxToObject(Type type) {
InsnList list = new InsnList();
switch (type.getSort()) {
case Type.INT -> list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false));
case Type.BOOLEAN -> list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false));
case Type.CHAR -> list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;", false));
case Type.BYTE -> list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false));
case Type.SHORT -> list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false));
case Type.LONG -> list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false));
case Type.FLOAT -> list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false));
case Type.DOUBLE -> list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false));
default -> list.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Object"));
}
return list;
}
/** Splits {@code "owner/of/Class/methodName"} into {@code ("owner/of/Class", "methodName")}. */
public static String[] splitOwnerName(String ownerSlashName) {
int slash = ownerSlashName.lastIndexOf('/');
if (slash < 0) {
return new String[] {"", ownerSlashName};
}
return new String[] {ownerSlashName.substring(0, slash), ownerSlashName.substring(slash + 1)};
}
}
@@ -0,0 +1,97 @@
package asm.patchify.loader;
import java.lang.instrument.Instrumentation;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Java agent entry point — loaded by the system class loader when the JVM is started with
* {@code -javaagent:<this jar>}.
*
* <p>In a ForgeGradle dev environment the mod jar and the agent jar are the same file but get
* loaded by different class loaders (system vs the Forge module layer). That means the static
* fields on this class are NOT shared between agent-side and mod-side copies of
* {@code PatchAgent}. To bridge the gap we stash {@link Instrumentation} in
* {@link System#getProperties()} under {@link #INSTRUMENTATION_KEY} so the mod can retrieve it
* regardless of which class loader it lives in.</p>
*/
public final class PatchAgent {
public static final String INSTRUMENTATION_KEY = "asm.patchify.instrumentation";
private static final Logger LOGGER = LogManager.getLogger("PatchAgent");
private PatchAgent() {
}
public static void premain(String args, Instrumentation inst) {
install(inst);
}
public static void agentmain(String args, Instrumentation inst) {
install(inst);
}
public static synchronized void install(Instrumentation inst) {
Object existing = System.getProperties().get(INSTRUMENTATION_KEY);
if (existing == inst) {
return;
}
System.getProperties().put(INSTRUMENTATION_KEY, inst);
LOGGER.info("PatchAgent attached, retransform supported = {}", inst.isRetransformClassesSupported());
}
/**
* Looks up the {@link Instrumentation} stashed by {@link #premain}. Works across class loaders.
*/
public static Instrumentation getInstrumentation() {
Object instObj = System.getProperties().get(INSTRUMENTATION_KEY);
return instObj instanceof Instrumentation ? (Instrumentation) instObj : null;
}
/**
* Install a transformer for the currently registered patches and retransform any patch target
* that is already loaded. Called from mod code once {@link PatchRegistry} is populated.
*/
public static void installPatchesAndRetransform() {
Instrumentation inst = getInstrumentation();
if (inst == null) {
LOGGER.warn("PatchAgent not attached; cannot install patches");
return;
}
PatchClassFileTransformer transformer = new PatchClassFileTransformer();
inst.addTransformer(transformer, true);
List<Class<?>> retransform = new ArrayList<>();
for (Class<?> patch : PatchRegistry.getPatches()) {
asm.patchify.annotation.Patch ann = patch.getAnnotation(asm.patchify.annotation.Patch.class);
if (ann == null) continue;
Class<?> target;
try {
target = ann.value();
} catch (Throwable t) {
LOGGER.warn("Patch target unresolved for {}: {}", patch.getName(), t.toString());
continue;
}
if (inst.isModifiableClass(target)) {
retransform.add(target);
} else {
LOGGER.warn("Cannot retransform unmodifiable target {}", target.getName());
}
}
if (retransform.isEmpty()) {
return;
}
// Retransform one class at a time so we can pinpoint which patch produces invalid
// bytecode if the JVM throws VerifyError / LinkageError.
int success = 0;
for (Class<?> target : retransform) {
try {
inst.retransformClasses(target);
success++;
} catch (Throwable t) {
LOGGER.error("Retransform failed for {}: {}", target.getName(), t.toString());
}
}
LOGGER.info("Retransformed {} / {} patch target(s)", success, retransform.size());
}
}
@@ -0,0 +1,112 @@
package asm.patchify.loader;
import asm.patchify.annotation.Patch;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
/**
* Java-agent {@link ClassFileTransformer} that applies registered patches at class load.
*
* <p>Indexes the patches by the JVM-internal name of their target class and rewrites class
* bytes via ASM. Classes that have no patch are returned untouched (null).</p>
*
* <p>If the system property {@code asm.patchify.dumpDir} is set, every successfully
* transformed class is written under that directory as {@code <internalName>.class} for
* inspection (use {@code javap -v} or open in Recaf).</p>
*/
public final class PatchClassFileTransformer implements ClassFileTransformer {
private static final Logger LOGGER = LogManager.getLogger("PatchTransformer");
private static final String DUMP_DIR_PROPERTY = "asm.patchify.dumpDir";
private final Map<String, List<Class<?>>> patchesByTarget = new HashMap<>();
public PatchClassFileTransformer() {
rebuildIndex();
}
public void rebuildIndex() {
patchesByTarget.clear();
for (Class<?> patchClass : PatchRegistry.getPatches()) {
Patch patch = patchClass.getAnnotation(Patch.class);
if (patch == null) continue;
String internalName = patch.value().getName().replace('.', '/');
patchesByTarget.computeIfAbsent(internalName, k -> new ArrayList<>()).add(patchClass);
}
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if (className == null) {
return null;
}
List<Class<?>> patches = patchesByTarget.get(className);
if (patches == null || patches.isEmpty()) {
return null;
}
try {
ClassReader reader = new ClassReader(classfileBuffer);
ClassNode classNode = new ClassNode();
reader.accept(classNode, 0);
for (Class<?> patch : patches) {
try {
LOGGER.debug("Applying patch {} -> {}", patch.getName(), className);
PatchTransformer.apply(patch, classNode);
} catch (Throwable t) {
LOGGER.error("Failed to apply patch {} -> {}", patch.getName(), className, t);
}
}
// Override getClassLoader so COMPUTE_FRAMES resolves Minecraft / mod classes via the
// class loader that actually owns the target class (Forge's TransformingClassLoader),
// not the one that loaded our PatchTransformer.
ClassLoader frameLoader = loader != null ? loader : Thread.currentThread().getContextClassLoader();
ClassWriter writer = new FrameAwareClassWriter(reader, ClassWriter.COMPUTE_FRAMES, frameLoader);
classNode.accept(writer);
byte[] transformed = writer.toByteArray();
dumpIfRequested(className, transformed);
return transformed;
} catch (Throwable t) {
LOGGER.error("Failed to transform {}", className, t);
return null;
}
}
private void dumpIfRequested(String internalName, byte[] bytes) {
String dumpDir = System.getProperty(DUMP_DIR_PROPERTY);
if (dumpDir == null) return;
try {
Path target = Path.of(dumpDir).resolve(internalName + ".class");
Files.createDirectories(target.getParent());
Files.write(target, bytes);
} catch (IOException e) {
LOGGER.warn("Failed to dump transformed class {}", internalName, e);
}
}
private static final class FrameAwareClassWriter extends ClassWriter {
private final ClassLoader loader;
FrameAwareClassWriter(ClassReader reader, int flags, ClassLoader loader) {
super(reader, flags);
this.loader = loader;
}
@Override
protected ClassLoader getClassLoader() {
return loader;
}
}
}
@@ -0,0 +1,44 @@
package asm.patchify.loader;
import asm.patchify.annotation.Patch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Runtime registry for {@link Patch}-annotated classes.
*
* <p>The original obfuscated client relied on a custom class-load transformer to wire up
* {@code @Inject} / {@code @Overwrite} / {@code @WrapInvoke} handlers. The transformer is
* provided by the loader and is not part of this restored source; this registry exposes the
* patch list so a coremod / launch plugin can drive the transformation, and provides a
* lightweight no-op fallback when no transformer is installed.</p>
*/
public final class PatchRegistry {
private static final Logger LOGGER = LogManager.getLogger("PatchRegistry");
private static final List<Class<?>> PATCHES = new ArrayList<>();
private PatchRegistry() {
}
public static void register(Class<?> patchClass) {
Patch annotation = patchClass.getAnnotation(Patch.class);
if (annotation == null) {
throw new IllegalArgumentException(patchClass.getName() + " is missing @Patch");
}
synchronized (PATCHES) {
if (!PATCHES.contains(patchClass)) {
PATCHES.add(patchClass);
LOGGER.debug("Registered patch {} -> {}", patchClass.getName(), annotation.value().getName());
}
}
}
public static List<Class<?>> getPatches() {
synchronized (PATCHES) {
return Collections.unmodifiableList(new ArrayList<>(PATCHES));
}
}
}
@@ -0,0 +1,690 @@
package asm.patchify.loader;
import asm.patchify.annotation.At;
import asm.patchify.annotation.Inject;
import asm.patchify.annotation.Local;
import asm.patchify.annotation.ModifyLocals;
import asm.patchify.annotation.Overwrite;
import asm.patchify.annotation.Patch;
import asm.patchify.annotation.Slice;
import asm.patchify.annotation.Transform;
import asm.patchify.annotation.WrapInvoke;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import shit.zen.asm.ILocals;
import shit.zen.asm.Invocation;
import shit.zen.asm.InvocationImpl;
import shit.zen.asm.Locals;
import shit.zen.asm.MethodWrapper;
import shit.zen.patch.CallbackInfo;
/**
* Applies all {@link Patch}-annotated handlers from a patch class to a target {@link ClassNode}.
* Ported from <a href="https://github.com/xiaojiang233/izmk-reborn">izmk-reborn</a>'s
* {@code PatchLoader}.
*
* <p>Supports:</p>
* <ul>
* <li>{@link Inject} with {@link At.Type#HEAD}/{@link At.Type#TAIL}/
* {@link At.Type#BEFORE_INVOKE}/{@link At.Type#AFTER_INVOKE} + {@link Slice}</li>
* <li>{@link Overwrite}</li>
* <li>{@link Transform} — direct {@link MethodNode} access for hand-written ASM</li>
* <li>{@link WrapInvoke} — wrap an {@code INVOKE} with an {@link Invocation} continuation</li>
* <li>{@link ModifyLocals} — read/write local slots via {@link ILocals}</li>
* <li>{@link Local} — pass a method-local slot directly to a handler parameter</li>
* </ul>
*/
public final class PatchTransformer {
private static final String CALLBACK_INFO = Type.getInternalName(CallbackInfo.class);
private static final String CALLBACK_INFO_DESC = Type.getDescriptor(CallbackInfo.class);
private PatchTransformer() {
}
public static void apply(Class<?> patchClass, ClassNode target) {
Patch patchAnnotation = patchClass.getAnnotation(Patch.class);
if (patchAnnotation == null) {
throw new IllegalArgumentException(patchClass.getName() + " is not @Patch");
}
Map<MethodKey, List<Method>> handlersByTarget = new HashMap<>();
for (Method handler : patchClass.getDeclaredMethods()) {
collectHandler(patchClass, handler, handlersByTarget);
}
for (MethodNode method : target.methods) {
List<Method> handlers = handlersByTarget.get(new MethodKey(method.name, method.desc));
if (handlers == null) continue;
for (Method handler : handlers) {
if (handler.isAnnotationPresent(Inject.class)) {
applyInject(method, handler);
} else if (handler.isAnnotationPresent(Overwrite.class)) {
overwriteMethod(method, handler);
} else if (handler.isAnnotationPresent(Transform.class)) {
try {
handler.setAccessible(true);
handler.invoke(null, method);
} catch (Exception e) {
throw new RuntimeException("Failed to apply @Transform " + handler, e);
}
} else if (handler.isAnnotationPresent(WrapInvoke.class)) {
wrapInvoke(method, handler);
} else if (handler.isAnnotationPresent(ModifyLocals.class)) {
modifyLocals(method, handler);
}
}
}
}
private static void collectHandler(Class<?> patchClass, Method handler,
Map<MethodKey, List<Method>> handlersByTarget) {
if (!(handler.isAnnotationPresent(Inject.class)
|| handler.isAnnotationPresent(Overwrite.class)
|| handler.isAnnotationPresent(Transform.class)
|| handler.isAnnotationPresent(WrapInvoke.class)
|| handler.isAnnotationPresent(ModifyLocals.class))) {
return;
}
if (!Modifier.isStatic(handler.getModifiers())) {
throw new IllegalArgumentException("Handler " + handler + " must be static");
}
String name;
String desc;
if (handler.isAnnotationPresent(Inject.class)) {
Inject inject = handler.getAnnotation(Inject.class);
name = inject.method();
desc = inject.desc();
validateInjectSignature(patchClass, handler, inject);
} else if (handler.isAnnotationPresent(Overwrite.class)) {
Overwrite overwrite = handler.getAnnotation(Overwrite.class);
name = overwrite.method();
desc = overwrite.desc();
} else if (handler.isAnnotationPresent(Transform.class)) {
Transform transform = handler.getAnnotation(Transform.class);
name = transform.method();
desc = transform.desc();
if (handler.getParameterCount() != 1 || handler.getParameterTypes()[0] != MethodNode.class) {
throw new IllegalArgumentException("@Transform " + handler + " must take a single MethodNode");
}
} else if (handler.isAnnotationPresent(WrapInvoke.class)) {
WrapInvoke wrap = handler.getAnnotation(WrapInvoke.class);
name = wrap.method();
desc = wrap.desc();
Class<?>[] params = handler.getParameterTypes();
if (params.length == 0 || !Invocation.class.isAssignableFrom(params[params.length - 1])) {
throw new IllegalArgumentException("@WrapInvoke " + handler + " must take an Invocation as last param");
}
} else {
ModifyLocals modify = handler.getAnnotation(ModifyLocals.class);
name = modify.method();
desc = modify.desc();
if (handler.getParameterCount() != 1 || !ILocals.class.isAssignableFrom(handler.getParameterTypes()[0])) {
throw new IllegalArgumentException("@ModifyLocals " + handler + " must take a single ILocals");
}
}
handlersByTarget.computeIfAbsent(new MethodKey(name, desc), k -> new ArrayList<>()).add(handler);
}
private static void validateInjectSignature(Class<?> patchClass, Method handler, Inject inject) {
if (handler.getReturnType() != void.class) {
throw new IllegalArgumentException("@Inject " + handler + " must return void");
}
Parameter[] params = handler.getParameters();
if (params.length == 0 || params[params.length - 1].getType() != CallbackInfo.class) {
throw new IllegalArgumentException("@Inject " + handler + " must take CallbackInfo as last param");
}
if (inject.at().value() == At.Type.HEAD) {
for (Parameter param : params) {
if (param.isAnnotationPresent(Local.class)) {
throw new IllegalArgumentException("@Inject " + handler + " HEAD cannot use @Local");
}
}
}
}
// ============================================================================
// @Inject
// ============================================================================
private static void applyInject(MethodNode method, Method handler) {
At at = handler.getAnnotation(Inject.class).at();
switch (at.value()) {
case HEAD -> injectHead(method, handler);
case TAIL -> injectTail(method, handler);
case BEFORE_INVOKE, AFTER_INVOKE -> {
String invokeName = at.method();
String invokeDesc = at.desc();
if (invokeName.isEmpty() || invokeDesc.isEmpty()) {
throw new IllegalArgumentException("@At " + handler + " missing method/desc");
}
injectAroundInvoke(method, handler, invokeName, invokeDesc, at.value() == At.Type.BEFORE_INVOKE);
}
}
}
private static void injectHead(MethodNode method, Method handler) {
Type returnType = Type.getReturnType(method.desc);
String handlerOwner = Type.getInternalName(handler.getDeclaringClass());
String handlerName = handler.getName();
String handlerDesc = Type.getMethodDescriptor(handler);
InsnList insns = new InsnList();
LabelNode notCancelled = new LabelNode();
int callbackIndex = method.maxLocals;
method.maxLocals += 1;
// Forward target method's receiver + args to the handler.
int slot = 0;
if (!Modifier.isStatic(method.access)) {
insns.add(new VarInsnNode(Opcodes.ALOAD, slot++));
}
for (Type argType : Type.getArgumentTypes(method.desc)) {
insns.add(new VarInsnNode(argType.getOpcode(Opcodes.ILOAD), slot));
slot += argType.getSize();
}
// CallbackInfo.create(null)
insns.add(new InsnNode(Opcodes.ACONST_NULL));
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC, CALLBACK_INFO, "create",
"(Ljava/lang/Object;)" + CALLBACK_INFO_DESC, false));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new VarInsnNode(Opcodes.ASTORE, callbackIndex));
// Invoke handler
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC, handlerOwner, handlerName, handlerDesc, false));
// Check CallbackInfo.cancelled
insns.add(new VarInsnNode(Opcodes.ALOAD, callbackIndex));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new FieldInsnNode(Opcodes.GETFIELD, CALLBACK_INFO, "cancelled", "Z"));
insns.add(new JumpInsnNode(Opcodes.IFEQ, notCancelled));
// cancelled -> return result
if (returnType == Type.VOID_TYPE) {
insns.add(new InsnNode(Opcodes.POP));
insns.add(new InsnNode(Opcodes.RETURN));
} else {
insns.add(new FieldInsnNode(Opcodes.GETFIELD, CALLBACK_INFO, "result", "Ljava/lang/Object;"));
insns.add(ASMHelpers.unboxFromObject(returnType));
insns.add(new InsnNode(returnType.getOpcode(Opcodes.IRETURN)));
}
insns.add(notCancelled);
insns.add(new InsnNode(Opcodes.POP));
method.instructions.insert(insns);
}
private static void injectTail(MethodNode method, Method handler) {
Type returnType = Type.getReturnType(method.desc);
int returnOp = returnType.getOpcode(Opcodes.IRETURN);
Slice slice = handler.getAnnotation(Inject.class).slice();
List<AbstractInsnNode> returnInsns = collectInjectionPoints(method.instructions, slice,
insn -> insn.getOpcode() == returnOp);
String handlerOwner = Type.getInternalName(handler.getDeclaringClass());
String handlerName = handler.getName();
String handlerDesc = Type.getMethodDescriptor(handler);
for (AbstractInsnNode returnInsn : returnInsns) {
InsnList insns = new InsnList();
int callbackIndex = method.maxLocals;
method.maxLocals += 1;
// Wrap return value as Object and stash into CallbackInfo.result.
if (returnType == Type.VOID_TYPE) {
insns.add(new InsnNode(Opcodes.ACONST_NULL));
} else {
insns.add(ASMHelpers.boxToObject(returnType));
}
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC, CALLBACK_INFO, "create",
"(Ljava/lang/Object;)" + CALLBACK_INFO_DESC, false));
// Forward (this, args..., @Local..., CallbackInfo) to handler. CallbackInfo is on top of stack now.
int slot = 0;
if (!Modifier.isStatic(method.access)) {
insns.add(new VarInsnNode(Opcodes.ALOAD, slot++));
insns.add(new InsnNode(Opcodes.SWAP));
}
for (Type argType : Type.getArgumentTypes(method.desc)) {
insns.add(new VarInsnNode(argType.getOpcode(Opcodes.ILOAD), slot));
slot += argType.getSize();
swapForCallback(argType, insns);
}
for (Parameter param : handler.getParameters()) {
Local local = param.getAnnotation(Local.class);
if (local == null) continue;
Type type = Type.getType(param.getType());
insns.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), local.value()));
swapForCallback(type, insns);
}
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new VarInsnNode(Opcodes.ASTORE, callbackIndex));
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC, handlerOwner, handlerName, handlerDesc, false));
// Restore the (possibly modified) return value from CallbackInfo.result.
insns.add(new VarInsnNode(Opcodes.ALOAD, callbackIndex));
insns.add(new FieldInsnNode(Opcodes.GETFIELD, CALLBACK_INFO, "result", "Ljava/lang/Object;"));
if (returnType == Type.VOID_TYPE) {
insns.add(new InsnNode(Opcodes.POP));
} else {
insns.add(ASMHelpers.unboxFromObject(returnType));
}
method.instructions.insertBefore(returnInsn, insns);
}
}
private static void injectAroundInvoke(MethodNode method, Method handler,
String invokeName, String invokeDesc, boolean before) {
Type returnType = Type.getReturnType(method.desc);
String[] split = ASMHelpers.splitOwnerName(invokeName);
String invokeOwner = split[0];
String invokeMethod = split[1];
Slice slice = handler.getAnnotation(Inject.class).slice();
List<AbstractInsnNode> sites = collectInjectionPoints(method.instructions, slice,
insn -> insn instanceof MethodInsnNode m
&& m.owner.equals(invokeOwner)
&& m.name.equals(invokeMethod)
&& m.desc.equals(invokeDesc));
if (sites.isEmpty()) {
return;
}
Set<Integer> initializedLocals = collectInitializedLocalsBefore(method, sites.get(0));
int callbackIndex = method.maxLocals;
method.maxLocals += 1;
String handlerOwner = Type.getInternalName(handler.getDeclaringClass());
String handlerName = handler.getName();
String handlerDesc = Type.getMethodDescriptor(handler);
for (AbstractInsnNode site : sites) {
InsnList insns = new InsnList();
LabelNode notCancelled = new LabelNode();
int slot = 0;
if (!Modifier.isStatic(method.access)) {
insns.add(new VarInsnNode(Opcodes.ALOAD, slot++));
}
for (Type argType : Type.getArgumentTypes(method.desc)) {
insns.add(new VarInsnNode(argType.getOpcode(Opcodes.ILOAD), slot));
slot += argType.getSize();
}
for (Parameter param : handler.getParameters()) {
Local local = param.getAnnotation(Local.class);
if (local == null) continue;
if (!initializedLocals.contains(local.value())) {
throw new IllegalArgumentException("@Local index " + local.value() + " not initialized before injection point in "
+ handler.getDeclaringClass().getName() + "." + handler.getName());
}
Type type = Type.getType(param.getType());
insns.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), local.value()));
}
insns.add(new InsnNode(Opcodes.ACONST_NULL));
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC, CALLBACK_INFO, "create",
"(Ljava/lang/Object;)" + CALLBACK_INFO_DESC, false));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new VarInsnNode(Opcodes.ASTORE, callbackIndex));
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC, handlerOwner, handlerName, handlerDesc, false));
insns.add(new VarInsnNode(Opcodes.ALOAD, callbackIndex));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new FieldInsnNode(Opcodes.GETFIELD, CALLBACK_INFO, "cancelled", "Z"));
insns.add(new JumpInsnNode(Opcodes.IFEQ, notCancelled));
insns.add(new FieldInsnNode(Opcodes.GETFIELD, CALLBACK_INFO, "result", "Ljava/lang/Object;"));
if (returnType == Type.VOID_TYPE) {
insns.add(new InsnNode(Opcodes.POP));
insns.add(new InsnNode(Opcodes.RETURN));
} else {
insns.add(ASMHelpers.unboxFromObject(returnType));
insns.add(new InsnNode(returnType.getOpcode(Opcodes.IRETURN)));
}
insns.add(notCancelled);
insns.add(new InsnNode(Opcodes.POP));
if (before) {
method.instructions.insertBefore(site, insns);
} else {
method.instructions.insert(site, insns);
}
}
}
// ============================================================================
// @Overwrite
// ============================================================================
private static void overwriteMethod(MethodNode method, Method handler) {
int expectedParams = Type.getArgumentTypes(method.desc).length
+ (Modifier.isStatic(method.access) ? 0 : 1);
if (handler.getParameterCount() != expectedParams) {
throw new IllegalArgumentException(
"@Overwrite handler " + handler + " has " + handler.getParameterCount()
+ " params but target requires " + expectedParams
+ " ((this if non-static), then method args). Remove any CallbackInfo param.");
}
method.instructions.clear();
if (method.tryCatchBlocks != null) method.tryCatchBlocks.clear();
if (method.localVariables != null) method.localVariables.clear();
InsnList insns = new InsnList();
int slot = 0;
if (!Modifier.isStatic(method.access)) {
insns.add(new VarInsnNode(Opcodes.ALOAD, slot++));
}
for (Type argType : Type.getArgumentTypes(method.desc)) {
insns.add(new VarInsnNode(argType.getOpcode(Opcodes.ILOAD), slot));
slot += argType.getSize();
}
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
Type.getInternalName(handler.getDeclaringClass()),
handler.getName(),
Type.getMethodDescriptor(handler),
false));
Type returnType = Type.getReturnType(method.desc);
insns.add(new InsnNode(returnType.getOpcode(Opcodes.IRETURN)));
method.instructions.insert(insns);
}
// ============================================================================
// @WrapInvoke
// ============================================================================
private static void wrapInvoke(MethodNode method, Method handler) {
WrapInvoke wrap = handler.getAnnotation(WrapInvoke.class);
String target = wrap.target();
String targetDesc = wrap.targetDesc();
String[] split = ASMHelpers.splitOwnerName(target);
String targetOwner = split[0];
String targetMethod = split[1];
List<AbstractInsnNode> sites = collectInjectionPoints(method.instructions, wrap.slice(),
insn -> insn instanceof MethodInsnNode m
&& m.owner.equals(targetOwner)
&& m.name.equals(targetMethod)
&& m.desc.equals(targetDesc));
if (sites.isEmpty()) {
return;
}
Set<Integer> initializedLocals = collectInitializedLocalsBefore(method, sites.get(0));
String handlerOwner = Type.getInternalName(handler.getDeclaringClass());
String handlerName = handler.getName();
String handlerDesc = Type.getMethodDescriptor(handler);
for (AbstractInsnNode site : sites) {
int op = site.getOpcode();
boolean staticCall = op == Opcodes.INVOKESTATIC;
if (!staticCall && op != Opcodes.INVOKEVIRTUAL && op != Opcodes.INVOKEINTERFACE) {
throw new IllegalArgumentException("@WrapInvoke unsupported opcode " + op + " in " + handler);
}
InsnList insns = new InsnList();
int wrapperLocal = method.maxLocals;
method.maxLocals += 1;
// Build MethodWrapper instance and stash it in a local.
insns.add(new LdcInsnNode(targetOwner));
insns.add(new LdcInsnNode(targetMethod));
insns.add(new LdcInsnNode(targetDesc));
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
Type.getInternalName(MethodWrapper.class), "getInstance",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)" + Type.getDescriptor(MethodWrapper.class),
false));
insns.add(new VarInsnNode(Opcodes.ASTORE, wrapperLocal));
// Stack: [..., receiver?, args...]
// Pop args in reverse, box them, push them into MethodWrapper.
Type[] argTypes = Type.getArgumentTypes(targetDesc);
for (int i = argTypes.length - 1; i >= 0; i--) {
insns.add(ASMHelpers.boxToObject(argTypes[i]));
insns.add(new VarInsnNode(Opcodes.ALOAD, wrapperLocal));
insns.add(new InsnNode(Opcodes.SWAP));
insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,
Type.getInternalName(MethodWrapper.class), "addParam",
"(Ljava/lang/Object;)" + Type.getDescriptor(MethodWrapper.class), false));
insns.add(new InsnNode(Opcodes.POP));
}
// Build the InvocationImpl. For non-static calls the receiver is still on the stack.
insns.add(new VarInsnNode(Opcodes.ALOAD, wrapperLocal));
if (staticCall) {
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
Type.getInternalName(InvocationImpl.class), "create",
"(" + Type.getDescriptor(MethodWrapper.class) + ")" + Type.getDescriptor(InvocationImpl.class),
false));
} else {
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
Type.getInternalName(InvocationImpl.class), "create",
"(Ljava/lang/Object;" + Type.getDescriptor(MethodWrapper.class) + ")" + Type.getDescriptor(InvocationImpl.class),
false));
}
// Stack now: [..., Invocation]
// Forward (this, methodArgs..., @Local..., Invocation) to handler.
int slot = 0;
if (!Modifier.isStatic(method.access)) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
insns.add(new InsnNode(Opcodes.SWAP));
slot++;
}
for (Type argType : Type.getArgumentTypes(method.desc)) {
insns.add(new VarInsnNode(argType.getOpcode(Opcodes.ILOAD), slot));
slot += argType.getSize();
swapForCallback(argType, insns);
}
for (Parameter param : handler.getParameters()) {
Local local = param.getAnnotation(Local.class);
if (local == null) continue;
if (!initializedLocals.contains(local.value())) {
throw new IllegalArgumentException("@Local index " + local.value() + " not initialized in " + handler);
}
Type type = Type.getType(param.getType());
insns.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), local.value()));
swapForCallback(type, insns);
}
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC, handlerOwner, handlerName, handlerDesc, false));
method.instructions.insertBefore(site, insns);
method.instructions.remove(site);
}
}
// ============================================================================
// @ModifyLocals
// ============================================================================
private static void modifyLocals(MethodNode method, Method handler) {
ModifyLocals modify = handler.getAnnotation(ModifyLocals.class);
int[] indexes = modify.indexes();
Class<?>[] typeClasses = modify.types();
if (indexes.length != typeClasses.length) {
throw new IllegalArgumentException("@ModifyLocals indexes/types length mismatch in " + handler);
}
Type[] types = new Type[typeClasses.length];
for (int i = 0; i < typeClasses.length; i++) {
types[i] = Type.getType(typeClasses[i]);
}
At at = modify.at();
AbstractInsnNode insertBefore = method.instructions.getFirst();
Set<Integer> initializedLocals = new HashSet<>();
if (at.value() != At.Type.HEAD) {
if (at.value() == At.Type.TAIL) {
int retOp = Type.getReturnType(method.desc).getOpcode(Opcodes.IRETURN);
for (AbstractInsnNode insn : method.instructions) {
if (insn.getOpcode() == retOp) {
insertBefore = insn;
break;
}
if (insn instanceof VarInsnNode v && v.getOpcode() >= Opcodes.ISTORE && v.getOpcode() <= Opcodes.ASTORE) {
initializedLocals.add(v.var);
}
}
} else {
String[] split = ASMHelpers.splitOwnerName(at.method());
for (AbstractInsnNode insn : method.instructions) {
if (insn instanceof MethodInsnNode m && m.owner.equals(split[0])
&& m.name.equals(split[1]) && m.desc.equals(at.desc())) {
insertBefore = insn;
break;
}
if (insn instanceof VarInsnNode v && v.getOpcode() >= Opcodes.ISTORE && v.getOpcode() <= Opcodes.ASTORE) {
initializedLocals.add(v.var);
}
}
}
for (int idx : indexes) {
if (!initializedLocals.contains(idx) && at.value() != At.Type.HEAD) {
// Don't hard-fail — caller might intentionally read an uninitialised slot.
// Just log via exception only if BEFORE/AFTER were used.
}
}
}
InsnList insns = new InsnList();
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
Type.getInternalName(Locals.class), "create",
"()" + Type.getDescriptor(Locals.class), false));
for (int i = 0; i < indexes.length; i++) {
int idx = indexes[i];
Type type = types[i];
insns.add(new LdcInsnNode(idx));
insns.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), idx));
insns.add(ASMHelpers.boxToObject(type));
insns.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE,
Type.getInternalName(ILocals.class), "set",
"(ILjava/lang/Object;)" + Type.getDescriptor(ILocals.class), true));
}
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
Type.getInternalName(handler.getDeclaringClass()),
handler.getName(), Type.getMethodDescriptor(handler), false));
for (int i = 0; i < indexes.length; i++) {
int idx = indexes[i];
Type type = types[i];
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new LdcInsnNode(idx));
insns.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE,
Type.getInternalName(ILocals.class), "get",
"(I)Ljava/lang/Object;", true));
insns.add(ASMHelpers.unboxFromObject(type));
insns.add(new VarInsnNode(type.getOpcode(Opcodes.ISTORE), idx));
}
insns.add(new InsnNode(Opcodes.POP));
method.instructions.insertBefore(insertBefore, insns);
}
// ============================================================================
// Helpers
// ============================================================================
private static List<AbstractInsnNode> collectInjectionPoints(InsnList insns, Slice slice,
Predicate<AbstractInsnNode> filter) {
boolean defaultStart = slice.start().value() == At.Type.HEAD;
boolean defaultEnd = slice.end().value() == At.Type.TAIL;
boolean indexed = slice.startIndex() != -1 || slice.endIndex() != -1;
List<AbstractInsnNode> matches = new ArrayList<>();
if (defaultStart && defaultEnd && !indexed) {
for (AbstractInsnNode insn : insns) {
if (filter.test(insn)) matches.add(insn);
}
return matches;
}
if (indexed) {
int count = 0;
int endIndex = slice.endIndex() == -1 ? Integer.MAX_VALUE : slice.endIndex();
int startIndex = slice.startIndex() == -1 ? 1 : slice.startIndex();
for (AbstractInsnNode insn : insns) {
if (!filter.test(insn)) continue;
count++;
if (count >= startIndex && count <= endIndex) {
matches.add(insn);
} else if (count > endIndex) {
break;
}
}
return matches;
}
// method-bounded slice
String[] startSplit = slice.start().method().isEmpty()
? null : ASMHelpers.splitOwnerName(slice.start().method());
String startDesc = slice.start().desc();
String[] endSplit = slice.end().method().isEmpty()
? null : ASMHelpers.splitOwnerName(slice.end().method());
String endDesc = slice.end().desc();
boolean foundStart = defaultStart;
for (AbstractInsnNode insn : insns) {
if (!foundStart && startSplit != null && insn instanceof MethodInsnNode m
&& m.owner.equals(startSplit[0]) && m.name.equals(startSplit[1]) && m.desc.equals(startDesc)) {
foundStart = true;
} else if (!defaultEnd && endSplit != null && insn instanceof MethodInsnNode m
&& m.owner.equals(endSplit[0]) && m.name.equals(endSplit[1]) && m.desc.equals(endDesc)) {
break;
}
if (foundStart && filter.test(insn)) {
matches.add(insn);
}
}
return matches;
}
private static Set<Integer> collectInitializedLocalsBefore(MethodNode method, AbstractInsnNode boundary) {
Set<Integer> locals = new HashSet<>();
for (AbstractInsnNode insn : method.instructions) {
if (insn == boundary) break;
if (insn instanceof VarInsnNode v && v.getOpcode() >= Opcodes.ISTORE && v.getOpcode() <= Opcodes.ASTORE) {
locals.add(v.var);
}
}
return locals;
}
/**
* Swap a value just pushed below the CallbackInfo / Invocation reference. Long/double take
* two slots and need DUP2_X1+POP2 instead of SWAP. Mirrors izmk's helper.
*/
private static void swapForCallback(Type type, InsnList insns) {
if (type == Type.LONG_TYPE || type == Type.DOUBLE_TYPE) {
insns.add(new InsnNode(Opcodes.DUP2_X1));
insns.add(new InsnNode(Opcodes.POP2));
} else {
insns.add(new InsnNode(Opcodes.SWAP));
}
}
private record MethodKey(String name, String desc) {
@Override
public boolean equals(Object o) {
return o instanceof MethodKey k && k.name.equals(name) && k.desc.equals(desc);
}
@Override
public int hashCode() {
return name.hashCode() * 31 + desc.hashCode();
}
}
/** Suppresses an unused-warning for {@link Arrays} import (kept for parity with izmk). */
@SuppressWarnings("unused")
private static void keepArraysImport() {
Arrays.asList();
}
}
+14
View File
@@ -0,0 +1,14 @@
package shit.zen;
import java.util.concurrent.ConcurrentLinkedQueue;
import net.minecraft.client.Minecraft;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClientBase {
public static Minecraft mc;
public static Logger logger = LogManager.getLogger("Client");
public static float partialTicks;
public static boolean isLoading;
public static final ConcurrentLinkedQueue<Runnable> delayPackets = new ConcurrentLinkedQueue<>();
}
+176
View File
@@ -0,0 +1,176 @@
package shit.zen;
import asm.patchify.loader.PatchAgent;
import asm.patchify.loader.PatchRegistry;
import java.io.File;
import java.lang.reflect.Field;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.common.Mod;
import shit.zen.event.EventBus;
import shit.zen.manager.CommandManager;
import shit.zen.manager.ConfigManager;
import shit.zen.manager.HudManager;
import shit.zen.manager.LagManager;
import shit.zen.manager.ModuleManager;
import shit.zen.manager.TargetManager;
import shit.zen.patch.ChatScreenPatch;
import shit.zen.patch.ClientLevelPatch;
import shit.zen.patch.ConnectionPatch;
import shit.zen.patch.EntityPatch;
import shit.zen.patch.EntityRendererPatch;
import shit.zen.patch.FriendlyByteBufPatch;
import shit.zen.patch.GameRendererPatch;
import shit.zen.patch.HumanoidModelPatch;
import shit.zen.patch.ItemInHandLayerPatch;
import shit.zen.patch.ItemInHandRendererPatch;
import shit.zen.patch.ItemPatch;
import shit.zen.patch.KeyboardHandlerPatch;
import shit.zen.patch.KeyboardInputPatch;
import shit.zen.patch.LevelRendererPatch;
import shit.zen.patch.LivingEntityPatch;
import shit.zen.patch.LivingEntityRendererPatch;
import shit.zen.patch.LocalPlayerPatch;
import shit.zen.patch.MinecraftPatch;
import shit.zen.patch.PacketUtilsPatch;
import shit.zen.patch.PlayerPatch;
import shit.zen.patch.PlayerTabOverlayPatch;
import shit.zen.patch.TimerPatch;
import shit.zen.utils.misc.Encryption;
import shit.zen.utils.rotation.RotationHandler;
@Mod(value = "hey")
@Getter
@Setter
public class ZenClient extends ClientBase {
@Getter
public static ZenClient instance;
public static final String CLIENT_NAME = "Zen";
public static final String VERSION = "1.0";
public static float serverTickRate;
public static boolean isReady;
public static boolean isMCPMapped;
public static String configDir = System.getProperty("user.home") + File.separator + ".zen";
public static String username = "";
private EventBus eventBus;
private RotationHandler rotationHandler;
private ModuleManager moduleManager;
private CommandManager commandManager;
private ConfigManager configManager;
private HudManager hudManager;
private LagManager lagManager;
private TargetManager targetManager;
private Encryption encryption;
private int reconnectAttempts;
public ZenClient() {
if (instance == null) {
instance = this;
this.init();
}
}
private void init() {
try {
username = System.getProperty("user.name", "Player");
File dir = new File(configDir);
if (!dir.exists() && !dir.mkdirs()) {
logger.warn("Failed to create config directory at {}", configDir);
}
mc = getMcInstance();
this.eventBus = new EventBus();
this.rotationHandler = new RotationHandler();
this.eventBus.register(this.rotationHandler);
this.moduleManager = new ModuleManager();
this.moduleManager.initModules();
this.hudManager = new HudManager();
this.commandManager = new CommandManager();
this.commandManager.initCommands();
this.configManager = new ConfigManager();
this.configManager.loadAll();
this.lagManager = new LagManager();
this.eventBus.register(this.lagManager);
this.targetManager = new TargetManager();
this.eventBus.register(this.targetManager);
this.encryption = new Encryption(Encryption.Algorithm.AES);
registerPatches();
if (PatchAgent.getInstrumentation() != null) {
PatchAgent.installPatchesAndRetransform();
} else {
logger.warn("PatchAgent not attached. Launch with `./gradlew runClient0` so the agent jvmArg is set.");
}
isReady = true;
logger.info("{} v{} initialized.", CLIENT_NAME, VERSION);
} catch (Throwable throwable) {
logger.error(throwable.getMessage(), throwable);
}
}
public static boolean isReady() {
return instance != null
&& ZenClient.instance.eventBus != null
&& isReady
&& mc != null
&& mc.player != null
&& !username.isEmpty()
&& mc.player.tickCount > 5;
}
public static boolean isOwner(String string) {
return false;
}
public static String decodeString(String s) {
return s;
}
public void disconnectFromServer() {
isReady = false;
if (this.configManager != null) {
this.configManager.saveAll();
}
}
private static void registerPatches() {
PatchRegistry.register(MinecraftPatch.class);
PatchRegistry.register(LocalPlayerPatch.class);
PatchRegistry.register(LivingEntityPatch.class);
PatchRegistry.register(EntityPatch.class);
PatchRegistry.register(PlayerPatch.class);
PatchRegistry.register(ClientLevelPatch.class);
PatchRegistry.register(ConnectionPatch.class);
PatchRegistry.register(PacketUtilsPatch.class);
PatchRegistry.register(KeyboardHandlerPatch.class);
PatchRegistry.register(KeyboardInputPatch.class);
PatchRegistry.register(ChatScreenPatch.class);
PatchRegistry.register(EntityRendererPatch.class);
PatchRegistry.register(LevelRendererPatch.class);
PatchRegistry.register(GameRendererPatch.class);
PatchRegistry.register(ItemInHandRendererPatch.class);
PatchRegistry.register(ItemInHandLayerPatch.class);
PatchRegistry.register(HumanoidModelPatch.class);
PatchRegistry.register(LivingEntityRendererPatch.class);
PatchRegistry.register(ItemPatch.class);
PatchRegistry.register(PlayerTabOverlayPatch.class);
PatchRegistry.register(FriendlyByteBufPatch.class);
}
public static Minecraft getMcInstance() {
Minecraft minecraft = null;
try {
Class<?> clazz = Minecraft.class;
for (Field field : clazz.getDeclaredFields()) {
if (field.getType() != clazz) continue;
field.setAccessible(true);
minecraft = (Minecraft) field.get(null);
field.setAccessible(false);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return minecraft != null ? minecraft : Minecraft.getInstance();
}
}
+10
View File
@@ -0,0 +1,10 @@
package shit.zen.asm;
/**
* Mutable view of the local-variable slots seen by a {@code @ModifyLocals} handler.
*/
public interface ILocals {
Object get(int index);
ILocals set(int index, Object value);
}
@@ -0,0 +1,22 @@
package shit.zen.asm;
import java.util.List;
import java.util.concurrent.Callable;
/**
* Handle to the original {@code INVOKE} that was wrapped by an {@code @WrapInvoke} patch.
*
* @param <T> receiver type of the wrapped method (or {@link Object} for static targets)
* @param <R> return type of the wrapped method
*/
public interface Invocation<T, R> extends Callable<R> {
/**
* Arguments captured at the wrapped call site, in their original order.
*/
List<Object> args();
/**
* Receiver of the wrapped call. Throws for static targets.
*/
T instance();
}
@@ -0,0 +1,46 @@
package shit.zen.asm;
import java.util.List;
@SuppressWarnings("rawtypes")
public final class InvocationImpl implements Invocation {
private final Object instance;
private final MethodWrapper wrapper;
private InvocationImpl(Object instance, MethodWrapper wrapper) {
this.instance = instance;
this.wrapper = wrapper;
}
public static InvocationImpl create(Object instance, MethodWrapper wrapper) {
return new InvocationImpl(instance, wrapper);
}
public static InvocationImpl create(MethodWrapper wrapper) {
return new InvocationImpl(null, wrapper);
}
@Override
public List<Object> args() {
return wrapper.getMethodParams();
}
@Override
public Object instance() {
if (instance == null) {
throw new IllegalStateException("static method invocation");
}
return instance;
}
@Override
public Object call() throws Exception {
try {
return wrapper.call(instance);
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
+29
View File
@@ -0,0 +1,29 @@
package shit.zen.asm;
import java.util.HashMap;
import java.util.Map;
public final class Locals implements ILocals {
private final Map<Integer, Object> locals = new HashMap<>();
private Locals() {
}
public static Locals create() {
return new Locals();
}
@Override
public Object get(int index) {
if (!locals.containsKey(index)) {
throw new IllegalArgumentException("Index " + index + " is not defined in the local list");
}
return locals.get(index);
}
@Override
public Locals set(int index, Object value) {
locals.put(index, value);
return this;
}
}
@@ -0,0 +1,81 @@
package shit.zen.asm;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.objectweb.asm.Type;
/**
* Accumulator for the (receiver, args) tuple captured at a wrapped invoke site, paired with a
* cached {@link MethodHandle} so the wrapper can re-invoke the original implementation on
* demand. The instances are short-lived — one per wrapped call.
*/
public final class MethodWrapper {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final Map<String, MethodHandle> CACHE = new ConcurrentHashMap<>();
private final MethodHandle handle;
private final List<Object> params = new LinkedList<>();
private MethodWrapper(MethodHandle handle) {
this.handle = handle;
}
public static MethodWrapper getInstance(String classOwner, String methodName, String methodDesc) throws Exception {
String key = classOwner + "/" + methodName + methodDesc;
MethodHandle cached = CACHE.get(key);
if (cached != null) {
return new MethodWrapper(cached);
}
Class<?> clazz = Class.forName(classOwner.replace('/', '.'), false,
Thread.currentThread().getContextClassLoader());
MethodHandle handle = lookup(clazz, methodName, methodDesc);
if (handle == null) {
throw new NoSuchMethodException("Method " + methodName + methodDesc + " not found on " + classOwner);
}
CACHE.put(key, handle);
return new MethodWrapper(handle);
}
private static MethodHandle lookup(Class<?> clazz, String methodName, String methodDesc) throws Exception {
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals(methodName) && Type.getMethodDescriptor(method).equals(methodDesc)) {
method.setAccessible(true);
return LOOKUP.unreflect(method);
}
}
return null;
}
public List<Object> getMethodParams() {
return params;
}
/**
* Bytecode entry point: pushes one argument onto the wrapper. Args are accumulated in reverse
* (the call site pushes them last-arg first), so we always insert at index 0 — the final
* list ends up in original calling order.
*/
public MethodWrapper addParam(Object param) {
params.add(0, param);
return this;
}
public Object call(Object instance) throws Throwable {
if (instance == null) {
if (params.isEmpty()) {
return handle.invoke();
}
return handle.invokeWithArguments(params);
}
if (params.isEmpty()) {
return handle.invoke(instance);
}
params.add(0, instance);
return handle.invokeWithArguments(params);
}
}
@@ -0,0 +1,22 @@
package shit.zen.command;
import lombok.Getter;
import lombok.Generated;
public abstract class Command {
@Getter
private final String prefix;
@Getter
private final String[] aliases;
public abstract void onCommand(String[] var1);
public abstract String[] onTab(String[] var1);
@Generated
public Command(String string, String[] stringArray) {
this.prefix = string;
this.aliases = stringArray;
}
}
@@ -0,0 +1,99 @@
package shit.zen.command.impl;
import com.mojang.blaze3d.platform.InputConstants;
import shit.zen.ZenClient;
import shit.zen.command.Command;
import shit.zen.event.EventTarget;
import shit.zen.exception.ModuleNotFoundException;
import shit.zen.modules.Module;
import shit.zen.utils.misc.ChatUtil;
public class BindCommand
extends Command {
public static final class EventHandler {
private final BindCommand parent;
private final Module module;
private final String name;
public EventHandler(BindCommand parent, Module module, String name) {
this.parent = parent;
this.module = module;
this.name = name;
}
@EventTarget
public void onKey(shit.zen.event.impl.KeyEvent event) {
if (!event.isPressed()) return;
int keyCode = event.getKeyCode();
if (keyCode == 256) {
module.setKey(0);
ChatUtil.print("Unbound " + this.name + ".");
} else {
module.setKey(keyCode);
ChatUtil.print("Bound " + this.name + " to key " + keyCode + ".");
}
ZenClient.getInstance().getEventBus().unregister(this);
ZenClient.getInstance().getConfigManager().saveAll();
}
}
public BindCommand() {
super("bind", new String[]{"b"});
}
@Override
public void onCommand(String[] args) {
if (args.length == 1) {
this.handleBindInteractive(args[0]);
} else if (args.length == 2) {
this.handleBindExplicit(args[0], args[1]);
} else {
ChatUtil.print("Usage: .bind <module> [key]");
}
}
private void handleBindInteractive(String moduleName) {
try {
Module module = ZenClient.getInstance().getModuleManager().getModule(moduleName);
if (module == null) {
ChatUtil.print("Invalid module.");
return;
}
ChatUtil.print("Press a key to bind " + moduleName + " to.");
ZenClient.getInstance().getEventBus().register(new BindCommand.EventHandler(this, module, moduleName));
} catch (ModuleNotFoundException e) {
ChatUtil.print("Invalid module.");
}
}
private void handleBindExplicit(String moduleName, String keyName) {
try {
Module module = ZenClient.getInstance().getModuleManager().getModule(moduleName);
if (module == null) {
ChatUtil.print("Invalid module.");
return;
}
if (keyName.equalsIgnoreCase("none")) {
module.setKey(InputConstants.UNKNOWN.getValue());
ChatUtil.print("Unbound " + moduleName + ".");
ZenClient.getInstance().getConfigManager().saveAll();
return;
}
InputConstants.Key key = InputConstants.getKey("key.keyboard." + keyName.toLowerCase());
if (key == InputConstants.UNKNOWN) {
ChatUtil.print("Invalid key.");
return;
}
module.setKey(key.getValue());
ChatUtil.print("Bound " + moduleName + " to " + keyName.toUpperCase() + ".");
ZenClient.getInstance().getConfigManager().saveAll();
} catch (ModuleNotFoundException e) {
ChatUtil.print("Invalid module.");
}
}
@Override
public String[] onTab(String[] stringArray) {
return ZenClient.getInstance().getModuleManager().getModules().stream().map(Module::getName).filter(string -> string.toLowerCase().startsWith(stringArray.length == 0 ? "" : stringArray[0].toLowerCase())).toArray(String[]::new);
}
}
@@ -0,0 +1,38 @@
package shit.zen.command.impl;
import java.io.IOException;
import shit.zen.ZenClient;
import shit.zen.command.Command;
import shit.zen.manager.ConfigManager;
import shit.zen.utils.misc.ChatUtil;
public class ConfigCommand extends Command {
public ConfigCommand() {
super("config", new String[]{"cfg"});
}
@Override
public void onCommand(String[] stringArray) {
if (stringArray.length == 1) {
switch (stringArray[0]) {
case "reload":
ZenClient.getInstance().getConfigManager().loadAll();
ChatUtil.print("Config reloaded!");
break;
case "folder":
try {
Runtime.getRuntime().exec("explorer " + ConfigManager.CONFIG_DIR.getAbsolutePath());
} catch (IOException ignored) {
}
break;
}
} else {
ChatUtil.print("Usage: config reload/folder");
}
}
@Override
public String[] onTab(String[] stringArray) {
return new String[0];
}
}
@@ -0,0 +1,30 @@
package shit.zen.command.impl;
import shit.zen.ZenClient;
import shit.zen.command.Command;
import shit.zen.command.impl.LanguageCommand.EventHandler;
public class LanguageCommand
extends Command {
public static final class EventHandler {
private final LanguageCommand parent;
public EventHandler(LanguageCommand parent) {
this.parent = parent;
}
}
public LanguageCommand() {
super("language", new String[]{"lang"});
}
@Override
public void onCommand(String[] stringArray) {
ZenClient.getInstance().getEventBus().register(new LanguageCommand.EventHandler(this));
}
@Override
public String[] onTab(String[] stringArray) {
return new String[0];
}
}
@@ -0,0 +1,37 @@
package shit.zen.command.impl;
import shit.zen.ZenClient;
import shit.zen.command.Command;
import shit.zen.exception.ModuleNotFoundException;
import shit.zen.modules.Module;
import shit.zen.utils.misc.ChatUtil;
public class ToggleCommand
extends Command {
public ToggleCommand() {
super("toggle", new String[]{"t"});
}
@Override
public void onCommand(String[] stringArray) {
if (stringArray.length == 1) {
String string = stringArray[0];
try {
Module module = ZenClient.getInstance().getModuleManager().getModule(string);
if (module != null) {
module.setEnabled(!module.isEnabled());
ChatUtil.print("Toggled " + module.getName() + ".");
} else {
ChatUtil.print("Invalid module.");
}
} catch (ModuleNotFoundException moduleNotFoundException) {
ChatUtil.print("Invalid module.");
}
}
}
@Override
public String[] onTab(String[] stringArray) {
return ZenClient.getInstance().getModuleManager().getModules().stream().map(Module::getName).filter(string -> string.toLowerCase().startsWith(stringArray.length == 0 ? "" : stringArray[0].toLowerCase())).toArray(String[]::new);
}
}
+25
View File
@@ -0,0 +1,25 @@
package shit.zen.config;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import lombok.Getter;
import shit.zen.manager.ConfigManager;
public abstract class Config {
@Getter
private final String name;
@Getter
private final File file;
public Config(String string) {
this.name = string;
this.file = new File(ConfigManager.CONFIG_DIR, string);
}
public abstract void read(BufferedReader var1) throws IOException;
public abstract void save(BufferedWriter var1) throws IOException;
}
@@ -0,0 +1,54 @@
package shit.zen.config;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import shit.zen.ZenClient;
import shit.zen.config.Config;
import shit.zen.exception.ModuleNotFoundException;
import shit.zen.manager.ModuleManager;
import shit.zen.modules.Module;
public class ModulesConfig
extends Config {
private static final Logger LOGGER = LogManager.getLogger(ModulesConfig.class);
public ModulesConfig() {
super("modules.cfg");
}
@Override
public void read(BufferedReader bufferedReader) throws IOException {
String string;
ModuleManager moduleManager = ZenClient.getInstance().getModuleManager();
while ((string = bufferedReader.readLine()) != null) {
String[] stringArray = string.split(":", 3);
if (stringArray.length != 3) {
LOGGER.error("Failed to read line {}!", string);
continue;
}
String string2 = stringArray[0];
int n = Integer.parseInt(stringArray[1]);
boolean bl = Boolean.parseBoolean(stringArray[2]);
try {
Module module = moduleManager.getModule(string2);
module.setKey(n);
module.setEnabled(bl);
} catch (ModuleNotFoundException moduleNotFoundException) {
LOGGER.error("Failed to find module {}!", string2);
}
}
}
@Override
public void save(BufferedWriter bufferedWriter) throws IOException {
ModuleManager moduleManager = ZenClient.getInstance().getModuleManager();
ArrayList<Module> arrayList = new ArrayList<>(moduleManager.getModules());
for (Module module : arrayList) {
bufferedWriter.write(String.format((String)"%s:%d:%s\n", (Object[])new Object[]{module.getName(), module.getKey(), module.isEnabled()}));
}
}
}
@@ -0,0 +1,121 @@
package shit.zen.config;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import shit.zen.ZenClient;
import shit.zen.config.Config;
import shit.zen.hud.HudElement;
import shit.zen.modules.Module;
import shit.zen.settings.impl.BooleanSetting;
import shit.zen.settings.impl.ModeSetting;
import shit.zen.settings.impl.MultiSelectSetting;
import shit.zen.settings.impl.NumberSetting;
public class ValuesConfig
extends Config {
private static final Logger LOGGER = LogManager.getLogger(ValuesConfig.class);
public ValuesConfig() {
super("values.cfg");
}
@Override
public void read(BufferedReader bufferedReader) throws IOException {
String string;
while ((string = bufferedReader.readLine()) != null) {
try {
String[] stringArray = string.split(":", 4);
if (stringArray.length != 4) {
LOGGER.error("Failed to read line {}!", string);
continue;
}
String string2 = stringArray[0];
String string3 = stringArray[1];
String string4 = stringArray[2];
String string5 = stringArray[3];
Module module = ZenClient.getInstance().getModuleManager().getModule(string3);
if (module == null) continue;
String string6 = string;
if (module instanceof HudElement hudElement) {
try {
if (string2.equals("P")) {
if (string4.equals("X")) {
hudElement.setX(Float.parseFloat(string5));
}
if (string4.equals("Y")) {
hudElement.setY(Float.parseFloat(string5));
}
}
} catch (Exception exception) {
LOGGER.error("Failed to set position of {}!", hudElement.getName());
}
}
module.getSettings().forEach(setting -> {
if (!string4.equals(setting.getName())) {
return;
}
switch (string2) {
case "B":
((BooleanSetting) setting).setValue(Boolean.parseBoolean(string5));
break;
case "F":
((NumberSetting) setting).setValue(Float.parseFloat(string5));
break;
case "MV":
MultiSelectSetting multiSelectSetting = (MultiSelectSetting) setting;
if (string5.isEmpty()) {
multiSelectSetting.setValue(new ArrayList<>());
} else {
multiSelectSetting.setValue(new ArrayList<>(Arrays.asList(string5.split(","))));
}
break;
case "M":
ModeSetting modeSetting = (ModeSetting) setting;
if (string5.isEmpty()) {
LOGGER.error("Failed to read mode value {}!", string6);
} else {
modeSetting.setValue(string5);
}
break;
default:
LOGGER.error("Unknown value type of {}!", string3);
}
});
} catch (Exception exception) {
LOGGER.error("Failed to read value {}!: {}", string, exception);
}
}
}
@Override
public void save(BufferedWriter bufferedWriter) throws IOException {
for (Module module : ZenClient.getInstance().getModuleManager().getModules()) {
if (module instanceof HudElement hudElement) {
bufferedWriter.write(String.format((String)"P:%s:X:%s\n", (Object[])new Object[]{module.getName(), Float.valueOf(hudElement.getX())}));
bufferedWriter.write(String.format((String)"P:%s:Y:%s\n", (Object[])new Object[]{module.getName(), Float.valueOf(hudElement.getY())}));
}
module.getSettings().forEach(setting -> {
try {
if (setting instanceof BooleanSetting booleanSetting) {
bufferedWriter.write(String.format((String)"B:%s:%s:%s\n", (Object[])new Object[]{module.getName(), booleanSetting.getName(), booleanSetting.getValue()}));
} else if (setting instanceof NumberSetting numberSetting) {
bufferedWriter.write(String.format((String)"F:%s:%s:%s\n", (Object[])new Object[]{module.getName(), numberSetting.getName(), numberSetting.getValue()}));
} else if (setting instanceof ModeSetting modeSetting) {
bufferedWriter.write(String.format((String)"M:%s:%s:%s\n", (Object[])new Object[]{module.getName(), modeSetting.getName(), modeSetting.getValue()}));
} else if (setting instanceof MultiSelectSetting multiSelectSetting) {
bufferedWriter.write(String.format((String)"MV:%s:%s:%s\n", (Object[])new Object[]{module.getName(), multiSelectSetting.getName(), String.join(",", multiSelectSetting.getValue())}));
} else {
LOGGER.error("Unknown value type of {}!", setting.getName());
}
} catch (Exception exception) {
LOGGER.error("Failed to save value {}!", setting.getName());
}
});
}
}
}
@@ -0,0 +1,19 @@
package shit.zen.event;
import shit.zen.event.EventMarker;
public abstract class AbstractCancellable
implements EventMarker {
private boolean cancelled;
protected AbstractCancellable() {
}
public void cancel() {
this.cancelled = true;
}
public boolean isCancelled() {
return this.cancelled;
}
}
@@ -0,0 +1,7 @@
package shit.zen.event;
public interface Cancellable {
boolean isCancelled();
void setCancelled(boolean var1);
}
+23
View File
@@ -0,0 +1,23 @@
package shit.zen.event;
import shit.zen.event.Cancellable;
import shit.zen.event.EventMarker;
public abstract class Event
implements Cancellable,
EventMarker {
public boolean cancelled;
protected Event() {
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean bl) {
this.cancelled = bl;
}
}
+118
View File
@@ -0,0 +1,118 @@
package shit.zen.event;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public final class EventBus {
private static final Logger LOGGER = LogManager.getLogger(EventBus.class);
private final Map<Class<? extends EventMarker>, List<ListenerEntry>> listeners = new HashMap<>();
public record ListenerEntry(Object listener, Method method, byte priority) {
}
public void register(Object object) {
for (Method method : object.getClass().getDeclaredMethods()) {
if (!isValidListener(method)) continue;
addListener(method, object);
}
}
public void registerForClass(Object object, Class<? extends EventMarker> clazz) {
for (Method method : object.getClass().getDeclaredMethods()) {
if (!isListenerForClass(method, clazz)) continue;
addListener(method, object);
}
}
public void unregister(Object object) {
for (List<ListenerEntry> list : listeners.values()) {
list.removeIf(e -> e.listener().equals(object));
}
}
public void unregisterForClass(Object object, Class<? extends EventMarker> clazz) {
if (listeners.containsKey(clazz)) {
listeners.get(clazz).removeIf(e -> e.listener().equals(object));
}
}
private void addListener(Method method, Object object) {
@SuppressWarnings("unchecked")
Class<? extends EventMarker> clazz = (Class<? extends EventMarker>) method.getParameterTypes()[0];
ListenerEntry entry = new ListenerEntry(object, method, method.getAnnotation(EventTarget.class).value());
if (!entry.method().isAccessible()) {
entry.method().setAccessible(true);
}
List<ListenerEntry> list = listeners.computeIfAbsent(clazz, k -> new CopyOnWriteArrayList<>());
if (!list.contains(entry)) {
list.add(entry);
sortByPriority(clazz);
}
}
public void callEventForClass(Class<? extends EventMarker> clazz) {
Iterator<Map.Entry<Class<? extends EventMarker>, List<ListenerEntry>>> iterator = listeners.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getKey().equals(clazz)) {
iterator.remove();
break;
}
}
}
private void sortByPriority(Class<? extends EventMarker> clazz) {
List<ListenerEntry> existing = listeners.get(clazz);
CopyOnWriteArrayList<ListenerEntry> sorted = new CopyOnWriteArrayList<>();
for (byte priority : EventPriority.PRIORITIES) {
for (ListenerEntry entry : existing) {
if (entry.priority() == priority) {
sorted.add(entry);
}
}
}
listeners.put(clazz, sorted);
}
private boolean isValidListener(Method method) {
return method.getParameterTypes().length == 1 && method.isAnnotationPresent(EventTarget.class);
}
private boolean isListenerForClass(Method method, Class<? extends EventMarker> clazz) {
return isValidListener(method) && method.getParameterTypes()[0].equals(clazz);
}
public EventMarker call(EventMarker eventMarker) {
List<ListenerEntry> list = listeners.get(eventMarker.getClass());
if (list == null) return eventMarker;
if (eventMarker instanceof AbstractCancellable abstractCancellable) {
for (ListenerEntry entry : list) {
dispatchToListener(entry, eventMarker);
if (abstractCancellable.isCancelled()) break;
}
} else {
for (ListenerEntry entry : list) {
dispatchToListener(entry, eventMarker);
}
}
return eventMarker;
}
private void dispatchToListener(ListenerEntry entry, EventMarker eventMarker) {
try {
entry.method().invoke(entry.listener(), eventMarker);
} catch (InvocationTargetException e) {
LOGGER.error("invocation target {} {} {}", entry.listener, entry.method, e);
e.printStackTrace();
} catch (Exception e) {
LOGGER.error("{} {}", entry.listener, entry.method);
e.printStackTrace();
}
}
}
@@ -0,0 +1,4 @@
package shit.zen.event;
public interface EventMarker {
}
@@ -0,0 +1,11 @@
package shit.zen.event;
public final class EventPriority {
public static final byte HIGHEST = 0;
public static final byte HIGH = 1;
public static final byte NORMAL = 2;
public static final byte LOW = 3;
public static final byte LOWEST = 4;
public static final byte[] PRIORITIES = new byte[]{HIGHEST, HIGH, NORMAL, LOW, LOWEST};
}
@@ -0,0 +1,14 @@
package shit.zen.event;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(value={ElementType.METHOD})
@Retention(value=RetentionPolicy.RUNTIME)
public @interface EventTarget {
byte value() default 2;
}
@@ -0,0 +1,5 @@
package shit.zen.event;
public interface Prioritized {
byte getPriority();
}
@@ -0,0 +1,22 @@
package shit.zen.event.impl;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class CameraPitchEvent
implements EventMarker {
private float pitch;
public float getPitch() {
return this.pitch;
}
public void setPitch(float f) {
this.pitch = f;
}
@Generated
public CameraPitchEvent(float f) {
this.pitch = f;
}
}
@@ -0,0 +1,54 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Generated;
import shit.zen.event.Event;
import java.util.Objects;
public class ChatEvent
extends Event {
@Getter
private final String message;
private static final String TO_STRING_PREFIX = "ChatEvent(message=";
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof ChatEvent chatEvent)) {
return false;
}
if (!chatEvent.canEqual(this)) {
return false;
}
String string = this.getMessage();
String string2 = chatEvent.getMessage();
return !(!Objects.equals(string, string2));
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof ChatEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
String string = this.getMessage();
n2 = n2 * 59 + (string == null ? 43 : string.hashCode());
return n2;
}
@Generated
public String toString() {
return TO_STRING_PREFIX + this.getMessage() + ")";
}
@Generated
public ChatEvent(String string) {
this.message = string;
}
}
@@ -0,0 +1,35 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import net.minecraft.network.chat.Component;
import shit.zen.event.EventMarker;
import shit.zen.event.impl.ChatReceiveEvent.MessageType;
public class ChatReceiveEvent
implements EventMarker {
public enum MessageType {
NAME, CHAT, SYSTEM
}
@Getter
private ChatReceiveEvent.MessageType msgType;
@Getter @Setter
private Component component;
public ChatReceiveEvent(Component component) {
this.msgType = ChatReceiveEvent.MessageType.NAME;
this.component = component;
}
@Generated
public void setMessageType(ChatReceiveEvent.MessageType chatReceiveEvent$MessageType) {
this.msgType = chatReceiveEvent$MessageType;
}
@Generated
public ChatReceiveEvent(ChatReceiveEvent.MessageType chatReceiveEvent$MessageType, Component component) {
this.msgType = chatReceiveEvent$MessageType;
this.component = component;
}
}
@@ -0,0 +1,7 @@
package shit.zen.event.impl;
import shit.zen.event.EventMarker;
public class DisconnectEvent
implements EventMarker {
}
@@ -0,0 +1,31 @@
package shit.zen.event.impl;
import lombok.Generated;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.LivingEntity;
import shit.zen.event.EventMarker;
public record EntityHurtEvent(LivingEntity entity, DamageSource damageSource, float amount)
implements EventMarker {
@Override
@Generated
public LivingEntity entity() {
return this.entity;
}
@Override
@Generated
public DamageSource damageSource() {
return this.damageSource;
}
@Override
@Generated
public float amount() {
return this.amount;
}
@Generated
public EntityHurtEvent {
}
}
@@ -0,0 +1,24 @@
package shit.zen.event.impl;
import lombok.Generated;
import net.minecraft.world.entity.Entity;
import shit.zen.event.EventMarker;
public record EntityRemoveEvent(boolean dead, Entity entity)
implements EventMarker {
@Override
@Generated
public boolean dead() {
return this.dead;
}
@Override
@Generated
public Entity entity() {
return this.entity;
}
@Generated
public EntityRemoveEvent {
}
}
@@ -0,0 +1,50 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class FallFlyingEvent
implements EventMarker {
@Getter @Setter
private float speed;
private static final String TO_STRING_PREFIX = "FallFlyingEvent(pitch=";
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof FallFlyingEvent fallFlyingEvent)) {
return false;
}
if (!fallFlyingEvent.canEqual(this)) {
return false;
}
return Float.compare(this.getSpeed(), fallFlyingEvent.getSpeed()) == 0;
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof FallFlyingEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
n2 = n2 * 59 + Float.floatToIntBits(this.getSpeed());
return n2;
}
@Generated
public String toString() {
return TO_STRING_PREFIX + this.getSpeed() + ")";
}
@Generated
public FallFlyingEvent(float f) {
this.speed = f;
}
}
@@ -0,0 +1,7 @@
package shit.zen.event.impl;
import shit.zen.event.EventMarker;
public class GameTickEvent
implements EventMarker {
}
@@ -0,0 +1,86 @@
package shit.zen.event.impl;
import com.mojang.blaze3d.vertex.PoseStack;
import lombok.Generated;
import net.minecraft.client.gui.GuiGraphics;
import shit.zen.event.EventMarker;
import shit.zen.render.DrawContext;
import java.util.Objects;
public record GlRenderEvent(GuiGraphics guiGraphics, PoseStack poseStack, DrawContext drawContext)
implements EventMarker {
@Override
@Generated
public GuiGraphics guiGraphics() {
return this.guiGraphics;
}
@Override
@Generated
public PoseStack poseStack() {
return this.poseStack;
}
@Override
@Generated
public DrawContext drawContext() {
return this.drawContext;
}
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof GlRenderEvent glRenderEvent)) {
return false;
}
if (!glRenderEvent.canEqual(this)) {
return false;
}
GuiGraphics guiGraphics = this.guiGraphics();
GuiGraphics guiGraphics2 = glRenderEvent.guiGraphics();
if (!Objects.equals(guiGraphics, guiGraphics2)) {
return false;
}
PoseStack poseStack = this.poseStack();
PoseStack poseStack2 = glRenderEvent.poseStack();
if (!Objects.equals(poseStack, poseStack2)) {
return false;
}
DrawContext drawContext = this.drawContext();
DrawContext drawContext2 = glRenderEvent.drawContext();
return !(!Objects.equals(drawContext, drawContext2));
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof GlRenderEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
GuiGraphics guiGraphics = this.guiGraphics();
n2 = n2 * 59 + (guiGraphics == null ? 43 : guiGraphics.hashCode());
PoseStack poseStack = this.poseStack();
n2 = n2 * 59 + (poseStack == null ? 43 : poseStack.hashCode());
DrawContext drawContext = this.drawContext();
n2 = n2 * 59 + (drawContext == null ? 43 : drawContext.hashCode());
return n2;
}
@Generated
public String toString() {
String string = String.valueOf(this.drawContext());
String string2 = String.valueOf(this.poseStack());
String string3 = String.valueOf(this.guiGraphics());
return "GlRenderEvent(guiGraphics=" + string3 + ", stack=" + string2 + ", context=" + string + ")";
}
@Generated
public GlRenderEvent {
}
}
@@ -0,0 +1,56 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class HeadTurnEvent
implements EventMarker {
@Getter @Setter
private float yaw;
@Getter @Setter
private float pitch;
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof HeadTurnEvent headTurnEvent)) {
return false;
}
if (!headTurnEvent.canEqual(this)) {
return false;
}
if (Float.compare(this.getYaw(), headTurnEvent.getYaw()) != 0) {
return false;
}
return Float.compare(this.getPitch(), headTurnEvent.getPitch()) == 0;
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof HeadTurnEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
n2 = n2 * 59 + Float.floatToIntBits(this.getYaw());
n2 = n2 * 59 + Float.floatToIntBits(this.getPitch());
return n2;
}
@Generated
public String toString() {
return "HeadTurnEvent(yaw=" + this.getYaw() + ", lastYaw=" + this.getPitch() + ")";
}
@Generated
public HeadTurnEvent(float f, float f2) {
this.yaw = f;
this.pitch = f2;
}
}
@@ -0,0 +1,11 @@
package shit.zen.event.impl;
import lombok.Generated;
import shit.zen.event.Event;
public class JumpEvent
extends Event {
@Generated
public JumpEvent() {
}
}
@@ -0,0 +1,50 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class JumpMarkerEvent
implements EventMarker {
@Getter @Setter
private float jumpHeight;
private static final String TO_STRING_PREFIX = "JumpEvent(yaw=";
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof JumpMarkerEvent jumpMarkerEvent)) {
return false;
}
if (!jumpMarkerEvent.canEqual(this)) {
return false;
}
return Float.compare(this.getJumpHeight(), jumpMarkerEvent.getJumpHeight()) == 0;
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof JumpMarkerEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
n2 = n2 * 59 + Float.floatToIntBits(this.getJumpHeight());
return n2;
}
@Generated
public String toString() {
return TO_STRING_PREFIX + this.getJumpHeight() + ")";
}
@Generated
public JumpMarkerEvent(float f) {
this.jumpHeight = f;
}
}
@@ -0,0 +1,55 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Generated;
import shit.zen.event.Event;
public class KeyEvent
extends Event {
@Getter
private final int keyCode;
@Getter
private final boolean pressed;
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof KeyEvent keyEvent)) {
return false;
}
if (!keyEvent.canEqual(this)) {
return false;
}
if (this.getKeyCode() != keyEvent.getKeyCode()) {
return false;
}
return this.isPressed() == keyEvent.isPressed();
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof KeyEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
n2 = n2 * 59 + this.getKeyCode();
n2 = n2 * 59 + (this.isPressed() ? 79 : 97);
return n2;
}
@Generated
public String toString() {
return "KeyEvent(key=" + this.getKeyCode() + ", state=" + this.isPressed() + ")";
}
@Generated
public KeyEvent(int n, boolean bl) {
this.keyCode = n;
this.pressed = bl;
}
}
@@ -0,0 +1,39 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import shit.zen.event.Event;
public class MotionEvent
extends Event {
@Getter @Setter
public boolean pre;
@Getter @Setter
public double x;
@Getter @Setter
public double y;
@Getter @Setter
public double z;
@Getter @Setter
public float yaw;
@Getter @Setter
public float pitch;
@Getter @Setter
public boolean onGround;
public boolean isPost() {
return !this.isPre();
}
@Generated
public MotionEvent(boolean bl, double d, double d2, double d3, float f, float f2, boolean bl2) {
this.pre = bl;
this.x = d;
this.y = d2;
this.z = d3;
this.yaw = f;
this.pitch = f2;
this.onGround = bl2;
}
}
@@ -0,0 +1,30 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import net.minecraft.network.protocol.Packet;
import shit.zen.event.Event;
public class PacketEvent
extends Event {
@Getter @Setter
private Packet<?> packet;
@Setter
private boolean incoming;
public boolean isIncoming() {
return !this.incoming;
}
@Generated
public boolean isIncomingRaw() {
return this.incoming;
}
@Generated
public PacketEvent(Packet<?> packet, boolean bl) {
this.packet = packet;
this.incoming = bl;
}
}
@@ -0,0 +1,15 @@
package shit.zen.event.impl;
import lombok.Generated;
import net.minecraft.network.protocol.Packet;
import shit.zen.event.Event;
public class PacketSendEvent
extends Event {
private final Packet<?> packet;
@Generated
public PacketSendEvent(Packet<?> packet) {
this.packet = packet;
}
}
@@ -0,0 +1,7 @@
package shit.zen.event.impl;
import shit.zen.event.EventMarker;
public class PostMotionEvent
implements EventMarker {
}
@@ -0,0 +1,7 @@
package shit.zen.event.impl;
import shit.zen.event.Event;
public class PreMotionEvent
extends Event {
}
@@ -0,0 +1,17 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Generated;
import net.minecraft.network.protocol.Packet;
import shit.zen.event.Event;
public class PrePacketEvent
extends Event {
@Getter
private final Packet<?> packet;
@Generated
public PrePacketEvent(Packet<?> packet) {
this.packet = packet;
}
}
@@ -0,0 +1,11 @@
package shit.zen.event.impl;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class PreTickEvent
implements EventMarker {
@Generated
public PreTickEvent() {
}
}
@@ -0,0 +1,19 @@
package shit.zen.event.impl;
import shit.zen.event.EventMarker;
import shit.zen.event.Prioritized;
public abstract class PrioritizedEvent
implements Prioritized,
EventMarker {
private final byte priority;
protected PrioritizedEvent(byte by) {
this.priority = by;
}
@Override
public byte getPriority() {
return this.priority;
}
}
@@ -0,0 +1,72 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import net.minecraft.world.entity.Entity;
import shit.zen.event.EventMarker;
import java.util.Objects;
public class RayTraceEvent
implements EventMarker {
@Getter @Setter
public Entity entity;
@Getter @Setter
public float range;
@Getter @Setter
public float blockRange;
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof RayTraceEvent rayTraceEvent)) {
return false;
}
if (!rayTraceEvent.canEqual(this)) {
return false;
}
if (Float.compare(this.getRange(), rayTraceEvent.getRange()) != 0) {
return false;
}
if (Float.compare(this.getBlockRange(), rayTraceEvent.getBlockRange()) != 0) {
return false;
}
Entity entity = this.getEntity();
Entity entity2 = rayTraceEvent.getEntity();
return !(!Objects.equals(entity, entity2));
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof RayTraceEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
n2 = n2 * 59 + Float.floatToIntBits(this.getRange());
n2 = n2 * 59 + Float.floatToIntBits(this.getBlockRange());
Entity entity = this.getEntity();
n2 = n2 * 59 + (entity == null ? 43 : entity.hashCode());
return n2;
}
@Generated
public String toString() {
float f = this.getBlockRange();
float f2 = this.getRange();
String string = String.valueOf(this.getEntity());
return "RayTraceEvent(entity=" + string + ", yaw=" + f2 + ", pitch=" + f + ")";
}
@Generated
public RayTraceEvent(Entity entity, float f, float f2) {
this.entity = entity;
this.range = f;
this.blockRange = f2;
}
}
@@ -0,0 +1,18 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Generated;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import shit.zen.event.Event;
public class ReceivePacketEvent
extends Event {
@Getter
private final Packet<ClientGamePacketListener> packet;
@Generated
public ReceivePacketEvent(Packet<ClientGamePacketListener> packet) {
this.packet = packet;
}
}
@@ -0,0 +1,82 @@
package shit.zen.event.impl;
import com.mojang.blaze3d.vertex.PoseStack;
import lombok.Generated;
import net.minecraft.client.gui.GuiGraphics;
import shit.zen.event.EventMarker;
import java.util.Objects;
public record Render2DEvent(PoseStack poseStack, GuiGraphics guiGraphics, float partialTick)
implements EventMarker {
@Override
@Generated
public PoseStack poseStack() {
return this.poseStack;
}
@Override
@Generated
public GuiGraphics guiGraphics() {
return this.guiGraphics;
}
@Override
@Generated
public float partialTick() {
return this.partialTick;
}
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Render2DEvent render2DEvent)) {
return false;
}
if (!render2DEvent.canEqual(this)) {
return false;
}
if (Float.compare(this.partialTick(), render2DEvent.partialTick()) != 0) {
return false;
}
PoseStack poseStack = this.poseStack();
PoseStack poseStack2 = render2DEvent.poseStack();
if (!Objects.equals(poseStack, poseStack2)) {
return false;
}
GuiGraphics guiGraphics = this.guiGraphics();
GuiGraphics guiGraphics2 = render2DEvent.guiGraphics();
return !(!Objects.equals(guiGraphics, guiGraphics2));
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof Render2DEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
n2 = n2 * 59 + Float.floatToIntBits(this.partialTick());
PoseStack poseStack = this.poseStack();
n2 = n2 * 59 + (poseStack == null ? 43 : poseStack.hashCode());
GuiGraphics guiGraphics = this.guiGraphics();
n2 = n2 * 59 + (guiGraphics == null ? 43 : guiGraphics.hashCode());
return n2;
}
@Generated
public String toString() {
float f = this.partialTick();
String string = String.valueOf(this.guiGraphics());
String string2 = String.valueOf(this.poseStack());
return "Render2DEvent(stack=" + string2 + ", guiGraphics=" + string + ", partialTicks=" + f + ")";
}
@Generated
public Render2DEvent {
}
}
@@ -0,0 +1,59 @@
package shit.zen.event.impl;
import com.mojang.blaze3d.vertex.PoseStack;
import lombok.Getter;
import lombok.Generated;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.world.entity.Entity;
import shit.zen.event.Event;
public class RenderEntityEvent
extends Event {
@Getter
private final EntityRenderer<?> entityRenderer;
@Getter
private final Entity entity;
@Getter
private final PoseStack poseStack;
@Getter
private final MultiBufferSource bufferSource;
@Getter
private final float partialTick;
@Getter
private final int packedLight;
private boolean cancelled;
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean bl) {
this.cancelled = bl;
}
@Generated
public RenderEntityEvent(EntityRenderer<?> entityRenderer, Entity entity, PoseStack poseStack, MultiBufferSource multiBufferSource, float f, int n, boolean bl) {
this.entityRenderer = entityRenderer;
this.entity = entity;
this.poseStack = poseStack;
this.bufferSource = multiBufferSource;
this.partialTick = f;
this.packedLight = n;
this.cancelled = bl;
}
public static class Pre extends RenderEntityEvent {
public Pre(EntityRenderer<?> renderer, Entity entity, PoseStack poseStack, MultiBufferSource bufferSource, float partialTick, int packedLight) {
super(renderer, entity, poseStack, bufferSource, partialTick, packedLight, false);
}
}
public static class Post extends RenderEntityEvent {
public Post(EntityRenderer<?> renderer, Entity entity, PoseStack poseStack, MultiBufferSource bufferSource, float partialTick, int packedLight) {
super(renderer, entity, poseStack, bufferSource, partialTick, packedLight, false);
}
}
}
@@ -0,0 +1,24 @@
package shit.zen.event.impl;
import com.mojang.blaze3d.vertex.PoseStack;
import lombok.Generated;
import shit.zen.event.EventMarker;
public record RenderEvent(PoseStack poseStack, float partialTick)
implements EventMarker {
@Override
@Generated
public PoseStack poseStack() {
return this.poseStack;
}
@Override
@Generated
public float partialTick() {
return this.partialTick;
}
@Generated
public RenderEvent {
}
}
@@ -0,0 +1,20 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class RotationEvent
implements EventMarker {
@Getter @Setter
private float yaw;
@Getter @Setter
private float pitch;
@Generated
public RotationEvent(float f, float f2) {
this.yaw = f;
this.pitch = f2;
}
}
@@ -0,0 +1,20 @@
package shit.zen.event.impl;
import lombok.Setter;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class SlowdownEvent
implements EventMarker {
@Setter
private boolean slowDown;
public boolean isSlowDown() {
return this.slowDown;
}
@Generated
public SlowdownEvent(boolean bl) {
this.slowDown = bl;
}
}
@@ -0,0 +1,7 @@
package shit.zen.event.impl;
import shit.zen.event.Event;
public class SneakEvent
extends Event {
}
@@ -0,0 +1,7 @@
package shit.zen.event.impl;
import shit.zen.event.EventMarker;
public class SprintEvent
implements EventMarker {
}
@@ -0,0 +1,23 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class StrafeEvent
implements EventMarker {
@Getter @Setter
private float forward;
@Getter @Setter
private float strafe;
@Getter @Setter
private boolean sprinting;
@Generated
public StrafeEvent(float f, float f2, boolean bl) {
this.forward = f;
this.strafe = f2;
this.sprinting = bl;
}
}
@@ -0,0 +1,66 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
import shit.zen.event.Event;
import java.util.Objects;
public class StuckInBlockEvent
extends Event {
@Getter @Setter
private BlockState blockState;
@Getter @Setter
private Vec3 motion;
@Generated
public String toString() {
return "StuckInBlockEvent(state=" + this.getBlockState() + ", stuckSpeedMultiplier=" + this.getMotion() + ")";
}
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof StuckInBlockEvent stuckInBlockEvent)) {
return false;
}
if (!stuckInBlockEvent.canEqual(this)) {
return false;
}
BlockState blockState = this.getBlockState();
BlockState blockState2 = stuckInBlockEvent.getBlockState();
if (!Objects.equals(blockState, blockState2)) {
return false;
}
Vec3 vec3 = this.getMotion();
Vec3 vec32 = stuckInBlockEvent.getMotion();
return !(!Objects.equals(vec3, vec32));
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof StuckInBlockEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
BlockState blockState = this.getBlockState();
n2 = n2 * 59 + (blockState == null ? 43 : blockState.hashCode());
Vec3 vec3 = this.getMotion();
n2 = n2 * 59 + (vec3 == null ? 43 : vec3.hashCode());
return n2;
}
@Generated
public StuckInBlockEvent(BlockState blockState, Vec3 vec3) {
this.blockState = blockState;
this.motion = vec3;
}
}
@@ -0,0 +1,7 @@
package shit.zen.event.impl;
import shit.zen.event.EventMarker;
public class TickEvent
implements EventMarker {
}
@@ -0,0 +1,66 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.item.ItemStack;
import shit.zen.event.EventMarker;
import java.util.Objects;
public class UpdateHeldItemEvent
implements EventMarker {
@Getter
private final InteractionHand hand;
@Getter @Setter
private ItemStack itemStack;
@Generated
public UpdateHeldItemEvent(InteractionHand interactionHand, ItemStack itemStack) {
this.hand = interactionHand;
this.itemStack = itemStack;
}
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof UpdateHeldItemEvent updateHeldItemEvent)) {
return false;
}
if (!updateHeldItemEvent.canEqual(this)) {
return false;
}
InteractionHand interactionHand = this.getHand();
InteractionHand interactionHand2 = updateHeldItemEvent.getHand();
if (!Objects.equals(interactionHand, interactionHand2)) {
return false;
}
ItemStack itemStack = this.getItemStack();
ItemStack itemStack2 = updateHeldItemEvent.getItemStack();
return !(!Objects.equals(itemStack, itemStack2));
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof UpdateHeldItemEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
InteractionHand interactionHand = this.getHand();
n2 = n2 * 59 + (interactionHand == null ? 43 : interactionHand.hashCode());
ItemStack itemStack = this.getItemStack();
n2 = n2 * 59 + (itemStack == null ? 43 : itemStack.hashCode());
return n2;
}
@Generated
public String toString() {
return "UpdateHeldItemEvent(hand=" + this.getHand() + ", item=" + this.getItemStack() + ")";
}
}
@@ -0,0 +1,56 @@
package shit.zen.event.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.Generated;
import shit.zen.event.EventMarker;
public class UseItemRayTraceEvent
implements EventMarker {
@Getter @Setter
private float range;
@Getter @Setter
private float blockRange;
@Generated
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof UseItemRayTraceEvent useItemRayTraceEvent)) {
return false;
}
if (!useItemRayTraceEvent.canEqual(this)) {
return false;
}
if (Float.compare(this.getRange(), useItemRayTraceEvent.getRange()) != 0) {
return false;
}
return Float.compare(this.getBlockRange(), useItemRayTraceEvent.getBlockRange()) == 0;
}
@Generated
protected boolean canEqual(Object object) {
return object instanceof UseItemRayTraceEvent;
}
@Generated
public int hashCode() {
int n = 59;
int n2 = 1;
n2 = n2 * 59 + Float.floatToIntBits(this.getRange());
n2 = n2 * 59 + Float.floatToIntBits(this.getBlockRange());
return n2;
}
@Generated
public String toString() {
return "UseItemRayTraceEvent(yaw=" + this.getRange() + ", pitch=" + this.getBlockRange() + ")";
}
@Generated
public UseItemRayTraceEvent(float f, float f2) {
this.range = f;
this.blockRange = f2;
}
}
@@ -0,0 +1,7 @@
package shit.zen.event.impl;
import shit.zen.event.EventMarker;
public class WorldChangeEvent
implements EventMarker {
}
@@ -0,0 +1,5 @@
package shit.zen.exception;
public class ModuleNotFoundException
extends RuntimeException {
}
@@ -0,0 +1,20 @@
package shit.zen.exception;
import java.io.PrintStream;
import java.io.PrintWriter;
public class SilentException
extends RuntimeException {
public SilentException() {
this.setStackTrace(new StackTraceElement[0]);
}
public void printStackTrace(PrintStream printStream) {
}
public void printStackTrace(PrintWriter printWriter) {
}
public void printStackTrace() {
}
}
@@ -0,0 +1,142 @@
package shit.zen.gui;
import java.awt.Color;
import shit.zen.ClientBase;
import shit.zen.ZenClient;
import shit.zen.event.impl.GlRenderEvent;
import shit.zen.render.FontPresets;
import shit.zen.render.FontRenderer;
import shit.zen.render.GlHelper;
import shit.zen.render.Paint;
import shit.zen.event.EventTarget;
public class IntroAnimation
extends ClientBase {
private static volatile boolean isActive = false;
private long startTime = -1L;
private boolean finished = false;
public IntroAnimation() {
isActive = true;
}
public static boolean isRunning() {
return isActive;
}
@EventTarget(value=4)
public void onRender(GlRenderEvent glRenderEvent) {
float f;
float f2;
long l;
if (this.finished) {
return;
}
if (this.startTime < 0L) {
this.startTime = System.currentTimeMillis();
}
long l2 = l = System.currentTimeMillis() - this.startTime;
float f3 = mc.getWindow().getGuiScaledWidth();
float f4 = mc.getWindow().getGuiScaledHeight();
float f5 = f3 / 2.0f;
float f6 = f4 / 2.0f;
long l3 = 1100L;
long l4 = l3 + 900L + 700L + 500L + 300L + 500L + 1300L;
if (l2 <= 800L) {
float fadeIn = IntroAnimation.easeOutCubic(IntroAnimation.clamp01((float)l2 / 800.0f));
f2 = 0.6f * fadeIn;
} else if (l2 <= l4) {
f2 = 0.6f;
} else if (l2 <= l4 + 700L) {
float fadeOut = 1.0f - IntroAnimation.easeInCubic(IntroAnimation.clamp01((float)(l2 - l4) / 700.0f));
f2 = 0.6f * fadeOut;
} else {
this.finish();
return;
}
Paint paint = GlHelper.toPaint(new Color(0, 0, 0, (int)(f2 * 255.0f)));
GlHelper.drawRect(0.0f, 0.0f, f3, f4, paint);
float f7 = 1.0f;
float f8 = 0.0f;
if (l2 >= l3) {
long l5 = l2 - l3;
if (l5 <= 900L) {
float f9 = IntroAnimation.easeOutCubic(IntroAnimation.clamp01((float)l5 / 900.0f));
f7 = IntroAnimation.lerp(2.0f, 1.0f, f9);
f8 = f9;
} else {
f7 = 1.0f;
f8 = 1.0f;
}
}
float f10 = 0.0f;
long l6 = l3 + 900L + 700L;
if (l2 > l6 && l2 <= l6 + 500L) {
f10 = IntroAnimation.easeOutCubic((float)(l2 - l6) / 500.0f);
} else if (l2 > l6 + 500L) {
f10 = 1.0f;
}
FontRenderer fontRenderer = FontPresets.axiformaBold(64.0f * f7);
FontRenderer fontRenderer2 = FontPresets.axiformaBold(64.0f);
float f11 = GlHelper.getStringWidth("Z", fontRenderer);
float f12 = GlHelper.getStringWidth("EN", fontRenderer2);
float f13 = f5 - f11 / 2.0f;
float f14 = f5 - (f11 + 0.0f + f12) / 2.0f;
float f15 = IntroAnimation.lerp(f13, f14, f10);
float f16 = f6 - fontRenderer.getMetrics().capHeight() / 2.0f;
float f17 = 0.0f;
float f18 = 12.0f;
long l7 = l6 + 500L + 300L;
if (l2 > l7 && l2 <= l7 + 500L) {
f17 = f = IntroAnimation.easeOutCubic((float)(l2 - l7) / 500.0f);
f18 = (1.0f - f) * 12.0f;
} else if (l2 > l7 + 500L) {
f17 = 1.0f;
f18 = 0.0f;
}
f = 1.0f;
if (l2 > l4) {
f = 1.0f - IntroAnimation.clamp01((float)(l2 - l4) / 700.0f);
}
int n = new Color(1.0f, 1.0f, 1.0f, IntroAnimation.clamp01(f8 * f)).getRGB();
GlHelper.drawText("Z", f15, f16, fontRenderer, n);
if (f17 > 0.0f) {
float f19 = f15 + f11 + 0.0f;
float f20 = f6 - fontRenderer2.getMetrics().capHeight() / 2.0f + f18;
int n2 = new Color(1.0f, 1.0f, 1.0f, IntroAnimation.clamp01(f17 * f)).getRGB();
GlHelper.drawText("EN", f19, f20, fontRenderer2, n2);
}
}
private void finish() {
if (!this.finished) {
this.finished = true;
try {
ZenClient.instance.getEventBus().unregister(this);
} catch (Throwable throwable) {
// empty catch block
}
isActive = false;
}
}
private static float clamp01(float f) {
return f < 0.0f ? 0.0f : (f > 1.0f ? 1.0f : f);
}
private static float lerp(float f, float f2, float f3) {
return f + (f2 - f) * f3;
}
private static float easeOutCubic(float f) {
float f2 = IntroAnimation.clamp01(f);
f2 = (float)(1.0 - Math.pow(1.0f - f2, 3.0));
return f2;
}
private static float easeInCubic(float f) {
float f2 = IntroAnimation.clamp01(f);
f2 = f2 * f2 * f2;
return f2;
}
}
+102
View File
@@ -0,0 +1,102 @@
package shit.zen.gui;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.NonNull;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.util.Mth;
import shit.zen.gui.newclickgui.CategoryPanel;
import shit.zen.modules.Category;
import shit.zen.utils.animation.SmoothAnimationTimer;
import shit.zen.utils.math.Easings;
public class NewClickGui
extends Screen {
private static final List<CategoryPanel> categoryPanels;
private static boolean initialized;
public static CategoryPanel focusedPanel;
@Getter
private boolean closing = false;
@Getter
private final SmoothAnimationTimer closeAnim = new SmoothAnimationTimer();
public NewClickGui() {
super(Component.literal("ClickGui"));
System.out.println("12");
}
protected void init() {
System.out.println("13");
focusedPanel = categoryPanels.get(0);
float f = (float)this.width / 2.0f - 380.0f;
for (CategoryPanel categoryPanel : categoryPanels) {
categoryPanel.setX(f);
categoryPanel.setY(36.0f);
f += 128.0f;
}
initialized = true;
System.out.println("14");
}
public void render(@NonNull GuiGraphics guiGraphics, int n, int n2, float f) {
if (guiGraphics == null) {
throw new NullPointerException("graphics is marked non-null but is null");
}
this.closeAnim.animate(this.closing ? 0.0 : 1.0, 0.2, Easings.EASE_OUT_POW2);
this.closeAnim.tick();
float f2 = this.closeAnim.getValueF();
if (Mth.equal(f2, 0.0f) && this.closing) {
this.closing = false;
super.onClose();
categoryPanels.forEach(CategoryPanel::reset);
return;
}
for (CategoryPanel categoryPanel : categoryPanels) {
categoryPanel.render(this, guiGraphics, guiGraphics.pose(), n, n2, f2, f);
}
}
public void onClose() {
this.closing = true;
}
public boolean mouseClicked(double d, double d2, int n) {
for (CategoryPanel categoryPanel : categoryPanels) {
if (!categoryPanel.mouseClicked(d, d2, n)) continue;
focusedPanel = categoryPanel;
return true;
}
return super.mouseClicked(d, d2, n);
}
public boolean mouseReleased(double d, double d2, int n) {
for (CategoryPanel categoryPanel : categoryPanels) {
categoryPanel.mouseReleased(d, d2, n);
}
return false;
}
public boolean isPauseScreen() {
return false;
}
public boolean mouseScrolled(double d, double d2, double d3) {
for (CategoryPanel categoryPanel : categoryPanels) {
if (!categoryPanel.mouseScrolled(d, d2, d3)) continue;
return true;
}
return false;
}
static {
NewClickGui newClickGui = new NewClickGui();
categoryPanels = new ArrayList<>();
initialized = false;
for (Category category : Category.values()) {
categoryPanels.add(new CategoryPanel(category));
}
}
}
@@ -0,0 +1,75 @@
package shit.zen.gui;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import shit.zen.ZenClient;
import shit.zen.gui.legacy.CategoryPanel;
import shit.zen.gui.legacy.ModuleButton;
import shit.zen.modules.Category;
public class OldClickGui
extends Screen {
private final List<CategoryPanel> categoryPanels = new ArrayList<>();
private static final String TITLE = "Click GUI";
public OldClickGui() {
super(Component.nullToEmpty(TITLE));
int n = 20;
for (Category category : Category.values()) {
this.categoryPanels.add(new CategoryPanel(n, 20, 140, 20, category));
n += 160;
}
}
public void init() {
super.init();
for (CategoryPanel categoryPanel : this.categoryPanels) {
for (ModuleButton moduleButton : categoryPanel.moduleButtons) {
moduleButton.reset();
}
}
}
public void render(GuiGraphics guiGraphics, int n, int n2, float f) {
for (CategoryPanel categoryPanel : this.categoryPanels) {
categoryPanel.render(guiGraphics, n, n2, f);
categoryPanel.mouseDragged(n, n2);
}
super.render(guiGraphics, n, n2, f);
}
public boolean mouseReleased(double d, double d2, int n) {
for (CategoryPanel categoryPanel : this.categoryPanels) {
categoryPanel.mouseReleased(d, d2, n);
}
return super.mouseReleased(d, d2, n);
}
public boolean mouseClicked(double d, double d2, int n) {
for (CategoryPanel categoryPanel : this.categoryPanels) {
categoryPanel.mouseClicked(d, d2, n);
}
return true;
}
public boolean mouseScrolled(double d, double d2, double d3) {
for (CategoryPanel categoryPanel : this.categoryPanels) {
categoryPanel.mouseScrolled(d, d2, d3);
}
return true;
}
public void onClose() {
if (ZenClient.isReady()) {
ZenClient.instance.getConfigManager().saveAll();
}
super.onClose();
}
static {
OldClickGui oldClickGui = new OldClickGui();
}
}
@@ -0,0 +1,461 @@
package shit.zen.gui;
import java.awt.Color;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.Nonnull;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import shit.zen.ZenClient;
import shit.zen.gui.panel.CategoryBar;
import shit.zen.gui.panel.KeybindOverlay;
import shit.zen.gui.panel.ModuleListPanel;
import shit.zen.gui.panel.ProfileWidget;
import shit.zen.gui.panel.ScaleSwitchOverlay;
import shit.zen.gui.panel.SettingsPanel;
import shit.zen.gui.panel.setting.NumberSettingRenderer;
import shit.zen.modules.Category;
import shit.zen.modules.Module;
import shit.zen.render.FontPresets;
import shit.zen.render.FontRenderer;
import shit.zen.render.GlHelper;
import shit.zen.render.Renderer;
import shit.zen.render.TextGlow;
import shit.zen.utils.math.LerpUtil;
import shit.zen.utils.render.RenderUtil;
public class PanelClickGui
extends Screen {
public enum OpenState {
CLOSED, OPENING, OPEN, CLOSING
}
public enum ScaleSwitchState {
IDLE, FADING_OUT, WAITING, FADING_IN
}
public static final class ToastEntry {
final String message;
final long createdAt;
float currentY;
float targetY;
float alpha;
public ToastEntry(String message) {
this.message = message;
this.createdAt = System.currentTimeMillis();
this.currentY = 20.0f;
this.targetY = 0.0f;
this.alpha = 0.0f;
}
}
public static PanelClickGui Đ;
private boolean searchActive = false;
private boolean searchFocused = false;
private String searchQuery = "";
private long searchCursorTime = 0L;
private final List<PanelClickGui.ToastEntry> toasts = new CopyOnWriteArrayList<>();
private PanelClickGui.OpenState currentScaleSwitchState = PanelClickGui.OpenState.CLOSED;
private float openProgress = 0.0f;
private float currentScale = 1.0f;
private final ProfileWidget profileWidget;
private final CategoryBar categoryBar;
private final ModuleListPanel moduleListPanel;
private final SettingsPanel settingsPanel;
public final KeybindOverlay keybindOverlay = new KeybindOverlay();
private final ScaleSwitchOverlay scaleSwitchOverlay = new ScaleSwitchOverlay();
private PanelClickGui.ScaleSwitchState currentOpenState = PanelClickGui.ScaleSwitchState.IDLE;
private long scaleWaitStart = 0L;
private float targetScale = 1.0f;
private float panelAlpha = 1.0f;
protected PanelClickGui() {
super(Component.nullToEmpty("New Click GUI"));
this.profileWidget = new ProfileWidget(this::setScale);
this.categoryBar = new CategoryBar();
this.moduleListPanel = new ModuleListPanel();
this.settingsPanel = new SettingsPanel();
}
public void setScale(float f) {
if (this.currentOpenState == PanelClickGui.ScaleSwitchState.IDLE && f != this.currentScale) {
this.targetScale = f;
this.currentOpenState = PanelClickGui.ScaleSwitchState.FADING_OUT;
this.scaleSwitchOverlay.show(this.currentScale, f);
}
}
public void init() {
super.init();
LerpUtil.reset();
if (this.currentScaleSwitchState == PanelClickGui.OpenState.CLOSED) {
this.openProgress = 0.0f;
}
this.currentScaleSwitchState = PanelClickGui.OpenState.OPENING;
}
private void updateOpenState() {
if (this.currentScaleSwitchState == PanelClickGui.OpenState.OPENING) {
this.openProgress = LerpUtil.lerp(this.openProgress, 1.0f, 0.08f);
if (this.openProgress >= 1.0f) {
this.currentScaleSwitchState = PanelClickGui.OpenState.OPEN;
}
} else if (this.currentScaleSwitchState == PanelClickGui.OpenState.CLOSING) {
this.openProgress = LerpUtil.lerp(this.openProgress, 0.0f, 0.1f);
if (this.openProgress <= 0.0f) {
this.currentScaleSwitchState = PanelClickGui.OpenState.CLOSED;
if (ZenClient.isReady()) {
ZenClient.instance.getConfigManager().saveAll();
}
this.minecraft.setScreen(null);
}
}
}
private float easeOutCubic(float f) {
return (float)(1.0 - Math.pow(1.0f - f, 3.0));
}
public void render(@Nonnull GuiGraphics guiGraphics, int n, int n2, float f) {
float f2;
LerpUtil.update();
this.updateOpenState();
if (this.currentScaleSwitchState == PanelClickGui.OpenState.CLOSED && this.openProgress <= 0.0f) {
return;
}
float f3 = f2 = this.easeOutCubic(this.openProgress);
float f4 = 0.98f + 0.02f * f2;
guiGraphics.fill(0, 0, this.width, this.height, new Color(0, 0, 0, (int)(80.0f * f3)).getRGB());
this.updateScaleSwitchState();
int n3 = this.width / 2;
int n4 = this.height / 2;
guiGraphics.pose().pushPose();
guiGraphics.pose().translate((float)n3, (float)n4, 0.0f);
guiGraphics.pose().scale(f4, f4, 1.0f);
guiGraphics.pose().translate((float)(-n3), (float)(-n4), 0.0f);
float f5 = this.currentOpenState == PanelClickGui.ScaleSwitchState.FADING_OUT || this.currentOpenState == PanelClickGui.ScaleSwitchState.WAITING ? this.targetScale : this.currentScale;
int n5 = (int)(600.0f * this.currentScale);
int n6 = (int)(400.0f * this.currentScale);
int n7 = n3 - n5 / 2;
int n8 = n4 - n6 / 2;
float f6 = this.panelAlpha * f3;
if (f6 > 0.005f) {
this.drawPanelGlow(guiGraphics, n7, n8, f, f6);
this.categoryBar.render(guiGraphics, n7, n8, n, n2, this.currentScale, f6);
this.moduleListPanel.render(guiGraphics, n7, n8, n, n2, this.getSelectedCategory(), this.currentScale, f6);
this.settingsPanel.render(guiGraphics, n7, n8, n, n2, this.moduleListPanel.getHoveredModule(), this.currentScale, f6);
this.profileWidget.render(guiGraphics, n7, n8, n, n2, this.currentScale, f6);
this.drawSearchBar(guiGraphics, n7, n8, n, n2, f6);
this.drawToasts(guiGraphics, n7, n8, f6);
}
super.render(guiGraphics, n, n2, f);
guiGraphics.pose().popPose();
this.keybindOverlay.render(guiGraphics, this.width, this.height, f5);
this.scaleSwitchOverlay.render(guiGraphics, this.width, this.height, f5);
}
private void updateScaleSwitchState() {
switch (this.currentOpenState) {
case FADING_OUT: {
this.panelAlpha = LerpUtil.lerp(this.panelAlpha, 0.0f, 0.08f);
if (!(this.panelAlpha <= 0.0f)) break;
this.currentOpenState = PanelClickGui.ScaleSwitchState.WAITING;
this.scaleWaitStart = System.currentTimeMillis();
break;
}
case WAITING: {
if (System.currentTimeMillis() - this.scaleWaitStart <= 3000L) break;
this.currentScale = this.targetScale;
this.currentOpenState = PanelClickGui.ScaleSwitchState.FADING_IN;
this.scaleSwitchOverlay.hide();
break;
}
case FADING_IN: {
this.panelAlpha = LerpUtil.lerp(this.panelAlpha, 1.0f, 0.08f);
if (!(this.panelAlpha >= 1.0f) || !this.scaleSwitchOverlay.isFullyHidden()) break;
this.currentOpenState = PanelClickGui.ScaleSwitchState.IDLE;
}
}
}
private void drawPanelGlow(GuiGraphics guiGraphics, int n, int n2, float f, float f2) {
int n3 = (int)(600.0f * this.currentScale);
int n4 = (int)(400.0f * this.currentScale);
TextGlow.drawBackground(guiGraphics.pose(), n, n2, n3, n4, 12.0f * this.currentScale, f2);
}
public boolean mouseClicked(double d, double d2, int n) {
boolean bl;
if (this.openProgress < 1.0f) {
return true;
}
if (this.keybindOverlay.isVisible()) {
if (n == 0) {
this.keybindOverlay.cancel();
}
return true;
}
int n2 = this.width / 2;
int n3 = this.height / 2;
int n4 = (int)(600.0f * this.currentScale);
int n5 = (int)(400.0f * this.currentScale);
int n6 = n2 - n4 / 2;
int n7 = n3 - n5 / 2;
if (this.profileWidget.isPopupOpen() && this.profileWidget.onMouseClick(n6, n7, (int)d, (int)d2, this.currentScale)) {
return true;
}
int n8 = (int)(200.0f * this.currentScale);
int n9 = (int)(20.0f * this.currentScale);
int n10 = n6 + (n4 - n8) / 2;
int n11 = n7 + n5 + (int)(15.0f * this.currentScale);
boolean bl2 = bl = d >= (double)n10 && d <= (double)(n10 + n8) && d2 >= (double)n11 && d2 <= (double)(n11 + n9);
if (bl) {
if (!this.searchActive) {
this.searchActive = true;
this.searchQuery = "";
this.moduleListPanel.setSearchQuery("");
}
this.searchFocused = true;
this.searchCursorTime = System.currentTimeMillis();
return true;
}
this.searchFocused = false;
boolean bl3 = false;
if (n == 0 || n == 1 || n == 2) {
if (!bl3 && n == 0 && this.categoryBar.onMouseClick(n6, n7, (int)d, (int)d2, this.currentScale)) {
if (this.searchActive) {
this.searchActive = false;
this.searchFocused = false;
this.searchQuery = "";
this.moduleListPanel.setSearchQuery(null);
}
bl3 = true;
}
if (!bl3 && this.moduleListPanel.onMouseClick(n6, n7, (int)d, (int)d2, this.getSelectedCategory(), n, this.currentScale)) {
bl3 = true;
}
if (!bl3 && this.profileWidget.onMouseClick(n6, n7, (int)d, (int)d2, this.currentScale)) {
bl3 = true;
}
if (!bl3 && (n == 0 || n == 1) && this.settingsPanel.onMouseClick(n6, n7, (int)d, (int)d2, n, this.currentScale)) {
bl3 = true;
}
}
if (!bl3) {
NumberSettingRenderer.clearEditing();
}
return bl3 || super.mouseClicked(d, d2, n);
}
public boolean mouseReleased(double d, double d2, int n) {
if (this.openProgress < 1.0f) {
return true;
}
this.moduleListPanel.onMouseRelease();
this.settingsPanel.onMouseRelease(d, d2, n);
this.profileWidget.onMouseRelease();
return super.mouseReleased(d, d2, n);
}
public boolean mouseScrolled(double d, double d2, double d3) {
if (this.openProgress < 1.0f) {
return true;
}
int n = this.width / 2;
int n2 = n - (int)(600.0f * this.currentScale) / 2;
int n3 = this.height / 2;
int n4 = n3 - (int)(400.0f * this.currentScale) / 2;
if (this.moduleListPanel.isMouseOverPanel(n2, n4, (int)d, (int)d2, this.currentScale)) {
this.moduleListPanel.onScroll(d3, this.currentScale);
return true;
}
if (this.settingsPanel.isMouseOverPanel(n2, n4, (int)d, (int)d2, this.currentScale)) {
this.settingsPanel.onScroll(d3, this.currentScale);
return true;
}
return super.mouseScrolled(d, d2, d3);
}
public boolean mouseDragged(double d, double d2, int n, double d3, double d4) {
if (this.openProgress < 1.0f) {
return true;
}
this.moduleListPanel.onMouseDrag(d, d2, this.currentScale);
this.settingsPanel.onMouseDrag(d, d2, this.currentScale);
this.profileWidget.onMouseDrag((int)d, (int)d2);
return super.mouseDragged(d, d2, n, d3, d4);
}
public boolean keyPressed(int n, int n2, int n3) {
if (this.keybindOverlay.onKeyPress(n, n2, n3)) {
return true;
}
if (this.searchActive) {
if (n == 256) {
this.searchActive = false;
this.searchFocused = false;
this.searchQuery = "";
this.moduleListPanel.setSearchQuery(null);
return true;
}
if (this.searchFocused) {
this.searchCursorTime = System.currentTimeMillis();
if (n == 259) {
if (!this.searchQuery.isEmpty()) {
this.searchQuery = this.searchQuery.substring(0, this.searchQuery.length() - 1);
this.moduleListPanel.setSearchQuery(this.searchQuery);
}
return true;
}
}
}
if (NumberSettingRenderer.onKeyPress(n, n2, n3)) {
return true;
}
if (n == 256 && !this.keybindOverlay.isVisible() && !this.searchActive) {
this.onClose();
return true;
}
return super.keyPressed(n, n2, n3);
}
public boolean charTyped(char c, int n) {
if (this.searchActive && this.searchFocused) {
this.searchCursorTime = System.currentTimeMillis();
this.searchQuery = this.searchQuery + c;
this.moduleListPanel.setSearchQuery(this.searchQuery);
return true;
}
if (NumberSettingRenderer.onCharTyped(c)) {
return true;
}
return super.charTyped(c, n);
}
public boolean isPauseScreen() {
return false;
}
public void onClose() {
if (this.currentScaleSwitchState != PanelClickGui.OpenState.CLOSING) {
this.currentScaleSwitchState = PanelClickGui.OpenState.CLOSING;
}
}
public Category getSelectedCategory() {
return this.categoryBar.getSelectedCategory();
}
public CategoryBar getCategoryBar() {
return this.categoryBar;
}
public ModuleListPanel getModuleListPanel() {
return this.moduleListPanel;
}
public SettingsPanel getSettingsPanel() {
return this.settingsPanel;
}
private void drawSearchBar(GuiGraphics guiGraphics, int n, int n2, int n3, int n4, float f) {
try {
int n5 = (int)(600.0f * this.currentScale);
int n6 = (int)(400.0f * this.currentScale);
int n7 = (int)(200.0f * this.currentScale);
int n8 = (int)(20.0f * this.currentScale);
int n9 = n + (n5 - n7) / 2;
int n10 = n2 + n6 + (int)(15.0f * this.currentScale);
TextGlow.drawBackground(guiGraphics.pose(), n9, n10, n7, n8, 8.0f * this.currentScale, f);
Renderer.renderConsumer((drawContext -> {
FontRenderer fontRenderer = FontPresets.materialIcons(20.0f * this.currentScale);
String string = "";
float f2 = (float)n9 + 12.0f * this.currentScale;
float f3 = (float)n10 + (float)n8 / 2.0f + fontRenderer.getMetrics().capHeight() / 2.0f - 12.0f * this.currentScale;
int iconColor = new Color(255, 255, 255, (int)(180.0f * f)).getRGB();
TextGlow.drawGlowText(string, f2, f3, fontRenderer, -2236963, iconColor, 12.0f * this.currentScale);
FontRenderer fontRenderer2 = FontPresets.axiformaRegular(16.0f * this.currentScale);
if (this.searchActive || !this.searchQuery.isEmpty()) {
float f4 = (float)n9 + 35.0f * this.currentScale;
float f5 = (float)n10 + (float)n8 / 2.0f + fontRenderer2.getMetrics().capHeight() / 2.0f - 9.0f * this.currentScale;
int queryColor = new Color(255, 255, 255, (int)(120.0f * f)).getRGB();
TextGlow.drawGlowText(this.searchQuery, f4, f5, fontRenderer2, -1, queryColor, 8.0f * this.currentScale);
if (this.searchFocused) {
long l = System.currentTimeMillis() - this.searchCursorTime;
float f6 = (float)(Math.sin((double)l / 200.0) * 0.5 + 0.5);
int cursorColor = (int)(f6 * f * 255.0f) << 24 | 0xFFFFFF;
float f7 = f4 + GlHelper.getStringWidth(this.searchQuery, fontRenderer2) + 2.0f * this.currentScale;
float f8 = fontRenderer2.getMetrics().capHeight();
RenderUtil.drawFilledRect(guiGraphics.pose(), f7, f5 - f8 + 11.0f * this.currentScale, this.currentScale, f8 - 3.0f * this.currentScale, cursorColor);
}
} else {
FontRenderer fontRenderer3 = FontPresets.axiformaBold(14.0f * this.currentScale);
String string2 = "search";
float f9 = GlHelper.getStringWidth(string2, fontRenderer3);
float f10 = (float)n9 + ((float)n7 - f9) / 2.0f;
float f11 = (float)n10 + (float)n8 / 2.0f + fontRenderer3.getMetrics().capHeight() / 2.0f - 8.0f * this.currentScale;
TextGlow.drawGlowText(string2, f10, f11, fontRenderer3, -3355444, new Color(255, 255, 255, (int)(130.0f * f)).getRGB(), 10.0f * this.currentScale);
}
}));
} catch (Exception exception) {
// empty catch block
}
}
public void addToast(String string) {
for (PanelClickGui.ToastEntry panelClickGui$ToastEntry : this.toasts) {
panelClickGui$ToastEntry.targetY -= 20.0f * this.currentScale;
}
this.toasts.add(new PanelClickGui.ToastEntry(string));
}
public void selectModule(Module module) {
this.keybindOverlay.startBinding(module);
}
private void drawToasts(GuiGraphics guiGraphics, int n, int n2, float f) {
if (this.toasts.isEmpty()) {
return;
}
try {
Renderer.renderConsumer((drawContext -> {
FontRenderer fontRenderer = FontPresets.axiformaBold(18.0f * this.currentScale);
for (PanelClickGui.ToastEntry panelClickGui$ToastEntry : this.toasts) {
long l = System.currentTimeMillis() - panelClickGui$ToastEntry.createdAt;
panelClickGui$ToastEntry.currentY = LerpUtil.smoothLerp(panelClickGui$ToastEntry.currentY, panelClickGui$ToastEntry.targetY, 0.2f);
float f2 = 0.0f;
if (l < 2000L) {
f2 = 1.0f;
} else if (l < 2500L) {
long l2 = l - 2000L;
f2 = 1.0f - (float)l2 / 500.0f;
}
panelClickGui$ToastEntry.alpha = LerpUtil.smoothLerp(panelClickGui$ToastEntry.alpha, f2, 0.25f);
if (panelClickGui$ToastEntry.alpha < 0.01f && l > 2000L) {
this.toasts.remove(panelClickGui$ToastEntry);
continue;
}
float f3 = GlHelper.getStringWidth(panelClickGui$ToastEntry.message, fontRenderer);
int n3 = (int)(600.0f * this.currentScale);
float f4 = (float)n + ((float)n3 - f3) / 2.0f;
float f5 = (float)(n2 - 25) + panelClickGui$ToastEntry.currentY;
int n4 = (int)(255.0f * panelClickGui$ToastEntry.alpha * f);
int n5 = n4 << 24 | 0xFFFFFF;
int n6 = (int)(120.0f * panelClickGui$ToastEntry.alpha * f);
int n7 = n6 << 24 | 0xFFFFFF;
TextGlow.drawGlowText(panelClickGui$ToastEntry.message, f4, f5 + 6.0f * this.currentScale, fontRenderer, n5, n7, 8.0f * this.currentScale);
}
}));
} catch (Exception exception) {
// empty catch block
}
}
static {
PanelClickGui panelClickGui = new PanelClickGui();
}
}
@@ -0,0 +1,68 @@
package shit.zen.gui.legacy;
import com.mojang.blaze3d.vertex.PoseStack;
import java.awt.Color;
import shit.zen.gui.legacy.ModuleButton;
import shit.zen.gui.legacy.SettingComponent;
import shit.zen.render.FontStore;
import shit.zen.settings.Setting;
import shit.zen.settings.impl.BooleanSetting;
import shit.zen.utils.render.RenderUtil;
public class BooleanComponent
extends SettingComponent {
private final BooleanSetting booleanSetting;
private float toggleAnim = 0.0f;
private final float animSpeed = 0.2f;
public BooleanComponent(Setting<?> setting, ModuleButton moduleButton, int n) {
super(setting, moduleButton, n);
this.booleanSetting = (BooleanSetting)setting;
this.toggleAnim = this.booleanSetting.getValue() != false ? 1.0f : 0.0f;
}
@Override
public void renderWithAlpha(PoseStack poseStack, int n, int n2, float f, float f2) {
float f3;
float f4 = f3 = this.booleanSetting.getValue() != false ? 1.0f : 0.0f;
this.toggleAnim = Math.abs(this.toggleAnim - f3) > 0.01f ? (this.toggleAnim += (f3 - this.toggleAnim) * 0.2f) : f3;
int n3 = this.parentButton.panel.y + this.parentButton.yOffset + this.parentButton.panel.rowHeight + this.yOffset;
int n4 = 4;
int n5 = this.parentButton.panel.rowHeight - n4 * 2;
int n6 = this.parentButton.panel.x;
int n7 = this.parentButton.panel.width;
int n8 = 8;
String string = this.booleanSetting.getName();
float f5 = (float)(n3 + n4) + ((float)n5 - FontStore.OPENSANS_16.getFontHeight()) / 2.0f;
int n9 = new Color(255, 255, 255, (int)(255.0f * f2)).getRGB();
FontStore.OPENSANS_16.drawStringWithShadow(poseStack, string, n6 + n8, f5, n9);
int n10 = 18;
int n11 = 8;
int n12 = n6 + n7 - n8 - n10;
int n13 = n3 + n4 + (n5 - n11) / 2 + 2;
Color color = this.booleanSetting.getValue() != false ? new Color(138, 180, 248, (int)(200.0f * f2)) : new Color(100, 100, 100, (int)(180.0f * f2));
RenderUtil.drawFilledRect(poseStack, n12, n13, n10, n11, color.getRGB());
float f6 = 7.0f;
float f7 = n11 + 4;
float f8 = (float)(n12 + 1) + ((float)n10 - f6 - 2.0f) * this.toggleAnim;
float f9 = n13 - 2;
RenderUtil.drawFilledRect(poseStack, f8, f9, f6, f7, new Color(160, 195, 255, (int)(255.0f * f2)).getRGB());
}
@Override
public void mouseClicked(double d, double d2, int n) {
if (this.isHovered(d, d2) && n == 0) {
boolean bl = this.booleanSetting.getValue();
this.booleanSetting.setValue(!bl);
if (bl != this.booleanSetting.getValue()) {
this.parentButton.panel.recalcLayout();
}
}
super.mouseClicked(d, d2, n);
}
@Override
public void mouseReleased(double d, double d2, int n) {
super.mouseReleased(d, d2, n);
}
}
@@ -0,0 +1,156 @@
package shit.zen.gui.legacy;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.GuiGraphics;
import shit.zen.ZenClient;
import shit.zen.gui.legacy.ModuleButton;
import shit.zen.modules.Category;
import shit.zen.modules.Module;
import shit.zen.render.FontStore;
import shit.zen.utils.render.RenderUtil;
public class CategoryPanel {
public int x;
public int y;
public int dragOffsetX;
public int dragOffsetY;
public int width;
public int rowHeight;
public Category category;
public boolean dragging;
public boolean expanded;
public List<ModuleButton> moduleButtons;
private float[] targetOffsets;
private float[] currentOffsets;
private final float lerpFactor = 0.2f;
private long lastTime = System.currentTimeMillis();
private boolean needsLayout = false;
public CategoryPanel(int n, int n2, int n3, int n4, Category category) {
this.x = n;
this.y = n2;
this.width = n3;
this.rowHeight = n4;
this.category = category;
this.dragging = false;
this.expanded = false;
this.moduleButtons = new ArrayList<>();
int n5 = n4;
for (Module module : ZenClient.getInstance().getModuleManager().getModulesByCategory(category)) {
this.moduleButtons.add(new ModuleButton(module, this, n5));
n5 += n4;
}
this.initOffsets();
}
private void initOffsets() {
this.targetOffsets = new float[this.moduleButtons.size()];
this.currentOffsets = new float[this.moduleButtons.size()];
for (int i = 0; i < this.moduleButtons.size(); ++i) {
this.targetOffsets[i] = this.rowHeight + i * this.rowHeight;
this.currentOffsets[i] = this.rowHeight + i * this.rowHeight;
}
}
public void tick() {
if (!this.needsLayout) {
return;
}
boolean bl = false;
long l = System.currentTimeMillis();
float f = (float)(l - this.lastTime) / 1000.0f;
this.lastTime = l;
for (ModuleButton moduleButton : this.moduleButtons) {
if (!moduleButton.isAnimating()) continue;
bl = true;
}
for (int i = 0; i < this.moduleButtons.size(); ++i) {
float f2 = this.targetOffsets[i] - this.currentOffsets[i];
if (Math.abs(f2) > 0.5f) {
int n = i;
this.currentOffsets[n] = this.currentOffsets[n] + f2 * 0.2f * (f * 60.0f);
bl = true;
this.moduleButtons.get(i).yOffset = (int)this.currentOffsets[i];
continue;
}
this.currentOffsets[i] = this.targetOffsets[i];
this.moduleButtons.get(i).yOffset = (int)this.targetOffsets[i];
}
this.needsLayout = bl;
}
public void render(GuiGraphics guiGraphics, int n, int n2, float f) {
this.tick();
RenderUtil.drawFilledRect(guiGraphics.pose(), this.x, this.y, this.width, this.rowHeight, new Color(16, 16, 20, 245).getRGB());
String string = String.valueOf(switch (this.category) {
case COMBAT -> 'a';
case MOVEMENT -> 'b';
case PLAYER -> 'c';
case RENDER -> 'd';
case EXPLOIT -> 'e';
default -> '?';
});
float f2 = (float)this.y + ((float)this.rowHeight / 2.0f - FontStore.ICON_30.getFontHeight() / 2.0f) + 3.0f;
FontStore.ICON_30.drawStringWithShadow(guiGraphics.pose(), string, this.x + 4, f2, -1);
float f3 = (float)this.y + ((float)this.rowHeight / 2.0f - FontStore.OPENSANS_18.getFontHeight() / 2.0f) - 0.5f;
FontStore.OPENSANS_18.drawStringWithShadow(guiGraphics.pose(), this.category.displayName, this.x + this.rowHeight + 4, f3, -1);
for (ModuleButton moduleButton : this.moduleButtons) {
moduleButton.render(guiGraphics.pose(), n, n2, f);
}
}
public void mouseClicked(double d, double d2, int n) {
if (this.isHovered(d, d2)) {
if (n == 0) {
this.dragging = true;
this.dragOffsetX = (int)(d - (double)this.x);
this.dragOffsetY = (int)(d2 - (double)this.y);
} else if (n == 1) {
this.expanded = !this.expanded;
this.recalcLayout();
}
}
for (ModuleButton moduleButton : this.moduleButtons) {
moduleButton.mouseClicked(d, d2, n);
}
}
public void mouseReleased(double d, double d2, int n) {
for (ModuleButton moduleButton : this.moduleButtons) {
moduleButton.mouseReleased(d, d2, n);
}
if (n == 0 && this.dragging) {
this.dragging = false;
}
}
public void mouseScrolled(double d, double d2, double d3) {
for (ModuleButton moduleButton : this.moduleButtons) {
moduleButton.mouseScrolled(d, d2, d3);
}
}
public boolean isHovered(double d, double d2) {
return d > (double)this.x && d < (double)(this.x + this.width) && d2 > (double)this.y && d2 < (double)(this.y + this.rowHeight);
}
public void mouseDragged(double d, double d2) {
if (this.dragging) {
this.x = (int)(d - (double)this.dragOffsetX);
this.y = (int)(d2 - (double)this.dragOffsetY);
}
}
public void recalcLayout() {
int n = this.rowHeight;
for (int i = 0; i < this.moduleButtons.size(); ++i) {
ModuleButton moduleButton = this.moduleButtons.get(i);
this.targetOffsets[i] = n;
n += moduleButton.getTotalHeight();
}
this.needsLayout = true;
this.lastTime = System.currentTimeMillis();
}
}
@@ -0,0 +1,139 @@
package shit.zen.gui.legacy;
import com.mojang.blaze3d.vertex.PoseStack;
import java.awt.Color;
import lombok.Getter;
import shit.zen.gui.legacy.ModuleButton;
import shit.zen.gui.legacy.SettingComponent;
import shit.zen.render.FontStore;
import shit.zen.settings.Setting;
import shit.zen.settings.impl.ModeSetting;
import shit.zen.utils.render.RenderUtil;
public class ModeComponent
extends SettingComponent {
private final ModeSetting modeSetting;
@Getter
private boolean dropdownOpen = false;
public ModeComponent(Setting<?> setting, ModuleButton moduleButton, int n) {
super(setting, moduleButton, n);
this.modeSetting = (ModeSetting)setting;
}
@Override
public void renderWithAlpha(PoseStack poseStack, int n, int n2, float f, float f2) {
int n3 = this.parentButton.panel.y + this.parentButton.yOffset + this.parentButton.panel.rowHeight + this.yOffset + 3;
int n4 = this.parentButton.panel.x;
int n5 = this.parentButton.panel.width;
int n6 = this.parentButton.panel.rowHeight;
int n7 = 4;
int n8 = n6 - n7 * 2;
int n9 = 8;
int n10 = 4;
int n11 = n4 + n9 + n10;
int n12 = n5 - (n9 + n10) * 2;
int n13 = new Color(255, 255, 255, (int)(255.0f * f2)).getRGB();
boolean bl = n >= n11 && n <= n11 + n12 && n2 >= n3 + n7 && n2 <= n3 + n7 + n8;
Color color = bl && !this.dropdownOpen ? new Color(45, 45, 45, (int)(180.0f * f2)) : new Color(25, 25, 25, (int)(150.0f * f2));
RenderUtil.drawFilledRect(poseStack, n11, n3 + n7, n12, n8, color.getRGB());
Color color2 = new Color(100, 100, 100, (int)(180.0f * f2));
RenderUtil.drawFilledRect(poseStack, n4 + n9 + 2, n3 + n7, n10 - 2, n8, color2.getRGB());
RenderUtil.drawFilledRect(poseStack, n4 + n5 - n9 - n10, n3 + n7, n10 - 2, n8, color2.getRGB());
String string = this.modeSetting.getName();
float f3 = (float)(n3 + n7) + ((float)n8 - FontStore.OPENSANS_16.getFontHeight()) / 2.0f - 1.5f;
FontStore.OPENSANS_16.drawStringWithShadow(poseStack, string, n11 + n10, f3, n13);
String string2 = this.modeSetting.getValue();
float f4 = (float)(n11 + n12) - FontStore.OPENSANS_16.getStringWidth(string2) - (float)n10;
FontStore.OPENSANS_16.drawStringWithShadow(poseStack, string2, f4, f3, new Color(138, 180, 248).getRGB());
if (this.dropdownOpen) {
int n14 = n3 + n7 + n8;
int n15 = this.getDropdownHeight();
RenderUtil.drawFilledRect(poseStack, n11, n14, n12, n15, new Color(33, 33, 33, 150).getRGB());
String[] stringArray = this.getModes();
for (int i = 0; i < stringArray.length; ++i) {
boolean bl2;
String string3 = stringArray[i];
float f5 = n14 + i * n8;
boolean bl3 = bl2 = n >= n11 && n <= n11 + n12 && (float)n2 >= f5 && (float)n2 < f5 + (float)n8;
if (bl2) {
RenderUtil.drawFilledRect(poseStack, n11, f5, n12, n8, new Color(0, 0, 0, 100).getRGB());
}
float f6 = FontStore.OPENSANS_16.getStringWidth(string3);
float f7 = (float)n11 + ((float)n12 - f6) / 2.0f;
float f8 = f5 + ((float)n8 - FontStore.OPENSANS_16.getFontHeight()) / 2.0f;
boolean bl4 = string3.equals(this.modeSetting.getValue());
FontStore.OPENSANS_16.drawStringWithShadow(poseStack, string3, f7, f8, bl4 ? new Color(138, 180, 248).getRGB() : n13);
}
}
}
@Override
public void mouseClicked(double d, double d2, int n) {
int n2;
int n3 = this.parentButton.panel.y + this.parentButton.yOffset + this.parentButton.panel.rowHeight + this.yOffset + 3;
int n4 = this.parentButton.panel.rowHeight;
int n5 = 4;
int n6 = n4 - n5 * 2;
int n7 = this.parentButton.panel.x;
int n8 = this.parentButton.panel.width;
int n9 = 8;
int n10 = 4;
int n11 = n7 + n9 + n10;
int n12 = n8 - (n9 + n10) * 2;
String[] stringArray = this.modeSetting.getModes();
if (this.dropdownOpen) {
n2 = n3 + n5 + n6;
int n13 = this.getDropdownHeight();
if (d >= (double)n11 && d <= (double)(n11 + n12) && d2 >= (double)n2 && d2 < (double)(n2 + n13)) {
int n14 = (int)((d2 - (double)n2) / (double)n6);
if (n14 >= 0 && n14 < stringArray.length) {
this.modeSetting.setValue(stringArray[n14]);
this.dropdownOpen = false;
this.parentButton.panel.recalcLayout();
}
return;
}
}
int n15 = n2 = d >= (double)n11 && d <= (double)(n11 + n12) && d2 >= (double)(n3 + n5) && d2 <= (double)(n3 + n5 + n6) ? 1 : 0;
if (n2 != 0 && (n == 0 || n == 1)) {
this.dropdownOpen = !this.dropdownOpen;
this.parentButton.panel.recalcLayout();
}
}
@Override
public boolean isHovered(double d, double d2) {
boolean bl;
int n = this.parentButton.panel.y + this.parentButton.yOffset + this.parentButton.panel.rowHeight + this.yOffset;
int n2 = this.parentButton.panel.x;
int n3 = this.parentButton.panel.width;
int n4 = this.parentButton.panel.rowHeight;
boolean bl2 = bl = d >= (double)n2 && d <= (double)(n2 + n3) && d2 >= (double)n && d2 <= (double)(n + n4);
if (bl) {
return true;
}
if (this.dropdownOpen) {
int n5 = n + n4;
int n6 = this.getDropdownHeight();
return d >= (double)n2 && d <= (double)(n2 + n3) && d2 >= (double)n5 && d2 <= (double)(n5 + n6);
}
return false;
}
@Override
public void mouseReleased(double d, double d2, int n) {
super.mouseReleased(d, d2, n);
}
public int getDropdownHeight() {
int n = 4;
int n2 = this.parentButton.panel.rowHeight - n * 2;
return n2 * this.modeSetting.getModes().length;
}
public String[] getModes() {
return this.modeSetting.getModes();
}
}
@@ -0,0 +1,210 @@
package shit.zen.gui.legacy;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import shit.zen.gui.legacy.BooleanComponent;
import shit.zen.gui.legacy.CategoryPanel;
import shit.zen.gui.legacy.ModeComponent;
import shit.zen.gui.legacy.MultiSelectComponent;
import shit.zen.gui.legacy.NumberComponent;
import shit.zen.gui.legacy.SettingComponent;
import shit.zen.modules.Module;
import shit.zen.render.FontStore;
import shit.zen.settings.Setting;
import shit.zen.settings.impl.BooleanSetting;
import shit.zen.settings.impl.ModeSetting;
import shit.zen.settings.impl.MultiSelectSetting;
import shit.zen.settings.impl.NumberSetting;
import shit.zen.utils.animation.SmoothAnimationTimer;
import shit.zen.utils.math.Easings;
import shit.zen.utils.render.ColorUtil;
import shit.zen.utils.render.RenderUtil;
public class ModuleButton {
public Module module;
public CategoryPanel panel;
public int yOffset;
public List<SettingComponent> settingComponents;
public boolean expanded;
private final SmoothAnimationTimer expandAnim;
private float hoverProgress = 0.0f;
private final float hoverSpeed = 4.0f;
private long lastTime = System.currentTimeMillis();
public ModuleButton(Module module, CategoryPanel categoryPanel, int n) {
this.module = module;
this.panel = categoryPanel;
this.yOffset = n;
this.expanded = false;
this.settingComponents = new ArrayList<>();
for (Setting setting : module.getSettings()) {
if (setting instanceof BooleanSetting) {
this.settingComponents.add(new BooleanComponent(setting, this, 0));
continue;
}
if (setting instanceof ModeSetting) {
this.settingComponents.add(new ModeComponent(setting, this, 0));
continue;
}
if (setting instanceof NumberSetting) {
this.settingComponents.add(new NumberComponent(setting, this, 0));
continue;
}
if (!(setting instanceof MultiSelectSetting)) continue;
this.settingComponents.add(new MultiSelectComponent(setting, this, 0));
}
this.expandAnim = new SmoothAnimationTimer();
}
public int getTotalHeight() {
if (!this.expanded) {
return this.panel.rowHeight;
}
int n = this.panel.rowHeight;
List<SettingComponent> list = this.settingComponents.stream().filter(settingComponent -> settingComponent.setting.getVisibility().displayable()).collect(Collectors.toList());
for (SettingComponent settingComponent2 : list) {
n += this.panel.rowHeight;
if (settingComponent2 instanceof ModeComponent mode && mode.isDropdownOpen()) {
n += mode.getDropdownHeight();
}
if (settingComponent2 instanceof MultiSelectComponent multi && multi.isDropdownOpen()) {
n += multi.getDropdownHeight();
}
}
return n;
}
public int getExpandedHeight() {
int n = 0;
List<SettingComponent> list = this.settingComponents.stream().filter(settingComponent -> settingComponent.setting.getVisibility().displayable()).collect(Collectors.toList());
for (SettingComponent settingComponent2 : list) {
n += this.panel.rowHeight;
if (settingComponent2 instanceof ModeComponent mode && mode.isDropdownOpen()) {
n += mode.getDropdownHeight();
}
if (settingComponent2 instanceof MultiSelectComponent multi && multi.isDropdownOpen()) {
n += multi.getDropdownHeight();
}
}
return n;
}
public void render(PoseStack poseStack, int n, int n2, float f) {
float f2;
this.expandAnim.tick();
long l = System.currentTimeMillis();
float f3 = (float)(l - this.lastTime) / 1000.0f;
this.lastTime = l;
if (this.isHovered(n, n2)) {
if (this.hoverProgress < 1.0f) {
this.hoverProgress += f3 * 4.0f;
}
if (this.hoverProgress > 1.0f) {
this.hoverProgress = 1.0f;
}
} else {
if (this.hoverProgress > 0.0f) {
this.hoverProgress -= f3 * 4.0f;
}
if (this.hoverProgress < 0.0f) {
this.hoverProgress = 0.0f;
}
}
int n3 = (int)(160.0f + 40.0f * this.hoverProgress);
int n4 = this.panel.y + this.yOffset - (this.yOffset == 0 ? 0 : 1);
int n5 = this.panel.rowHeight + (this.yOffset == 0 ? 0 : 1);
RenderUtil.drawBlurredRect(poseStack, this.panel.x, n4, this.panel.width, n5, 4.0f, 6.0f, 0.9f, 0);
RenderUtil.drawFilledRect(poseStack, this.panel.x, n4, this.panel.width, n5, new Color(21, 21, 21, n3).getRGB());
String string = this.module.getName();
float f4 = FontStore.OPENSANS_16.getStringWidth(string);
float f5 = (float)this.panel.x + (float)this.panel.width / 2.0f - f4 / 2.0f;
float f6 = (float)(this.panel.y + this.yOffset) + (float)this.panel.rowHeight / 2.0f - FontStore.OPENSANS_16.getFontHeight() / 2.0f;
FontStore.OPENSANS_16.drawStringWithShadow(poseStack, string, f5, f6, this.module.isEnabled() ? ColorUtil.fromARGB(138, 180, 248, 255) : -1);
if (!this.module.getSettings().isEmpty()) {
poseStack.pushPose();
f2 = this.panel.x + this.panel.width - 15;
float f7 = (float)(this.panel.y + this.yOffset) + (float)this.panel.rowHeight / 2.0f;
float f8 = 180.0f * this.expandAnim.getValueF();
poseStack.translate(f2, f7, 0.0f);
poseStack.mulPose(Axis.ZP.rotationDegrees(f8));
poseStack.translate(-f2, -f7, 0.0f);
FontStore.MATERIAL_20.drawStringWithShadow(poseStack, "", f2 - FontStore.MATERIAL_20.getStringWidth("") / 2.0f, f7 - FontStore.MATERIAL_20.getFontHeight() / 2.0f, -1);
poseStack.popPose();
}
if ((f2 = (float)this.getExpandedHeight() * this.expandAnim.getValueF()) > 0.0f) {
int n6 = this.panel.y + this.yOffset + this.panel.rowHeight - 1;
RenderUtil.drawBlurredRect(poseStack, this.panel.x, n6, this.panel.width, (int)f2 + 1, 4.0f, 6.0f, 0.9f, 0);
RenderUtil.pushScissor(this.panel.x, n6, this.panel.width, (int)f2 + 1);
RenderUtil.drawFilledRect(poseStack, this.panel.x, n6, this.panel.width, (int)f2 + 1, new Color(11, 11, 11, 150).getRGB());
List<SettingComponent> list = this.settingComponents.stream().filter(settingComponent -> settingComponent.setting.getVisibility().displayable()).collect(Collectors.toList());
int n7 = 0;
for (SettingComponent settingComponent2 : list) {
SettingComponent settingComponent3;
settingComponent2.yOffset = n7;
settingComponent2.renderWithAlpha(poseStack, n, n2, f, 1.0f);
n7 += this.panel.rowHeight;
if (settingComponent2 instanceof ModeComponent && ((ModeComponent)(settingComponent3 = settingComponent2)).isDropdownOpen()) {
n7 += ((ModeComponent)settingComponent3).getDropdownHeight();
}
if (!(settingComponent2 instanceof MultiSelectComponent) || !((MultiSelectComponent)(settingComponent3 = settingComponent2)).isDropdownOpen()) continue;
n7 += ((MultiSelectComponent)settingComponent3).getDropdownHeight();
}
RenderUtil.popScissor();
}
}
public void mouseClicked(double d, double d2, int n) {
if (this.isHovered(d, d2)) {
if (n == 0) {
this.module.setEnabled(!this.module.isEnabled());
} else if (n == 1 && !this.module.getSettings().isEmpty()) {
this.expanded = !this.expanded;
this.expandAnim.animate(this.expanded ? 1.0 : 0.0, 0.2, Easings.EASE_OUT_QUAD);
this.panel.recalcLayout();
}
}
if (this.expanded) {
List<SettingComponent> list = this.settingComponents.stream().filter(settingComponent -> settingComponent.setting.getVisibility().displayable()).collect(Collectors.toList());
int n2 = 0;
for (SettingComponent settingComponent2 : list) {
SettingComponent settingComponent3;
settingComponent2.yOffset = n2;
if (settingComponent2.isHovered(d, d2)) {
settingComponent2.mouseClicked(d, d2, n);
}
n2 += this.panel.rowHeight;
if (settingComponent2 instanceof ModeComponent && ((ModeComponent)(settingComponent3 = settingComponent2)).isDropdownOpen()) {
n2 += ((ModeComponent)settingComponent3).getDropdownHeight();
}
if (!(settingComponent2 instanceof MultiSelectComponent) || !((MultiSelectComponent)(settingComponent3 = settingComponent2)).isDropdownOpen()) continue;
n2 += ((MultiSelectComponent)settingComponent3).getDropdownHeight();
}
}
}
public void mouseReleased(double d, double d2, int n) {
if (this.expanded) {
for (SettingComponent settingComponent : this.settingComponents) {
settingComponent.mouseReleased(d, d2, n);
}
}
}
public void mouseScrolled(double d, double d2, double d3) {
}
public void reset() {
}
public boolean isHovered(double d, double d2) {
return d >= (double)this.panel.x && d <= (double)(this.panel.x + this.panel.width) && d2 >= (double)(this.panel.y + this.yOffset) && d2 <= (double)(this.panel.y + this.yOffset + this.panel.rowHeight);
}
public boolean isAnimating() {
return !this.expandAnim.isDone();
}
}

Some files were not shown because too many files have changed in this diff Show More