Compare commits
91
Commits
old-system
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12f204d375 | ||
|
|
a694655f58 | ||
|
|
ce16368d3a | ||
|
|
1a1bef3461 | ||
|
|
5ab7b91ae6 | ||
|
|
99172592b2 | ||
|
|
8e0895a537 | ||
|
|
2484f54fae | ||
|
|
539c9654cd | ||
|
|
168a9ca763 | ||
|
|
a143576170 | ||
|
|
67047f503f | ||
|
|
a89252299e | ||
|
|
38ddbb8a54 | ||
|
|
80bfeacae3 | ||
|
|
beb59f3b16 | ||
|
|
3882ab1654 | ||
|
|
b4da9ed07e | ||
|
|
636198f30c | ||
|
|
151b5aed5a | ||
|
|
3e7f70244e | ||
|
|
d146f7edbe | ||
|
|
1d0237e7b2 | ||
|
|
ff8a6e3550 | ||
|
|
1e66f9f96b | ||
|
|
1efee80f96 | ||
|
|
b9c89fcaed | ||
|
|
3d1965e77f | ||
|
|
2ec1a223c4 | ||
|
|
5be25dd487 | ||
|
|
702f961746 | ||
|
|
955f0481b4 | ||
|
|
173d4578a7 | ||
|
|
1fb1fa3546 | ||
|
|
9f4de18ea9 | ||
|
|
749d82a1c0 | ||
|
|
3b9ff1087b | ||
|
|
976da2cc83 | ||
|
|
b7b1b384eb | ||
|
|
89b550609f | ||
|
|
7a5c44ca9d | ||
|
|
67573e1b0d | ||
|
|
ff3b3361a2 | ||
|
|
ae0dd9b9b7 | ||
|
|
82bd01e037 | ||
|
|
6c457b253c | ||
|
|
cb2afe770c | ||
|
|
1f768476d2 | ||
|
|
01090b122e | ||
|
|
2a3f1cfc21 | ||
|
|
122937c35e | ||
|
|
dfd990cfaa | ||
|
|
2a81661401 | ||
|
|
5d802da010 | ||
|
|
fa4fd743e1 | ||
|
|
85bbb86cb4 | ||
|
|
8d4f30004b | ||
|
|
45665a74f4 | ||
|
|
50ba0ba332 | ||
|
|
540fbff280 | ||
|
|
498c0d2bcb | ||
|
|
09e8793208 | ||
|
|
237171f798 | ||
|
|
ab366df733 | ||
|
|
fa0aa6cbb1 | ||
|
|
581c1834ca | ||
|
|
6849592cbb | ||
|
|
283f76e0b9 | ||
|
|
d5b7a33318 | ||
|
|
ddcc0c4aae | ||
|
|
b014d135b3 | ||
|
|
6b838619aa | ||
|
|
f4c903c703 | ||
|
|
ccb91ce3b0 | ||
|
|
bd1bb1a06a | ||
|
|
8b54e7d731 | ||
|
|
f995dc505b | ||
|
|
97591486ec | ||
|
|
8a0fc68ea0 | ||
|
|
f74d09a9a7 | ||
|
|
e878da1705 | ||
|
|
48e1411488 | ||
|
|
85169a487e | ||
|
|
28566eadfa | ||
|
|
f992ffca3c | ||
|
|
64632855f0 | ||
|
|
79b295dc59 | ||
|
|
67ae79559c | ||
|
|
0d24b8194c | ||
|
|
e2b9f3f9ce | ||
|
|
8abb06ff44 |
No files matched your search
@@ -116,3 +116,5 @@ run/
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
|
||||
license.txt
|
||||
@@ -1,201 +1,674 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
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.
|
||||
|
||||
1. Definitions.
|
||||
Preamble
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
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.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
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.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
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.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
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.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
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.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
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.
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
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.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
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.
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
0. Definitions.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
"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.
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
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.
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
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.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
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.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
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.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
1. Source Code.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
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.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
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.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
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.
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
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.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
Copyright 2023 AlexDev_
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
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
|
||||
2. Basic Permissions.
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
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.
|
||||
|
||||
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.
|
||||
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>.
|
||||
@@ -0,0 +1,136 @@
|
||||
<div align="center">
|
||||
|
||||
<h1><b>UnlimitedNameTags</b></h1>
|
||||
<p><i>A powerful tool to customize and manage player name tags like never before!</i></p>
|
||||
|
||||
<br>
|
||||
|
||||
<img alt="GitHub Release" src="https://img.shields.io/github/release/alexdev03/unlimitednametags.svg">
|
||||
<a href="https://www.codefactor.io/repository/github/alexdev03/unlimitednametags"><img src="https://www.codefactor.io/repository/github/alexdev03/unlimitednametags/badge" alt="CodeFactor" /></a>
|
||||
<br>
|
||||
<a href="https://www.spigotmc.org/resources/unlimitednametags.117526/"><img alt="SpigotMC" src="https://img.shields.io/badge/-SpigotMC-blue?style=for-the-badge&logo=SpigotMC"></a>
|
||||
<a href="https://builtbybit.com/resources/unlimitednametags.46172/"><img alt="BuiltByBit" src="https://img.shields.io/badge/-BuiltByBit-lightblue?style=for-the-badge&logo=BuiltByBit"></a>
|
||||
<br>
|
||||
<a href="https://discord.gg/W4Fu8fqCKs"><img alt="Discord" src="https://img.shields.io/badge/-Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white"></a>
|
||||
<br>
|
||||
<br>
|
||||
<img alt="Unlimited Name Tags in Action" src="https://i.imgur.com/w7zlGaO.gif">
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 📌 **Overview**
|
||||
Unlimited Name Tags is a robust plugin designed for Minecraft servers running **Paper 1.20.1+** or **Spigot 1.20.2+**. While the plugin supports Spigot, **Paper is highly recommended** for optimal performance and compatibility with advanced features.
|
||||
|
||||
Enhance your server's customization by tailoring player name tags, integrating dynamic placeholders, and supporting vanish plugins seamlessly. Built with ease-of-use and flexibility in mind, this plugin elevates the player experience while simplifying server management.
|
||||
|
||||
---
|
||||
|
||||
## 🌟 **Features**
|
||||
- **🎨 Customizable Name Tags**: Change colors, formats, lines, and add extra details to player name tags.
|
||||
- **🚀 Smooth Movement**: Name tags are not entities that are teleported every tick. This ensures that when a player moves, the name tag does not lag and follows the player smoothly, as the movement is entirely client-side. The effect is identical to vanilla name tag movement.
|
||||
- **⚡ Placeholder Support**: Integrate with [PlaceholderAPI](https://github.com/PlaceholderAPI/PlaceholderAPI) for dynamic, real-time information.
|
||||
- **👥 Relational Placeholders**: Fully supports relational placeholders to display dynamic information based on the relationship between players.
|
||||
- **🕵️ Vanish Integration**: Automatically hide name tags for vanished players.
|
||||
- **⚙️ Easy Configuration**: Simple yet powerful configuration via `settings.yml`.
|
||||
- **🛠️ Bedrock Support**: Limited Bedrock compatibility through Geyser; text displays are converted into armor stands due to platform restrictions.
|
||||
- **📏 Conditional Lines**: Add or remove lines dynamically based on specific conditions or placeholders.
|
||||
- **🔤 Multiple Text Formatters**: Choose from **MINIMESSAGE**, **MINEDOWN**, **LEGACY**, or **UNIVERSAL** formats:
|
||||
- **UNIVERSAL**: The most resource-intensive but supports all formatting options (except for **MINEDOWN**).
|
||||
Examples:
|
||||
- **LEGACY OF LEGACY**: `&x&0&8&4&c&f&bc`
|
||||
- **LEGACY**: `Tcfbc`
|
||||
- **MINEDOWN**: `Tcfbc&`
|
||||
- **MINIMESSAGE**: `<color:#084cfbc>`
|
||||
- **🌌 Simulate Lunar Client's Show Own Nametag Mod**: Enable the ability to display your own name tag, simulating the behavior of Lunar Client's mod.
|
||||
- **🔄 Placeholder Replacements**: Customize placeholder outputs dynamically. Example:
|
||||
- Placeholder: `%advancedvanish_is_vanished%`
|
||||
- Replacements:
|
||||
- **"Yes"**: `&7[V]&r`
|
||||
- **"No"**: `""`
|
||||
|
||||
---
|
||||
|
||||
## 🚀 **Getting Started**
|
||||
|
||||
### **Installation**
|
||||
|
||||
1. **Download the Plugin**
|
||||
Get the latest Unlimited Name Tags JAR from:
|
||||
- [BuiltByBit](https://builtbybit.com/resources/unlimitednametags.46172/)
|
||||
- [SpigotMC](https://www.spigotmc.org/resources/unlimitednametags.117526/)
|
||||
|
||||
2. **Add Dependencies**
|
||||
Download [PacketEvents](https://modrinth.com/plugin/packetevents) and place it in the `plugins` directory.
|
||||
|
||||
3. **Upload to Server**
|
||||
Place both JAR files (`UnlimitedNameTags` and `PacketEvents`) in the `plugins` directory.
|
||||
|
||||
4. **Restart the Server**
|
||||
Restart your server to load the plugin.
|
||||
|
||||
5. **Configure**
|
||||
Customize the `settings.yml` file located in the plugin's folder to suit your server’s needs.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ **Commands**
|
||||
|
||||
#### Main:
|
||||
- **`/unt`**: Displays the plugin version and a list of available commands. *(Permission: none)*
|
||||
- **`/unt reload`**: Reloads the plugin configuration without restarting the server. *(Permission: `unt.reload`)*
|
||||
- **`/unt debug`**: Performs a debug operation for troubleshooting. *(Permission: `unt.debug`)*
|
||||
- **`/unt debugger <true/false>`**: Enable or disable the debugger. *(Permission: `unt.debug`)*
|
||||
|
||||
#### Name Tag Management:
|
||||
- **`/unt show <player>`**: Displays the name tag for a specific player. *(Permission: `unt.show`)*
|
||||
- **`/unt hide <player>`**: Hides the name tag for a specific player. *(Permission: `unt.hide`)*
|
||||
- **`/unt refresh <player>`**: Refreshes the name tag of a specific player for the command sender. *(Permission: `unt.refresh`)*
|
||||
|
||||
#### Customization and Configuration:
|
||||
- **`/unt billboard <type>`**: Sets the default billboard type (e.g., `CENTER`, `FIXED`, etc.). *(Permission: `unt.billboard`)*
|
||||
- **`/unt formatter <formatter>`**: Sets the default name tag formatter. *(Permission: `unt.formatter`)*
|
||||
|
||||
#### Managing Other Players' Name Tags:
|
||||
- **`/unt hideOtherNametags [-h]`**: Hides the name tags of other players. Use the `-h` flag to suppress the confirmation message. *(Permission: `unt.hideOtherNametags`)*
|
||||
- **`/unt showOtherNametags [-h]`**: Displays the name tags of other players. Use the `-h` flag to suppress the confirmation message. *(Permission: `unt.showOtherNametags`)*
|
||||
|
||||
---
|
||||
|
||||
## 🔒 **Default Permissions**
|
||||
- **`unt.shownametags`**: Enabled by default. Revoking this permission hides other name tags globally for the player.
|
||||
- **`unt.showownnametag`**: Enabled by default. Revoking this permission hides the player's own name tag.
|
||||
|
||||
---
|
||||
|
||||
## 🔌 **Integrations**
|
||||
|
||||
Unlimited Name Tags works seamlessly with:
|
||||
|
||||
- **[PlaceholderAPI](https://github.com/PlaceholderAPI/PlaceholderAPI)**: Add dynamic data (e.g., health, rank) to name tags. Relational placeholders are fully supported.
|
||||
- **Vanish Plugins**: Automatically hide name tags for invisible players.
|
||||
- **TypeWriter**: Adjust name tags during cinematic mode.
|
||||
- **[Nexo](https://polymart.org/resource/nexo.6901)**: Ensures compatibility with 3D helmets.
|
||||
- **[Oraxen](https://oraxen.com/)**: Ensures compatibility with 3D helmets.
|
||||
- **MiniPlaceholders**: Works when using MiniMessage for advanced formatting.
|
||||
- **Custom Plugins**: Easily hook into your custom plugins to extend functionality.
|
||||
|
||||
---
|
||||
|
||||
## 📜 **Supported Versions**
|
||||
- **Paper**: Fully supported from **1.20.1+** *(highly recommended)*.
|
||||
- **Spigot**: Supported from **1.20.2+**, but Paper is preferred for enhanced performance. (Not all spigot versions can be supported)
|
||||
|
||||
> **Note**: Versions below **1.19.4** do not support text displays because the required packet functionality does not exist. Additionally, clients connecting with **ViaBackwards** are not compatible and will not display name tags correctly. For the best experience, ensure both the server and clients are using compatible versions.
|
||||
> You may connect with 1.19.4 client using **ViaBackwards** and **ViaVersion** and a server on one of the supported versions.
|
||||
|
||||
---
|
||||
|
||||
## 💬 **Support**
|
||||
|
||||
Need help? Join our [Discord Server](https://discord.gg/W4Fu8fqCKs)! For **pre-sale questions**, feel free to use the **#chat** channel. If you need support, please open a ticket and ensure your license is verified to gain access to assistance.
|
||||
|
||||
---
|
||||
|
||||
Take your server customization to the next level with **Unlimited Name Tags**! 🚀
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'com.github.johnrengelman.shadow' version '8.1.1'
|
||||
id 'maven-publish'
|
||||
}
|
||||
|
||||
group = 'com.github.alexdev03'
|
||||
version = '1.0'
|
||||
|
||||
repositories {
|
||||
maven {
|
||||
name = 'jitpack'
|
||||
url = 'https://jitpack.io'
|
||||
}
|
||||
mavenCentral()
|
||||
maven {
|
||||
name = "papermc-repo"
|
||||
url = "https://repo.papermc.io/repository/maven-public/"
|
||||
}
|
||||
maven {
|
||||
url "https://repo.purpurmc.org/snapshots"
|
||||
}
|
||||
maven {
|
||||
name = "sonatype"
|
||||
url = "https://oss.sonatype.org/content/groups/public/"
|
||||
}
|
||||
|
||||
maven {
|
||||
url = 'https://repo.extendedclip.com/content/repositories/placeholderapi/'
|
||||
}
|
||||
maven { url = 'https://repo.minebench.de/' }
|
||||
maven { url = 'https:/oss.sonatype.org/content/repositories/snapshots' }
|
||||
maven { url = 'https://libraries.minecraft.net/' }
|
||||
maven { url = 'https://repo.codemc.io/repository/maven-public/' }
|
||||
maven { url = 'https://repo.opencollab.dev/maven-public/' }
|
||||
maven { url = 'https://repo.codemc.io/repository/maven-releases/' }
|
||||
maven { url = 'https://repo.viaversion.com/' }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly 'com.github.gabber235:typewriter:ee4fc95cce'
|
||||
compileOnly 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.0-RC'
|
||||
compileOnly 'com.github.dyam0:LirandAPI:96cc59d4fb'
|
||||
compileOnly 'net.kyori:adventure-api:4.13.1'
|
||||
compileOnly 'net.kyori:adventure-text-minimessage:4.13.1'
|
||||
|
||||
compileOnly 'org.purpurmc.purpur:purpur-api:1.19.4-R0.1-SNAPSHOT'
|
||||
compileOnly 'org.projectlombok:lombok:1.18.30'
|
||||
compileOnly 'me.clip:placeholderapi:2.11.3'
|
||||
compileOnly 'io.github.miniplaceholders:miniplaceholders-api:2.1.0'
|
||||
compileOnly 'com.github.retrooper.packetevents:spigot:2.2.0'
|
||||
compileOnly 'com.viaversion:viaversion-api:4.9.2'
|
||||
compileOnly 'com.viaversion:viaversion:4.9.2'
|
||||
compileOnly 'net.kyori:adventure-nbt:4.8.1'
|
||||
|
||||
annotationProcessor 'org.projectlombok:lombok:1.18.30'
|
||||
|
||||
implementation 'com.github.Exlll.ConfigLib:configlib-paper:dev-SNAPSHOT'
|
||||
implementation 'org.jetbrains:annotations:24.0.0'
|
||||
implementation 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT'
|
||||
implementation 'com.github.alexdev03:drink:1.5.1'
|
||||
}
|
||||
|
||||
|
||||
shadowJar {
|
||||
relocate 'org.jetbrains', 'org.alexdev.libraries'
|
||||
relocate 'org.intellij', 'org.alexdev.libraries'
|
||||
relocate 'de.themoep', 'org.alexdev.libraries'
|
||||
|
||||
dependencies {
|
||||
//noinspection GroovyAssignabilityCheck
|
||||
exclude dependency(':slf4j-api')
|
||||
}
|
||||
|
||||
destinationDirectory.set(file("$rootDir/target"))
|
||||
archiveClassifier.set('')
|
||||
|
||||
minimize()
|
||||
}
|
||||
build.dependsOn shadowJar
|
||||
clean.delete "$rootDir/target"
|
||||
|
||||
def targetJavaVersion = 17
|
||||
java {
|
||||
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
|
||||
sourceCompatibility = javaVersion
|
||||
targetCompatibility = javaVersion
|
||||
if (JavaVersion.current() < javaVersion) {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
|
||||
options.release = targetJavaVersion
|
||||
}
|
||||
}
|
||||
|
||||
processResources {
|
||||
def props = [version: version]
|
||||
inputs.properties props
|
||||
filteringCharset 'UTF-8'
|
||||
filesMatching('plugin.yml') {
|
||||
expand props
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
|
||||
plugins {
|
||||
id("com.gradleup.shadow") version "8.3.2"
|
||||
id("java")
|
||||
id("org.jetbrains.kotlin.jvm") version "2.0.0"
|
||||
id("xyz.jpenilla.run-paper") version "2.3.1"
|
||||
}
|
||||
|
||||
group = "org.alexdev"
|
||||
version = "1.6.6"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
maven("https://oss.sonatype.org/content/groups/public/")
|
||||
maven("https://repo.extendedclip.com/releases")
|
||||
maven("https://repo.minebench.de/")
|
||||
maven("https://oss.sonatype.org/content/repositories/snapshots")
|
||||
maven("https://libraries.minecraft.net/")
|
||||
maven("https://repo.codemc.io/repository/maven-public/")
|
||||
maven("https://repo.codemc.io/repository/maven-releases/")
|
||||
maven("https://repo.viaversion.com/")
|
||||
maven("https://repo.opencollab.dev/main/")
|
||||
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/")
|
||||
maven("https://repo.oraxen.com/releases")
|
||||
maven("https://repo.oraxen.com/snapshots")
|
||||
maven("https://jitpack.io")
|
||||
maven("https://repo.viaversion.com")
|
||||
maven("https://maven.evokegames.gg/snapshots")
|
||||
maven("https://repo.alessiodp.com/releases")
|
||||
maven("https://maven.typewritermc.com/beta")
|
||||
maven("https://repo.nexomc.com/snapshots/")
|
||||
maven("https://repo.hibiscusmc.com/releases")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly(libs.paperApi)
|
||||
compileOnly(libs.adventureApi)
|
||||
implementation(libs.entityLib)
|
||||
compileOnly(libs.typeWriter) {
|
||||
exclude(group = "io.papermc.paper") // Exclude Paper API
|
||||
exclude(group = "com.github.Tofaa2.EntityLib") // Exclude EntityLib
|
||||
exclude(group = "me.tofaa.entitylib") // Exclude EntityLib
|
||||
}
|
||||
compileOnly(libs.placeholderapi)
|
||||
compileOnly(libs.miniplaceholdersApi)
|
||||
compileOnly(libs.floodgateApi)
|
||||
compileOnly(libs.geyserApi)
|
||||
compileOnly(libs.commonsLang)
|
||||
compileOnly(libs.configlib)
|
||||
compileOnly(libs.configlibPaper)
|
||||
compileOnly(libs.packeteventsSpigot)
|
||||
compileOnly(libs.viaVersionApi)
|
||||
compileOnly(libs.bstatsBukkit)
|
||||
compileOnly(libs.expiringMap)
|
||||
compileOnly(libs.commonsJexl3)
|
||||
compileOnly(libs.nexo)
|
||||
compileOnly(libs.oraxen)
|
||||
compileOnly(libs.itemsAdder)
|
||||
compileOnly(libs.hmccosmetics)
|
||||
|
||||
implementation(libs.minedownAdventure)
|
||||
implementation(libs.drink)
|
||||
implementation(libs.universalScheduler)
|
||||
implementation(libs.libbyBukkit)
|
||||
|
||||
compileOnly(libs.gson)
|
||||
|
||||
compileOnly(libs.lombok)
|
||||
annotationProcessor(libs.lombok)
|
||||
}
|
||||
|
||||
tasks.named<ShadowJar>("shadowJar") {
|
||||
val relocation = "org.alexdev.unlimitednametags.libraries."
|
||||
relocate("net.byteflux.libby", relocation + "libby.bukkit")
|
||||
relocate("org.jetbrains", relocation + "jetbrains")
|
||||
relocate("org.intellij", relocation + "intellij")
|
||||
relocate("de.themoep", relocation + "themoep")
|
||||
relocate("me.tofaa.entitylib", relocation + "entitylib")
|
||||
relocate("com.jonahseguin.drink", relocation + "drink")
|
||||
relocate("javax.annotation", relocation + "annotation")
|
||||
relocate("com.github.Anon8281.universalScheduler", relocation + "universalScheduler")
|
||||
relocate("net.kyori.adventure.text.serializer", "io.github.retrooper.packetevents.adventure.serializer")
|
||||
relocate("net.byteflux.libby", relocation + "libby.bukkit")
|
||||
|
||||
dependencies {
|
||||
exclude(dependency(":kotlin-stdlib"))
|
||||
exclude(dependency(":slf4j-api"))
|
||||
exclude(dependency("com.google.code.gson:gson"))
|
||||
exclude(dependency("net.kyori:adventure-api"))
|
||||
exclude(dependency("net.kyori:adventure-key"))
|
||||
exclude(dependency("net.kyori:adventure-nbt"))
|
||||
exclude(dependency("net.kyori:option"))
|
||||
exclude(dependency("net.kyori:examination-api"))
|
||||
exclude(dependency("net.kyori:examination-string"))
|
||||
exclude(dependency("net.kyori:text"))
|
||||
exclude(dependency("net.kyori:adventure-text-serializer-gson"))
|
||||
exclude(dependency("net.kyori:adventure-text-serializer-json"))
|
||||
}
|
||||
|
||||
//mappings
|
||||
exclude("assets/mappings/block/**")
|
||||
exclude("assets/mappings/stats/**")
|
||||
exclude("assets/mappings/particle/**")
|
||||
exclude("assets/mappings/enchantment/**")
|
||||
|
||||
destinationDirectory.set(file("$rootDir/target"))
|
||||
archiveFileName.set("${project.name}.jar")
|
||||
|
||||
minimize()
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile> {
|
||||
options.encoding = "UTF-8"
|
||||
options.release.set(21)
|
||||
|
||||
}
|
||||
tasks.withType<Javadoc> {
|
||||
options.encoding = "UTF-8"
|
||||
}
|
||||
|
||||
java {
|
||||
toolchain.languageVersion.set(JavaLanguageVersion.of(21))
|
||||
}
|
||||
|
||||
tasks.named<Jar>("jar").configure {
|
||||
dependsOn("shadowJar")
|
||||
}
|
||||
tasks.named<Delete>("clean").configure {
|
||||
delete(tasks.named<ShadowJar>("shadowJar").get().archiveFile)
|
||||
}
|
||||
|
||||
tasks {
|
||||
runServer {
|
||||
minecraftVersion("1.21.3")
|
||||
|
||||
downloadPlugins {
|
||||
hangar("PlaceholderAPI", "2.11.6")
|
||||
modrinth("luckperms", "v5.4.145-bukkit")
|
||||
modrinth("multiverse-core", "4.3.14")
|
||||
url("https://github.com/retrooper/packetevents/releases/download/v2.6.0/packetevents-spigot-2.6.0.jar")
|
||||
github("ViaVersion", "ViaVersion", "5.1.1", "ViaVersion-5.1.1.jar")
|
||||
github("ViaVersion", "ViaBackwards", "5.1.1", "ViaBackwards-5.1.1.jar")
|
||||
github("MilkBowl", "Vault", "1.7.3", "Vault.jar")
|
||||
github("gecolay", "GSit", "1.11.2", "GSit-1.11.2.jar")
|
||||
// url("https://github.com/EssentialsX/Essentials/releases/download/2.20.1/EssentialsX-2.20.1.jar")
|
||||
}
|
||||
}
|
||||
runPaper.folia.registerTask {
|
||||
minecraftVersion("1.21.1")
|
||||
|
||||
downloadPlugins {
|
||||
github("Anon8281", "PlaceholderAPI", "2.11.7", "PlaceholderAPI-2.11.7-DEV-Folia.jar")
|
||||
|
||||
url("https://cdn.modrinth.com/data/HQyibRsN/versions/J2guR3GH/MiniPlaceholders-Paper-2.2.4.jar")
|
||||
url("https://ci.lucko.me/job/LuckPerms-Folia/lastSuccessfulBuild/artifact/bukkit/loader/build/libs/LuckPerms-Bukkit-5.4.141.jar")
|
||||
url("https://github.com/retrooper/packetevents/releases/download/v2.4.0/packetevents-spigot-2.4.0.jar")
|
||||
github("ViaVersion", "ViaVersion", "5.0.1", "ViaVersion-5.0.1.jar")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.processResources {
|
||||
var compiled = true
|
||||
if (file("license.txt").exists()) {
|
||||
compiled = false
|
||||
}
|
||||
|
||||
from("src/main/resources") {
|
||||
include("plugin.yml")
|
||||
duplicatesStrategy = DuplicatesStrategy.INCLUDE
|
||||
expand(
|
||||
"configlibVersion" to libs.versions.configlibVersion.get(),
|
||||
"expiringMapVersion" to libs.versions.expiringMapVersion.get(),
|
||||
"commonsJexl3Version" to libs.versions.commonsJexl3Version.get(),
|
||||
"version" to version,
|
||||
"compiled" to compiled
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,57 @@
|
||||
[versions]
|
||||
paperApiVersion = "1.21.1-R0.1-SNAPSHOT"
|
||||
adventureApiVersion = "4.16.0"
|
||||
adventureTextMinimessageVersion = "4.17.0"
|
||||
adventureTextSerializerLegacyVersion = "4.17.0"
|
||||
adventurePlatformBukkitVersion = "4.3.3"
|
||||
typeWriterVersion = "0.7.0"
|
||||
lombokVersion = "1.18.30"
|
||||
placeholderapiVersion = "2.11.6"
|
||||
miniplaceholdersApiVersion = "2.2.3"
|
||||
floodgateApiVersion = "2.2.3-SNAPSHOT"
|
||||
geyserApiVersion = "2.4.2-SNAPSHOT"
|
||||
commonsLangVersion = "3.14.0"
|
||||
configlibVersion = "4.5.0"
|
||||
minedownAdventureVersion = "1.7.2-SNAPSHOT"
|
||||
drinkVersion = "1.5.3"
|
||||
entityLibVersion = "+39cce79-SNAPSHOT"
|
||||
packeteventsSpigotVersion = "2.6.0"
|
||||
universalSchedulerVersion = "0.1.6"
|
||||
viaVersionApiVersion = "5.0.1"
|
||||
libbyBukkitVersion = "1.3.1"
|
||||
bstatsBukkitVersion = "3.0.2"
|
||||
expiringMapVersion = "0.5.11"
|
||||
commonsJexl3Version = "3.4.0"
|
||||
nexoVersion = "0.9.0-dev.19"
|
||||
oraxenVersion = "1.174.0"
|
||||
itemsAdderVersion = "3.6.1"
|
||||
gsonVersion = "2.11.0"
|
||||
hmccosmeticsVersion = "2.7.4"
|
||||
|
||||
[libraries]
|
||||
paperApi = { module = "io.papermc.paper:paper-api", version.ref = "paperApiVersion" }
|
||||
adventureApi = { module = "net.kyori:adventure-api", version.ref = "adventureApiVersion" }
|
||||
typeWriter = { module = "com.typewritermc:engine-paper", version.ref = "typeWriterVersion" }
|
||||
lombok = { module = "org.projectlombok:lombok", version.ref = "lombokVersion" }
|
||||
placeholderapi = { module = "me.clip:placeholderapi", version.ref = "placeholderapiVersion" }
|
||||
miniplaceholdersApi = { module = "io.github.miniplaceholders:miniplaceholders-api", version.ref = "miniplaceholdersApiVersion" }
|
||||
floodgateApi = { module = "org.geysermc.floodgate:api", version.ref = "floodgateApiVersion" }
|
||||
geyserApi = { module = "org.geysermc.geyser:api", version.ref = "geyserApiVersion" }
|
||||
commonsLang = { module = "org.apache.commons:commons-lang3", version.ref = "commonsLangVersion" }
|
||||
configlib = { module = "de.exlll:configlib-yaml", version.ref = "configlibVersion" }
|
||||
configlibPaper = { module = "de.exlll:configlib-paper", version.ref = "configlibVersion" }
|
||||
minedownAdventure = { module = "de.themoep:minedown-adventure", version.ref = "minedownAdventureVersion" }
|
||||
drink = { module = "com.github.alexdev03:drink", version.ref = "drinkVersion" }
|
||||
entityLib = { module = "me.tofaa.entitylib:spigot", version.ref = "entityLibVersion" }
|
||||
packeteventsSpigot = { module = "com.github.retrooper:packetevents-spigot", version.ref = "packeteventsSpigotVersion" }
|
||||
universalScheduler = { module = "com.github.Anon8281:UniversalScheduler", version.ref = "universalSchedulerVersion" }
|
||||
viaVersionApi = { module = "com.viaversion:viaversion-api", version.ref = "viaVersionApiVersion" }
|
||||
libbyBukkit = { module = "net.byteflux:libby-bukkit", version.ref = "libbyBukkitVersion" }
|
||||
bstatsBukkit = { module = "org.bstats:bstats-bukkit", version.ref = "bstatsBukkitVersion" }
|
||||
expiringMap = { module = "net.jodah:expiringmap", version.ref = "expiringMapVersion" }
|
||||
commonsJexl3 = { module = "org.apache.commons:commons-jexl3", version.ref = "commonsJexl3Version" }
|
||||
nexo = { module = "com.nexomc:nexo", version.ref = "nexoVersion" }
|
||||
oraxen = { module = "io.th0rgal:oraxen", version.ref = "oraxenVersion" }
|
||||
itemsAdder = { module = "com.github.LoneDev6:API-ItemsAdder", version.ref = "itemsAdderVersion" }
|
||||
gson = { module = "com.google.code.gson:gson", version.ref = "gsonVersion" }
|
||||
hmccosmetics = { module = "com.hibiscusmc:HMCCosmetics", version.ref = "hmccosmeticsVersion" }
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
|
||||
networkTimeout=10000
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+8
-1
@@ -1,2 +1,9 @@
|
||||
jdk:
|
||||
- openjdk17
|
||||
- openjdk21
|
||||
|
||||
stages:
|
||||
- name: build
|
||||
|
||||
build:
|
||||
script:
|
||||
- ./gradlew build
|
||||
@@ -1 +0,0 @@
|
||||
rootProject.name = 'UnlimitedNametags'
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = "UnlimitedNametags"
|
||||
@@ -1,86 +1,221 @@
|
||||
package org.alexdev.unlimitednametags;
|
||||
|
||||
import com.github.Anon8281.universalScheduler.UniversalScheduler;
|
||||
import com.github.Anon8281.universalScheduler.scheduling.schedulers.TaskScheduler;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.jonahseguin.drink.CommandService;
|
||||
import com.jonahseguin.drink.Drink;
|
||||
import lombok.Getter;
|
||||
import net.byteflux.libby.BukkitLibraryManager;
|
||||
import net.byteflux.libby.Library;
|
||||
import org.alexdev.unlimitednametags.api.UNTAPI;
|
||||
import org.alexdev.unlimitednametags.commands.MainCommand;
|
||||
import org.alexdev.unlimitednametags.config.ConfigManager;
|
||||
import org.alexdev.unlimitednametags.events.PacketEventsListener;
|
||||
import org.alexdev.unlimitednametags.events.PlayerListener;
|
||||
import org.alexdev.unlimitednametags.events.PurpurListener;
|
||||
import org.alexdev.unlimitednametags.events.TypeWriterListener;
|
||||
import org.alexdev.unlimitednametags.events.*;
|
||||
import org.alexdev.unlimitednametags.hook.*;
|
||||
import org.alexdev.unlimitednametags.hook.hat.HatHook;
|
||||
import org.alexdev.unlimitednametags.metrics.Metrics;
|
||||
import org.alexdev.unlimitednametags.nametags.ConditionalManager;
|
||||
import org.alexdev.unlimitednametags.nametags.NameTagManager;
|
||||
import org.alexdev.unlimitednametags.packet.KyoriManager;
|
||||
import org.alexdev.unlimitednametags.packet.PacketManager;
|
||||
import org.alexdev.unlimitednametags.placeholders.PlaceholderManager;
|
||||
import org.alexdev.unlimitednametags.vanish.VanishManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Getter
|
||||
public final class UnlimitedNameTags extends JavaPlugin {
|
||||
|
||||
private boolean isPaper;
|
||||
private ConfigManager configManager;
|
||||
private NameTagManager nametagManager;
|
||||
private PlaceholderManager placeholderManager;
|
||||
private VanishManager vanishManager;
|
||||
private PacketEventsListener packetEventsListener;
|
||||
private PacketManager packetManager;
|
||||
private PlayerListener playerListener;
|
||||
private TrackerManager trackerManager;
|
||||
private Map<Class<? extends Hook>, Hook> hooks;
|
||||
private List<HatHook> hatHooks;
|
||||
private TaskScheduler taskScheduler;
|
||||
private KyoriManager kyoriManager;
|
||||
private ConditionalManager conditionalManager;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("PacketEvents")) {
|
||||
getLogger().info("PacketEvents found, hooking into it");
|
||||
packetEventsListener = new PacketEventsListener(this);
|
||||
packetEventsListener.onLoad();
|
||||
}
|
||||
hooks = Maps.newConcurrentMap();
|
||||
hatHooks = Lists.newCopyOnWriteArrayList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
isPaper = isPaperSupported();
|
||||
loadLibraries().join();
|
||||
kyoriManager = new KyoriManager(this);
|
||||
|
||||
taskScheduler = UniversalScheduler.getScheduler(this);
|
||||
configManager = new ConfigManager(this);
|
||||
placeholderManager = new PlaceholderManager(this);
|
||||
if (!loadConfig()) {
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
|
||||
trackerManager = new TrackerManager(this);
|
||||
nametagManager = new NameTagManager(this);
|
||||
placeholderManager = new PlaceholderManager(this);
|
||||
vanishManager = new VanishManager(this);
|
||||
packetManager = new PacketManager(this);
|
||||
conditionalManager = new ConditionalManager(this);
|
||||
|
||||
|
||||
loadCommands();
|
||||
loadListeners();
|
||||
loadHooks();
|
||||
loadStats();
|
||||
|
||||
UNTAPI.register(this);
|
||||
|
||||
getLogger().info("API registered");
|
||||
|
||||
getLogger().info("UnlimitedNameTags has been enabled!");
|
||||
}
|
||||
|
||||
private void loadListeners() {
|
||||
Bukkit.getPluginManager().registerEvents(new PlayerListener(this), this);
|
||||
|
||||
if (isPurpur()) {
|
||||
Bukkit.getPluginManager().registerEvents(new PurpurListener(this), this);
|
||||
getLogger().info("Purpur found, teleporting with passengers will work");
|
||||
} else {
|
||||
getLogger().warning("Purpur not found, teleporting with passengers will not work. This could create problems with teleports");
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("TypeWriter")) {
|
||||
Bukkit.getPluginManager().registerEvents(new TypeWriterListener(this), this);
|
||||
getLogger().info("TypeWriter found, hooking into it");
|
||||
}
|
||||
|
||||
if (packetEventsListener != null) {
|
||||
packetEventsListener.onEnable();
|
||||
private boolean loadConfig() {
|
||||
final Optional<Throwable> error = configManager.loadConfigs();
|
||||
if (error.isPresent()) {
|
||||
getLogger().log(java.util.logging.Level.SEVERE, "Failed to load configuration", error.get());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isPurpur() {
|
||||
private CompletableFuture<Void> loadLibraries() {
|
||||
if (isPaper) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
final BukkitLibraryManager bukkitLibraryManager = new BukkitLibraryManager(this);
|
||||
bukkitLibraryManager.addMavenCentral();
|
||||
|
||||
final List<Library> libraries = Lists.newArrayList(
|
||||
Library.builder()
|
||||
.groupId("net{}kyori")
|
||||
.artifactId("adventure-text-minimessage")
|
||||
.version("4.17.0")
|
||||
.relocate("net{}]kyori{}adventure{}text{}serializer", "io{}github{}retrooper{}packetevents{}adventure{}serializer")
|
||||
.build()
|
||||
);
|
||||
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
libraries.forEach(bukkitLibraryManager::loadLibrary);
|
||||
});
|
||||
}
|
||||
|
||||
private void loadListeners() {
|
||||
playerListener = new PlayerListener(this);
|
||||
Bukkit.getPluginManager().registerEvents(playerListener, this);
|
||||
|
||||
if (isPaper) {
|
||||
getLogger().info("Paper found, using Paper's tracker");
|
||||
Bukkit.getPluginManager().registerEvents(new PaperTrackerListener(this), this);
|
||||
} else {
|
||||
if (!isCorrectSpigotVersion()) {
|
||||
getLogger().severe("Unsupported Spigot version, please use 1.20.2 or higher");
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
getLogger().info("Paper not found, using Spigot's tracker");
|
||||
Bukkit.getPluginManager().registerEvents(new SpigotTrackerListener(this), this);
|
||||
}
|
||||
|
||||
getLogger().info("PacketEvents found, hooking into it");
|
||||
packetEventsListener = new PacketEventsListener(this);
|
||||
packetEventsListener.onEnable();
|
||||
}
|
||||
|
||||
private boolean isCorrectSpigotVersion() {
|
||||
final String version = Bukkit.getServer().getBukkitVersion().split("-")[0];
|
||||
final String[] split = version.split("\\.");
|
||||
if (split.length < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final int major = Integer.parseInt(split[1]);
|
||||
final int minor = Integer.parseInt(split[2]);
|
||||
|
||||
if (major < 20) {
|
||||
return false;
|
||||
} else return major != 20 || minor >= 2;
|
||||
}
|
||||
|
||||
private boolean isPaperSupported() {
|
||||
try {
|
||||
Class.forName("org.purpurmc.purpur.event.entity.EntityTeleportHinderedEvent");
|
||||
Class.forName("io.papermc.paper.event.player.PlayerTrackEntityEvent");
|
||||
return true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void loadHooks() {
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("TypeWriter")) {
|
||||
hooks.put(TypeWriterListener.class, new TypeWriterListener(this));
|
||||
getLogger().info("TypeWriter found, hooking into it");
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("MiniPlaceholders")) {
|
||||
hooks.put(MiniPlaceholdersHook.class, new MiniPlaceholdersHook(this));
|
||||
getLogger().info("MiniPlaceholders found, hooking into it");
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("Nexo")) {
|
||||
final NexoHook hook = new NexoHook(this);
|
||||
hatHooks.add(hook);
|
||||
hooks.put(NexoHook.class, hook);
|
||||
getLogger().info("Nexo found, hooking into it");
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("Oraxen")) {
|
||||
final OraxenHook hook = new OraxenHook(this);
|
||||
hatHooks.add(hook);
|
||||
hooks.put(OraxenHook.class, hook);
|
||||
getLogger().info("Oraxen found, hooking into it");
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("ItemsAdder")) {
|
||||
final ItemsAdderHook hook = new ItemsAdderHook(this);
|
||||
hatHooks.add(hook);
|
||||
hooks.put(ItemsAdderHook.class, hook);
|
||||
getLogger().info("ItemsAdder found, hooking into it");
|
||||
}
|
||||
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("ViaVersion")) {
|
||||
final ViaVersionHook hook = new ViaVersionHook(this);
|
||||
hooks.put(ViaVersionHook.class, hook);
|
||||
getLogger().info("ViaVersion found, hooking into it");
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("geyser")) {
|
||||
final GeyserHook hook = new GeyserHook(this);
|
||||
hooks.put(GeyserHook.class, hook);
|
||||
getLogger().info("Geyser found, hooking into it");
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("floodgate")) {
|
||||
final FloodgateHook hook = new FloodgateHook(this);
|
||||
hooks.put(FloodgateHook.class, hook);
|
||||
getLogger().info("Floodgate found, hooking into it");
|
||||
}
|
||||
|
||||
hooks.values().forEach(Hook::onEnable);
|
||||
}
|
||||
|
||||
private void loadCommands() {
|
||||
final CommandService drink = Drink.get(this);
|
||||
|
||||
@@ -88,13 +223,45 @@ public final class UnlimitedNameTags extends JavaPlugin {
|
||||
drink.registerCommands();
|
||||
}
|
||||
|
||||
private void loadStats() {
|
||||
final org.alexdev.unlimitednametags.metrics.Metrics metrics = new org.alexdev.unlimitednametags.metrics.Metrics(this, 23081);
|
||||
metrics.addCustomChart(new Metrics.SimplePie("paper", () -> String.valueOf(isPaper)));
|
||||
metrics.addCustomChart(new Metrics.AdvancedPie("nametags", () -> {
|
||||
final Map<String, Integer> map = Maps.newHashMap();
|
||||
configManager.getSettings().getNameTags().forEach((key, value) -> {
|
||||
final int count = (int) nametagManager.getNameTags().values().stream()
|
||||
.filter(n -> n.getNameTag().equals(value))
|
||||
.count();
|
||||
map.put(key, count);
|
||||
});
|
||||
return map;
|
||||
}));
|
||||
metrics.addCustomChart(new Metrics.SimplePie("compiled", () -> String.valueOf(configManager.isCompiled())));
|
||||
metrics.addCustomChart(new Metrics.SimplePie("formatter", () -> configManager.getSettings().getFormat().getName()));
|
||||
metrics.addCustomChart(new Metrics.SimplePie("default_billboard", () -> configManager.getSettings().getDefaultBillboard().name()));
|
||||
metrics.addCustomChart(new Metrics.AdvancedPie("hooks", () -> {
|
||||
final Map<String, Integer> map = Maps.newHashMap();
|
||||
hooks.values().forEach(hook -> map.put(hook.getClass().getSimpleName(), 1));
|
||||
return map;
|
||||
}));
|
||||
}
|
||||
|
||||
public <H extends Hook> Optional<H> getHook(@NotNull Class<H> hookType) {
|
||||
return Optional.ofNullable(hooks.get(hookType)).map(hookType::cast);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
UNTAPI.unregister();
|
||||
|
||||
hooks.values().forEach(Hook::onDisable);
|
||||
|
||||
trackerManager.onDisable();
|
||||
packetEventsListener.onDisable();
|
||||
nametagManager.removeAll();
|
||||
placeholderManager.close();
|
||||
Bukkit.getScheduler().cancelTasks(this);
|
||||
packetManager.close();
|
||||
taskScheduler.cancelTasks();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,17 +2,21 @@ package org.alexdev.unlimitednametags.api;
|
||||
|
||||
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.hook.hat.HatHook;
|
||||
import org.alexdev.unlimitednametags.packet.PacketNameTag;
|
||||
import org.alexdev.unlimitednametags.vanish.VanishIntegration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The UnlimitedNameTags API class.
|
||||
* Retrieve an instance of the API class via {@link #getInstance()}.
|
||||
*/ public class UNTAPI {
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class UNTAPI {
|
||||
|
||||
// Instance of the plugin
|
||||
private final UnlimitedNameTags plugin;
|
||||
@@ -26,8 +30,7 @@ import org.jetbrains.annotations.NotNull;
|
||||
/**
|
||||
* Entrypoint to the {@link UNTAPI} API - returns an instance of the API
|
||||
*
|
||||
* @return instance of the HuskSync API
|
||||
* @since 1.5.2
|
||||
* @return instance of the UnlimitedNameTags API
|
||||
*/
|
||||
@NotNull
|
||||
public static UNTAPI getInstance() {
|
||||
@@ -41,7 +44,6 @@ import org.jetbrains.annotations.NotNull;
|
||||
* <b>(Internal use only)</b> - Register the API.
|
||||
*
|
||||
* @param plugin the plugin instance
|
||||
* @since 3.0
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public static void register(@NotNull UnlimitedNameTags plugin) {
|
||||
@@ -94,6 +96,56 @@ import org.jetbrains.annotations.NotNull;
|
||||
plugin.getVanishManager().unVanishPlayer(player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the nametag of the specified player.
|
||||
*
|
||||
* @param player The player whose nametag should be hidden
|
||||
* @throws IllegalArgumentException if player is null
|
||||
* @since 1.5
|
||||
*/
|
||||
public void hideNametag(@NotNull Player player) {
|
||||
plugin.getNametagManager().removeAllViewers(player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the nametag of the specified player to the tracked players.
|
||||
*
|
||||
* @param player the player whose nametag should be shown
|
||||
* @throws IllegalArgumentException if player is null
|
||||
* @since 1.5
|
||||
*/
|
||||
public void showNametag(@NotNull Player player) {
|
||||
plugin.getNametagManager().showToTrackedPlayers(player, plugin.getTrackerManager().getTrackedPlayers(player.getUniqueId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a {@link HatHook} to the plugin.
|
||||
* This hook is used to determine the height of the hat for a player.
|
||||
*
|
||||
* @param hook the hook to add
|
||||
*/
|
||||
public void addHatHook(@NotNull HatHook hook) {
|
||||
plugin.getHatHooks().add(hook);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the display text packet for the specified player.
|
||||
*
|
||||
* @param player the player to retrieve the display text packet for
|
||||
* @return the display text packet for the player
|
||||
*/
|
||||
public Optional<PacketNameTag> getPacketDisplayText(@NotNull Player player) {
|
||||
return plugin.getNametagManager().getPacketDisplayText(player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a {@link HatHook} from the plugin.
|
||||
*
|
||||
* @param hook the hook to remove
|
||||
*/
|
||||
public void removeHatHook(@NotNull HatHook hook) {
|
||||
plugin.getHatHooks().remove(hook);
|
||||
}
|
||||
|
||||
static final class NotRegisteredException extends IllegalStateException {
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package org.alexdev.unlimitednametags.commands;
|
||||
|
||||
import com.jonahseguin.drink.annotation.Command;
|
||||
import com.jonahseguin.drink.annotation.Require;
|
||||
import com.jonahseguin.drink.annotation.Sender;
|
||||
import com.jonahseguin.drink.annotation.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import me.tofaa.entitylib.meta.display.AbstractDisplayMeta;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.config.Formatter;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@SuppressWarnings("unused")
|
||||
@@ -14,17 +14,96 @@ public class MainCommand {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
|
||||
@Command(name = "reload", desc = "Reloads the plugin", usage = "/unt reload")
|
||||
@Require("unt.reload")
|
||||
@Command(name = "unt", desc = "Main command for UnlimitedNameTags", usage = "/unt")
|
||||
@SuppressWarnings("deprecation")
|
||||
public void onMain(@Sender CommandSender sender) {
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&aUnlimitedNameTags v" + plugin.getDescription().getVersion()));
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&a/unt reload &7- Reloads the plugin"));
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&a/unt debug &7- Debugs the plugin"));
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&a/unt hide <player> &7- Hides the nametag"));
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&a/unt show <player> &7- Shows the nametag"));
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&a/unt debugger <true/false> &7- Enable or disable the debugger"));
|
||||
}
|
||||
|
||||
@Command(name = "reload", desc = "Reloads the plugin", usage = "reload")
|
||||
@Require(value = "unt.reload", message = "&cYou do not have permission to reload the plugin")
|
||||
public void onReload(@Sender CommandSender sender) {
|
||||
plugin.getConfigManager().reload();
|
||||
plugin.getNametagManager().reload();
|
||||
sender.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize("&cPlugin reloaded!"));
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&aUnlimitedNameTags has been reloaded!"));
|
||||
}
|
||||
|
||||
@Command(name = "debug", desc = "Debugs the plugin", usage = "/unt debug")
|
||||
@Require("unt.debug")
|
||||
@Command(name = "debugger", desc = "Enables/Disables the debug mode", usage = "debugger")
|
||||
@Require(value = "unt.debug", message = "&cYou do not have permission to debug the plugin")
|
||||
public void onDebug(@Sender CommandSender sender, boolean debug) {
|
||||
plugin.getNametagManager().setDebug(debug);
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&aUnlimitedNameTags debug mode set to " + debug));
|
||||
}
|
||||
|
||||
@Command(name = "debug", desc = "Debugs the plugin", usage = "debug")
|
||||
@Require(value = "unt.debug", message = "&cYou do not have permission to debug the plugin")
|
||||
public void onDebug(@Sender CommandSender sender) {
|
||||
plugin.getNametagManager().debug(sender);
|
||||
}
|
||||
|
||||
@Command(name = "hide", desc = "Hides the nametag", usage = "hide")
|
||||
@Require(value = "unt.hide", message = "&cYou do not have permission to hide the nametag")
|
||||
public void onHide(@Sender CommandSender sender, Player target) {
|
||||
plugin.getNametagManager().removeAllViewers(target);
|
||||
}
|
||||
|
||||
@Command(name = "show", desc = "Shows the nametag", usage = "show")
|
||||
@Require(value = "unt.show", message = "&cYou do not have permission to show the nametag")
|
||||
public void onShow(@Sender CommandSender sender, Player target) {
|
||||
plugin.getNametagManager().showToTrackedPlayers(target, plugin.getTrackerManager().getTrackedPlayers(target.getUniqueId()));
|
||||
}
|
||||
|
||||
@Command(name = "refresh", desc = "Refreshes the nametag of a player for you", usage = "refresh")
|
||||
@Require(value = "unt.refresh", message = "&cYou do not have permission to refresh the nametag")
|
||||
public void onRefresh(@Sender Player sender, Player target) {
|
||||
plugin.getNametagManager().getPacketDisplayText(target).ifPresent(packetDisplayText -> {
|
||||
packetDisplayText.refreshForPlayer(sender);
|
||||
});
|
||||
}
|
||||
|
||||
@Command(name = "billboard", desc = "Sets the default billboard", usage = "billboard")
|
||||
@Require(value = "unt.billboard", message = "&cYou do not have permission to set the default billboard")
|
||||
public void onBillboard(@Sender CommandSender sender, AbstractDisplayMeta.BillboardConstraints billboardConstraints) {
|
||||
plugin.getConfigManager().getSettings().setDefaultBillboard(billboardConstraints);
|
||||
plugin.getConfigManager().save();
|
||||
plugin.getNametagManager().reload();
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&aDefault billboard set to " + billboardConstraints.name()));
|
||||
}
|
||||
|
||||
@Command(name = "formatter", desc = "Sets the default formatter", usage = "formatter")
|
||||
@Require(value = "unt.formatter", message = "&cYou do not have permission to set the default formatter")
|
||||
public void onFormatter(@Sender CommandSender sender, Formatter formatter) {
|
||||
plugin.getConfigManager().getSettings().setFormat(formatter);
|
||||
plugin.getConfigManager().save();
|
||||
plugin.getNametagManager().reload();
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&aDefault formatter set to " + formatter.name()));
|
||||
}
|
||||
|
||||
@Command(name = "hideOtherNametags", desc = "Hides other nametags", usage = "hideOtherNametags [-h]")
|
||||
@Require(value = "unt.hideOtherNametags", message = "&cYou do not have permission to hide other nametags")
|
||||
public void onHideOtherNametags(@Sender Player sender, @OptArg(value = "false") boolean hideMessage) {
|
||||
if (!plugin.getNametagManager().isHiddenOtherNametags(sender)) {
|
||||
plugin.getNametagManager().hideOtherNametags(sender);
|
||||
if (!hideMessage) {
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&aOther nametags hidden"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Command(name = "showOtherNametags", desc = "Shows other nametags", usage = "showOtherNametags [-h]")
|
||||
@Require(value = "unt.showOtherNametags", message = "&cYou do not have permission to show other nametags")
|
||||
public void onShowOtherNametags(@Sender Player sender, @OptArg(value = "false") boolean showMessage) {
|
||||
if (plugin.getNametagManager().isHiddenOtherNametags(sender)) {
|
||||
plugin.getNametagManager().showOtherNametags(sender);
|
||||
if (!showMessage) {
|
||||
plugin.getKyoriManager().sendMessage(sender, Formatter.LEGACY.format(plugin, sender, "&aOther nametags shown"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,41 +1,103 @@
|
||||
package org.alexdev.unlimitednametags.config;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import de.exlll.configlib.ConfigLib;
|
||||
import de.exlll.configlib.YamlConfigurationProperties;
|
||||
import de.exlll.configlib.YamlConfigurations;
|
||||
import lombok.Getter;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
@Getter
|
||||
public class ConfigManager {
|
||||
|
||||
private static final YamlConfigurationProperties PROPERTIES = ConfigLib.BUKKIT_DEFAULT_PROPERTIES.toBuilder()
|
||||
.charset(StandardCharsets.UTF_8)
|
||||
.outputNulls(true)
|
||||
.inputNulls(false)
|
||||
.footer("Authors: AlexDev_")
|
||||
.build();
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
private Settings settings;
|
||||
private boolean compiled;
|
||||
|
||||
public ConfigManager(UnlimitedNameTags plugin) {
|
||||
public ConfigManager(@NotNull UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
loadConfigs();
|
||||
this.loadUsage();
|
||||
}
|
||||
|
||||
public void loadConfigs() {
|
||||
final YamlConfigurationProperties properties = ConfigLib.BUKKIT_DEFAULT_PROPERTIES.toBuilder()
|
||||
.footer("Authors: AlexDev_")
|
||||
.build();
|
||||
private void loadUsage() {
|
||||
try (@NotNull final InputStream inputStream = Objects.requireNonNull(getClass().getResourceAsStream("/plugin.yml"));
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))
|
||||
) {
|
||||
compiled = YamlConfiguration.loadConfiguration(reader).getBoolean("compiled", true);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Optional<Throwable> loadConfigs() {
|
||||
final File settingsFile = new File(plugin.getDataFolder(), "settings.yml");
|
||||
|
||||
settings = YamlConfigurations.update(
|
||||
settingsFile.toPath(),
|
||||
Settings.class,
|
||||
properties
|
||||
);
|
||||
try {
|
||||
settings = YamlConfigurations.update(
|
||||
settingsFile.toPath(),
|
||||
Settings.class,
|
||||
PROPERTIES
|
||||
);
|
||||
checkData();
|
||||
return Optional.empty();
|
||||
} catch (Exception e) {
|
||||
return Optional.of(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
final YamlConfigurationProperties properties = ConfigLib.BUKKIT_DEFAULT_PROPERTIES.toBuilder()
|
||||
.footer("Authors: AlexDev_")
|
||||
.build();
|
||||
settings = YamlConfigurations.load(new File(plugin.getDataFolder(), "settings.yml").toPath(), Settings.class, properties);
|
||||
settings = YamlConfigurations.load(new File(plugin.getDataFolder(), "settings.yml").toPath(), Settings.class, PROPERTIES);
|
||||
checkData();
|
||||
}
|
||||
|
||||
private void checkData() {
|
||||
if (settings == null) {
|
||||
throw new IllegalStateException("Settings not loaded");
|
||||
}
|
||||
|
||||
if (settings.getDefaultNameTag().isEmpty()) {
|
||||
throw new IllegalStateException("Default name tag is empty");
|
||||
}
|
||||
|
||||
final Map<String, Settings.NameTag> nameTags = Maps.newLinkedHashMap();
|
||||
boolean save = false;
|
||||
|
||||
for (Map.Entry<String, Settings.NameTag> entry : settings.getNameTags().entrySet()) {
|
||||
final Settings.NameTag nameTag = entry.getValue();
|
||||
if (nameTag.scale() <= 0) {
|
||||
plugin.getLogger().warning("Nametag scale is less than or equal to 0");
|
||||
nameTags.put(entry.getKey(), new Settings.NameTag(nameTag.permission(), nameTag.linesGroups(), nameTag.background(), 1f));
|
||||
save = true;
|
||||
} else {
|
||||
nameTags.put(entry.getKey(), nameTag);
|
||||
}
|
||||
}
|
||||
|
||||
if (save) {
|
||||
settings.getNameTags().clear();
|
||||
settings.getNameTags().putAll(nameTags);
|
||||
save();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void save() {
|
||||
YamlConfigurations.save(new File(plugin.getDataFolder(), "settings.yml").toPath(), Settings.class, settings, PROPERTIES);
|
||||
}
|
||||
}
|
||||
@@ -1,61 +1,85 @@
|
||||
/*
|
||||
* This file is part of Velocitab, licensed under the Apache License 2.0.
|
||||
*
|
||||
* Copyright (c) William278 <will27528@gmail.com>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* http://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.
|
||||
*/
|
||||
|
||||
package org.alexdev.unlimitednametags.config;
|
||||
|
||||
import de.themoep.minedown.adventure.MineDown;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.hook.MiniPlaceholdersHook;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Different formatting markup options for the TAB list
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public enum Formatter {
|
||||
|
||||
MINEDOWN(
|
||||
(text) -> new MineDown(text).toComponent(),
|
||||
(plugin, player, text) -> new MineDown(text).toComponent(),
|
||||
"MineDown"
|
||||
),
|
||||
MINIMESSAGE(
|
||||
(text) -> MiniMessage.miniMessage().deserialize(text),
|
||||
(plugin, player, text) -> plugin.getHook(MiniPlaceholdersHook.class)
|
||||
.map(hook -> hook.format(text, player))
|
||||
.orElse(MiniMessage.miniMessage().deserialize(text)),
|
||||
"MiniMessage"
|
||||
),
|
||||
LEGACY(
|
||||
(text) -> LegacyComponentSerializer.legacyAmpersand().deserialize(text),
|
||||
(plugin, player, text) -> getSTUPID().deserialize(replaceHexColorCodes(text)),
|
||||
"Legacy Text"
|
||||
),
|
||||
UNIVERSAL(
|
||||
(plugin, player, text) -> {
|
||||
final String legacy = getHEX().serialize(getSTUPID().deserialize(replaceHexColorCodes(text)));
|
||||
final Component component = getHEX().deserialize(legacy);
|
||||
final String string = MiniMessage.miniMessage().serialize(component).replace("\\<", "<").replace("\\", "");
|
||||
return MINIMESSAGE.formatter.apply(plugin, player, string);
|
||||
},
|
||||
"Universal"
|
||||
);
|
||||
|
||||
@NotNull
|
||||
private static String replaceHexColorCodes(@NotNull String text) {
|
||||
return text.replace('§', '&');
|
||||
}
|
||||
|
||||
/**
|
||||
* Name of the formatter
|
||||
*/
|
||||
@Getter
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Function to apply formatting to a string
|
||||
*/
|
||||
private final Function<String, Component> formatter;
|
||||
private final TriFunction<UnlimitedNameTags, CommandSender, String, Component> formatter;
|
||||
|
||||
Formatter(@NotNull Function<String, Component> formatter, @NotNull String name) {
|
||||
@Getter(value = AccessLevel.PRIVATE)
|
||||
private final static Pattern HEX_PATTERN = Pattern.compile("&#[a-fA-F0-9]{6}");
|
||||
@Getter(value = AccessLevel.PRIVATE)
|
||||
private final static String LEGACY_RESET = "&r";
|
||||
@Getter(value = AccessLevel.PRIVATE)
|
||||
private final static String REPLACE_RESET = "###RESET###";
|
||||
@Getter(value = AccessLevel.PRIVATE)
|
||||
private final static LegacyComponentSerializer STUPID = LegacyComponentSerializer.builder()
|
||||
.character('&')
|
||||
.hexCharacter('#')
|
||||
.useUnusualXRepeatedCharacterHexFormat()
|
||||
.hexColors()
|
||||
.build();
|
||||
@Getter(value = AccessLevel.PRIVATE)
|
||||
private final static LegacyComponentSerializer HEX = LegacyComponentSerializer.builder()
|
||||
.character('&')
|
||||
.hexCharacter('#')
|
||||
.hexColors()
|
||||
.build();
|
||||
|
||||
Formatter(@NotNull TriFunction<UnlimitedNameTags, CommandSender, String, Component> formatter, @NotNull String name) {
|
||||
this.formatter = formatter;
|
||||
this.name = name;
|
||||
}
|
||||
@@ -66,14 +90,8 @@ public enum Formatter {
|
||||
* @param text the string to format
|
||||
* @return the formatted string
|
||||
*/
|
||||
public Component format(@NotNull String text) {
|
||||
return formatter.apply(text);
|
||||
}
|
||||
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
public Component format(@NotNull UnlimitedNameTags plugin, @NotNull CommandSender audience, @NotNull String text) {
|
||||
return formatter.apply(plugin, audience, text);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,21 +2,37 @@ package org.alexdev.unlimitednametags.config;
|
||||
|
||||
import de.exlll.configlib.Comment;
|
||||
import de.exlll.configlib.Configuration;
|
||||
import de.exlll.configlib.Polymorphic;
|
||||
import de.exlll.configlib.PolymorphicTypes;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
import me.tofaa.entitylib.meta.display.AbstractDisplayMeta;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
|
||||
@Configuration
|
||||
@SuppressWarnings({"FieldMayBeFinal", "FieldCanBeLocal"})
|
||||
@Getter
|
||||
public class Settings {
|
||||
|
||||
private Map<String, NameTag> nameTags = Map.of(
|
||||
"staffer", new NameTag("nametag.staffer", List.of("%luckperms_prefix% %player_name% %luckperms_suffix%")),
|
||||
"default", new NameTag("nametag.default", List.of("%luckperms_prefix% %player_name% %luckperms_suffix%", "%vault_eco_balance_formatted%"))
|
||||
);
|
||||
private Map<String, NameTag> nameTags = new LinkedHashMap<>() {{
|
||||
put("staffer", new NameTag("nametag.staffer", List.of(new LinesGroup(List.of("%luckperms_prefix% %player_name% %luckperms_suffix%"), List.of(new GlobalModifier(true)))),
|
||||
new IntegerBackground(true, 255, 0, 0, 255, true, false), 1f));
|
||||
put("default", new NameTag("nametag.default", List.of(new LinesGroup(List.of("%luckperms_prefix% %player_name% %luckperms_suffix%"), List.of(new GlobalModifier(true))),
|
||||
new LinesGroup(List.of("Rich Player"), List.of(new ConditionalModifier("%vault_eco_balance%", ">", "1000")))),
|
||||
new HexBackground(false, "#ffffff", 255, false, false), 1f));
|
||||
}};
|
||||
|
||||
@Setter
|
||||
@Comment("The default billboard constraints for the nametag. CENTER, HORIZONTAL, VERTICAL, FIXED)")
|
||||
private AbstractDisplayMeta.BillboardConstraints defaultBillboard = AbstractDisplayMeta.BillboardConstraints.CENTER;
|
||||
|
||||
public NameTag getNametag(Player player) {
|
||||
return nameTags.entrySet().stream()
|
||||
@@ -26,24 +42,163 @@ public class Settings {
|
||||
.orElse(nameTags.get("default"));
|
||||
}
|
||||
|
||||
protected Optional<NameTag> getDefaultNameTag() {
|
||||
return Optional.ofNullable(nameTags.get("default"));
|
||||
}
|
||||
|
||||
private int taskInterval = 20;
|
||||
|
||||
@Comment(value = {"This is opacity that will be applied to the nametag when a player sneaks. So, the value is from -128 to 127. ",
|
||||
"Similar to the background, the text rendering is discarded when it is less than 26. Defaults to -1, which represents 255 and is completely opaque."})
|
||||
private int sneakOpacity = 70;
|
||||
private float yOffset = 0.7f;
|
||||
private float yOffset = 0.3f;
|
||||
private float viewDistance = 60;
|
||||
|
||||
@Comment("The format of the nametag. Can be either LEGACY, MINEDOWN or MINIMESSAGE")
|
||||
private Formatter format = Formatter.LEGACY;
|
||||
@Comment("""
|
||||
Which text formatter to use (MINIMESSAGE, MINEDOWN, LEGACY or UNIVERSAL)\s
|
||||
Take note that UNIVERSAL is the most resource intensive but it supports all formatting options (except for MINEDOWN)\s
|
||||
|
||||
@Comment("Whether to disable the default name tag or not. Only works if PacketEvents is installed.")
|
||||
private boolean disableDefaultNameTag = false;
|
||||
(&x&0&8&4&c&f&bc LEGACY OF LEGACY - Tcfbc LEGACY - Tcfbc& MINEDOWN - <color:#084cfbc> MINIMESSAGE)""")
|
||||
@Setter
|
||||
private Formatter format = Formatter.MINIMESSAGE;
|
||||
|
||||
@Comment("Whether to disable the default name tag or not.")
|
||||
private boolean disableDefaultNameTag = true;
|
||||
|
||||
private boolean removeEmptyLines = true;
|
||||
|
||||
@Comment("Whether to see the NameTag of a user only while pointing at them")
|
||||
private boolean showWhileLooking = false;
|
||||
|
||||
@Comment("Whether to see your own NameTag (Similar to nametag mod of Lunar Client)")
|
||||
private boolean showCurrentNameTag = false;
|
||||
|
||||
public float getViewDistance() {
|
||||
return viewDistance / 160;
|
||||
}
|
||||
|
||||
public record NameTag(String permission, List<String> lines) {
|
||||
private Map<String, List<PlaceholderReplacement>> placeholdersReplacements = new LinkedHashMap<>() {{
|
||||
put("%advancedvanish_is_vanished%", List.of(new PlaceholderReplacement("Yes", " &7[V]&r"), new PlaceholderReplacement("No", "")));
|
||||
}};
|
||||
|
||||
|
||||
public record PlaceholderReplacement(String placeholder, String replacement) {
|
||||
}
|
||||
|
||||
public record NameTag(String permission, List<LinesGroup> linesGroups, Background background, float scale) {
|
||||
}
|
||||
|
||||
public record LinesGroup(List<String> lines, List<Modifier> modifiers) {
|
||||
|
||||
}
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@Accessors(fluent = true)
|
||||
@Polymorphic
|
||||
@PolymorphicTypes({
|
||||
@PolymorphicTypes.Type(type = GlobalModifier.class, alias = "global"),
|
||||
@PolymorphicTypes.Type(type = ConditionalModifier.class, alias = "conditional")
|
||||
})
|
||||
@Configuration
|
||||
public abstract static class Modifier {
|
||||
|
||||
public abstract boolean isVisible(@NotNull Player player, @NotNull UnlimitedNameTags plugin);
|
||||
|
||||
}
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class GlobalModifier extends Modifier {
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
@Override
|
||||
public boolean isVisible(@NotNull Player player, @NotNull UnlimitedNameTags plugin) {
|
||||
return enabled;
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class ConditionalModifier extends Modifier {
|
||||
|
||||
private String parameter;
|
||||
private String condition;
|
||||
private String value;
|
||||
|
||||
public String getExpression() {
|
||||
return parameter + " " + condition + " " + value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible(@NotNull Player player, @NotNull UnlimitedNameTags plugin) {
|
||||
return plugin.getConditionalManager().evaluateExpression(this, player);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Accessors(fluent = true)
|
||||
@Polymorphic
|
||||
@PolymorphicTypes({
|
||||
@PolymorphicTypes.Type(type = IntegerBackground.class, alias = "integer"),
|
||||
@PolymorphicTypes.Type(type = HexBackground.class, alias = "hex")
|
||||
})
|
||||
@Configuration
|
||||
public static class Background {
|
||||
|
||||
protected boolean enabled;
|
||||
protected int opacity;
|
||||
protected boolean shadowed;
|
||||
protected boolean seeThrough;
|
||||
|
||||
public Color getColor() {
|
||||
return Color.BLACK.setAlpha(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
public static class IntegerBackground extends Background {
|
||||
|
||||
private int red;
|
||||
private int green;
|
||||
private int blue;
|
||||
|
||||
public IntegerBackground(boolean enabled, int red, int green, int blue, int opacity, boolean shadowed, boolean seeThrough) {
|
||||
super(enabled, opacity, shadowed, seeThrough);
|
||||
this.red = red;
|
||||
this.green = green;
|
||||
this.blue = blue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Color getColor() {
|
||||
return !enabled ? Color.BLACK.setAlpha(0) : Color.fromRGB(red, green, blue).setAlpha(opacity);
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class HexBackground extends Background {
|
||||
|
||||
private String hex;
|
||||
|
||||
public HexBackground(boolean enabled, String hex, int opacity, boolean shadowed, boolean seeThrough) {
|
||||
super(enabled, opacity, shadowed, seeThrough);
|
||||
this.hex = hex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Color getColor() {
|
||||
int hex = Integer.parseInt(this.hex.substring(1), 16);
|
||||
return !enabled ? Color.BLACK.setAlpha(0) : Color.fromRGB(hex).setAlpha(opacity);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.alexdev.unlimitednametags.config;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface TriFunction<T, U, V, R> {
|
||||
R apply(T t, U u, V v);
|
||||
}
|
||||
@@ -2,95 +2,89 @@ package org.alexdev.unlimitednametags.events;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
|
||||
import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.util.FakeChannelUtil;
|
||||
import com.github.retrooper.packetevents.util.Vector3f;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientEntityAction;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPassengers;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerTeams;
|
||||
import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
|
||||
import io.github.retrooper.packetevents.injector.SpigotChannelInjector;
|
||||
import io.github.retrooper.packetevents.util.FoliaCompatUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.hook.ViaVersionHook;
|
||||
import org.alexdev.unlimitednametags.packet.PacketNameTag;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.TextDisplay;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class PacketEventsListener extends PacketListenerAbstract {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
|
||||
public void onLoad() {
|
||||
PacketEvents.setAPI(SpigotPacketEventsBuilder.build(plugin));
|
||||
//Are all listeners read only?
|
||||
PacketEvents.getAPI().getSettings().reEncodeByDefault(false)
|
||||
.checkForUpdates(true)
|
||||
.bStats(true);
|
||||
PacketEvents.getAPI().load();
|
||||
public PacketEventsListener(UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
PacketEvents.getAPI().getEventManager().registerListener(this);
|
||||
PacketEvents.getAPI().init();
|
||||
inject();
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void inject() {
|
||||
Bukkit.getOnlinePlayers().forEach(player -> {
|
||||
SpigotChannelInjector injector = (SpigotChannelInjector) PacketEvents.getAPI().getInjector();
|
||||
|
||||
User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user == null) {
|
||||
//We did not inject this user
|
||||
Object channel = PacketEvents.getAPI().getPlayerManager().getChannel(player);
|
||||
//Check if it is a fake connection...
|
||||
if (!FakeChannelUtil.isFakeChannel(channel)) {
|
||||
//Kick them, if they are not a fake player.
|
||||
FoliaCompatUtil.runTaskForEntity(player, plugin, () -> player.kickPlayer("PacketEvents 2.0 failed to inject"), null, 0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Set bukkit player object in the injectors
|
||||
injector.updatePlayer(user, player);
|
||||
});
|
||||
}
|
||||
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
if (event.getPacketType() == PacketType.Play.Server.ENTITY_METADATA) {
|
||||
handleMetaData(event);
|
||||
} else if (event.getPacketType() == PacketType.Play.Server.TEAMS) {
|
||||
public void onPacketSend(@NotNull PacketSendEvent event) {
|
||||
if (event.getPacketType() == PacketType.Play.Server.TEAMS) {
|
||||
handleTeams(event);
|
||||
} else if (event.getPacketType() == PacketType.Play.Server.SET_PASSENGERS) {
|
||||
handlePassengers(event);
|
||||
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_METADATA) {
|
||||
handleMetaData(event);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleMetaData(@NotNull PacketSendEvent event) {
|
||||
if(event.getUser().getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_20_2)) {
|
||||
return;
|
||||
@Override
|
||||
public void onPacketReceive(@NotNull PacketReceiveEvent event) {
|
||||
if (event.getPacketType() == PacketType.Play.Client.ENTITY_ACTION) {
|
||||
handleUseEntity(event);
|
||||
}
|
||||
final WrapperPlayServerEntityMetadata packet = new WrapperPlayServerEntityMetadata(event);
|
||||
final @NotNull Optional<TextDisplay> textDisplay = plugin.getNametagManager().getEntityById(packet.getEntityId());
|
||||
}
|
||||
|
||||
if (textDisplay.isEmpty()) {
|
||||
private void handleUseEntity(PacketReceiveEvent event) {
|
||||
if (!(event.getPlayer() instanceof Player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (final EntityData eData : packet.getEntityMetadata()) {
|
||||
if (eData.getIndex() == 10) {
|
||||
final Vector3f old = (Vector3f) eData.getValue();
|
||||
final Vector3f newV = new Vector3f(old.getX(), old.getY() + 0.45f, old.getZ());
|
||||
eData.setValue(newV);
|
||||
event.markForReEncode(true);
|
||||
return;
|
||||
}
|
||||
final WrapperPlayClientEntityAction packet = new WrapperPlayClientEntityAction(event);
|
||||
final Optional<? extends Player> player = plugin.getPlayerListener().getPlayerFromEntityId(packet.getEntityId());
|
||||
if (player.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
switch (packet.getAction()) {
|
||||
case START_SNEAKING -> plugin.getNametagManager().updateSneaking(player.get(), true);
|
||||
case STOP_SNEAKING -> plugin.getNametagManager().updateSneaking(player.get(), false);
|
||||
case START_FLYING_WITH_ELYTRA -> plugin.getPlayerListener().logicElytra(player.get());
|
||||
}
|
||||
}
|
||||
|
||||
private void handlePassengers(@NotNull PacketSendEvent event) {
|
||||
final WrapperPlayServerSetPassengers packet = new WrapperPlayServerSetPassengers(event);
|
||||
final Optional<? extends Player> player = plugin.getPlayerListener().getPlayerFromEntityId(packet.getEntityId());
|
||||
if (player.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Optional<PacketNameTag> optionalPacketDisplayText = plugin.getNametagManager().getPacketDisplayText(player.get());
|
||||
if (optionalPacketDisplayText.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Integer> passengers = Arrays.stream(packet.getPassengers()).boxed().collect(Collectors.toList());
|
||||
|
||||
plugin.getPacketManager().setPassengers(player.get(), passengers);
|
||||
if(!passengers.contains(optionalPacketDisplayText.get().getEntityId())) {
|
||||
passengers.add(optionalPacketDisplayText.get().getEntityId());
|
||||
packet.setPassengers(passengers.stream().mapToInt(i -> i).toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,10 +93,50 @@ public class PacketEventsListener extends PacketListenerAbstract {
|
||||
return;
|
||||
}
|
||||
|
||||
final Player player = Bukkit.getPlayer(event.getUser().getUUID());
|
||||
if(player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(plugin.getHook(ViaVersionHook.class).map(h -> h.hasNotTextDisplays(player)).orElse(false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final WrapperPlayServerTeams packet = new WrapperPlayServerTeams(event);
|
||||
if (packet.getTeamMode() == WrapperPlayServerTeams.TeamMode.CREATE || packet.getTeamMode() == WrapperPlayServerTeams.TeamMode.UPDATE) {
|
||||
packet.getTeamInfo().ifPresent(t -> t.setTagVisibility(WrapperPlayServerTeams.NameTagVisibility.NEVER));
|
||||
event.markForReEncode(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleMetaData(@NotNull PacketSendEvent event) {
|
||||
if (!(event.getPlayer() instanceof Player)) {
|
||||
return;
|
||||
}
|
||||
int protocol = event.getUser().getClientVersion().getProtocolVersion();
|
||||
//handle metadata for : bedrock players && client with version 1.20.1 or lower
|
||||
if (protocol >= 764) {
|
||||
return;
|
||||
}
|
||||
|
||||
final WrapperPlayServerEntityMetadata packet = new WrapperPlayServerEntityMetadata(event);
|
||||
final Optional<PacketNameTag> textDisplay = plugin.getNametagManager().getPacketDisplayText(packet.getEntityId());
|
||||
if (textDisplay.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (final EntityData eData : packet.getEntityMetadata()) {
|
||||
if (eData.getIndex() == 11) {
|
||||
final Vector3f old = (Vector3f) eData.getValue();
|
||||
final Vector3f newV = new Vector3f(old.getX(), old.getY() + 0.45f, old.getZ());
|
||||
eData.setValue(newV);
|
||||
event.markForReEncode(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
PacketEvents.getAPI().getEventManager().unregisterListener(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.alexdev.unlimitednametags.events;
|
||||
|
||||
import io.papermc.paper.event.player.PlayerTrackEntityEvent;
|
||||
import io.papermc.paper.event.player.PlayerUntrackEntityEvent;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class PaperTrackerListener implements Listener {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
|
||||
@EventHandler
|
||||
public void onTrack(@NotNull PlayerTrackEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!target.isOnline()) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getTrackerManager().handleAdd(event.getPlayer(), target);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onUnTrack(@NotNull PlayerUntrackEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getTrackerManager().handleRemove(event.getPlayer(), target);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,127 +1,193 @@
|
||||
package org.alexdev.unlimitednametags.events;
|
||||
|
||||
import com.github.Anon8281.universalScheduler.foliaScheduler.FoliaScheduler;
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Sets;
|
||||
import lombok.Getter;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.hook.PackSendHandler;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.entity.TextDisplay;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityPotionEffectEvent;
|
||||
import org.bukkit.event.entity.PlayerDeathEvent;
|
||||
import org.bukkit.event.player.*;
|
||||
import org.spigotmc.event.entity.EntityDismountEvent;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class PlayerListener implements PackSendHandler {
|
||||
|
||||
public class PlayerListener implements Listener {
|
||||
|
||||
@Getter
|
||||
private final UnlimitedNameTags plugin;
|
||||
private final Set<UUID> ejectCache;
|
||||
private final Set<UUID> diedPlayers;
|
||||
private final Map<Integer, UUID> playerEntityId;
|
||||
|
||||
public PlayerListener(UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
this.ejectCache = Sets.newConcurrentHashSet();
|
||||
this.diedPlayers = Sets.newConcurrentHashSet();
|
||||
this.playerEntityId = Maps.newConcurrentMap();
|
||||
this.loadFoliaRespawnTask();
|
||||
this.loadEntityIds();
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
plugin.getNametagManager().addPlayer(event.getPlayer());
|
||||
private void loadEntityIds() {
|
||||
Bukkit.getOnlinePlayers().forEach(player -> playerEntityId.put(player.getEntityId(), player.getUniqueId()));
|
||||
}
|
||||
|
||||
plugin.getNametagManager().updateDisplaysForPlayer(event.getPlayer());
|
||||
private void loadFoliaRespawnTask() {
|
||||
if (!(plugin.getTaskScheduler() instanceof FoliaScheduler)) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getTaskScheduler().runTaskTimerAsynchronously(() -> diedPlayers.forEach(player -> {
|
||||
final Player p = plugin.getServer().getPlayer(player);
|
||||
if (p == null || p.isDead()) {
|
||||
return;
|
||||
}
|
||||
plugin.getNametagManager().addPlayer(p);
|
||||
diedPlayers.remove(player);
|
||||
}), 1, 1);
|
||||
}
|
||||
|
||||
public Optional<Player> getPlayerFromEntityId(int entityId) {
|
||||
final UUID player = playerEntityId.get(entityId);
|
||||
if (player == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(plugin.getServer().getPlayer(player));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
plugin.getNametagManager().removePlayer(event.getPlayer(), false);
|
||||
public void onJoin(@NotNull PlayerJoinEvent event) {
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> plugin.getNametagManager().addPlayer(event.getPlayer()), 2);
|
||||
playerEntityId.put(event.getPlayer().getEntityId(), event.getPlayer().getUniqueId());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onEject(EntityDismountEvent event) {
|
||||
if (!(event.getEntity() instanceof TextDisplay textDisplay)) return;
|
||||
if (!(event.getDismounted() instanceof Player player)) return;
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onQuit(@NotNull PlayerQuitEvent event) {
|
||||
diedPlayers.remove(event.getPlayer().getUniqueId());
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> plugin.getNametagManager().removePlayer(event.getPlayer(), true), 1);
|
||||
playerEntityId.remove(event.getPlayer().getEntityId());
|
||||
}
|
||||
|
||||
if (!textDisplay.hasMetadata("nametag")) return;
|
||||
@EventHandler
|
||||
public void onPotion(@NotNull EntityPotionEffectEvent event) {
|
||||
if (!(event.getEntity() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ejectCache.contains(player.getUniqueId())) return;
|
||||
if (player.getGameMode() == GameMode.SPECTATOR) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(plugin.getNametagManager().getEjectable().contains(player.getUniqueId())) return;
|
||||
|
||||
ejectCache.add(player.getUniqueId());
|
||||
plugin.getServer().getScheduler().runTaskLater(plugin, () -> {
|
||||
if (player.isOnline()) {
|
||||
plugin.getNametagManager().teleportAndApply(player);
|
||||
if (event.getAction() == EntityPotionEffectEvent.Action.ADDED) {
|
||||
if (event.getNewEffect() == null || event.getNewEffect().getType() != PotionEffectType.INVISIBILITY) {
|
||||
return;
|
||||
}
|
||||
}, 3);
|
||||
plugin.getNametagManager().removeAllViewers(player);
|
||||
} else if (event.getAction() == EntityPotionEffectEvent.Action.REMOVED || event.getAction() == EntityPotionEffectEvent.Action.CLEARED) {
|
||||
if (event.getOldEffect() == null || event.getOldEffect().getType() != PotionEffectType.INVISIBILITY) {
|
||||
return;
|
||||
}
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> {
|
||||
plugin.getNametagManager().unblockPlayer(player);
|
||||
plugin.getNametagManager().showToTrackedPlayers(player, plugin.getTrackerManager().getTrackedPlayers().get(player.getUniqueId()));
|
||||
}, 1);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onTeleportComplete(PlayerTeleportEvent event) {
|
||||
plugin.getNametagManager().teleportAndApply(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onSneak(PlayerToggleSneakEvent event) {
|
||||
plugin.getNametagManager().updateSneaking(event.getPlayer(), event.isSneaking());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onGameModeChange(PlayerGameModeChangeEvent e) {
|
||||
public void onGameModeChange(@NotNull PlayerGameModeChangeEvent e) {
|
||||
if (e.getPlayer().getGameMode() == GameMode.SPECTATOR) {
|
||||
plugin.getNametagManager().addPlayer(e.getPlayer());
|
||||
plugin.getNametagManager().showToTrackedPlayers(e.getPlayer(), plugin.getTrackerManager().getTrackedPlayers().get(e.getPlayer().getUniqueId()));
|
||||
} else if (e.getNewGameMode() == GameMode.SPECTATOR) {
|
||||
plugin.getNametagManager().removePlayer(e.getPlayer(), true);
|
||||
plugin.getNametagManager().removeAllViewers(e.getPlayer());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerDeath(PlayerDeathEvent event) {
|
||||
plugin.getNametagManager().removePlayer(event.getEntity(), false);
|
||||
public void onPlayerDeath(@NotNull PlayerDeathEvent event) {
|
||||
diedPlayers.add(event.getEntity().getUniqueId());
|
||||
plugin.getNametagManager().removeAllViewers(event.getEntity());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerRespawn(PlayerRespawnEvent event) {
|
||||
plugin.getNametagManager().addPlayer(event.getPlayer());
|
||||
public void onPlayerRespawn(@NotNull PlayerRespawnEvent event) {
|
||||
diedPlayers.remove(event.getPlayer().getUniqueId());
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> {
|
||||
plugin.getNametagManager().getPacketDisplayText(event.getPlayer()).ifPresent(d -> d.setVisible(true));
|
||||
}, 1);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onMove(PlayerMoveEvent event) {
|
||||
|
||||
if (!event.hasChangedPosition()) return;
|
||||
|
||||
final org.bukkit.util.BoundingBox playerBoundingBox = event.getPlayer().getBoundingBox();
|
||||
final World world = event.getPlayer().getWorld();
|
||||
final Location loc1 = new Location(world, playerBoundingBox.getMaxX(), playerBoundingBox.getMaxY(), playerBoundingBox.getMaxZ());
|
||||
final Location loc2 = loc1.clone().subtract(0, 1, 0);
|
||||
final Location loc3 = new Location(world, playerBoundingBox.getMinX(), playerBoundingBox.getMinY(), playerBoundingBox.getMinZ());
|
||||
final Location loc4 = loc3.clone().add(0, 1, 0);
|
||||
|
||||
boolean inPortal = false;
|
||||
for (final Location loc : new Location[]{loc1, loc2, loc3, loc4}) {
|
||||
final Block block = loc.getBlock();
|
||||
if (
|
||||
block.getType() == Material.NETHER_PORTAL
|
||||
|| block.getType() == Material.END_PORTAL
|
||||
|| block.getType() == Material.END_GATEWAY
|
||||
) {
|
||||
inPortal = true;
|
||||
break;
|
||||
}
|
||||
@EventHandler
|
||||
public void onPlayerVanishes(@NotNull PlayerShowEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (inPortal) {
|
||||
event.getPlayer().eject();
|
||||
plugin.getNametagManager().removePlayer(event.getPlayer(), false);
|
||||
} else {
|
||||
plugin.getNametagManager().addPlayer(event.getPlayer());
|
||||
if (plugin.getConfigManager().getSettings().isShowWhileLooking()) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getNametagManager().getPacketDisplayText(player).ifPresent(display -> {
|
||||
display.showToPlayer(event.getPlayer());
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerUnvanishes(@NotNull PlayerHideEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getNametagManager().getPacketDisplayText(player).ifPresent(display -> {
|
||||
display.hideFromPlayer(event.getPlayer());
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTeleport(@NotNull PlayerTeleportEvent event) {
|
||||
//1.20.1+ bug
|
||||
if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_21_1) &&
|
||||
event.getFrom().getWorld() != event.getTo().getWorld()
|
||||
) {
|
||||
plugin.getTrackerManager().forceUntrack(event.getPlayer());
|
||||
}
|
||||
if (!plugin.getConfigManager().getSettings().isShowCurrentNameTag()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.getFrom().getWorld() == event.getTo().getWorld() && event.getFrom().distance(event.getTo()) <= 80) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.getPlayer().getGameMode() == GameMode.SPECTATOR) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> plugin.getNametagManager().showToOwner(event.getPlayer()), 5);
|
||||
}
|
||||
|
||||
public void logicElytra(Player player) {
|
||||
if (!plugin.getConfigManager().getSettings().isShowCurrentNameTag()) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getNametagManager().getPacketDisplayText(player).ifPresent(packetDisplayText -> {
|
||||
packetDisplayText.hideForOwner();
|
||||
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(packetDisplayText::showForOwner, 5);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package org.alexdev.unlimitednametags.events;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.purpurmc.purpur.event.entity.EntityTeleportHinderedEvent;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@SuppressWarnings("unused")
|
||||
public class PurpurListener implements Listener {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
|
||||
@EventHandler()
|
||||
public void onTeleportCancelled(EntityTeleportHinderedEvent e) {
|
||||
if (e.getReason() != EntityTeleportHinderedEvent.Reason.IS_VEHICLE) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(!(e.getEntity() instanceof Player player)) return;
|
||||
|
||||
player.eject();
|
||||
e.setShouldRetry(true);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package org.alexdev.unlimitednametags.events;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class SpigotTrackerListener implements Listener {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
|
||||
public SpigotTrackerListener(UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
startCheckTask();
|
||||
}
|
||||
|
||||
private void startCheckTask() {
|
||||
plugin.getTaskScheduler().runTaskTimerAsynchronously(() -> {
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
final Set<UUID> trackedPlayers = plugin.getTrackerManager().getTrackedPlayers(player.getUniqueId());
|
||||
final Set<UUID> current = player.getTrackedBy().stream()
|
||||
.map(Player::getUniqueId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
final Set<UUID> toRemove = Sets.difference(trackedPlayers, current);
|
||||
final Set<UUID> toAdd = Sets.difference(current, trackedPlayers);
|
||||
|
||||
toRemove.stream()
|
||||
.map(Bukkit::getPlayer)
|
||||
.filter(Objects::nonNull)
|
||||
.forEach(p -> plugin.getTrackerManager().handleRemove(player, p));
|
||||
|
||||
toAdd.stream()
|
||||
.map(Bukkit::getPlayer)
|
||||
.filter(Objects::nonNull)
|
||||
.forEach(p -> plugin.getTrackerManager().handleAdd(player, p));
|
||||
}
|
||||
}, 0, 5);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
private void onQuit(PlayerQuitEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
plugin.getTrackerManager().handleQuit(player);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package org.alexdev.unlimitednametags.events;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.google.common.collect.*;
|
||||
import lombok.Getter;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.packet.PacketNameTag;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class TrackerManager {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
@Getter
|
||||
private final SetMultimap<UUID, UUID> trackedPlayers;
|
||||
|
||||
public TrackerManager(UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
this.trackedPlayers = Multimaps.newSetMultimap(Maps.newConcurrentMap(), Sets::newConcurrentHashSet);
|
||||
loadTracker();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"deprecation"})
|
||||
private void loadTracker() {
|
||||
final boolean isPaper = plugin.isPaper();
|
||||
Bukkit.getOnlinePlayers().forEach(player -> {
|
||||
final Set<Player> currentTracked = (isPaper ? player.getTrackedPlayers() : player.getTrackedBy()).stream()
|
||||
.filter(p -> Bukkit.getPlayer(p.getUniqueId()) != null)
|
||||
.collect(ImmutableSet.toImmutableSet());
|
||||
trackedPlayers.putAll(player.getUniqueId(), currentTracked
|
||||
.stream()
|
||||
.map(Player::getUniqueId)
|
||||
.collect(ImmutableSet.toImmutableSet()));
|
||||
});
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
trackedPlayers.clear();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<UUID> getTrackedPlayers(@NotNull UUID player) {
|
||||
return trackedPlayers.get(player);
|
||||
}
|
||||
|
||||
public void handleAdd(@NotNull Player player, @NotNull Player target) {
|
||||
if (!target.isConnected()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a real player
|
||||
if (Bukkit.getPlayer(target.getUniqueId()) == null || Bukkit.getPlayer(player.getUniqueId()) == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (PacketEvents.getAPI().getPlayerManager().getUser(target) == null || PacketEvents.getAPI().getPlayerManager().getUser(player) == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> {
|
||||
trackedPlayers.put(player.getUniqueId(), target.getUniqueId());
|
||||
|
||||
final boolean isVanished = plugin.getVanishManager().isVanished(target);
|
||||
if (isVanished && !plugin.getVanishManager().canSee(player, target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.hasPotionEffect(PotionEffectType.INVISIBILITY)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Optional<PacketNameTag> display = plugin.getNametagManager().getPacketDisplayText(target);
|
||||
|
||||
if (display.isEmpty()) {
|
||||
// plugin.getLogger().warning("Display is empty for " + target.getName());
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getNametagManager().updateDisplay(player, target);
|
||||
}, 3);
|
||||
|
||||
}
|
||||
|
||||
public void handleRemove(@NotNull Player player, @NotNull Player target) {
|
||||
plugin.getTaskScheduler().runTaskAsynchronously(() -> {
|
||||
trackedPlayers.remove(player.getUniqueId(), target.getUniqueId());
|
||||
|
||||
plugin.getNametagManager().removeDisplay(player, target);
|
||||
});
|
||||
}
|
||||
|
||||
public void handleQuit(@NotNull Player player) {
|
||||
plugin.getTaskScheduler().runTaskAsynchronously(() -> {
|
||||
trackedPlayers.removeAll(player.getUniqueId());
|
||||
trackedPlayers.values().remove(player.getUniqueId());
|
||||
});
|
||||
}
|
||||
|
||||
public void forceUntrack(@NotNull Player player) {
|
||||
plugin.getTaskScheduler().runTaskAsynchronously(() -> {
|
||||
trackedPlayers.get(player.getUniqueId())
|
||||
.stream()
|
||||
.map(Bukkit::getPlayer)
|
||||
.filter(Objects::nonNull)
|
||||
.forEach(p -> handleRemove(p, player));
|
||||
Bukkit.getOnlinePlayers().stream()
|
||||
.filter(p -> trackedPlayers.get(player.getUniqueId()).contains(p.getUniqueId()))
|
||||
.forEach(p -> handleRemove(player, p));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package org.alexdev.unlimitednametags.events;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import me.gabber235.typewriter.events.AsyncCinematicEndEvent;
|
||||
import me.gabber235.typewriter.events.AsyncCinematicStartEvent;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class TypeWriterListener implements Listener {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
|
||||
@EventHandler
|
||||
public void onStart(AsyncCinematicStartEvent event) {
|
||||
plugin.getNametagManager().blockPlayer(event.getPlayer());
|
||||
Bukkit.getScheduler().runTaskLater(plugin,
|
||||
() -> {
|
||||
plugin.getNametagManager().hideAllDisplays(event.getPlayer());
|
||||
plugin.getNametagManager().removePlayer(event.getPlayer(), true);
|
||||
},
|
||||
1);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onEnd(AsyncCinematicEndEvent event) {
|
||||
plugin.getNametagManager().unblockPlayer(event.getPlayer());
|
||||
Bukkit.getScheduler().runTaskLater(plugin,
|
||||
() -> plugin.getNametagManager().addPlayer(event.getPlayer()),
|
||||
1);
|
||||
Bukkit.getScheduler().runTaskLater(plugin,
|
||||
() -> plugin.getNametagManager().updateDisplaysForPlayer(event.getPlayer()),
|
||||
5);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.geysermc.floodgate.api.FloodgateApi;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class FloodgateHook extends Hook {
|
||||
|
||||
private FloodgateApi floodgateAPI;
|
||||
|
||||
public FloodgateHook(UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
floodgateAPI = FloodgateApi.getInstance();
|
||||
}
|
||||
|
||||
public boolean isFloodgatePlayer(@NotNull Player player) {
|
||||
return floodgateAPI.isFloodgatePlayer(player.getUniqueId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.geysermc.geyser.api.GeyserApi;
|
||||
|
||||
public class GeyserHook extends Hook {
|
||||
|
||||
private GeyserApi geyser;
|
||||
|
||||
public GeyserHook(UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
geyser = GeyserApi.api();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
}
|
||||
|
||||
public boolean isBedrockPlayer(Player player) {
|
||||
return geyser.isBedrockPlayer(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import com.hibiscusmc.hmccosmetics.api.HMCCosmeticsAPI;
|
||||
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
|
||||
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
|
||||
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.hook.hat.HatHook;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class HMCCosmeticsHook extends Hook implements HatHook {
|
||||
|
||||
|
||||
public HMCCosmeticsHook(UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public double getHigh(@NotNull Player player) {
|
||||
final CosmeticUser user = HMCCosmeticsAPI.getUser(player.getUniqueId());
|
||||
if (user == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
final Cosmetic cosmetic = user.getCosmetic(CosmeticSlot.HELMET);
|
||||
if (cosmetic == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Getter
|
||||
public abstract class Hook {
|
||||
|
||||
@NotNull
|
||||
protected final UnlimitedNameTags plugin;
|
||||
|
||||
public abstract void onEnable();
|
||||
|
||||
public abstract void onDisable();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import dev.lone.itemsadder.api.Events.ItemsAdderLoadDataEvent;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.hook.hat.HatHook;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@SuppressWarnings("DuplicatedCode")
|
||||
public class ItemsAdderHook extends Hook implements Listener, HatHook {
|
||||
|
||||
private final Map<String, Double> height;
|
||||
|
||||
public ItemsAdderHook(@NotNull UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
this.height = Maps.newConcurrentMap();
|
||||
}
|
||||
|
||||
public double getHigh(@NotNull Player player) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onEnable(ItemsAdderLoadDataEvent event) {
|
||||
height.clear();
|
||||
plugin.getLogger().info("ItemsAdder items loaded, clearing cache");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import io.github.miniplaceholders.api.MiniPlaceholders;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class MiniPlaceholdersHook extends Hook {
|
||||
|
||||
public MiniPlaceholdersHook(@NotNull UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Component format(@NotNull String text, @NotNull Audience player) {
|
||||
return MiniMessage.miniMessage().deserialize(text, MiniPlaceholders.getAudienceGlobalPlaceholders(player));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Component format(@NotNull Component component, @NotNull Audience player) {
|
||||
return format(MiniMessage.miniMessage().serialize(component), player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.nexomc.nexo.api.NexoItems;
|
||||
import com.nexomc.nexo.api.events.NexoItemsLoadedEvent;
|
||||
import com.nexomc.nexo.items.ItemBuilder;
|
||||
import com.nexomc.nexo.items.NexoMeta;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.hook.hat.HatHook;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@SuppressWarnings("DuplicatedCode")
|
||||
public class NexoHook extends Hook implements Listener, HatHook {
|
||||
|
||||
private static final File NEXO_FOLDER = new File("plugins/Nexo/pack/assets/minecraft/models");
|
||||
|
||||
private final Map<String, Double> height;
|
||||
private final Gson jsonParser;
|
||||
|
||||
public NexoHook(@NotNull UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
this.height = Maps.newConcurrentMap();
|
||||
this.jsonParser = new Gson();
|
||||
}
|
||||
|
||||
public double getHigh(@NotNull Player player) {
|
||||
final ItemStack helmet = player.getInventory().getHelmet();
|
||||
if (helmet == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!helmet.hasItemMeta() || !helmet.getItemMeta().hasCustomModelData()) {
|
||||
return 0;
|
||||
}
|
||||
final Optional<ItemBuilder> optionalItemBuilder = findItem(helmet);
|
||||
return optionalItemBuilder.map(itemBuilder -> getHigh(getModelName(itemBuilder.getNexoMeta()) + ".json")).orElse(0.0);
|
||||
}
|
||||
|
||||
private Optional<ItemBuilder> findItem(@NotNull ItemStack item) {
|
||||
return Optional.ofNullable(NexoItems.builderFromItem(item));
|
||||
}
|
||||
|
||||
private String getModelName(@NotNull NexoMeta meta) {
|
||||
return meta.getModelKey().value();
|
||||
}
|
||||
|
||||
private double getHigh(@NotNull String model) {
|
||||
if (height.containsKey(model)) {
|
||||
return height.get(model);
|
||||
}
|
||||
final File file = new File(NEXO_FOLDER, model);
|
||||
if (!file.exists()) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
final JsonObject jsonObject = parseFile(file);
|
||||
final JsonArray elements = jsonObject.getAsJsonArray("elements");
|
||||
if (elements.size() == 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
double highest = 0;
|
||||
for (int i = 0; i < elements.size(); i++) {
|
||||
final JsonObject element = elements.get(i).getAsJsonObject();
|
||||
final double to = element.getAsJsonArray("to").get(1).getAsDouble();
|
||||
if (to > highest) {
|
||||
highest = to;
|
||||
}
|
||||
}
|
||||
|
||||
final JsonObject display = jsonObject.getAsJsonObject("display");
|
||||
if (!display.has("head")) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
final JsonObject head = display.getAsJsonObject("head");
|
||||
final double scale = head.has("scale") ? head.getAsJsonArray("scale").get(1).getAsDouble() : 1;
|
||||
highest *= scale;
|
||||
final double translation = head.has("translation") ? head.getAsJsonArray("translation").get(1).getAsDouble() : 0;
|
||||
|
||||
|
||||
final double value = highest + translation;
|
||||
height.put(model, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private JsonObject parseFile(@NotNull File file) {
|
||||
try (final FileReader reader = new FileReader(file)) {
|
||||
return jsonParser.fromJson(reader, JsonObject.class);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to parse file: " + file, e);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onEnable(NexoItemsLoadedEvent event) {
|
||||
height.clear();
|
||||
plugin.getLogger().info("Nexo items loaded, clearing cache");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import io.th0rgal.oraxen.api.OraxenItems;
|
||||
import io.th0rgal.oraxen.api.events.OraxenItemsLoadedEvent;
|
||||
import io.th0rgal.oraxen.items.ItemBuilder;
|
||||
import io.th0rgal.oraxen.items.OraxenMeta;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.hook.hat.HatHook;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@SuppressWarnings("DuplicatedCode")
|
||||
public class OraxenHook extends Hook implements Listener, HatHook {
|
||||
|
||||
private static final File ORAXEN_FOLDER = new File("plugins/Oraxen/pack/models");
|
||||
|
||||
private final Map<String, Double> height;
|
||||
private final Gson jsonParser;
|
||||
|
||||
public OraxenHook(@NotNull UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
this.height = Maps.newConcurrentMap();
|
||||
this.jsonParser = new Gson();
|
||||
}
|
||||
|
||||
public double getHigh(@NotNull Player player) {
|
||||
final ItemStack helmet = player.getInventory().getHelmet();
|
||||
if (helmet == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!helmet.hasItemMeta() || !helmet.getItemMeta().hasCustomModelData()) {
|
||||
return 0;
|
||||
}
|
||||
final int customModelData = helmet.getItemMeta().getCustomModelData();
|
||||
final Optional<ItemBuilder> optionalItemBuilder = findItem(customModelData, helmet.getType());
|
||||
return optionalItemBuilder.map(itemBuilder -> getHigh(getModelName(itemBuilder.getOraxenMeta()) + ".json")).orElse(0.0);
|
||||
}
|
||||
|
||||
private Optional<ItemBuilder> findItem(int customModelData, @NotNull Material material) {
|
||||
return OraxenItems.getItems().stream()
|
||||
.filter(item -> getCustomModelData(item.getOraxenMeta()) == customModelData)
|
||||
.filter(item -> item.getType() == material)
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private int getCustomModelData(@NotNull OraxenMeta meta) {
|
||||
return meta.getCustomModelData();
|
||||
}
|
||||
|
||||
private String getModelName(OraxenMeta meta) {
|
||||
return meta.getModelName();
|
||||
}
|
||||
|
||||
private double getHigh(@NotNull String model) {
|
||||
if (height.containsKey(model)) {
|
||||
return height.get(model);
|
||||
}
|
||||
final File file = new File(ORAXEN_FOLDER, model);
|
||||
if (!file.exists()) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
final JsonObject jsonObject = parseFile(file);
|
||||
final JsonArray elements = jsonObject.getAsJsonArray("elements");
|
||||
if (elements.size() == 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
double highest = 0;
|
||||
for (int i = 0; i < elements.size(); i++) {
|
||||
final JsonObject element = elements.get(i).getAsJsonObject();
|
||||
final double to = element.getAsJsonArray("to").get(1).getAsDouble();
|
||||
if (to > highest) {
|
||||
highest = to;
|
||||
}
|
||||
}
|
||||
|
||||
final JsonObject display = jsonObject.getAsJsonObject("display");
|
||||
if (!display.has("head")) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
final JsonObject head = display.getAsJsonObject("head");
|
||||
final double scale = head.has("scale") ? head.getAsJsonArray("scale").get(1).getAsDouble() : 1;
|
||||
highest *= scale;
|
||||
final double translation = head.has("translation") ? head.getAsJsonArray("translation").get(1).getAsDouble() : 0;
|
||||
|
||||
|
||||
final double value = highest + translation;
|
||||
height.put(model, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private JsonObject parseFile(@NotNull File file) {
|
||||
try (final FileReader reader = new FileReader(file)) {
|
||||
return jsonParser.fromJson(reader, JsonObject.class);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to parse file: " + file, e);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onEnable(OraxenItemsLoadedEvent event) {
|
||||
height.clear();
|
||||
plugin.getLogger().info("Oraxen items loaded, clearing cache");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface PackSendHandler extends Listener {
|
||||
|
||||
@NotNull
|
||||
UnlimitedNameTags getPlugin();
|
||||
|
||||
@EventHandler
|
||||
default void onPackSend(PlayerResourcePackStatusEvent event) {
|
||||
if(PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_19_4)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(event.getStatus() == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) {
|
||||
getPlugin().getNametagManager().refreshDisplaysForPlayer(event.getPlayer());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
|
||||
import com.typewritermc.engine.paper.events.AsyncCinematicEndEvent;
|
||||
import com.typewritermc.engine.paper.events.AsyncCinematicStartEvent;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TypeWriterListener extends Hook implements Listener {
|
||||
|
||||
public TypeWriterListener(UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onStart(@NotNull AsyncCinematicStartEvent event) {
|
||||
plugin.getNametagManager().blockPlayer(event.getPlayer());
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> plugin.getNametagManager().hideAllDisplays(event.getPlayer()), 1);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onEnd(@NotNull AsyncCinematicEndEvent event) {
|
||||
plugin.getNametagManager().unblockPlayer(event.getPlayer());
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> {
|
||||
plugin.getNametagManager().unBlockForAllPlayers(event.getPlayer());
|
||||
final Set<Player> viewers = plugin.getTrackerManager().getTrackedPlayers(event.getPlayer().getUniqueId())
|
||||
.stream()
|
||||
.map(Bukkit::getPlayer)
|
||||
.filter(p -> p != null && p != event.getPlayer())
|
||||
.collect(Collectors.toSet());
|
||||
plugin.getNametagManager().getPacketDisplayText(event.getPlayer()).ifPresent(display -> display.showToPlayers(viewers));
|
||||
},
|
||||
1);
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(
|
||||
() -> plugin.getNametagManager().updateDisplaysForPlayer(event.getPlayer()), 2);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
Bukkit.getPluginManager().registerEvents(this, plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package org.alexdev.unlimitednametags.hook;
|
||||
|
||||
import com.viaversion.viaversion.api.Via;
|
||||
import com.viaversion.viaversion.api.ViaAPI;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class ViaVersionHook extends Hook {
|
||||
|
||||
private ViaAPI<Player> viaAPI;
|
||||
|
||||
public ViaVersionHook(UnlimitedNameTags plugin) {
|
||||
super(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public void onEnable() {
|
||||
viaAPI = Via.getAPI();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
|
||||
public boolean hasNotTextDisplays(@NotNull Player player) {
|
||||
return viaAPI.getPlayerVersion(player) < 762;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.alexdev.unlimitednametags.hook.hat;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface HatHook {
|
||||
|
||||
/**
|
||||
* Get the height of the player's hat
|
||||
* @param player the player involved
|
||||
* @return the height of the player's hat
|
||||
*/
|
||||
double getHigh(@NotNull Player player);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,882 @@
|
||||
package org.alexdev.unlimitednametags.metrics;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Level;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
public class Metrics {
|
||||
|
||||
private final Plugin plugin;
|
||||
|
||||
private final MetricsBase metricsBase;
|
||||
|
||||
/**
|
||||
* Creates a new Metrics instance.
|
||||
*
|
||||
* @param plugin Your plugin instance.
|
||||
* @param serviceId The id of the service. It can be found at <a
|
||||
* href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
|
||||
*/
|
||||
public Metrics(Plugin plugin, int serviceId) {
|
||||
this.plugin = plugin;
|
||||
// Get the config file
|
||||
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
|
||||
File configFile = new File(bStatsFolder, "config.yml");
|
||||
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
|
||||
if (!config.isSet("serverUuid")) {
|
||||
config.addDefault("enabled", true);
|
||||
config.addDefault("serverUuid", UUID.randomUUID().toString());
|
||||
config.addDefault("logFailedRequests", false);
|
||||
config.addDefault("logSentData", false);
|
||||
config.addDefault("logResponseStatusText", false);
|
||||
// Inform the server owners about bStats
|
||||
config
|
||||
.options()
|
||||
.header(
|
||||
"bStats (https://bStats.org) collects some basic information for plugin authors, like how\n"
|
||||
+ "many people use their plugin and their total player count. It's recommended to keep bStats\n"
|
||||
+ "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n"
|
||||
+ "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n"
|
||||
+ "anonymous.")
|
||||
.copyDefaults(true);
|
||||
try {
|
||||
config.save(configFile);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
// Load the data
|
||||
boolean enabled = true;
|
||||
String serverUUID = config.getString("serverUuid");
|
||||
boolean logErrors = config.getBoolean("logFailedRequests", false);
|
||||
boolean logSentData = config.getBoolean("logSentData", false);
|
||||
boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false);
|
||||
boolean isFolia;
|
||||
try {
|
||||
isFolia = Class.forName("io.papermc.paper.threadedregions.RegionizedServer") != null;
|
||||
} catch (Exception e) {
|
||||
isFolia = false;
|
||||
}
|
||||
metricsBase =
|
||||
new // See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
MetricsBase(
|
||||
"bukkit",
|
||||
serverUUID,
|
||||
serviceId,
|
||||
enabled,
|
||||
this::appendPlatformData,
|
||||
this::appendServiceData,
|
||||
isFolia
|
||||
? null
|
||||
: submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask),
|
||||
plugin::isEnabled,
|
||||
(message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),
|
||||
(message) -> this.plugin.getLogger().log(Level.INFO, message),
|
||||
logErrors,
|
||||
logSentData,
|
||||
logResponseStatusText,
|
||||
false);
|
||||
}
|
||||
|
||||
/** Shuts down the underlying scheduler service. */
|
||||
public void shutdown() {
|
||||
metricsBase.shutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a custom chart.
|
||||
*
|
||||
* @param chart The chart to add.
|
||||
*/
|
||||
public void addCustomChart(CustomChart chart) {
|
||||
metricsBase.addCustomChart(chart);
|
||||
}
|
||||
|
||||
private void appendPlatformData(JsonObjectBuilder builder) {
|
||||
builder.appendField("playerAmount", getPlayerAmount());
|
||||
builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0);
|
||||
builder.appendField("bukkitVersion", Bukkit.getVersion());
|
||||
builder.appendField("bukkitName", Bukkit.getName());
|
||||
builder.appendField("javaVersion", System.getProperty("java.version"));
|
||||
builder.appendField("osName", System.getProperty("os.name"));
|
||||
builder.appendField("osArch", System.getProperty("os.arch"));
|
||||
builder.appendField("osVersion", System.getProperty("os.version"));
|
||||
builder.appendField("coreCount", Runtime.getRuntime().availableProcessors());
|
||||
}
|
||||
|
||||
private void appendServiceData(JsonObjectBuilder builder) {
|
||||
builder.appendField("pluginVersion", plugin.getDescription().getVersion());
|
||||
}
|
||||
|
||||
private int getPlayerAmount() {
|
||||
try {
|
||||
// Around MC 1.8 the return type was changed from an array to a collection,
|
||||
// This fixes java.lang.NoSuchMethodError:
|
||||
// org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
|
||||
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
|
||||
return onlinePlayersMethod.getReturnType().equals(Collection.class)
|
||||
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
|
||||
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
|
||||
} catch (Exception e) {
|
||||
// Just use the new method if the reflection failed
|
||||
return Bukkit.getOnlinePlayers().size();
|
||||
}
|
||||
}
|
||||
|
||||
public static class MetricsBase {
|
||||
|
||||
/** The version of the Metrics class. */
|
||||
public static final String METRICS_VERSION = "3.1.0";
|
||||
|
||||
private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s";
|
||||
|
||||
private final ScheduledExecutorService scheduler;
|
||||
|
||||
private final String platform;
|
||||
|
||||
private final String serverUuid;
|
||||
|
||||
private final int serviceId;
|
||||
|
||||
private final Consumer<JsonObjectBuilder> appendPlatformDataConsumer;
|
||||
|
||||
private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;
|
||||
|
||||
private final Consumer<Runnable> submitTaskConsumer;
|
||||
|
||||
private final Supplier<Boolean> checkServiceEnabledSupplier;
|
||||
|
||||
private final BiConsumer<String, Throwable> errorLogger;
|
||||
|
||||
private final Consumer<String> infoLogger;
|
||||
|
||||
private final boolean logErrors;
|
||||
|
||||
private final boolean logSentData;
|
||||
|
||||
private final boolean logResponseStatusText;
|
||||
|
||||
private final Set<CustomChart> customCharts = new HashSet<>();
|
||||
|
||||
private final boolean enabled;
|
||||
|
||||
/**
|
||||
* Creates a new MetricsBase class instance.
|
||||
*
|
||||
* @param platform The platform of the service.
|
||||
* @param serviceId The id of the service.
|
||||
* @param serverUuid The server uuid.
|
||||
* @param enabled Whether or not data sending is enabled.
|
||||
* @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
|
||||
* appends all platform-specific data.
|
||||
* @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
|
||||
* appends all service-specific data.
|
||||
* @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be
|
||||
* used to delegate the data collection to a another thread to prevent errors caused by
|
||||
* concurrency. Can be {@code null}.
|
||||
* @param checkServiceEnabledSupplier A supplier to check if the service is still enabled.
|
||||
* @param errorLogger A consumer that accepts log message and an error.
|
||||
* @param infoLogger A consumer that accepts info log messages.
|
||||
* @param logErrors Whether or not errors should be logged.
|
||||
* @param logSentData Whether or not the sent data should be logged.
|
||||
* @param logResponseStatusText Whether or not the response status text should be logged.
|
||||
* @param skipRelocateCheck Whether or not the relocate check should be skipped.
|
||||
*/
|
||||
public MetricsBase(
|
||||
String platform,
|
||||
String serverUuid,
|
||||
int serviceId,
|
||||
boolean enabled,
|
||||
Consumer<JsonObjectBuilder> appendPlatformDataConsumer,
|
||||
Consumer<JsonObjectBuilder> appendServiceDataConsumer,
|
||||
Consumer<Runnable> submitTaskConsumer,
|
||||
Supplier<Boolean> checkServiceEnabledSupplier,
|
||||
BiConsumer<String, Throwable> errorLogger,
|
||||
Consumer<String> infoLogger,
|
||||
boolean logErrors,
|
||||
boolean logSentData,
|
||||
boolean logResponseStatusText,
|
||||
boolean skipRelocateCheck) {
|
||||
ScheduledThreadPoolExecutor scheduler =
|
||||
new ScheduledThreadPoolExecutor(
|
||||
1,
|
||||
task -> {
|
||||
Thread thread = new Thread(task, "bStats-Metrics");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
// We want delayed tasks (non-periodic) that will execute in the future to be
|
||||
// cancelled when the scheduler is shutdown.
|
||||
// Otherwise, we risk preventing the server from shutting down even when
|
||||
// MetricsBase#shutdown() is called
|
||||
scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
|
||||
this.scheduler = scheduler;
|
||||
this.platform = platform;
|
||||
this.serverUuid = serverUuid;
|
||||
this.serviceId = serviceId;
|
||||
this.enabled = enabled;
|
||||
this.appendPlatformDataConsumer = appendPlatformDataConsumer;
|
||||
this.appendServiceDataConsumer = appendServiceDataConsumer;
|
||||
this.submitTaskConsumer = submitTaskConsumer;
|
||||
this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;
|
||||
this.errorLogger = errorLogger;
|
||||
this.infoLogger = infoLogger;
|
||||
this.logErrors = logErrors;
|
||||
this.logSentData = logSentData;
|
||||
this.logResponseStatusText = logResponseStatusText;
|
||||
if (!skipRelocateCheck) {
|
||||
checkRelocation();
|
||||
}
|
||||
if (enabled) {
|
||||
// WARNING: Removing the option to opt-out will get your plugin banned from
|
||||
// bStats
|
||||
startSubmitting();
|
||||
}
|
||||
}
|
||||
|
||||
public void addCustomChart(CustomChart chart) {
|
||||
this.customCharts.add(chart);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
scheduler.shutdown();
|
||||
}
|
||||
|
||||
private void startSubmitting() {
|
||||
final Runnable submitTask =
|
||||
() -> {
|
||||
if (!enabled || !checkServiceEnabledSupplier.get()) {
|
||||
// Submitting data or service is disabled
|
||||
scheduler.shutdown();
|
||||
return;
|
||||
}
|
||||
if (submitTaskConsumer != null) {
|
||||
submitTaskConsumer.accept(this::submitData);
|
||||
} else {
|
||||
this.submitData();
|
||||
}
|
||||
};
|
||||
// Many servers tend to restart at a fixed time at xx:00 which causes an uneven
|
||||
// distribution of requests on the
|
||||
// bStats backend. To circumvent this problem, we introduce some randomness into
|
||||
// the initial and second delay.
|
||||
// WARNING: You must not modify and part of this Metrics class, including the
|
||||
// submit delay or frequency!
|
||||
// WARNING: Modifying this code will get your plugin banned on bStats. Just
|
||||
// don't do it!
|
||||
long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));
|
||||
long secondDelay = (long) (1000 * 60 * (Math.random() * 30));
|
||||
scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);
|
||||
scheduler.scheduleAtFixedRate(
|
||||
submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private void submitData() {
|
||||
final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();
|
||||
appendPlatformDataConsumer.accept(baseJsonBuilder);
|
||||
final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();
|
||||
appendServiceDataConsumer.accept(serviceJsonBuilder);
|
||||
JsonObjectBuilder.JsonObject[] chartData =
|
||||
customCharts.stream()
|
||||
.map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))
|
||||
.filter(Objects::nonNull)
|
||||
.toArray(JsonObjectBuilder.JsonObject[]::new);
|
||||
serviceJsonBuilder.appendField("id", serviceId);
|
||||
serviceJsonBuilder.appendField("customCharts", chartData);
|
||||
baseJsonBuilder.appendField("service", serviceJsonBuilder.build());
|
||||
baseJsonBuilder.appendField("serverUUID", serverUuid);
|
||||
baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION);
|
||||
JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();
|
||||
scheduler.execute(
|
||||
() -> {
|
||||
try {
|
||||
// Send the data
|
||||
sendData(data);
|
||||
} catch (Exception e) {
|
||||
// Something went wrong! :(
|
||||
if (logErrors) {
|
||||
errorLogger.accept("Could not submit bStats metrics data", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {
|
||||
if (logSentData) {
|
||||
infoLogger.accept("Sent bStats metrics data: " + data.toString());
|
||||
}
|
||||
String url = String.format(REPORT_URL, platform);
|
||||
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
|
||||
// Compress the data to save bandwidth
|
||||
byte[] compressedData = compress(data.toString());
|
||||
connection.setRequestMethod("POST");
|
||||
connection.addRequestProperty("Accept", "application/json");
|
||||
connection.addRequestProperty("Connection", "close");
|
||||
connection.addRequestProperty("Content-Encoding", "gzip");
|
||||
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
connection.setRequestProperty("User-Agent", "Metrics-Service/1");
|
||||
connection.setDoOutput(true);
|
||||
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
|
||||
outputStream.write(compressedData);
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
try (BufferedReader bufferedReader =
|
||||
new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
builder.append(line);
|
||||
}
|
||||
}
|
||||
if (logResponseStatusText) {
|
||||
infoLogger.accept("Sent data to bStats and received response: " + builder);
|
||||
}
|
||||
}
|
||||
|
||||
/** Checks that the class was properly relocated. */
|
||||
private void checkRelocation() {
|
||||
// You can use the property to disable the check in your test environment
|
||||
if (System.getProperty("bstats.relocatecheck") == null
|
||||
|| !System.getProperty("bstats.relocatecheck").equals("false")) {
|
||||
// Maven's Relocate is clever and changes strings, too. So we have to use this
|
||||
// little "trick" ... :D
|
||||
final String defaultPackage =
|
||||
new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});
|
||||
final String examplePackage =
|
||||
new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
|
||||
// We want to make sure no one just copy & pastes the example and uses the wrong
|
||||
// package names
|
||||
if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage)
|
||||
|| MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {
|
||||
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gzips the given string.
|
||||
*
|
||||
* @param str The string to gzip.
|
||||
* @return The gzipped string.
|
||||
*/
|
||||
private static byte[] compress(final String str) throws IOException {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
|
||||
gzip.write(str.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static class AdvancedBarChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, int[]>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
||||
Map<String, int[]> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, int[]> entry : map.entrySet()) {
|
||||
if (entry.getValue().length == 0) {
|
||||
// Skip this invalid
|
||||
continue;
|
||||
}
|
||||
allSkipped = false;
|
||||
valuesBuilder.appendField(entry.getKey(), entry.getValue());
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public static class SimplePie extends CustomChart {
|
||||
|
||||
private final Callable<String> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SimplePie(String chartId, Callable<String> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
||||
String value = callable.call();
|
||||
if (value == null || value.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
return new JsonObjectBuilder().appendField("value", value).build();
|
||||
}
|
||||
}
|
||||
|
||||
public static class DrilldownPie extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Map<String, Integer>>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
||||
Map<String, Map<String, Integer>> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean reallyAllSkipped = true;
|
||||
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
|
||||
JsonObjectBuilder valueBuilder = new JsonObjectBuilder();
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
|
||||
valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue());
|
||||
allSkipped = false;
|
||||
}
|
||||
if (!allSkipped) {
|
||||
reallyAllSkipped = false;
|
||||
valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build());
|
||||
}
|
||||
}
|
||||
if (reallyAllSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public static class SingleLineChart extends CustomChart {
|
||||
|
||||
private final Callable<Integer> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SingleLineChart(String chartId, Callable<Integer> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
||||
int value = callable.call();
|
||||
if (value == 0) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
return new JsonObjectBuilder().appendField("value", value).build();
|
||||
}
|
||||
}
|
||||
|
||||
public static class MultiLineChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
if (entry.getValue() == 0) {
|
||||
// Skip this invalid
|
||||
continue;
|
||||
}
|
||||
allSkipped = false;
|
||||
valuesBuilder.appendField(entry.getKey(), entry.getValue());
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public static class AdvancedPie extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
if (entry.getValue() == 0) {
|
||||
// Skip this invalid
|
||||
continue;
|
||||
}
|
||||
allSkipped = false;
|
||||
valuesBuilder.appendField(entry.getKey(), entry.getValue());
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public abstract static class CustomChart {
|
||||
|
||||
private final String chartId;
|
||||
|
||||
protected CustomChart(String chartId) {
|
||||
if (chartId == null) {
|
||||
throw new IllegalArgumentException("chartId must not be null");
|
||||
}
|
||||
this.chartId = chartId;
|
||||
}
|
||||
|
||||
public JsonObjectBuilder.JsonObject getRequestJsonObject(
|
||||
BiConsumer<String, Throwable> errorLogger, boolean logErrors) {
|
||||
JsonObjectBuilder builder = new JsonObjectBuilder();
|
||||
builder.appendField("chartId", chartId);
|
||||
try {
|
||||
JsonObjectBuilder.JsonObject data = getChartData();
|
||||
if (data == null) {
|
||||
// If the data is null we don't send the chart.
|
||||
return null;
|
||||
}
|
||||
builder.appendField("data", data);
|
||||
} catch (Throwable t) {
|
||||
if (logErrors) {
|
||||
errorLogger.accept("Failed to get data for custom chart with id " + chartId, t);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;
|
||||
}
|
||||
|
||||
public static class SimpleBarChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()});
|
||||
}
|
||||
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An extremely simple JSON builder.
|
||||
*
|
||||
* <p>While this class is neither feature-rich nor the most performant one, it's sufficient enough
|
||||
* for its use-case.
|
||||
*/
|
||||
public static class JsonObjectBuilder {
|
||||
|
||||
private StringBuilder builder = new StringBuilder();
|
||||
|
||||
private boolean hasAtLeastOneField = false;
|
||||
|
||||
public JsonObjectBuilder() {
|
||||
builder.append("{");
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a null field to the JSON.
|
||||
*
|
||||
* @param key The key of the field.
|
||||
* @return A reference to this object.
|
||||
*/
|
||||
public JsonObjectBuilder appendNull(String key) {
|
||||
appendFieldUnescaped(key, "null");
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a string field to the JSON.
|
||||
*
|
||||
* @param key The key of the field.
|
||||
* @param value The value of the field.
|
||||
* @return A reference to this object.
|
||||
*/
|
||||
public JsonObjectBuilder appendField(String key, String value) {
|
||||
if (value == null) {
|
||||
throw new IllegalArgumentException("JSON value must not be null");
|
||||
}
|
||||
appendFieldUnescaped(key, "\"" + escape(value) + "\"");
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends an integer field to the JSON.
|
||||
*
|
||||
* @param key The key of the field.
|
||||
* @param value The value of the field.
|
||||
* @return A reference to this object.
|
||||
*/
|
||||
public JsonObjectBuilder appendField(String key, int value) {
|
||||
appendFieldUnescaped(key, String.valueOf(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends an object to the JSON.
|
||||
*
|
||||
* @param key The key of the field.
|
||||
* @param object The object.
|
||||
* @return A reference to this object.
|
||||
*/
|
||||
public JsonObjectBuilder appendField(String key, JsonObject object) {
|
||||
if (object == null) {
|
||||
throw new IllegalArgumentException("JSON object must not be null");
|
||||
}
|
||||
appendFieldUnescaped(key, object.toString());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a string array to the JSON.
|
||||
*
|
||||
* @param key The key of the field.
|
||||
* @param values The string array.
|
||||
* @return A reference to this object.
|
||||
*/
|
||||
public JsonObjectBuilder appendField(String key, String[] values) {
|
||||
if (values == null) {
|
||||
throw new IllegalArgumentException("JSON values must not be null");
|
||||
}
|
||||
String escapedValues =
|
||||
Arrays.stream(values)
|
||||
.map(value -> "\"" + escape(value) + "\"")
|
||||
.collect(Collectors.joining(","));
|
||||
appendFieldUnescaped(key, "[" + escapedValues + "]");
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends an integer array to the JSON.
|
||||
*
|
||||
* @param key The key of the field.
|
||||
* @param values The integer array.
|
||||
* @return A reference to this object.
|
||||
*/
|
||||
public JsonObjectBuilder appendField(String key, int[] values) {
|
||||
if (values == null) {
|
||||
throw new IllegalArgumentException("JSON values must not be null");
|
||||
}
|
||||
String escapedValues =
|
||||
Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(","));
|
||||
appendFieldUnescaped(key, "[" + escapedValues + "]");
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends an object array to the JSON.
|
||||
*
|
||||
* @param key The key of the field.
|
||||
* @param values The integer array.
|
||||
* @return A reference to this object.
|
||||
*/
|
||||
public JsonObjectBuilder appendField(String key, JsonObject[] values) {
|
||||
if (values == null) {
|
||||
throw new IllegalArgumentException("JSON values must not be null");
|
||||
}
|
||||
String escapedValues =
|
||||
Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(","));
|
||||
appendFieldUnescaped(key, "[" + escapedValues + "]");
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a field to the object.
|
||||
*
|
||||
* @param key The key of the field.
|
||||
* @param escapedValue The escaped value of the field.
|
||||
*/
|
||||
private void appendFieldUnescaped(String key, String escapedValue) {
|
||||
if (builder == null) {
|
||||
throw new IllegalStateException("JSON has already been built");
|
||||
}
|
||||
if (key == null) {
|
||||
throw new IllegalArgumentException("JSON key must not be null");
|
||||
}
|
||||
if (hasAtLeastOneField) {
|
||||
builder.append(",");
|
||||
}
|
||||
builder.append("\"").append(escape(key)).append("\":").append(escapedValue);
|
||||
hasAtLeastOneField = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the JSON string and invalidates this builder.
|
||||
*
|
||||
* @return The built JSON string.
|
||||
*/
|
||||
public JsonObject build() {
|
||||
if (builder == null) {
|
||||
throw new IllegalStateException("JSON has already been built");
|
||||
}
|
||||
JsonObject object = new JsonObject(builder.append("}").toString());
|
||||
builder = null;
|
||||
return object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.
|
||||
*
|
||||
* <p>This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'.
|
||||
* Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n").
|
||||
*
|
||||
* @param value The value to escape.
|
||||
* @return The escaped value.
|
||||
*/
|
||||
private static String escape(String value) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
if (c == '"') {
|
||||
builder.append("\\\"");
|
||||
} else if (c == '\\') {
|
||||
builder.append("\\\\");
|
||||
} else if (c <= '\u000F') {
|
||||
builder.append("\\u000").append(Integer.toHexString(c));
|
||||
} else if (c <= '\u001F') {
|
||||
builder.append("\\u00").append(Integer.toHexString(c));
|
||||
} else {
|
||||
builder.append(c);
|
||||
}
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* A super simple representation of a JSON object.
|
||||
*
|
||||
* <p>This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not
|
||||
* allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String,
|
||||
* JsonObject)}.
|
||||
*/
|
||||
public static class JsonObject {
|
||||
|
||||
private final String value;
|
||||
|
||||
private JsonObject(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package org.alexdev.unlimitednametags.nametags;
|
||||
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import net.jodah.expiringmap.ExpiringMap;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.config.Settings;
|
||||
import org.apache.commons.jexl3.*;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ConditionalManager {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
private final BlockingQueue<JexlEngine> jexlEnginePool;
|
||||
private final JexlContext jexlContext;
|
||||
private final Map<String, Object> cachedExpressions;
|
||||
|
||||
public ConditionalManager(UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
this.jexlEnginePool = createJexlEnginePool();
|
||||
this.jexlContext = createJexlContext();
|
||||
this.cachedExpressions = ExpiringMap.builder()
|
||||
.expiration(5, TimeUnit.MINUTES)
|
||||
.build();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private BlockingQueue<JexlEngine> createJexlEnginePool() {
|
||||
final BlockingQueue<JexlEngine> pool = new LinkedBlockingQueue<>(10);
|
||||
for (int i = 0; i < 10; i++) {
|
||||
pool.add(new JexlBuilder().debug(false).create());
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private JexlContext createJexlContext() {
|
||||
return new MapContext();
|
||||
}
|
||||
|
||||
public boolean evaluateExpression(@NotNull Settings.ConditionalModifier modifier, @NotNull Player player) {
|
||||
final String entireExpression = plugin.getPlaceholderManager().getPapiManager().isPAPIEnabled() ?
|
||||
PlaceholderAPI.setPlaceholders(player, modifier.getExpression()) :
|
||||
modifier.getExpression();
|
||||
|
||||
if (cachedExpressions.containsKey(entireExpression)) {
|
||||
return (boolean) cachedExpressions.get(entireExpression);
|
||||
}
|
||||
|
||||
JexlEngine jexlEngine = null;
|
||||
try {
|
||||
jexlEngine = jexlEnginePool.poll(1, TimeUnit.SECONDS);
|
||||
if (jexlEngine == null) {
|
||||
jexlEngine = new JexlBuilder().debug(false).create();
|
||||
}
|
||||
|
||||
final Object result = jexlEngine.createExpression(entireExpression).evaluate(jexlContext);
|
||||
final boolean boolResult = result instanceof Boolean bb && bb;
|
||||
|
||||
cachedExpressions.put(entireExpression, boolResult);
|
||||
|
||||
return boolResult;
|
||||
} catch (Exception e) {
|
||||
plugin.getLogger().warning("Failed to evaluate expression: " + entireExpression);
|
||||
return false;
|
||||
} finally {
|
||||
if (jexlEngine != null && !jexlEnginePool.offer(jexlEngine)) {
|
||||
plugin.getLogger().warning("JexlEngine pool is full. Discarding engine.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,56 +1,164 @@
|
||||
package org.alexdev.unlimitednametags.nametags;
|
||||
|
||||
import com.github.Anon8281.universalScheduler.scheduling.tasks.MyScheduledTask;
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Sets;
|
||||
import lombok.Getter;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import lombok.Setter;
|
||||
import me.tofaa.entitylib.meta.display.AbstractDisplayMeta;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.config.Settings;
|
||||
import org.alexdev.unlimitednametags.hook.ViaVersionHook;
|
||||
import org.alexdev.unlimitednametags.packet.PacketNameTag;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Display;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.attribute.AttributeInstance;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.entity.TextDisplay;
|
||||
import org.bukkit.metadata.FixedMetadataValue;
|
||||
import org.bukkit.util.Transformation;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
@Getter
|
||||
public class NameTagManager {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
private final Map<UUID, UUID> nameTags;
|
||||
private final Map<UUID, UUID> white;
|
||||
private final List<UUID> creating;
|
||||
private final List<UUID> blocked;
|
||||
private final Set<UUID> ejectable;
|
||||
private final Map<UUID, PacketNameTag> nameTags;
|
||||
private final Map<Integer, PacketNameTag> entityIdToDisplay;
|
||||
private final Set<UUID> creating;
|
||||
private final Set<UUID> blocked;
|
||||
private final Set<UUID> hiddenOtherNametags;
|
||||
private final List<MyScheduledTask> tasks;
|
||||
@Setter
|
||||
private boolean debug = false;
|
||||
|
||||
public NameTagManager(UnlimitedNameTags plugin) {
|
||||
public NameTagManager(@NotNull UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
this.nameTags = Maps.newConcurrentMap();
|
||||
this.creating = Lists.newCopyOnWriteArrayList();
|
||||
this.white = Maps.newConcurrentMap();
|
||||
this.blocked = Lists.newCopyOnWriteArrayList();
|
||||
this.ejectable = Sets.newConcurrentHashSet();
|
||||
this.entityIdToDisplay = Maps.newConcurrentMap();
|
||||
this.tasks = Lists.newCopyOnWriteArrayList();
|
||||
this.creating = Sets.newConcurrentHashSet();
|
||||
this.blocked = Sets.newConcurrentHashSet();
|
||||
this.hiddenOtherNametags = Sets.newConcurrentHashSet();
|
||||
this.loadAll();
|
||||
this.startTask();
|
||||
}
|
||||
|
||||
private void loadAll() {
|
||||
Bukkit.getOnlinePlayers().forEach(this::addPlayer);
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> {
|
||||
Bukkit.getOnlinePlayers().forEach(this::addPlayer);
|
||||
this.startTask();
|
||||
}, 5);
|
||||
}
|
||||
|
||||
private void startTask() {
|
||||
Bukkit.getScheduler().runTaskTimerAsynchronously(plugin,
|
||||
() -> Bukkit.getOnlinePlayers().forEach(this::refreshPlayer),
|
||||
tasks.forEach(MyScheduledTask::cancel);
|
||||
final MyScheduledTask refresh = plugin.getTaskScheduler().runTaskTimerAsynchronously(
|
||||
() -> Bukkit.getOnlinePlayers().forEach(p -> refresh(p, false)),
|
||||
10, plugin.getConfigManager().getSettings().getTaskInterval());
|
||||
|
||||
// Refresh passengers
|
||||
final MyScheduledTask passengers = plugin.getTaskScheduler().runTaskTimerAsynchronously(() ->
|
||||
Bukkit.getOnlinePlayers().forEach(player ->
|
||||
getPacketDisplayText(player)
|
||||
.ifPresent(PacketNameTag::sendPassengerPacketToViewers))
|
||||
, 20, 20 * 5L);
|
||||
|
||||
// Scale task
|
||||
if (isScalePresent()) {
|
||||
final MyScheduledTask scale = plugin.getTaskScheduler().runTaskTimerAsynchronously(() ->
|
||||
Bukkit.getOnlinePlayers().forEach(player ->
|
||||
getPacketDisplayText(player)
|
||||
.filter(PacketNameTag::checkScale)
|
||||
.ifPresent(PacketNameTag::refresh))
|
||||
, 20, 10);
|
||||
tasks.add(scale);
|
||||
}
|
||||
|
||||
if (plugin.getConfigManager().getSettings().isShowWhileLooking()) {
|
||||
final boolean current = plugin.getConfigManager().getSettings().isShowCurrentNameTag();
|
||||
final MyScheduledTask point = plugin.getTaskScheduler().runTaskTimerAsynchronously(() ->
|
||||
Bukkit.getOnlinePlayers().forEach(player1 -> {
|
||||
final Optional<PacketNameTag> display = getPacketDisplayText(player1);
|
||||
if (display.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Bukkit.getOnlinePlayers().forEach(player2 -> {
|
||||
if (plugin.getHook(ViaVersionHook.class).map(h -> h.hasNotTextDisplays(player2)).orElse(false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (player1.getWorld() != player2.getWorld()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean isPointing = isPlayerPointingAt(player2, player1) || (current && player1 == player2);
|
||||
if (display.get().canPlayerSee(player2) && !isPointing) {
|
||||
display.get().hideFromPlayer(player2);
|
||||
} else if (!display.get().canPlayerSee(player2) && isPointing) {
|
||||
display.get().showToPlayer(player2);
|
||||
}
|
||||
|
||||
});
|
||||
})
|
||||
|
||||
, 5, 5);
|
||||
tasks.add(point);
|
||||
}
|
||||
|
||||
tasks.add(refresh);
|
||||
tasks.add(passengers);
|
||||
}
|
||||
|
||||
public boolean isPlayerPointingAt(Player player1, Player player2) {
|
||||
if (player1.getWorld() != player2.getWorld()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (player1.getLocation().distance(player2.getLocation()) < 5) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final org.bukkit.util.Vector direction = player1.getEyeLocation().getDirection();
|
||||
final Vector toPlayer2 = player2.getEyeLocation().toVector().subtract(player1.getEyeLocation().toVector());
|
||||
toPlayer2.normalize();
|
||||
|
||||
final double dotProduct = direction.dot(toPlayer2);
|
||||
return dotProduct > 0.90;
|
||||
}
|
||||
|
||||
public boolean isScalePresent() {
|
||||
return PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_20_5);
|
||||
}
|
||||
|
||||
public float getScale(@NotNull Player player) {
|
||||
if (!isScalePresent()) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if(PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_20_5)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
final AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_SCALE);
|
||||
|
||||
if (attribute == null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return (int) attribute.getValue();
|
||||
}
|
||||
|
||||
public void blockPlayer(@NotNull Player player) {
|
||||
@@ -63,24 +171,51 @@ public class NameTagManager {
|
||||
|
||||
public void addPlayer(@NotNull Player player) {
|
||||
if (nameTags.containsKey(player.getUniqueId())) {
|
||||
if (debug) {
|
||||
plugin.getLogger().info("Player " + player.getName() + " already has a nametag");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (creating.contains(player.getUniqueId())) {
|
||||
if (debug) {
|
||||
plugin.getLogger().info("Player " + player.getName() + " is already creating a nametag");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (blocked.contains(player.getUniqueId())) {
|
||||
if (debug) {
|
||||
plugin.getLogger().info("Player " + player.getName() + " is blocked");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
createBlankDisplay(player);
|
||||
if (player.hasPotionEffect(PotionEffectType.INVISIBILITY)) {
|
||||
if (debug) {
|
||||
plugin.getLogger().info("Player " + player.getName() + " has invisibility potion effect, blocking");
|
||||
}
|
||||
blockPlayer(player);
|
||||
return;
|
||||
}
|
||||
final Settings.NameTag nametag = plugin.getConfigManager().getSettings().getNametag(player);
|
||||
final PacketNameTag display = new PacketNameTag(plugin, player, nametag);
|
||||
display.text(player, Component.empty());
|
||||
display.spawn(player);
|
||||
|
||||
if (plugin.getConfigManager().getSettings().isShowCurrentNameTag()) {
|
||||
display.showToPlayer(player);
|
||||
}
|
||||
|
||||
handleVanish(player, display);
|
||||
|
||||
nameTags.put(player.getUniqueId(), display);
|
||||
entityIdToDisplay.put(display.getEntityId(), display);
|
||||
|
||||
creating.add(player.getUniqueId());
|
||||
final Settings.NameTag nametag = plugin.getConfigManager().getSettings().getNametag(player);
|
||||
|
||||
plugin.getPlaceholderManager().applyPlaceholders(player, nametag.lines())
|
||||
.thenAccept(lines -> createDisplay(player, lines))
|
||||
plugin.getPlaceholderManager().applyPlaceholders(player, nametag.linesGroups(), List.of(player))
|
||||
.thenAccept(lines -> loadDisplay(player, lines.get(player), nametag, display))
|
||||
.exceptionally(throwable -> {
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to create nametag for " + player.getName(), throwable);
|
||||
creating.remove(player.getUniqueId());
|
||||
@@ -88,205 +223,215 @@ public class NameTagManager {
|
||||
});
|
||||
}
|
||||
|
||||
private void createBlankDisplay(@NotNull Player player) {
|
||||
final TextDisplay display = player.getWorld().spawn(player.getLocation().clone().add(0, 1.80, 0), TextDisplay.class);
|
||||
white.put(player.getUniqueId(), display.getUniqueId());
|
||||
display.text(Component.empty());
|
||||
display.setInvulnerable(true);
|
||||
display.setPersistent(false);
|
||||
display.setBillboard(Display.Billboard.CENTER);
|
||||
player.addPassenger(display);
|
||||
}
|
||||
|
||||
public void refreshPlayer(@NotNull Player player) {
|
||||
public void refresh(@NotNull Player player, boolean force) {
|
||||
final Settings.NameTag nametag = plugin.getConfigManager().getSettings().getNametag(player);
|
||||
|
||||
if(PacketEvents.getAPI().getPlayerManager().getUser(player) == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!nameTags.containsKey(player.getUniqueId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getPlaceholderManager().applyPlaceholders(player, nametag.lines())
|
||||
.thenAccept(lines -> editDisplay(player, lines))
|
||||
.exceptionally(throwable -> {
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to create nametag for " + player.getName(), throwable);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void editDisplay(Player player, Component component) {
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
final UUID uuid = nameTags.get(player.getUniqueId());
|
||||
if (uuid == null) return;
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(uuid);
|
||||
if (display == null) return;
|
||||
|
||||
display.text(component);
|
||||
});
|
||||
}
|
||||
|
||||
private void applyPassenger(Player player) {
|
||||
final UUID uuid = nameTags.get(player.getUniqueId());
|
||||
if (uuid == null) return;
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(uuid);
|
||||
if (display == null) return;
|
||||
|
||||
final boolean isVanished = plugin.getVanishManager().isVanished(player);
|
||||
|
||||
//show to all players except the player itself after tp
|
||||
Bukkit.getOnlinePlayers().stream()
|
||||
.filter(p -> p != player && (isVanished || plugin.getVanishManager().canSee(p, player)))
|
||||
.forEach(p -> p.showEntity(plugin, display));
|
||||
|
||||
player.addPassenger(display);
|
||||
}
|
||||
|
||||
public void updateDisplaysForPlayer(Player player) {
|
||||
Bukkit.getScheduler().runTask(plugin, () -> nameTags.forEach((uuid, display) -> {
|
||||
final Player p = Bukkit.getPlayer(uuid);
|
||||
|
||||
//player is offline
|
||||
if (p == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
TextDisplay textDisplay = (TextDisplay) Bukkit.getEntity(display);
|
||||
|
||||
if (textDisplay == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!plugin.getVanishManager().isVanished(p) || plugin.getVanishManager().canSee(player, p)) {
|
||||
player.showEntity(plugin, textDisplay);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void createDisplay(Player player, Component component) {
|
||||
Bukkit.getScheduler().runTaskLater(plugin, () -> {
|
||||
try {
|
||||
final Location location = player.getLocation().clone();
|
||||
//add 1.80 to make a perfect tp animation
|
||||
location.setY(location.getY() + 1.80);
|
||||
|
||||
final TextDisplay display = location.getWorld().spawn(location, TextDisplay.class);
|
||||
nameTags.put(player.getUniqueId(), display.getUniqueId());
|
||||
creating.remove(player.getUniqueId());
|
||||
display.text(component);
|
||||
display.setInvulnerable(true);
|
||||
display.setPersistent(false);
|
||||
display.setBillboard(Display.Billboard.CENTER);
|
||||
display.setShadowed(false);
|
||||
display.setSeeThrough(true);
|
||||
//invisible background
|
||||
display.setBackgroundColor(Color.BLACK.setAlpha(0));
|
||||
display.setVisibleByDefault(false);
|
||||
display.setMetadata("nametag", new FixedMetadataValue(plugin, player.getUniqueId()));
|
||||
|
||||
final Transformation transformation = display.getTransformation();
|
||||
transformation.getTranslation().add(0, plugin.getConfigManager().getSettings().getYOffset(), 0);
|
||||
display.setTransformation(transformation);
|
||||
|
||||
display.setViewRange(plugin.getConfigManager().getSettings().getViewDistance());
|
||||
|
||||
Optional.ofNullable(Bukkit.getEntity(white.remove(player.getUniqueId()))).ifPresent(Entity::remove);
|
||||
player.addPassenger(display);
|
||||
|
||||
final boolean isVanished = plugin.getVanishManager().isVanished(player);
|
||||
|
||||
//if player is vanished, hide display for all players except for who can see the player
|
||||
Bukkit.getOnlinePlayers().stream()
|
||||
.filter(p -> p != player)
|
||||
.filter(p -> !isVanished || plugin.getVanishManager().canSee(p, player))
|
||||
.forEach(p -> p.showEntity(plugin, display));
|
||||
} catch (Exception e) {
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to create nametag for " + player.getName(), e);
|
||||
}
|
||||
|
||||
}, 5);
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull Player player, boolean removePassenger) {
|
||||
final UUID uuid = nameTags.get(player.getUniqueId());
|
||||
if (uuid == null) return;
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(uuid);
|
||||
if (display == null) return;
|
||||
|
||||
if (removePassenger) {
|
||||
player.removePassenger(display);
|
||||
}
|
||||
display.remove();
|
||||
nameTags.remove(player.getUniqueId());
|
||||
}
|
||||
|
||||
public void hideAllDisplays(Player player) {
|
||||
Bukkit.getScheduler().runTask(plugin, () -> nameTags.forEach((uuid, display) -> {
|
||||
final TextDisplay textDisplay = (TextDisplay) Bukkit.getEntity(display);
|
||||
|
||||
if (textDisplay == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
player.hideEntity(plugin, textDisplay);
|
||||
}));
|
||||
}
|
||||
|
||||
public void teleportAndApply(@NotNull Player player) {
|
||||
final UUID uuid = nameTags.get(player.getUniqueId());
|
||||
if (uuid == null) {
|
||||
return;
|
||||
}
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(uuid);
|
||||
final PacketNameTag display = nameTags.get(player.getUniqueId());
|
||||
if (display == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (player.getPassengers().contains(display) && display.getWorld() == player.getWorld() && display.getLocation().distance(player.getLocation()) < 4) {
|
||||
final boolean show = plugin.getConfigManager().getSettings().isShowCurrentNameTag();
|
||||
if (show && !display.canPlayerSee(player)) {
|
||||
display.showToPlayer(player);
|
||||
} else if (!show && display.canPlayerSee(player)) {
|
||||
display.hideFromPlayer(player);
|
||||
}
|
||||
|
||||
final List<Player> relationalPlayers = display.getViewers().stream()
|
||||
.map(Bukkit::getPlayer)
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
|
||||
plugin.getPlaceholderManager().applyPlaceholders(player, nametag.linesGroups(), relationalPlayers)
|
||||
.thenAccept(lines -> editDisplay(player, lines, nametag, force))
|
||||
.exceptionally(throwable -> {
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to edit nametag for " + player.getName(), throwable);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void editDisplay(@NotNull Player player, Map<Player, Component> components,
|
||||
@NotNull Settings.NameTag nameTag, boolean force) {
|
||||
getPacketDisplayText(player).ifPresent(packetNameTag -> {
|
||||
if (!packetNameTag.getNameTag().equals(nameTag)) {
|
||||
packetNameTag.setNameTag(nameTag);
|
||||
}
|
||||
if (force && isScalePresent()) {
|
||||
packetNameTag.checkScale();
|
||||
}
|
||||
components.forEach((p, c) -> {
|
||||
final AtomicBoolean update = new AtomicBoolean(false);
|
||||
update.set(packetNameTag.text(p, c) || force);
|
||||
final User user = PacketEvents.getAPI().getPlayerManager().getUser(p);
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
packetNameTag.modify(user, m -> {
|
||||
|
||||
if(force) {
|
||||
m.setShadow(nameTag.background().shadowed());
|
||||
m.setSeeThrough(nameTag.background().seeThrough());
|
||||
m.setBackgroundColor(nameTag.background().getColor().asARGB());
|
||||
update.set(true);
|
||||
} else {
|
||||
if(m.isShadow() != nameTag.background().shadowed()) {
|
||||
m.setShadow(nameTag.background().shadowed());
|
||||
update.set(true);
|
||||
}
|
||||
if(m.isSeeThrough() != nameTag.background().seeThrough()) {
|
||||
m.setSeeThrough(nameTag.background().seeThrough());
|
||||
update.set(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
|
||||
if (update.get()) {
|
||||
packetNameTag.refreshForPlayer(p);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void loadDisplay(@NotNull Player player, @NotNull Component component,
|
||||
@NotNull Settings.NameTag nameTag,
|
||||
@NotNull PacketNameTag display) {
|
||||
try {
|
||||
final Location location = player.getLocation().clone();
|
||||
//add 1.80 to make a perfect tp animation
|
||||
location.setY(location.getY() + 1.80);
|
||||
|
||||
creating.remove(player.getUniqueId());
|
||||
display.modify(m -> m.setUseDefaultBackground(false));
|
||||
display.text(player, component);
|
||||
display.setBillboard(plugin.getConfigManager().getSettings().getDefaultBillboard());
|
||||
display.setShadowed(nameTag.background().shadowed());
|
||||
display.setSeeThrough(nameTag.background().seeThrough());
|
||||
//background color, if disabled, set to transparent
|
||||
display.setBackgroundColor(nameTag.background().getColor());
|
||||
|
||||
// display.setTransformation(new Vector3f(0, plugin.getConfigManager().getSettings().getYOffset(), 0));
|
||||
display.resetOffset(plugin.getConfigManager().getSettings().getYOffset());
|
||||
|
||||
display.setViewRange(plugin.getConfigManager().getSettings().getViewDistance());
|
||||
|
||||
plugin.getTaskScheduler().runTaskLater(() -> display.modifyOwner(meta -> meta.setText(component)), 1);
|
||||
|
||||
display.refresh();
|
||||
|
||||
handleVanish(player, display);
|
||||
|
||||
} catch (Throwable e) {
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to create nametag for " + player.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleVanish(@NotNull Player player, @NotNull PacketNameTag display) {
|
||||
final boolean isVanished = plugin.getVanishManager().isVanished(player);
|
||||
|
||||
//if player is vanished, hide display for all players except for who can see the player
|
||||
Bukkit.getOnlinePlayers().stream()
|
||||
.filter(p -> p != player)
|
||||
.filter(p -> p.getLocation().getWorld() == player.getLocation().getWorld())
|
||||
.filter(p -> !isVanished || plugin.getVanishManager().canSee(p, player))
|
||||
.filter(p -> p.getLocation().distance(player.getLocation()) <= 250)
|
||||
.filter(p -> !display.canPlayerSee(p))
|
||||
.forEach(display::showToPlayer);
|
||||
}
|
||||
|
||||
|
||||
public void removePlayer(@NotNull Player player, boolean quit) {
|
||||
final PacketNameTag packetNameTag = nameTags.remove(player.getUniqueId());
|
||||
if (packetNameTag != null) {
|
||||
packetNameTag.remove();
|
||||
}
|
||||
|
||||
entityIdToDisplay.remove(player.getEntityId());
|
||||
|
||||
nameTags.forEach((uuid, display) -> {
|
||||
if (quit) {
|
||||
display.handleQuit(player);
|
||||
} else {
|
||||
display.hideFromPlayerSilently(player);
|
||||
}
|
||||
display.getBlocked().remove(player.getUniqueId());
|
||||
});
|
||||
}
|
||||
|
||||
public void removeAllViewers(@NotNull Player player) {
|
||||
final PacketNameTag packetNameTag = nameTags.get(player.getUniqueId());
|
||||
if (packetNameTag != null) {
|
||||
packetNameTag.setVisible(false);
|
||||
packetNameTag.clearViewers();
|
||||
}
|
||||
}
|
||||
|
||||
public void showToTrackedPlayers(@NotNull Player player, @NotNull Collection<UUID> tracked) {
|
||||
final PacketNameTag packetNameTag = nameTags.get(player.getUniqueId());
|
||||
if (packetNameTag != null) {
|
||||
packetNameTag.setVisible(true);
|
||||
packetNameTag.showToPlayers(tracked.stream()
|
||||
.map(Bukkit::getPlayer)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet()));
|
||||
return;
|
||||
}
|
||||
|
||||
Bukkit.getScheduler().runTaskLater(plugin, () -> {
|
||||
display.teleport(player.getLocation().clone().add(0, 1.8, 0));
|
||||
applyPassenger(player);
|
||||
ejectable.remove(player.getUniqueId());
|
||||
}, 1);
|
||||
addPlayer(player);
|
||||
}
|
||||
|
||||
public void hideAllDisplays(@NotNull Player player) {
|
||||
nameTags.forEach((uuid, display) -> {
|
||||
display.hideFromPlayer(player);
|
||||
display.getBlocked().add(player.getUniqueId());
|
||||
});
|
||||
getPacketDisplayText(player).ifPresent(PacketNameTag::clearViewers);
|
||||
}
|
||||
|
||||
public void removeAll() {
|
||||
nameTags.forEach((uuid, display) -> Optional.ofNullable(Bukkit.getEntity(display)).ifPresent(entity -> {
|
||||
entity.removeMetadata("nametag", plugin);
|
||||
entity.remove();
|
||||
}));
|
||||
nameTags.forEach((uuid, display) -> display.remove());
|
||||
|
||||
entityIdToDisplay.clear();
|
||||
nameTags.clear();
|
||||
}
|
||||
|
||||
|
||||
public void updateSneaking(@NotNull Player player, boolean sneaking) {
|
||||
final UUID uuid = nameTags.get(player.getUniqueId());
|
||||
if (uuid == null) return;
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(uuid);
|
||||
if (display == null) return;
|
||||
|
||||
display.setSeeThrough(!sneaking);
|
||||
display.setTextOpacity((byte) (sneaking ? plugin.getConfigManager().getSettings().getSneakOpacity() : -1));
|
||||
getPacketDisplayText(player).ifPresent(packetNameTag -> {
|
||||
if (packetNameTag.getNameTag().background().seeThrough()) {
|
||||
packetNameTag.setSeeThrough(!sneaking);
|
||||
}
|
||||
packetNameTag.setTextOpacity((byte) (sneaking ? plugin.getConfigManager().getSettings().getSneakOpacity() : -1));
|
||||
packetNameTag.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
final float yOffset = plugin.getConfigManager().getSettings().getYOffset();
|
||||
final float viewDistance = plugin.getConfigManager().getSettings().getViewDistance();
|
||||
final AbstractDisplayMeta.BillboardConstraints billboard = plugin.getConfigManager().getSettings().getDefaultBillboard();
|
||||
|
||||
|
||||
plugin.getServer().getScheduler().runTask(plugin, () -> Bukkit.getOnlinePlayers().forEach(p -> {
|
||||
refreshPlayer(p);
|
||||
plugin.getTaskScheduler().runTaskAsynchronously(() -> Bukkit.getOnlinePlayers().forEach(p -> {
|
||||
setYOffset(p, yOffset);
|
||||
setViewDistance(p, viewDistance);
|
||||
setBillBoard(p, billboard);
|
||||
refresh(p, true);
|
||||
}));
|
||||
startTask();
|
||||
}
|
||||
|
||||
public void debug(@NotNull Audience audience) {
|
||||
audience.sendMessage(Component.text("Nametags:"));
|
||||
public void debug(@NotNull CommandSender audience) {
|
||||
audience.sendRichMessage("<red>UnlimitedNameTags v" + plugin.getPluginMeta().getVersion() + " . Compiled: " + plugin.getConfigManager().isCompiled());
|
||||
final AtomicReference<Component> component = new AtomicReference<>(Component.text("Nametags:").colorIfAbsent(TextColor.color(0xFF0000)));
|
||||
nameTags.forEach((uuid, display) -> {
|
||||
final Player player = Bukkit.getPlayer(uuid);
|
||||
|
||||
@@ -294,71 +439,183 @@ public class NameTagManager {
|
||||
return;
|
||||
}
|
||||
|
||||
audience.sendMessage(Component.text(player.getName() + " -> " + player.getPassengers().stream().map(entity -> entity.getType().name()).reduce((a, b) -> a + ", " + b).orElse("")));
|
||||
final List<String> viewers = display.getViewers().stream()
|
||||
.map(Bukkit::getPlayer)
|
||||
.filter(Objects::nonNull)
|
||||
.map(Player::getName)
|
||||
.toList();
|
||||
final long lastUpdate = display.getLastUpdate();
|
||||
|
||||
final Component text = getComponent(display, viewers, player, lastUpdate);
|
||||
component.set(component.get().append(Component.text("\n")).append(text));
|
||||
});
|
||||
|
||||
plugin.getKyoriManager().sendMessage(audience, component.get());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private Component getComponent(@NotNull PacketNameTag display, @NotNull List<String> viewers,
|
||||
@NotNull Player player, long lastUpdate) {
|
||||
final int seconds = (int) ((System.currentTimeMillis() - lastUpdate) / 1000);
|
||||
final Map<String, String> properties = display.properties();
|
||||
Component hover = Component.text("Viewers: " + viewers).appendNewline()
|
||||
.append(Component.text("Owner: " + display.getOwner().getName())).appendNewline()
|
||||
.append(Component.text("Visible: " + display.isVisible())).appendNewline()
|
||||
.append(Component.text("Last update: " + seconds + "s ago")).appendNewline();
|
||||
|
||||
for (Map.Entry<String, String> entry : properties.entrySet()) {
|
||||
hover = hover.append(Component.text(entry.getKey() + ": " + entry.getValue())).appendNewline();
|
||||
}
|
||||
|
||||
Component text = Component.text(player.getName() + " -> " + " " + display.getEntityId());
|
||||
text = text.color(TextColor.color(0x00FF00));
|
||||
text = text.hoverEvent(hover.color(TextColor.color(Color.RED.asRGB())));
|
||||
return text;
|
||||
}
|
||||
|
||||
private void setYOffset(@NotNull Player player, float yOffset) {
|
||||
final UUID uuid = nameTags.get(player.getUniqueId());
|
||||
if (uuid == null) return;
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(uuid);
|
||||
if (display == null) return;
|
||||
final Transformation transformation = display.getTransformation();
|
||||
transformation.getTranslation().set(0, yOffset, 0);
|
||||
display.setTransformation(transformation);
|
||||
getPacketDisplayText(player).ifPresent(packetNameTag -> {
|
||||
packetNameTag.resetOffset(yOffset);
|
||||
});
|
||||
}
|
||||
|
||||
private void setBillBoard(@NotNull Player player, AbstractDisplayMeta.BillboardConstraints billboard) {
|
||||
getPacketDisplayText(player).ifPresent(packetNameTag -> packetNameTag.setBillboard(billboard));
|
||||
}
|
||||
|
||||
private void setViewDistance(@NotNull Player player, float viewDistance) {
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(nameTags.get(player.getUniqueId()));
|
||||
if (display == null) return;
|
||||
display.setViewRange(viewDistance);
|
||||
getPacketDisplayText(player).ifPresent(packetNameTag -> packetNameTag.setViewRange(viewDistance));
|
||||
}
|
||||
|
||||
|
||||
public void vanishPlayer(@NotNull Player player) {
|
||||
Bukkit.getScheduler().runTaskLater(plugin, () -> {
|
||||
final UUID uuid = nameTags.get(player.getUniqueId());
|
||||
if (uuid == null) return;
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(uuid);
|
||||
if (display == null) return;
|
||||
|
||||
List<? extends Player> canSee = Bukkit.getOnlinePlayers()
|
||||
.stream()
|
||||
.filter(p -> plugin.getVanishManager().canSee(p, player))
|
||||
.toList();
|
||||
|
||||
List<? extends Player> cannotSee = Bukkit.getOnlinePlayers()
|
||||
.stream()
|
||||
.filter(p -> !canSee.contains(p))
|
||||
.toList();
|
||||
|
||||
cannotSee.forEach(p -> p.hideEntity(plugin, display));
|
||||
}, 1);
|
||||
getPacketDisplayText(player).ifPresent(packetNameTag -> {
|
||||
final Set<UUID> viewers = new HashSet<>(packetNameTag.getViewers());
|
||||
final boolean isVanished = plugin.getVanishManager().isVanished(player);
|
||||
viewers.forEach(uuid -> {
|
||||
final Player viewer = Bukkit.getPlayer(uuid);
|
||||
if (viewer == null || viewer == player) {
|
||||
return;
|
||||
}
|
||||
if (isVanished && !plugin.getVanishManager().canSee(viewer, player)) {
|
||||
return;
|
||||
}
|
||||
packetNameTag.hideFromPlayer(viewer);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void unVanishPlayer(@NotNull Player player) {
|
||||
Bukkit.getScheduler().runTaskLater(plugin, () -> {
|
||||
final UUID uuid = nameTags.get(player.getUniqueId());
|
||||
if (uuid == null) return;
|
||||
final TextDisplay display = (TextDisplay) Bukkit.getEntity(uuid);
|
||||
if (display == null) return;
|
||||
getPacketDisplayText(player).ifPresent(packetNameTag -> {
|
||||
final Set<UUID> viewers = new HashSet<>(packetNameTag.getViewers());
|
||||
viewers.forEach(uuid -> {
|
||||
final Player viewer = Bukkit.getPlayer(uuid);
|
||||
if (viewer == null || viewer == player) {
|
||||
return;
|
||||
}
|
||||
packetNameTag.showToPlayer(viewer);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Bukkit.getOnlinePlayers()
|
||||
.stream()
|
||||
.filter(p -> p != player)
|
||||
.forEach(p -> p.showEntity(plugin, display));
|
||||
}, 1);
|
||||
|
||||
@NotNull
|
||||
public Optional<PacketNameTag> getPacketDisplayText(@NotNull Player player) {
|
||||
return Optional.ofNullable(nameTags.get(player.getUniqueId()));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Optional<TextDisplay> getEntityById(int entityId) {
|
||||
for (UUID uuid : nameTags.values()) {
|
||||
final Entity entity = Bukkit.getEntity(uuid);
|
||||
if (entity == null) continue;
|
||||
if (entity.getEntityId() == entityId) {
|
||||
return Optional.of((TextDisplay) entity);
|
||||
}
|
||||
public Optional<PacketNameTag> getPacketDisplayText(int id) {
|
||||
return Optional.ofNullable(entityIdToDisplay.get(id));
|
||||
}
|
||||
|
||||
public void updateDisplay(@NotNull Player player, @NotNull Player target) {
|
||||
if (player == target && plugin.getConfigManager().getSettings().isShowCurrentNameTag()) {
|
||||
showToOwner(player);
|
||||
return;
|
||||
}
|
||||
return Optional.empty();
|
||||
getPacketDisplayText(target).ifPresent(packetNameTag -> {
|
||||
packetNameTag.hideFromPlayerSilently(player);
|
||||
packetNameTag.showToPlayer(player);
|
||||
});
|
||||
}
|
||||
|
||||
public void showToOwner(@NotNull Player player) {
|
||||
if (!plugin.getConfigManager().getSettings().isShowCurrentNameTag()) {
|
||||
return;
|
||||
}
|
||||
getPacketDisplayText(player).ifPresent(PacketNameTag::spawnForOwner);
|
||||
}
|
||||
|
||||
public void removeDisplay(@NotNull Player player, @NotNull Player target) {
|
||||
if (player == target && !plugin.getConfigManager().getSettings().isShowCurrentNameTag()) {
|
||||
return;
|
||||
}
|
||||
getPacketDisplayText(target).ifPresent(packetNameTag -> packetNameTag.hideFromPlayer(player));
|
||||
}
|
||||
|
||||
public void updateDisplaysForPlayer(@NotNull Player player) {
|
||||
nameTags.forEach((uuid, display) -> {
|
||||
final Player owner = display.getOwner();
|
||||
if (owner == player) {
|
||||
return;
|
||||
}
|
||||
final Set<UUID> tracked = plugin.getTrackerManager().getTrackedPlayers(owner.getUniqueId());
|
||||
|
||||
if (player.getLocation().getWorld() != owner.getLocation().getWorld()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (plugin.getVanishManager().isVanished(owner) && !plugin.getVanishManager().canSee(player, owner)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!tracked.contains(player.getUniqueId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
display.getBlocked().remove(player.getUniqueId());
|
||||
|
||||
display.hideFromPlayerSilently(player);
|
||||
display.showToPlayer(player);
|
||||
});
|
||||
}
|
||||
|
||||
public void refreshDisplaysForPlayer(@NotNull Player player) {
|
||||
nameTags.forEach((uuid, display) -> {
|
||||
if (!display.canPlayerSee(player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
display.refreshForPlayer(player);
|
||||
});
|
||||
}
|
||||
|
||||
public void unBlockForAllPlayers(@NotNull Player player) {
|
||||
nameTags.forEach((uuid, display) -> display.getBlocked().remove(player.getUniqueId()));
|
||||
}
|
||||
|
||||
public void hideOtherNametags(@NotNull Player player) {
|
||||
hiddenOtherNametags.add(player.getUniqueId());
|
||||
nameTags.forEach((uuid, display) -> {
|
||||
if (display.canPlayerSee(player)) {
|
||||
display.hideFromPlayer(player);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void showOtherNametags(@NotNull Player player) {
|
||||
hiddenOtherNametags.remove(player.getUniqueId());
|
||||
plugin.getTrackerManager().getTrackedPlayers(player.getUniqueId()).forEach(uuid -> {
|
||||
final Player tracked = Bukkit.getPlayer(uuid);
|
||||
if (tracked == null) {
|
||||
return;
|
||||
}
|
||||
getPacketDisplayText(tracked).ifPresent(display -> display.showToPlayer(player));
|
||||
});
|
||||
}
|
||||
|
||||
public boolean isHiddenOtherNametags(@NotNull Player player) {
|
||||
return hiddenOtherNametags.contains(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package org.alexdev.unlimitednametags.packet;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class KyoriManager {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
|
||||
public void sendMessage(@NotNull CommandSender sender, @NotNull Component component) {
|
||||
if (plugin.isPaper()) {
|
||||
sender.sendMessage(component);
|
||||
return;
|
||||
}
|
||||
|
||||
if(!(sender instanceof Player)) {
|
||||
sender.sendMessage(LegacyComponentSerializer.legacySection().serialize(component));
|
||||
return;
|
||||
}
|
||||
|
||||
PacketEvents.getAPI().getPlayerManager().getUser(sender).sendMessage(component);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package org.alexdev.unlimitednametags.packet;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPassengers;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.Multimaps;
|
||||
import com.google.common.collect.Sets;
|
||||
import io.github.retrooper.packetevents.util.SpigotReflectionUtil;
|
||||
import me.tofaa.entitylib.APIConfig;
|
||||
import me.tofaa.entitylib.EntityLib;
|
||||
import me.tofaa.entitylib.spigot.SpigotEntityLibPlatform;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class PacketManager {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
private final Multimap<UUID, Integer> passengers;
|
||||
private final ExecutorService executorService;
|
||||
|
||||
public PacketManager(@NotNull UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
this.initialize();
|
||||
this.passengers = (Multimaps.newSetMultimap(Maps.newConcurrentMap(), Sets::newConcurrentHashSet)); //Multimaps.synchronizedMultimap
|
||||
this.executorService = Executors.newFixedThreadPool(2, r -> {
|
||||
final Thread thread = new Thread(r);
|
||||
thread.setName("UnlimitedNameTags-PacketManager");
|
||||
return thread;
|
||||
});
|
||||
}
|
||||
|
||||
private void initialize() {
|
||||
final SpigotEntityLibPlatform platform = new SpigotEntityLibPlatform(plugin);
|
||||
final APIConfig settings = new APIConfig(PacketEvents.getAPI())
|
||||
.usePlatformLogger();
|
||||
EntityLib.init(platform, settings);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
this.executorService.shutdown();
|
||||
}
|
||||
|
||||
public void setPassengers(@NotNull Player player, @NotNull List<Integer> passengers) {
|
||||
final List<Integer> clone = List.copyOf(passengers);
|
||||
plugin.getTaskScheduler().runTaskAsynchronously(() -> {
|
||||
executorService.submit(() -> this.passengers.replaceValues(player.getUniqueId(), clone));
|
||||
});
|
||||
}
|
||||
|
||||
public void sendPassengersPacket(@NotNull Player player, @NotNull PacketNameTag packetNameTag) {
|
||||
final int entityId = packetNameTag.getEntityId();
|
||||
final int ownerId = packetNameTag.getOwner().getEntityId();
|
||||
executorService.submit(() -> {
|
||||
final Set<Integer> passengers = Sets.newHashSet(this.passengers.get(packetNameTag.getOwner().getUniqueId()));
|
||||
passengers.add(entityId);
|
||||
final int[] passengersArray = passengers.stream().mapToInt(i -> i).toArray();
|
||||
final WrapperPlayServerSetPassengers packet = new WrapperPlayServerSetPassengers(ownerId, passengersArray);
|
||||
PacketEvents.getAPI().getPlayerManager().sendPacket(player, packet);
|
||||
});
|
||||
}
|
||||
|
||||
public void removePassenger(@NotNull Player player, int passenger) {
|
||||
executorService.submit(() -> this.passengers.remove(player.getUniqueId(), passenger));
|
||||
}
|
||||
|
||||
public synchronized int getEntityIndex() {
|
||||
return SpigotReflectionUtil.generateEntityId();
|
||||
}
|
||||
|
||||
public void removePassenger(int passenger) {
|
||||
this.passengers.values().remove(passenger);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
package org.alexdev.unlimitednametags.packet;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
|
||||
import com.github.retrooper.packetevents.protocol.entity.data.EntityDataTypes;
|
||||
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.util.Vector3f;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Sets;
|
||||
import io.github.retrooper.packetevents.util.SpigotConversionUtil;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.SneakyThrows;
|
||||
import me.tofaa.entitylib.meta.Metadata;
|
||||
import me.tofaa.entitylib.meta.display.AbstractDisplayMeta;
|
||||
import me.tofaa.entitylib.meta.display.TextDisplayMeta;
|
||||
import me.tofaa.entitylib.wrapper.WrapperEntity;
|
||||
import me.tofaa.entitylib.wrapper.WrapperPerPlayerEntity;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.alexdev.unlimitednametags.config.Settings;
|
||||
import org.alexdev.unlimitednametags.hook.ViaVersionHook;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.attribute.AttributeInstance;
|
||||
import org.bukkit.entity.Display;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Getter
|
||||
public class PacketNameTag {
|
||||
|
||||
private final UnlimitedNameTags plugin;
|
||||
private final WrapperPerPlayerEntity perPlayerEntity;
|
||||
private final Set<UUID> viewers;
|
||||
private final int entityId;
|
||||
private final UUID entityIdUuid;
|
||||
private final Player owner;
|
||||
private final Set<UUID> blocked;
|
||||
@NotNull
|
||||
private final Map<UUID, Component> relationalCache;
|
||||
private long lastUpdate;
|
||||
@Setter
|
||||
private boolean visible;
|
||||
@Setter
|
||||
private Settings.NameTag nameTag;
|
||||
private float scale;
|
||||
private float offset;
|
||||
private float increasedOffset;
|
||||
|
||||
public PacketNameTag(@NotNull UnlimitedNameTags plugin, @NotNull Player owner, @NotNull Settings.NameTag nameTag) {
|
||||
this.plugin = plugin;
|
||||
this.owner = owner;
|
||||
this.relationalCache = Maps.newConcurrentMap();
|
||||
this.entityId = plugin.getPacketManager().getEntityIndex();
|
||||
this.entityIdUuid = UUID.randomUUID();
|
||||
this.perPlayerEntity = new WrapperPerPlayerEntity(this.getBaseSupplier());
|
||||
this.viewers = Sets.newConcurrentHashSet();
|
||||
this.blocked = Sets.newConcurrentHashSet();
|
||||
this.lastUpdate = System.currentTimeMillis();
|
||||
this.nameTag = nameTag;
|
||||
this.scale = plugin.getNametagManager().getScale(owner);
|
||||
this.setScale(scale);
|
||||
}
|
||||
|
||||
private Function<User, WrapperEntity> getBaseSupplier() {
|
||||
return user -> {
|
||||
final WrapperEntity wrapper = new WrapperEntity(entityId, entityIdUuid, EntityTypes.TEXT_DISPLAY);
|
||||
final TextDisplayMeta meta = (TextDisplayMeta) wrapper.getEntityMeta();
|
||||
meta.setLineWidth(1000);
|
||||
meta.setNotifyAboutChanges(false);
|
||||
return wrapper;
|
||||
};
|
||||
}
|
||||
|
||||
public boolean text(@NotNull Player player, @NotNull Component text) {
|
||||
if (text.equals(relationalCache.get(player.getUniqueId()))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
relationalCache.put(player.getUniqueId(), text);
|
||||
final User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
modify(user, meta -> meta.setText(text));
|
||||
lastUpdate = System.currentTimeMillis();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void modify(User user, Consumer<TextDisplayMeta> consumer) {
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
perPlayerEntity.modify(user, e -> {
|
||||
final TextDisplayMeta meta = (TextDisplayMeta) e.getEntityMeta();
|
||||
consumer.accept(meta);
|
||||
});
|
||||
}
|
||||
|
||||
public void modifyOwner(Consumer<TextDisplayMeta> consumer) {
|
||||
final User owner = PacketEvents.getAPI().getPlayerManager().getUser(this.owner);
|
||||
if (owner == null) {
|
||||
return;
|
||||
}
|
||||
modify(owner, consumer);
|
||||
}
|
||||
|
||||
public void modifyOwnerEntity(Consumer<WrapperEntity> consumer) {
|
||||
final User owner = PacketEvents.getAPI().getPlayerManager().getUser(this.owner);
|
||||
if (owner == null) {
|
||||
return;
|
||||
}
|
||||
modifyEntity(owner, consumer);
|
||||
}
|
||||
|
||||
public void modify(Consumer<TextDisplayMeta> consumer) {
|
||||
perPlayerEntity.execute(e -> {
|
||||
final TextDisplayMeta meta = (TextDisplayMeta) e.getEntityMeta();
|
||||
consumer.accept(meta);
|
||||
});
|
||||
}
|
||||
|
||||
public void modifyEntity(User user, Consumer<WrapperEntity> consumer) {
|
||||
perPlayerEntity.modify(user, consumer);
|
||||
}
|
||||
|
||||
public void modifyEntity(Consumer<WrapperEntity> consumer) {
|
||||
perPlayerEntity.execute(consumer);
|
||||
}
|
||||
|
||||
public float getDefaultScale() {
|
||||
return nameTag.scale();
|
||||
}
|
||||
|
||||
public boolean checkScale() {
|
||||
final AttributeInstance attribute = owner.getAttribute(Attribute.GENERIC_SCALE);
|
||||
if (attribute == null) {
|
||||
if (scale != getDefaultScale()) {
|
||||
setScale(getDefaultScale());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
final double playerScale = attribute.getValue() * getDefaultScale();
|
||||
final double diff = Math.abs(playerScale - scale);
|
||||
if (diff <= 0.01 && diff >= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
setScale((float) playerScale);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void setScale(float scale) {
|
||||
this.scale = scale;
|
||||
this.increasedOffset = scale > 1 ? scale / 5 : 0;
|
||||
updateYOOffset();
|
||||
modify(meta -> meta.setScale(new Vector3f(scale, scale, scale)));
|
||||
}
|
||||
|
||||
public void setBillboard(@NotNull Display.Billboard billboard) {
|
||||
final AbstractDisplayMeta.BillboardConstraints billboardConstraints = AbstractDisplayMeta.BillboardConstraints.valueOf(billboard.name());
|
||||
modify(meta -> meta.setBillboardConstraints(billboardConstraints));
|
||||
}
|
||||
|
||||
public void setBillboard(@NotNull AbstractDisplayMeta.BillboardConstraints billboard) {
|
||||
modify(meta -> meta.setBillboardConstraints(billboard));
|
||||
}
|
||||
|
||||
public void setShadowed(boolean shadowed) {
|
||||
modify(meta -> meta.setShadow(shadowed));
|
||||
}
|
||||
|
||||
public void setSeeThrough(boolean seeThrough) {
|
||||
modify(meta -> meta.setSeeThrough(seeThrough));
|
||||
}
|
||||
|
||||
public void setBackgroundColor(@NotNull Color color) {
|
||||
modify(meta -> meta.setBackgroundColor(color.asARGB()));
|
||||
}
|
||||
|
||||
public void setTransformation(@NotNull Vector3f vector3f) {
|
||||
modify(meta -> meta.setTranslation(vector3f));
|
||||
}
|
||||
|
||||
public void resetOffset(float offset) {
|
||||
this.setTransformation(new Vector3f(0, offset + increasedOffset, 0));
|
||||
this.offset = offset;
|
||||
}
|
||||
|
||||
public void updateYOOffset() {
|
||||
this.setTransformation(new Vector3f(0, offset + increasedOffset, 0));
|
||||
}
|
||||
|
||||
public void setViewRange(float range) {
|
||||
modify(meta -> meta.setViewRange(range));
|
||||
}
|
||||
|
||||
public void showToPlayer(@NotNull Player player) {
|
||||
if (!isEligibleToShow(player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!player.getUniqueId().equals(owner.getUniqueId())) {
|
||||
applyOwnerData(perPlayerEntity.getEntityOf(getUser(player)));
|
||||
}
|
||||
|
||||
spawn(player);
|
||||
|
||||
if (isOwner(player) && plugin.getConfigManager().getSettings().isShowCurrentNameTag()) {
|
||||
setOwnerPosition();
|
||||
} else {
|
||||
setPosition();
|
||||
}
|
||||
|
||||
viewers.add(player.getUniqueId());
|
||||
perPlayerEntity.addViewer(getUser(player));
|
||||
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> sendPassengersPacket(player), 1);
|
||||
}
|
||||
|
||||
private boolean isEligibleToShow(@NotNull Player player) {
|
||||
if (!visible) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (plugin.getHook(ViaVersionHook.class).map(h -> h.hasNotTextDisplays(player)).orElse(false)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (blocked.contains(player.getUniqueId())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!player.canSee(owner)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isPlayerChannelNotValid(player) || isPlayerChannelNotValid(owner)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!hasRequiredPermissions(player)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (plugin.getNametagManager().isHiddenOtherNametags(player)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (plugin.getConfigManager().getSettings().isShowWhileLooking() &&
|
||||
!plugin.getNametagManager().isPlayerPointingAt(player, owner)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !viewers.contains(player.getUniqueId());
|
||||
}
|
||||
|
||||
private boolean isPlayerChannelNotValid(@NotNull Player player) {
|
||||
return PacketEvents.getAPI().getPlayerManager().getChannel(player) == null ||
|
||||
PacketEvents.getAPI().getPlayerManager().getUser(player) == null;
|
||||
}
|
||||
|
||||
private User getUser(@NotNull Player player) {
|
||||
return PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
}
|
||||
|
||||
private boolean isOwner(@NotNull Player player) {
|
||||
return player.getUniqueId().equals(owner.getUniqueId());
|
||||
}
|
||||
|
||||
private boolean hasRequiredPermissions(@NotNull Player player) {
|
||||
boolean isOwner = isOwner(player);
|
||||
if (!isOwner && !player.hasPermission("unt.shownametags")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !isOwner || player.hasPermission("unt.showownnametag");
|
||||
}
|
||||
|
||||
public void spawnForOwner() {
|
||||
this.visible = true;
|
||||
final User user = PacketEvents.getAPI().getPlayerManager().getUser(owner);
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
modifyEntity(user, e -> {
|
||||
e.despawn();
|
||||
e.spawn(SpigotConversionUtil.fromBukkitLocation(getOffsetLocation()));
|
||||
});
|
||||
|
||||
plugin.getTaskScheduler().runTaskLaterAsynchronously(() -> {
|
||||
sendPassengersPacket(owner);
|
||||
}, 1);
|
||||
}
|
||||
|
||||
public void sendPassengersPacket(@NotNull Player player) {
|
||||
plugin.getPacketManager().sendPassengersPacket(player, this);
|
||||
}
|
||||
|
||||
public void sendPassengerPacketToViewers() {
|
||||
if (!visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
viewers.forEach(u -> {
|
||||
final Player player = Bukkit.getPlayer(u);
|
||||
if (player != null) {
|
||||
sendPassengersPacket(player);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void setPosition() {
|
||||
final Location location = getOffsetLocation();
|
||||
modifyEntity(meta -> meta.setLocation(SpigotConversionUtil.fromBukkitLocation(location)));
|
||||
}
|
||||
|
||||
private void setOwnerPosition() {
|
||||
final Location location = getOffsetLocation().add(0, 0.25, 0);
|
||||
modifyOwnerEntity(meta -> meta.setLocation(SpigotConversionUtil.fromBukkitLocation(location)));
|
||||
}
|
||||
|
||||
public Location getOffsetLocation() {
|
||||
final Location location = owner.getLocation().clone();
|
||||
location.setPitch(0);
|
||||
location.setYaw(0);
|
||||
location.setY(location.getY() + (1.8) * scale);
|
||||
return location;
|
||||
}
|
||||
|
||||
public void hideFromPlayer(@NotNull Player player) {
|
||||
if (blocked.contains(player.getUniqueId())) {
|
||||
return;
|
||||
}
|
||||
viewers.remove(player.getUniqueId());
|
||||
final User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
final WrapperEntity wrapperEntity = perPlayerEntity.getEntityOf(user);
|
||||
if (wrapperEntity != null) {
|
||||
wrapperEntity.removeViewer(user);
|
||||
}
|
||||
if (!player.getUniqueId().equals(owner.getUniqueId())) {
|
||||
perPlayerEntity.getEntities().remove(user.getUUID());
|
||||
}
|
||||
relationalCache.remove(player.getUniqueId());
|
||||
|
||||
plugin.getPacketManager().removePassenger(player, entityId);
|
||||
}
|
||||
|
||||
public void clearViewers() {
|
||||
viewers.forEach(u -> {
|
||||
final Player player = Bukkit.getPlayer(u);
|
||||
if (player != null) {
|
||||
hideFromPlayer(player);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void showToPlayers(Set<Player> players) {
|
||||
players.forEach(this::showToPlayer);
|
||||
}
|
||||
|
||||
public void hideFromPlayerSilently(@NotNull Player player) {
|
||||
if (blocked.contains(player.getUniqueId())) {
|
||||
return;
|
||||
}
|
||||
viewers.remove(player.getUniqueId());
|
||||
perPlayerEntity.getEntities().remove(player.getUniqueId());
|
||||
relationalCache.remove(player.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean canPlayerSee(@NotNull Player player) {
|
||||
return viewers.contains(player.getUniqueId());
|
||||
}
|
||||
|
||||
public void spawn(@NotNull Player player) {
|
||||
this.visible = true;
|
||||
final User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
modifyEntity(user, e -> e.spawn(SpigotConversionUtil.fromBukkitLocation(getOffsetLocation())));
|
||||
}
|
||||
|
||||
public void refresh() {
|
||||
perPlayerEntity.getEntities().forEach((u, e) -> {
|
||||
if(blocked.contains(u)) {
|
||||
return;
|
||||
}
|
||||
|
||||
e.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
public void refreshForPlayer(@NotNull Player player) {
|
||||
final User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(blocked.contains(player.getUniqueId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
perPlayerEntity.getEntityOf(user).refresh();
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
viewers.forEach(u -> {
|
||||
final Player player = Bukkit.getPlayer(u);
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user != null) {
|
||||
perPlayerEntity.removeViewer(user);
|
||||
}
|
||||
});
|
||||
viewers.clear();
|
||||
plugin.getPacketManager().removePassenger(entityId);
|
||||
relationalCache.clear();
|
||||
}
|
||||
|
||||
public void handleQuit(@NotNull Player player) {
|
||||
viewers.remove(player.getUniqueId());
|
||||
clearCache(player.getUniqueId());
|
||||
plugin.getPacketManager().removePassenger(player, entityId);
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private void clearCache(@NotNull UUID uuid) {
|
||||
perPlayerEntity.getEntities().remove(uuid);
|
||||
}
|
||||
|
||||
public void setTextOpacity(byte b) {
|
||||
modify(meta -> meta.setTextOpacity(b));
|
||||
}
|
||||
|
||||
public void hideForOwner() {
|
||||
hideFromPlayer(owner);
|
||||
blocked.add(owner.getUniqueId());
|
||||
}
|
||||
|
||||
public void showForOwner() {
|
||||
blocked.remove(owner.getUniqueId());
|
||||
showToPlayer(owner);
|
||||
}
|
||||
|
||||
private void applyOwnerData(@NotNull WrapperEntity wrapper) {
|
||||
final User ownerUser = PacketEvents.getAPI().getPlayerManager().getUser(owner);
|
||||
final Metadata metadata = wrapper.getEntityMeta().getMetadata();
|
||||
final Optional<EntityData> component = wrapper.getEntityMeta().entityData()
|
||||
.stream()
|
||||
.filter(e -> e.getType() == EntityDataTypes.ADV_COMPONENT)
|
||||
.findFirst();
|
||||
final Metadata ownerMetadata = perPlayerEntity.getEntityOf(ownerUser).getEntityMeta().getMetadata();
|
||||
metadata.copyFrom(ownerMetadata);
|
||||
component.ifPresent(entityData -> ((TextDisplayMeta) wrapper.getEntityMeta()).setText((Component) entityData.getValue()));
|
||||
metadata.setNotifyAboutChanges(false);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Map<String, String> properties() {
|
||||
final Map<String, String> properties = new LinkedHashMap<>();
|
||||
final TextDisplayMeta meta = (TextDisplayMeta) this.perPlayerEntity.getEntityOf(PacketEvents.getAPI().getPlayerManager().getUser(owner)).getEntityMeta();
|
||||
properties.put("text", MiniMessage.miniMessage().serialize(meta.getText()));
|
||||
properties.put("billboard", meta.getBillboardConstraints().name());
|
||||
properties.put("shadowed", String.valueOf(meta.isShadow()));
|
||||
properties.put("seeThrough", String.valueOf(meta.isSeeThrough()));
|
||||
properties.put("backgroundColor", String.valueOf(meta.getBackgroundColor()));
|
||||
properties.put("transformation", meta.getTranslation().toString());
|
||||
properties.put("yOffset", String.valueOf(offset));
|
||||
properties.put("scale", String.valueOf(meta.getScale()));
|
||||
properties.put("increasedOffset", String.valueOf(increasedOffset));
|
||||
properties.put("viewRange", String.valueOf(meta.getViewRange()));
|
||||
return properties;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package org.alexdev.unlimitednametags.placeholders;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class PAPIManager {
|
||||
@@ -13,8 +15,30 @@ public class PAPIManager {
|
||||
return plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String setPlaceholders(Player player, String text) {
|
||||
return me.clip.placeholderapi.PlaceholderAPI.setPlaceholders(player, text);
|
||||
if (text.isEmpty()) {
|
||||
return text;
|
||||
}
|
||||
try {
|
||||
return PlaceholderAPI.setPlaceholders(player, text);
|
||||
} catch (Throwable e) {
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to set placeholders for text: " + text, e);
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String setRelationalPlaceholders(@NotNull Player whoSees, @NotNull Player target, @NotNull String text) {
|
||||
if (text.isEmpty()) {
|
||||
return text;
|
||||
}
|
||||
try {
|
||||
return PlaceholderAPI.setRelationalPlaceholders(whoSees, target, text);
|
||||
} catch (Throwable e) {
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to set relational placeholders for text: " + text, e);
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,38 +1,77 @@
|
||||
package org.alexdev.unlimitednametags.placeholders;
|
||||
|
||||
import lombok.Getter;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.JoinConfiguration;
|
||||
import org.alexdev.unlimitednametags.UnlimitedNameTags;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.alexdev.unlimitednametags.config.Settings;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Getter
|
||||
public class PlaceholderManager {
|
||||
|
||||
private static final String ELSE_PLACEHOLDER = "ELSE";
|
||||
private static final int maxIndex = 16777215;
|
||||
private static final int maxMIndex = 10;
|
||||
private static final double minMGIndex = -1.0;
|
||||
private static final int MORE_LINES = 15;
|
||||
private final UnlimitedNameTags plugin;
|
||||
private final ExecutorService executorService;
|
||||
private int index = 16777215;
|
||||
private final PAPIManager papiManager;
|
||||
private int index = maxIndex;
|
||||
private int mmIndex = maxMIndex;
|
||||
private double mGIndex = 1.0;
|
||||
private DecimalFormat decimalFormat;
|
||||
|
||||
public PlaceholderManager(UnlimitedNameTags plugin) {
|
||||
public PlaceholderManager(@NotNull UnlimitedNameTags plugin) {
|
||||
this.plugin = plugin;
|
||||
this.executorService = Executors.newCachedThreadPool();
|
||||
this.executorService = Executors.newFixedThreadPool(5);
|
||||
this.papiManager = new PAPIManager(plugin);
|
||||
startIndexTask();
|
||||
createDecimalFormat();
|
||||
}
|
||||
|
||||
private void createDecimalFormat() {
|
||||
decimalFormat = new DecimalFormat("#.#");
|
||||
decimalFormat.setRoundingMode(RoundingMode.DOWN);
|
||||
|
||||
final DecimalFormatSymbols symbols = new DecimalFormatSymbols();
|
||||
symbols.setDecimalSeparator('.');
|
||||
decimalFormat.setDecimalFormatSymbols(symbols);
|
||||
}
|
||||
|
||||
private void startIndexTask() {
|
||||
Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, () -> {
|
||||
plugin.getTaskScheduler().runTaskTimerAsynchronously(() -> {
|
||||
index -= 1;
|
||||
if (index == 0) {
|
||||
index = 16777215;
|
||||
// index = 10000;
|
||||
}
|
||||
}, 0, 1);
|
||||
plugin.getTaskScheduler().runTaskTimerAsynchronously(() -> {
|
||||
mmIndex -= 1;
|
||||
if (mmIndex == 1) {
|
||||
mmIndex = maxMIndex;
|
||||
}
|
||||
}, 0, 2);
|
||||
plugin.getTaskScheduler().runTaskTimerAsynchronously(() -> {
|
||||
mGIndex += 0.1;
|
||||
if (mGIndex >= 1d) {
|
||||
mGIndex = minMGIndex;
|
||||
}
|
||||
}, 0, 2);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
@@ -40,22 +79,99 @@ public class PlaceholderManager {
|
||||
}
|
||||
|
||||
|
||||
public CompletableFuture<Component> applyPlaceholders(Player player, List<String> lines) {
|
||||
return CompletableFuture.supplyAsync(() -> createComponent(player, lines), executorService);
|
||||
@NotNull
|
||||
public CompletableFuture<Map<Player, Component>> applyPlaceholders(@NotNull Player player, @NotNull List<Settings.LinesGroup> lines,
|
||||
@NotNull List<Player> relationalPlayers) {
|
||||
return getCheckedLines(player, lines).thenApply(strings -> createComponent(player, strings, relationalPlayers));
|
||||
}
|
||||
|
||||
private Component createComponent(Player player, List<String> strings) {
|
||||
return Component.join(JoinConfiguration.separator(Component.newline()), strings.stream()
|
||||
// .map(text -> PlaceholderAPI.setPlaceholders(player, text))
|
||||
.map(t -> papiManager.isPAPIEnabled() ? papiManager.setPlaceholders(player, t) : t)
|
||||
.map(t -> t.replace("#val#", String.valueOf(index)))
|
||||
.map(this::format)
|
||||
.toArray(Component[]::new));
|
||||
@NotNull
|
||||
private CompletableFuture<List<String>> getCheckedLines(@NotNull Player player, @NotNull List<Settings.LinesGroup> lines) {
|
||||
return CompletableFuture.supplyAsync(() -> lines.parallelStream()
|
||||
.filter(l -> l.modifiers().stream().allMatch(m -> m.isVisible(player, plugin)))
|
||||
.map(Settings.LinesGroup::lines)
|
||||
.flatMap(List::stream)
|
||||
.toList(), executorService);
|
||||
}
|
||||
|
||||
private Component format(String value) {
|
||||
return plugin.getConfigManager().getSettings().getFormat().format(value);
|
||||
@NotNull
|
||||
private Map<Player, Component> createComponent(@NotNull Player player, @NotNull List<String> strings, @NotNull List<Player> relationalPlayers) {
|
||||
final double moreLines = plugin.getHatHooks().stream()
|
||||
.mapToDouble(h -> h.getHigh(player))
|
||||
.filter(h -> h > 0)
|
||||
.findFirst()
|
||||
.orElse(0d);
|
||||
|
||||
if (moreLines > 0) {
|
||||
strings = new ArrayList<>(strings);
|
||||
int lines = (int) (moreLines / MORE_LINES);
|
||||
for (int i = 0; i < lines; i++) {
|
||||
strings.add(" ");
|
||||
}
|
||||
}
|
||||
|
||||
final List<String> stringsCopy = papiManager.isPAPIEnabled() ?
|
||||
strings.stream()
|
||||
.map(s -> replacePlaceholders(s, player))
|
||||
.toList()
|
||||
: strings;
|
||||
return relationalPlayers.stream()
|
||||
.map(r -> Map.entry(r, Component.join(JoinConfiguration.separator(Component.newline()), stringsCopy.parallelStream()
|
||||
.map(t -> papiManager.isPAPIEnabled() ? papiManager.setRelationalPlaceholders(r, player, t) : t)
|
||||
.filter(s -> !plugin.getConfigManager().getSettings().isRemoveEmptyLines() || !s.isEmpty())
|
||||
.map(this::formatPhases)
|
||||
.map(t -> format(t, player))
|
||||
.filter(c -> !plugin.getConfigManager().getSettings().isRemoveEmptyLines() || !c.equals(Component.empty()))
|
||||
.toList())
|
||||
.compact()))
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private String formatPhases(@NotNull String value) {
|
||||
return value.replace("#phase-md#", Integer.toString(index))
|
||||
.replace("#phase-mm#", Integer.toString(mmIndex))
|
||||
.replace("#phase-mm-g#", decimalFormat.format(mGIndex))
|
||||
.replace("#-phase-md#", Integer.toString(maxIndex - index))
|
||||
.replace("#-phase-mm#", Integer.toString(maxMIndex - mmIndex))
|
||||
.replace("#-phase-mm-g#", decimalFormat.format(mGIndex * -1));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private Component format(@NotNull String value, @NotNull Player player) {
|
||||
return plugin.getConfigManager().getSettings().getFormat().format(plugin, player, value);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private String replacePlaceholders(@NotNull String string, @NotNull Player player) {
|
||||
for (Map.Entry<String, List<Settings.PlaceholderReplacement>> entry : plugin.getConfigManager().getSettings().getPlaceholdersReplacements().entrySet()) {
|
||||
if (!string.contains(entry.getKey())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final String replaced = papiManager.setPlaceholders(player, entry.getKey());
|
||||
final Optional<Settings.PlaceholderReplacement> replacement = entry.getValue().stream()
|
||||
.filter(r -> r.placeholder().equals(replaced))
|
||||
.findFirst();
|
||||
|
||||
if (replacement.isPresent()) {
|
||||
string = string.replace(entry.getKey(), replacement.get().replacement());
|
||||
} else {
|
||||
final Optional<Settings.PlaceholderReplacement> elseReplacement = entry.getValue().stream()
|
||||
.filter(r -> r.placeholder().equalsIgnoreCase(ELSE_PLACEHOLDER))
|
||||
.findFirst();
|
||||
if (elseReplacement.isPresent()) {
|
||||
string = string.replace(entry.getKey(), elseReplacement.get().replacement());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (papiManager.isPAPIEnabled()) {
|
||||
return papiManager.setPlaceholders(player, string);
|
||||
}
|
||||
|
||||
return string;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,12 +10,12 @@ public final class DefaultVanishIntegration implements VanishIntegration {
|
||||
|
||||
@Override
|
||||
public boolean canSee(@NotNull Player name, @NotNull Player other) {
|
||||
return true;
|
||||
return name.canSee(other);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanished(@NotNull Player name) {
|
||||
return false;
|
||||
return name.hasMetadata("vanished");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,27 @@
|
||||
name: UnlimitedNameTags
|
||||
version: '${version}'
|
||||
version: ${version}
|
||||
main: org.alexdev.unlimitednametags.UnlimitedNameTags
|
||||
api-version: '1.19'
|
||||
author: AlexDev_
|
||||
folia-supported: true
|
||||
libraries:
|
||||
- de.exlll:configlib-yaml:${configlibVersion}
|
||||
- de.exlll:configlib-paper:${configlibVersion}
|
||||
- net.jodah:expiringmap:${expiringMapVersion}
|
||||
- org.apache.commons:commons-jexl3:${commonsJexl3Version}
|
||||
depend:
|
||||
- packetevents
|
||||
softdepend:
|
||||
- PlaceholderAPI
|
||||
- ProtocolLib
|
||||
- ProtocolSupport
|
||||
- ViaVersion
|
||||
- ViaBackwards
|
||||
- ViaRewind
|
||||
- Oraxen
|
||||
permissions:
|
||||
unt.shownametags:
|
||||
default: true
|
||||
unt.showownnametag:
|
||||
default: true
|
||||
compiled: ${compiled}
|
||||
Reference in new issue
Block a user