[ci skip] Initial files

This commit is contained in:
etil2jz
2022-06-13 16:14:55 +02:00
parent 496cc3fa79
commit ed359f8be7
137 changed files with 14216 additions and 0 deletions

6
.editorconfig Normal file
View File

@@ -0,0 +1,6 @@
[*.java]
charset=utf-8
end_of_line=lf
insert_final_newline=true
indent_style=space
indent_size=4

7
.gitattributes vendored Normal file
View File

@@ -0,0 +1,7 @@
* text=auto
*.sh text eol=lf
gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

47
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,47 @@
name: Build
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Git Repository
uses: actions/checkout@v2.4.0
- name: Validate Gradle Wrapper
uses: gradle/wrapper-validation-action@v1.0.4
- name: Set up JDK (GraalVM)
uses: graalvm/setup-graalvm@v1
with:
version: 'latest'
java-version: '17'
github-token: ${{ secrets.GITHUB_TOKEN }}
automatic_release_tag: 1.19"
- name: Pull Gradle Cache
uses: actions/cache@v3.0.1
id: gradle-cache
with:
path: ~/.gradle
key: ${{ runner.os }}-maven-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties') }}-java-${{ matrix.java }}
- name: Configure Git
run: |
git config --global user.email "no-reply@github.com"
git config --global user.name "Github Actions"
- name: Patch
run: |
./gradlew -Dorg.gradle.jvmargs="-Dfile.encoding=UTF-8 -Djdk.nio.maxCachedBufferSize=262144 -Dgraal.CompilerConfiguration=community -Dgraal.UsePriorityInlining=true -Dgraal.Vectorization=true -Dgraal.OptDuplication=true -Dgraal.SpeculativeGuardMovement=true -Dgraal.WriteableCodeCache=true --add-modules jdk.incubator.vector" applyPatches --stacktrace --no-daemon
- name: Build
run: |
./gradlew -Dorg.gradle.jvmargs="-Dfile.encoding=UTF-8 -Djdk.nio.maxCachedBufferSize=262144 -Dgraal.CompilerConfiguration=community -Dgraal.UsePriorityInlining=true -Dgraal.Vectorization=true -Dgraal.OptDuplication=true -Dgraal.SpeculativeGuardMovement=true -Dgraal.WriteableCodeCache=true --add-modules jdk.incubator.vector" createReobfPaperclipJar --stacktrace --no-daemon
- name: Archive Paperclip
uses: actions/upload-artifact@v3.0.0
with:
name: Mirai-1.19
path: build/libs/mirai-paperclip-1.19-R0.1-SNAPSHOT-reobf.jar
- name: Release
if: github.ref_name == 'ver/1.19'
uses: marvinpinto/action-automatic-releases@latest
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
automatic_release_tag: '1.19'
prerelease: false
title: 'Mirai 1.19'
files: build/libs/mirai-paperclip-1.19-R0.1-SNAPSHOT-reobf.jar

53
.gitignore vendored Normal file
View File

@@ -0,0 +1,53 @@
.gradle/
build/
# Eclipse stuff
.classpath
.project
.settings/
# VSCode stuff
.vscode/
# netbeans
nbproject/
nbactions.xml
# we use maven!
build.xml
# maven
target/
dependency-reduced-pom.xml
# vim
.*.sw[a-p]
# various other potential build files
build/
bin/
dist/
manifest.mf
# Mac filesystem dust
.DS_Store/
.DS_Store
# intellij
*.iml
*.ipr
*.iws
.idea/
out/
# Linux temp files
*~
# other stuff
run/
mirai-server
mirai-api
!gradle/wrapper/gradle-wrapper.jar

674
LICENSE.md Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

47
README.md Normal file
View File

@@ -0,0 +1,47 @@
<img src="logo.webp" alt="Mirai Face" align="right">
<div align="center">
<h1>Mirai</h1>
<h3>A powerful Minecraft Server Software coming from the future</h3>
<h4>Mirai is ❗under heavy development❗ and contributions are welcome!</h4>
<h5><b>This project is experimental, its usage in production environment is discouraged if you are not ready to face possible bugs.</b></h5>
![Build status](https://img.shields.io/github/workflow/status/etil2jz/Mirai/Build/ver/1.19?style=for-the-badge)
[![Discord](https://img.shields.io/discord/928402257605701683?color=5865F2&label=discord&style=for-the-badge)](https://discord.gg/DdH6Yfu9gM)
</div>
## Features
- **Fork of [Pufferfish](https://github.com/pufferfish-gg/Pufferfish)** for the best performance.
- **Contains [Lithium](https://github.com/CaffeineMC/lithium-fabric) patches** which respect Vanilla parity.
- **Efficient redstone** relying on [Alternate Current](https://github.com/SpaceWalkerRS/alternate-current), up to 4 times faster than Paper's algorithm.
- **(WIP) Implements [C2ME](https://github.com/RelativityMC/C2ME-fabric)** to improve chunk generation speed, I/O and loading.
- **Reduced bandwidth consumption and CPU usage** from avoiding sending useless packets in certain situations.
- **Pre-tweaked** configuration files to reach optimal performance with minimal impact on normal behaviors.
- **Login location** hiding feature, which adds another security layer in the logs for admins.
- **Toggleable metrics**, no one can collect data, not even us.
- **Bugfixes** for several Minecraft issues.
- **Faster process** for Vanilla methods.
- **Plugin compatibility** with Spigot & Paper plugins.
## Downloads
The latest JAR file can be downloaded here:
[Mirai-1.19-R0.1-SNAPSHOT.jar](https://github.com/etil2jz/Mirai/releases/download/1.19/mirai-paperclip-1.19-R0.1-SNAPSHOT-reobf.jar)
**Please note Java >=17 is required.**
You can also clone this repository and build it yourself.
If you are interested in making a fork, check out this template [there](https://github.com/PaperMC/paperweight-examples)!
## Building
In order to distribute and use this server software, you need a paperclip file:
```bash
./gradlew applyPatches && ./gradlew createReobfPaperclipJar
```
## License
Patches are licensed under GPL-3.0.
All other files are licensed under MIT.
## bStats
[![](https://bstats.org/signatures/server-implementation/mirai.svg)](https://bstats.org/plugin/server-implementation/Mirai/14774)

View File

@@ -0,0 +1,10 @@
# You can use this file to import files from minecraft libraries into the project
# format:
# <artifactId> <fileName>
# both fully qualified and a file based syntax are accepted for <fileName>:
# authlib com/mojang/authlib/yggdrasil/YggdrasilGameProfileRepository.java
# datafixerupper com.mojang.datafixers.DataFixerBuilder
# datafixerupper com/mojang/datafixers/util/Either.java
# To import classes from the vanilla Minecraft jar use `minecraft` as the artifactId:
# minecraft net.minecraft.world.level.entity.LevelEntityGetterAdapter
# minecraft net/minecraft/world/level/entity/LevelEntityGetter.java

View File

@@ -0,0 +1,22 @@
# We would like for paperweight to generate 100% perfect reobf mappings (and deobf mappings for that matter).
# But unfortunately it's not quite there yet - and it may be some time before that happens. Generating perfect mappings
# from Spigot's mappings is extremely difficult due to Spigot's bad tooling and bad mappings. To add insult to injury
# we remap Spigot's _source code_ which is a lot more complex and error-prone than bytecode remapping. So with all that
# said, this file exists to help fill in the gap.
#
# We will continue to improve paperweight and will work on fixing these issues so they don't come up in the first place,
# but these mappings exist to prevent these issues from holding everything else in Paper up while we work through all
# of these issues. Due to the complex nature of mappings generation and the debugging difficulty involved it may take
# a significant amount of time for us to track down every possible issue, so this file will likely be around and in
# use - at least in some capacity - for a long time.
#
# If you are adding mappings patches which are correcting for issues in paperweight's reobf mappings generation,
# unrelated to any changes in your patches, we ask that you PR the mapping to Paper so more users can benefit rather
# than keep the fix for your own fork. If the mappings patch is there to correct reobf for changes made in your patches,
# then obviously it doesn't make any sense to PR them upstream.
tiny 2 0 mojang+yarn spigot
# Workaround by MoritzR200 (see issue#87)
c net/minecraft/server/dedicated/DedicatedServerProperties net/minecraft/server/dedicated/DedicatedServerProperties
m (Ljava/lang/String;)Ljava/lang/String; lambda$new$3 d

79
build.gradle.kts Normal file
View File

@@ -0,0 +1,79 @@
import io.papermc.paperweight.util.constants.*
plugins {
java
`maven-publish`
id("com.github.johnrengelman.shadow") version "7.1.2" apply false
id("io.papermc.paperweight.patcher") version "1.3.8-SNAPSHOT"
}
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/") {
content { onlyForConfigurations("paperclip") }
}
}
dependencies {
remapper("net.fabricmc:tiny-remapper:0.8.4:fat")
decompiler("org.quiltmc:quiltflower:1.8.1")
paperclip("io.papermc:paperclip:3.0.3-SNAPSHOT")
}
subprojects {
apply(plugin = "java")
apply(plugin = "maven-publish")
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
tasks.withType<JavaCompile> {
options.encoding = Charsets.UTF_8.name()
options.release.set(17)
}
tasks.withType<Javadoc> {
options.encoding = Charsets.UTF_8.name()
}
tasks.withType<ProcessResources> {
filteringCharset = Charsets.UTF_8.name()
}
repositories {
mavenLocal()
mavenCentral()
maven("https://oss.sonatype.org/content/groups/public/")
maven("https://repo.papermc.io/repository/maven-public/")
maven("https://ci.emc.gs/nexus/content/groups/aikar/")
maven("https://repo.aikar.co/content/groups/aikar")
maven("https://repo.md-5.net/content/repositories/releases/")
maven("https://hub.spigotmc.org/nexus/content/groups/public/")
maven("https://jitpack.io")
maven("https://repo.codemc.io/repository/maven-public/")
}
}
paperweight {
serverProject.set(project(":mirai-server"))
remapRepo.set("https://maven.fabricmc.net/")
decompileRepo.set("https://maven.quiltmc.org/")
useStandardUpstream("pufferfish") {
url.set(github("pufferfish-gg", "Pufferfish"))
ref.set(providers.gradleProperty("pufferfishRef"))
withStandardPatcher {
apiSourceDirPath.set("pufferfish-api")
serverSourceDirPath.set("pufferfish-server")
apiPatchDir.set(layout.projectDirectory.dir("patches/api"))
serverPatchDir.set(layout.projectDirectory.dir("patches/server"))
apiOutputDir.set(layout.projectDirectory.dir("mirai-api"))
serverOutputDir.set(layout.projectDirectory.dir("mirai-server"))
}
}
}

13
gradle.properties Normal file
View File

@@ -0,0 +1,13 @@
group=wtf.etil.mirai
version=1.19-R0.1-SNAPSHOT
mcVersion=1.19
packageVersion=1_19_R1
pufferfishRef=671d68b85d4e9367f6847e4475e106135169c0e3
org.gradle.caching=true
org.gradle.caching.debug=false
org.gradle.configureondemand=true
org.gradle.parallel=true
org.gradle.vfs.watch=false
org.gradle.daemon=false
org.gradle.jvmargs=-Dfile.encoding=UTF-8 -Djdk.nio.maxCachedBufferSize=262144

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@@ -0,0 +1,234 @@
#!/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/master/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
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# 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"'
# 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*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
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
# 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 \
"$@"
# 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" "$@"

89
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,89 @@
@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=.
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%" == "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%"=="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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

BIN
logo.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

View File

@@ -0,0 +1,29 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Etil <81570777+etil2jz@users.noreply.github.com>
Date: Thu, 2 Dec 2021 16:06:46 +0100
Subject: [PATCH] Mirai Configuration
diff --git a/src/main/java/org/bukkit/Server.java b/src/main/java/org/bukkit/Server.java
index 79b26045a68ebb9b01e5bd06abbccaaef5489777..3dd9204c639737ad0c508d2d4a0ac8bc61c74910 100644
--- a/src/main/java/org/bukkit/Server.java
+++ b/src/main/java/org/bukkit/Server.java
@@ -1897,6 +1897,18 @@ public interface Server extends PluginMessageRecipient, net.kyori.adventure.audi
}
// Paper end
+ // Mirai start
+ @NotNull
+ public org.bukkit.configuration.file.YamlConfiguration getMiraiConfig() {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @NotNull
+ public java.util.Properties getServerProperties() {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+ // Mirai end
+
/**
* Sends the component to the player
*

View File

@@ -0,0 +1,78 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: tr7zw <tr7zw@live.de>
Date: Sat, 1 Aug 2020 15:52:50 -0500
Subject: [PATCH] Add GameProfileLookupEvent
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/build.gradle.kts b/build.gradle.kts
index 9d7bd0f965c7dc3a60246310688aa5f93a4594a4..3a1c5a4aa8d512d50565b22a383e44b73b276ee5 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -51,6 +51,7 @@ dependencies {
compileOnly("org.apache.maven.resolver:maven-resolver-connector-basic:1.7.2")
compileOnly("org.apache.maven.resolver:maven-resolver-transport-http:1.7.2")
compileOnly("com.google.code.findbugs:jsr305:1.3.9") // Paper
+ compileOnly("com.mojang:authlib:3.2.38") // Yatopia
val annotations = "org.jetbrains:annotations:23.0.0" // Paper - we don't want Java 5 annotations...
compileOnly(annotations)
diff --git a/src/main/java/org/yatopiamc/yatopia/api/events/GameProfileLookupEvent.java b/src/main/java/org/yatopiamc/yatopia/api/events/GameProfileLookupEvent.java
new file mode 100644
index 0000000000000000000000000000000000000000..d7db9c87dc82c883004a906e024d2f6de3e40961
--- /dev/null
+++ b/src/main/java/org/yatopiamc/yatopia/api/events/GameProfileLookupEvent.java
@@ -0,0 +1,51 @@
+package org.yatopiamc.yatopia.api.events;
+
+import com.mojang.authlib.GameProfile;
+import java.util.UUID;
+import org.bukkit.event.Event;
+import org.bukkit.event.HandlerList;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public class GameProfileLookupEvent extends Event {
+ private static final HandlerList handlers = new HandlerList();
+ private GameProfile gameProfile = null;
+ private final UUID uuid;
+ private final String name;
+
+ public GameProfileLookupEvent(boolean async, @NotNull UUID uuid, @NotNull String name) {
+ super(async);
+ this.uuid = uuid;
+ this.name = name;
+ }
+
+ @Nullable
+ public GameProfile getGameProfile() {
+ return gameProfile;
+ }
+
+ public void setGameProfile(@Nullable GameProfile gameProfile) {
+ this.gameProfile = gameProfile;
+ }
+
+ @NotNull
+ public UUID getUuid() {
+ return uuid;
+ }
+
+ @NotNull
+ public String getName() {
+ return name;
+ }
+
+ @NotNull
+ @Override
+ public HandlerList getHandlers() {
+ return handlers;
+ }
+
+ @NotNull
+ public static HandlerList getHandlerList() {
+ return handlers;
+ }
+}
\ No newline at end of file

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Ben Kerllenevich <ben@omega24.dev>
Date: Sat, 12 Jun 2021 12:35:38 -0400
Subject: [PATCH] Build System Changes
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/build.gradle.kts b/build.gradle.kts
index 3a1c5a4aa8d512d50565b22a383e44b73b276ee5..ea01ad75a874944a16f817f0a27e12b251111192 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -103,6 +103,8 @@ tasks.jar {
}
tasks.withType<Javadoc> {
+ (options as StandardJavadocDocletOptions).addStringOption("-add-modules", "jdk.incubator.vector") // Purpur - our javadocs need this for pufferfish's SIMD patch
+ (options as StandardJavadocDocletOptions).addStringOption("Xdoclint:none", "-quiet") // Purpur - silence Paper's bajillion javadoc warnings
val options = options as StandardJavadocDocletOptions
options.overview = "src/main/javadoc/overview.html"
options.isDocFilesSubDirs = true

View File

@@ -0,0 +1,30 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Ivan Pekov <ivan@mrivanplays.com>
Date: Mon, 19 Oct 2020 15:48:06 +0300
Subject: [PATCH] Disable reload command
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/src/main/java/org/bukkit/command/defaults/ReloadCommand.java b/src/main/java/org/bukkit/command/defaults/ReloadCommand.java
index 0c7ba0718de2b93d013968ca0fec34ffd423990f..535800197c43f43c30854d2b193107808dc3b6c7 100644
--- a/src/main/java/org/bukkit/command/defaults/ReloadCommand.java
+++ b/src/main/java/org/bukkit/command/defaults/ReloadCommand.java
@@ -21,6 +21,17 @@ public class ReloadCommand extends BukkitCommand {
@Override
public boolean execute(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull String[] args) { // Paper
if (!testPermission(sender)) return true;
+ // Yatopia start - disable reload command
+ if (Boolean.parseBoolean(System.getProperty("Mirai.DisableReloadCommand", "true"))) {
+ sender.sendMessage(ChatColor.RED + "Operation denied.");
+ sender.sendMessage(ChatColor.YELLOW + "Reload command SHOULD NEVER EVER EVER be used in whatever circumstances.");
+ sender.sendMessage(ChatColor.YELLOW + "Mirai has intentionally disabled it in order to stop you using it, instead of restarting your server.");
+ sender.sendMessage(ChatColor.GREEN + "---------------------------------------------");
+ sender.sendMessage(ChatColor.YELLOW + "RESTART YOUR SERVER AND NEVER USE /reload");
+ sender.sendMessage(ChatColor.YELLOW + "For plugin developers: learn what a HOTSWAP AGENT is and stop using /reload");
+ return true;
+ }
+ // Yatopia end
// Paper start - Reload permissions.yml & require confirm
boolean confirmed = System.getProperty("LetMeReload") != null;

View File

@@ -0,0 +1,60 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Ivan Pekov <ivan@mrivanplays.com>
Date: Sun, 27 Sep 2020 18:01:50 +0300
Subject: [PATCH] Add last tick time API
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/src/main/java/org/bukkit/Bukkit.java b/src/main/java/org/bukkit/Bukkit.java
index d8666481f9a407403d0114ff02024fd3c50c27c4..cfa749cfa9fc8bade80018f0deaa6420c57d8272 100644
--- a/src/main/java/org/bukkit/Bukkit.java
+++ b/src/main/java/org/bukkit/Bukkit.java
@@ -2336,6 +2336,16 @@ public final class Bukkit {
return server.isStopping();
}
+ // Yatopia start
+ @Deprecated
+ public static long getLastTickMs() {
+ return server.getLastTickMs();
+ }
+ @NotNull public static java.time.Duration getLastTickTime() {
+ return server.getLastTickTime();
+ }
+ // Yatopia end
+
/**
* Returns the {@link com.destroystokyo.paper.entity.ai.MobGoals} manager
*
diff --git a/src/main/java/org/bukkit/Server.java b/src/main/java/org/bukkit/Server.java
index 3dd9204c639737ad0c508d2d4a0ac8bc61c74910..2e6bd4a4b333eea52339ebd99410ec13300bda67 100644
--- a/src/main/java/org/bukkit/Server.java
+++ b/src/main/java/org/bukkit/Server.java
@@ -2046,6 +2046,26 @@ public interface Server extends PluginMessageRecipient, net.kyori.adventure.audi
*/
boolean isStopping();
+ // Yatopia start
+ /**
+ * Returns the time the last tick took in milliseconds.
+ *
+ * @return long time value
+ * @deprecated newer method with java's Duration and a possibility to convert it from millis to something else
+ */
+ @Deprecated
+ default long getLastTickMs() {
+ return getLastTickTime().toMillis();
+ }
+ /**
+ * Returns the time in {@link java.time.Duration} the last tick took.
+ *
+ * @return duration
+ */
+ @NotNull
+ java.time.Duration getLastTickTime();
+ // Yatopia end
+
/**
* Returns the {@link com.destroystokyo.paper.entity.ai.MobGoals} manager
*

View File

@@ -0,0 +1,47 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Bjarne Koll <lynxplay101@gmail.com>
Date: Thu, 9 Dec 2021 01:53:30 +0100
Subject: [PATCH] Optimize Spigot event bus
Original code by lynxplay, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/lynxplay/ktp
diff --git a/src/main/java/org/bukkit/plugin/RegisteredListener.java b/src/main/java/org/bukkit/plugin/RegisteredListener.java
index 419aec56b0e3fa8bcec2ea7f340caa3456b57d00..8530d926931a54ed1300c40cd1e0908b2d9b594d 100644
--- a/src/main/java/org/bukkit/plugin/RegisteredListener.java
+++ b/src/main/java/org/bukkit/plugin/RegisteredListener.java
@@ -62,8 +62,10 @@ public class RegisteredListener {
* @throws EventException If an event handler throws an exception.
*/
public void callEvent(@NotNull final Event event) throws EventException {
- if (event instanceof Cancellable) {
- if (((Cancellable) event).isCancelled() && isIgnoringCancelled()) {
+ // KTP start - optimize spigot event bus
+ if (isIgnoringCancelled()) {
+ if (event instanceof Cancellable cancellable && cancellable.isCancelled()) {
+ // KTP end - optimize spigot event bus
return;
}
}
diff --git a/src/main/java/org/bukkit/plugin/SimplePluginManager.java b/src/main/java/org/bukkit/plugin/SimplePluginManager.java
index dba9041784e7d3051b5248cbc24e4879e60103c1..20408d8668aa17bb6ab9ecee94db32a0cae5e95e 100644
--- a/src/main/java/org/bukkit/plugin/SimplePluginManager.java
+++ b/src/main/java/org/bukkit/plugin/SimplePluginManager.java
@@ -653,11 +653,15 @@ public final class SimplePluginManager implements PluginManager {
@Override
public void callEvent(@NotNull Event event) {
// Paper - replace callEvent by merging to below method
- if (event.isAsynchronous() && server.isPrimaryThread()) {
+ // KTP start - optimize spigot event bus
+ final boolean isAsync = event.isAsynchronous();
+ final boolean isPrimary = server.isPrimaryThread(); // Cache to prevent multiple thread object comparisons.
+ if (isAsync && isPrimary) {
throw new IllegalStateException(event.getEventName() + " may only be triggered asynchronously.");
- } else if (!event.isAsynchronous() && !server.isPrimaryThread() && !server.isStopping() ) {
+ } else if (!isAsync && !isPrimary && !server.isStopping() ) {
throw new IllegalStateException(event.getEventName() + " may only be triggered synchronously.");
}
+ // KTP end - optimize spigot event bus
HandlerList handlers = event.getHandlers();
RegisteredListener[] listeners = handlers.getRegisteredListeners();

View File

@@ -0,0 +1,119 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <Blake.Galbreath@GMail.com>
Date: Fri, 5 Jun 2020 23:32:38 -0500
Subject: [PATCH] Default Purpur permissions
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/org/bukkit/util/permissions/CommandPermissions.java b/src/main/java/org/bukkit/util/permissions/CommandPermissions.java
index 7763d6101ac61900db1e2310966b99584539fd0e..d5a42707d365ffd72532bbb1a59a1ca7145f9918 100644
--- a/src/main/java/org/bukkit/util/permissions/CommandPermissions.java
+++ b/src/main/java/org/bukkit/util/permissions/CommandPermissions.java
@@ -18,6 +18,7 @@ public final class CommandPermissions {
DefaultPermissions.registerPermission(PREFIX + "plugins", "Allows the user to view the list of plugins running on this server", PermissionDefault.TRUE, commands);
DefaultPermissions.registerPermission(PREFIX + "reload", "Allows the user to reload the server settings", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "version", "Allows the user to view the version of the server", PermissionDefault.TRUE, commands);
+ DefaultPermissions.registerPermission(PREFIX + "purpur", "Allows the user to use the purpur command", PermissionDefault.OP, commands); // Purpur
commands.recalculatePermissibles();
return commands;
diff --git a/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java b/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java
index e1a4ddf2c07cdd242fa8054a0152522fe4039e85..8e481e3815f5645ee92f0d229e5ff25c8fc9a6c2 100644
--- a/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java
+++ b/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java
@@ -89,6 +89,8 @@ public final class DefaultPermissions {
CommandPermissions.registerPermissions(parent);
BroadcastPermissions.registerPermissions(parent);
+ PurpurPermissions.registerPermissions(); // Purpur
+
parent.recalculatePermissibles();
}
}
diff --git a/src/main/java/org/bukkit/util/permissions/PurpurPermissions.java b/src/main/java/org/bukkit/util/permissions/PurpurPermissions.java
new file mode 100644
index 0000000000000000000000000000000000000000..efef6b099202717d2b53316028dc6dfb0e5f01ec
--- /dev/null
+++ b/src/main/java/org/bukkit/util/permissions/PurpurPermissions.java
@@ -0,0 +1,79 @@
+package org.bukkit.util.permissions;
+
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.EntityType;
+import org.bukkit.entity.Mob;
+import org.bukkit.permissions.Permission;
+import org.bukkit.permissions.PermissionDefault;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public final class PurpurPermissions {
+ private static final String ROOT = "purpur";
+ private static final String PREFIX = ROOT + ".";
+ private static final Set<String> mobs = new HashSet<>();
+
+ static {
+ for (EntityType mob : EntityType.values()) {
+ Class<? extends Entity> clazz = mob.getEntityClass();
+ if (clazz != null && Mob.class.isAssignableFrom(clazz)) {
+ mobs.add(mob.getName());
+ }
+ }
+ }
+
+ @NotNull
+ public static Permission registerPermissions() {
+ Permission purpur = DefaultPermissions.registerPermission(ROOT, "Gives the user the ability to use all Purpur utilities and commands", PermissionDefault.FALSE);
+
+ DefaultPermissions.registerPermission(PREFIX + "enderchest.rows.six", "Gives the user six rows of enderchest space", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "enderchest.rows.five", "Gives the user five rows of enderchest space", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "enderchest.rows.four", "Gives the user four rows of enderchest space", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "enderchest.rows.three", "Gives the user three rows of enderchest space", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "enderchest.rows.two", "Gives the user two rows of enderchest space", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "enderchest.rows.one", "Gives the user one row of enderchest space", PermissionDefault.FALSE, purpur);
+
+ DefaultPermissions.registerPermission(PREFIX + "debug.f3n", "Allows the user to use F3+N keybind to swap gamemodes", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "joinfullserver", "Allows the user to join a full server", PermissionDefault.OP, purpur);
+
+ DefaultPermissions.registerPermission(PREFIX + "drop.spawner", "Allows the user to drop spawner cage when broken with diamond pickaxe with silk touch", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "place.spawner", "Allows the user to place spawner cage in the world", PermissionDefault.FALSE, purpur);
+
+ DefaultPermissions.registerPermission(PREFIX + "anvil.color", "Allows the user to use color codes on anvils", PermissionDefault.FALSE, purpur);
+
+ Permission book = DefaultPermissions.registerPermission(PREFIX + "book", "Allows the user to use color codes on books", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "book.color.edit", "Allows the user to use color codes on books when editing", PermissionDefault.FALSE, book);
+ DefaultPermissions.registerPermission(PREFIX + "book.color.sign", "Allows the user to use color codes on books when signing", PermissionDefault.FALSE, book);
+ book.recalculatePermissibles();
+
+ Permission sign = DefaultPermissions.registerPermission(PREFIX + "sign", "Allows the user to use all sign abilities", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission(PREFIX + "sign.edit", "Allows the user to click signs to open sign editor", PermissionDefault.FALSE, sign);
+ DefaultPermissions.registerPermission(PREFIX + "sign.color", "Allows the user to use color codes on signs", PermissionDefault.FALSE, sign);
+ DefaultPermissions.registerPermission(PREFIX + "sign.style", "Allows the user to use style codes on signs", PermissionDefault.FALSE, sign);
+ DefaultPermissions.registerPermission(PREFIX + "sign.magic", "Allows the user to use magic/obfuscate code on signs", PermissionDefault.FALSE, sign);
+ sign.recalculatePermissibles();
+
+ Permission ride = DefaultPermissions.registerPermission("allow.ride", "Allows the user to ride all mobs", PermissionDefault.FALSE, purpur);
+ for (String mob : mobs) {
+ DefaultPermissions.registerPermission("allow.ride." + mob, "Allows the user to ride " + mob, PermissionDefault.FALSE, ride);
+ }
+ ride.recalculatePermissibles();
+
+ Permission special = DefaultPermissions.registerPermission("allow.special", "Allows the user to use all mobs special abilities", PermissionDefault.FALSE, purpur);
+ for (String mob : mobs) {
+ DefaultPermissions.registerPermission("allow.special." + mob, "Allows the user to use " + mob + " special ability", PermissionDefault.FALSE, special);
+ }
+ special.recalculatePermissibles();
+
+ Permission powered = DefaultPermissions.registerPermission("allow.powered", "Allows the user to toggle all mobs powered state", PermissionDefault.FALSE, purpur);
+ DefaultPermissions.registerPermission("allow.powered.creeper", "Allows the user to toggle creeper powered state", PermissionDefault.FALSE, powered);
+ powered.recalculatePermissibles();
+
+ DefaultPermissions.registerPermission(PREFIX + "portal.instant", "Allows the user to bypass portal wait time", PermissionDefault.FALSE, purpur);
+
+ purpur.recalculatePermissibles();
+ return purpur;
+ }
+}
\ No newline at end of file

View File

@@ -0,0 +1,37 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Simon Gardling <titaniumtown@gmail.com>
Date: Mon, 13 Dec 2021 11:28:08 -0500
Subject: [PATCH] Skip event if no listeners
Original code by Titaniumtown, licensed under GNU General Public License v3.0
You can find the original code on https://gitlab.com/Titaniumtown/JettPack
diff --git a/src/main/java/org/bukkit/plugin/SimplePluginManager.java b/src/main/java/org/bukkit/plugin/SimplePluginManager.java
index 20408d8668aa17bb6ab9ecee94db32a0cae5e95e..3a93a1e4d0f0345a601428f2758653dc406be122 100644
--- a/src/main/java/org/bukkit/plugin/SimplePluginManager.java
+++ b/src/main/java/org/bukkit/plugin/SimplePluginManager.java
@@ -652,6 +652,13 @@ public final class SimplePluginManager implements PluginManager {
*/
@Override
public void callEvent(@NotNull Event event) {
+ // JettPack start
+ HandlerList handlers = event.getHandlers();
+ RegisteredListener[] listeners = handlers.getRegisteredListeners();
+ if (listeners.length == 0) {
+ return;
+ }
+ // JettPack end
// Paper - replace callEvent by merging to below method
// KTP start - optimize spigot event bus
final boolean isAsync = event.isAsynchronous();
@@ -663,8 +670,8 @@ public final class SimplePluginManager implements PluginManager {
}
// KTP end - optimize spigot event bus
- HandlerList handlers = event.getHandlers();
- RegisteredListener[] listeners = handlers.getRegisteredListeners();
+ //HandlerList handlers = event.getHandlers();
+ //RegisteredListener[] listeners = handlers.getRegisteredListeners();
for (RegisteredListener registration : listeners) {
if (!registration.getPlugin().isEnabled()) {

View File

@@ -0,0 +1,20 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: foss-mc <69294560+foss-mc@users.noreply.github.com>
Date: Sat, 22 Jan 2022 03:59:27 -0800
Subject: [PATCH] disable AnnotationTest
Original code by PatinaMC, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/PatinaMC/Patina
diff --git a/src/test/java/org/bukkit/AnnotationTest.java b/src/test/java/org/bukkit/AnnotationTest.java
index 57cf9fab2501da6f1abd12e14697630ca82b0a6d..cca7e9876c7609acb26a6c9116b191b0e467a0b0 100644
--- a/src/test/java/org/bukkit/AnnotationTest.java
+++ b/src/test/java/org/bukkit/AnnotationTest.java
@@ -63,6 +63,7 @@ public class AnnotationTest {
@Test
public void testAll() throws IOException, URISyntaxException {
+ if (true) return; // Patina
URL loc = Bukkit.class.getProtectionDomain().getCodeSource().getLocation();
File file = new File(loc.toURI());

View File

@@ -0,0 +1,37 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Cryptite <cryptite@gmail.com>
Date: Thu, 7 Apr 2022 16:35:36 -0500
Subject: [PATCH] Set multiple Team settings with a single packet
Original license: MIT
Original project: https://github.com/Cryptite/Slice
diff --git a/src/main/java/org/bukkit/scoreboard/Team.java b/src/main/java/org/bukkit/scoreboard/Team.java
index 0f5c49d41c9460da0ba913b4ca8bef375f2c23df..46eee49bb149910c01db377c9cc8a96da9ead797 100644
--- a/src/main/java/org/bukkit/scoreboard/Team.java
+++ b/src/main/java/org/bukkit/scoreboard/Team.java
@@ -534,6 +534,24 @@ public interface Team {
boolean hasEntity(@NotNull org.bukkit.entity.Entity entity) throws IllegalStateException, IllegalArgumentException;
// Paper end
+ // Slice start
+ /**
+ * Fully set all team options, combining all 5 options into one packet send, rather than one packet sent
+ * for every single option change.
+ * @param displayName New display name
+ * @param prefix New prefix
+ * @param suffix New suffix
+ * @param color new color
+ * @param options A Paired list of options
+ * @throws IllegalStateException
+ */
+ void teamOptions(net.kyori.adventure.text.Component displayName,
+ net.kyori.adventure.text.Component prefix,
+ net.kyori.adventure.text.Component suffix,
+ net.kyori.adventure.text.format.NamedTextColor color,
+ java.util.List<org.apache.commons.lang3.tuple.Pair<Option, OptionStatus>> options) throws IllegalStateException;
+ // Slice end
+
/**
* Represents an option which may be applied to this team.
*/

View File

@@ -0,0 +1,241 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: etil2jz <blanchot.arthur@protonmail.ch>
Date: Sun, 27 Mar 2022 23:23:55 +0200
Subject: [PATCH] Mirai Branding Changes
diff --git a/build.gradle.kts b/build.gradle.kts
index b04e9ab317fbce9c090b61076eb07c40f069dc59..0321eac313212c717cf02889589bbc5f73c7d6ca 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -9,7 +9,7 @@ plugins {
}
dependencies {
- implementation(project(":pufferfish-api")) // Pufferfish // Paper
+ implementation(project(":mirai-api")) // Mirai // Pufferfish // Paper
// Pufferfish start
implementation("io.papermc.paper:paper-mojangapi:1.18.2-R0.1-SNAPSHOT") {
exclude("io.papermc.paper", "paper-api")
@@ -74,13 +74,13 @@ tasks.jar {
manifest {
val git = Git(rootProject.layout.projectDirectory.path)
val gitHash = git("rev-parse", "--short=7", "HEAD").getText().trim()
- val implementationVersion = System.getenv("BUILD_NUMBER") ?: "\"$gitHash\""
+ val implementationVersion = System.getenv("BUILD_NUMBER") ?: gitHash // Mirai - removed quotation marks
val date = git("show", "-s", "--format=%ci", gitHash).getText().trim() // Paper
val gitBranch = git("rev-parse", "--abbrev-ref", "HEAD").getText().trim() // Paper
attributes(
"Main-Class" to "org.bukkit.craftbukkit.Main",
"Implementation-Title" to "CraftBukkit",
- "Implementation-Version" to "git-Pufferfish-$implementationVersion", // Pufferfish
+ "Implementation-Version" to "git-Mirai-$implementationVersion", // Mirai // Pufferfish
"Implementation-Vendor" to date, // Paper
"Specification-Title" to "Bukkit",
"Specification-Version" to project.version,
diff --git a/src/main/java/com/destroystokyo/paper/Metrics.java b/src/main/java/com/destroystokyo/paper/Metrics.java
index f2fe6ea3719ff8b2913b7a3a939d7a5b75cb8b28..d7d614f679ac30360eee431044962614b498a72e 100644
--- a/src/main/java/com/destroystokyo/paper/Metrics.java
+++ b/src/main/java/com/destroystokyo/paper/Metrics.java
@@ -593,7 +593,7 @@ public class Metrics {
boolean logFailedRequests = config.getBoolean("logFailedRequests", false);
// Only start Metrics, if it's enabled in the config
if (config.getBoolean("enabled", true)) {
- Metrics metrics = new Metrics("Pufferfish", serverUUID, logFailedRequests, Bukkit.getLogger()); // Pufferfish
+ Metrics metrics = new Metrics("Mirai", serverUUID, logFailedRequests, Bukkit.getLogger()); // Mirai
metrics.addCustomChart(new Metrics.SimplePie("minecraft_version", () -> {
String minecraftVersion = Bukkit.getVersion();
@@ -603,7 +603,7 @@ public class Metrics {
metrics.addCustomChart(new Metrics.SingleLineChart("players", () -> Bukkit.getOnlinePlayers().size()));
metrics.addCustomChart(new Metrics.SimplePie("online_mode", () -> Bukkit.getOnlineMode() ? "online" : "offline"));
- metrics.addCustomChart(new Metrics.SimplePie("pufferfish_version", () -> (Metrics.class.getPackage().getImplementationVersion() != null) ? Metrics.class.getPackage().getImplementationVersion() : "unknown"));
+ metrics.addCustomChart(new Metrics.SimplePie("mirai_version", () -> (Metrics.class.getPackage().getImplementationVersion() != null) ? Metrics.class.getPackage().getImplementationVersion() : "unknown")); // Mirai
metrics.addCustomChart(new Metrics.DrilldownPie("java_version", () -> {
Map<String, Map<String, Integer>> map = new HashMap<>();
diff --git a/src/main/java/com/destroystokyo/paper/console/PaperConsole.java b/src/main/java/com/destroystokyo/paper/console/PaperConsole.java
index e0b1f0671d16ddddcb6725acd25a1d1d69e42701..c5dc798bb272a94520404e0e14c17500d3d045ae 100644
--- a/src/main/java/com/destroystokyo/paper/console/PaperConsole.java
+++ b/src/main/java/com/destroystokyo/paper/console/PaperConsole.java
@@ -17,7 +17,7 @@ public final class PaperConsole extends SimpleTerminalConsole {
@Override
protected LineReader buildReader(LineReaderBuilder builder) {
builder
- .appName("Paper")
+ .appName("Mirai") // Mirai
.variable(LineReader.HISTORY_FILE, java.nio.file.Paths.get(".console_history"))
.completer(new ConsoleCommandCompleter(this.server))
.option(LineReader.Option.COMPLETE_IN_WORD, true);
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 371b0f95b23d67c9913875a3dd7888e722551f18..7ba86703433322e2b166cc263cedd6e7310d36a4 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -1695,7 +1695,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
@DontObfuscate
public String getServerModName() {
- return "Pufferfish"; // Pufferfish - Pufferfish > // Paper - Paper > // Spigot - Spigot > // CraftBukkit - cb > vanilla!
+ return "Mirai"; // Mirai - Mirai > // Pufferfish - Pufferfish > // Paper - Paper > // Spigot - Spigot > // CraftBukkit - cb > vanilla!
}
public SystemReport fillSystemReport(SystemReport details) {
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index ce1ca033b351785fb67304b8933990d7f2f22d29..ccf826e4d9815af19e598a2320c880c9235eb15a 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -249,7 +249,7 @@ import javax.annotation.Nullable; // Paper
import javax.annotation.Nonnull; // Paper
public final class CraftServer implements Server {
- private final String serverName = "Pufferfish"; // Paper // Pufferfish
+ private final String serverName = "Mirai"; // Paper // Pufferfish // Mirai
private final String serverVersion;
private final String bukkitVersion = Versioning.getBukkitVersion();
private final Logger logger = Logger.getLogger("Minecraft");
diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
index f71af7ecad4b6b0328da8cf8c4e5a8e163866e19..1e74799bb012ca45769a3fd103f0b24eba0a9a99 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
@@ -430,7 +430,7 @@ public final class CraftMagicNumbers implements UnsafeValues {
@Override
public com.destroystokyo.paper.util.VersionFetcher getVersionFetcher() {
- return new gg.pufferfish.pufferfish.PufferfishVersionFetcher(); // Pufferfish
+ return new wtf.etil.mirai.MiraiVersionFetcher(); // Mirai
}
@Override
diff --git a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java
index 80553face9c70c2a3d897681e7761df85b22d464..4c7515fa391ee9b631cb9cd3da67b50a9378e7fc 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java
@@ -11,7 +11,7 @@ public final class Versioning {
public static String getBukkitVersion() {
String result = "Unknown-Version";
- InputStream stream = Bukkit.class.getClassLoader().getResourceAsStream("META-INF/maven/gg.pufferfish.pufferfish/pufferfish-api/pom.properties"); // Pufferfish
+ InputStream stream = Bukkit.class.getClassLoader().getResourceAsStream("META-INF/maven/wtf.etil.mirai/mirai-api/pom.properties"); // Mirai
Properties properties = new Properties();
if (stream != null) {
diff --git a/src/main/java/wtf/etil/mirai/MiraiVersionFetcher.java b/src/main/java/wtf/etil/mirai/MiraiVersionFetcher.java
new file mode 100644
index 0000000000000000000000000000000000000000..2a7ea9e238be3a253d560ebcacc433258ea636d9
--- /dev/null
+++ b/src/main/java/wtf/etil/mirai/MiraiVersionFetcher.java
@@ -0,0 +1,112 @@
+package wtf.etil.mirai;
+
+import com.destroystokyo.paper.VersionHistoryManager;
+import com.destroystokyo.paper.util.VersionFetcher;
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.JoinConfiguration;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.format.TextDecoration;
+import org.bukkit.craftbukkit.CraftServer;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import static net.kyori.adventure.text.Component.text;
+import static net.kyori.adventure.text.format.NamedTextColor.GREEN;
+import static net.kyori.adventure.text.format.NamedTextColor.RED;
+
+public class MiraiVersionFetcher implements VersionFetcher {
+
+ /*
+ * Huge shoutout to Airplane for providing basically this entire class.
+ * My brain and fingers thank you.
+ * ~ Code
+ */
+
+ private static final Logger LOGGER = Logger.getLogger("MiraiVersionFetcher");
+ private static final HttpClient client = HttpClient.newHttpClient();
+
+ private static final String GITHUB_FORMAT = "https://api.github.com/repos/etil2jz/Mirai/compare/ver/1.18.2...%s";
+
+ private static final HttpResponse.BodyHandler<JsonObject> JSON_OBJECT_BODY_HANDLER = responseInfo -> HttpResponse.BodySubscribers.mapping(
+ HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8),
+ string -> new Gson().fromJson(string, JsonObject.class)
+ );
+
+ @Override
+ public long getCacheTime() {
+ return TimeUnit.MINUTES.toMillis(30);
+ }
+
+ @Override
+ public @NotNull Component getVersionMessage(final @NotNull String serverVersion) {
+ final String[] parts = CraftServer.class.getPackage().getImplementationVersion().split("-");
+ @NotNull Component component;
+
+ if (parts.length != 3) {
+ component = text("Unknown server version.", RED);
+ } else {
+ component = this.fetchGithubVersion(parts[2]);
+ }
+
+ final @Nullable Component history = this.getHistory();
+ return history != null ? Component.join(JoinConfiguration.noSeparators(), component, Component.newline(), this.getHistory()) : component;
+ }
+
+ // Based off code contributed by Techcable <Techcable@outlook.com> in Paper/GH-65
+ private @NotNull Component fetchGithubVersion(final @NotNull String hash) {
+ final URI uri = URI.create(String.format(GITHUB_FORMAT, hash));
+ final HttpRequest request = HttpRequest.newBuilder(uri).build();
+ try {
+ final HttpResponse<JsonObject> response = client.send(request, JSON_OBJECT_BODY_HANDLER);
+ if (response.statusCode() != 200) {
+ return text("Received invalid status code (" + response.statusCode() + ") from server.", RED);
+ }
+
+ final JsonObject obj = response.body();
+ final int versionDiff = obj.get("behind_by").getAsInt();
+
+ return this.getResponseMessage(versionDiff);
+ } catch (IOException | InterruptedException e) {
+ LOGGER.log(Level.WARNING, "Failed to look up version from GitHub", e);
+ return text("Failed to retrieve version from server.", RED);
+ }
+ }
+
+ private @NotNull Component getResponseMessage(final int versionDiff) {
+ return switch (Math.max(-1, Math.min(1, versionDiff))) {
+ case -1 ->
+ text("You are running an unsupported version of Mirai.", RED);
+ case 0 ->
+ text("You are on the latest version!", GREEN);
+ default ->
+ text("You are running " + versionDiff + " version" + (versionDiff == 1 ? "" : "s") + " beyond. " +
+ "Please update your server when possible to maintain stability, security, and receive the latest optimizations.", RED);
+ };
+ }
+
+ private @Nullable Component getHistory() {
+ final VersionHistoryManager.VersionData data = VersionHistoryManager.INSTANCE.getVersionData();
+ if (data == null) {
+ return null;
+ }
+
+ final String oldVersion = data.getOldVersion();
+ if (oldVersion == null) {
+ return null;
+ }
+
+ return Component.text("Previous version: " + oldVersion, NamedTextColor.GRAY, TextDecoration.ITALIC);
+ }
+}
\ No newline at end of file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,42 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: YatopiaMC <yatopiamc@gmail.com>
Date: Fri, 23 Oct 2020 09:20:01 -0700
Subject: [PATCH] Time Utilities
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/src/main/java/org/yatopiamc/yatopia/server/util/TimeUtils.java b/src/main/java/org/yatopiamc/yatopia/server/util/TimeUtils.java
new file mode 100644
index 0000000000000000000000000000000000000000..bb023bcb4b1e1ab5261c83358ce0951cc35ba16d
--- /dev/null
+++ b/src/main/java/org/yatopiamc/yatopia/server/util/TimeUtils.java
@@ -0,0 +1,27 @@
+package org.yatopiamc.yatopia.server.util;
+
+import java.util.concurrent.TimeUnit;
+
+public class TimeUtils {
+
+ public static String getFriendlyName(TimeUnit unit) {
+ switch (unit) {
+ case NANOSECONDS:
+ return "ns";
+ case MILLISECONDS:
+ return "ms";
+ case MICROSECONDS:
+ return "micros";
+ case SECONDS:
+ return "s";
+ case MINUTES:
+ return "m";
+ case DAYS:
+ return "d";
+ case HOURS:
+ return "h";
+ default:
+ throw new AssertionError();
+ }
+ }
+}
\ No newline at end of file

View File

@@ -0,0 +1,76 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E3=84=97=E3=84=A0=CB=8B=20=E3=84=91=E3=84=A7=CB=8A?=
<tsao-chi@the-lingo.org>
Date: Fri, 10 Apr 2020 15:47:15 +0800
Subject: [PATCH] Swaps the predicate order of collision
Original code by Akarin-project, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/Akarin-project/Akarin
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index c9e23c09bc9db25a813e703817d51e1763b0b3b6..38cb136d34cbc83dde1c766196f60a30d38005e3 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -1869,37 +1869,35 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
public void playerTouch(Player player) {}
public void push(Entity entity) {
- if (!this.isPassengerOfSameVehicle(entity)) {
- if (!entity.noPhysics && !this.noPhysics) {
- if (this.level.paperConfig.onlyPlayersCollide && !(entity instanceof ServerPlayer || this instanceof ServerPlayer)) return; // Paper
- double d0 = entity.getX() - this.getX();
- double d1 = entity.getZ() - this.getZ();
- double d2 = Mth.absMax(d0, d1);
-
- if (d2 >= 0.009999999776482582D) {
- d2 = Math.sqrt(d2);
- d0 /= d2;
- d1 /= d2;
- double d3 = 1.0D / d2;
-
- if (d3 > 1.0D) {
- d3 = 1.0D;
- }
-
- d0 *= d3;
- d1 *= d3;
- d0 *= 0.05000000074505806D;
- d1 *= 0.05000000074505806D;
- if (!this.isVehicle()) {
- this.push(-d0, 0.0D, -d1);
- }
+ if (!entity.noPhysics && !this.noPhysics && !this.isPassengerOfSameVehicle(entity)) { // Akarin - Swap the predicate order of collision
+ if (this.level.paperConfig.onlyPlayersCollide && !(entity instanceof ServerPlayer || this instanceof ServerPlayer)) return; // Paper
+ double d0 = entity.getX() - this.getX();
+ double d1 = entity.getZ() - this.getZ();
+ double d2 = Mth.absMax(d0, d1);
+
+ if (d2 >= 0.009999999776482582D) {
+ d2 = Math.sqrt(d2);
+ d0 /= d2;
+ d1 /= d2;
+ double d3 = 1.0D / d2;
+
+ if (d3 > 1.0D) {
+ d3 = 1.0D;
+ }
- if (!entity.isVehicle()) {
- entity.push(d0, 0.0D, d1);
- }
+ d0 *= d3;
+ d1 *= d3;
+ d0 *= 0.05000000074505806D;
+ d1 *= 0.05000000074505806D;
+ if (!this.isVehicle()) {
+ this.push(-d0, 0.0D, -d1);
}
+ if (!entity.isVehicle()) {
+ entity.push(d0, 0.0D, d1);
+ }
}
+
}
}

View File

@@ -0,0 +1,624 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Simon Gardling <titaniumtown@gmail.com>
Date: Tue, 9 Nov 2021 16:53:39 -0500
Subject: [PATCH] reduce allocs
This patch includes code from the lithium project under the GNU Lesser General Public License v3.0: https://github.com/CaffeineMC/lithium-fabric/ but also original code created by your's truly
Original code by Titaniumtown, licensed under GNU General Public License v3.0
You can find the original code on https://gitlab.com/Titaniumtown/JettPack
diff --git a/src/main/java/com/destroystokyo/paper/PaperCommand.java b/src/main/java/com/destroystokyo/paper/PaperCommand.java
index 45d1807b31f5acd5f08f729701cec4b464ad9398..e85175910454fc08704ea01e4b852136a6c6c60f 100644
--- a/src/main/java/com/destroystokyo/paper/PaperCommand.java
+++ b/src/main/java/com/destroystokyo/paper/PaperCommand.java
@@ -214,7 +214,7 @@ public class PaperCommand extends Command {
case "version":
Command ver = MinecraftServer.getServer().server.getCommandMap().getCommand("version");
if (ver != null) {
- ver.execute(sender, commandLabel, new String[0]);
+ ver.execute(sender, commandLabel, me.titaniumtown.Constants.EMPTY_string_arr); // JettPack
break;
}
// else - fall through to default
diff --git a/src/main/java/com/destroystokyo/paper/util/maplist/EntityList.java b/src/main/java/com/destroystokyo/paper/util/maplist/EntityList.java
index 0133ea6feb1ab88f021f66855669f58367e7420b..cd5499e750764eaa5e361e73eb581bfce7f9f7c1 100644
--- a/src/main/java/com/destroystokyo/paper/util/maplist/EntityList.java
+++ b/src/main/java/com/destroystokyo/paper/util/maplist/EntityList.java
@@ -17,9 +17,9 @@ public final class EntityList implements Iterable<Entity> {
this.entityToIndex.defaultReturnValue(Integer.MIN_VALUE);
}
- protected static final Entity[] EMPTY_LIST = new Entity[0];
+ // protected static final Entity[] EMPTY_LIST = new Entity[0]; // JettPack
- protected Entity[] entities = EMPTY_LIST;
+ protected Entity[] entities = me.titaniumtown.Constants.EMPTY_entity_arr; // JettPack
protected int count;
public int size() {
diff --git a/src/main/java/com/destroystokyo/paper/util/maplist/IBlockDataList.java b/src/main/java/com/destroystokyo/paper/util/maplist/IBlockDataList.java
index 277cfd9d1e8fff5d9b5e534b75c3c5162d58b0b7..52ec153be9d7177102dd137dfc356e29173f62bd 100644
--- a/src/main/java/com/destroystokyo/paper/util/maplist/IBlockDataList.java
+++ b/src/main/java/com/destroystokyo/paper/util/maplist/IBlockDataList.java
@@ -20,9 +20,7 @@ public final class IBlockDataList {
this.map.defaultReturnValue(Long.MAX_VALUE);
}
- private static final long[] EMPTY_LIST = new long[0];
-
- private long[] byIndex = EMPTY_LIST;
+ private long[] byIndex = me.titaniumtown.Constants.EMPTY_long_arr; // JettPack
private int size;
public static int getLocationKey(final int x, final int y, final int z) {
diff --git a/src/main/java/io/papermc/paper/world/ChunkEntitySlices.java b/src/main/java/io/papermc/paper/world/ChunkEntitySlices.java
index 47b5f75d9f27cf3ab947fd1f69cbd609fb9f2749..a919e8a2aa10ba01d7f389985591a0681c1b4426 100644
--- a/src/main/java/io/papermc/paper/world/ChunkEntitySlices.java
+++ b/src/main/java/io/papermc/paper/world/ChunkEntitySlices.java
@@ -63,7 +63,7 @@ public final class ChunkEntitySlices {
}
}
- return ret.toArray(new org.bukkit.entity.Entity[0]);
+ return ret.toArray(me.titaniumtown.Constants.EMPTY_bukkit_entity_arr); // JettPack
}
// Paper end - optimise CraftChunk#getEntities
@@ -189,7 +189,7 @@ public final class ChunkEntitySlices {
protected static final class BasicEntityList<E extends Entity> {
- protected static final Entity[] EMPTY = new Entity[0];
+ // protected static final Entity[] EMPTY = new Entity[0]; // JettPack
protected static final int DEFAULT_CAPACITY = 4;
protected E[] storage;
@@ -200,7 +200,7 @@ public final class ChunkEntitySlices {
}
public BasicEntityList(final int cap) {
- this.storage = (E[])(cap <= 0 ? EMPTY : new Entity[cap]);
+ this.storage = (E[])(cap <= 0 ? me.titaniumtown.Constants.EMPTY_entity_arr : new Entity[cap]); // JettPack
}
public boolean isEmpty() {
@@ -212,7 +212,7 @@ public final class ChunkEntitySlices {
}
private void resize() {
- if (this.storage == EMPTY) {
+ if (this.storage == me.titaniumtown.Constants.EMPTY_entity_arr) { // JettPack
this.storage = (E[])new Entity[DEFAULT_CAPACITY];
} else {
this.storage = Arrays.copyOf(this.storage, this.storage.length * 2);
diff --git a/src/main/java/me/titaniumtown/Constants.java b/src/main/java/me/titaniumtown/Constants.java
new file mode 100644
index 0000000000000000000000000000000000000000..1a39467fcbb849c79bea21a020b4270a2850e02c
--- /dev/null
+++ b/src/main/java/me/titaniumtown/Constants.java
@@ -0,0 +1,14 @@
+package me.titaniumtown;
+
+import net.minecraft.core.BlockPos;
+
+public final class Constants {
+ public static final Object[] EMPTY_object_arr = new Object[0];
+ public static final int[] EMPTY_int_arr = new int[0];
+ public static final int[] ZERO_int_arr = new int[]{0};
+ public static final byte[] EMPTY_byte_arr = new byte[0];
+ public static final String[] EMPTY_string_arr = new String[0];
+ public static final long[] EMPTY_long_arr = new long[0];
+ public static final org.bukkit.entity.Entity[] EMPTY_bukkit_entity_arr = new org.bukkit.entity.Entity[0];
+ public static final net.minecraft.world.entity.Entity[] EMPTY_entity_arr = new net.minecraft.world.entity.Entity[0];
+}
\ No newline at end of file
diff --git a/src/main/java/net/minecraft/nbt/ByteArrayTag.java b/src/main/java/net/minecraft/nbt/ByteArrayTag.java
index 3dd8a189c26f41759c59c3b9d0e5282038989a9f..147beddf8ef369cdae4b1ed2dcd0d7b2fd865315 100644
--- a/src/main/java/net/minecraft/nbt/ByteArrayTag.java
+++ b/src/main/java/net/minecraft/nbt/ByteArrayTag.java
@@ -170,7 +170,7 @@ public class ByteArrayTag extends CollectionTag<ByteTag> {
}
public void clear() {
- this.data = new byte[0];
+ this.data = me.titaniumtown.Constants.EMPTY_byte_arr; // JettPack
}
@Override
diff --git a/src/main/java/net/minecraft/nbt/CompoundTag.java b/src/main/java/net/minecraft/nbt/CompoundTag.java
index 29f6fc5f83042713704b83f3b5257eb8b9b747f2..0211e70eede03cbe6cdc657e2265c5a1683b7b6c 100644
--- a/src/main/java/net/minecraft/nbt/CompoundTag.java
+++ b/src/main/java/net/minecraft/nbt/CompoundTag.java
@@ -364,7 +364,7 @@ public class CompoundTag implements Tag {
throw new ReportedException(this.createReport(key, ByteArrayTag.TYPE, var3));
}
- return new byte[0];
+ return me.titaniumtown.Constants.EMPTY_byte_arr; // JettPack
}
public int[] getIntArray(String key) {
@@ -376,7 +376,7 @@ public class CompoundTag implements Tag {
throw new ReportedException(this.createReport(key, IntArrayTag.TYPE, var3));
}
- return new int[0];
+ return me.titaniumtown.Constants.EMPTY_int_arr; // JettPack
}
public long[] getLongArray(String key) {
@@ -388,7 +388,7 @@ public class CompoundTag implements Tag {
throw new ReportedException(this.createReport(key, LongArrayTag.TYPE, var3));
}
- return new long[0];
+ return me.titaniumtown.Constants.EMPTY_long_arr; // JettPack
}
public CompoundTag getCompound(String key) {
diff --git a/src/main/java/net/minecraft/nbt/IntArrayTag.java b/src/main/java/net/minecraft/nbt/IntArrayTag.java
index a14b01cee7a8d7022c4fa7264d349a76be143ba5..44f441d6c102fa5bd50071cae991a8a6ba0ec713 100644
--- a/src/main/java/net/minecraft/nbt/IntArrayTag.java
+++ b/src/main/java/net/minecraft/nbt/IntArrayTag.java
@@ -184,7 +184,7 @@ public class IntArrayTag extends CollectionTag<IntTag> {
}
public void clear() {
- this.data = new int[0];
+ this.data = me.titaniumtown.Constants.EMPTY_int_arr; // JettPack
}
@Override
diff --git a/src/main/java/net/minecraft/nbt/ListTag.java b/src/main/java/net/minecraft/nbt/ListTag.java
index 17a37d453b3d6cdb838dd7e8071bb9ad34cd2c20..1e2aca86f30c43f25aea7f18b67b4f6ddbd4c2cf 100644
--- a/src/main/java/net/minecraft/nbt/ListTag.java
+++ b/src/main/java/net/minecraft/nbt/ListTag.java
@@ -221,7 +221,7 @@ public class ListTag extends CollectionTag<Tag> {
}
}
- return new int[0];
+ return me.titaniumtown.Constants.EMPTY_int_arr; // JettPack
}
public long[] getLongArray(int index) {
@@ -232,7 +232,7 @@ public class ListTag extends CollectionTag<Tag> {
}
}
- return new long[0];
+ return me.titaniumtown.Constants.EMPTY_long_arr; // JettPack
}
public double getDouble(int index) {
diff --git a/src/main/java/net/minecraft/network/Connection.java b/src/main/java/net/minecraft/network/Connection.java
index 9bbf990212ee55a267d0eb1e863618c50fa706da..b9b93606b5771de854cd0e1af0001cc8cf6aca2f 100644
--- a/src/main/java/net/minecraft/network/Connection.java
+++ b/src/main/java/net/minecraft/network/Connection.java
@@ -316,7 +316,7 @@ public class Connection extends SimpleChannelInboundHandler<Packet<?>> {
}
public void setListener(PacketListener listener) {
- Validate.notNull(listener, "packetListener", new Object[0]);
+ Validate.notNull(listener, "packetListener", me.titaniumtown.Constants.EMPTY_object_arr); // JettPack
this.packetListener = listener;
}
// Paper start
diff --git a/src/main/java/net/minecraft/server/Main.java b/src/main/java/net/minecraft/server/Main.java
index 1e0d261439255091a6f61485c0747231fbd5b1db..490f5d86df7fff6537c7080361a7df80951647df 100644
--- a/src/main/java/net/minecraft/server/Main.java
+++ b/src/main/java/net/minecraft/server/Main.java
@@ -80,7 +80,7 @@ public class Main {
OptionSpec<Void> optionspec6 = optionparser.accepts("safeMode", "Loads level with vanilla datapack only");
OptionSpec<Void> optionspec7 = optionparser.accepts("help").forHelp();
OptionSpec<String> optionspec8 = optionparser.accepts("singleplayer").withRequiredArg();
- OptionSpec<String> optionspec9 = optionparser.accepts("universe").withRequiredArg().defaultsTo(".", new String[0]);
+ OptionSpec<String> optionspec9 = optionparser.accepts("universe").withRequiredArg().defaultsTo(".", me.titaniumtown.Constants.EMPTY_string_arr); // JettPack
OptionSpec<String> optionspec10 = optionparser.accepts("world").withRequiredArg();
OptionSpec<Integer> optionspec11 = optionparser.accepts("port").withRequiredArg().ofType(Integer.class).defaultsTo(-1, new Integer[0]);
OptionSpec<String> optionspec12 = optionparser.accepts("serverId").withRequiredArg();
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 7ba86703433322e2b166cc263cedd6e7310d36a4..26841729126b022f75e55e584fe850771dedd4cd 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -1412,8 +1412,8 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
try {
BufferedImage bufferedimage = ImageIO.read(file);
- Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
- Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
+ Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", me.titaniumtown.Constants.EMPTY_object_arr); // JettPack
+ Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", me.titaniumtown.Constants.EMPTY_object_arr); // JettPack
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "PNG", bytearrayoutputstream);
diff --git a/src/main/java/net/minecraft/server/level/ServerEntity.java b/src/main/java/net/minecraft/server/level/ServerEntity.java
index d52072ab126f2fdee30bb114f3058338edd72fd5..44560edcf339c1749b9df78e6e57075499d5813d 100644
--- a/src/main/java/net/minecraft/server/level/ServerEntity.java
+++ b/src/main/java/net/minecraft/server/level/ServerEntity.java
@@ -314,7 +314,7 @@ public class ServerEntity {
if (this.entity instanceof LivingEntity) {
List<Pair<EquipmentSlot, ItemStack>> list = Lists.newArrayList();
- EquipmentSlot[] aenumitemslot = EquipmentSlot.values();
+ EquipmentSlot[] aenumitemslot = EquipmentSlot.VALUES; // JettPack
int i = aenumitemslot.length;
for (int j = 0; j < i; ++j) {
diff --git a/src/main/java/net/minecraft/server/level/ServerLevel.java b/src/main/java/net/minecraft/server/level/ServerLevel.java
index 93c1f9e3e9d62cc993fedb93fe43cbeed7d39542..da6156f1d61ca20fd39f35da36c64afe62b2731b 100644
--- a/src/main/java/net/minecraft/server/level/ServerLevel.java
+++ b/src/main/java/net/minecraft/server/level/ServerLevel.java
@@ -851,7 +851,7 @@ public class ServerLevel extends Level implements WorldGenLevel {
BlockPos blockposition2 = blockposition.set(j + randomX, randomY, k + randomZ);
BlockState iblockdata = com.destroystokyo.paper.util.maplist.IBlockDataList.getBlockDataFromRaw(raw);
- iblockdata.randomTick(this, blockposition2, this.randomTickRandom);
+ iblockdata.randomTick(this, blockposition2.immutable(), this.randomTickRandom); // JettPack - reduce allocs
// We drop the fluid tick since LAVA is ALREADY TICKED by the above method (See LiquidBlock).
// TODO CHECK ON UPDATE
}
@@ -1106,7 +1106,7 @@ public class ServerLevel extends Level implements WorldGenLevel {
public static List<Entity> getCurrentlyTickingEntities() {
Entity ticking = currentlyTickingEntity.get();
- List<Entity> ret = java.util.Arrays.asList(ticking == null ? new Entity[0] : new Entity[] { ticking });
+ List<Entity> ret = java.util.Arrays.asList(ticking == null ? me.titaniumtown.Constants.EMPTY_entity_arr : new Entity[] { ticking }); // JettPack
return ret;
}
diff --git a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index 676f2cd4b152984aa76903fcf4377c745775bfc8..f0e7c7c84052f29349b60ad06ec4f9ee1771f4bb 100644
--- a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -359,7 +359,7 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
if (this.keepAlivePending) {
if (!this.processedDisconnect && elapsedTime >= KEEPALIVE_LIMIT) { // check keepalive limit, don't fire if already disconnected
ServerGamePacketListenerImpl.LOGGER.warn("{} was kicked due to keepalive timeout!", this.player.getScoreboardName()); // more info
- this.disconnect(new TranslatableComponent("disconnect.timeout", new Object[0]), org.bukkit.event.player.PlayerKickEvent.Cause.TIMEOUT); // Paper - kick event cause
+ this.disconnect(new TranslatableComponent("disconnect.timeout", me.titaniumtown.Constants.EMPTY_object_arr), org.bukkit.event.player.PlayerKickEvent.Cause.TIMEOUT); // Paper - kick event cause // JettPack
}
} else {
if (elapsedTime >= 15000L) { // 15 seconds
@@ -799,13 +799,13 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
// PlayerConnectionUtils.ensureMainThread(packetplayintabcomplete, this, this.player.getWorldServer()); // Paper - run this async
// CraftBukkit start
if (this.chatSpamTickCount.addAndGet(com.destroystokyo.paper.PaperConfig.tabSpamIncrement) > com.destroystokyo.paper.PaperConfig.tabSpamLimit && !this.server.getPlayerList().isOp(this.player.getGameProfile())) { // Paper start - split and make configurable
- server.scheduleOnMain(() -> this.disconnect(new TranslatableComponent("disconnect.spam", new Object[0]), org.bukkit.event.player.PlayerKickEvent.Cause.SPAM)); // Paper - kick event cause
+ server.scheduleOnMain(() -> this.disconnect(new TranslatableComponent("disconnect.spam", me.titaniumtown.Constants.EMPTY_object_arr), org.bukkit.event.player.PlayerKickEvent.Cause.SPAM)); // Paper - kick event cause // JettPack
return;
}
// Paper start
String str = packet.getCommand(); int index = -1;
if (str.length() > 64 && ((index = str.indexOf(' ')) == -1 || index >= 64)) {
- server.scheduleOnMain(() -> this.disconnect(new TranslatableComponent("disconnect.spam", new Object[0]), org.bukkit.event.player.PlayerKickEvent.Cause.SPAM)); // Paper - kick event cause
+ server.scheduleOnMain(() -> this.disconnect(new TranslatableComponent("disconnect.spam", me.titaniumtown.Constants.EMPTY_object_arr), org.bukkit.event.player.PlayerKickEvent.Cause.SPAM)); // Paper - kick event cause // JettPack
return;
}
// Paper end
@@ -2952,7 +2952,7 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
// Paper start
if (!org.bukkit.Bukkit.isPrimaryThread()) {
if (recipeSpamPackets.addAndGet(com.destroystokyo.paper.PaperConfig.autoRecipeIncrement) > com.destroystokyo.paper.PaperConfig.autoRecipeLimit) {
- server.scheduleOnMain(() -> this.disconnect(new TranslatableComponent("disconnect.spam", new Object[0]), org.bukkit.event.player.PlayerKickEvent.Cause.SPAM)); // Paper - kick event cause
+ server.scheduleOnMain(() -> this.disconnect(new TranslatableComponent("disconnect.spam", me.titaniumtown.Constants.EMPTY_object_arr), org.bukkit.event.player.PlayerKickEvent.Cause.SPAM)); // Paper - kick event cause // JettPack
return;
}
}
diff --git a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
index befcb501b4b1b6330bf3cd53e00e30b01efade6f..0c4e34c02060c00bdbed6388989660ec023b4d1c 100644
--- a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
@@ -249,9 +249,9 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener
@Override
public void handleHello(ServerboundHelloPacket packet) {
- Validate.validState(this.state == ServerLoginPacketListenerImpl.State.HELLO, "Unexpected hello packet", new Object[0]);
+ Validate.validState(this.state == ServerLoginPacketListenerImpl.State.HELLO, "Unexpected hello packet", me.titaniumtown.Constants.EMPTY_object_arr); // JettPack
this.gameProfile = packet.getGameProfile();
- Validate.validState(ServerLoginPacketListenerImpl.isValidUsername(this.gameProfile.getName()), "Invalid characters in username", new Object[0]);
+ Validate.validState(ServerLoginPacketListenerImpl.isValidUsername(this.gameProfile.getName()), "Invalid characters in username", me.titaniumtown.Constants.EMPTY_object_arr); // JettPack
// Paper start - validate usernames
if (com.destroystokyo.paper.PaperConfig.isProxyOnlineMode() && com.destroystokyo.paper.PaperConfig.performUsernameValidation) {
if (!this.iKnowThisMayNotBeTheBestIdeaButPleaseDisableUsernameValidation && !validateUsername(this.gameProfile.getName())) {
@@ -300,7 +300,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener
@Override
public void handleKey(ServerboundKeyPacket packet) {
- Validate.validState(this.state == ServerLoginPacketListenerImpl.State.KEY, "Unexpected key packet", new Object[0]);
+ Validate.validState(this.state == ServerLoginPacketListenerImpl.State.KEY, "Unexpected key packet", me.titaniumtown.Constants.EMPTY_object_arr); // JettPack
PrivateKey privatekey = this.server.getKeyPair().getPrivate();
final String s;
diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java
index 624946f48f0811c94d05174f28d0b1fc6d5e6a00..49e27efb5fdf26f6a8026c8c17e25d87026ab45d 100644
--- a/src/main/java/net/minecraft/server/players/PlayerList.java
+++ b/src/main/java/net/minecraft/server/players/PlayerList.java
@@ -316,7 +316,7 @@ public abstract class PlayerList {
}
void disconnectPendingPlayer(ServerPlayer entityplayer) {
- TranslatableComponent msg = new TranslatableComponent("multiplayer.disconnect.duplicate_login", new Object[0]);
+ TranslatableComponent msg = new TranslatableComponent("multiplayer.disconnect.duplicate_login", me.titaniumtown.Constants.EMPTY_object_arr); // JettPack
entityplayer.networkManager.send(new ClientboundDisconnectPacket(msg), (future) -> {
entityplayer.networkManager.disconnect(msg);
entityplayer.networkManager = null;
@@ -731,7 +731,7 @@ public abstract class PlayerList {
while (iterator.hasNext()) {
entityplayer = (ServerPlayer) iterator.next();
this.save(entityplayer); // CraftBukkit - Force the player's inventory to be saved
- entityplayer.connection.disconnect(new TranslatableComponent("multiplayer.disconnect.duplicate_login", new Object[0]), org.bukkit.event.player.PlayerKickEvent.Cause.DUPLICATE_LOGIN); // Paper - kick event cause
+ entityplayer.connection.disconnect(new TranslatableComponent("multiplayer.disconnect.duplicate_login", me.titaniumtown.Constants.EMPTY_object_arr), org.bukkit.event.player.PlayerKickEvent.Cause.DUPLICATE_LOGIN); // Paper - kick event cause // JettPack
}
// Instead of kicking then returning, we need to store the kick reason
diff --git a/src/main/java/net/minecraft/server/players/StoredUserList.java b/src/main/java/net/minecraft/server/players/StoredUserList.java
index 4fd709a550bf8da1e996894a1ca6b91206c31e9e..63c0fe30ff035b6b5c1b4b35d3ad6c649d94e421 100644
--- a/src/main/java/net/minecraft/server/players/StoredUserList.java
+++ b/src/main/java/net/minecraft/server/players/StoredUserList.java
@@ -95,7 +95,7 @@ public abstract class StoredUserList<K, V extends StoredUserEntry<K>> {
}
public String[] getUserList() {
- return (String[]) this.map.keySet().toArray(new String[0]);
+ return (String[]) this.map.keySet().toArray(me.titaniumtown.Constants.EMPTY_string_arr); // JettPack
}
// CraftBukkit start
diff --git a/src/main/java/net/minecraft/util/ZeroBitStorage.java b/src/main/java/net/minecraft/util/ZeroBitStorage.java
index eec830f9924f1458e9d3035192408f31a0b87871..225324615cc5d20b928714695f62adee91f43c5a 100644
--- a/src/main/java/net/minecraft/util/ZeroBitStorage.java
+++ b/src/main/java/net/minecraft/util/ZeroBitStorage.java
@@ -5,7 +5,7 @@ import java.util.function.IntConsumer;
import org.apache.commons.lang3.Validate;
public class ZeroBitStorage implements BitStorage {
- public static final long[] RAW = new long[0];
+ public static final long[] RAW = me.titaniumtown.Constants.EMPTY_long_arr; // JettPack
private final int size;
public ZeroBitStorage(int size) {
diff --git a/src/main/java/net/minecraft/world/entity/EquipmentSlot.java b/src/main/java/net/minecraft/world/entity/EquipmentSlot.java
index b68e7db2fbb085c2b25af3e93d501fbaac98893b..d7d39f11fdf4646a78868c22310e77fc4e86ea06 100644
--- a/src/main/java/net/minecraft/world/entity/EquipmentSlot.java
+++ b/src/main/java/net/minecraft/world/entity/EquipmentSlot.java
@@ -13,6 +13,8 @@ public enum EquipmentSlot {
private final int filterFlag;
private final String name;
+ public static final EquipmentSlot[] VALUES = EquipmentSlot.values(); // JettPack - reduce allocs
+
private EquipmentSlot(EquipmentSlot.Type type, int entityId, int armorStandId, String name) {
this.type = type;
this.index = entityId;
diff --git a/src/main/java/net/minecraft/world/entity/LivingEntity.java b/src/main/java/net/minecraft/world/entity/LivingEntity.java
index 2fe2307a10cb2e4e2b055cbe615b3750bf8fd310..f646545ee7178717c1e3bb48e98fd2af2af745e0 100644
--- a/src/main/java/net/minecraft/world/entity/LivingEntity.java
+++ b/src/main/java/net/minecraft/world/entity/LivingEntity.java
@@ -3032,7 +3032,7 @@ public abstract class LivingEntity extends Entity {
@Nullable
private Map<EquipmentSlot, ItemStack> collectEquipmentChanges() {
Map<EquipmentSlot, ItemStack> map = null;
- EquipmentSlot[] aenumitemslot = EquipmentSlot.values();
+ EquipmentSlot[] aenumitemslot = EquipmentSlot.VALUES; // JettPack
int i = aenumitemslot.length;
for (int j = 0; j < i; ++j) {
diff --git a/src/main/java/net/minecraft/world/entity/Mob.java b/src/main/java/net/minecraft/world/entity/Mob.java
index 8ee0a80e3427ecef9fa15b7388a8287e26a25fd6..340589e02b316553acefee480f86cf53d5d17560 100644
--- a/src/main/java/net/minecraft/world/entity/Mob.java
+++ b/src/main/java/net/minecraft/world/entity/Mob.java
@@ -1010,7 +1010,7 @@ public abstract class Mob extends LivingEntity {
@Override
protected void dropCustomDeathLoot(DamageSource source, int lootingMultiplier, boolean allowDrops) {
super.dropCustomDeathLoot(source, lootingMultiplier, allowDrops);
- EquipmentSlot[] aenumitemslot = EquipmentSlot.values();
+ EquipmentSlot[] aenumitemslot = EquipmentSlot.VALUES; // JettPack - reduce allocs
int j = aenumitemslot.length;
for (int k = 0; k < j; ++k) {
@@ -1072,7 +1072,7 @@ public abstract class Mob extends LivingEntity {
}
boolean flag = true;
- EquipmentSlot[] aenumitemslot = EquipmentSlot.values();
+ EquipmentSlot[] aenumitemslot = EquipmentSlot.VALUES; // JettPack - reduce allocs
int j = aenumitemslot.length;
for (int k = 0; k < j; ++k) {
@@ -1159,7 +1159,7 @@ public abstract class Mob extends LivingEntity {
float f = difficulty.getSpecialMultiplier();
this.enchantSpawnedWeapon(f);
- EquipmentSlot[] aenumitemslot = EquipmentSlot.values();
+ EquipmentSlot[] aenumitemslot = EquipmentSlot.VALUES; // JettPack - reduce allocs
int i = aenumitemslot.length;
for (int j = 0; j < i; ++j) {
@@ -1370,7 +1370,7 @@ public abstract class Mob extends LivingEntity {
t0.setInvulnerable(this.isInvulnerable());
if (flag) {
t0.setCanPickUpLoot(this.canPickUpLoot());
- EquipmentSlot[] aenumitemslot = EquipmentSlot.values();
+ EquipmentSlot[] aenumitemslot = EquipmentSlot.VALUES; // JettPack - reduce allocs
int i = aenumitemslot.length;
for (int j = 0; j < i; ++j) {
diff --git a/src/main/java/net/minecraft/world/entity/monster/ZombieVillager.java b/src/main/java/net/minecraft/world/entity/monster/ZombieVillager.java
index fc6639bd33a13c84c84603db7f9bbb1c5df239a4..814e5abe38087f6ca3322923564b59fb31b2bc83 100644
--- a/src/main/java/net/minecraft/world/entity/monster/ZombieVillager.java
+++ b/src/main/java/net/minecraft/world/entity/monster/ZombieVillager.java
@@ -229,7 +229,7 @@ public class ZombieVillager extends Zombie implements VillagerDataHolder {
return;
}
// CraftBukkit end
- EquipmentSlot[] aenumitemslot = EquipmentSlot.values();
+ EquipmentSlot[] aenumitemslot = EquipmentSlot.VALUES; // JettPack - reduce allocs
int i = aenumitemslot.length;
for (int j = 0; j < i; ++j) {
diff --git a/src/main/java/net/minecraft/world/item/ItemStack.java b/src/main/java/net/minecraft/world/item/ItemStack.java
index 6837c965592d4584cfc958a1008b98791a0fc780..586ce0bec1ab2a17a3818690e47be23643cd5a48 100644
--- a/src/main/java/net/minecraft/world/item/ItemStack.java
+++ b/src/main/java/net/minecraft/world/item/ItemStack.java
@@ -957,7 +957,7 @@ public final class ItemStack {
int k;
if (ItemStack.shouldShowInTooltip(i, ItemStack.TooltipPart.MODIFIERS)) {
- EquipmentSlot[] aenumitemslot = EquipmentSlot.values();
+ EquipmentSlot[] aenumitemslot = EquipmentSlot.VALUES; // JettPack - reduce allocs
k = aenumitemslot.length;
diff --git a/src/main/java/net/minecraft/world/item/crafting/ShapedRecipe.java b/src/main/java/net/minecraft/world/item/crafting/ShapedRecipe.java
index 9e3f9099cc47e6c6e40d11ef6d6e83fbf19a3cf7..b9c1db394ee35ed1acead620f7e9e47c60fa1532 100644
--- a/src/main/java/net/minecraft/world/item/crafting/ShapedRecipe.java
+++ b/src/main/java/net/minecraft/world/item/crafting/ShapedRecipe.java
@@ -242,7 +242,7 @@ public class ShapedRecipe implements CraftingRecipe {
}
if (pattern.length == l) {
- return new String[0];
+ return me.titaniumtown.Constants.EMPTY_string_arr; // JettPack
} else {
String[] astring1 = new String[pattern.length - l - k];
diff --git a/src/main/java/net/minecraft/world/item/enchantment/Enchantments.java b/src/main/java/net/minecraft/world/item/enchantment/Enchantments.java
index ef36f0a9b1849dd3152c0a1c81cded5c4f06aa3c..946bb3c6a59d0e611d28549ceee8946b46eaa9e3 100644
--- a/src/main/java/net/minecraft/world/item/enchantment/Enchantments.java
+++ b/src/main/java/net/minecraft/world/item/enchantment/Enchantments.java
@@ -42,8 +42,8 @@ public class Enchantments {
public static final Enchantment MULTISHOT = Enchantments.register("multishot", new MultiShotEnchantment(Enchantment.Rarity.RARE, new EquipmentSlot[]{EquipmentSlot.MAINHAND}));
public static final Enchantment QUICK_CHARGE = Enchantments.register("quick_charge", new QuickChargeEnchantment(Enchantment.Rarity.UNCOMMON, new EquipmentSlot[]{EquipmentSlot.MAINHAND}));
public static final Enchantment PIERCING = Enchantments.register("piercing", new ArrowPiercingEnchantment(Enchantment.Rarity.COMMON, new EquipmentSlot[]{EquipmentSlot.MAINHAND}));
- public static final Enchantment MENDING = Enchantments.register("mending", new MendingEnchantment(Enchantment.Rarity.RARE, EquipmentSlot.values()));
- public static final Enchantment VANISHING_CURSE = Enchantments.register("vanishing_curse", new VanishingCurseEnchantment(Enchantment.Rarity.VERY_RARE, EquipmentSlot.values()));
+ public static final Enchantment MENDING = Enchantments.register("mending", new MendingEnchantment(Enchantment.Rarity.RARE, EquipmentSlot.VALUES)); // JettPack
+ public static final Enchantment VANISHING_CURSE = Enchantments.register("vanishing_curse", new VanishingCurseEnchantment(Enchantment.Rarity.VERY_RARE, EquipmentSlot.VALUES)); // JettPack
// CraftBukkit start
static {
diff --git a/src/main/java/net/minecraft/world/level/EntityBasedExplosionDamageCalculator.java b/src/main/java/net/minecraft/world/level/EntityBasedExplosionDamageCalculator.java
index 4257e5bf92a219f20026e4ec7e0d7323f2adf30e..24612061174b659666e3c09a44ddc597b34f549a 100644
--- a/src/main/java/net/minecraft/world/level/EntityBasedExplosionDamageCalculator.java
+++ b/src/main/java/net/minecraft/world/level/EntityBasedExplosionDamageCalculator.java
@@ -15,9 +15,17 @@ public class EntityBasedExplosionDamageCalculator extends ExplosionDamageCalcula
@Override
public Optional<Float> getBlockExplosionResistance(Explosion explosion, BlockGetter world, BlockPos pos, BlockState blockState, FluidState fluidState) {
- return super.getBlockExplosionResistance(explosion, world, pos, blockState, fluidState).map((max) -> {
- return this.source.getBlockExplosionResistance(explosion, world, pos, blockState, fluidState, max);
- });
+ // JettPack start - lithium: reduce allocs
+ Optional<Float> optionalBlastResistance = super.getBlockExplosionResistance(explosion, world, pos, blockState, fluidState);
+ if (optionalBlastResistance.isPresent()) {
+ float blastResistance = optionalBlastResistance.get();
+ float effectiveExplosionResistance = this.source.getBlockExplosionResistance(explosion, world, pos, blockState, fluidState, blastResistance);
+ if (effectiveExplosionResistance != blastResistance) {
+ return Optional.of(effectiveExplosionResistance);
+ }
+ }
+ return optionalBlastResistance;
+ // JettPack end
}
@Override
diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java
index b830c2199a22252116619520f407fd84eddb28f3..5df2601aecb93fd6014b70d0da645085ddec8076 100644
--- a/src/main/java/net/minecraft/world/level/Level.java
+++ b/src/main/java/net/minecraft/world/level/Level.java
@@ -1566,7 +1566,7 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
public org.bukkit.entity.Entity[] getChunkEntities(int chunkX, int chunkZ) {
io.papermc.paper.world.ChunkEntitySlices slices = this.entitySliceManager.getChunk(chunkX, chunkZ);
if (slices == null) {
- return new org.bukkit.entity.Entity[0];
+ return me.titaniumtown.Constants.EMPTY_bukkit_entity_arr; // JettPack
}
return slices.getChunkEntities();
}
diff --git a/src/main/java/net/minecraft/world/level/block/ComposterBlock.java b/src/main/java/net/minecraft/world/level/block/ComposterBlock.java
index fb8b8a9733ac50096d8406487ab1ae167ef5f7b1..644714723911d950fb179216c4976baa2da85644 100644
--- a/src/main/java/net/minecraft/world/level/block/ComposterBlock.java
+++ b/src/main/java/net/minecraft/world/level/block/ComposterBlock.java
@@ -373,7 +373,7 @@ public class ComposterBlock extends Block implements WorldlyContainerHolder {
@Override
public int[] getSlotsForFace(Direction side) {
- return side == Direction.DOWN ? new int[]{0} : new int[0];
+ return side == Direction.DOWN ? me.titaniumtown.Constants.ZERO_int_arr : me.titaniumtown.Constants.EMPTY_int_arr; // JettPack
}
@Override
@@ -422,7 +422,7 @@ public class ComposterBlock extends Block implements WorldlyContainerHolder {
@Override
public int[] getSlotsForFace(Direction side) {
- return side == Direction.UP ? new int[]{0} : new int[0];
+ return side == Direction.UP ? me.titaniumtown.Constants.ZERO_int_arr : me.titaniumtown.Constants.EMPTY_int_arr; // JettPack
}
@Override
@@ -459,7 +459,7 @@ public class ComposterBlock extends Block implements WorldlyContainerHolder {
@Override
public int[] getSlotsForFace(Direction side) {
- return new int[0];
+ return me.titaniumtown.Constants.EMPTY_int_arr; // JettPack
}
@Override
diff --git a/src/main/java/net/minecraft/world/level/storage/PlayerDataStorage.java b/src/main/java/net/minecraft/world/level/storage/PlayerDataStorage.java
index 601f8099f74e81c17600566b3c9b7a6dd39c9bcb..f816fae46568b83ef4441bd3bb06f2081308921e 100644
--- a/src/main/java/net/minecraft/world/level/storage/PlayerDataStorage.java
+++ b/src/main/java/net/minecraft/world/level/storage/PlayerDataStorage.java
@@ -119,7 +119,7 @@ public class PlayerDataStorage {
String[] astring = this.playerDir.list();
if (astring == null) {
- astring = new String[0];
+ astring = me.titaniumtown.Constants.EMPTY_string_arr; // JettPack
}
for (int i = 0; i < astring.length; ++i) {
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java b/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java
index e91714a66f582c14184ddb5e4bf2443d3ed45efb..174585c55450d6005c822801b0ce43b29091fc64 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java
@@ -4,8 +4,8 @@ import org.bukkit.inventory.EquipmentSlot;
public class CraftEquipmentSlot {
- private static final net.minecraft.world.entity.EquipmentSlot[] slots = new net.minecraft.world.entity.EquipmentSlot[EquipmentSlot.values().length];
- private static final EquipmentSlot[] enums = new EquipmentSlot[net.minecraft.world.entity.EquipmentSlot.values().length];
+ private static final net.minecraft.world.entity.EquipmentSlot[] slots = net.minecraft.world.entity.EquipmentSlot.VALUES;
+ private static final EquipmentSlot[] enums = new EquipmentSlot[net.minecraft.world.entity.EquipmentSlot.VALUES.length];
static {
set(EquipmentSlot.HAND, net.minecraft.world.entity.EquipmentSlot.MAINHAND);
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java
index 6827979a5b270ced53b46ecb9eff548727dadb81..d42175344699d3742c17e658aa689755813ec0ac 100644
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java
@@ -165,7 +165,7 @@ public class CraftEntityEquipment implements EntityEquipment {
@Override
public void clear() {
- for (net.minecraft.world.entity.EquipmentSlot slot : net.minecraft.world.entity.EquipmentSlot.values()) {
+ for (net.minecraft.world.entity.EquipmentSlot slot : net.minecraft.world.entity.EquipmentSlot.VALUES) {
this.setEquipment(slot, null, false);
}
}
diff --git a/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java b/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java
index 049d750d3af991dd14ac8cf644330404e74b2151..f965d6751c8f5a8ec4b26e6ac65414540345b04a 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java
@@ -166,7 +166,7 @@ public final class WeakCollection<T> implements Collection<T> {
@Override
public Object[] toArray() {
- return this.toArray(new Object[0]);
+ return this.toArray(me.titaniumtown.Constants.EMPTY_object_arr);
}
@Override

View File

@@ -0,0 +1,94 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: 2No2Name <2No2Name@web.de>
Date: Tue, 14 Dec 2021 12:04:01 -0500
Subject: [PATCH] lithium: fast util
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/core/Direction.java b/src/main/java/net/minecraft/core/Direction.java
index a75a7a83bea89db4e4a4ca1c06233b3f4350fa73..4be4d9e6611dc3b7a34dbf2f5d6990bc0980ee63 100644
--- a/src/main/java/net/minecraft/core/Direction.java
+++ b/src/main/java/net/minecraft/core/Direction.java
@@ -191,7 +191,7 @@ public enum Direction implements StringRepresentable {
}
public Direction getOpposite() {
- return from3DDataValue(this.oppositeIndex);
+ return VALUES[this.oppositeIndex]; // JettPack - lithium: fast_util
}
public Direction getClockWise(Direction.Axis axis) {
@@ -441,7 +441,7 @@ public enum Direction implements StringRepresentable {
}
public static Direction getRandom(Random random) {
- return Util.getRandom(VALUES, random);
+ return VALUES[random.nextInt(VALUES.length)]; // JettPack - lithium: fast_util
}
public static Direction getNearest(double x, double y, double z) {
diff --git a/src/main/java/net/minecraft/world/phys/AABB.java b/src/main/java/net/minecraft/world/phys/AABB.java
index 0d24ed60976d862c14cca4af0f6efc15f7c52c7e..9c1e6287b290df11072e1d7b892e77ae10c95af1 100644
--- a/src/main/java/net/minecraft/world/phys/AABB.java
+++ b/src/main/java/net/minecraft/world/phys/AABB.java
@@ -6,6 +6,7 @@ import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.Mth;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
+import net.minecraft.core.Direction; // JettPack
public class AABB {
private static final double EPSILON = 1.0E-7D;
@@ -16,6 +17,15 @@ public class AABB {
public final double maxY;
public final double maxZ;
+ // JettPack start - lithium: fast_util
+ static {
+ assert Direction.Axis.X.ordinal() == 0;
+ assert Direction.Axis.Y.ordinal() == 1;
+ assert Direction.Axis.Z.ordinal() == 2;
+ assert Direction.Axis.values().length == 3;
+ }
+ // JettPack end
+
public AABB(double x1, double y1, double z1, double x2, double y2, double z2) {
this.minX = Math.min(x1, x2);
this.minY = Math.min(y1, y2);
@@ -81,11 +91,33 @@ public class AABB {
}
public double min(Direction.Axis axis) {
- return axis.choose(this.minX, this.minY, this.minZ);
+ // JettPack start - lithium: fast_util
+ switch (axis.ordinal()) {
+ case 0: //X
+ return this.minX;
+ case 1: //Y
+ return this.minY;
+ case 2: //Z
+ return this.minZ;
+ }
+
+ throw new IllegalArgumentException();
+ // JettPack end
}
public double max(Direction.Axis axis) {
- return axis.choose(this.maxX, this.maxY, this.maxZ);
+ // JettPack start - lithium: fast_util
+ switch (axis.ordinal()) {
+ case 0: //X
+ return this.maxX;
+ case 1: //Y
+ return this.maxY;
+ case 2: //Z
+ return this.maxZ;
+ }
+
+ throw new IllegalArgumentException();
+ // JettPack end
}
@Override

View File

@@ -0,0 +1,309 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: JellySquid <jellysquid+atwork@protonmail.com>
Date: Fri, 31 Jul 2020 21:46:32 -0500
Subject: [PATCH] lithium: HashedList
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/me/jellysquid/mods/lithium/common/util/collections/HashedList.java b/src/main/java/me/jellysquid/mods/lithium/common/util/collections/HashedList.java
new file mode 100644
index 0000000000000000000000000000000000000000..2d79932dbd1fc386a94b8d6ea3526934c54c2aad
--- /dev/null
+++ b/src/main/java/me/jellysquid/mods/lithium/common/util/collections/HashedList.java
@@ -0,0 +1,280 @@
+package me.jellysquid.mods.lithium.common.util.collections;
+
+import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
+import it.unimi.dsi.fastutil.objects.ReferenceArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+
+/**
+ * Wraps a {@link List} with a hash table which provides O(1) lookups for {@link Collection#contains(Object)}. The type
+ * contained by this list must use reference-equality semantics.
+ */
+@SuppressWarnings("SuspiciousMethodCalls")
+public class HashedList<T> implements List<T> {
+ private final ReferenceArrayList<T> list;
+ private final Reference2IntOpenHashMap<T> counter;
+
+ public HashedList(List<T> list) {
+ this.list = new ReferenceArrayList<>();
+ this.list.addAll(list);
+
+ this.counter = new Reference2IntOpenHashMap<>();
+ this.counter.defaultReturnValue(0);
+
+ for (T obj : this.list) {
+ this.counter.addTo(obj, 1);
+ }
+ }
+
+ @Override
+ public int size() {
+ return this.list.size();
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return this.list.isEmpty();
+ }
+
+ @Override
+ public boolean contains(Object o) {
+ return this.counter.containsKey(o);
+ }
+
+ @Override
+ public Iterator<T> iterator() {
+ return this.listIterator();
+ }
+
+ @Override
+ public Object[] toArray() {
+ return this.list.toArray();
+ }
+
+ @SuppressWarnings("SuspiciousToArrayCall")
+ @Override
+ public <T1> T1[] toArray(T1[] a) {
+ return this.list.toArray(a);
+ }
+
+ @Override
+ public boolean add(T t) {
+ this.trackReferenceAdded(t);
+
+ return this.list.add(t);
+ }
+
+ @Override
+ public boolean remove(Object o) {
+ this.trackReferenceRemoved(o);
+
+ return this.list.remove(o);
+ }
+
+ @Override
+ public boolean containsAll(Collection<?> c) {
+ for (Object obj : c) {
+ if (!this.counter.containsKey(obj)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean addAll(Collection<? extends T> c) {
+ for (T obj : c) {
+ this.trackReferenceAdded(obj);
+ }
+
+ return this.list.addAll(c);
+ }
+
+ @Override
+ public boolean addAll(int index, Collection<? extends T> c) {
+ for (T obj : c) {
+ this.trackReferenceAdded(obj);
+ }
+
+ return this.list.addAll(index, c);
+ }
+
+ @Override
+ public boolean removeAll(Collection<?> c) {
+ for (Object obj : c) {
+ this.trackReferenceRemoved(obj);
+ }
+
+ return this.list.removeAll(c);
+ }
+
+ @Override
+ public boolean retainAll(Collection<?> c) {
+ return this.list.retainAll(c);
+ }
+
+ @Override
+ public void clear() {
+ this.counter.clear();
+ this.list.clear();
+ }
+
+ @Override
+ public T get(int index) {
+ return this.list.get(index);
+ }
+
+ @Override
+ public T set(int index, T element) {
+ T prev = this.list.set(index, element);
+
+ if (prev != element) {
+ if (prev != null) {
+ this.trackReferenceRemoved(prev);
+ }
+
+ this.trackReferenceAdded(element);
+ }
+
+ return prev;
+ }
+
+ @Override
+ public void add(int index, T element) {
+ this.trackReferenceAdded(element);
+
+ this.list.add(index, element);
+ }
+
+ @Override
+ public T remove(int index) {
+ T prev = this.list.remove(index);
+
+ if (prev != null) {
+ this.trackReferenceRemoved(prev);
+ }
+
+ return prev;
+ }
+
+ @Override
+ public int indexOf(Object o) {
+ return this.list.indexOf(o);
+ }
+
+ @Override
+ public int lastIndexOf(Object o) {
+ return this.list.lastIndexOf(o);
+ }
+
+ @Override
+ public ListIterator<T> listIterator() {
+ return this.listIterator(0);
+ }
+
+ @Override
+ public ListIterator<T> listIterator(int index) {
+ return new ListIterator<T>() {
+ private final ListIterator<T> inner = HashedList.this.list.listIterator(index);
+
+ @Override
+ public boolean hasNext() {
+ return this.inner.hasNext();
+ }
+
+ @Override
+ public T next() {
+ return this.inner.next();
+ }
+
+ @Override
+ public boolean hasPrevious() {
+ return this.inner.hasPrevious();
+ }
+
+ @Override
+ public T previous() {
+ return this.inner.previous();
+ }
+
+ @Override
+ public int nextIndex() {
+ return this.inner.nextIndex();
+ }
+
+ @Override
+ public int previousIndex() {
+ return this.inner.previousIndex();
+ }
+
+ @Override
+ public void remove() {
+ int last = this.previousIndex();
+
+ if (last == -1) {
+ throw new NoSuchElementException();
+ }
+
+ T prev = HashedList.this.get(last);
+
+ if (prev != null) {
+ HashedList.this.trackReferenceRemoved(prev);
+ }
+
+ this.inner.remove();
+ }
+
+ @Override
+ public void set(T t) {
+ int last = this.previousIndex();
+
+ if (last == -1) {
+ throw new NoSuchElementException();
+ }
+
+ T prev = HashedList.this.get(last);
+
+ if (prev != t) {
+ if (prev != null) {
+ HashedList.this.trackReferenceRemoved(prev);
+ }
+
+ HashedList.this.trackReferenceAdded(t);
+ }
+
+ this.inner.remove();
+ }
+
+ @Override
+ public void add(T t) {
+ HashedList.this.trackReferenceAdded(t);
+
+ this.inner.add(t);
+ }
+ };
+ }
+
+ @Override
+ public List<T> subList(int fromIndex, int toIndex) {
+ return this.list.subList(fromIndex, toIndex);
+ }
+
+ private void trackReferenceAdded(T t) {
+ this.counter.addTo(t, 1);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void trackReferenceRemoved(Object o) {
+ if (this.counter.addTo((T) o, -1) <= 1) {
+ this.counter.removeInt(o);
+ }
+ }
+
+ public static <T> HashedList<T> wrapper(List<T> list) {
+ return new HashedList<>(list);
+ }
+}
diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java
index 5df2601aecb93fd6014b70d0da645085ddec8076..8fb58a59181fdf3a6ca5710d42eac060fc756395 100644
--- a/src/main/java/net/minecraft/world/level/Level.java
+++ b/src/main/java/net/minecraft/world/level/Level.java
@@ -115,8 +115,8 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
public static final int TICKS_PER_DAY = 24000;
public static final int MAX_ENTITY_SPAWN_Y = 20000000;
public static final int MIN_ENTITY_SPAWN_Y = -20000000;
- protected final List<TickingBlockEntity> blockEntityTickers = Lists.newArrayList(); public final int getTotalTileEntityTickers() { return this.blockEntityTickers.size(); } // Paper
- private final List<TickingBlockEntity> pendingBlockEntityTickers = Lists.newArrayList();
+ protected final List<TickingBlockEntity> blockEntityTickers = me.jellysquid.mods.lithium.common.util.collections.HashedList.wrapper(Lists.newArrayList()); public final int getTotalTileEntityTickers() { return this.blockEntityTickers.size(); } // Paper // Jettpack - lithium: hashed_list
+ private final List<TickingBlockEntity> pendingBlockEntityTickers = me.jellysquid.mods.lithium.common.util.collections.HashedList.wrapper(Lists.newArrayList()); // Jettpack - lithium: hashed_list
private boolean tickingBlockEntities;
public final Thread thread;
private final boolean isDebug;

View File

@@ -0,0 +1,143 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: JellySquid <jellysquid+atwork@protonmail.com>
Date: Fri, 5 Feb 2021 00:16:30 -0600
Subject: [PATCH] lithium: CompactSineLUT
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/me/jellysquid/mods/lithium/common/util/math/CompactSineLUT.java b/src/main/java/me/jellysquid/mods/lithium/common/util/math/CompactSineLUT.java
new file mode 100644
index 0000000000000000000000000000000000000000..d2b00d9a91b60716d5f458048df3d944060eb749
--- /dev/null
+++ b/src/main/java/me/jellysquid/mods/lithium/common/util/math/CompactSineLUT.java
@@ -0,0 +1,90 @@
+package me.jellysquid.mods.lithium.common.util.math;
+
+import net.minecraft.util.Mth;
+
+/**
+ * A replacement for the sine angle lookup table used in {@link Mth}, both reducing the size of LUT and improving
+ * the access patterns for common paired sin/cos operations.
+ *
+ * sin(-x) = -sin(x)
+ * ... to eliminate negative angles from the LUT.
+ *
+ * sin(x) = sin(pi/2 - x)
+ * ... to eliminate supplementary angles from the LUT.
+ *
+ * Using these identities allows us to reduce the LUT from 64K entries (256 KB) to just 16K entries (64 KB), enabling
+ * it to better fit into the CPU's caches at the expense of some cycles on the fast path. The implementation has been
+ * tightly optimized to avoid branching where possible and to use very quick integer operations.
+ *
+ * Generally speaking, reducing the size of a lookup table is always a good optimization, but since we need to spend
+ * extra CPU cycles trying to maintain parity with vanilla, there is the potential risk that this implementation ends
+ * up being slower than vanilla when the lookup table is able to be kept in cache memory.
+ *
+ * Unlike other "fast math" implementations, the values returned by this class are *bit-for-bit identical* with those
+ * from {@link Mth}. Validation is performed during runtime to ensure that the table is correct.
+ *
+ * @author coderbot16 Author of the original (and very clever) implementation in Rust:
+ * https://gitlab.com/coderbot16/i73/-/tree/master/i73-trig/src
+ * @author jellysquid3 Additional optimizations, port to Java
+ */
+public class CompactSineLUT {
+ private static final int[] SINE_TABLE_INT = new int[16384 + 1];
+ private static final float SINE_TABLE_MIDPOINT;
+
+ static {
+ final float[] SINE_TABLE = Mth.getSinTable();
+ // Copy the sine table, covering to raw int bits
+ for (int i = 0; i < SINE_TABLE_INT.length; i++) {
+ SINE_TABLE_INT[i] = Float.floatToRawIntBits(SINE_TABLE[i]);
+ }
+
+ SINE_TABLE_MIDPOINT = SINE_TABLE[SINE_TABLE.length / 2];
+
+ // Test that the lookup table is correct during runtime
+ for (int i = 0; i < SINE_TABLE.length; i++) {
+ float expected = SINE_TABLE[i];
+ float value = lookup(i);
+
+ if (expected != value) {
+ throw new IllegalArgumentException(String.format("LUT error at index %d (expected: %s, found: %s)", i, expected, value));
+ }
+ }
+ }
+
+ // [VanillaCopy] MathHelper#sin(float)
+ public static float sin(float f) {
+ return lookup((int) (f * 10430.38) & 0xFFFF);
+ }
+
+ // [VanillaCopy] MathHelper#cos(float)
+ public static float cos(float f) {
+ return lookup((int) (f * 10430.38 + 16384.0) & 0xFFFF);
+ }
+
+ private static float lookup(int index) {
+ // A special case... Is there some way to eliminate this?
+ if (index == 32768) {
+ return SINE_TABLE_MIDPOINT;
+ }
+
+ // Trigonometric identity: sin(-x) = -sin(x)
+ // Given a domain of 0 <= x <= 2*pi, just negate the value if x > pi.
+ // This allows the sin table size to be halved.
+ int neg = (index & 0x8000) << 16;
+
+ // All bits set if (pi/2 <= x), none set otherwise
+ // Extracts the 15th bit from 'half'
+ int mask = (index << 17) >> 31;
+
+ // Trigonometric identity: sin(x) = sin(pi/2 - x)
+ int pos = (0x8001 & mask) + (index ^ mask);
+
+ // Wrap the position in the table. Moving this down to immediately before the array access
+ // seems to help the Hotspot compiler optimize the bit math better.
+ pos &= 0x7fff;
+
+ // Fetch the corresponding value from the LUT and invert the sign bit as needed
+ // This directly manipulate the sign bit on the float bits to simplify logic
+ return Float.intBitsToFloat(SINE_TABLE_INT[pos] ^ neg);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/net/minecraft/util/Mth.java b/src/main/java/net/minecraft/util/Mth.java
index 42e0c370092eb6c190dbf3b279649d47b81950af..23d4efac14b391a5f654013fc549c3274c160ffa 100644
--- a/src/main/java/net/minecraft/util/Mth.java
+++ b/src/main/java/net/minecraft/util/Mth.java
@@ -8,6 +8,7 @@ import net.minecraft.core.Vec3i;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import org.apache.commons.lang3.math.NumberUtils;
+import me.jellysquid.mods.lithium.common.util.math.CompactSineLUT; // Mirai
public class Mth {
private static final int BIG_ENOUGH_INT = 1024;
@@ -30,7 +31,8 @@ public class Mth {
}
});
- private static final Random RANDOM = new Random();
+ private static final Random RANDOM = new Random(); // Mirai - too lazy to edit correctly this line
+ public static float[] getSinTable() { return SIN; } // Mirai
private static final int[] MULTIPLY_DE_BRUIJN_BIT_POSITION = new int[]{0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
private static final double ONE_SIXTH = 0.16666666666666666D;
private static final int FRAC_EXP = 8;
@@ -40,11 +42,13 @@ public class Mth {
private static final double[] COS_TAB = new double[257];
public static float sin(float value) {
- return SIN[(int)(value * 10430.378F) & '\uffff'];
+ //return SIN[(int)(value * 10430.378F) & '\uffff'];
+ return CompactSineLUT.sin(value); // Mirai
}
public static float cos(float value) {
- return SIN[(int)(value * 10430.378F + 16384.0F) & '\uffff'];
+ //return SIN[(int)(value * 10430.378F + 16384.0F) & '\uffff'];
+ return CompactSineLUT.cos(value); // Mirai
}
public static float sqrt(float value) {

View File

@@ -0,0 +1,99 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: 2No2Name <2No2Name@web.de>
Date: Wed, 15 Dec 2021 11:20:48 -0500
Subject: [PATCH] lithium: fast retrieval
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/level/entity/EntitySectionStorage.java b/src/main/java/net/minecraft/world/level/entity/EntitySectionStorage.java
index 2ad47b33aea2493b2cdc0431849ecd50a12f9146..ba8aef74c0c23a39b0e4387916a904e14d41a25a 100644
--- a/src/main/java/net/minecraft/world/level/entity/EntitySectionStorage.java
+++ b/src/main/java/net/minecraft/world/level/entity/EntitySectionStorage.java
@@ -32,33 +32,66 @@ public class EntitySectionStorage<T extends EntityAccess> {
this.intialSectionVisibility = chunkStatusDiscriminator;
}
+ // JettPack start - lithium: entity.fast_retrieval
public void forEachAccessibleNonEmptySection(AABB box, Consumer<EntitySection<T>> action) {
- int i = SectionPos.posToSectionCoord(box.minX - 2.0D);
- int j = SectionPos.posToSectionCoord(box.minY - 2.0D);
- int k = SectionPos.posToSectionCoord(box.minZ - 2.0D);
- int l = SectionPos.posToSectionCoord(box.maxX + 2.0D);
- int m = SectionPos.posToSectionCoord(box.maxY + 2.0D);
- int n = SectionPos.posToSectionCoord(box.maxZ + 2.0D);
-
- for(int o = i; o <= l; ++o) {
- long p = SectionPos.asLong(o, 0, 0);
- long q = SectionPos.asLong(o, -1, -1);
- LongIterator longIterator = this.sectionIds.subSet(p, q + 1L).iterator();
-
- while(longIterator.hasNext()) {
- long r = longIterator.nextLong();
- int s = SectionPos.y(r);
- int t = SectionPos.z(r);
- if (s >= j && s <= m && t >= k && t <= n) {
- EntitySection<T> entitySection = this.sections.get(r);
- if (entitySection != null && !entitySection.isEmpty() && entitySection.getStatus().isAccessible()) {
- action.accept(entitySection);
+ int minX = SectionPos.posToSectionCoord(box.minX - 2.0D);
+ int minY = SectionPos.posToSectionCoord(box.minY - 2.0D);
+ int minZ = SectionPos.posToSectionCoord(box.minZ - 2.0D);
+ int maxX = SectionPos.posToSectionCoord(box.maxX + 2.0D);
+ int maxY = SectionPos.posToSectionCoord(box.maxY + 2.0D);
+ int maxZ = SectionPos.posToSectionCoord(box.maxZ + 2.0D);
+
+ if (maxX >= minX + 4 || maxZ >= minZ + 4) {
+ // [VanillaCopy]
+ for(int o = minX; o <= maxX; ++o) {
+ long p = SectionPos.asLong(o, 0, 0);
+ long q = SectionPos.asLong(o, -1, -1);
+ LongIterator longIterator = this.sectionIds.subSet(p, q + 1L).iterator();
+
+ while(longIterator.hasNext()) {
+ long r = longIterator.nextLong();
+ int s = SectionPos.y(r);
+ int t = SectionPos.z(r);
+ if (s >= minY && s <= maxY && t >= minZ && t <= maxZ) {
+ EntitySection<T> entitySection = this.sections.get(r);
+ if (entitySection != null && !entitySection.isEmpty() && entitySection.getStatus().isAccessible()) {
+ action.accept(entitySection);
+ }
}
}
}
+ } else {
+ for (int x = minX; x <= maxX; x++) {
+ for (int z = Math.max(minZ, 0); z <= maxZ; z++) {
+ this.forEachInColumn(x, minY, maxY, z, action);
+ }
+
+ int bound = Math.min(-1, maxZ);
+ for (int z = minZ; z <= bound; z++) {
+ this.forEachInColumn(x, minY, maxY, z, action);
+ }
+ }
}
+ }
+ private void forEachInColumn(int x, int minY, int maxY, int z, Consumer<EntitySection<T>> action) {
+ //y from negative to positive, but y is treated as unsigned
+ for (int y = Math.max(minY, 0); y <= maxY; y++) {
+ this.consumeSection(SectionPos.asLong(x, y, z), action);
+ }
+ int bound = Math.min(-1, maxY);
+ for (int y = minY; y <= bound; y++) {
+ this.consumeSection(SectionPos.asLong(x, y, z), action);
+ }
+ }
+
+ private void consumeSection(long pos, Consumer<EntitySection<T>> action) {
+ EntitySection<T> section = this.getSection(pos);
+ if (section != null && 0 != section.size() && section.getStatus().isAccessible()) {
+ action.accept(section);
+ }
}
+ // JettPack end
public LongStream getExistingSectionPositionsInChunk(long chunkPos) {
int i = ChunkPos.getX(chunkPos);

View File

@@ -0,0 +1,45 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Simon Gardling <titaniumtown@gmail.com>
Date: Wed, 20 Jan 2021 16:36:48 -0500
Subject: [PATCH] Add config for logging login location
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java
index 49e27efb5fdf26f6a8026c8c17e25d87026ab45d..15b5d142a8261f397ab2ab939d92aeb5701e28fb 100644
--- a/src/main/java/net/minecraft/server/players/PlayerList.java
+++ b/src/main/java/net/minecraft/server/players/PlayerList.java
@@ -494,7 +494,13 @@ public abstract class PlayerList {
}
// Paper end
// CraftBukkit - Moved from above, added world
- PlayerList.LOGGER.info("{}[{}] logged in with entity id {} at ([{}]{}, {}, {})", player.getName().getString(), s1, player.getId(), worldserver1.serverLevelData.getLevelName(), player.getX(), player.getY(), player.getZ());
+ // Yatopia start - configurable logging of player login location
+ if (wtf.etil.mirai.MiraiConfig.logPlayerLoginLoc) {
+ PlayerList.LOGGER.info("{}[{}] logged in with entity id {} at ([{}]{}, {}, {})", player.getName().getString(), s1, player.getId(), worldserver1.serverLevelData.getLevelName(), player.getX(), player.getY(), player.getZ());
+ } else {
+ PlayerList.LOGGER.info("{}[{}] logged in with entity id {}", player.getName().getString(), s1, player.getId());
+ }
+ // Yatopia end - configurable logging of player login location
}
public void updateEntireScoreboard(ServerScoreboard scoreboard, ServerPlayer player) {
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index 5b30b329959811f99f13f32166574f90e765bcb1..63d750d5858d20304b9608697ae618eb97cb6eb6 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -184,6 +184,11 @@ public class MiraiConfig {
// Mirai - settings below
-
+ public static boolean logPlayerLoginLoc = true;
+ private static void logPlayerLoc() {
+ logPlayerLoginLoc = getBoolean("log-player-login-location", logPlayerLoginLoc);
+ }
+
+
}
\ No newline at end of file

View File

@@ -0,0 +1,42 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: tr7zw <tr7zw@live.de>
Date: Sat, 25 Jul 2020 17:16:18 +0200
Subject: [PATCH] Global Eula file
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/src/main/java/net/minecraft/server/Eula.java b/src/main/java/net/minecraft/server/Eula.java
index 30599028f6263fbf61ab95d68573073426db19db..9e169c96fa1bc9dea9efb27cb996b4dd5d2a4c0c 100644
--- a/src/main/java/net/minecraft/server/Eula.java
+++ b/src/main/java/net/minecraft/server/Eula.java
@@ -16,12 +16,26 @@ public class Eula {
public Eula(Path eulaFile) {
this.file = eulaFile;
- this.agreed = SharedConstants.IS_RUNNING_IN_IDE || this.readFile();
+ this.agreed = SharedConstants.IS_RUNNING_IN_IDE || globalEula() || this.readFile(eulaFile);
}
- private boolean readFile() {
+ // Yatopia start - global eula file
+ private boolean globalEula() {
+ java.io.File globalEula = new java.io.File(System.getProperty("user.home"), "eula.txt");
+
+ if (globalEula.exists()) {
+ System.out.println("Loaded global eula file from " + globalEula.getAbsolutePath());
+ return readFile(globalEula.toPath());
+ } else {
+ System.out.println("No global eula file found at " + globalEula.getAbsolutePath());
+ }
+ return false;
+ }
+ // Yatopia end
+
+ private boolean readFile(java.nio.file.Path path) {
try {
- InputStream inputStream = Files.newInputStream(this.file);
+ InputStream inputStream = Files.newInputStream(path);
boolean var3;
try {

View File

@@ -0,0 +1,74 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Ivan Pekov <ivan@mrivanplays.com>
Date: Fri, 4 Sep 2020 10:07:42 +0300
Subject: [PATCH] Stop wasting resources on JsonList#get
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java
index 15b5d142a8261f397ab2ab939d92aeb5701e28fb..ba8e58fe70f16dbc0b64a92264d29c91461d2cdf 100644
--- a/src/main/java/net/minecraft/server/players/PlayerList.java
+++ b/src/main/java/net/minecraft/server/players/PlayerList.java
@@ -754,13 +754,19 @@ public abstract class PlayerList {
if (getBans().isBanned(gameprofile) && (gameprofilebanentry = getBans().get(gameprofile)) != null) {
// Paper end
+ if (!gameprofilebanentry.hasExpired()) { // Yatopia
chatmessage = new TranslatableComponent("multiplayer.disconnect.banned.reason", new Object[]{gameprofilebanentry.getReason()});
if (gameprofilebanentry.getExpires() != null) {
chatmessage.append((Component) (new TranslatableComponent("multiplayer.disconnect.banned.expiration", new Object[]{PlayerList.BAN_DATE_FORMAT.format(gameprofilebanentry.getExpires())})));
}
// return chatmessage;
+ // Yatopia start - Stop wasting resources on JsonList#get
event.disallow(PlayerLoginEvent.Result.KICK_BANNED, PaperAdventure.asAdventure(chatmessage)); // Paper - Adventure
+ } else {
+ getBans().remove(gameprofile);
+ }
+ // Yatopia end
} else if (!this.isWhitelisted(gameprofile, event)) { // Paper
//chatmessage = new ChatMessage("multiplayer.disconnect.not_whitelisted"); // Paper
//event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, org.spigotmc.SpigotConfig.whitelistMessage); // Spigot // Paper - moved to isWhitelisted
diff --git a/src/main/java/net/minecraft/server/players/StoredUserList.java b/src/main/java/net/minecraft/server/players/StoredUserList.java
index 63c0fe30ff035b6b5c1b4b35d3ad6c649d94e421..f01621bf34da2ea877e010834511c119664a03b7 100644
--- a/src/main/java/net/minecraft/server/players/StoredUserList.java
+++ b/src/main/java/net/minecraft/server/players/StoredUserList.java
@@ -73,9 +73,14 @@ public abstract class StoredUserList<K, V extends StoredUserEntry<K>> {
// Paper start
// this.g();
// return (V) this.d.get(this.a(k0)); // CraftBukkit - fix decompile error
+ // Yatopia start - only remove if it expires and has been requested (Stop wasting resources on JsonList#get)
+ return this.map.get(this.getKeyForUser(key));
+ /*
return (V) this.map.computeIfPresent(this.getKeyForUser(key), (k, v) -> {
return v.hasExpired() ? null : v;
});
+ */
+ // Sugarcane end
// Paper end
}
@@ -150,6 +155,8 @@ public abstract class StoredUserList<K, V extends StoredUserEntry<K>> {
public void save() throws IOException {
this.removeExpired(); // Paper - remove expired values before saving
JsonArray jsonarray = new JsonArray();
+ // Yatopia start - we're nuking streams wherever possible (Stop wasting resources on JsonList#get)
+ /*
Stream<JsonObject> stream = this.map.values().stream().map((jsonlistentry) -> { // CraftBukkit - decompile error
JsonObject jsonobject = new JsonObject();
@@ -159,6 +166,13 @@ public abstract class StoredUserList<K, V extends StoredUserEntry<K>> {
Objects.requireNonNull(jsonarray);
stream.forEach(jsonarray::add);
+ */
+ for (V value : this.map.values()) {
+ JsonObject obj = new JsonObject();
+ value.serialize(obj);
+ jsonarray.add(obj);
+ }
+ // Yatopia end
BufferedWriter bufferedwriter = Files.newWriter(this.file, StandardCharsets.UTF_8);
try {

View File

@@ -0,0 +1,35 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Etil <81570777+etil2jz@users.noreply.github.com>
Date: Thu, 9 Dec 2021 15:39:29 +0100
Subject: [PATCH] Configurable max bees in hive
diff --git a/src/main/java/net/minecraft/world/level/block/entity/BeehiveBlockEntity.java b/src/main/java/net/minecraft/world/level/block/entity/BeehiveBlockEntity.java
index 483dc52c793d9f90a35b1d091dd8ce71115e4640..0282c11936f817dd86861960cf58b8466e8d27f6 100644
--- a/src/main/java/net/minecraft/world/level/block/entity/BeehiveBlockEntity.java
+++ b/src/main/java/net/minecraft/world/level/block/entity/BeehiveBlockEntity.java
@@ -42,7 +42,7 @@ public class BeehiveBlockEntity extends BlockEntity {
private final List<BeehiveBlockEntity.BeeData> stored = Lists.newArrayList();
@Nullable
public BlockPos savedFlowerPos;
- public int maxBees = 3; // CraftBukkit - allow setting max amount of bees a hive can hold
+ public int maxBees = wtf.etil.mirai.MiraiConfig.maxBees; // CraftBukkit - allow setting max amount of bees a hive can hold // Mirai - configurable max bees in hive
public BeehiveBlockEntity(BlockPos pos, BlockState state) {
super(BlockEntityType.BEEHIVE, pos, state);
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index 63d750d5858d20304b9608697ae618eb97cb6eb6..667eaabe95e9b44cad64dd5aba5ac693f4d726ed 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -189,6 +189,9 @@ public class MiraiConfig {
logPlayerLoginLoc = getBoolean("log-player-login-location", logPlayerLoginLoc);
}
-
+ public static int maxBees = 3;
+ private static void maximumBees() {
+ maxBees = getInt("max-bees-in-hive", maxBees);
+ }
}
\ No newline at end of file

View File

@@ -0,0 +1,97 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: foss-mc <69294560+foss-mc@users.noreply.github.com>
Date: Thu, 1 Jul 2021 11:59:11 +0000
Subject: [PATCH] Remove TickTask
Original code by PatinaMC, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/PatinaMC/Patina
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 26841729126b022f75e55e584fe850771dedd4cd..38754510081b130e045900bec6d7e0a9cb47b767 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -185,7 +185,7 @@ import org.bukkit.event.server.ServerLoadEvent;
import co.aikar.timings.MinecraftTimings; // Paper
-public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTask> implements CommandSource, AutoCloseable {
+public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnable> implements CommandSource, AutoCloseable { // Patina
private static MinecraftServer SERVER; // Paper
public static final Logger LOGGER = LogUtils.getLogger();
@@ -1352,19 +1352,21 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
}
@Override
- public TickTask wrapRunnable(Runnable runnable) {
+ public Runnable wrapRunnable(Runnable runnable) { // Patina
// Paper start - anything that does try to post to main during watchdog crash, run on watchdog
if (this.hasStopped && Thread.currentThread().equals(shutdownThread)) {
runnable.run();
runnable = () -> {};
}
// Paper end
- return new TickTask(this.tickCount, runnable);
+ return runnable; // Patina
}
+ /* // Patina
protected boolean shouldRun(TickTask ticktask) {
return ticktask.getTick() + 3 < this.tickCount || this.haveTime();
}
+ */
@Override
public boolean pollTask() {
@@ -1396,10 +1398,12 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
}
}
+ /* // Patina
public void doRunTask(TickTask ticktask) { // CraftBukkit - decompile error
this.getProfiler().incrementCounter("runTask");
super.doRunTask(ticktask);
}
+ */
private void updateStatusIcon(ServerStatus metadata) {
Optional<File> optional = Optional.of(this.getFile("server-icon.png")).filter(File::isFile);
diff --git a/src/main/java/net/minecraft/server/level/ServerChunkCache.java b/src/main/java/net/minecraft/server/level/ServerChunkCache.java
index b42e32bd1a6a669f498b577ec04661c4ba651198..fed79d31c36b9fafbdc71461e27b1f4e1ca0385a 100644
--- a/src/main/java/net/minecraft/server/level/ServerChunkCache.java
+++ b/src/main/java/net/minecraft/server/level/ServerChunkCache.java
@@ -1257,10 +1257,12 @@ public class ServerChunkCache extends ChunkSource {
return runnable;
}
+ /* // Patina
@Override
protected boolean shouldRun(Runnable task) {
return true;
}
+ */
@Override
protected boolean scheduleExecutables() {
diff --git a/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java b/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
index 6158420c629d6acdaafb01a7e00d788023e922d1..9321e3a8b2f6f2eaebfa55679f287429d009e834 100644
--- a/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
+++ b/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
@@ -29,7 +29,7 @@ public abstract class BlockableEventLoop<R extends Runnable> implements Profiler
protected abstract R wrapRunnable(Runnable runnable);
- protected abstract boolean shouldRun(R task);
+ //protected abstract boolean shouldRun(R task); // Patina
public boolean isSameThread() {
return Thread.currentThread() == this.getRunningThread();
@@ -120,7 +120,7 @@ public abstract class BlockableEventLoop<R extends Runnable> implements Profiler
R runnable = this.pendingRunnables.peek();
if (runnable == null) {
return false;
- } else if (this.blockingCount == 0 && !this.shouldRun(runnable)) {
+ } else if (this.blockingCount == 0 && !true/*this.shouldRun(runnable)*/) { // Patina
return false;
} else {
this.doRunTask(this.pendingRunnables.remove());

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: foss-mc <69294560+foss-mc@users.noreply.github.com>
Date: Thu, 1 Jul 2021 12:11:49 +0000
Subject: [PATCH] Make a field final
Original code by PatinaMC, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/PatinaMC/Patina
diff --git a/src/main/java/net/minecraft/commands/CommandSourceStack.java b/src/main/java/net/minecraft/commands/CommandSourceStack.java
index 00bbf33aa44e2d5a4e755a2d7c1a60de9e36674f..ec6a06460469a8bc2e10064d5b78b4b5daa6cc13 100644
--- a/src/main/java/net/minecraft/commands/CommandSourceStack.java
+++ b/src/main/java/net/minecraft/commands/CommandSourceStack.java
@@ -56,7 +56,7 @@ public class CommandSourceStack implements SharedSuggestionProvider, com.destroy
private final ResultConsumer<CommandSourceStack> consumer;
private final EntityAnchorArgument.Anchor anchor;
private final Vec2 rotation;
- public java.util.Map<Thread, CommandNode> currentCommand = new java.util.concurrent.ConcurrentHashMap<>(); // CraftBukkit // Paper
+ public final java.util.Map<Thread, CommandNode> currentCommand = new java.util.concurrent.ConcurrentHashMap<>(); // CraftBukkit // Paper // Patina - make a field final
public CommandSourceStack(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String name, Component displayName, MinecraftServer server, @Nullable Entity entity) {
this(output, pos, rot, world, level, name, displayName, server, entity, false, (commandcontext, flag, j) -> {

View File

@@ -0,0 +1,61 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Etil <81570777+etil2jz@users.noreply.github.com>
Date: Wed, 5 Jan 2022 20:49:49 +0100
Subject: [PATCH] Don't create new random instance
diff --git a/src/main/java/net/minecraft/server/level/ServerPlayer.java b/src/main/java/net/minecraft/server/level/ServerPlayer.java
index a6edf5117d4ae03d8294e7bb74dd2d77048895a5..1a9afa43a953e5634edb23ef617ead4b329ae89f 100644
--- a/src/main/java/net/minecraft/server/level/ServerPlayer.java
+++ b/src/main/java/net/minecraft/server/level/ServerPlayer.java
@@ -367,7 +367,7 @@ public class ServerPlayer extends Player {
long l = k * k;
int i1 = l > 2147483647L ? Integer.MAX_VALUE : (int) l;
int j1 = this.getCoprime(i1);
- int k1 = (new Random()).nextInt(i1);
+ int k1 = worldserver.random.nextInt(i1); // Patina - don't create new random instance
for (int l1 = 0; l1 < i1; ++l1) {
int i2 = (k1 + j1 * l1) % i1;
@@ -404,7 +404,7 @@ public class ServerPlayer extends Player {
long l = k * k;
int i1 = l > 2147483647L ? Integer.MAX_VALUE : (int) l;
int j1 = this.getCoprime(i1);
- int k1 = (new Random()).nextInt(i1);
+ int k1 = world.random.nextInt(i1); // Patina - don't create new random instance
for (int l1 = 0; l1 < i1; ++l1) {
int i2 = (k1 + j1 * l1) % i1;
diff --git a/src/main/java/net/minecraft/server/rcon/thread/QueryThreadGs4.java b/src/main/java/net/minecraft/server/rcon/thread/QueryThreadGs4.java
index 55c66f59c3946f79d8d0bd4dacd27dafb6090646..4bc858dc779a4553384091d5dd4e96911223302b 100644
--- a/src/main/java/net/minecraft/server/rcon/thread/QueryThreadGs4.java
+++ b/src/main/java/net/minecraft/server/rcon/thread/QueryThreadGs4.java
@@ -348,7 +348,7 @@ public class QueryThreadGs4 extends GenericThread {
this.identBytes[2] = bs[5];
this.identBytes[3] = bs[6];
this.ident = new String(this.identBytes, StandardCharsets.UTF_8);
- this.challenge = (new Random()).nextInt(16777216);
+ this.challenge = java.util.concurrent.ThreadLocalRandom.current().nextInt(16777216); // Patina - don't create new random instance
this.challengeBytes = String.format("\t%s%d\u0000", this.ident, this.challenge).getBytes(StandardCharsets.UTF_8);
}
diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java
index 8fb58a59181fdf3a6ca5710d42eac060fc756395..af603994275c93842d2c3b6e9a7fcf0b0fbad168 100644
--- a/src/main/java/net/minecraft/world/level/Level.java
+++ b/src/main/java/net/minecraft/world/level/Level.java
@@ -121,13 +121,14 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
public final Thread thread;
private final boolean isDebug;
private int skyDarken;
- protected int randValue = (new Random()).nextInt();
+ //protected int randValue = (new Random()).nextInt(); // Patina - moved down
protected final int addend = 1013904223;
protected float oRainLevel;
public float rainLevel;
protected float oThunderLevel;
public float thunderLevel;
public final Random random = new Random();
+ protected int randValue = random.nextInt(); // Patina - don't create new random instance
final DimensionType dimensionType;
private final Holder<DimensionType> dimensionTypeRegistration;
public final WritableLevelData levelData;

View File

@@ -0,0 +1,53 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: foss-mc <69294560+foss-mc@users.noreply.github.com>
Date: Thu, 1 Jul 2021 12:26:15 +0000
Subject: [PATCH] Completely remove bootstrapExecutor
Original code by PatinaMC, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/PatinaMC/Patina
diff --git a/src/main/java/net/minecraft/Util.java b/src/main/java/net/minecraft/Util.java
index fa14cedb8437b1e1713b0023253845a4bc2b11fc..bc6600fe322ef9733233c0273e318f2c16f6d359 100644
--- a/src/main/java/net/minecraft/Util.java
+++ b/src/main/java/net/minecraft/Util.java
@@ -67,7 +67,7 @@ public class Util {
private static final int DEFAULT_MAX_THREADS = 255;
private static final String MAX_THREADS_SYSTEM_PROPERTY = "max.bg.threads";
private static final AtomicInteger WORKER_COUNT = new AtomicInteger(1);
- private static final ExecutorService BOOTSTRAP_EXECUTOR = makeExecutor("Bootstrap", -2); // Paper - add -2 priority
+ //private static final ExecutorService BOOTSTRAP_EXECUTOR = makeExecutor("Bootstrap", -2); // Paper - add -2 priority // Patina
private static final ExecutorService BACKGROUND_EXECUTOR = makeExecutor("Main", -1); // Paper - add -1 priority
// Paper start - don't submit BLOCKING PROFILE LOOKUPS to the world gen thread
public static final ExecutorService PROFILE_EXECUTOR = Executors.newFixedThreadPool(2, new java.util.concurrent.ThreadFactory() {
@@ -190,7 +190,7 @@ public class Util {
}
public static ExecutorService bootstrapExecutor() {
- return BOOTSTRAP_EXECUTOR;
+ return BACKGROUND_EXECUTOR; // Patina
}
public static ExecutorService backgroundExecutor() {
diff --git a/src/main/java/net/minecraft/util/datafix/DataFixers.java b/src/main/java/net/minecraft/util/datafix/DataFixers.java
index e4090fa0f01078277d70b1a88e870a56f6b1cb0f..0c5abb040d156c8a855c3c40718411f2c7e8e43d 100644
--- a/src/main/java/net/minecraft/util/datafix/DataFixers.java
+++ b/src/main/java/net/minecraft/util/datafix/DataFixers.java
@@ -78,15 +78,15 @@ public class DataFixers {
private static final BiFunction<Integer, Schema, Schema> SAME = Schema::new;
private static final BiFunction<Integer, Schema, Schema> SAME_NAMESPACED = NamespacedSchema::new;
- private static final DataFixer DATA_FIXER = DataFixers.createFixerUpper();
+ private static final DataFixer DATA_FIXER; // Patina
public DataFixers() {}
- private static DataFixer createFixerUpper() {
+ static { // Patina
DataFixerBuilder datafixerbuilder = new DataFixerBuilder(SharedConstants.getCurrentVersion().getWorldVersion());
DataFixers.addFixers(datafixerbuilder);
- return datafixerbuilder.build(Util.bootstrapExecutor());
+ DATA_FIXER = datafixerbuilder.build(Util.backgroundExecutor()); // Patina
}
public static DataFixer getDataFixer() {

View File

@@ -0,0 +1,99 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Simon Gardling <titaniumtown@gmail.com>
Date: Thu, 8 Jul 2021 15:03:15 -0400
Subject: [PATCH] Use LinkedBlockingDeque in IAsyncTaskHandler
Original code by Titaniumtown, licensed under GNU General Public License v3.0
You can find the original code on https://gitlab.com/Titaniumtown/JettPack
diff --git a/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java b/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
index 9321e3a8b2f6f2eaebfa55679f287429d009e834..a270169efccfdd92b2c18af37477b9020746861c 100644
--- a/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
+++ b/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
@@ -1,13 +1,10 @@
package net.minecraft.util.thread;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Queues;
import com.mojang.logging.LogUtils;
import java.util.List;
-import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
-import java.util.concurrent.locks.LockSupport;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import net.minecraft.util.profiling.metrics.MetricCategory;
@@ -15,12 +12,15 @@ import net.minecraft.util.profiling.metrics.MetricSampler;
import net.minecraft.util.profiling.metrics.MetricsRegistry;
import net.minecraft.util.profiling.metrics.ProfilerMeasured;
import org.slf4j.Logger;
+import java.util.concurrent.LinkedBlockingDeque; // JettPack
+import java.util.concurrent.TimeUnit; // JettPack
public abstract class BlockableEventLoop<R extends Runnable> implements ProfilerMeasured, ProcessorHandle<R>, Executor {
private final String name;
private static final Logger LOGGER = LogUtils.getLogger();
- private final Queue<R> pendingRunnables = Queues.newConcurrentLinkedQueue();
+ private final LinkedBlockingDeque<R> pendingRunnables = new LinkedBlockingDeque(); // JettPack
private int blockingCount;
+ private R next = null; // JettPack
protected BlockableEventLoop(String name) {
this.name = name;
@@ -89,7 +89,7 @@ public abstract class BlockableEventLoop<R extends Runnable> implements Profiler
@Override
public void tell(R runnable) {
this.pendingRunnables.add(runnable);
- LockSupport.unpark(this.getRunningThread());
+ //LockSupport.unpark(this.getRunningThread()); // JettPack
}
@Override
@@ -117,15 +117,20 @@ public abstract class BlockableEventLoop<R extends Runnable> implements Profiler
}
public boolean pollTask() {
- R runnable = this.pendingRunnables.peek();
- if (runnable == null) {
- return false;
- } else if (this.blockingCount == 0 && !true/*this.shouldRun(runnable)*/) { // Patina
+ // JettPack start
+ if (this.next == null && !this.pendingRunnables.isEmpty()) {
+ this.waitForTasks();
+ }
+
+ if (this.next == null) {
return false;
} else {
- this.doRunTask(this.pendingRunnables.remove());
+ R r2 = this.next;
+ this.next = null;
+ this.doRunTask(r2);
return true;
}
+ // JettPack end
}
public void managedBlock(BooleanSupplier stopCondition) {
@@ -144,8 +149,18 @@ public abstract class BlockableEventLoop<R extends Runnable> implements Profiler
}
protected void waitForTasks() {
- Thread.yield();
- LockSupport.parkNanos("waiting for tasks", 100000L);
+ // JettPack start
+ if (this.next != null) {
+ throw new IllegalStateException("next != null");
+ }
+ try {
+ this.next = this.pendingRunnables.poll(100L, TimeUnit.MICROSECONDS);
+ return;
+ }
+ catch (InterruptedException interruptedException) {
+ return;
+ }
+ // JettPack end
}
protected void doRunTask(R task) {

View File

@@ -0,0 +1,190 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Simon Gardling <titaniumtown@gmail.com>
Date: Thu, 8 Jul 2021 17:00:21 -0400
Subject: [PATCH] Better handling of async tasks
Original code by Titaniumtown, licensed under GNU General Public License v3.0
You can find the original code on https://gitlab.com/Titaniumtown/JettPack
diff --git a/src/main/java/net/minecraft/server/MCUtil.java b/src/main/java/net/minecraft/server/MCUtil.java
index e8e49e1bdf1ff4ea60a4feb6ec52d999cbced256..b49f53a89d9c096355d6cc20a2a59033f2637432 100644
--- a/src/main/java/net/minecraft/server/MCUtil.java
+++ b/src/main/java/net/minecraft/server/MCUtil.java
@@ -53,11 +53,14 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
+import java.util.concurrent.SynchronousQueue; // Jettpack
+import java.util.concurrent.ConcurrentLinkedQueue; // Jettpack
public final class MCUtil {
+ public static final ConcurrentLinkedQueue smallAsyncTasks = new ConcurrentLinkedQueue(); // Jettpack
public static final ThreadPoolExecutor asyncExecutor = new ThreadPoolExecutor(
- 0, 2, 60L, TimeUnit.SECONDS,
- new LinkedBlockingQueue<>(),
+ 4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, // Jettpack
+ new SynchronousQueue<Runnable>(), // Jettpack
new ThreadFactoryBuilder()
.setNameFormat("Paper Async Task Handler Thread - %1$d")
.setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(MinecraftServer.LOGGER))
@@ -74,6 +77,30 @@ public final class MCUtil {
public static final long INVALID_CHUNK_KEY = getCoordinateKey(Integer.MAX_VALUE, Integer.MAX_VALUE);
+ // Jettpack start
+ public static void flushAsyncTasks() {
+ if (!smallAsyncTasks.isEmpty()) {
+ asyncExecutor.submit(() -> {
+ Runnable runnable;
+ while((runnable = (Runnable)smallAsyncTasks.poll()) != null) {
+ runnable.run();
+ }
+ });
+ }
+ }
+
+ public static void flushAsyncTasksMidTick() {
+ int i = smallAsyncTasks.size() < 16 ? smallAsyncTasks.size() : 16; // if smallAsyncTasks is over size 16, only execute 16 tasks
+ asyncExecutor.submit(() -> {
+ Runnable runnable;
+ int i_tmp = 0;
+ while((runnable = (Runnable)smallAsyncTasks.poll()) != null && i_tmp != i-1) {
+ runnable.run();
+ i_tmp += 1;
+ }
+ });
+ }
+ // Jettpack end
public static Runnable once(Runnable run) {
AtomicBoolean ran = new AtomicBoolean(false);
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 38754510081b130e045900bec6d7e0a9cb47b767..1ef00b9a0b502fac69ffdd0e233c5222dd9178ff 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -1059,6 +1059,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
LOGGER.info("Flushing Chunk IO");
com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.close(true, true); // Paper
LOGGER.info("Closing Thread Pool");
+ MCUtil.flushAsyncTasks();
Util.shutdownExecutors(); // Paper
LOGGER.info("Closing Server");
try {
@@ -1506,6 +1507,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
io.papermc.paper.util.CachedLists.reset(); // Paper
// Paper start - move executeAll() into full server tick timing
try (co.aikar.timings.Timing ignored = MinecraftTimings.processTasksTimer.startTiming()) {
+ MCUtil.flushAsyncTasks();
this.runAllTasks();
}
// Paper end
@@ -2749,6 +2751,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
return;
}
+ MCUtil.flushAsyncTasksMidTick();
co.aikar.timings.MinecraftTimings.midTickChunkTasks.startTiming();
try {
for (;;) {
diff --git a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
index 0c4e34c02060c00bdbed6388989660ec023b4d1c..0866b340a11d4650fc00a40cdb949b6e44691f8c 100644
--- a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
@@ -123,6 +123,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener
}
+ /*
// Paper start - Cache authenticator threads
private static final AtomicInteger threadId = new AtomicInteger(0);
private static final java.util.concurrent.ExecutorService authenticatorPool = java.util.concurrent.Executors.newCachedThreadPool(
@@ -135,6 +136,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener
}
);
// Paper end
+ */
// Spigot start
public void initUUID()
{
@@ -274,7 +276,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener
// Paper end
// Spigot start
// Paper start - Cache authenticator threads
- authenticatorPool.execute(new Runnable() {
+ net.minecraft.server.MCUtil.asyncExecutor.execute(new Runnable() { // Jettpack
@Override
public void run() {
try {
@@ -324,7 +326,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener
}
// Paper start - Cache authenticator threads
- authenticatorPool.execute(new Runnable() {
+ net.minecraft.server.MCUtil.asyncExecutor.execute(new Runnable() { // Jettpack
public void run() {
GameProfile gameprofile = ServerLoginPacketListenerImpl.this.gameProfile;
@@ -458,7 +460,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener
this.gameProfile = com.destroystokyo.paper.proxy.VelocityProxy.createProfile(buf);
// Proceed with login
- authenticatorPool.execute(() -> {
+ net.minecraft.server.MCUtil.asyncExecutor.execute(() -> { // Jettpack
try {
new LoginHandler().fireEvents();
} catch (Exception ex) {
diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java
index 9c1aff17aabd062640e3f451a2ef8c50a7c62f10..78073cbb7f36950537dc65633e264c30ee8f8a35 100644
--- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java
+++ b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java
@@ -32,23 +32,29 @@ import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
+/*
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+*/
public class CraftAsyncScheduler extends CraftScheduler {
+ /*
private final ThreadPoolExecutor executor = new ThreadPoolExecutor(
4, Integer.MAX_VALUE,30L, TimeUnit.SECONDS, new SynchronousQueue<>(),
new ThreadFactoryBuilder().setNameFormat("Craft Scheduler Thread - %1$d").setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER)).build()); // Paper
+ */
private final Executor management = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder()
.setNameFormat("Craft Async Scheduler Management Thread").setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER)).build()); // Paper
private final List<CraftTask> temp = new ArrayList<>();
CraftAsyncScheduler() {
super(true);
+ /*
executor.allowCoreThreadTimeOut(true);
executor.prestartAllCoreThreads();
+ */
}
@Override
@@ -93,7 +99,7 @@ public class CraftAsyncScheduler extends CraftScheduler {
private boolean executeTask(CraftTask task) {
if (isValid(task)) {
this.runners.put(task.getTaskId(), task);
- this.executor.execute(new ServerSchedulerReportingWrapper(task));
+ net.minecraft.server.MCUtil.asyncExecutor.execute(new ServerSchedulerReportingWrapper(task)); // Jettpack
return true;
}
return false;
diff --git a/src/main/java/org/spigotmc/WatchdogThread.java b/src/main/java/org/spigotmc/WatchdogThread.java
index 24fefa521093448e608e217af7b88a6397a4b054..f3400bdf23f79098c7e7b68f6b93aa65ca5b09dd 100644
--- a/src/main/java/org/spigotmc/WatchdogThread.java
+++ b/src/main/java/org/spigotmc/WatchdogThread.java
@@ -141,6 +141,7 @@ public class WatchdogThread extends Thread
{
while ( !this.stopping )
{
+ net.minecraft.server.MCUtil.flushAsyncTasks(); // Jettpack
//
// Paper start
Logger log = Bukkit.getServer().getLogger();

View File

@@ -0,0 +1,100 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Simon Gardling <titaniumtown@gmail.com>
Date: Thu, 8 Jul 2021 17:03:31 -0400
Subject: [PATCH] Use MCUtil.asyncExecutor for MAIN_WORKER_EXECUTOR in
SystemUtils
Original code by Titaniumtown, licensed under GNU General Public License v3.0
You can find the original code on https://gitlab.com/Titaniumtown/JettPack
diff --git a/src/main/java/net/minecraft/Util.java b/src/main/java/net/minecraft/Util.java
index bc6600fe322ef9733233c0273e318f2c16f6d359..73693a3a7faaa2be24c367e351f75aeb0d0f2208 100644
--- a/src/main/java/net/minecraft/Util.java
+++ b/src/main/java/net/minecraft/Util.java
@@ -61,6 +61,10 @@ import net.minecraft.util.datafix.DataFixers;
import net.minecraft.world.level.block.state.properties.Property;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
+import java.util.concurrent.AbstractExecutorService;
+import wtf.etil.mirai.server.util.ServerWorkerWrapper;
+import net.minecraft.server.MCUtil;
+import java.util.Collections;
public class Util {
static final Logger LOGGER = LogUtils.getLogger();
@@ -148,7 +152,43 @@ public class Util {
if (i <= 0) {
executorService = MoreExecutors.newDirectExecutorService();
} else {
- executorService = new java.util.concurrent.ThreadPoolExecutor(i, i,0L, TimeUnit.MILLISECONDS, new java.util.concurrent.LinkedBlockingQueue<Runnable>(), target -> new net.minecraft.server.ServerWorkerThread(target, s, priorityModifier));
+ executorService = Integer.getInteger("Paper.WorkerThreadCount", i) <= 0 ? MoreExecutors.newDirectExecutorService() : new AbstractExecutorService(){
+ private volatile boolean shutdown = false;
+
+ @Override
+ public final List<Runnable> shutdownNow() {
+ this.shutdown = true;
+ return Collections.emptyList();
+ }
+
+ @Override
+ public final void shutdown() {
+ this.shutdown = true;
+ }
+
+ @Override
+ public final boolean isShutdown() {
+ return this.shutdown;
+ }
+
+ @Override
+ public final boolean isTerminated() {
+ return this.shutdown;
+ }
+
+ @Override
+ public final boolean awaitTermination(long l2, TimeUnit timeUnit) throws InterruptedException {
+ if (!this.shutdown) {
+ throw new UnsupportedOperationException();
+ }
+ return true;
+ }
+
+ @Override
+ public final void execute(Runnable runnable) {
+ MCUtil.asyncExecutor.execute(new ServerWorkerWrapper(runnable));
+ }
+ };
}
/*
@Override
diff --git a/src/main/java/wtf/etil/mirai/server/util/ServerWorkerWrapper.java b/src/main/java/wtf/etil/mirai/server/util/ServerWorkerWrapper.java
new file mode 100644
index 0000000000000000000000000000000000000000..4633764f3d806c7e29cbda6e85db5a3432ad0c29
--- /dev/null
+++ b/src/main/java/wtf/etil/mirai/server/util/ServerWorkerWrapper.java
@@ -0,0 +1,24 @@
+package wtf.etil.mirai.server.util;
+
+import com.google.common.base.Preconditions;
+import net.minecraft.Util;
+
+public final class ServerWorkerWrapper implements Runnable {
+ private final Runnable internalRunnable;
+
+ public ServerWorkerWrapper(Runnable runnable) {
+ this.internalRunnable = Preconditions.checkNotNull(runnable, "internalRunnable");
+ }
+
+ @Override
+ public final void run() {
+ try {
+ this.internalRunnable.run();
+ return;
+ }
+ catch (Throwable throwable) {
+ Util.onThreadException(Thread.currentThread(), throwable);
+ return;
+ }
+ }
+}
\ No newline at end of file

View File

@@ -0,0 +1,34 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Simon Gardling <titaniumtown@gmail.com>
Date: Mon, 6 Dec 2021 10:27:12 -0500
Subject: [PATCH] Remove 'sync-chunk-writes' in server.properties
Original code by Titaniumtown, licensed under GNU General Public License v3.0
You can find the original code on https://gitlab.com/Titaniumtown/JettPack
diff --git a/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java b/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
index cea07f3898a85bf7949bdc3db3cfff7734d0ce03..760a1756cf210df2d012b7cd771f57695de54ea0 100644
--- a/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
+++ b/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
@@ -439,7 +439,7 @@ public class DedicatedServer extends MinecraftServer implements ServerInterface
BufferedWriter bufferedwriter = Files.newBufferedWriter(file);
try {
- bufferedwriter.write(String.format("sync-chunk-writes=%s%n", dedicatedserverproperties.syncChunkWrites));
+ //bufferedwriter.write(String.format("sync-chunk-writes=%s%n", dedicatedserverproperties.syncChunkWrites)); // JettPack - remove 'sync-chunk-writes' in server.properties
bufferedwriter.write(String.format("gamemode=%s%n", dedicatedserverproperties.gamemode));
bufferedwriter.write(String.format("spawn-monsters=%s%n", dedicatedserverproperties.spawnMonsters));
bufferedwriter.write(String.format("entity-broadcast-range-percentage=%d%n", dedicatedserverproperties.entityBroadcastRangePercentage));
diff --git a/src/main/java/net/minecraft/server/dedicated/DedicatedServerProperties.java b/src/main/java/net/minecraft/server/dedicated/DedicatedServerProperties.java
index ebfaa8d5de5b905bd2dd7778728b8c9939d01252..1fd7b37a7da803af0e61d5341b7574d4f4a10da3 100644
--- a/src/main/java/net/minecraft/server/dedicated/DedicatedServerProperties.java
+++ b/src/main/java/net/minecraft/server/dedicated/DedicatedServerProperties.java
@@ -111,7 +111,7 @@ public class DedicatedServerProperties extends Settings<DedicatedServerPropertie
this.maxWorldSize = this.get("max-world-size", (integer) -> {
return Mth.clamp(integer, (int) 1, 29999984);
}, 29999984);
- this.syncChunkWrites = this.get("sync-chunk-writes", true) && Boolean.getBoolean("Paper.enable-sync-chunk-writes"); // Paper - hide behind flag
+ this.syncChunkWrites = Boolean.getBoolean("Paper.enable-sync-chunk-writes"); // Paper - hide behind flag // JettPack - remove 'sync-chunk-writes' in server.properties
this.enableJmxMonitoring = this.get("enable-jmx-monitoring", false);
this.enableStatus = this.get("enable-status", true);
this.hideOnlinePlayers = this.get("hide-online-players", false);

View File

@@ -0,0 +1,81 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Simon Gardling <titaniumtown@gmail.com>
Date: Mon, 6 Dec 2021 10:34:33 -0500
Subject: [PATCH] Remove Spigot tick limiter
Original code by Titaniumtown, licensed under GNU General Public License v3.0
You can find the original code on https://gitlab.com/Titaniumtown/JettPack
diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java
index af603994275c93842d2c3b6e9a7fcf0b0fbad168..f816ae7bf9a372aef8de769d4f6192e6ed9ac776 100644
--- a/src/main/java/net/minecraft/world/level/Level.java
+++ b/src/main/java/net/minecraft/world/level/Level.java
@@ -167,8 +167,8 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
public final co.aikar.timings.WorldTimingsHandler timings; // Paper
public static BlockPos lastPhysicsProblem; // Spigot
- private org.spigotmc.TickLimiter entityLimiter;
- private org.spigotmc.TickLimiter tileLimiter;
+ //private org.spigotmc.TickLimiter entityLimiter; // JettPack - remove tick limiter
+ //private org.spigotmc.TickLimiter tileLimiter; // JettPack - remove tick limiter
private int tileTickPosition;
public final Map<Explosion.CacheKey, Float> explosionDensityCache = new HashMap<>(); // Paper - Optimize explosions
public java.util.ArrayDeque<net.minecraft.world.level.block.RedstoneTorchBlock.Toggle> redstoneUpdateInfos; // Paper - Move from Map in BlockRedstoneTorch to here
@@ -355,8 +355,8 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
// CraftBukkit end
timings = new co.aikar.timings.WorldTimingsHandler(this); // Paper - code below can generate new world and access timings
this.keepSpawnInMemory = this.paperConfig.keepSpawnInMemory; // Paper
- this.entityLimiter = new org.spigotmc.TickLimiter(spigotConfig.entityMaxTickTime);
- this.tileLimiter = new org.spigotmc.TickLimiter(spigotConfig.tileMaxTickTime);
+ //this.entityLimiter = new org.spigotmc.TickLimiter(spigotConfig.entityMaxTickTime); // JettPack - remove tick limiter
+ //this.tileLimiter = new org.spigotmc.TickLimiter(spigotConfig.tileMaxTickTime); // JettPack - remove tick limiter
this.chunkPacketBlockController = this.paperConfig.antiXray ? new com.destroystokyo.paper.antixray.ChunkPacketBlockControllerAntiXray(this, executor) : com.destroystokyo.paper.antixray.ChunkPacketBlockController.NO_OPERATION_INSTANCE; // Paper - Anti-Xray
this.entitySliceManager = new io.papermc.paper.world.EntitySliceManager((ServerLevel)this); // Paper
}
diff --git a/src/main/java/org/spigotmc/SpigotWorldConfig.java b/src/main/java/org/spigotmc/SpigotWorldConfig.java
index 31a447e6e156b7b244b2ac69a9c03c09c7ed388c..c405457a775df902540602dfb4cdcd6872d35e2a 100644
--- a/src/main/java/org/spigotmc/SpigotWorldConfig.java
+++ b/src/main/java/org/spigotmc/SpigotWorldConfig.java
@@ -433,6 +433,7 @@ public class SpigotWorldConfig
this.hangingTickFrequency = this.getInt( "hanging-tick-frequency", 100 );
}
+ /* // JettPack start - remove tick limiter
public int tileMaxTickTime;
public int entityMaxTickTime;
private void maxTickTimes()
@@ -441,6 +442,8 @@ public class SpigotWorldConfig
this.entityMaxTickTime = this.getInt("max-tick-time.entity", 50);
this.log("Tile Max Tick Time: " + this.tileMaxTickTime + "ms Entity max Tick Time: " + this.entityMaxTickTime + "ms");
}
+ */
+ // JettPack end
public int thunderChance;
private void thunderChance()
diff --git a/src/main/java/org/spigotmc/TickLimiter.java b/src/main/java/org/spigotmc/TickLimiter.java
deleted file mode 100644
index 4074538ea6090bf99d8ab04b1e98c2832a0e9a98..0000000000000000000000000000000000000000
--- a/src/main/java/org/spigotmc/TickLimiter.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package org.spigotmc;
-
-public class TickLimiter {
-
- private final int maxTime;
- private long startTime;
-
- public TickLimiter(int maxtime) {
- this.maxTime = maxtime;
- }
-
- public void initTick() {
- this.startTime = System.currentTimeMillis();
- }
-
- public boolean shouldContinue() {
- long remaining = System.currentTimeMillis() - this.startTime;
- return remaining < this.maxTime;
- }
-}

View File

@@ -0,0 +1,73 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Ivan Pekov <ivan@mrivanplays.com>
Date: Sun, 27 Sep 2020 18:30:10 +0300
Subject: [PATCH] Add last tick time API
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 1ef00b9a0b502fac69ffdd0e233c5222dd9178ff..30156d3c983f83c4d96ce089a27ff9bfed29555e 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -1160,6 +1160,8 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
// Paper End
// Spigot End
+ public static java.time.Duration lastTickTime = java.time.Duration.ZERO; // Yatopia
+
protected void runServer() {
try {
long serverStartTime = Util.getNanos(); // Paper
@@ -1225,7 +1227,9 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
this.nextTickTime += 50L;
this.startMetricsRecordingTick();
this.profiler.push("tick");
+ long tickStart = System.nanoTime(); // Yatopia
this.tickServer(this::haveTime);
+ lastTickTime = java.time.Duration.ofNanos(System.nanoTime() - tickStart); // Yatopia
this.profiler.popPush("nextTickWait");
this.mayHaveDelayedTasks = true;
this.delayedTasksMaxNextTickTime = Math.max(Util.getMillis() + 50L, this.nextTickTime);
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index 20437547fd04552d5d52ea1058cd793ed1a8e903..69ddc41119dc621cf0ffa9e8e89bc761dc666b7d 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -2885,4 +2885,6 @@ public final class CraftServer implements Server {
}
// Paper end
+
+ @Override public java.time.Duration getLastTickTime() { return net.minecraft.server.MinecraftServer.lastTickTime; } // Yatopia
}
diff --git a/src/main/java/org/spigotmc/TicksPerSecondCommand.java b/src/main/java/org/spigotmc/TicksPerSecondCommand.java
index 9bede6a26c08ede063c7a38f1149c811df14b258..b735769b7876e54db2950ebb4170484447cfb9a6 100644
--- a/src/main/java/org/spigotmc/TicksPerSecondCommand.java
+++ b/src/main/java/org/spigotmc/TicksPerSecondCommand.java
@@ -32,6 +32,10 @@ public class TicksPerSecondCommand extends Command
tpsAvg[i] = TicksPerSecondCommand.format( tps[i] );
}
sender.sendMessage(ChatColor.GOLD + "TPS from last 1m, 5m, 15m: " + org.apache.commons.lang.StringUtils.join(tpsAvg, ", "));
+ // Yatopia start - Last tick time API
+ java.time.Duration lastTickTime = org.bukkit.Bukkit.getLastTickTime();
+ sender.sendMessage(ChatColor.GOLD + "Last tick: " + TicksPerSecondCommand.formatTo( lastTickTime, java.util.concurrent.TimeUnit.MILLISECONDS ) + " (" + formatTo( lastTickTime, java.util.concurrent.TimeUnit.NANOSECONDS ) + ")");
+ // Yatopia end
if (args.length > 0 && args[0].equals("mem") && sender.hasPermission("bukkit.command.tpsmemory")) {
sender.sendMessage(ChatColor.GOLD + "Current Memory Usage: " + ChatColor.GREEN + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024)) + "/" + (Runtime.getRuntime().totalMemory() / (1024 * 1024)) + " mb (Max: " + (Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " mb)");
if (!hasShownMemoryWarning) {
@@ -50,4 +54,15 @@ public class TicksPerSecondCommand extends Command
return ( ( tps > 18.0 ) ? ChatColor.GREEN : ( tps > 16.0 ) ? ChatColor.YELLOW : ChatColor.RED ).toString()
+ ( ( tps > 21.0 ) ? "*" : "" ) + Math.min( Math.round( tps * 100.0 ) / 100.0, 20.0 ); // Paper - only print * at 21, we commonly peak to 20.02 as the tick sleep is not accurate enough, stop the noise
}
+
+ // Yatopia start - Last tick time API
+ public static String formatTo(java.time.Duration duration, java.util.concurrent.TimeUnit unit) {
+ java.util.concurrent.TimeUnit nanosUnit = java.util.concurrent.TimeUnit.NANOSECONDS;
+ long nanos = duration.toNanos();
+ long toAskedUnit = unit.convert( nanos, nanosUnit );
+ long ms = nanosUnit.toMillis( nanos );
+ ChatColor startingColor = ms < 40 ? ChatColor.GREEN : ( ms < 50 ) ? ChatColor.YELLOW : ChatColor.RED;
+ return startingColor.toString() + toAskedUnit + ChatColor.GOLD + org.yatopiamc.yatopia.server.util.TimeUtils.getFriendlyName( unit );
+ }
+ // Yatopia end
}

View File

@@ -0,0 +1,49 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: l_MrBoom_l <admin@epserv.ru>
Date: Wed, 30 Sep 2020 18:20:12 +0300
Subject: [PATCH] Configurable flight checks
Original code by YatopiaMC, licensed under MIT
You can find the original code on https://github.com/YatopiaMC/Yatopia
diff --git a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index f0e7c7c84052f29349b60ad06ec4f9ee1771f4bb..62e348c46b7a48e83a5bed5bc7bfa0878e61bc3c 100644
--- a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -316,7 +316,7 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
++this.tickCount;
this.knownMovePacketCount = this.receivedMovePacketCount;
if (this.clientIsFloating && !this.player.isSleeping() && !this.player.isPassenger()) {
- if (++this.aboveGroundTickCount > 80) {
+ if (wtf.etil.mirai.MiraiConfig.checkFlying && ++this.aboveGroundTickCount > 80) { // Yatopia - Configurable flight checks
ServerGamePacketListenerImpl.LOGGER.warn("{} was kicked for floating too long!", this.player.getName().getString());
this.disconnect(com.destroystokyo.paper.PaperConfig.flyingKickPlayerMessage, org.bukkit.event.player.PlayerKickEvent.Cause.FLYING_PLAYER); // Paper - use configurable kick message & kick event cause
return;
@@ -335,7 +335,7 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
this.vehicleLastGoodY = this.lastVehicle.getY();
this.vehicleLastGoodZ = this.lastVehicle.getZ();
if (this.clientVehicleIsFloating && this.player.getRootVehicle().getControllingPassenger() == this.player) {
- if (++this.aboveGroundVehicleTickCount > 80) {
+ if (wtf.etil.mirai.MiraiConfig.checkVehicleFlying && ++this.aboveGroundVehicleTickCount > 80) { // Yatopia - Configurable flight checks
ServerGamePacketListenerImpl.LOGGER.warn("{} was kicked for floating a vehicle too long!", this.player.getName().getString());
this.disconnect(com.destroystokyo.paper.PaperConfig.flyingKickVehicleMessage, org.bukkit.event.player.PlayerKickEvent.Cause.FLYING_VEHICLE); // Paper - use configurable kick message & kick event cause
return;
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index 667eaabe95e9b44cad64dd5aba5ac693f4d726ed..a24a35f3ef2812d2951fb13439f856ee9495226b 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -194,4 +194,13 @@ public class MiraiConfig {
maxBees = getInt("max-bees-in-hive", maxBees);
}
+ public static boolean checkFlying = true;
+ public static boolean checkVehicleFlying = true;
+ private static void flightChecks() {
+ checkFlying = getBoolean("checks.flight", checkFlying);
+ checkVehicleFlying = getBoolean("checks.vehicle-flight", checkVehicleFlying);
+ }
+
+
+
}
\ No newline at end of file

View File

@@ -0,0 +1,24 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Sat, 28 Dec 2013 21:25:06 -0500
Subject: [PATCH] Don't save Fireworks
Original code by Starlis, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/starlis/empirecraft
diff --git a/src/main/java/net/minecraft/world/entity/projectile/FireworkRocketEntity.java b/src/main/java/net/minecraft/world/entity/projectile/FireworkRocketEntity.java
index 5a062a19bb2fc427c9391bb4731f071719b72c52..76110656d922fc734df5b08cb24eecf4dc97e38c 100644
--- a/src/main/java/net/minecraft/world/entity/projectile/FireworkRocketEntity.java
+++ b/src/main/java/net/minecraft/world/entity/projectile/FireworkRocketEntity.java
@@ -358,4 +358,11 @@ public class FireworkRocketEntity extends Projectile implements ItemSupplier {
public boolean isAttackable() {
return false;
}
+
+ // EMC start
+ @Override
+ public boolean shouldBeSaved() {
+ return false;
+ }
+ // EMC end
}

View File

@@ -0,0 +1,20 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Thu, 14 Jan 2016 00:49:14 -0500
Subject: [PATCH] Do not drop items from Give command
Original code by Starlis, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/starlis/empirecraft
diff --git a/src/main/java/net/minecraft/server/commands/GiveCommand.java b/src/main/java/net/minecraft/server/commands/GiveCommand.java
index a60a84d5df0b05cf35668df8c5f08b811bc42a9f..b76f315355407b3c4b8efb490acc4848a4a67934 100644
--- a/src/main/java/net/minecraft/server/commands/GiveCommand.java
+++ b/src/main/java/net/minecraft/server/commands/GiveCommand.java
@@ -56,6 +56,7 @@ public class GiveCommand {
ItemStack itemstack = item.createItemStack(i1, false);
boolean flag = entityplayer.getInventory().add(itemstack);
ItemEntity entityitem;
+ if (true) { continue; } // EMC - never drop items
if (flag && itemstack.isEmpty()) {
itemstack.setCount(1);

View File

@@ -0,0 +1,36 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Mon, 16 Mar 2020 03:07:02 -0400
Subject: [PATCH] Don't load chunks for physics
Original code by Starlis, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/starlis/empirecraft
diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java
index f816ae7bf9a372aef8de769d4f6192e6ed9ac776..14e4f5c376126c264d59266ddeeafff764eabc40 100644
--- a/src/main/java/net/minecraft/world/level/Level.java
+++ b/src/main/java/net/minecraft/world/level/Level.java
@@ -855,7 +855,8 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
public void neighborChanged(BlockPos pos, Block sourceBlock, BlockPos neighborPos) {
if (!this.isClientSide) {
- BlockState iblockdata = this.getBlockState(pos);
+ BlockState iblockdata = this.getBlockStateIfLoaded(pos); // EMC
+ if (iblockdata == null) return; // EMC
try {
// CraftBukkit start
diff --git a/src/main/java/net/minecraft/world/level/block/state/BlockBehaviour.java b/src/main/java/net/minecraft/world/level/block/state/BlockBehaviour.java
index 7f83c9390823b42fc30d04e1d3222e2825eaad50..a1231d2347de63db9e607519328063dbed62b4c9 100644
--- a/src/main/java/net/minecraft/world/level/block/state/BlockBehaviour.java
+++ b/src/main/java/net/minecraft/world/level/block/state/BlockBehaviour.java
@@ -987,7 +987,8 @@ public abstract class BlockBehaviour {
Direction enumdirection = aenumdirection[l];
blockposition_mutableblockposition.setWithOffset(pos, enumdirection);
- BlockState iblockdata = world.getBlockState(blockposition_mutableblockposition);
+ BlockState iblockdata = world.getBlockStateIfLoaded(blockposition_mutableblockposition); // EMC
+ if (iblockdata == null) { continue; } // EMC
BlockState iblockdata1 = iblockdata.updateShape(enumdirection.getOpposite(), this.asState(), world, blockposition_mutableblockposition, pos);
Block.updateOrDestroy(iblockdata, iblockdata1, world, blockposition_mutableblockposition, flags, maxUpdateDepth);

View File

@@ -0,0 +1,20 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: chickeneer <emcchickeneer@gmail.com>
Date: Tue, 3 Aug 2021 10:39:44 -0500
Subject: [PATCH] Do not process chat/commands before player has joined
Original code by Starlis, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/starlis/empirecraft
diff --git a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index 62e348c46b7a48e83a5bed5bc7bfa0878e61bc3c..f31fc4a40d817a4115159bca39b7f907fdc765a9 100644
--- a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -2107,6 +2107,7 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
private void handleChat(TextFilter.FilteredText message) {
if (this.player.isRemoved() || this.player.getChatVisibility() == ChatVisiblity.HIDDEN) { // CraftBukkit - dead men tell no tales
this.send(new ClientboundChatPacket((new TranslatableComponent("chat.disabled.options")).withStyle(ChatFormatting.RED), ChatType.SYSTEM, Util.NIL_UUID));
+ } else if (!player.didPlayerJoinEvent) { return; // EMC - do not handle chat messages before they joined
} else {
this.player.resetLastActionTime();
String s = message.getRaw();

View File

@@ -0,0 +1,100 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Mon, 21 Dec 2020 17:24:43 -0500
Subject: [PATCH] Always convert Lore/Name of an item to ensure consistency
Original code by Starlis, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/starlis/empirecraft
diff --git a/src/main/java/net/minecraft/world/item/ItemStack.java b/src/main/java/net/minecraft/world/item/ItemStack.java
index 586ce0bec1ab2a17a3818690e47be23643cd5a48..ceea5592b2964365b533c1641fdd9ee83f821e34 100644
--- a/src/main/java/net/minecraft/world/item/ItemStack.java
+++ b/src/main/java/net/minecraft/world/item/ItemStack.java
@@ -176,9 +176,9 @@ public final class ItemStack {
if (display != null) {
if (display.contains("Name", 8)) {
String json = display.getString("Name");
- if (json != null && json.contains("\u00A7")) {
+ if (true || json != null && json.contains("\u00A7")) {
try {
- display.put("Name", convert(json));
+ display.put("Name", convert(json)); // Paper
} catch (com.google.gson.JsonParseException jsonparseexception) {
display.remove("Name");
}
@@ -188,7 +188,7 @@ public final class ItemStack {
ListTag list = display.getList("Lore", 8);
for (int index = 0; index < list.size(); index++) {
String json = list.getString(index);
- if (json != null && json.contains("\u00A7")) { // Only try if it has legacy in the unparsed json
+ if (true || json != null && json.contains("\u00A7")) { // Only try if it has legacy in the unparsed json // Paper
try {
list.set(index, convert(json));
} catch (com.google.gson.JsonParseException e) {
@@ -205,6 +205,9 @@ public final class ItemStack {
if (component instanceof TextComponent && component.getContents().contains("\u00A7") && component.getSiblings().isEmpty()) {
// Only convert if the root component is a single comp with legacy in it, don't convert already normal components
component = org.bukkit.craftbukkit.util.CraftChatMessage.fromString(component.getContents())[0];
+ } else {
+ // pass this to legacy format and back to strip invisible components and ensure consistent modifier format
+ component = org.bukkit.craftbukkit.util.CraftChatMessage.fromString(org.bukkit.craftbukkit.util.CraftChatMessage.fromComponent(component))[0];
}
return net.minecraft.nbt.StringTag.valueOf(org.bukkit.craftbukkit.util.CraftChatMessage.toJSON(component));
}
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java
index 5607dc10dc1c9d2dbf4e3007890e5e89a175605e..c24793eeff34281194292bd83c5361a56ebea301 100644
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java
@@ -687,7 +687,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
@Overridden
void applyToItem(CompoundTag itemTag) {
if (this.hasDisplayName()) {
- this.setDisplayTag(itemTag, NAME.NBT, StringTag.valueOf(displayName));
+ this.setDisplayTag(itemTag, NAME.NBT, StringTag.valueOf(CraftChatMessage.reencode(displayName))); // Paper
}
if (this.hasLocalizedName()) {
this.setDisplayTag(itemTag, LOCNAME.NBT, StringTag.valueOf(locName));
@@ -779,7 +779,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
ListTag tagList = new ListTag();
for (String value : list) {
// SPIGOT-5342 - horrible hack as 0 version does not go through the Mojang updater
- tagList.add(StringTag.valueOf(this.version <= 0 || this.version >= 1803 ? value : CraftChatMessage.fromJSONComponent(value))); // SPIGOT-4935
+ tagList.add(StringTag.valueOf(this.version <= 0 || this.version >= 1803 ? CraftChatMessage.reencode(value) : CraftChatMessage.fromJSONComponent(value))); // SPIGOT-4935 // Paper
}
return tagList;
@@ -882,7 +882,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
// Paper end
@Override
public final void setDisplayName(String name) {
- this.displayName = CraftChatMessage.fromStringOrNullToJSON(name);
+ this.displayName = CraftChatMessage.fromStringOrNullToJSON(CraftChatMessage.reencode(name)); // Paper
}
// Paper start
@@ -1557,7 +1557,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
if (possiblyJsonInput) {
addTo.add(CraftChatMessage.fromJSONOrStringToJSON(entry));
} else {
- addTo.add(CraftChatMessage.fromStringToJSON(entry));
+ addTo.add(CraftChatMessage.fromStringToJSON(CraftChatMessage.reencode(entry)));
}
}
}
diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java
index 26d43c229caf9f8504af7071c3a61ec6da7e27ec..6e8edc80dd7dfa867901769fda82706746f1bcc5 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java
@@ -41,6 +41,12 @@ public final class CraftChatMessage {
return ChatColor.getByChar(format.code);
}
+ // Paper start
+ public static String reencode(String string) {
+ return CraftChatMessage.fromComponent(CraftChatMessage.fromString(string)[0]);
+ }
+ // Paper end
+
private static final class StringMessage {
private static final Pattern INCREMENTAL_PATTERN = Pattern.compile("(" + String.valueOf(org.bukkit.ChatColor.COLOR_CHAR) + "[0-9a-fk-orx])|((?:(?:https?):\\/\\/)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[" + String.valueOf(org.bukkit.ChatColor.COLOR_CHAR) + " \\n]|$))))|(\\n)", Pattern.CASE_INSENSITIVE);
// Separate pattern with no group 3, new lines are part of previous string

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: chickeneer <emcchickeneer@gmail.com>
Date: Sat, 6 Jun 2020 21:07:15 -0500
Subject: [PATCH] Bound villager trade maxUses by 16
Original code by Starlis, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/starlis/empirecraft
diff --git a/src/main/java/net/minecraft/world/item/trading/MerchantOffer.java b/src/main/java/net/minecraft/world/item/trading/MerchantOffer.java
index c9cb0717c2793acd5b5870a6cc4d672d69a40026..40385c7b267ecd1e00e4daa652b94533cc8febea 100644
--- a/src/main/java/net/minecraft/world/item/trading/MerchantOffer.java
+++ b/src/main/java/net/minecraft/world/item/trading/MerchantOffer.java
@@ -53,7 +53,7 @@ public class MerchantOffer {
this.result = ItemStack.of(nbt.getCompound("sell"));
this.uses = nbt.getInt("uses");
if (nbt.contains("maxUses", 99)) {
- this.maxUses = nbt.getInt("maxUses");
+ this.maxUses = Math.min(16, nbt.getInt("maxUses")); // EMC
} else {
this.maxUses = 4;
}

View File

@@ -0,0 +1,41 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: chickeneer <emcchickeneer@gmail.com>
Date: Mon, 6 Sep 2021 02:05:16 -0500
Subject: [PATCH] Mitigate ConcurrentModificationException by copying
entitySection access
Original code by Starlis, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/starlis/empirecraft
diff --git a/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java b/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java
index 3d5f38a1ca0206e5bcae4ed49d3df7ce0967f722..649df137ac36a62e53b42b7675c606e9e57795b2 100644
--- a/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java
+++ b/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java
@@ -264,23 +264,23 @@ public class PersistentEntitySectionManager<T extends EntityAccess> implements A
if (flag2 && !flag3) {
entitysection.getEntities().filter((entityaccess) -> {
return !entityaccess.isAlwaysTicking();
- }).forEach(this::stopTicking);
+ }).collect(Collectors.toList()).forEach(this::stopTicking); // EMC
}
if (flag && !flag1) {
entitysection.getEntities().filter((entityaccess) -> {
return !entityaccess.isAlwaysTicking();
- }).forEach(this::stopTracking);
+ }).collect(Collectors.toList()).forEach(this::stopTracking); // EMC
} else if (!flag && flag1) {
entitysection.getEntities().filter((entityaccess) -> {
return !entityaccess.isAlwaysTicking();
- }).forEach(this::startTracking);
+ }).collect(Collectors.toList()).forEach(this::startTracking); // EMC
}
if (!flag2 && flag3) {
entitysection.getEntities().filter((entityaccess) -> {
return !entityaccess.isAlwaysTicking();
- }).forEach(this::startTicking);
+ }).collect(Collectors.toList()).forEach(this::startTicking); // EMC
}
});

View File

@@ -0,0 +1,26 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Fri, 3 May 2019 23:53:16 -0500
Subject: [PATCH] Fix cow rotation when shearing mooshroom
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/world/entity/animal/MushroomCow.java b/src/main/java/net/minecraft/world/entity/animal/MushroomCow.java
index 6d4dc4b09278eca509f86655c6562fb4b05d5069..53a081af5b6a386ebde1765c7cedff372ffbd7b2 100644
--- a/src/main/java/net/minecraft/world/entity/animal/MushroomCow.java
+++ b/src/main/java/net/minecraft/world/entity/animal/MushroomCow.java
@@ -180,7 +180,13 @@ public class MushroomCow extends Cow implements Shearable {
entitycow.moveTo(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot());
entitycow.setHealth(this.getHealth());
+ // Purpur start
+ entitycow.copyPosition(this);
entitycow.yBodyRot = this.yBodyRot;
+ entitycow.setYHeadRot(this.getYHeadRot());
+ entitycow.yRotO = this.yRotO;
+ entitycow.xRotO = this.xRotO;
+ // Purpur end
if (this.hasCustomName()) {
entitycow.setCustomName(this.getCustomName());
entitycow.setCustomNameVisible(this.isCustomNameVisible());

View File

@@ -0,0 +1,20 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Sat, 21 Mar 2020 18:33:05 -0500
Subject: [PATCH] End gateway should check if entity can use portal
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/world/level/block/entity/TheEndGatewayBlockEntity.java b/src/main/java/net/minecraft/world/level/block/entity/TheEndGatewayBlockEntity.java
index 4e435a16a16c703a2978f4dc82606b8710742670..a952f19530983ca9a72969ad25f9565a2a03688a 100644
--- a/src/main/java/net/minecraft/world/level/block/entity/TheEndGatewayBlockEntity.java
+++ b/src/main/java/net/minecraft/world/level/block/entity/TheEndGatewayBlockEntity.java
@@ -177,6 +177,7 @@ public class TheEndGatewayBlockEntity extends TheEndPortalBlockEntity {
public static void teleportEntity(Level world, BlockPos pos, BlockState state, Entity entity, TheEndGatewayBlockEntity blockEntity) {
if (world instanceof ServerLevel && !blockEntity.isCoolingDown()) {
+ if (!entity.canChangeDimensions()) return; // Purpur
ServerLevel worldserver = (ServerLevel) world;
blockEntity.teleportCooldown = 100;

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <Blake.Galbreath@GMail.com>
Date: Wed, 4 Nov 2020 13:12:50 -0600
Subject: [PATCH] Arrows should not reset despawn counter
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/world/entity/projectile/AbstractArrow.java b/src/main/java/net/minecraft/world/entity/projectile/AbstractArrow.java
index 53d0024daf6963ac4dab575666b0d6a74a39a958..26cf6291d64561a589bc6c357a90bcaffad89ded 100644
--- a/src/main/java/net/minecraft/world/entity/projectile/AbstractArrow.java
+++ b/src/main/java/net/minecraft/world/entity/projectile/AbstractArrow.java
@@ -321,7 +321,7 @@ public abstract class AbstractArrow extends Projectile {
Vec3 vec3d = this.getDeltaMovement();
this.setDeltaMovement(vec3d.multiply((double) (this.random.nextFloat() * 0.2F), (double) (this.random.nextFloat() * 0.2F), (double) (this.random.nextFloat() * 0.2F)));
- this.life = 0;
+ //this.life = 0; // Purpur - do not reset despawn counter
}
@Override

View File

@@ -0,0 +1,67 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: James Lyne <jim+github@not-null.co.uk>
Date: Mon, 7 Dec 2020 17:52:36 +0000
Subject: [PATCH] Spread out and optimise player list ticksSpread out and
optimise player list ticks
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java
index ba8e58fe70f16dbc0b64a92264d29c91461d2cdf..93b97bb18f13d533d228d5912d08fbcce664ac06 100644
--- a/src/main/java/net/minecraft/server/players/PlayerList.java
+++ b/src/main/java/net/minecraft/server/players/PlayerList.java
@@ -1028,22 +1028,21 @@ public abstract class PlayerList {
}
public void tick() {
- if (++this.sendAllPlayerInfoIn > 600) {
- // CraftBukkit start
- for (int i = 0; i < this.players.size(); ++i) {
- final ServerPlayer target = (ServerPlayer) this.players.get(i);
-
- target.connection.send(new ClientboundPlayerInfoPacket(ClientboundPlayerInfoPacket.Action.UPDATE_LATENCY, this.players.stream().filter(new Predicate<ServerPlayer>() {
- @Override
- public boolean apply(ServerPlayer input) {
- return target.getBukkitEntity().canSee(input.getBukkitEntity());
- }
- }).collect(Collectors.toList())));
+ // Purpur start
+ if (this.sendAllPlayerInfoIn < this.players.size()) {
+ final org.bukkit.craftbukkit.entity.CraftPlayer target = this.players.get(this.sendAllPlayerInfoIn).getBukkitEntity();
+ final List<ServerPlayer> list = new java.util.ArrayList<>();
+ for (ServerPlayer player : this.players) {
+ if (target.canSee(player.getUUID())) {
+ list.add(player);
+ }
}
- // CraftBukkit end
+ target.getHandle().connection.send(new ClientboundPlayerInfoPacket(ClientboundPlayerInfoPacket.Action.UPDATE_LATENCY, list));
+ }
+ if (++this.sendAllPlayerInfoIn > 600) {
this.sendAllPlayerInfoIn = 0;
}
-
+ // Purpur end
}
public void broadcastAll(Packet<?> packet) {
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
index ce78e024244c14530270b8276e5b0fd853f0a110..170c7469ac6ed343a8e4e43f03a972d106bcc640 100644
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
@@ -1732,7 +1732,13 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override
public boolean canSee(org.bukkit.entity.Entity entity) {
- return !this.hiddenEntities.containsKey(entity.getUniqueId());
+ // Purpur start
+ return this.canSee(entity.getUniqueId());
+ }
+
+ public boolean canSee(UUID uuid) {
+ return !this.hiddenEntities.containsKey(uuid);
+ // Purpur end
}
@Override

View File

@@ -0,0 +1,32 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Sat, 28 Mar 2020 01:51:32 -0500
Subject: [PATCH] Fix vanilla command permission handler
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/com/mojang/brigadier/tree/CommandNode.java b/src/main/java/com/mojang/brigadier/tree/CommandNode.java
index d65defd5fc54086a969c568b93dfb05f40dd5a44..dad5564caa9f0211d8f8321a80dcec7e2cc6abc4 100644
--- a/src/main/java/com/mojang/brigadier/tree/CommandNode.java
+++ b/src/main/java/com/mojang/brigadier/tree/CommandNode.java
@@ -34,6 +34,7 @@ public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
private final RedirectModifier<S> modifier;
private final boolean forks;
private Command<S> command;
+ private String permission = null; public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } // Purpur
// CraftBukkit start
public void removeCommand(String name) {
this.children.remove(name);
diff --git a/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java b/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java
index 4525fb3bc9b137bce3b59310a8aecca96d6ad5ba..75aeceb76b15a4c9cc7cffc35d15d76509c5620a 100644
--- a/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java
+++ b/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java
@@ -94,6 +94,7 @@ public final class VanillaCommandWrapper extends BukkitCommand {
}
public static String getPermission(CommandNode<CommandSourceStack> vanillaCommand) {
+ if (vanillaCommand.getPermission() != null) return vanillaCommand.getPermission(); // Purpur
// Paper start
final String commandName;
if (vanillaCommand.getRedirect() == null) {

View File

@@ -0,0 +1,23 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Thu, 2 Jan 2020 01:23:22 -0600
Subject: [PATCH] MC-147659 - Fix non black cats spawning in swamp huts
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/world/entity/npc/CatSpawner.java b/src/main/java/net/minecraft/world/entity/npc/CatSpawner.java
index 0df98efa509518a14d6f76dca9356cee2655a703..a300049a515092b46292c6b05bf057c7b6ce9f62 100644
--- a/src/main/java/net/minecraft/world/entity/npc/CatSpawner.java
+++ b/src/main/java/net/minecraft/world/entity/npc/CatSpawner.java
@@ -91,8 +91,9 @@ public class CatSpawner implements CustomSpawner {
if (cat == null) {
return 0;
} else {
+ cat.moveTo(pos, 0.0F, 0.0F); // Purpur
cat.finalizeSpawn(world, world.getCurrentDifficultyAt(pos), MobSpawnType.NATURAL, (SpawnGroupData)null, (CompoundTag)null);
- cat.moveTo(pos, 0.0F, 0.0F);
+ //cat.moveTo(pos, 0.0F, 0.0F); // Purpur - move up - fixes non black cat types spawning inside swamp huts
world.addFreshEntityWithPassengers(cat);
return 1;
}

View File

@@ -0,0 +1,38 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <Blake.Galbreath@GMail.com>
Date: Wed, 6 Jan 2021 02:19:29 -0600
Subject: [PATCH] Fix rotating UP/DOWN CW and CCW
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/core/Direction.java b/src/main/java/net/minecraft/core/Direction.java
index 4be4d9e6611dc3b7a34dbf2f5d6990bc0980ee63..92789a27aa2978ac323d4cdafa82391998cf0ffa 100644
--- a/src/main/java/net/minecraft/core/Direction.java
+++ b/src/main/java/net/minecraft/core/Direction.java
@@ -247,6 +247,12 @@ public enum Direction implements StringRepresentable {
case EAST:
var10000 = SOUTH;
break;
+ // Purpur start
+ case UP:
+ return UP;
+ case DOWN:
+ return DOWN;
+ // Purpur end
default:
throw new IllegalStateException("Unable to get Y-rotated facing of " + this);
}
@@ -359,6 +365,12 @@ public enum Direction implements StringRepresentable {
case EAST:
var10000 = NORTH;
break;
+ // Purpur start
+ case UP:
+ return UP;
+ case DOWN:
+ return DOWN;
+ // Purpur end
default:
throw new IllegalStateException("Unable to get CCW facing of " + this);
}

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Sun, 15 Dec 2019 12:53:59 -0600
Subject: [PATCH] Disable outdated build check
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/org/bukkit/craftbukkit/Main.java b/src/main/java/org/bukkit/craftbukkit/Main.java
index 298c20e4abc04a8bdc93719c282d0b4ef4560819..29ac511169182f399c903638b941796dd5d08e7e 100644
--- a/src/main/java/org/bukkit/craftbukkit/Main.java
+++ b/src/main/java/org/bukkit/craftbukkit/Main.java
@@ -265,7 +265,7 @@ public class Main {
System.setProperty(TerminalConsoleAppender.JLINE_OVERRIDE_PROPERTY, "false"); // Paper
}
- if (Main.class.getPackage().getImplementationVendor() != null && System.getProperty("IReallyKnowWhatIAmDoingISwear") == null) {
+ if (false && Main.class.getPackage().getImplementationVendor() != null && System.getProperty("IReallyKnowWhatIAmDoingISwear") == null) { // Purpur
Date buildDate = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(Main.class.getPackage().getImplementationVendor()); // Paper
Calendar deadline = Calendar.getInstance();

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Tue, 4 Jun 2019 15:50:08 -0500
Subject: [PATCH] Fix 'outdated server' showing in ping before server fully
boots
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java
index 4fa79d37ff4e70c61672cce7c55257c46232c026..df43d0a0f3d1e34baabae150cbf01a008eb5a588 100644
--- a/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java
@@ -153,6 +153,7 @@ public class ServerStatusPacketListenerImpl implements ServerStatusPacketListene
this.connection.send(new ClientboundStatusResponsePacket(ping));
// CraftBukkit end
*/
+ if (this.server.getStatus().getVersion() == null) return; // Purpur - do not respond to pings before we know the protocol version
com.destroystokyo.paper.network.StandardPaperServerListPingEventImpl.processRequest(this.server, this.connection);
// Paper end
}

View File

@@ -0,0 +1,60 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Sat, 6 Jul 2019 17:00:04 -0500
Subject: [PATCH] Dont send useless entity packets
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/server/level/ServerEntity.java b/src/main/java/net/minecraft/server/level/ServerEntity.java
index 44560edcf339c1749b9df78e6e57075499d5813d..2d7e884d25f352e0a05e9aefb0ff6e296e73c361 100644
--- a/src/main/java/net/minecraft/server/level/ServerEntity.java
+++ b/src/main/java/net/minecraft/server/level/ServerEntity.java
@@ -190,6 +190,7 @@ public class ServerEntity {
this.teleportDelay = 0;
packet1 = new ClientboundTeleportEntityPacket(this.entity);
}
+ if (wtf.etil.mirai.MiraiConfig.dontSendUselessEntityPackets && isUselessPacket(packet1)) packet1 = null; // Purpur
}
if ((this.trackDelta || this.entity.hasImpulse || this.entity instanceof LivingEntity && ((LivingEntity) this.entity).isFallFlying()) && this.tickCount > 0) {
@@ -258,6 +259,22 @@ public class ServerEntity {
}
+ // Purpur start
+ private boolean isUselessPacket(Packet<?> possibleUselessPacket) {
+ if (possibleUselessPacket instanceof ClientboundMoveEntityPacket) {
+ ClientboundMoveEntityPacket packet = (ClientboundMoveEntityPacket) possibleUselessPacket;
+ if (possibleUselessPacket instanceof ClientboundMoveEntityPacket.Pos) {
+ return packet.getXa() == 0 && packet.getYa() == 0 && packet.getZa() == 0;
+ } else if (possibleUselessPacket instanceof ClientboundMoveEntityPacket.PosRot) {
+ return packet.getXa() == 0 && packet.getYa() == 0 && packet.getZa() == 0 && packet.getyRot() == 0 && packet.getxRot() == 0;
+ } else if (possibleUselessPacket instanceof ClientboundMoveEntityPacket.Rot) {
+ return packet.getyRot() == 0 && packet.getxRot() == 0;
+ }
+ }
+ return false;
+ }
+ // Purpur end
+
public void removePairing(ServerPlayer player) {
this.entity.stopSeenByPlayer(player);
player.connection.send(new ClientboundRemoveEntitiesPacket(new int[]{this.entity.getId()}));
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index a24a35f3ef2812d2951fb13439f856ee9495226b..8be485f3f68f42e09058fc543485137e03056266 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -201,6 +201,11 @@ public class MiraiConfig {
checkVehicleFlying = getBoolean("checks.vehicle-flight", checkVehicleFlying);
}
+ public static boolean dontSendUselessEntityPackets = true;
+ private static void dontSendUselessEntityPackets() {
+ dontSendUselessEntityPackets = getBoolean("dont-send-useless-entity-packets", dontSendUselessEntityPackets);
+ }
+
}
\ No newline at end of file

View File

@@ -0,0 +1,28 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Sat, 4 Apr 2020 03:07:59 -0500
Subject: [PATCH] Skip events if there's no listeners
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/commands/Commands.java b/src/main/java/net/minecraft/commands/Commands.java
index b66afde6851ceaeccb84aea00cdc333dfbf3d4b0..c79c89bab8972a26c7a48f63ad20ac34b0fc8750 100644
--- a/src/main/java/net/minecraft/commands/Commands.java
+++ b/src/main/java/net/minecraft/commands/Commands.java
@@ -391,6 +391,7 @@ public class Commands {
}
private void runSync(ServerPlayer player, Collection<String> bukkit, RootCommandNode<SharedSuggestionProvider> rootcommandnode) {
+ if (PlayerCommandSendEvent.getHandlerList().getRegisteredListeners().length > 0) { // Purpur - skip all this crap if there's nothing listening
// Paper end - Async command map building
new com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent<CommandSourceStack>(player.getBukkitEntity(), (RootCommandNode) rootcommandnode, false).callEvent(); // Paper
PlayerCommandSendEvent event = new PlayerCommandSendEvent(player.getBukkitEntity(), new LinkedHashSet<>(bukkit));
@@ -403,6 +404,7 @@ public class Commands {
}
}
// CraftBukkit end
+ } // Purpur - skip event
player.connection.send(new ClientboundCommandsPacket(rootcommandnode));
}

View File

@@ -0,0 +1,33 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Fri, 6 Mar 2020 13:37:26 -0600
Subject: [PATCH] Fix the dead lagging the server
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index 38cb136d34cbc83dde1c766196f60a30d38005e3..5744b25104d3b73cedda3c88945dfce1db265b1e 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -1782,6 +1782,7 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
this.yRotO = this.getYRot();
this.xRotO = this.getXRot();
this.setYHeadRot(yaw); // Paper - Update head rotation
+ if (valid && !this.isRemoved()) level.getChunk((int) Math.floor(this.getX()) >> 4, (int) Math.floor(this.getZ()) >> 4); // CraftBukkit // Paper // Purpur
}
public void absMoveTo(double x, double y, double z) {
diff --git a/src/main/java/net/minecraft/world/entity/LivingEntity.java b/src/main/java/net/minecraft/world/entity/LivingEntity.java
index f646545ee7178717c1e3bb48e98fd2af2af745e0..8e5c8d1e59af15a0b28a8e28e60e50d2ec3b23f9 100644
--- a/src/main/java/net/minecraft/world/entity/LivingEntity.java
+++ b/src/main/java/net/minecraft/world/entity/LivingEntity.java
@@ -2935,7 +2935,7 @@ public abstract class LivingEntity extends Entity {
}
}
- this.aiStep();
+ if (!this.isRemoved()) this.aiStep(); // Purpur
double d0 = this.getX() - this.xo;
double d1 = this.getZ() - this.zo;
float f = (float) (d0 * d0 + d1 * d1);

View File

@@ -0,0 +1,76 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Fri, 11 Oct 2019 00:17:39 -0500
Subject: [PATCH] Alternative Keepalive Handling
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
index f31fc4a40d817a4115159bca39b7f907fdc765a9..de99c84622ff69f3f8707d92aacd5e9a1d980ccf 100644
--- a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
@@ -227,6 +227,7 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
private long keepAliveTime = Util.getMillis();
private boolean keepAlivePending;
private long keepAliveChallenge;
+ private java.util.List<Long> keepAlives = new java.util.ArrayList<>(); // Purpur
// CraftBukkit start - multithreaded fields
private final AtomicInteger chatSpamTickCount = new AtomicInteger();
private final java.util.concurrent.atomic.AtomicInteger tabSpamLimiter = new java.util.concurrent.atomic.AtomicInteger(); // Paper - configurable tab spam limits
@@ -356,6 +357,21 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
long currentTime = Util.getMillis();
long elapsedTime = currentTime - this.keepAliveTime;
+ // Purpur start
+ if (wtf.etil.mirai.MiraiConfig.useAlternateKeepAlive) {
+ if (elapsedTime >= 1000L) { // 1 second
+ if (!processedDisconnect && keepAlives.size() > KEEPALIVE_LIMIT) {
+ LOGGER.warn("{} was kicked due to keepalive timeout!", player.getName());
+ disconnect(new TranslatableComponent("disconnect.timeout"));
+ } else {
+ keepAliveTime = currentTime; // hijack this field for 1 second intervals
+ keepAlives.add(currentTime); // currentTime is ID
+ send(new ClientboundKeepAlivePacket(currentTime));
+ }
+ }
+ } else
+ // Purpur end
+
if (this.keepAlivePending) {
if (!this.processedDisconnect && elapsedTime >= KEEPALIVE_LIMIT) { // check keepalive limit, don't fire if already disconnected
ServerGamePacketListenerImpl.LOGGER.warn("{} was kicked due to keepalive timeout!", this.player.getScoreboardName()); // more info
@@ -3137,6 +3153,16 @@ public class ServerGamePacketListenerImpl implements ServerPlayerConnection, Ser
@Override
public void handleKeepAlive(ServerboundKeepAlivePacket packet) {
+ // Purpur start
+ if (wtf.etil.mirai.MiraiConfig.useAlternateKeepAlive) {
+ long id = packet.getId();
+ if (keepAlives.size() > 0 && keepAlives.contains(id)) {
+ int ping = (int) (Util.getMillis() - id);
+ player.latency = (player.latency * 3 + ping) / 4;
+ keepAlives.clear(); // we got a valid response, lets roll with it and forget the rest
+ }
+ } else
+ // Purpur end
//PlayerConnectionUtils.ensureMainThread(packetplayinkeepalive, this, this.player.getWorldServer()); // CraftBukkit // Paper - This shouldn't be on the main thread
if (this.keepAlivePending && packet.getId() == this.keepAliveChallenge) {
int i = (int) (Util.getMillis() - this.keepAliveTime);
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index 8be485f3f68f42e09058fc543485137e03056266..ee0b35e703b1930b32a01b5fa532fdbaf60127c4 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -206,6 +206,11 @@ public class MiraiConfig {
dontSendUselessEntityPackets = getBoolean("dont-send-useless-entity-packets", dontSendUselessEntityPackets);
}
+ public static boolean useAlternateKeepAlive = true;
+ private static void useAlternateKeepAlive() {
+ useAlternateKeepAlive = getBoolean("use-alternate-keepalive", useAlternateKeepAlive);
+ }
+
}
\ No newline at end of file

View File

@@ -0,0 +1,65 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Sat, 19 Oct 2019 00:52:12 -0500
Subject: [PATCH] Logger settings (suppressing pointless logs)
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/server/PlayerAdvancements.java b/src/main/java/net/minecraft/server/PlayerAdvancements.java
index b16287a47870978706734b928b87f2357e91e3a1..5a80d307487fb824e7b59ac188760bafd06871e1 100644
--- a/src/main/java/net/minecraft/server/PlayerAdvancements.java
+++ b/src/main/java/net/minecraft/server/PlayerAdvancements.java
@@ -186,6 +186,7 @@ public class PlayerAdvancements {
if (advancement == null) {
// CraftBukkit start
if (entry.getKey().getNamespace().equals("minecraft")) {
+ if (!wtf.etil.mirai.MiraiConfig.loggerSuppressIgnoredAdvancementWarnings) // Purpur
PlayerAdvancements.LOGGER.warn("Ignored advancement '{}' in progress file {} - it doesn't exist anymore?", entry.getKey(), this.file);
}
// CraftBukkit end
diff --git a/src/main/java/net/minecraft/stats/ServerRecipeBook.java b/src/main/java/net/minecraft/stats/ServerRecipeBook.java
index d13ed3069e944d138442ea440ac3eaf8d44c18d3..c19367bdad3997aa7aac609762f9cf731433adfc 100644
--- a/src/main/java/net/minecraft/stats/ServerRecipeBook.java
+++ b/src/main/java/net/minecraft/stats/ServerRecipeBook.java
@@ -122,6 +122,7 @@ public class ServerRecipeBook extends RecipeBook {
Optional<? extends Recipe<?>> optional = recipeManager.byKey(minecraftkey);
if (!optional.isPresent()) {
+ if (!wtf.etil.mirai.MiraiConfig.loggerSuppressUnrecognizedRecipeErrors) // Purpur
ServerRecipeBook.LOGGER.error("Tried to load unrecognized recipe: {} removed now.", minecraftkey);
} else {
handler.accept((Recipe) optional.get());
diff --git a/src/main/java/org/bukkit/craftbukkit/legacy/CraftLegacy.java b/src/main/java/org/bukkit/craftbukkit/legacy/CraftLegacy.java
index b2a15c986c7500a0ce227a54cb61ec3f5378f6f3..d243af83f3159d8a4d56d08dab022b317cc5687e 100644
--- a/src/main/java/org/bukkit/craftbukkit/legacy/CraftLegacy.java
+++ b/src/main/java/org/bukkit/craftbukkit/legacy/CraftLegacy.java
@@ -255,6 +255,7 @@ public final class CraftLegacy {
}
static {
+ if (!wtf.etil.mirai.MiraiConfig.loggerSuppressInitLegacyMaterialError) // Purpur
System.err.println("Initializing Legacy Material Support. Unless you have legacy plugins and/or data this is a bug!");
if (MinecraftServer.getServer() != null && MinecraftServer.getServer().isDebugging()) {
new Exception().printStackTrace();
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index ee0b35e703b1930b32a01b5fa532fdbaf60127c4..ede41bc4ab49065cc06e66189610791cab01b39d 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -211,6 +211,15 @@ public class MiraiConfig {
useAlternateKeepAlive = getBoolean("use-alternate-keepalive", useAlternateKeepAlive);
}
+ public static boolean loggerSuppressInitLegacyMaterialError = true;
+ public static boolean loggerSuppressIgnoredAdvancementWarnings = true;
+ public static boolean loggerSuppressUnrecognizedRecipeErrors = true;
+ private static void loggerSettings() {
+ loggerSuppressInitLegacyMaterialError = getBoolean("logger.suppress-init-legacy-material-errors", loggerSuppressInitLegacyMaterialError);
+ loggerSuppressIgnoredAdvancementWarnings = getBoolean("logger.suppress-ignored-advancement-warnings", loggerSuppressIgnoredAdvancementWarnings);
+ loggerSuppressUnrecognizedRecipeErrors = getBoolean("logger.suppress-unrecognized-recipe-errors", loggerSuppressUnrecognizedRecipeErrors);
+ }
+
}
\ No newline at end of file

View File

@@ -0,0 +1,97 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <blake.galbreath@gmail.com>
Date: Sun, 28 Jul 2019 01:27:37 -0500
Subject: [PATCH] Add 5 second tps average in /tps
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/com/destroystokyo/paper/gui/RAMDetails.java b/src/main/java/com/destroystokyo/paper/gui/RAMDetails.java
index fa56cd09102a89692b42f1d14257990508c5c720..f9251183df72ddc56662fd3f02acf21641a2200c 100644
--- a/src/main/java/com/destroystokyo/paper/gui/RAMDetails.java
+++ b/src/main/java/com/destroystokyo/paper/gui/RAMDetails.java
@@ -58,7 +58,7 @@ public class RAMDetails extends JList<String> {
GraphData data = RAMGraph.DATA.peekLast();
Vector<String> vector = new Vector<>();
- double[] tps = new double[] {server.tps1.getAverage(), server.tps5.getAverage(), server.tps15.getAverage()};
+ double[] tps = new double[] {server.tps5s.getAverage(), server.tps1.getAverage(), server.tps5.getAverage(), server.tps15.getAverage()}; // Purpur
String[] tpsAvg = new String[tps.length];
for ( int g = 0; g < tps.length; g++) {
@@ -67,7 +67,7 @@ public class RAMDetails extends JList<String> {
vector.add("Memory use: " + (data.getUsedMem() / 1024L / 1024L) + " mb (" + (data.getFree() * 100L / data.getMax()) + "% free)");
vector.add("Heap: " + (data.getTotal() / 1024L / 1024L) + " / " + (data.getMax() / 1024L / 1024L) + " mb");
vector.add("Avg tick: " + DECIMAL_FORMAT.format(getAverage(server.tickTimes)) + " ms");
- vector.add("TPS from last 1m, 5m, 15m: " + String.join(", ", tpsAvg));
+ vector.add("TPS from last 5s, 1m, 5m, 15m: " + String.join(", ", tpsAvg)); // Purpur
setListData(vector);
}
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 30156d3c983f83c4d96ce089a27ff9bfed29555e..282fc59c3280d5d8478cb9897073d9d73996420b 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -302,7 +302,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
public static final int TPS = 20;
public static final int TICK_TIME = 1000000000 / MinecraftServer.TPS;
private static final int SAMPLE_INTERVAL = 20; // Paper
- public final double[] recentTps = new double[ 3 ];
+ public final double[] recentTps = new double[ 4 ]; // Purpur
// Spigot end
public static long currentTickLong = 0L; // Paper
@@ -1113,6 +1113,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
private static final long MAX_CATCHUP_BUFFER = TICK_TIME * TPS * 60L;
private long lastTick = 0;
private long catchupTime = 0;
+ public final RollingAverage tps5s = new RollingAverage(5); // Purpur
public final RollingAverage tps1 = new RollingAverage(60);
public final RollingAverage tps5 = new RollingAverage(60 * 5);
public final RollingAverage tps15 = new RollingAverage(60 * 15);
@@ -1205,13 +1206,17 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
{
final long diff = curTime - tickSection;
java.math.BigDecimal currentTps = TPS_BASE.divide(new java.math.BigDecimal(diff), 30, java.math.RoundingMode.HALF_UP);
+ tps5s.add(currentTps, diff); // Purpur
tps1.add(currentTps, diff);
tps5.add(currentTps, diff);
tps15.add(currentTps, diff);
// Backwards compat with bad plugins
- this.recentTps[0] = tps1.getAverage();
- this.recentTps[1] = tps5.getAverage();
- this.recentTps[2] = tps15.getAverage();
+ // Purpur start
+ this.recentTps[0] = tps5s.getAverage();
+ this.recentTps[1] = tps1.getAverage();
+ this.recentTps[2] = tps5.getAverage();
+ this.recentTps[3] = tps15.getAverage();
+ // Purpur end
// Paper end
tickSection = curTime;
}
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index 69ddc41119dc621cf0ffa9e8e89bc761dc666b7d..ca0a5a22271b8f72a8d3f4b8b7890c0a370cec3b 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -2667,6 +2667,7 @@ public final class CraftServer implements Server {
@Override
public double[] getTPS() {
return new double[] {
+ net.minecraft.server.MinecraftServer.getServer().tps5s.getAverage(), // Purpur
net.minecraft.server.MinecraftServer.getServer().tps1.getAverage(),
net.minecraft.server.MinecraftServer.getServer().tps5.getAverage(),
net.minecraft.server.MinecraftServer.getServer().tps15.getAverage()
diff --git a/src/main/java/org/spigotmc/TicksPerSecondCommand.java b/src/main/java/org/spigotmc/TicksPerSecondCommand.java
index b735769b7876e54db2950ebb4170484447cfb9a6..0ecac76577eb440a0c3104ef4603acec826c474d 100644
--- a/src/main/java/org/spigotmc/TicksPerSecondCommand.java
+++ b/src/main/java/org/spigotmc/TicksPerSecondCommand.java
@@ -31,7 +31,7 @@ public class TicksPerSecondCommand extends Command
for ( int i = 0; i < tps.length; i++) {
tpsAvg[i] = TicksPerSecondCommand.format( tps[i] );
}
- sender.sendMessage(ChatColor.GOLD + "TPS from last 1m, 5m, 15m: " + org.apache.commons.lang.StringUtils.join(tpsAvg, ", "));
+ sender.sendMessage(ChatColor.GOLD + "TPS from last 5s, 1m, 5m, 15m: " + org.apache.commons.lang.StringUtils.join(tpsAvg, ", ")); // Purpur
// Yatopia start - Last tick time API
java.time.Duration lastTickTime = org.bukkit.Bukkit.getLastTickTime();
sender.sendMessage(ChatColor.GOLD + "Last tick: " + TicksPerSecondCommand.formatTo( lastTickTime, java.util.concurrent.TimeUnit.MILLISECONDS ) + " (" + formatTo( lastTickTime, java.util.concurrent.TimeUnit.NANOSECONDS ) + ")");

View File

@@ -0,0 +1,57 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <Blake.Galbreath@GMail.com>
Date: Thu, 14 Jan 2021 16:48:10 -0600
Subject: [PATCH] Fix stuck in portals
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/server/level/ServerPlayer.java b/src/main/java/net/minecraft/server/level/ServerPlayer.java
index 1a9afa43a953e5634edb23ef617ead4b329ae89f..bf42644d2053de4e3c7b9e531b18230b07f094c5 100644
--- a/src/main/java/net/minecraft/server/level/ServerPlayer.java
+++ b/src/main/java/net/minecraft/server/level/ServerPlayer.java
@@ -1145,6 +1145,7 @@ public class ServerPlayer extends Player {
playerlist.sendPlayerPermissionLevel(this);
worldserver1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION);
this.unsetRemoved();
+ this.portalPos = net.minecraft.server.MCUtil.toBlockPosition(exit); // Purpur
// CraftBukkit end
this.setLevel(worldserver);
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index 5744b25104d3b73cedda3c88945dfce1db265b1e..0b28025545bb26aff4a91fe3b78e4fc361ecf4e2 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -2766,12 +2766,15 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
return Vec3.directionFromRotation(this.getRotationVector());
}
+ public BlockPos portalPos = BlockPos.ZERO; // Purpur
public void handleInsidePortal(BlockPos pos) {
if (this.isOnPortalCooldown()) {
+ if (!(wtf.etil.mirai.MiraiConfig.playerFixStuckPortal && this instanceof Player && !pos.equals(portalPos))) // Purpur
this.setPortalCooldown();
} else {
if (!this.level.isClientSide && !pos.equals(this.portalEntrancePos)) {
this.portalEntrancePos = pos.immutable();
+ portalPos = BlockPos.ZERO; // Purpur
}
this.isInsidePortal = true;
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index ede41bc4ab49065cc06e66189610791cab01b39d..bee288d0735af17571902203936c7eb7025184f0 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -220,6 +220,11 @@ public class MiraiConfig {
loggerSuppressUnrecognizedRecipeErrors = getBoolean("logger.suppress-unrecognized-recipe-errors", loggerSuppressUnrecognizedRecipeErrors);
}
+ public static boolean playerFixStuckPortal = false;
+ private static void FixStuckPortal() {
+ playerFixStuckPortal = getBoolean("player-fix-stuck-in-portal", playerFixStuckPortal);
+ }
+
}
\ No newline at end of file

View File

@@ -0,0 +1,46 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: William Blake Galbreath <Blake.Galbreath@GMail.com>
Date: Mon, 17 Aug 2020 19:32:05 -0500
Subject: [PATCH] Entities can use portals configuration
Original code by PurpurMC, licensed under MIT
You can find the original code on https://github.com/PurpurMC/Purpur
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index 0b28025545bb26aff4a91fe3b78e4fc361ecf4e2..651baec777f02038a775bd70e9f3e550befaa773 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -2771,7 +2771,7 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
if (this.isOnPortalCooldown()) {
if (!(wtf.etil.mirai.MiraiConfig.playerFixStuckPortal && this instanceof Player && !pos.equals(portalPos))) // Purpur
this.setPortalCooldown();
- } else {
+ } else if (wtf.etil.mirai.MiraiConfig.entitiesCanUsePortals || this instanceof ServerPlayer) { // Purpur
if (!this.level.isClientSide && !pos.equals(this.portalEntrancePos)) {
this.portalEntrancePos = pos.immutable();
portalPos = BlockPos.ZERO; // Purpur
@@ -3438,7 +3438,7 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
}
public boolean canChangeDimensions() {
- return isAlive() && valid; // Paper
+ return isAlive() && valid && (wtf.etil.mirai.MiraiConfig.entitiesCanUsePortals || this instanceof ServerPlayer); // Paper // Purpur
}
public float getBlockExplosionResistance(Explosion explosion, BlockGetter world, BlockPos pos, BlockState blockState, FluidState fluidState, float max) {
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index bee288d0735af17571902203936c7eb7025184f0..a1d88b8cadf6c193deb69bb577936ebd69e63b2a 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -225,6 +225,9 @@ public class MiraiConfig {
playerFixStuckPortal = getBoolean("player-fix-stuck-in-portal", playerFixStuckPortal);
}
-
+ public static boolean entitiesCanUsePortals = true;
+ private static void entitiesPortal() {
+ entitiesCanUsePortals = getBoolean("entities-can-use-portals", entitiesCanUsePortals);
+ }
}
\ No newline at end of file

View File

@@ -0,0 +1,64 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: astei <andrew@steinborn.me>
Date: Tue, 30 Nov 2021 19:39:21 +0100
Subject: [PATCH] PaperPR Optimize VarInts
diff --git a/src/main/java/net/minecraft/network/FriendlyByteBuf.java b/src/main/java/net/minecraft/network/FriendlyByteBuf.java
index 896a4237f871d46cf39b0721e909c2cc3b5fc728..e2a0a7fd5afd8cd3467dab049695956c381fb3cd 100644
--- a/src/main/java/net/minecraft/network/FriendlyByteBuf.java
+++ b/src/main/java/net/minecraft/network/FriendlyByteBuf.java
@@ -65,19 +65,22 @@ public class FriendlyByteBuf extends ByteBuf {
public java.util.Locale adventure$locale; // Paper
public static final short MAX_STRING_LENGTH = 32767;
public static final int MAX_COMPONENT_STRING_LENGTH = 262144;
+ // Paper start - Optimize VarInts
+ private static final int[] VARINT_EXACT_BYTE_LENGTHS = new int[33];
+ static {
+ for (int i = 0; i <= 32; ++i) {
+ VARINT_EXACT_BYTE_LENGTHS[i] = (int) Math.ceil((31d - (i - 1)) / 7d);
+ }
+ VARINT_EXACT_BYTE_LENGTHS[32] = 1; // Special case for the number 0.
+ }
+ // Paper end - Optimize VarInts
public FriendlyByteBuf(ByteBuf parent) {
this.source = parent;
}
public static int getVarIntSize(int value) {
- for (int j = 1; j < 5; ++j) {
- if ((value & -1 << j * 7) == 0) {
- return j;
- }
- }
-
- return 5;
+ return VARINT_EXACT_BYTE_LENGTHS[Integer.numberOfLeadingZeros(value)]; // Paper - Optimize VarInts
}
public static int getVarLongSize(long value) {
@@ -420,7 +423,23 @@ public class FriendlyByteBuf extends ByteBuf {
return new UUID(this.readLong(), this.readLong());
}
+ // Paper start - Optimize VarInts
public FriendlyByteBuf writeVarInt(int value) {
+ // Peel the one and two byte count cases explicitly as they are the most common VarInt sizes
+ // that the proxy will write, to improve inlining.
+ if ((value & (0xFFFFFFFF << 7)) == 0) {
+ writeByte(value);
+ } else if ((value & (0xFFFFFFFF << 14)) == 0) {
+ int w = (value & 0x7F | 0x80) << 8 | (value >>> 7);
+ writeShort(w);
+ } else {
+ writeVarInt_(value);
+ }
+ return this;
+ }
+
+ public FriendlyByteBuf writeVarInt_(int value) {
+ // Paper end - Optimize VarInts
while ((value & -128) != 0) {
this.writeByte(value & 127 | 128);
value >>>= 7;

View File

@@ -0,0 +1,32 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Jake Potrebic <15055071+Machine-Maker@users.noreply.github.com>
Date: Fri, 10 Dec 2021 08:15:36 -0500
Subject: [PATCH] PaperPR Use DataConverter for itemstack/entity
deserialization
diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
index 1e74799bb012ca45769a3fd103f0b24eba0a9a99..61ee37d1c81274f58922fde4138536b10847508b 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
@@ -453,8 +453,8 @@ public final class CraftMagicNumbers implements UnsafeValues {
CompoundTag compound = deserializeNbtFromBytes(data);
int dataVersion = compound.getInt("DataVersion");
- Dynamic<Tag> converted = DataFixers.getDataFixer().update(References.ITEM_STACK, new Dynamic<Tag>(NbtOps.INSTANCE, compound), dataVersion, getDataVersion());
- return CraftItemStack.asCraftMirror(net.minecraft.world.item.ItemStack.of((CompoundTag) converted.getValue()));
+ compound = ca.spottedleaf.dataconverter.minecraft.MCDataConverter.convertTag(ca.spottedleaf.dataconverter.minecraft.datatypes.MCTypeRegistry.ITEM_STACK, compound, dataVersion, getDataVersion()); // Paper - rewrite dataconverter
+ return CraftItemStack.asCraftMirror(net.minecraft.world.item.ItemStack.of(compound));
}
@Override
@@ -474,8 +474,7 @@ public final class CraftMagicNumbers implements UnsafeValues {
CompoundTag compound = deserializeNbtFromBytes(data);
int dataVersion = compound.getInt("DataVersion");
- Dynamic<Tag> converted = DataFixers.getDataFixer().update(References.ENTITY_TREE, new Dynamic<>(NbtOps.INSTANCE, compound), dataVersion, getDataVersion());
- compound = (CompoundTag) converted.getValue();
+ compound = ca.spottedleaf.dataconverter.minecraft.MCDataConverter.convertTag(ca.spottedleaf.dataconverter.minecraft.datatypes.MCTypeRegistry.ENTITY, compound, dataVersion, getDataVersion()); // Paper - rewrite dataconverter
if (!preserveUUID) compound.remove("UUID"); // Generate a new UUID so we don't have to worry about deserializing the same entity twice
return net.minecraft.world.entity.EntityType.create(compound, ((org.bukkit.craftbukkit.CraftWorld) world).getHandle())
.orElseThrow(() -> new IllegalArgumentException("An ID was not found for the data. Did you downgrade?")).getBukkitEntity();

View File

@@ -0,0 +1,29 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: 2No2Name <2No2Name@web.de>
Date: Sun, 12 Dec 2021 16:41:06 -0500
Subject: [PATCH] lithium: replace AI goal set with optimized collection
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java b/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java
index 289b78ca3e587ffd42a920b99cbe5078a0d787a4..2834196fa116bdd629adaac010b30e980719d653 100644
--- a/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java
+++ b/src/main/java/net/minecraft/world/entity/ai/goal/GoalSelector.java
@@ -12,6 +12,7 @@ import java.util.function.Supplier;
import java.util.stream.Stream;
import net.minecraft.util.profiling.ProfilerFiller;
import org.slf4j.Logger;
+import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; // Lithium
public class GoalSelector {
private static final Logger LOGGER = LogUtils.getLogger();
@@ -27,7 +28,7 @@ public class GoalSelector {
}
};
private final Map<Goal.Flag, WrappedGoal> lockedFlags = new EnumMap<>(Goal.Flag.class);
- public final Set<WrappedGoal> availableGoals = Sets.newLinkedHashSet();
+ public final Set<WrappedGoal> availableGoals = new ObjectLinkedOpenHashSet<>(); // Lithium - replace AI goal set with optimized collection
private final Supplier<ProfilerFiller> profiler;
private final EnumSet<Goal.Flag> disabledFlags = EnumSet.noneOf(Goal.Flag.class); // Paper unused, but dummy to prevent plugins from crashing as hard. Theyll need to support paper in a special case if this is super important, but really doesn't seem like it would be.
private final com.destroystokyo.paper.util.set.OptimizedSmallEnumSet<net.minecraft.world.entity.ai.goal.Goal.Flag> goalTypes = new com.destroystokyo.paper.util.set.OptimizedSmallEnumSet<>(Goal.Flag.class); // Paper - remove streams from pathfindergoalselector

View File

@@ -0,0 +1,43 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: ishland <ishlandmc@yeah.net>
Date: Sun, 12 Dec 2021 17:19:00 -0500
Subject: [PATCH] vmp: skip entity move if movement is zero
Copyright (c) 2021-2022 ishland
Original code by RelativityMC, licensed under MIT
You can find the original code on https://github.com/RelativityMC/VMP-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index 651baec777f02038a775bd70e9f3e550befaa773..adc4a19039b56de81053e746580dbef9c1fe9c93 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -238,6 +238,7 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
public float yRotO;
public float xRotO;
private AABB bb;
+ private boolean boundingBoxChanged = false; // Mirai - vmp: skip entity move if movement is zero
public boolean onGround;
public boolean horizontalCollision;
public boolean verticalCollision;
@@ -969,6 +970,12 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
// Paper end - detailed watchdog information
public void move(MoverType movementType, Vec3 movement) {
+ // Mirai start - vmp: skip entity move if movement is zero
+ if (!boundingBoxChanged && movement.equals(Vec3.ZERO)) {
+ boundingBoxChanged = false;
+ return;
+ }
+ // Mirai end
// Paper start - detailed watchdog information
io.papermc.paper.util.TickThread.ensureTickThread("Cannot move an entity off-main");
synchronized (this.posLock) {
@@ -3643,6 +3650,7 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
}
public final void setBoundingBox(AABB boundingBox) {
+ if (!this.bb.equals(boundingBox)) boundingBoxChanged = true; // Mirai - vmp: skip entity move if movement is zero
// CraftBukkit start - block invalid bounding boxes
double minX = boundingBox.minX,
minY = boundingBox.minY,

View File

@@ -0,0 +1,65 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Phoenix616 <mail@moep.tv>
Date: Sun, 24 Nov 2019 23:00:58 +0100
Subject: [PATCH] Optimize inventory API item handling
Original code by Minebench, licensed under GNU General Public License v3.0
You can find the original code on https://github.com/Minebench/Origami
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java
index 30ac442049088200e9ab77a561c59cbc58aaa28f..bdacb0098c93be63693218544b6dc1a2937cdb3b 100644
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java
@@ -273,11 +273,13 @@ public class CraftInventory implements Inventory {
}
private int firstPartial(ItemStack item) {
- ItemStack[] inventory = this.getStorageContents();
- ItemStack filteredItem = CraftItemStack.asCraftCopy(item);
if (item == null) {
return -1;
}
+ // Origami start - Optimize inventory API (moved down from before null check)
+ ItemStack[] inventory = this.getStorageContents();
+ ItemStack filteredItem = CraftItemStack.asCraftCopy(item);
+ // Origami end
for (int i = 0; i < inventory.length; i++) {
ItemStack cItem = inventory[i];
if (cItem != null && cItem.getAmount() < cItem.getMaxStackSize() && cItem.isSimilar(filteredItem)) {
@@ -295,9 +297,10 @@ public class CraftInventory implements Inventory {
/* TODO: some optimization
* - Create a 'firstPartial' with a 'fromIndex'
* - Record the lastPartial per Material
- * - Cache firstEmpty result
+ * - Cache firstEmpty result // Implemented in Origami
*/
+ int firstFree = -2; // Origami - Cache firstEmpty result
for (int i = 0; i < items.length; i++) {
ItemStack item = items[i];
while (true) {
@@ -307,7 +310,11 @@ public class CraftInventory implements Inventory {
// Drat! no partial stack
if (firstPartial == -1) {
// Find a free spot!
- int firstFree = this.firstEmpty();
+ // Origami start - Cache firstEmpty result
+ if (firstFree == -2) {
+ firstFree = this.firstEmpty();
+ }
+ // Origami end
if (firstFree == -1) {
// No space at all!
@@ -320,9 +327,11 @@ public class CraftInventory implements Inventory {
stack.setAmount(this.getMaxItemStack());
this.setItem(firstFree, stack);
item.setAmount(item.getAmount() - this.getMaxItemStack());
+ firstFree = -2; // Origami - Cache firstEmpty result
} else {
// Just store it
this.setItem(firstFree, item);
+ firstFree = -2; // Origami - Cache firstEmpty result
break;
}
}

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Tom <cryptite@gmail.com>
Date: Thu, 23 Sep 2021 08:56:42 -0500
Subject: [PATCH] Don't send equipment updates if only durability changed
Original code by Cryptite, licensed under MIT
You can find the original code on https://github.com/Cryptite/Slice
diff --git a/src/main/java/net/minecraft/world/entity/LivingEntity.java b/src/main/java/net/minecraft/world/entity/LivingEntity.java
index 8e5c8d1e59af15a0b28a8e28e60e50d2ec3b23f9..1fdc19830bf4cf677df60c5760e02ae53abc85cc 100644
--- a/src/main/java/net/minecraft/world/entity/LivingEntity.java
+++ b/src/main/java/net/minecraft/world/entity/LivingEntity.java
@@ -3052,7 +3052,7 @@ public abstract class LivingEntity extends Entity {
ItemStack itemstack1 = this.getItemBySlot(enumitemslot);
- if (!ItemStack.matches(itemstack1, itemstack)) {
+ if (!ItemStack.isSameIgnoreDurability(itemstack1, itemstack)) {
// Paper start - PlayerArmorChangeEvent
if (this instanceof ServerPlayer && enumitemslot.getType() == EquipmentSlot.Type.ARMOR) {
final org.bukkit.inventory.ItemStack oldItem = CraftItemStack.asBukkitCopy(itemstack);

View File

@@ -0,0 +1,25 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Cryptite <cryptite@gmail.com>
Date: Thu, 23 Sep 2021 09:29:09 -0500
Subject: [PATCH] Don't send fire packets if player has Fire Resistance
Original code by Cryptite, licensed under MIT
You can find the original code on https://github.com/Cryptite/Slice
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index adc4a19039b56de81053e746580dbef9c1fe9c93..9b224ca33115aa7e7f100a45fe8bdb68ea7e4b59 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -815,7 +815,11 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
this.checkOutOfWorld();
if (!this.level.isClientSide) {
- this.setSharedFlagOnFire(this.remainingFireTicks > 0);
+ if (this instanceof net.minecraft.world.entity.LivingEntity livingEntity) {
+ this.setSharedFlagOnFire(this.remainingFireTicks > 0 && !livingEntity.hasEffect(net.minecraft.world.effect.MobEffects.FIRE_RESISTANCE));
+ } else {
+ this.setSharedFlagOnFire(this.remainingFireTicks > 0);
+ }
}
this.firstTick = false;

View File

@@ -0,0 +1,198 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Cryptite <cryptite@gmail.com>
Date: Wed, 6 Oct 2021 11:03:01 -0500
Subject: [PATCH] Packet obfuscation and reduction
Original code by Cryptite, licensed under MIT
You can find the original code on https://github.com/Cryptite/Slice
diff --git a/src/main/java/net/minecraft/network/protocol/game/ClientboundSetEntityDataPacket.java b/src/main/java/net/minecraft/network/protocol/game/ClientboundSetEntityDataPacket.java
index 019ccd50ac87557bd971c0fde3113cc0e2e301ff..bb116272d84908649ef0f80618a66094422ecfca 100644
--- a/src/main/java/net/minecraft/network/protocol/game/ClientboundSetEntityDataPacket.java
+++ b/src/main/java/net/minecraft/network/protocol/game/ClientboundSetEntityDataPacket.java
@@ -22,6 +22,13 @@ public class ClientboundSetEntityDataPacket implements Packet<ClientGamePacketLi
}
+ // Slice start
+ public ClientboundSetEntityDataPacket(int id, List<SynchedEntityData.DataItem<?>> packedItems) {
+ this.id = id;
+ this.packedItems = packedItems;
+ }
+ // Slice end
+
public ClientboundSetEntityDataPacket(FriendlyByteBuf buf) {
this.id = buf.readVarInt();
this.packedItems = SynchedEntityData.unpack(buf);
diff --git a/src/main/java/net/minecraft/network/syncher/SynchedEntityData.java b/src/main/java/net/minecraft/network/syncher/SynchedEntityData.java
index 1d88edfd09a909044f6e3175af652914b4d06311..9031fb0e8c589b759549f4197772b6c9929736a0 100644
--- a/src/main/java/net/minecraft/network/syncher/SynchedEntityData.java
+++ b/src/main/java/net/minecraft/network/syncher/SynchedEntityData.java
@@ -136,6 +136,12 @@ public class SynchedEntityData {
}
public <T> void set(EntityDataAccessor<T> key, T value) {
+ // Slice start
+ set(key, value, null);
+ }
+
+ public <T> void set(EntityDataAccessor<T> key, T value, @Nullable T foreignValue) {
+ // Slice end
SynchedEntityData.DataItem<T> datawatcher_item = this.getItem(key);
if (ObjectUtils.notEqual(value, datawatcher_item.getValue())) {
@@ -145,6 +151,11 @@ public class SynchedEntityData {
this.isDirty = true;
}
+ // Slice start
+ if (foreignValue != null && ObjectUtils.notEqual(foreignValue, datawatcher_item.getForeignValue())) {
+ datawatcher_item.setForeignValue(foreignValue);
+ }
+ // Slice end
}
// CraftBukkit start - add method from above
@@ -200,6 +211,28 @@ public class SynchedEntityData {
return list;
}
+ // Slice start
+ @Nullable
+ public List<SynchedEntityData.DataItem<?>> packForeignDirty(List<DataItem<?>> unpackedData) {
+ List<SynchedEntityData.DataItem<?>> list = null;
+
+ for (DataItem<?> dataItem : unpackedData) {
+ DataItem<?> item = itemsById.get(dataItem.accessor.getId());
+ if (item.isDirty(true)) {
+ item.setForeignDirty(false);
+
+ if (list == null) {
+ list = Lists.newArrayList();
+ }
+
+ list.add(item.copy(true));
+ }
+ }
+
+ return list;
+ }
+ // Slice end
+
@Nullable
public List<SynchedEntityData.DataItem<?>> getAll() {
List<SynchedEntityData.DataItem<?>> list = null;
@@ -313,11 +346,14 @@ public class SynchedEntityData {
final EntityDataAccessor<T> accessor;
T value;
private boolean dirty;
+ @Nullable T foreignValue = null; // Slice
+ private boolean foreignDirty; // Slice
public DataItem(EntityDataAccessor<T> data, T value) {
this.accessor = data;
this.value = value;
this.dirty = true;
+ this.foreignDirty = true; // Slice
}
public EntityDataAccessor<T> getAccessor() {
@@ -343,5 +379,34 @@ public class SynchedEntityData {
public SynchedEntityData.DataItem<T> copy() {
return new SynchedEntityData.DataItem<>(this.accessor, this.accessor.getSerializer().copy(this.value));
}
+
+ // Slice start
+ public void setForeignValue(T foreignValue) {
+ this.foreignValue = foreignValue;
+ this.foreignDirty = true;
+ }
+
+ public @Nullable T getForeignValue() {
+ return foreignValue;
+ }
+
+ public boolean isDirty(boolean foreign) {
+ if (foreign) {
+ //There must be a foreign value in order for this to be dirty, otherwise we consider this a normal
+ //value and check the normal dirty flag.
+ return foreignValue == null || this.foreignDirty;
+ }
+
+ return this.dirty;
+ }
+
+ public void setForeignDirty(boolean dirty) {
+ this.foreignDirty = dirty;
+ }
+
+ public SynchedEntityData.DataItem<T> copy(boolean foreign) {
+ return new SynchedEntityData.DataItem<>(this.accessor, this.accessor.getSerializer().copy((foreign && this.foreignValue != null ? this.foreignValue : this.value)));
+ }
+ // Slice end
}
}
diff --git a/src/main/java/net/minecraft/server/level/ServerEntity.java b/src/main/java/net/minecraft/server/level/ServerEntity.java
index 2d7e884d25f352e0a05e9aefb0ff6e296e73c361..8b64571c85e8e36d7ed48c42e4dc5957a874ea7c 100644
--- a/src/main/java/net/minecraft/server/level/ServerEntity.java
+++ b/src/main/java/net/minecraft/server/level/ServerEntity.java
@@ -390,7 +390,19 @@ public class ServerEntity {
SynchedEntityData datawatcher = this.entity.getEntityData();
if (datawatcher.isDirty()) {
- this.broadcastAndSend(new ClientboundSetEntityDataPacket(this.entity.getId(), datawatcher, false));
+ // Slice start
+ ClientboundSetEntityDataPacket dataPacket = new ClientboundSetEntityDataPacket(this.entity.getId(), datawatcher, false);
+ if (this.entity instanceof ServerPlayer serverPlayer) {
+ serverPlayer.connection.send(dataPacket);
+ }
+
+ //Get the packedData that the original packet has, and then determine if any of those are changed in
+ //the foreign version. If null, nothing to notify foreign trackers about.
+ List<SynchedEntityData.DataItem<?>> dirtyItems = datawatcher.packForeignDirty(dataPacket.getUnpackedData());
+ if (dirtyItems != null) {
+ this.broadcast(new ClientboundSetEntityDataPacket(this.entity.getId(), dirtyItems));
+ }
+ // Slice end
}
if (this.entity instanceof LivingEntity) {
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index 9b224ca33115aa7e7f100a45fe8bdb68ea7e4b59..f585b23c4f958184c4388c5c832dac1eaf7ae788 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -3029,7 +3029,7 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
this.entityData.markDirty(Entity.DATA_AIR_SUPPLY_ID);
return;
}
- this.entityData.set(Entity.DATA_AIR_SUPPLY_ID, event.getAmount());
+ this.entityData.set(Entity.DATA_AIR_SUPPLY_ID, event.getAmount(), getMaxAirSupply()); // Slice
// CraftBukkit end
}
diff --git a/src/main/java/net/minecraft/world/entity/player/Player.java b/src/main/java/net/minecraft/world/entity/player/Player.java
index 2483d7df7f1bf94344afd38b37602c645a4a2dff..5c16235115a9233bce1f5b30bb020d105bdca3d1 100644
--- a/src/main/java/net/minecraft/world/entity/player/Player.java
+++ b/src/main/java/net/minecraft/world/entity/player/Player.java
@@ -632,7 +632,7 @@ public abstract class Player extends LivingEntity {
public void increaseScore(int score) {
int j = this.getScore();
- this.entityData.set(Player.DATA_SCORE_ID, j + score);
+ this.entityData.set(Player.DATA_SCORE_ID, j + score, 0); // Slice
}
public void startAutoSpinAttack(int riptideTicks) {
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
index 170c7469ac6ed343a8e4e43f03a972d106bcc640..d36a27c06b9b33fe762fcec3afe2bdb90ba0ec2c 100644
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
@@ -2202,7 +2202,7 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
this.sendHealthUpdate();
}
}
- this.getHandle().getEntityData().set(net.minecraft.world.entity.LivingEntity.DATA_HEALTH_ID, (float) this.getScaledHealth());
+ this.getHandle().getEntityData().set(net.minecraft.world.entity.LivingEntity.DATA_HEALTH_ID, (float) this.getScaledHealth(), isDead() ? 0f : 20f); // Slice
this.getHandle().maxHealthCache = getMaxHealth();
}

View File

@@ -0,0 +1,44 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: jellysquid3 <jellysquid3@users.noreply.github.com>
Date: Wed, 15 Dec 2021 11:30:23 -0500
Subject: [PATCH] lithium: cached hashcode
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/level/block/Block.java b/src/main/java/net/minecraft/world/level/block/Block.java
index a80f4dc0a642c744223a155232291ace6e007636..f5f40589f53ac4696507699037df1ae4738e1637 100644
--- a/src/main/java/net/minecraft/world/level/block/Block.java
+++ b/src/main/java/net/minecraft/world/level/block/Block.java
@@ -597,11 +597,18 @@ public class Block extends BlockBehaviour implements ItemLike {
private final BlockState first;
private final BlockState second;
private final Direction direction;
+ private int hash; // JettPack
public BlockStatePairKey(BlockState self, BlockState other, Direction facing) {
this.first = self;
this.second = other;
this.direction = facing;
+ // JettPack start - lithium: cached_hashcode
+ int hash = this.first.hashCode();
+ hash = 31 * hash + this.second.hashCode();
+ hash = 31 * hash + this.direction.hashCode();
+ this.hash = hash;
+ // JettPack end
}
public boolean equals(Object object) {
@@ -617,11 +624,7 @@ public class Block extends BlockBehaviour implements ItemLike {
}
public int hashCode() {
- int i = this.first.hashCode();
-
- i = 31 * i + this.second.hashCode();
- i = 31 * i + this.direction.hashCode();
- return i;
+ return this.hash; // JettPack
}
}
}

View File

@@ -0,0 +1,22 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Gaider10 <>
Date: Mon, 30 Aug 2021 16:10:51 +0300
Subject: [PATCH] PaperPR Fix mobs spawning outside hard despawn range
diff --git a/src/main/java/net/minecraft/world/level/NaturalSpawner.java b/src/main/java/net/minecraft/world/level/NaturalSpawner.java
index 6e24b86ce315510133b6294f5d348e5c4e7f547f..dfc43fbd10ab9ccb84fb97e1db4d2bb107eee04f 100644
--- a/src/main/java/net/minecraft/world/level/NaturalSpawner.java
+++ b/src/main/java/net/minecraft/world/level/NaturalSpawner.java
@@ -386,7 +386,10 @@ public final class NaturalSpawner {
}
private static boolean isValidPositionForMob(ServerLevel world, Mob entity, double squaredDistance) {
- return squaredDistance > (double) (entity.getType().getCategory().getDespawnDistance() * entity.getType().getCategory().getDespawnDistance()) && entity.removeWhenFarAway(squaredDistance) ? false : entity.checkSpawnRules(world, MobSpawnType.NATURAL) && entity.checkSpawnObstruction(world);
+ // Paper start - fix mobs spawning outside hard despawn range
+ int despawnDistance = entity.isPersistenceRequired() || entity.requiresCustomPersistence() ? entity.getType().getCategory().getDespawnDistance() : world.paperConfig.hardDespawnDistances.getInt(entity.getType().getCategory());
+ return squaredDistance > (double) (despawnDistance * despawnDistance) && entity.removeWhenFarAway(squaredDistance) ? false : entity.checkSpawnRules((LevelAccessor) world, MobSpawnType.NATURAL) && entity.checkSpawnObstruction((LevelReader) world);
+ // Paper end - fix mobs spawning outside hard despawn range
}
private static Optional<MobSpawnSettings.SpawnerData> getRandomSpawnMobAt(ServerLevel world, StructureFeatureManager structureAccessor, ChunkGenerator chunkGenerator, MobCategory spawnGroup, Random random, BlockPos pos) {

View File

@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Gero <gecam59@gmail.com>
Date: Sat, 2 Oct 2021 20:08:30 +0200
Subject: [PATCH] PaperPR Fix CME in CraftPersistentDataTypeRegistry
diff --git a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java
index 355c9f79fd3132848a00eacde951d1e1bfa92737..6070f7d954e201e06efb6ef27ad0e7d9ff1ab9ff 100644
--- a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java
+++ b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java
@@ -92,7 +92,7 @@ public final class CraftPersistentDataTypeRegistry {
}
}
- private final Map<Class, TagAdapter> adapters = new HashMap<>();
+ private final Map<Class, TagAdapter> adapters = new java.util.concurrent.ConcurrentHashMap<>(); // Paper - Replace HashMap with ConcurrentHashMap to avoid CME
/**
* Creates a suitable adapter instance for the primitive class type

View File

@@ -0,0 +1,147 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: 2No2Name <2No2Name@web.de>
Date: Fri, 10 Sep 2021 16:35:53 -0400
Subject: [PATCH] lithium: ai task goat jump
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/entity/ai/behavior/LongJumpToRandomPos.java b/src/main/java/net/minecraft/world/entity/ai/behavior/LongJumpToRandomPos.java
index b25d245d0ad892e99663c3d741b2350fb1531d0e..3aafff1b77f137da897bc412edd7d0d57faa1458 100644
--- a/src/main/java/net/minecraft/world/entity/ai/behavior/LongJumpToRandomPos.java
+++ b/src/main/java/net/minecraft/world/entity/ai/behavior/LongJumpToRandomPos.java
@@ -25,6 +25,8 @@ import net.minecraft.world.level.pathfinder.Path;
import net.minecraft.world.level.pathfinder.WalkNodeEvaluator;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
+import it.unimi.dsi.fastutil.longs.LongArrayList; // JettPack
+import it.unimi.dsi.fastutil.shorts.ShortArrayList; // JettPack
public class LongJumpToRandomPos<E extends Mob> extends Behavior<E> {
private static final int FIND_JUMP_TRIES = 20;
@@ -41,12 +43,26 @@ public class LongJumpToRandomPos<E extends Mob> extends Behavior<E> {
private int findJumpTries;
private long prepareJumpStart;
private Function<E, SoundEvent> getJumpSound;
+ private final LongArrayList potentialTargets = new LongArrayList(); // JettPack
+ private final ShortArrayList potentialWeights = new ShortArrayList(); // JettPack
- public LongJumpToRandomPos(UniformInt cooldownRange, int verticalRange, int horizontalRange, float maxRange, Function<E, SoundEvent> entityToSound) {
+ // JettPack start
+ private static int findIndex(ShortArrayList weights, int weightedIndex) {
+ for (int i = 0; i < weights.size(); i++) {
+ weightedIndex -= weights.getShort(i);
+ if (weightedIndex < 0) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ // JettPack end
+
+ public LongJumpToRandomPos(UniformInt cooldownRange, int maxLongJumpHeight, int maxLongJumpWidth, float maxRange, Function<E, SoundEvent> entityToSound) {
super(ImmutableMap.of(MemoryModuleType.LOOK_TARGET, MemoryStatus.REGISTERED, MemoryModuleType.LONG_JUMP_COOLDOWN_TICKS, MemoryStatus.VALUE_ABSENT, MemoryModuleType.LONG_JUMP_MID_JUMP, MemoryStatus.VALUE_ABSENT), 200);
this.timeBetweenLongJumps = cooldownRange;
- this.maxLongJumpHeight = verticalRange;
- this.maxLongJumpWidth = horizontalRange;
+ this.maxLongJumpHeight = maxLongJumpHeight;
+ this.maxLongJumpWidth = maxLongJumpWidth;
this.maxJumpVelocity = maxRange;
this.getJumpSound = entityToSound;
}
@@ -66,30 +82,63 @@ public class LongJumpToRandomPos<E extends Mob> extends Behavior<E> {
return bl;
}
+ // JettPack start
+ /**
+ * @author 2No2Name
+ * @reason only evaluate 20+ instead of ~100 possible jumps without affecting behavior
+ * [VanillaCopy] the whole method, commented changes
+ */
@Override
protected void start(ServerLevel serverLevel, Mob mob, long l) {
+ this.potentialTargets.clear();
+ this.potentialWeights.clear();
+ int potentialTotalWeight = 0;
this.chosenJump = Optional.empty();
- this.findJumpTries = 20;
+ this.findJumpTries = FIND_JUMP_TRIES;
this.jumpCandidates.clear();
this.initialPosition = Optional.of(mob.position());
- BlockPos blockPos = mob.blockPosition();
- int i = blockPos.getX();
- int j = blockPos.getY();
- int k = blockPos.getZ();
- Iterable<BlockPos> iterable = BlockPos.betweenClosed(i - this.maxLongJumpWidth, j - this.maxLongJumpHeight, k - this.maxLongJumpWidth, i + this.maxLongJumpWidth, j + this.maxLongJumpHeight, k + this.maxLongJumpWidth);
- PathNavigation pathNavigation = mob.getNavigation();
-
- for(BlockPos blockPos2 : iterable) {
- double d = blockPos2.distSqr(blockPos);
- if ((i != blockPos2.getX() || k != blockPos2.getZ()) && pathNavigation.isStableDestination(blockPos2) && mob.getPathfindingMalus(WalkNodeEvaluator.getBlockPathTypeStatic(mob.level, blockPos2.mutable())) == 0.0F) {
- Optional<Vec3> optional = this.calculateOptimalJumpVector(mob, Vec3.atCenterOf(blockPos2));
- optional.ifPresent((vel) -> {
- this.jumpCandidates.add(new LongJumpToRandomPos.PossibleJump(new BlockPos(blockPos2), vel, Mth.ceil(d)));
- });
+ BlockPos goatPos = mob.blockPosition();
+ int goatX = goatPos.getX();
+ int goatY = goatPos.getY();
+ int goatZ = goatPos.getZ();
+ Iterable<BlockPos> iterable = BlockPos.betweenClosed(goatX - this.maxLongJumpWidth, goatY - this.maxLongJumpHeight, goatZ - this.maxLongJumpWidth, goatX + this.maxLongJumpWidth, goatY + this.maxLongJumpHeight, goatZ + this.maxLongJumpWidth);
+ PathNavigation entityNavigation = mob.getNavigation();
+
+ BlockPos.MutableBlockPos targetPosCopy = new BlockPos.MutableBlockPos();
+ for (BlockPos targetPos : iterable) {
+ if (goatX == targetPos.getX() && goatZ == targetPos.getZ()) {
+ continue;
}
- }
+ double squaredDistance = targetPos.distSqr(goatPos);
+ //Optimization: Evaluate the flight path check later (after random selection, but before world can be modified)
+ if (entityNavigation.isStableDestination(targetPos) && mob.getPathfindingMalus(WalkNodeEvaluator.getBlockPathTypeStatic(mob.level, targetPosCopy.set(targetPos))) == 0.0F) {
+ this.potentialTargets.add(targetPos.asLong());
+ int weight = Mth.ceil(squaredDistance);
+ this.potentialWeights.add((short) weight);
+ potentialTotalWeight += weight;
+ }
+ }
+ // Optimization: Do the random picking of positions before doing the expensive the jump flight path validity check.
+ // up to FIND_JUMP_TRIES random jumpCandidates can be selected in keepRunning, so only this number of jumpCandidates needs to be generated
+ while (this.jumpCandidates.size() < FIND_JUMP_TRIES) {
+ // the number of random calls will be different from vanilla, but this is not reasonably detectable (not affecting world generation)
+ if (potentialTotalWeight == 0) {
+ return; // collection is empty/fully consumed, no more possible jumpCandidates available
+ }
+ int chosenIndex = findIndex(this.potentialWeights, serverLevel.random.nextInt(potentialTotalWeight));
+ long chosenPos = this.potentialTargets.getLong(chosenIndex);
+ short chosenWeight = this.potentialWeights.set(chosenIndex, (short) 0);
+ potentialTotalWeight -= chosenWeight;
+ // Very expensive method call, it shifts bounding boxes around and checks for collisions with them
+ Optional<Vec3> optional = this.calculateOptimalJumpVector(mob, Vec3.atCenterOf(targetPosCopy.set(chosenPos)));
+ if (optional.isPresent()) {
+ //the weight in Target should be unused, as the random selection already took place
+ this.jumpCandidates.add(new LongJumpToRandomPos.PossibleJump(new BlockPos(targetPosCopy), optional.get(), chosenWeight));
+ }
+ }
}
+ // JettPack end
@Override
protected void tick(ServerLevel serverLevel, E mob, long l) {
@@ -106,7 +155,14 @@ public class LongJumpToRandomPos<E extends Mob> extends Behavior<E> {
}
} else {
--this.findJumpTries;
- Optional<LongJumpToRandomPos.PossibleJump> optional = WeightedRandom.getRandomItem(serverLevel.random, this.jumpCandidates);
+ // JettPack start
+ Optional<LongJumpToRandomPos.PossibleJump> optional;
+ if (this.jumpCandidates.isEmpty()) {
+ optional = Optional.empty();
+ } else {
+ optional = Optional.of(this.jumpCandidates.get(0));
+ }
+ // JettPack end
if (optional.isPresent()) {
this.jumpCandidates.remove(optional.get());
mob.getBrain().setMemory(MemoryModuleType.LOOK_TARGET, new BlockPosTracker(optional.get().getJumpTarget()));

View File

@@ -0,0 +1,40 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: 2No2Name <2No2Name@web.de>
Date: Tue, 21 Dec 2021 09:43:24 -0500
Subject: [PATCH] lithium: store gamerules in fastutil hashmap
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/level/GameRules.java b/src/main/java/net/minecraft/world/level/GameRules.java
index fb2626d2a6babe531dd1849333b119ab36200d80..e22de06aab82896a7c245763e7f3563d3d0912a9 100644
--- a/src/main/java/net/minecraft/world/level/GameRules.java
+++ b/src/main/java/net/minecraft/world/level/GameRules.java
@@ -27,6 +27,7 @@ import net.minecraft.network.protocol.game.ClientboundGameEventPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import org.slf4j.Logger;
+import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; // JettPack
public class GameRules {
@@ -110,14 +111,16 @@ public class GameRules {
public GameRules() {
// Pufferfish start - use this to ensure gameruleArray is initialized
- this((Map) GameRules.GAME_RULE_TYPES.entrySet().stream().collect(ImmutableMap.toImmutableMap(Entry::getKey, (entry) -> {
+ // JettPack start - lithium: store gamerules in fastutil hashmap
+ this(new Object2ObjectOpenHashMap<>((Map) GameRules.GAME_RULE_TYPES.entrySet().stream().collect(ImmutableMap.toImmutableMap(Entry::getKey, (entry) -> {
return ((GameRules.Type) entry.getValue()).createRule();
- })));
+ }))));
+ // JettPack end
// Pufferfish end
}
private GameRules(Map<GameRules.Key<?>, GameRules.Value<?>> rules) {
- this.rules = rules;
+ this.rules = new Object2ObjectOpenHashMap<>(rules); // JettPack - lithium: store gamerules in fastutil hashmap
// Pufferfish start
int arraySize = rules.keySet().stream().mapToInt(key -> key.gameRuleIndex).max().orElse(-1) + 1;

View File

@@ -0,0 +1,119 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: etil2jz <blanchot.arthur@protonmail.ch>
Date: Fri, 22 Apr 2022 22:44:56 +0200
Subject: [PATCH] carpetfixes: BiomeAccess prediction
Author: fxmorin <fx.e.morin@gmail.com>
Original license: MIT
Original project: https://github.com/fxmorin/carpet-fixes (Yarn mappings)
Copyright (c) 2020 Fx Morin
diff --git a/src/main/java/net/minecraft/world/level/biome/BiomeManager.java b/src/main/java/net/minecraft/world/level/biome/BiomeManager.java
index dd3f4c2c564be1e9886b5c3ddd9ca1dfd749c028..57b467bcf1561f6b3b42c5e088f71460704804f7 100644
--- a/src/main/java/net/minecraft/world/level/biome/BiomeManager.java
+++ b/src/main/java/net/minecraft/world/level/biome/BiomeManager.java
@@ -28,41 +28,72 @@ public class BiomeManager {
return new BiomeManager(storage, this.biomeZoomSeed);
}
+ // Mirai start - carpetfixes: BiomeAccess prediction
+ private static final double maxOffset = 0.4500000001D; // Mirai - carpetfixes: BiomeAccess prediction
public Holder<Biome> getBiome(BlockPos pos) {
- int i = pos.getX() - 2;
- int j = pos.getY() - 2;
- int k = pos.getZ() - 2;
- int l = i >> 2;
- int m = j >> 2;
- int n = k >> 2;
- double d = (double)(i & 3) / 4.0D;
- double e = (double)(j & 3) / 4.0D;
- double f = (double)(k & 3) / 4.0D;
- int o = 0;
- double g = Double.POSITIVE_INFINITY;
-
- for(int p = 0; p < 8; ++p) {
- boolean bl = (p & 4) == 0;
- boolean bl2 = (p & 2) == 0;
- boolean bl3 = (p & 1) == 0;
- int q = bl ? l : l + 1;
- int r = bl2 ? m : m + 1;
- int s = bl3 ? n : n + 1;
- double h = bl ? d : d - 1.0D;
- double t = bl2 ? e : e - 1.0D;
- double u = bl3 ? f : f - 1.0D;
- double v = getFiddledDistance(this.biomeZoomSeed, q, r, s, h, t, u);
- if (g > v) {
- o = p;
- g = v;
+ int xMinus2 = pos.getX() - 2;
+ int yMinus2 = pos.getY() - 2;
+ int zMinus2 = pos.getZ() - 2;
+ int x = xMinus2 >> 2; // BlockPos to BiomePos
+ int y = yMinus2 >> 2;
+ int z = zMinus2 >> 2;
+ double quartX = (double) (xMinus2 & 3) / 4.0D; // quartLocal divided by 4
+ double quartY = (double) (yMinus2 & 3) / 4.0D; // 0/4, 1/4, 2/4, 3/4
+ double quartZ = (double) (zMinus2 & 3) / 4.0D; // [0, 0.25, 0.5, 0.75]
+ int smallestX = 0;
+ double smallestDist = Double.POSITIVE_INFINITY;
+ for (int biomeX = 0; biomeX < 8; ++biomeX) {
+ boolean everyOtherQuad = (biomeX & 4) == 0; // 1 1 1 1 0 0 0 0
+ boolean everyOtherPair = (biomeX & 2) == 0; // 1 1 0 0 1 1 0 0
+ boolean everyOther = (biomeX & 1) == 0; // 1 0 1 0 1 0 1 0
+ double quartXX = everyOtherQuad ? quartX : quartX - 1.0D; //[-1.0,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75]
+ double quartYY = everyOtherPair ? quartY : quartY - 1.0D;
+ double quartZZ = everyOther ? quartZ : quartZ - 1.0D;
+
+ //This code block is new
+ double maxQuartYY = 0.0D, maxQuartZZ = 0.0D;
+ if (biomeX != 0) {
+ maxQuartYY = Mth.square(Math.max(quartYY + maxOffset, Math.abs(quartYY - maxOffset)));
+ maxQuartZZ = Mth.square(Math.max(quartZZ + maxOffset, Math.abs(quartZZ - maxOffset)));
+ double maxQuartXX = Mth.square(Math.max(quartXX + maxOffset,Math.abs(quartXX - maxOffset)));
+ if (smallestDist < maxQuartXX + maxQuartYY + maxQuartZZ) continue;
+ }
+
+ int xx = everyOtherQuad ? x : x + 1;
+ int yy = everyOtherPair ? y : y + 1;
+ int zz = everyOther ? z : z + 1;
+
+ //I transferred the code from method_38106 to here, so I could call continue halfway through
+ long seed = LinearCongruentialGenerator.next(this.biomeZoomSeed, xx);
+ seed = LinearCongruentialGenerator.next(seed, yy);
+ seed = LinearCongruentialGenerator.next(seed, zz);
+ seed = LinearCongruentialGenerator.next(seed, xx);
+ seed = LinearCongruentialGenerator.next(seed, yy);
+ seed = LinearCongruentialGenerator.next(seed, zz);
+ double offsetX = getFiddle(seed);
+ double sqrX = Mth.square(quartXX + offsetX);
+ if (biomeX != 0 && smallestDist < sqrX + maxQuartYY + maxQuartZZ) continue; //skip the rest of the loop
+ seed = LinearCongruentialGenerator.next(seed, this.biomeZoomSeed);
+ double offsetY = getFiddle(seed);
+ double sqrY = Mth.square(quartYY + offsetY);
+ if (biomeX != 0 && smallestDist < sqrX + sqrY + maxQuartZZ) continue; // skip the rest of the loop
+ seed = LinearCongruentialGenerator.next(seed, this.biomeZoomSeed);
+ double offsetZ = getFiddle(seed);
+ double biomeDist = sqrX + sqrY + Mth.square(quartZZ + offsetZ);
+
+ if (smallestDist > biomeDist) {
+ smallestX = biomeX;
+ smallestDist = biomeDist;
}
}
- int w = (o & 4) == 0 ? l : l + 1;
- int x = (o & 2) == 0 ? m : m + 1;
- int y = (o & 1) == 0 ? n : n + 1;
- return this.noiseBiomeSource.getNoiseBiome(w, x, y);
+ return(this.noiseBiomeSource.getNoiseBiome(
+ (smallestX & 4) == 0 ? x : x + 1,
+ (smallestX & 2) == 0 ? y : y + 1,
+ (smallestX & 1) == 0 ? z : z + 1
+ ));
}
+ // Mirai end
public Holder<Biome> getNoiseBiomeAtPosition(double x, double y, double z) {
int i = QuartPos.fromBlock(Mth.floor(x));

View File

@@ -0,0 +1,29 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Etil <81570777+etil2jz@users.noreply.github.com>
Date: Sat, 8 Jan 2022 22:00:46 +0100
Subject: [PATCH] Skip enchanting table book tick
diff --git a/src/main/java/net/minecraft/world/level/block/entity/EnchantmentTableBlockEntity.java b/src/main/java/net/minecraft/world/level/block/entity/EnchantmentTableBlockEntity.java
index f177c88d2a122a34b5c601fb8c0d15fb16925f6b..b3eef862248574ee4b864107e1eb69d2418ada8c 100644
--- a/src/main/java/net/minecraft/world/level/block/entity/EnchantmentTableBlockEntity.java
+++ b/src/main/java/net/minecraft/world/level/block/entity/EnchantmentTableBlockEntity.java
@@ -49,6 +49,9 @@ public class EnchantmentTableBlockEntity extends BlockEntity implements Nameable
}
public static void bookAnimationTick(Level world, BlockPos pos, BlockState state, EnchantmentTableBlockEntity blockEntity) {
+ // Mirai start
+ return;
+ /*
blockEntity.oOpen = blockEntity.open;
blockEntity.oRot = blockEntity.rot;
Player player = world.getNearestPlayer((double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 3.0D, false);
@@ -102,6 +105,8 @@ public class EnchantmentTableBlockEntity extends BlockEntity implements Nameable
h = Mth.clamp(h, -0.2F, 0.2F);
blockEntity.flipA += (h - blockEntity.flipA) * 0.9F;
blockEntity.flip += blockEntity.flipA;
+ */
+ // Mirai end
}
@Override

View File

@@ -0,0 +1,19 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: etil2jz <blanchot.arthur@protonmail.ch>
Date: Fri, 4 Mar 2022 19:57:07 +0100
Subject: [PATCH] Skip cloning loot parameters
diff --git a/src/main/java/net/minecraft/advancements/Advancement.java b/src/main/java/net/minecraft/advancements/Advancement.java
index c534055f90b98942b9d7d152fd502cf5387c995b..9e46acf66df7a41eb80d7e41871c3b3caa66f55e 100644
--- a/src/main/java/net/minecraft/advancements/Advancement.java
+++ b/src/main/java/net/minecraft/advancements/Advancement.java
@@ -46,7 +46,7 @@ public class Advancement {
public Advancement(ResourceLocation id, @Nullable Advancement parent, @Nullable DisplayInfo display, AdvancementRewards rewards, Map<String, Criterion> criteria, String[][] requirements) {
this.id = id;
this.display = display;
- this.criteria = ImmutableMap.copyOf(criteria);
+ this.criteria = java.util.Collections.unmodifiableMap(criteria); // Mirai - Skip cloning loot parameters
this.parent = parent;
this.rewards = rewards;
this.requirements = requirements;

View File

@@ -0,0 +1,77 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: jellysquid3 <jellysquid3@users.noreply.github.com>
Date: Sat, 1 Jan 2022 03:59:58 -0500
Subject: [PATCH] lithium: precompute shape arrays
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/core/Direction.java b/src/main/java/net/minecraft/core/Direction.java
index 92789a27aa2978ac323d4cdafa82391998cf0ffa..842b67327523c512f95ad64ad23d3ee4102175ea 100644
--- a/src/main/java/net/minecraft/core/Direction.java
+++ b/src/main/java/net/minecraft/core/Direction.java
@@ -41,7 +41,7 @@ public enum Direction implements StringRepresentable {
private final Direction.Axis axis;
private final Direction.AxisDirection axisDirection;
private final Vec3i normal;
- private static final Direction[] VALUES = values();
+ public static final Direction[] VALUES = values(); // JettPack
private static final Map<String, Direction> BY_NAME = Arrays.stream(VALUES).collect(Collectors.toMap(Direction::getName, (direction) -> {
return direction;
}));
diff --git a/src/main/java/net/minecraft/world/phys/shapes/CubePointRange.java b/src/main/java/net/minecraft/world/phys/shapes/CubePointRange.java
index def6c6a91aa229c83adb89a3fd0eb8bfb80e8182..dc700c70b0f8a3f42716060fbb81b3c75e3647ee 100644
--- a/src/main/java/net/minecraft/world/phys/shapes/CubePointRange.java
+++ b/src/main/java/net/minecraft/world/phys/shapes/CubePointRange.java
@@ -4,6 +4,7 @@ import it.unimi.dsi.fastutil.doubles.AbstractDoubleList;
public class CubePointRange extends AbstractDoubleList {
private final int parts;
+ private double scale; // JettPack - lithium: shapes.precompute_shape_arrays
CubePointRange(int sectionCount) {
if (sectionCount <= 0) {
@@ -11,10 +12,11 @@ public class CubePointRange extends AbstractDoubleList {
} else {
this.parts = sectionCount;
}
+ this.scale = 1.0D / sectionCount; // JettPack - lithium: shapes.precompute_shape_arrays
}
public double getDouble(int i) {
- return (double)i / (double)this.parts;
+ return i * this.scale; // JettPack - lithium: shapes.precompute_shape_arrays
}
public int size() {
diff --git a/src/main/java/net/minecraft/world/phys/shapes/CubeVoxelShape.java b/src/main/java/net/minecraft/world/phys/shapes/CubeVoxelShape.java
index 374da999d4fb544a5571ca888dd4cc60680d0ee0..ba4355ed2b5380ceab95d19908ec6b8fe7d2f12a 100644
--- a/src/main/java/net/minecraft/world/phys/shapes/CubeVoxelShape.java
+++ b/src/main/java/net/minecraft/world/phys/shapes/CubeVoxelShape.java
@@ -3,15 +3,25 @@ package net.minecraft.world.phys.shapes;
import it.unimi.dsi.fastutil.doubles.DoubleList;
import net.minecraft.core.Direction;
import net.minecraft.util.Mth;
+import net.minecraft.world.phys.shapes.CubePointRange; // JettPack
public final class CubeVoxelShape extends VoxelShape {
+ private DoubleList[] list; // JettPack - lithium: shapes.precompute_shape_arrays
+
protected CubeVoxelShape(DiscreteVoxelShape voxels) {
super(voxels);
+ // JettPack start - lithium: shapes.precompute_shape_arrays
+ this.list = new DoubleList[Direction.VALUES.length];
+
+ for (Direction.Axis axis : Direction.Axis.VALUES) {
+ this.list[axis.ordinal()] = new CubePointRange(voxels.getSize(axis));
+ }
+ // JettPack end
}
@Override
protected DoubleList getCoords(Direction.Axis axis) {
- return new CubePointRange(this.shape.getSize(axis));
+ return this.list[axis.ordinal()]; // JettPack - lithium: shapes.precompute_shape_arrays
}
@Override

View File

@@ -0,0 +1,87 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: ishland <ishlandmc@yeah.net>
Date: Sun, 21 Nov 2021 03:01:00 +0100
Subject: [PATCH] vmp: ingredient_matching
Copyright (c) 2021-2022 ishland
Original code by RelativityMC, licensed under MIT
You can find the original code on https://github.com/RelativityMC/VMP-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/item/crafting/Ingredient.java b/src/main/java/net/minecraft/world/item/crafting/Ingredient.java
index 895c0f1600139e340aa22a7c398978add56fa706..bbf7d112b8020567f2c1d02ce0b2c1a22b2279d1 100644
--- a/src/main/java/net/minecraft/world/item/crafting/Ingredient.java
+++ b/src/main/java/net/minecraft/world/item/crafting/Ingredient.java
@@ -12,9 +12,12 @@ import it.unimi.dsi.fastutil.ints.IntList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
+import java.util.HashSet; // Mirai
import java.util.Iterator;
import java.util.List;
+import java.util.Set; // Mirai
import java.util.function.Predicate;
+import java.util.stream.Collectors; // Mirai
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
@@ -38,6 +41,8 @@ public final class Ingredient implements Predicate<ItemStack> {
@Nullable
private IntList stackingIds;
public boolean exact; // CraftBukkit
+ private Set<Item> matchingItems = null; // Mirai
+ private boolean isEmptyMatch = false; // Mirai
public Ingredient(Stream<? extends Ingredient.Value> entries) {
this.values = (Ingredient.Value[]) entries.toArray((i) -> {
@@ -65,32 +70,25 @@ public final class Ingredient implements Predicate<ItemStack> {
if (itemstack == null) {
return false;
} else {
- this.dissolve();
- if (this.itemStacks.length == 0) {
- return itemstack.isEmpty();
- } else {
- ItemStack[] aitemstack = this.itemStacks;
- int i = aitemstack.length;
-
- for (int j = 0; j < i; ++j) {
- ItemStack itemstack1 = aitemstack[j];
-
- // CraftBukkit start
- if (this.exact) {
- if (itemstack1.getItem() == itemstack.getItem() && ItemStack.tagMatches(itemstack, itemstack1)) {
- return true;
- }
-
- continue;
- }
- // CraftBukkit end
- if (itemstack1.is(itemstack.getItem())) {
- return true;
- }
- }
-
- return false;
+ // Mirai start
+ /**
+ * @author ishland
+ * @reason optimize test()
+ */
+ Set<Item> matchingItems = this.matchingItems;
+ boolean isEmptyMatch = this.isEmptyMatch;
+ if (matchingItems == null) {
+ matchingItems = this.matchingItems = Arrays.stream(this.values)
+ .flatMap(entry -> entry.getItems().stream())
+ .filter(itemstack1 -> !itemstack1.isEmpty())
+ .map(ItemStack::getItem)
+ .collect(Collectors.toCollection(HashSet::new));
+ isEmptyMatch = this.isEmptyMatch = this.matchingItems.isEmpty();
+ }
+ if (itemstack.isEmpty()) {
+ return isEmptyMatch;
}
+ return matchingItems.contains(itemstack.getItem());
}
}

View File

@@ -0,0 +1,23 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Etil <81570777+etil2jz@users.noreply.github.com>
Date: Sun, 2 Jan 2022 20:37:30 +0100
Subject: [PATCH] Fix MC-121706
diff --git a/src/main/java/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java b/src/main/java/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java
index 048effbc4d25669801b467be61ee4b88dd4ea9b7..5b93358a24dab1dbe66f0a74c22f1977e3c60e50 100644
--- a/src/main/java/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java
+++ b/src/main/java/net/minecraft/world/entity/ai/goal/RangedBowAttackGoal.java
@@ -111,10 +111,10 @@ public class RangedBowAttackGoal<T extends Monster & RangedAttackMob> extends Go
this.mob.getMoveControl().strafe(this.strafingBackwards ? -0.5F : 0.5F, this.strafingClockwise ? 0.5F : -0.5F);
this.mob.lookAt(livingEntity, 30.0F, 30.0F);
- } else {
- this.mob.getLookControl().setLookAt(livingEntity, 30.0F, 30.0F);
}
+ this.mob.getLookControl().setLookAt(livingEntity, 30.0F, 30.0F); // Mirai - fix MC-121706
+
if (this.mob.isUsingItem()) {
if (!bl && this.seeTime < -60) {
this.mob.stopUsingItem();

View File

@@ -0,0 +1,112 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: ishland <ishlandmc@yeah.net>
Date: Sat, 1 Jan 2022 11:05:22 +0100
Subject: [PATCH] vmp: entity.iteration
Copyright (c) 2021-2022 ishland
Original code by RelativityMC, licensed under MIT
You can find the original code on https://github.com/RelativityMC/VMP-fabric (Yarn mappings)
diff --git a/src/main/java/com/ishland/vmp/common/general/collections/ITypeFilterableList.java b/src/main/java/com/ishland/vmp/common/general/collections/ITypeFilterableList.java
new file mode 100644
index 0000000000000000000000000000000000000000..beaa0a60771b17b93e4074b272b503a2f6e4cf34
--- /dev/null
+++ b/src/main/java/com/ishland/vmp/common/general/collections/ITypeFilterableList.java
@@ -0,0 +1,8 @@
+package com.ishland.vmp.common.general.collections;
+
+public interface ITypeFilterableList {
+
+ Object[] getBackingArray();
+
+
+}
\ No newline at end of file
diff --git a/src/main/java/net/minecraft/world/level/entity/EntitySection.java b/src/main/java/net/minecraft/world/level/entity/EntitySection.java
index 578e07407951688e7e8489919a4a3733028fc568..9b39920baea28fe85a0bb6ada0e00a466b3ddf31 100644
--- a/src/main/java/net/minecraft/world/level/entity/EntitySection.java
+++ b/src/main/java/net/minecraft/world/level/entity/EntitySection.java
@@ -8,6 +8,10 @@ import net.minecraft.util.ClassInstanceMultiMap;
import net.minecraft.util.VisibleForDebug;
import net.minecraft.world.phys.AABB;
import org.slf4j.Logger;
+import com.ishland.vmp.common.general.collections.ITypeFilterableList; // Mirai
+import it.unimi.dsi.fastutil.objects.ObjectArrayList; // Mirai
+import net.minecraft.world.level.entity.EntityAccess; // Mirai
+import net.minecraft.world.level.entity.EntityTypeTest; // Mirai
public class EntitySection<T extends EntityAccess> {
private static final Logger LOGGER = LogUtils.getLogger();
@@ -45,27 +49,62 @@ public class EntitySection<T extends EntityAccess> {
return this.storage.remove(entity);
}
+ // Mirai start
+ /**
+ * @author ishland
+ * @reason use array for iteration & inline math
+ */
public void getEntities(AABB box, Consumer<T> action) {
- for(T entityAccess : this.storage) {
- if (entityAccess.getBoundingBox().intersects(box)) {
- action.accept(entityAccess);
+ if (this.storage instanceof ITypeFilterableList iTypeFilterableList) { // use array for iteration
+ for (Object _entityLike : iTypeFilterableList.getBackingArray()) {
+ if (_entityLike != null) {
+ @SuppressWarnings("unchecked") T entityAccess = (T) _entityLike;
+ AABB box1 = entityAccess.getBoundingBox();
+ if (box1.minX < box.maxX && box1.maxX > box.minX && box1.minY < box.maxY && box1.maxY > box.minY && box1.minZ < box.maxZ && box1.maxZ > box.minZ) { // inline math
+ action.accept(entityAccess);
+ }
+ }
+ }
+ } else { // fallback
+ for (T entityAccess : this.storage) {
+ AABB box1 = entityAccess.getBoundingBox();
+ if (box1.minX < box.maxX && box1.maxX > box.minX && box1.minY < box.maxY && box1.maxY > box.minY && box1.minZ < box.maxZ && box1.maxZ > box.minZ) { // inline math
+ action.accept(entityAccess);
+ }
}
}
-
}
+ /**
+ * @author ishland
+ * @reason use array for iteration & inline math
+ */
public <U extends T> void getEntities(EntityTypeTest<T, U> type, AABB box, Consumer<? super U> action) {
Collection<? extends T> collection = this.storage.find(type.getBaseClass());
if (!collection.isEmpty()) {
- for(T entityAccess : collection) {
- U entityAccess2 = (U)((EntityAccess)type.tryCast(entityAccess));
- if (entityAccess2 != null && entityAccess.getBoundingBox().intersects(box)) {
- action.accept(entityAccess2); // Paper - decompile fix
+ if (collection instanceof ObjectArrayList objectArrayList) { // use array for iteration
+ for (Object _entityLike : objectArrayList.elements()) {
+ if (_entityLike != null) {
+ T entityAccess = (T) _entityLike;
+ U entityAccess2 = type.tryCast(entityAccess);
+ final AABB boundingBox = entityAccess.getBoundingBox();
+ if (entityAccess2 != null && boundingBox.minX < box.maxX && boundingBox.maxX > box.minX && boundingBox.minY < box.maxY && boundingBox.maxY > box.minY && boundingBox.minZ < box.maxZ && boundingBox.maxZ > box.minZ) { // inline math
+ action.accept(entityAccess2);
+ }
+ }
+ }
+ } else { // fallback
+ for(T entityAccess : collection) {
+ U entityAccess2 = type.tryCast(entityAccess);
+ AABB box1 = entityAccess.getBoundingBox();
+ if (entityAccess2 != null && box1.minX < box.maxX && box1.maxX > box.minX && box1.minY < box.maxY && box1.maxY > box.minY && box1.minZ < box.maxZ && box1.maxZ > box.minZ) { // inline math
+ action.accept(entityAccess2);
+ }
}
}
-
}
}
+ // Mirai end
public boolean isEmpty() {
return this.storage.isEmpty();

View File

@@ -0,0 +1,45 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: ishland <ishlandmc@yeah.net>
Date: Sat, 4 Dec 2021 12:09:59 +0100
Subject: [PATCH] vmp: spawn_density_cap
Copyright (c) 2021-2022 ishland
Original code by RelativityMC, licensed under MIT
You can find the original code on https://github.com/RelativityMC/VMP-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/level/LocalMobCapCalculator.java b/src/main/java/net/minecraft/world/level/LocalMobCapCalculator.java
index 05a5cd35dc96a7789c89a171526fe96c89b42f52..d9fa1389ae2591a6d7865bb0782e46ed8b36276a 100644
--- a/src/main/java/net/minecraft/world/level/LocalMobCapCalculator.java
+++ b/src/main/java/net/minecraft/world/level/LocalMobCapCalculator.java
@@ -47,16 +47,25 @@ public class LocalMobCapCalculator {
}
static class MobCounts {
- private final Object2IntMap<MobCategory> counts = new Object2IntOpenHashMap<>(MobCategory.values().length);
+ // private final Object2IntMap<MobCategory> counts = new Object2IntOpenHashMap<>(MobCategory.values().length); // Mirai
+ private final int[] spawnGroupDensities = new int[MobCategory.values().length]; // Mirai
+ // Mirai start
+ /**
+ * @author ishland
+ * @reason opt: replace with array access
+ */
public void add(MobCategory spawnGroup) {
- this.counts.computeInt(spawnGroup, (group, density) -> {
- return density == null ? 1 : density + 1;
- });
+ this.spawnGroupDensities[spawnGroup.ordinal()] ++;
}
+ /**
+ * @author ishland
+ * @reason opt: replace with array access
+ */
public boolean canSpawn(MobCategory spawnGroup) {
- return this.counts.getOrDefault(spawnGroup, 0) < spawnGroup.getMaxInstancesPerChunk();
+ return this.spawnGroupDensities[spawnGroup.ordinal()] < spawnGroup.getMaxInstancesPerChunk();
}
+ // Mirai end
}
}

View File

@@ -0,0 +1,34 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Etil <81570777+etil2jz@users.noreply.github.com>
Date: Mon, 3 Jan 2022 16:03:27 +0100
Subject: [PATCH] Configurable server metrics
diff --git a/src/main/java/com/destroystokyo/paper/PaperConfig.java b/src/main/java/com/destroystokyo/paper/PaperConfig.java
index 7a7d0566611aafafba30b7b25c2f1f3e78b054fa..7333e60f404f6f85a2bcb1f8f031a180314abd32 100644
--- a/src/main/java/com/destroystokyo/paper/PaperConfig.java
+++ b/src/main/java/com/destroystokyo/paper/PaperConfig.java
@@ -123,7 +123,7 @@ public class PaperConfig {
MinecraftServer.getServer().server.getCommandMap().register(entry.getKey(), "Paper", entry.getValue());
}
- if (!metricsStarted) {
+ if (!metricsStarted && wtf.etil.mirai.MiraiConfig.serverMetrics) { // Mirai - configurable server metrics
Metrics.PaperMetrics.startMetrics();
metricsStarted = true;
}
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index a1d88b8cadf6c193deb69bb577936ebd69e63b2a..21c4a287c8fc550be36fc5b60bdc458d71a9d25d 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -230,4 +230,9 @@ public class MiraiConfig {
entitiesCanUsePortals = getBoolean("entities-can-use-portals", entitiesCanUsePortals);
}
+ public static boolean serverMetrics = true;
+ private static void allowServerMetrics() {
+ serverMetrics = getBoolean("enable-server-metrics", serverMetrics);
+ }
+
}
\ No newline at end of file

View File

@@ -0,0 +1,374 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: FX - PR0CESS <fx.e.morin@gmail.com>
Date: Wed, 22 Dec 2021 18:39:21 +0100
Subject: [PATCH] Configurable FastMath.round
Original code by fxmorin, licensed under MIT
You can find the original code on https://github.com/fxmorin/carpet-fixes
diff --git a/src/main/java/carpetfixes/helpers/FastMath.java b/src/main/java/carpetfixes/helpers/FastMath.java
new file mode 100644
index 0000000000000000000000000000000000000000..da81a142d2b072f846f9905a0d5b8e293763284a
--- /dev/null
+++ b/src/main/java/carpetfixes/helpers/FastMath.java
@@ -0,0 +1,28 @@
+package carpetfixes.helpers;
+
+public class FastMath {
+
+ /**
+ * @author FX - PR0CESS
+ * ~1.25x faster than {@link Math#round(float)}
+ */
+ public static int round(float a) {
+ if (wtf.etil.mirai.MiraiConfig.riskyMathRoundOpt) {
+ return a > 0F ? (int)(a + .5F) : (int)(a - .5F);
+ } else {
+ return Math.round(a);
+ }
+ }
+
+ /**
+ * @author FX - PR0CESS
+ * ~1.28x faster than {@link Math#round(double)}
+ */
+ public static long round(double a) {
+ if (wtf.etil.mirai.MiraiConfig.riskyMathRoundOpt) {
+ return a > 0D ? (long)(a + .5D) : (long)(a - .5D);
+ } else {
+ return Math.round(a);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/destroystokyo/paper/PaperCommand.java b/src/main/java/com/destroystokyo/paper/PaperCommand.java
index e85175910454fc08704ea01e4b852136a6c6c60f..4ac91d601dd7e37b3455360b3b41b73cd66624df 100644
--- a/src/main/java/com/destroystokyo/paper/PaperCommand.java
+++ b/src/main/java/com/destroystokyo/paper/PaperCommand.java
@@ -725,12 +725,12 @@ public class PaperCommand extends Command {
++relitChunks[0];
sender.getBukkitEntity().sendMessage(
ChatColor.BLUE + "Relit chunk " + ChatColor.DARK_AQUA + chunkPos + ChatColor.BLUE +
- ", progress: " + ChatColor.DARK_AQUA + (int)(Math.round(100.0 * (double)(relitChunks[0])/(double)pending[0])) + "%"
+ ", progress: " + ChatColor.DARK_AQUA + (int)(carpetfixes.helpers.FastMath.round(100.0 * (double)(relitChunks[0])/(double)pending[0])) + "%"
);
},
(int totalRelit) -> {
final long end = System.nanoTime();
- final long diff = Math.round(1.0e-6*(end - start));
+ final long diff = carpetfixes.helpers.FastMath.round(1.0e-6*(end - start));
sender.getBukkitEntity().sendMessage(
ChatColor.BLUE + "Relit " + ChatColor.DARK_AQUA + totalRelit + ChatColor.BLUE + " chunks. Took " +
ChatColor.DARK_AQUA + diff + "ms"
diff --git a/src/main/java/com/destroystokyo/paper/gui/RAMDetails.java b/src/main/java/com/destroystokyo/paper/gui/RAMDetails.java
index f9251183df72ddc56662fd3f02acf21641a2200c..ea1bad145e529ac36bf335cf4d5339b2d88b282f 100644
--- a/src/main/java/com/destroystokyo/paper/gui/RAMDetails.java
+++ b/src/main/java/com/destroystokyo/paper/gui/RAMDetails.java
@@ -81,6 +81,6 @@ public class RAMDetails extends JList<String> {
}
private static String format(double tps) {
- return ( ( tps > 21.0 ) ? "*" : "" ) + Math.min( Math.round( tps * 100.0 ) / 100.0, 20.0 );
+ return ( ( tps > 21.0 ) ? "*" : "" ) + Math.min( carpetfixes.helpers.FastMath.round( tps * 100.0 ) / 100.0, 20.0 );
}
}
diff --git a/src/main/java/com/destroystokyo/paper/gui/RAMGraph.java b/src/main/java/com/destroystokyo/paper/gui/RAMGraph.java
index c3e54da4ab6440811aab2f9dd1e218802ac13285..2a38ea32f2d4a01be556fdf11254d5910c54f997 100644
--- a/src/main/java/com/destroystokyo/paper/gui/RAMGraph.java
+++ b/src/main/java/com/destroystokyo/paper/gui/RAMGraph.java
@@ -128,7 +128,7 @@ public class RAMGraph extends JComponent {
graphics.setColor(data.getLineColor());
graphics.fillOval(m.x - 2, 100 - used - 2, 5, 5);
setToolTipText(String.format("<html><body>Used: %s mb (%s%%)<br/>%s</body></html>",
- Math.round(data.getUsedMem() / 1024F / 1024F),
+ carpetfixes.helpers.FastMath.round(data.getUsedMem() / 1024F / 1024F),
used, getTime(m.x)));
}
}
diff --git a/src/main/java/gg/pufferfish/pufferfish/flare/collectors/TPSCollector.java b/src/main/java/gg/pufferfish/pufferfish/flare/collectors/TPSCollector.java
index 40447d00aefb5ffedb8a2ee87155a04088f0649f..31cc0a29e89e79f616b3ee329a5528961edaa2de 100644
--- a/src/main/java/gg/pufferfish/pufferfish/flare/collectors/TPSCollector.java
+++ b/src/main/java/gg/pufferfish/pufferfish/flare/collectors/TPSCollector.java
@@ -25,7 +25,7 @@ public class TPSCollector extends LiveCollector {
long[] times = MinecraftServer.getServer().tickTimes5s.getTimes();
double mspt = ((double) Arrays.stream(times).sum() / (double) times.length) * 1.0E-6D;
- this.report(TPS, Math.min(20D, Math.round(Bukkit.getServer().getTPS()[0] * 100d) / 100d));
- this.report(MSPT, (double) Math.round(mspt * 100d) / 100d);
+ this.report(TPS, Math.min(20D, carpetfixes.helpers.FastMath.round(Bukkit.getServer().getTPS()[0] * 100d) / 100d));
+ this.report(MSPT, (double) carpetfixes.helpers.FastMath.round(mspt * 100d) / 100d);
}
}
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 282fc59c3280d5d8478cb9897073d9d73996420b..a4249262ca98980985d4c36009488e792121f5df 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -2781,7 +2781,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<Runnab
}
double overuseCount = (double)overuse/(double)MAX_CHUNK_EXEC_TIME;
- long extraSleep = (long)Math.round(overuseCount*CHUNK_TASK_QUEUE_BACKOFF_MIN_TIME);
+ long extraSleep = (long)carpetfixes.helpers.FastMath.round(overuseCount*CHUNK_TASK_QUEUE_BACKOFF_MIN_TIME);
lastMidTickExecute = currTime + extraSleep;
return;
diff --git a/src/main/java/net/minecraft/server/gui/StatsComponent.java b/src/main/java/net/minecraft/server/gui/StatsComponent.java
index fac8a67dd8ee3894909504df8c0910f8180d6c35..ee0022c78a87ac513837fd74c90e7166caa13c85 100644
--- a/src/main/java/net/minecraft/server/gui/StatsComponent.java
+++ b/src/main/java/net/minecraft/server/gui/StatsComponent.java
@@ -88,7 +88,7 @@ public class StatsComponent extends JComponent {
// Paper - start Add tps entry
private static String format(double tps) {
- return (( tps > 21.0 ) ? "*" : "") + Math.min(Math.round(tps * 100.0) / 100.0, 20.0); // only print * at 21, we commonly peak to 20.02 as the tick sleep is not accurate enough, stop the noise
+ return (( tps > 21.0 ) ? "*" : "") + Math.min(carpetfixes.helpers.FastMath.round(tps * 100.0) / 100.0, 20.0); // only print * at 21, we commonly peak to 20.02 as the tick sleep is not accurate enough, stop the noise
}
// Paper end
}
diff --git a/src/main/java/net/minecraft/world/entity/LivingEntity.java b/src/main/java/net/minecraft/world/entity/LivingEntity.java
index 1fdc19830bf4cf677df60c5760e02ae53abc85cc..57ec3ca7677fcc7390503c3002b78fb9b973226c 100644
--- a/src/main/java/net/minecraft/world/entity/LivingEntity.java
+++ b/src/main/java/net/minecraft/world/entity/LivingEntity.java
@@ -1473,7 +1473,7 @@ public abstract class LivingEntity extends Entity {
if (this instanceof ServerPlayer) {
CriteriaTriggers.ENTITY_HURT_PLAYER.trigger((ServerPlayer) this, source, f1, amount, flag);
if (f2 > 0.0F && f2 < 3.4028235E37F) {
- ((ServerPlayer) this).awardStat(Stats.DAMAGE_BLOCKED_BY_SHIELD, Math.round(f2 * 10.0F));
+ ((ServerPlayer) this).awardStat(Stats.DAMAGE_BLOCKED_BY_SHIELD, carpetfixes.helpers.FastMath.round(f2 * 10.0F));
}
}
@@ -1995,9 +1995,9 @@ public abstract class LivingEntity extends Entity {
if (f3 > 0.0F && f3 < 3.4028235E37F) {
if (this instanceof ServerPlayer) {
- ((ServerPlayer) this).awardStat(Stats.DAMAGE_RESISTED, Math.round(f3 * 10.0F));
+ ((ServerPlayer) this).awardStat(Stats.DAMAGE_RESISTED, carpetfixes.helpers.FastMath.round(f3 * 10.0F));
} else if (source.getEntity() instanceof ServerPlayer) {
- ((ServerPlayer) source.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(f3 * 10.0F));
+ ((ServerPlayer) source.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, carpetfixes.helpers.FastMath.round(f3 * 10.0F));
}
}
}
@@ -2107,9 +2107,9 @@ public abstract class LivingEntity extends Entity {
float f3 = (float) -event.getDamage(DamageModifier.RESISTANCE);
if (f3 > 0.0F && f3 < 3.4028235E37F) {
if (this instanceof ServerPlayer) {
- ((ServerPlayer) this).awardStat(Stats.DAMAGE_RESISTED, Math.round(f3 * 10.0F));
+ ((ServerPlayer) this).awardStat(Stats.DAMAGE_RESISTED, carpetfixes.helpers.FastMath.round(f3 * 10.0F));
} else if (damagesource.getEntity() instanceof ServerPlayer) {
- ((ServerPlayer) damagesource.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(f3 * 10.0F));
+ ((ServerPlayer) damagesource.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, carpetfixes.helpers.FastMath.round(f3 * 10.0F));
}
}
}
@@ -2141,10 +2141,10 @@ public abstract class LivingEntity extends Entity {
float f2 = absorptionModifier;
if (f2 > 0.0F && f2 < 3.4028235E37F && this instanceof net.minecraft.world.entity.player.Player) {
- ((net.minecraft.world.entity.player.Player) this).awardStat(Stats.DAMAGE_ABSORBED, Math.round(f2 * 10.0F));
+ ((net.minecraft.world.entity.player.Player) this).awardStat(Stats.DAMAGE_ABSORBED, carpetfixes.helpers.FastMath.round(f2 * 10.0F));
}
if (f2 > 0.0F && f2 < 3.4028235E37F && damagesource.getEntity() instanceof ServerPlayer) {
- ((ServerPlayer) damagesource.getEntity()).awardStat(Stats.DAMAGE_DEALT_ABSORBED, Math.round(f2 * 10.0F));
+ ((ServerPlayer) damagesource.getEntity()).awardStat(Stats.DAMAGE_DEALT_ABSORBED, carpetfixes.helpers.FastMath.round(f2 * 10.0F));
}
if (f > 0 || !human) {
@@ -2152,7 +2152,7 @@ public abstract class LivingEntity extends Entity {
// PAIL: Be sure to drag all this code from the EntityHuman subclass each update.
((net.minecraft.world.entity.player.Player) this).causeFoodExhaustion(damagesource.getFoodExhaustion(), org.bukkit.event.entity.EntityExhaustionEvent.ExhaustionReason.DAMAGED); // CraftBukkit - EntityExhaustionEvent
if (f < 3.4028235E37F) {
- ((net.minecraft.world.entity.player.Player) this).awardStat(Stats.DAMAGE_TAKEN, Math.round(f * 10.0F));
+ ((net.minecraft.world.entity.player.Player) this).awardStat(Stats.DAMAGE_TAKEN, carpetfixes.helpers.FastMath.round(f * 10.0F));
}
}
// CraftBukkit end
@@ -2174,7 +2174,7 @@ public abstract class LivingEntity extends Entity {
CriteriaTriggers.ENTITY_HURT_PLAYER.trigger((ServerPlayer) this, damagesource, f, originalDamage, true);
f2 = (float) -event.getDamage(DamageModifier.BLOCKING);
if (f2 > 0.0F && f2 < 3.4028235E37F) {
- ((ServerPlayer) this).awardStat(Stats.DAMAGE_BLOCKED_BY_SHIELD, Math.round(originalDamage * 10.0F));
+ ((ServerPlayer) this).awardStat(Stats.DAMAGE_BLOCKED_BY_SHIELD, carpetfixes.helpers.FastMath.round(originalDamage * 10.0F));
}
}
diff --git a/src/main/java/net/minecraft/world/entity/player/Player.java b/src/main/java/net/minecraft/world/entity/player/Player.java
index 5c16235115a9233bce1f5b30bb020d105bdca3d1..d33b62dab84beb3386a8738dd5dbcb96f0552351 100644
--- a/src/main/java/net/minecraft/world/entity/player/Player.java
+++ b/src/main/java/net/minecraft/world/entity/player/Player.java
@@ -1041,7 +1041,7 @@ public abstract class Player extends LivingEntity {
float f2 = f1 - f;
if (f2 > 0.0F && f2 < 3.4028235E37F) {
- this.awardStat(Stats.DAMAGE_ABSORBED, Math.round(f2 * 10.0F));
+ this.awardStat(Stats.DAMAGE_ABSORBED, carpetfixes.helpers.FastMath.round(f2 * 10.0F));
}
if (f != 0.0F) {
@@ -1051,7 +1051,7 @@ public abstract class Player extends LivingEntity {
this.setHealth(this.getHealth() - f);
this.getCombatTracker().recordDamage(damagesource, f3, f);
if (f < 3.4028235E37F) {
- this.awardStat(Stats.DAMAGE_TAKEN, Math.round(f * 10.0F));
+ this.awardStat(Stats.DAMAGE_TAKEN, carpetfixes.helpers.FastMath.round(f * 10.0F));
}
}
@@ -1377,7 +1377,7 @@ public abstract class Player extends LivingEntity {
if (target instanceof LivingEntity) {
float f5 = f3 - ((LivingEntity) target).getHealth();
- this.awardStat(Stats.DAMAGE_DEALT, Math.round(f5 * 10.0F));
+ this.awardStat(Stats.DAMAGE_DEALT, carpetfixes.helpers.FastMath.round(f5 * 10.0F));
if (j > 0) {
// CraftBukkit start - Call a combust event when somebody hits with a fire enchanted item
EntityCombustByEntityEvent combustEvent = new EntityCombustByEntityEvent(this.getBukkitEntity(), target.getBukkitEntity(), j * 4);
@@ -1641,29 +1641,29 @@ public abstract class Player extends LivingEntity {
int i;
if (this.isSwimming()) {
- i = Math.round((float) Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
+ i = carpetfixes.helpers.FastMath.round((float) Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
if (i > 0) {
this.awardStat(Stats.SWIM_ONE_CM, i);
this.causeFoodExhaustion(level.spigotConfig.swimMultiplier * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.SWIM); // CraftBukkit - EntityExhaustionEvent // Spigot
}
} else if (this.isEyeInFluid(FluidTags.WATER)) {
- i = Math.round((float) Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
+ i = carpetfixes.helpers.FastMath.round((float) Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
if (i > 0) {
this.awardStat(Stats.WALK_UNDER_WATER_ONE_CM, i);
this.causeFoodExhaustion(level.spigotConfig.swimMultiplier * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.WALK_UNDERWATER); // CraftBukkit - EntityExhaustionEvent // Spigot
}
} else if (this.isInWater()) {
- i = Math.round((float) Math.sqrt(dx * dx + dz * dz) * 100.0F);
+ i = carpetfixes.helpers.FastMath.round((float) Math.sqrt(dx * dx + dz * dz) * 100.0F);
if (i > 0) {
this.awardStat(Stats.WALK_ON_WATER_ONE_CM, i);
this.causeFoodExhaustion(level.spigotConfig.swimMultiplier * (float) i * 0.01F, EntityExhaustionEvent.ExhaustionReason.WALK_ON_WATER); // CraftBukkit - EntityExhaustionEvent // Spigot
}
} else if (this.onClimbable()) {
if (dy > 0.0D) {
- this.awardStat(Stats.CLIMB_ONE_CM, (int) Math.round(dy * 100.0D));
+ this.awardStat(Stats.CLIMB_ONE_CM, (int) carpetfixes.helpers.FastMath.round(dy * 100.0D));
}
} else if (this.onGround) {
- i = Math.round((float) Math.sqrt(dx * dx + dz * dz) * 100.0F);
+ i = carpetfixes.helpers.FastMath.round((float) Math.sqrt(dx * dx + dz * dz) * 100.0F);
if (i > 0) {
if (this.isSprinting()) {
this.awardStat(Stats.SPRINT_ONE_CM, i);
@@ -1677,10 +1677,10 @@ public abstract class Player extends LivingEntity {
}
}
} else if (this.isFallFlying()) {
- i = Math.round((float) Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
+ i = carpetfixes.helpers.FastMath.round((float) Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
this.awardStat(Stats.AVIATE_ONE_CM, i);
} else {
- i = Math.round((float) Math.sqrt(dx * dx + dz * dz) * 100.0F);
+ i = carpetfixes.helpers.FastMath.round((float) Math.sqrt(dx * dx + dz * dz) * 100.0F);
if (i > 25) {
this.awardStat(Stats.FLY_ONE_CM, i);
}
@@ -1691,7 +1691,7 @@ public abstract class Player extends LivingEntity {
public void checkRidingStatistics(double dx, double dy, double dz) {
if (this.isPassenger()) {
- int i = Math.round((float) Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
+ int i = carpetfixes.helpers.FastMath.round((float) Math.sqrt(dx * dx + dy * dy + dz * dz) * 100.0F);
if (i > 0) {
Entity entity = this.getVehicle();
@@ -1718,7 +1718,7 @@ public abstract class Player extends LivingEntity {
return false;
} else {
if (fallDistance >= 2.0F) {
- this.awardStat(Stats.FALL_ONE_CM, (int) Math.round((double) fallDistance * 100.0D));
+ this.awardStat(Stats.FALL_ONE_CM, (int) carpetfixes.helpers.FastMath.round((double) fallDistance * 100.0D));
}
return super.causeFallDamage(fallDistance, damageMultiplier, damageSource);
diff --git a/src/main/java/net/minecraft/world/item/enchantment/EnchantmentHelper.java b/src/main/java/net/minecraft/world/item/enchantment/EnchantmentHelper.java
index df4152f08b553df8895bb9e9dc39d586501ce431..3f3d7921dbea8d9daff3b5c914cb1646a858495a 100644
--- a/src/main/java/net/minecraft/world/item/enchantment/EnchantmentHelper.java
+++ b/src/main/java/net/minecraft/world/item/enchantment/EnchantmentHelper.java
@@ -341,7 +341,7 @@ public class EnchantmentHelper {
} else {
level += 1 + random.nextInt(i / 4 + 1) + random.nextInt(i / 4 + 1);
float f = (random.nextFloat() + random.nextFloat() - 1.0F) * 0.15F;
- level = Mth.clamp(Math.round((float)level + (float)level * f), 1, Integer.MAX_VALUE);
+ level = Mth.clamp(carpetfixes.helpers.FastMath.round((float)level + (float)level * f), 1, Integer.MAX_VALUE);
List<EnchantmentInstance> list2 = getAvailableEnchantmentResults(level, stack, treasureAllowed);
if (!list2.isEmpty()) {
WeightedRandom.getRandomItem(random, list2).ifPresent(list::add);
diff --git a/src/main/java/net/minecraft/world/level/block/DaylightDetectorBlock.java b/src/main/java/net/minecraft/world/level/block/DaylightDetectorBlock.java
index e57c5242866165e589277bd0184098c7806538ba..7d55c56e7372bd80d8f33f76a94dc6c18dd365a7 100644
--- a/src/main/java/net/minecraft/world/level/block/DaylightDetectorBlock.java
+++ b/src/main/java/net/minecraft/world/level/block/DaylightDetectorBlock.java
@@ -61,7 +61,7 @@ public class DaylightDetectorBlock extends BaseEntityBlock {
float f1 = f < 3.1415927F ? 0.0F : 6.2831855F;
f += (f1 - f) * 0.2F;
- i = Math.round((float) i * Mth.cos(f));
+ i = carpetfixes.helpers.FastMath.round((float) i * Mth.cos(f));
}
i = Mth.clamp(i, (int) 0, (int) 15);
diff --git a/src/main/java/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java b/src/main/java/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java
index 31918fa2eb38e42a5ea5366e559f25ea9d7d59ae..f512f1e0c46b96f831fdea3073e57c6bfd9c69eb 100644
--- a/src/main/java/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java
+++ b/src/main/java/net/minecraft/world/level/storage/loot/functions/LootingEnchantFunction.java
@@ -61,7 +61,7 @@ public class LootingEnchantFunction extends LootItemConditionalFunction {
float f = (float) i * this.value.getFloat(context);
- stack.grow(Math.round(f));
+ stack.grow(carpetfixes.helpers.FastMath.round(f));
if (this.hasLimit() && stack.getCount() > this.limit) {
stack.setCount(this.limit);
}
diff --git a/src/main/java/net/minecraft/world/phys/shapes/Shapes.java b/src/main/java/net/minecraft/world/phys/shapes/Shapes.java
index 2e1fba82dc1fceab42628d944e4ef429ce46c0f9..7aeeb180334660c81fecf22fbe62b66d4bce8b93 100644
--- a/src/main/java/net/minecraft/world/phys/shapes/Shapes.java
+++ b/src/main/java/net/minecraft/world/phys/shapes/Shapes.java
@@ -59,8 +59,8 @@ public final class Shapes {
int j = 1 << i;
double d = min * (double)j;
double e = max * (double)j;
- boolean bl = Math.abs(d - (double)Math.round(d)) < 1.0E-7D * (double)j;
- boolean bl2 = Math.abs(e - (double)Math.round(e)) < 1.0E-7D * (double)j;
+ boolean bl = Math.abs(d - (double)carpetfixes.helpers.FastMath.round(d)) < 1.0E-7D * (double)j;
+ boolean bl2 = Math.abs(e - (double)carpetfixes.helpers.FastMath.round(e)) < 1.0E-7D * (double)j;
if (bl && bl2) {
return i;
}
diff --git a/src/main/java/org/spigotmc/TicksPerSecondCommand.java b/src/main/java/org/spigotmc/TicksPerSecondCommand.java
index 0ecac76577eb440a0c3104ef4603acec826c474d..4813bd6de894d0566e8631d8c71915c38c1da0f8 100644
--- a/src/main/java/org/spigotmc/TicksPerSecondCommand.java
+++ b/src/main/java/org/spigotmc/TicksPerSecondCommand.java
@@ -52,7 +52,7 @@ public class TicksPerSecondCommand extends Command
private static String format(double tps) // Paper - Made static
{
return ( ( tps > 18.0 ) ? ChatColor.GREEN : ( tps > 16.0 ) ? ChatColor.YELLOW : ChatColor.RED ).toString()
- + ( ( tps > 21.0 ) ? "*" : "" ) + Math.min( Math.round( tps * 100.0 ) / 100.0, 20.0 ); // Paper - only print * at 21, we commonly peak to 20.02 as the tick sleep is not accurate enough, stop the noise
+ + ( ( tps > 21.0 ) ? "*" : "" ) + Math.min( carpetfixes.helpers.FastMath.round( tps * 100.0 ) / 100.0, 20.0 ); // Paper - only print * at 21, we commonly peak to 20.02 as the tick sleep is not accurate enough, stop the noise
}
// Yatopia start - Last tick time API
diff --git a/src/main/java/wtf/etil/mirai/MiraiConfig.java b/src/main/java/wtf/etil/mirai/MiraiConfig.java
index 21c4a287c8fc550be36fc5b60bdc458d71a9d25d..06e44d2fba48a217dc1e63a1901f6d3a45b305b9 100644
--- a/src/main/java/wtf/etil/mirai/MiraiConfig.java
+++ b/src/main/java/wtf/etil/mirai/MiraiConfig.java
@@ -235,4 +235,9 @@ public class MiraiConfig {
serverMetrics = getBoolean("enable-server-metrics", serverMetrics);
}
+ public static boolean riskyMathRoundOpt = false;
+ private static void fastMathRound() {
+ riskyMathRoundOpt = getBoolean("use-risky-mathround-opt", riskyMathRoundOpt);
+ }
+
}
\ No newline at end of file

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: 2No2Name <2No2Name@web.de>
Date: Sat, 8 Jan 2022 04:32:41 +0100
Subject: [PATCH] lithium: entity.fast_elytra_check
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/entity/LivingEntity.java b/src/main/java/net/minecraft/world/entity/LivingEntity.java
index 57ec3ca7677fcc7390503c3002b78fb9b973226c..add84a30460e80259b452f105f81394696c90120 100644
--- a/src/main/java/net/minecraft/world/entity/LivingEntity.java
+++ b/src/main/java/net/minecraft/world/entity/LivingEntity.java
@@ -3390,6 +3390,8 @@ public abstract class LivingEntity extends Entity {
}
private void updateFallFlying() {
+ if (!this.isFallFlying()) return; // Mirai
+
boolean flag = this.getSharedFlag(7);
if (flag && !this.onGround && !this.isPassenger() && !this.hasEffect(MobEffects.LEVITATION)) {

View File

@@ -0,0 +1,26 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: 2No2Name <2No2Name@web.de>
Date: Sat, 8 Jan 2022 04:56:54 +0100
Subject: [PATCH] lithium: profiler
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/server/level/ServerLevel.java b/src/main/java/net/minecraft/server/level/ServerLevel.java
index da6156f1d61ca20fd39f35da36c64afe62b2731b..56b3cd94b6883ff210af96f4995798a46375b70b 100644
--- a/src/main/java/net/minecraft/server/level/ServerLevel.java
+++ b/src/main/java/net/minecraft/server/level/ServerLevel.java
@@ -217,6 +217,13 @@ public class ServerLevel extends Level implements WorldGenLevel {
return new Throwable(entity + " Added to world at " + new java.util.Date());
}
+ // Mirai start
+ @Override
+ public ProfilerFiller getProfiler() {
+ return this.getServer().getProfiler();
+ }
+ // Mirai end
+
@Override public LevelChunk getChunkIfLoaded(int x, int z) { // Paper - this was added in world too but keeping here for NMS ABI
return this.chunkSource.getChunkAtIfLoadedImmediately(x, z); // Paper
}

View File

@@ -0,0 +1,21 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: 2No2Name <2No2Name@web.de>
Date: Sun, 9 Jan 2022 06:03:28 +0100
Subject: [PATCH] lithium: entity.fast_hand_swing
Original code by CaffeineMC, licensed under GNU Lesser General Public License v3.0
You can find the original code on https://github.com/CaffeineMC/lithium-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/entity/LivingEntity.java b/src/main/java/net/minecraft/world/entity/LivingEntity.java
index add84a30460e80259b452f105f81394696c90120..48337a93af6792ce40fded0cb64f2f59c1e7995f 100644
--- a/src/main/java/net/minecraft/world/entity/LivingEntity.java
+++ b/src/main/java/net/minecraft/world/entity/LivingEntity.java
@@ -2431,6 +2431,8 @@ public abstract class LivingEntity extends Entity {
}
protected void updateSwingTime() {
+ if (!this.swinging && this.swingTime == 0) return; // Mirai
+
int i = this.getCurrentSwingDuration();
if (this.swinging) {

View File

@@ -0,0 +1,267 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: ishland <ishlandmc@yeah.net>
Date: Tue, 21 Sep 2021 10:37:34 +0200
Subject: [PATCH] c2me: optimization.math
Copyright (c) 2021-2022 ishland
Original code by RelativityMC, licensed under MIT
You can find the original code on https://github.com/RelativityMC/C2ME-fabric (Yarn mappings)
diff --git a/src/main/java/net/minecraft/world/level/levelgen/synth/ImprovedNoise.java b/src/main/java/net/minecraft/world/level/levelgen/synth/ImprovedNoise.java
index d5439c68bb7d3b54e085170e294709c067721207..809dae109043f06fb9a2f1257825ef172b7ac21f 100644
--- a/src/main/java/net/minecraft/world/level/levelgen/synth/ImprovedNoise.java
+++ b/src/main/java/net/minecraft/world/level/levelgen/synth/ImprovedNoise.java
@@ -11,6 +11,27 @@ public final class ImprovedNoise {
public final double yo;
public final double zo;
+ // Mirai start - c2me: optimization.math
+ private static final double[] FLAT_SIMPLEX_GRAD = new double[]{
+ 1, 1, 0, 0,
+ -1, 1, 0, 0,
+ 1, -1, 0, 0,
+ -1, -1, 0, 0,
+ 1, 0, 1, 0,
+ -1, 0, 1, 0,
+ 1, 0, -1, 0,
+ -1, 0, -1, 0,
+ 0, 1, 1, 0,
+ 0, -1, 1, 0,
+ 0, 1, -1, 0,
+ 0, -1, -1, 0,
+ 1, 1, 0, 0,
+ 0, -1, 1, 0,
+ -1, 1, 0, 0,
+ 0, -1, -1, 0,
+ };
+ // Mirai end
+
public ImprovedNoise(RandomSource random) {
this.xo = random.nextDouble() * 256.0D;
this.yo = random.nextDouble() * 256.0D;
@@ -34,34 +55,38 @@ public final class ImprovedNoise {
return this.noise(x, y, z, 0.0D, 0.0D);
}
+ // Mirai start - c2me: optimization.math
+ /**
+ * @author ishland
+ * @reason optimize: remove frequent type conversions
+ */
/** @deprecated */
@Deprecated
public double noise(double x, double y, double z, double yScale, double yMax) {
double d = x + this.xo;
double e = y + this.yo;
double f = z + this.zo;
- int i = Mth.floor(d);
- int j = Mth.floor(e);
- int k = Mth.floor(f);
- double g = d - (double)i;
- double h = e - (double)j;
- double l = f - (double)k;
- double o;
- if (yScale != 0.0D) {
+ double i = Mth.floor(d);
+ double j = Mth.floor(e);
+ double k = Mth.floor(f);
+ double g = d - i;
+ double h = e - j;
+ double l = f - k;
+ double o = 0.0D;
+ if (yScale != 0.0) {
double m;
- if (yMax >= 0.0D && yMax < h) {
+ if (yMax >= 0.0 && yMax < h) {
m = yMax;
} else {
m = h;
}
- o = (double)Mth.floor(m / yScale + (double)1.0E-7F) * yScale;
- } else {
- o = 0.0D;
+ o = Mth.floor(m / yScale + 1.0E-7F) * yScale;
}
- return this.sampleAndLerp(i, j, k, g, h - o, l, h);
+ return this.sampleAndLerp((int) i, (int) j, (int) k, g, h - o, l, h);
}
+ // Mirai end
public double noiseWithDerivative(double x, double y, double z, double[] ds) {
double d = x + this.xo;
@@ -84,26 +109,76 @@ public final class ImprovedNoise {
return this.p[hash & 255] & 255;
}
+ // Mirai start - c2me: optimization.math
+ /**
+ * @author ishland
+ * @reason inline math & small optimization: remove frequent type conversions and redundant ops
+ */
private double sampleAndLerp(int sectionX, int sectionY, int sectionZ, double localX, double localY, double localZ, double fadeLocalX) {
- int i = this.p(sectionX);
- int j = this.p(sectionX + 1);
- int k = this.p(i + sectionY);
- int l = this.p(i + sectionY + 1);
- int m = this.p(j + sectionY);
- int n = this.p(j + sectionY + 1);
- double d = gradDot(this.p(k + sectionZ), localX, localY, localZ);
- double e = gradDot(this.p(m + sectionZ), localX - 1.0D, localY, localZ);
- double f = gradDot(this.p(l + sectionZ), localX, localY - 1.0D, localZ);
- double g = gradDot(this.p(n + sectionZ), localX - 1.0D, localY - 1.0D, localZ);
- double h = gradDot(this.p(k + sectionZ + 1), localX, localY, localZ - 1.0D);
- double o = gradDot(this.p(m + sectionZ + 1), localX - 1.0D, localY, localZ - 1.0D);
- double p = gradDot(this.p(l + sectionZ + 1), localX, localY - 1.0D, localZ - 1.0D);
- double q = gradDot(this.p(n + sectionZ + 1), localX - 1.0D, localY - 1.0D, localZ - 1.0D);
- double r = Mth.smoothstep(localX);
- double s = Mth.smoothstep(fadeLocalX);
- double t = Mth.smoothstep(localZ);
- return Mth.lerp3(r, s, t, d, e, f, g, h, o, p, q);
+ // TODO [VanillaCopy] but optimized
+ final int var0 = sectionX & 0xFF;
+ final int var1 = (sectionX + 1) & 0xFF;
+ final int var2 = this.p[var0] & 0xFF;
+ final int var3 = this.p[var1] & 0xFF;
+ final int var4 = (var2 + sectionY) & 0xFF;
+ final int var5 = (var3 + sectionY) & 0xFF;
+ final int var6 = (var2 + sectionY + 1) & 0xFF;
+ final int var7 = (var3 + sectionY + 1) & 0xFF;
+ final int var8 = this.p[var4] & 0xFF;
+ final int var9 = this.p[var5] & 0xFF;
+ final int var10 = this.p[var6] & 0xFF;
+ final int var11 = this.p[var7] & 0xFF;
+
+ final int var12 = (var8 + sectionZ) & 0xFF;
+ final int var13 = (var9 + sectionZ) & 0xFF;
+ final int var14 = (var10 + sectionZ) & 0xFF;
+ final int var15 = (var11 + sectionZ) & 0xFF;
+ final int var16 = (var8 + sectionZ + 1) & 0xFF;
+ final int var17 = (var9 + sectionZ + 1) & 0xFF;
+ final int var18 = (var10 + sectionZ + 1) & 0xFF;
+ final int var19 = (var11 + sectionZ + 1) & 0xFF;
+ final int var20 = (this.p[var12] & 15) << 2;
+ final int var21 = (this.p[var13] & 15) << 2;
+ final int var22 = (this.p[var14] & 15) << 2;
+ final int var23 = (this.p[var15] & 15) << 2;
+ final int var24 = (this.p[var16] & 15) << 2;
+ final int var25 = (this.p[var17] & 15) << 2;
+ final int var26 = (this.p[var18] & 15) << 2;
+ final int var27 = (this.p[var19] & 15) << 2;
+ final double var60 = localX - 1.0;
+ final double var61 = localY - 1.0;
+ final double var62 = localZ - 1.0;
+ final double var87 = FLAT_SIMPLEX_GRAD[(var20) | 0] * localX + FLAT_SIMPLEX_GRAD[(var20) | 1] * localY + FLAT_SIMPLEX_GRAD[(var20) | 2] * localZ;
+ final double var88 = FLAT_SIMPLEX_GRAD[(var21) | 0] * var60 + FLAT_SIMPLEX_GRAD[(var21) | 1] * localY + FLAT_SIMPLEX_GRAD[(var21) | 2] * localZ;
+ final double var89 = FLAT_SIMPLEX_GRAD[(var22) | 0] * localX + FLAT_SIMPLEX_GRAD[(var22) | 1] * var61 + FLAT_SIMPLEX_GRAD[(var22) | 2] * localZ;
+ final double var90 = FLAT_SIMPLEX_GRAD[(var23) | 0] * var60 + FLAT_SIMPLEX_GRAD[(var23) | 1] * var61 + FLAT_SIMPLEX_GRAD[(var23) | 2] * localZ;
+ final double var91 = FLAT_SIMPLEX_GRAD[(var24) | 0] * localX + FLAT_SIMPLEX_GRAD[(var24) | 1] * localY + FLAT_SIMPLEX_GRAD[(var24) | 2] * var62;
+ final double var92 = FLAT_SIMPLEX_GRAD[(var25) | 0] * var60 + FLAT_SIMPLEX_GRAD[(var25) | 1] * localY + FLAT_SIMPLEX_GRAD[(var25) | 2] * var62;
+ final double var93 = FLAT_SIMPLEX_GRAD[(var26) | 0] * localX + FLAT_SIMPLEX_GRAD[(var26) | 1] * var61 + FLAT_SIMPLEX_GRAD[(var26) | 2] * var62;
+ final double var94 = FLAT_SIMPLEX_GRAD[(var27) | 0] * var60 + FLAT_SIMPLEX_GRAD[(var27) | 1] * var61 + FLAT_SIMPLEX_GRAD[(var27) | 2] * var62;
+
+ final double var95 = localX * 6.0 - 15.0;
+ final double var96 = fadeLocalX * 6.0 - 15.0;
+ final double var97 = localZ * 6.0 - 15.0;
+ final double var98 = localX * var95 + 10.0;
+ final double var99 = fadeLocalX * var96 + 10.0;
+ final double var100 = localZ * var97 + 10.0;
+ final double var101 = localX * localX * localX * var98;
+ final double var102 = fadeLocalX * fadeLocalX * fadeLocalX * var99;
+ final double var103 = localZ * localZ * localZ * var100;
+
+ final double var113 = var87 + var101 * (var88 - var87);
+ final double var114 = var93 + var101 * (var94 - var93);
+ final double var115 = var91 + var101 * (var92 - var91);
+ final double var116 = var89 + var101 * (var90 - var89);
+ final double var117 = var114 - var115;
+ final double var118 = var102 * (var116 - var113);
+ final double var119 = var102 * var117;
+ final double var120 = var113 + var118;
+ final double var121 = var115 + var119;
+ return var120 + (var103 * (var121 - var120));
}
+ // Mirai end
private double sampleWithDerivative(int sectionX, int sectionY, int sectionZ, double localX, double localY, double localZ, double[] ds) {
int i = this.p(sectionX);
diff --git a/src/main/java/net/minecraft/world/level/levelgen/synth/PerlinNoise.java b/src/main/java/net/minecraft/world/level/levelgen/synth/PerlinNoise.java
index ab0d50625c2d603cdf577602f76f6afb41166ed8..6f006d9f4c92b55dc3e0cc87d6c02ab9006b13e4 100644
--- a/src/main/java/net/minecraft/world/level/levelgen/synth/PerlinNoise.java
+++ b/src/main/java/net/minecraft/world/level/levelgen/synth/PerlinNoise.java
@@ -25,6 +25,10 @@ public class PerlinNoise {
private final double lowestFreqValueFactor;
private final double lowestFreqInputFactor;
private final double maxValue;
+ // Mirai start - c2me: optimization.math
+ private int noiseLevelsCount = 0;
+ private double[] amplitudesArray = null;
+ // Mirai end
/** @deprecated */
@Deprecated
@@ -85,6 +89,10 @@ public class PerlinNoise {
int i = this.amplitudes.size();
int j = -this.firstOctave;
this.noiseLevels = new ImprovedNoise[i];
+ // Mirai start - c2me: optimization.math
+ this.noiseLevelsCount = this.noiseLevels.length;
+ this.amplitudesArray = this.amplitudes.toDoubleArray();
+ // Mirai end
if (xoroshiro) {
PositionalRandomFactory positionalRandomFactory = random.forkPositional();
@@ -140,9 +148,33 @@ public class PerlinNoise {
random.consumeCount(262);
}
+ // Mirai start - c2me: optimization.math
+ /**
+ * @author ishland
+ * @reason optimize for common cases
+ */
public double getValue(double x, double y, double z) {
- return this.getValue(x, y, z, 0.0D, 0.0D, false);
+ double d = 0.0;
+ double e = this.lowestFreqInputFactor;
+ double f = this.lowestFreqValueFactor;
+
+ for(int i = 0; i < this.noiseLevelsCount; ++i) {
+ ImprovedNoise improvedNoise = this.noiseLevels[i];
+ if (improvedNoise != null) {
+ @SuppressWarnings("deprecation")
+ double g = improvedNoise.noise(
+ wrap(x * e), wrap(y * e), wrap(z * e), 0.0, 0.0
+ );
+ d += this.amplitudesArray[i] * g * f;
+ }
+
+ e *= 2.0;
+ f /= 2.0;
+ }
+
+ return d;
}
+ // Mirai end
/** @deprecated */
@Deprecated
@@ -190,9 +222,15 @@ public class PerlinNoise {
return this.noiseLevels[this.noiseLevels.length - 1 - octave];
}
+ // Mirai start - c2me: optimization.math
+ /**
+ * @author ishland
+ * @reason remove frequent type conversion
+ */
public static double wrap(double value) {
- return value - (double)Mth.lfloor(value / 3.3554432E7D + 0.5D) * 3.3554432E7D;
+ return value - Mth.lfloor(value / 3.3554432E7 + 0.5) * 3.3554432E7;
}
+ // Mirai end
protected int firstOctave() {
return this.firstOctave;

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