diff options
110 files changed, 2215 insertions, 886 deletions
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3393d05..18146a8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -55,7 +55,7 @@ jobs: name: Upload runs-on: ubuntu-latest needs: build - if: ${{ 'push' == github.event_name && 'master' == github.ref_name && '637563904' == github.repository_id }} + if: ${{ 'push' == github.event_name && ('master' == github.ref_name || startsWith(github.ref_name, 'mc-')) && '637563904' == github.repository_id }} steps: - name: Download generated artifact uses: actions/download-artifact@v4 @@ -31,3 +31,4 @@ gradle-app.setting /logs/ *.xsd *.png~ +*.kra diff --git a/LICENSES/LGPL-3.0-or-later.txt b/LICENSES/LGPL-3.0-or-later.txt new file mode 100644 index 0000000..513d1c0 --- /dev/null +++ b/LICENSES/LGPL-3.0-or-later.txt @@ -0,0 +1,304 @@ +GNU LESSER GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. + +0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. + +"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". + +The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. +You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. + +2. Conveying Modified Versions. +If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: + + a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. + +3. Object Code Incorporating Material from Library Header Files. +The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license document. + +4. Combined Works. +You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: + + a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license document. + + c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. + + e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) + +5. Combined Libraries. +You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +6. Revised Versions of the GNU Lesser General Public License. +The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. + +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/> + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see <http://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 <http://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 <http://www.gnu.org/philosophy/why-not-lgpl.html>. @@ -28,6 +28,11 @@ SPDX-License-Identifier = "CC0-1.0" SPDX-FileCopyrightText = ["Linnea Gräf <nea@nea.moe>", "Firmament Contributors"] [[annotations]] +path = "**/fabric.mod.json" +SPDX-License-Identifier = "CC0-1.0" +SPDX-FileCopyrightText = ["Linnea Gräf <nea@nea.moe>", "Firmament Contributors"] + +[[annotations]] path = ["src/main/resources/assets/firmament/gui/**/*.xml"] SPDX-License-Identifier = "CC0-1.0" SPDX-FileCopyrightText = ["Linnea Gräf <nea@nea.moe>", "Firmament Contributors"] diff --git a/build.gradle.kts b/build.gradle.kts index c8bdfdb..ac6399d 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -14,9 +14,11 @@ import com.google.gson.JsonObject import moe.nea.licenseextractificator.LicenseDiscoveryTask import moe.nea.mcautotranslations.gradle.CollectTranslations import net.fabricmc.loom.LoomGradleExtension +import net.fabricmc.loom.task.RunGameTask import org.apache.tools.ant.taskdefs.condition.Os import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.jetbrains.kotlin.gradle.utils.extendsFrom import java.nio.charset.StandardCharsets import java.util.* @@ -27,10 +29,8 @@ plugins { alias(libs.plugins.kotlin.plugin.serialization) alias(libs.plugins.kotlin.plugin.powerassert) alias(libs.plugins.kotlin.plugin.ksp) - // alias(libs.plugins.loom) + alias(libs.plugins.loom) alias(libs.plugins.shadow) apply false - // TODO: use arch loom once they update to 1.8 - id("fabric-loom") version "1.10.1" id("firmament.common") id("firmament.license-management") alias(libs.plugins.mcAutoTranslations) @@ -184,6 +184,17 @@ val testAgent by configurations.creating { isVisible = false } +fabricApi.configureTests { + createSourceSet.set(true) + enableClientGameTests.set(true) + modId.set("firmament-gametest") + eula.set(true) + username.set("CoolGuy123") +} +val gameTestSourceSet by sourceSets.named("gametest") { + configurations.named(compileClasspathConfigurationName).extendsFrom(configurations.testCompileClasspath) + configurations.named(runtimeClasspathConfigurationName).extendsFrom(configurations.testRuntimeClasspath) +} val configuredSourceSet = createIsolatedSourceSet( "configured", @@ -252,8 +263,10 @@ dependencies { (yaclSourceSet.modImplementationConfigurationName)(libs.yacl) // Actual dependencies - (reiSourceSet.modImplementationConfigurationName)(libs.rei.api) - (reiSourceSet.modRuntimeOnlyConfigurationName)(libs.rei.fabric) + + val reiDeps = libs.rei.dev + (reiSourceSet.modImplementationConfigurationName)(reiDeps.api) + (reiSourceSet.modRuntimeOnlyConfigurationName)(reiDeps.fabric) nonModImplentation(libs.repoparser) shadowMe(libs.repoparser) fun ktor(mod: String) = "io.ktor:ktor-$mod-jvm:${libs.versions.ktor.get()}" @@ -279,6 +292,8 @@ dependencies { testImplementation("net.fabricmc:fabric-loader-junit:${libs.versions.fabric.loader.get()}") testAgent(files(tasks.getByPath(":testagent:jar"))) + "gametestImplementation"(sourceSets.test.map { it.output }) + implementation(projects.symbols) ksp(projects.symbols) } @@ -287,7 +302,7 @@ loom { clientOnlyMinecraftJar() accessWidenerPath.set(project.file("src/main/resources/firmament.accesswidener")) runs { - removeIf { it.name != "client" } + removeIf { it.name == "server" } configureEach { property("fabric.log.level", "info") property("firmament.debug", "true") diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d4ff2c4..707add4 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -3,42 +3,42 @@ # SPDX-License-Identifier: CC0-1.0 [versions] -minecraft = "1.21.5" +minecraft = "1.21.7" +# Update from https://maven.fabricmc.net/net/fabricmc/fabric-language-kotlin/ +fabric_kotlin = "1.13.2+kotlin.2.1.20" # Update from https://kotlinlang.org/ kotlin = "2.1.20" # Update from https://github.com/google/ksp/releases kotlin_ksp = "2.1.20-2.0.0" -# Update from https://linkie.shedaniel.me/dependencies?loader=fabric -fabric_loader = "0.16.13" -fabric_api = "0.119.9+1.21.5" -yarn = "1.21.5+build.1" -modmenu = "14.0.0-rc.2" -architectury = "16.0.3" +# Update from https://linkie.shedaniel.dev/dependencies?loader=fabric +yarn = "1.21.7+build.8" +fabric_loader = "0.16.14" +fabric_api = "0.129.0+1.21.7" +architectury = "17.0.6" +modmenu = "15.0.0-beta.3" # Update from https://maven.architectury.dev/me/shedaniel/RoughlyEnoughItems-fabric/ (but is typically late) rei = "19.0.805" - -# Update from https://maven.fabricmc.net/net/fabricmc/fabric-language-kotlin/ -fabric_kotlin = "1.13.2+kotlin.2.1.20" +reidev = "33d8900cd6621816680634fcbae2dd07f1cffbd3" # Update from https://maven.architectury.dev/dev/architectury/loom/dev.architectury.loom.gradle.plugin/ -loom = "1.7.414" # TODO: port back to architectury (and) 1.9.424 +loom = "1.10.433" # TODO: port back to architectury (and) 1.9.424 # Update from https://modrinth.com/mod/qolify/versions?l=fabric qolify = "1.6.0-1.21.1" # Update from https://modrinth.com/mod/sodium/versions?l=fabric -sodium = "mc1.21.5-0.6.13-fabric" +sodium = "mc1.21.6-0.6.13-fabric" # Update from https://modrinth.com/mod/freecam/versions?l=fabric -freecammod = "1.3.3+mc1.21.5" +freecammod = "1.3.4+mc1.21.6" # Update from https://modrinth.com/mod/no-chat-reports/versions?l=fabric -ncr = "Fabric-1.21.5-v2.12.0" +ncr = "Fabric-1.21.7-v2.14.0" # Update from https://modrinth.com/mod/female-gender/versions?l=fabric -femalegender = "4.3.4+1.21.5" +femalegender = "4.3.4+1.21.7" shadow = "8.3.8" @@ -46,18 +46,18 @@ shadow = "8.3.8" explosiveenhancement = "1.2.3-1.21.0" # Update from https://modrinth.com/mod/not-enough-animations/versions?l=fabric -notenoughanimations = "prj4BdjU" +notenoughanimations = "JTLkasT1" -# Update from https://modrinth.com/mod/cit-resewn/versions?l=fabric +# Update from https://modrinth.com/mod/cit-resewn/versions?l=fabric lmao yeah sure citresewn = "1.2.0+1.21" # Update from https://modrinth.com/mod/jade/versions?l=fabric -jade = "18.1.0+fabric" +jade = "19.0.4+fabric" devauth = "1.2.1" # Update from https://ktor.io/docs/ -ktor = "3.1.2" +ktor = "3.2.2" # Update from https://repo.nea.moe/#/releases/moe/nea/neurepoparser neurepoparser = "1.8.0" @@ -69,11 +69,13 @@ hotswap_agent = "1.4.2-SNAPSHOT" # Update from https://github.com/LlamaLad7/MixinExtras/tags mixinextras = "0.4.1" -jarvis = "1.1.4" +# Update from https://repo.nea.moe/#/releases/moe/nea/jarvis/ +jarvis = "2.0.0" + nealisp = "1.1.0" # Update from https://github.com/NotEnoughUpdates/MoulConfig/tags -moulconfig = "4.0.1-beta" +moulconfig = "4.1.0-beta" # Update from https://repo.nea.moe/#/releases/moe/nea/mc-auto-translations/moe.nea.mc-auto-translations.gradle.plugin mcAutoTranslations = "0.3.0" @@ -90,7 +92,7 @@ manninghamMills = "2.4.1" # Update from https://docs.isxander.dev/yet-another-config-lib/installing-yacl # Nvm, they just don't update docs: https://modrinth.com/mod/yacl/versions?l=fabric -yacl = "3.6.6+1.21.5-fabric" +yacl = "3.7.1+1.21.6-fabric" # Update from https://maven.shedaniel.me/me/shedaniel/cloth/basic-math/ basicMath = "0.6.1" @@ -108,8 +110,14 @@ fabric_api = { module = "net.fabricmc.fabric-api:fabric-api", version.ref = "fab fabric_api_deprecated = { module = "net.fabricmc.fabric-api:fabric-api-deprecated", version.ref = "fabric_api" } fabric_kotlin = { module = "net.fabricmc:fabric-language-kotlin", version.ref = "fabric_kotlin" } architectury = { module = "dev.architectury:architectury", version.ref = "architectury" } + rei_api = { module = "me.shedaniel:RoughlyEnoughItems-api", version.ref = "rei" } -moulconfig = { module = "org.notenoughupdates.moulconfig:modern-1.21.5", version.ref = "moulconfig" } +rei_fabric = { module = "me.shedaniel:RoughlyEnoughItems-fabric", version.ref = "rei" } + +rei_dev_api = { module = "com.github.shedaniel.roughlyenoughitems:RoughlyEnoughItems-api", version.ref = "reidev" } +rei_dev_fabric = { module = "com.github.shedaniel.roughlyenoughitems:RoughlyEnoughItems-fabric", version.ref = "reidev" } + +moulconfig = { module = "org.notenoughupdates.moulconfig:modern-1.21.7", version.ref = "moulconfig" } repoparser = { module = "moe.nea:neurepoparser", version.ref = "neurepoparser" } mixinextras = { module = "io.github.llamalad7:mixinextras-fabric", version.ref = "mixinextras" } jarvis_api = { module = "moe.nea.jarvis:jarvis-api", version.ref = "jarvis" } @@ -125,7 +133,6 @@ configured = { module = "curse.maven:configured-457570", version.ref = "configur notenoughanimations = { module = "maven.modrinth:not-enough-animations", version.ref = "notenoughanimations" } hotswap = { module = "virtual.github.hotswapagent:hotswap-agent", version.ref = "hotswap_agent" } architectury_fabric = { module = "dev.architectury:architectury-fabric", version.ref = "architectury" } -rei_fabric = { module = "me.shedaniel:RoughlyEnoughItems-fabric", version.ref = "rei" } devauth = { module = "me.djtheredstoner:DevAuth-fabric", version.ref = "devauth" } modmenu = { module = "maven.modrinth:modmenu", version.ref = "modmenu" } qolify = { module = "maven.modrinth:qolify", version.ref = "qolify" } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 4cdd0fb..8b8fb18 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -4,6 +4,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/compat/jade/java/moe/nea/firmament/compat/jade/DrillToolProvider.kt b/src/compat/jade/java/moe/nea/firmament/compat/jade/DrillToolProvider.kt index 10bff1b..addfc42 100644 --- a/src/compat/jade/java/moe/nea/firmament/compat/jade/DrillToolProvider.kt +++ b/src/compat/jade/java/moe/nea/firmament/compat/jade/DrillToolProvider.kt @@ -1,6 +1,5 @@ package moe.nea.firmament.compat.jade -import java.util.Optional import java.util.function.UnaryOperator import snownee.jade.api.BlockAccessor import snownee.jade.api.IBlockComponentProvider @@ -8,14 +7,13 @@ import snownee.jade.api.ITooltip import snownee.jade.api.JadeIds import snownee.jade.api.config.IPluginConfig import snownee.jade.api.theme.IThemeHelper -import snownee.jade.api.ui.IElement -import snownee.jade.api.ui.IElementHelper +import snownee.jade.api.ui.Element +import snownee.jade.api.ui.JadeUI +import snownee.jade.gui.JadeLinearLayout import snownee.jade.impl.ui.ItemStackElement -import snownee.jade.impl.ui.TextElement -import kotlin.jvm.optionals.getOrDefault +import snownee.jade.impl.ui.TextElementImpl import net.minecraft.text.Text import net.minecraft.util.Identifier -import net.minecraft.util.math.Vec2f import moe.nea.firmament.Firmament import moe.nea.firmament.repo.ExpensiveItemCacheApi import moe.nea.firmament.repo.RepoManager @@ -38,34 +36,31 @@ class DrillToolProvider : IBlockComponentProvider { if (lastItemIndex < 0) return@map inner val innerMut = inner.toMutableList() val harvestIndicator = innerMut.indexOfLast { - it is TextElement && it.cachedSize == Vec2f.ZERO && it.text.visit { - if (it.isEmpty()) Optional.empty() else Optional.of(true) - }.getOrDefault(false) + it is TextElementImpl && it.width == 0 && it.string.isNotEmpty() } val canHarvest = SBItemStack(MC.stackInHand).breakingPower >= customBlock.breakingPower val lastItem = innerMut[lastItemIndex] as ItemStackElement if (harvestIndicator < 0) { - innerMut.add(lastItemIndex + 1, canHarvestIndicator(canHarvest, lastItem.alignment)) + innerMut.add(lastItemIndex + 1, canHarvestIndicator(canHarvest)) } else { - innerMut.set(harvestIndicator, canHarvestIndicator(canHarvest, lastItem.alignment)) + innerMut.set(harvestIndicator, canHarvestIndicator(canHarvest)) } - innerMut.set(lastItemIndex, IElementHelper.get() - .item(tool, 0.75f) - .translate(lastItem.translation) - .size(lastItem.size) - .message(null) - .align(lastItem.alignment)) + innerMut.set( + lastItemIndex, JadeUI + .item(tool, 0.75f) + ) innerMut.subList(0, lastItemIndex - 1).removeIf { it is ItemStackElement } innerMut } }) } - fun canHarvestIndicator(canHarvest: Boolean, align: IElement.Align): IElement { + fun canHarvestIndicator(canHarvest: Boolean): Element { val t = IThemeHelper.get() val text = if (canHarvest) t.success(CHECK) else t.danger(X) - return IElementHelper.get().text(text) - .scale(0.75F).zOffset(800).size(Vec2f.ZERO).translate(Vec2f(-3F, 3.25F)).align(align) + return JadeUI.text(text) + .scale(0.75F) + .alignSelfCenter() } private val CHECK: Text = Text.literal("✔") diff --git a/src/compat/jade/java/moe/nea/firmament/mixins/compat/jade/ElementAccessor.java b/src/compat/jade/java/moe/nea/firmament/mixins/compat/jade/ElementAccessor.java deleted file mode 100644 index 1b58e3c..0000000 --- a/src/compat/jade/java/moe/nea/firmament/mixins/compat/jade/ElementAccessor.java +++ /dev/null @@ -1,12 +0,0 @@ -package moe.nea.firmament.mixins.compat.jade; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; -import snownee.jade.api.ui.Element; -import snownee.jade.api.ui.IElement; - -@Mixin(Element.class) -public interface ElementAccessor { - @Accessor("align") - IElement.Align getAlign_firmament(); -} diff --git a/src/compat/moulconfig/java/MCConfigEditorIntegration.kt b/src/compat/moulconfig/java/MCConfigEditorIntegration.kt index 874e58d..a568c19 100644 --- a/src/compat/moulconfig/java/MCConfigEditorIntegration.kt +++ b/src/compat/moulconfig/java/MCConfigEditorIntegration.kt @@ -7,8 +7,10 @@ import io.github.notenoughupdates.moulconfig.DescriptionRendereringBehaviour import io.github.notenoughupdates.moulconfig.Social import io.github.notenoughupdates.moulconfig.common.IMinecraft import io.github.notenoughupdates.moulconfig.common.MyResourceLocation +import io.github.notenoughupdates.moulconfig.common.text.StructuredText import io.github.notenoughupdates.moulconfig.gui.GuiComponent -import io.github.notenoughupdates.moulconfig.gui.GuiElementWrapper +import io.github.notenoughupdates.moulconfig.gui.GuiContext +import io.github.notenoughupdates.moulconfig.gui.GuiElementComponent import io.github.notenoughupdates.moulconfig.gui.GuiOptionEditor import io.github.notenoughupdates.moulconfig.gui.HorizontalAlign import io.github.notenoughupdates.moulconfig.gui.MoulConfigEditor @@ -25,6 +27,8 @@ import io.github.notenoughupdates.moulconfig.gui.editors.GuiOptionEditorColour import io.github.notenoughupdates.moulconfig.gui.editors.GuiOptionEditorDropdown import io.github.notenoughupdates.moulconfig.gui.editors.GuiOptionEditorText import io.github.notenoughupdates.moulconfig.observer.GetSetter +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform +import io.github.notenoughupdates.moulconfig.platform.MoulConfigScreenComponent import io.github.notenoughupdates.moulconfig.processor.ProcessedCategory import io.github.notenoughupdates.moulconfig.processor.ProcessedOption import java.lang.reflect.Type @@ -33,6 +37,7 @@ import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds import kotlin.time.DurationUnit import net.minecraft.client.gui.screen.Screen +import net.minecraft.text.Text import net.minecraft.util.Identifier import net.minecraft.util.StringIdentifiable import net.minecraft.util.Util @@ -104,8 +109,8 @@ class MCConfigEditorIntegration : FirmamentConfigScreenProvider { RowComponent( AlignComponent( TextComponent( - IMinecraft.instance.defaultFontRenderer, - { formatter(setter.get()) }, + IMinecraft.INSTANCE.defaultFontRenderer, + { StructuredText.of(formatter(setter.get())) }, 25, TextComponent.TextAlignment.CENTER, false, false ), @@ -212,7 +217,7 @@ class MCConfigEditorIntegration : FirmamentConfigScreenProvider { register(ClickHandler::class.java) { handler, option, categoryAccordionId, configObject -> object : ProcessedEditableOptionFirm<Unit>(option, categoryAccordionId, configObject) { override fun createEditor(): GuiOptionEditor { - return GuiOptionEditorButton(this, -1, "Click", configObject) + return GuiOptionEditorButton(this, -1, StructuredText.of("Click"), configObject) } override fun toT(any: Any?): Unit? { @@ -231,7 +236,7 @@ class MCConfigEditorIntegration : FirmamentConfigScreenProvider { register(HudMetaHandler::class.java) { handler, option, categoryAccordionId, configObject -> object : ProcessedEditableOptionFirm<HudMeta>(option, categoryAccordionId, configObject) { override fun createEditor(): GuiOptionEditor { - return GuiOptionEditorButton(this, -1, "Edit HUD", configObject) + return GuiOptionEditorButton(this, -1, StructuredText.of("Edit HUD"), configObject) } override fun fromT(t: HudMeta): Any { @@ -337,8 +342,8 @@ class MCConfigEditorIntegration : FirmamentConfigScreenProvider { return true } - override fun getTitle(): String { - return "Firmament ${Firmament.version.friendlyString}" + override fun getTitle(): StructuredText { + return StructuredText.of("Firmament ${Firmament.version.friendlyString}") } @Deprecated("Deprecated in java") @@ -356,8 +361,8 @@ class MCConfigEditorIntegration : FirmamentConfigScreenProvider { Util.getOperatingSystem().open(URI(link)) } - override fun getTooltip(): List<String> { - return listOf(name) + override fun getTooltip(): List<StructuredText> { + return listOf(StructuredText.of(name)) } override fun getIcon(): MyResourceLocation { @@ -394,12 +399,12 @@ class MCConfigEditorIntegration : FirmamentConfigScreenProvider { return "FirmamentConfig:${config.name}" } - override fun getName(): String { - return config.labelText.string + override fun getName(): StructuredText { + return MoulConfigPlatform.wrap(config.labelText) } - override fun getDescription(): String { - return "Missing description" + override fun getDescription(): StructuredText { + return StructuredText.of("Missing description") } override fun get(): Any { @@ -432,7 +437,7 @@ class MCConfigEditorIntegration : FirmamentConfigScreenProvider { if (search != null) editor.search(search) editor.setWide(AllConfigsGui.ConfigConfig.enableWideMC) - return GuiElementWrapper(editor) // TODO : add parent support + return MoulConfigScreenComponent(Text.empty(), GuiContext(GuiElementComponent(editor)), parent) // TODO : add parent support } } diff --git a/src/compat/moulconfig/java/ProcessedCategoryFirm.kt b/src/compat/moulconfig/java/ProcessedCategoryFirm.kt index 5313441..38a613a 100644 --- a/src/compat/moulconfig/java/ProcessedCategoryFirm.kt +++ b/src/compat/moulconfig/java/ProcessedCategoryFirm.kt @@ -1,6 +1,8 @@ package moe.nea.firmament.compat.moulconfig +import io.github.notenoughupdates.moulconfig.common.text.StructuredText import io.github.notenoughupdates.moulconfig.gui.editors.GuiOptionEditorAccordion +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform import io.github.notenoughupdates.moulconfig.processor.ProcessedCategory import io.github.notenoughupdates.moulconfig.processor.ProcessedOption import moe.nea.firmament.gui.config.ManagedConfig @@ -21,12 +23,12 @@ class ProcessedCategoryFirm( return "FirmamentCategory.${category.name}" } - override fun getDisplayName(): String { - return category.labelText.string + override fun getDisplayName(): StructuredText { + return MoulConfigPlatform.wrap(category.labelText) } - override fun getDescription(): String { - return category.description.string + override fun getDescription(): StructuredText { + return MoulConfigPlatform.wrap(category.description) } override fun getIdentifier(): String { diff --git a/src/compat/moulconfig/java/ProcessedEditableOptionFirm.kt b/src/compat/moulconfig/java/ProcessedEditableOptionFirm.kt index f0e9aa4..ac23ec7 100644 --- a/src/compat/moulconfig/java/ProcessedEditableOptionFirm.kt +++ b/src/compat/moulconfig/java/ProcessedEditableOptionFirm.kt @@ -1,6 +1,8 @@ package moe.nea.firmament.compat.moulconfig import io.github.notenoughupdates.moulconfig.Config +import io.github.notenoughupdates.moulconfig.common.text.StructuredText +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform import moe.nea.firmament.gui.config.ManagedOption import moe.nea.firmament.util.ErrorUtil @@ -14,12 +16,12 @@ abstract class ProcessedEditableOptionFirm<T : Any>( return "FirmamentOption:${managedConfig.name}:${managedOption.propertyName}" } - override fun getName(): String { - return managedOption.labelText.string + override fun getName(): StructuredText { + return MoulConfigPlatform.wrap(managedOption.labelText) } - override fun getDescription(): String { - return managedOption.labelDescription.string + override fun getDescription(): StructuredText { + return MoulConfigPlatform.wrap(managedOption.labelDescription) } abstract fun fromT(t: T): Any diff --git a/src/compat/rei/java/moe/nea/firmament/compat/rei/NEUItemEntryRenderer.kt b/src/compat/rei/java/moe/nea/firmament/compat/rei/NEUItemEntryRenderer.kt index 5e4eee3..f881f77 100644 --- a/src/compat/rei/java/moe/nea/firmament/compat/rei/NEUItemEntryRenderer.kt +++ b/src/compat/rei/java/moe/nea/firmament/compat/rei/NEUItemEntryRenderer.kt @@ -52,9 +52,9 @@ object NEUItemEntryRenderer : EntryRenderer<SBItemStack> { entry.value.asImmutableItemStack() } - context.matrices.push() - context.matrices.translate(bounds.centerX.toFloat(), bounds.centerY.toFloat(), 0F) - context.matrices.scale(bounds.width.toFloat() / 16F, bounds.height.toFloat() / 16F, 1f) + context.matrices.pushMatrix() + context.matrices.translate(bounds.centerX.toFloat(), bounds.centerY.toFloat(), ) + context.matrices.scale(bounds.width.toFloat() / 16F, bounds.height.toFloat() / 16F, ) context.drawItemWithoutEntity(itemToRender, -8, -8) context.drawStackOverlay( minecraft.textRenderer, itemToRender, -8, -8, @@ -64,7 +64,7 @@ object NEUItemEntryRenderer : EntryRenderer<SBItemStack> { ) else null ) - context.matrices.pop() + context.matrices.popMatrix() } val minecraft = MinecraftClient.getInstance() diff --git a/src/compat/rei/java/moe/nea/firmament/compat/rei/recipes/SBKatRecipe.kt b/src/compat/rei/java/moe/nea/firmament/compat/rei/recipes/SBKatRecipe.kt index cce1465..cb7877d 100644 --- a/src/compat/rei/java/moe/nea/firmament/compat/rei/recipes/SBKatRecipe.kt +++ b/src/compat/rei/java/moe/nea/firmament/compat/rei/recipes/SBKatRecipe.kt @@ -8,7 +8,7 @@ import io.github.notenoughupdates.moulconfig.gui.MouseEvent import io.github.notenoughupdates.moulconfig.gui.component.SliderComponent import io.github.notenoughupdates.moulconfig.observer.GetSetter import io.github.notenoughupdates.moulconfig.observer.Property -import io.github.notenoughupdates.moulconfig.platform.ModernRenderContext +import io.github.notenoughupdates.moulconfig.platform.MoulConfigRenderContext import me.shedaniel.math.Point import me.shedaniel.math.Rectangle import me.shedaniel.rei.api.client.gui.Renderer @@ -17,7 +17,6 @@ import me.shedaniel.rei.api.client.gui.widgets.WidgetWithBounds import me.shedaniel.rei.api.client.gui.widgets.Widgets import me.shedaniel.rei.api.client.registry.display.DisplayCategory import me.shedaniel.rei.api.common.category.CategoryIdentifier -import me.shedaniel.rei.api.common.util.EntryStacks import kotlin.time.Duration.Companion.seconds import net.minecraft.client.gui.DrawContext import net.minecraft.client.gui.Element @@ -55,11 +54,13 @@ class SBKatRecipe(override val neuRecipe: NEUKatUpgradeRecipe) : SBRecipe() { val inputLevelLabelCenter = Point(bounds.minX + 30 - 18 + 5 + 8, bounds.minY + 25) val inputLevelLabel = Widgets.createLabel( inputLevelLabelCenter, - Text.literal("")).centered() + Text.literal("") + ).centered() val outputLevelLabelCenter = Point(bounds.maxX - 30 + 8, bounds.minY + 25) val outputLevelLabel = Widgets.createLabel( outputLevelLabelCenter, - Text.literal("")).centered() + Text.literal("") + ).centered() val coinStack = SBItemStack(SkyblockId.COINS, recipe.coins.toInt()) levelValue.whenChanged { oldValue, newValue -> if (oldValue.toInt() == newValue.toInt()) return@whenChanged @@ -72,40 +73,60 @@ class SBKatRecipe(override val neuRecipe: NEUKatUpgradeRecipe) : SBRecipe() { inputLevelLabel.message = Text.literal(newInput.levelData.currentLevel.toString()) inputLevelLabel.bounds.location = Point( inputLevelLabelCenter.x - MC.font.getWidth(inputLevelLabel.message) / 2, - inputLevelLabelCenter.y) + inputLevelLabelCenter.y + ) outputLevelLabel.message = Text.literal(newOutput.levelData.currentLevel.toString()) outputLevelLabel.bounds.location = Point( outputLevelLabelCenter.x - MC.font.getWidth(outputLevelLabel.message) / 2, - outputLevelLabelCenter.y) + outputLevelLabelCenter.y + ) coinStack.setStackSize((recipe.coins * (1 - 0.3 * newValue / 100)).toInt()) } levelValue.set(1F) add(Widgets.createRecipeBase(bounds)) - add(wrapWidget(Rectangle(bounds.centerX - slider.width / 2, - bounds.maxY - 30, - slider.width, - slider.height), - slider)) - add(Widgets.withTooltip( - Widgets.createArrow(Point(bounds.centerX - arrowWidth / 2, bounds.minY + 40)), - Text.literal("Upgrade time: " + FirmFormatters.formatTimespan(recipe.seconds.seconds)))) + add( + wrapWidget( + Rectangle( + bounds.centerX - slider.width / 2, + bounds.maxY - 30, + slider.width, + slider.height + ), + slider + ) + ) + add( + Widgets.withTooltip( + Widgets.createArrow(Point(bounds.centerX - arrowWidth / 2, bounds.minY + 40)), + Text.literal("Upgrade time: " + FirmFormatters.formatTimespan(recipe.seconds.seconds)) + ) + ) add(Widgets.createResultSlotBackground(Point(bounds.maxX - 30, bounds.minY + 40))) add(inputLevelLabel) add(outputLevelLabel) - add(Widgets.createSlot(Point(bounds.maxX - 30, bounds.minY + 40)).markOutput().disableBackground() - .entry(SBItemEntryDefinition.getEntry(outputStack))) - add(Widgets.createSlot(Point(bounds.minX + 30 - 18 + 5, bounds.minY + 40)).markInput() - .entry(SBItemEntryDefinition.getEntry(inputStack))) + add( + Widgets.createSlot(Point(bounds.maxX - 30, bounds.minY + 40)).markOutput().disableBackground() + .entry(SBItemEntryDefinition.getEntry(outputStack)) + ) + add( + Widgets.createSlot(Point(bounds.minX + 30 - 18 + 5, bounds.minY + 40)).markInput() + .entry(SBItemEntryDefinition.getEntry(inputStack)) + ) val allInputs = recipe.items.map { SBItemEntryDefinition.getEntry(it) } + listOf(SBItemEntryDefinition.getEntry(coinStack)) for ((index, item) in allInputs.withIndex()) { - add(Widgets.createSlot( - Point(bounds.centerX + index * 20 - allInputs.size * 18 / 2 - (allInputs.size - 1) * 2 / 2, - bounds.minY + 20)) - .markInput() - .entry(item)) + add( + Widgets.createSlot( + Point( + bounds.centerX + index * 20 - allInputs.size * 18 / 2 - (allInputs.size - 1) * 2 / 2, + bounds.minY + 20 + ) + ) + .markInput() + .entry(item) + ) } } } @@ -123,60 +144,67 @@ fun wrapWidget(bounds: Rectangle, component: GuiComponent): Widget { } override fun render(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { - context.matrices.push() - context.matrices.translate(bounds.minX.toFloat(), bounds.minY.toFloat(), 0F) + context.matrices.pushMatrix() + context.matrices.translate(bounds.minX.toFloat(), bounds.minY.toFloat()) component.render( GuiImmediateContext( - ModernRenderContext(context), + MoulConfigRenderContext(context), bounds.minX, bounds.minY, bounds.width, bounds.height, mouseX - bounds.minX, mouseY - bounds.minY, mouseX, mouseY, mouseX.toFloat(), mouseY.toFloat() - )) - context.matrices.pop() + ) + ) + context.matrices.popMatrix() } override fun mouseMoved(mouseX: Double, mouseY: Double) { val mouseXInt = mouseX.toInt() val mouseYInt = mouseY.toInt() - component.mouseEvent(MouseEvent.Move(0F, 0F), - GuiImmediateContext( - IMinecraft.instance.provideTopLevelRenderContext(), - bounds.minX, bounds.minY, - bounds.width, bounds.height, - mouseXInt - bounds.minX, mouseYInt - bounds.minY, - mouseXInt, mouseYInt, - mouseX.toFloat(), mouseY.toFloat() - )) + component.mouseEvent( + MouseEvent.Move(0F, 0F), + GuiImmediateContext( + IMinecraft.INSTANCE.provideTopLevelRenderContext(), + bounds.minX, bounds.minY, + bounds.width, bounds.height, + mouseXInt - bounds.minX, mouseYInt - bounds.minY, + mouseXInt, mouseYInt, + mouseX.toFloat(), mouseY.toFloat() + ) + ) } override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean { val mouseXInt = mouseX.toInt() val mouseYInt = mouseY.toInt() - return component.mouseEvent(MouseEvent.Click(button, true), - GuiImmediateContext( - IMinecraft.instance.provideTopLevelRenderContext(), - bounds.minX, bounds.minY, - bounds.width, bounds.height, - mouseXInt - bounds.minX, mouseYInt - bounds.minY, - mouseXInt, mouseYInt, - mouseX.toFloat(), mouseY.toFloat() - )) + return component.mouseEvent( + MouseEvent.Click(button, true), + GuiImmediateContext( + IMinecraft.INSTANCE.provideTopLevelRenderContext(), + bounds.minX, bounds.minY, + bounds.width, bounds.height, + mouseXInt - bounds.minX, mouseYInt - bounds.minY, + mouseXInt, mouseYInt, + mouseX.toFloat(), mouseY.toFloat() + ) + ) } override fun mouseReleased(mouseX: Double, mouseY: Double, button: Int): Boolean { val mouseXInt = mouseX.toInt() val mouseYInt = mouseY.toInt() - return component.mouseEvent(MouseEvent.Click(button, false), - GuiImmediateContext( - IMinecraft.instance.provideTopLevelRenderContext(), - bounds.minX, bounds.minY, - bounds.width, bounds.height, - mouseXInt - bounds.minX, mouseYInt - bounds.minY, - mouseXInt, mouseYInt, - mouseX.toFloat(), mouseY.toFloat() - )) + return component.mouseEvent( + MouseEvent.Click(button, false), + GuiImmediateContext( + IMinecraft.INSTANCE.provideTopLevelRenderContext(), + bounds.minX, bounds.minY, + bounds.width, bounds.height, + mouseXInt - bounds.minX, mouseYInt - bounds.minY, + mouseXInt, mouseYInt, + mouseX.toFloat(), mouseY.toFloat() + ) + ) } override fun mouseDragged( @@ -188,15 +216,17 @@ fun wrapWidget(bounds: Rectangle, component: GuiComponent): Widget { ): Boolean { val mouseXInt = mouseX.toInt() val mouseYInt = mouseY.toInt() - return component.mouseEvent(MouseEvent.Move(deltaX.toFloat(), deltaY.toFloat()), - GuiImmediateContext( - IMinecraft.instance.provideTopLevelRenderContext(), - bounds.minX, bounds.minY, - bounds.width, bounds.height, - mouseXInt - bounds.minX, mouseYInt - bounds.minY, - mouseXInt, mouseYInt, - mouseX.toFloat(), mouseY.toFloat() - )) + return component.mouseEvent( + MouseEvent.Move(deltaX.toFloat(), deltaY.toFloat()), + GuiImmediateContext( + IMinecraft.INSTANCE.provideTopLevelRenderContext(), + bounds.minX, bounds.minY, + bounds.width, bounds.height, + mouseXInt - bounds.minX, mouseYInt - bounds.minY, + mouseXInt, mouseYInt, + mouseX.toFloat(), mouseY.toFloat() + ) + ) } @@ -208,15 +238,17 @@ fun wrapWidget(bounds: Rectangle, component: GuiComponent): Widget { ): Boolean { val mouseXInt = mouseX.toInt() val mouseYInt = mouseY.toInt() - return component.mouseEvent(MouseEvent.Scroll(verticalAmount.toFloat()), - GuiImmediateContext( - IMinecraft.instance.provideTopLevelRenderContext(), - bounds.minX, bounds.minY, - bounds.width, bounds.height, - mouseXInt - bounds.minX, mouseYInt - bounds.minY, - mouseXInt, mouseYInt, - mouseX.toFloat(), mouseY.toFloat() - )) + return component.mouseEvent( + MouseEvent.Scroll(verticalAmount.toFloat()), + GuiImmediateContext( + IMinecraft.INSTANCE.provideTopLevelRenderContext(), + bounds.minX, bounds.minY, + bounds.width, bounds.height, + mouseXInt - bounds.minX, mouseYInt - bounds.minY, + mouseXInt, mouseYInt, + mouseX.toFloat(), mouseY.toFloat() + ) + ) } } } diff --git a/src/compat/rei/java/moe/nea/firmament/compat/rei/recipes/SBReforgeRecipe.kt b/src/compat/rei/java/moe/nea/firmament/compat/rei/recipes/SBReforgeRecipe.kt index fca3edf..cc05861 100644 --- a/src/compat/rei/java/moe/nea/firmament/compat/rei/recipes/SBReforgeRecipe.kt +++ b/src/compat/rei/java/moe/nea/firmament/compat/rei/recipes/SBReforgeRecipe.kt @@ -74,13 +74,37 @@ class SBReforgeRecipe( val inputSlot = Widgets.createSlot(Point(bounds.minX + 10, bounds.centerY - 9)) .markInput().entries(display.inputItems) list.add(inputSlot) + list.add(Widgets.createSlot(Point(bounds.minX + 10 + 24 + 24, bounds.centerY - 9)) + .markInput().entries(display.outputItems)) + val statToLineMappings = mutableListOf<Pair<String, Label>>() + for ((i, statId) in display.reforge.statUniverse.withIndex()) { + val label = Widgets.createLabel( + Point(bounds.minX + 10 + 24 + 24 + 20, bounds.minY + 8 + i * 11), + SBItemStack.Companion.StatLine(SBItemStack.statIdToName(statId), null).reconstitute(7)) + .horizontalAlignment(Label.LEFT_ALIGNED) + statToLineMappings.add(statId to label) + list.add(label) + } + fun updateStatLines() { + val entry = inputSlot.currentEntry?.castValue<SBItemStack>() ?: return + val stats = display.reforge.reforgeStats?.get(entry.rarity) ?: mapOf() + for ((stat, label) in statToLineMappings) { + label.message = + SBItemStack.Companion.StatLine( + SBItemStack.statIdToName(stat), null, + valueNum = stats[stat] + ).reconstitute(7) + } + } + updateStatLines() + inputSlot.withEntriesListener { updateStatLines() } if (display.reforgeStone != null) { list.add(Widgets.createSlot(Point(bounds.minX + 10 + 24, bounds.centerY - 9 - 10)) - .markInput().entry(display.reforgeStone)) + .markInput().entry(display.reforgeStone)) list.add(Widgets.withTooltip( - Widgets.withTranslate(Widgets.wrapRenderer( + Widgets.wrapRenderer( Rectangle(Point(bounds.minX + 10 + 24, bounds.centerY - 9 + 10), Dimension(16, 16)), - SBItemEntryDefinition.getEntry(SkyBlockItems.REFORGE_ANVIL)), 0.0, 0.0, 150.0), + SBItemEntryDefinition.getEntry(SkyBlockItems.REFORGE_ANVIL)), Rarity.entries.mapNotNull { rarity -> display.reforge.reforgeCosts?.get(rarity)?.let { rarity to it } }.map { (rarity, cost) -> @@ -102,33 +126,9 @@ class SBReforgeRecipe( dimension ), tr("firmament.recipecategory.reforge.basic", - "This is a basic reforge, available at the Blacksmith.").grey() + "This is a basic reforge, available at the Blacksmith.").grey() )) } - list.add(Widgets.createSlot(Point(bounds.minX + 10 + 24 + 24, bounds.centerY - 9)) - .markInput().entries(display.outputItems)) - val statToLineMappings = mutableListOf<Pair<String, Label>>() - for ((i, statId) in display.reforge.statUniverse.withIndex()) { - val label = Widgets.createLabel( - Point(bounds.minX + 10 + 24 + 24 + 20, bounds.minY + 8 + i * 11), - SBItemStack.Companion.StatLine(SBItemStack.statIdToName(statId), null).reconstitute(7)) - .horizontalAlignment(Label.LEFT_ALIGNED) - statToLineMappings.add(statId to label) - list.add(label) - } - fun updateStatLines() { - val entry = inputSlot.currentEntry?.castValue<SBItemStack>() ?: return - val stats = display.reforge.reforgeStats?.get(entry.rarity) ?: mapOf() - for ((stat, label) in statToLineMappings) { - label.message = - SBItemStack.Companion.StatLine( - SBItemStack.statIdToName(stat), null, - valueNum = stats[stat] - ).reconstitute(7) - } - } - updateStatLines() - inputSlot.withEntriesListener { updateStatLines() } return list } } diff --git a/src/gametest/kotlin/moe/nea/firmament/gametest/GameTest.kt b/src/gametest/kotlin/moe/nea/firmament/gametest/GameTest.kt new file mode 100644 index 0000000..0ef0340 --- /dev/null +++ b/src/gametest/kotlin/moe/nea/firmament/gametest/GameTest.kt @@ -0,0 +1,24 @@ +package moe.nea.firmament.gametest + +import net.fabricmc.fabric.api.client.gametest.v1.FabricClientGameTest +import net.fabricmc.fabric.api.client.gametest.v1.context.ClientGameTestContext +import org.junit.jupiter.api.Assertions +import org.spongepowered.asm.mixin.MixinEnvironment +import moe.nea.firmament.init.MixinPlugin +import moe.nea.firmament.test.FirmTestBootstrap + +class GameTest : FabricClientGameTest { + override fun runTest(ctx: ClientGameTestContext) { + FirmTestBootstrap.bootstrapMinecraft() + MixinEnvironment.getCurrentEnvironment().audit() + val mp = MixinPlugin.instances.single() + Assertions.assertEquals( + mp.expectedFullPathMixins, + mp.appliedFullPathMixins, + ) + Assertions.assertNotEquals( + 0, + mp.mixins.size + ) + } +} diff --git a/src/gametest/resources/fabric.mod.json b/src/gametest/resources/fabric.mod.json new file mode 100644 index 0000000..fb1174d --- /dev/null +++ b/src/gametest/resources/fabric.mod.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": 1, + "id": "firmament-gametest", + "version": "1.0.0", + "name": "Firmament Game Tests", + "environment": "*", + "entrypoints": { + "fabric-gametest": [ + ], + "fabric-client-gametest": [ + "moe.nea.firmament.gametest.GameTest" + ] + } +} diff --git a/src/main/java/moe/nea/firmament/init/AutoDiscoveryPlugin.java b/src/main/java/moe/nea/firmament/init/AutoDiscoveryPlugin.java index a9db7f9..07e4549 100644 --- a/src/main/java/moe/nea/firmament/init/AutoDiscoveryPlugin.java +++ b/src/main/java/moe/nea/firmament/init/AutoDiscoveryPlugin.java @@ -27,6 +27,8 @@ public class AutoDiscoveryPlugin { return mixins.stream().map(it -> defaultName + "." + it).toList(); } + // TODO: remove println + private static final List<AutoDiscoveryPlugin> mixinPlugins = new ArrayList<>(); public static List<AutoDiscoveryPlugin> getMixinPlugins() { diff --git a/src/main/java/moe/nea/firmament/mixins/HideStatusEffectsPatch.java b/src/main/java/moe/nea/firmament/mixins/HideStatusEffectsPatch.java index c5af8b6..2a58921 100644 --- a/src/main/java/moe/nea/firmament/mixins/HideStatusEffectsPatch.java +++ b/src/main/java/moe/nea/firmament/mixins/HideStatusEffectsPatch.java @@ -1,17 +1,16 @@ package moe.nea.firmament.mixins; -import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; import moe.nea.firmament.features.fixes.Fixes; import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.screen.ingame.InventoryScreen; import net.minecraft.client.gui.screen.ingame.StatusEffectsDisplay; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(InventoryScreen.class) +@Mixin(StatusEffectsDisplay.class) public abstract class HideStatusEffectsPatch { @Shadow public abstract boolean shouldHideStatusEffectHud(); @@ -21,9 +20,11 @@ public abstract class HideStatusEffectsPatch { cir.setReturnValue(!Fixes.TConfig.INSTANCE.getHidePotionEffects()); } - @WrapWithCondition(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/ingame/StatusEffectsDisplay;drawStatusEffects(Lnet/minecraft/client/gui/DrawContext;IIF)V")) - private boolean conditionalRenderStatuses(StatusEffectsDisplay instance, DrawContext context, int mouseX, int mouseY, float tickDelta) { - return shouldHideStatusEffectHud() || !Fixes.TConfig.INSTANCE.getHidePotionEffects(); + @Inject(method = "drawStatusEffects", at = @At("HEAD"), cancellable = true) + private void conditionalRenderStatuses(DrawContext context, int mouseX, int mouseY, CallbackInfo ci) { + if (shouldHideStatusEffectHud() || !Fixes.TConfig.INSTANCE.getHidePotionEffects()) { + ci.cancel(); + } } } diff --git a/src/main/java/moe/nea/firmament/mixins/MainWindowFirstLoadPatch.java b/src/main/java/moe/nea/firmament/mixins/MainWindowFirstLoadPatch.java index 0a90b35..9e42b20 100644 --- a/src/main/java/moe/nea/firmament/mixins/MainWindowFirstLoadPatch.java +++ b/src/main/java/moe/nea/firmament/mixins/MainWindowFirstLoadPatch.java @@ -17,7 +17,7 @@ public class MainWindowFirstLoadPatch { @Inject(method = "<init>(ZLnet/minecraft/client/gui/LogoDrawer;)V", at = @At("RETURN")) private void onCreate(boolean doBackgroundFade, LogoDrawer logoDrawer, CallbackInfo ci) { - if (!hasInited) { + if (!hasInited && Firmament.INSTANCE.getDEBUG()) { try { DebugInstantiateEvent.Companion.publish(new DebugInstantiateEvent()); } catch (Throwable t) { diff --git a/src/main/java/moe/nea/firmament/mixins/MixinHandledScreen.java b/src/main/java/moe/nea/firmament/mixins/MixinHandledScreen.java index 43aec40..530fe47 100644 --- a/src/main/java/moe/nea/firmament/mixins/MixinHandledScreen.java +++ b/src/main/java/moe/nea/firmament/mixins/MixinHandledScreen.java @@ -62,12 +62,9 @@ public abstract class MixinHandledScreen<T extends ScreenHandler> { } } - @Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/ingame/HandledScreen;drawForeground(Lnet/minecraft/client/gui/DrawContext;II)V", shift = At.Shift.AFTER)) + @Inject(method = "renderMain", at = @At("HEAD")) public void onAfterRenderForeground(DrawContext context, int mouseX, int mouseY, float delta, CallbackInfo ci) { - context.getMatrices().push(); - context.getMatrices().translate(-x, -y, 0); HandledScreenForegroundEvent.Companion.publish(new HandledScreenForegroundEvent((HandledScreen<?>) (Object) this, context, mouseX, mouseY, delta)); - context.getMatrices().pop(); } @Inject(method = "onMouseClick(Lnet/minecraft/screen/slot/Slot;IILnet/minecraft/screen/slot/SlotActionType;)V", at = @At("HEAD"), cancellable = true) diff --git a/src/main/java/moe/nea/firmament/mixins/PlayerDropEventPatch.java b/src/main/java/moe/nea/firmament/mixins/PlayerDropEventPatch.java index f07604e..86f6806 100644 --- a/src/main/java/moe/nea/firmament/mixins/PlayerDropEventPatch.java +++ b/src/main/java/moe/nea/firmament/mixins/PlayerDropEventPatch.java @@ -15,7 +15,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(ClientPlayerEntity.class) public abstract class PlayerDropEventPatch extends PlayerEntity { public PlayerDropEventPatch() { - super(null, null, 0, null); + super(null, null); } @Inject(method = "dropSelectedItem", at = @At("HEAD"), cancellable = true) diff --git a/src/main/java/moe/nea/firmament/mixins/WorldRenderLastEventPatch.java b/src/main/java/moe/nea/firmament/mixins/WorldRenderLastEventPatch.java index 3ed8c1b..e268819 100644 --- a/src/main/java/moe/nea/firmament/mixins/WorldRenderLastEventPatch.java +++ b/src/main/java/moe/nea/firmament/mixins/WorldRenderLastEventPatch.java @@ -2,8 +2,10 @@ package moe.nea.firmament.mixins; +import com.mojang.blaze3d.buffers.GpuBufferSlice; import moe.nea.firmament.events.WorldRenderLastEvent; import net.minecraft.client.render.*; +import net.minecraft.client.render.fog.FogRenderer; import net.minecraft.client.util.Handle; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.util.profiler.Profiler; @@ -29,7 +31,7 @@ public abstract class WorldRenderLastEventPatch { protected abstract void checkEmpty(MatrixStack matrices); @Inject(method = "method_62214", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/profiler/Profiler;pop()V", shift = At.Shift.AFTER)) - public void onWorldRenderLast(Fog fog, RenderTickCounter renderTickCounter, Camera camera, Profiler profiler, Matrix4f matrix4f, Matrix4f matrix4f2, Handle handle, Handle handle2, boolean bl, Frustum frustum, Handle handle3, Handle handle4, CallbackInfo ci) { + public void onWorldRenderLast(GpuBufferSlice gpuBufferSlice, RenderTickCounter renderTickCounter, Camera camera, Profiler profiler, Matrix4f matrix4f, Handle handle, Handle handle2, boolean bl, Frustum frustum, Handle handle3, Handle handle4, CallbackInfo ci) { var imm = this.bufferBuilders.getEntityVertexConsumers(); var stack = new MatrixStack(); // TODO: pre-cancel this event if F1 is active diff --git a/src/main/java/moe/nea/firmament/mixins/customgui/PatchHandledScreen.java b/src/main/java/moe/nea/firmament/mixins/customgui/PatchHandledScreen.java index 6e1090a..4d51239 100644 --- a/src/main/java/moe/nea/firmament/mixins/customgui/PatchHandledScreen.java +++ b/src/main/java/moe/nea/firmament/mixins/customgui/PatchHandledScreen.java @@ -134,7 +134,7 @@ public class PatchHandledScreen<T extends ScreenHandler> extends Screen implemen } } - @Inject(method = "render", at = @At("HEAD")) + @Inject(method = "renderBackground", at = @At("HEAD")) public void moveSlots(DrawContext context, int mouseX, int mouseY, float delta, CallbackInfo ci) { if (override != null) { for (Slot slot : handler.slots) { diff --git a/src/main/java/moe/nea/firmament/mixins/feature/devcosmetics/CustomCapeFeatureRenderer.java b/src/main/java/moe/nea/firmament/mixins/feature/devcosmetics/CustomCapeFeatureRenderer.java index 5a92f89..c9115d2 100644 --- a/src/main/java/moe/nea/firmament/mixins/feature/devcosmetics/CustomCapeFeatureRenderer.java +++ b/src/main/java/moe/nea/firmament/mixins/feature/devcosmetics/CustomCapeFeatureRenderer.java @@ -29,12 +29,13 @@ public abstract class CustomCapeFeatureRenderer extends FeatureRenderer<PlayerEn method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/client/render/entity/state/PlayerEntityRenderState;FF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/entity/model/BipedEntityModel;render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumer;II)V") ) - private void onRender(BipedEntityModel instance, MatrixStack matrixStack, VertexConsumer vertexConsumer, int light, int overlay, Operation<Void> original, @Local PlayerEntityRenderState playerEntityRenderState, @Local SkinTextures skinTextures, @Local VertexConsumerProvider vertexConsumerProvider) { + private void onRender(BipedEntityModel<PlayerEntityRenderState> instance, MatrixStack matrixStack, VertexConsumer vertexConsumer, int light, int overlay, Operation<Void> original, @Local(argsOnly = true) PlayerEntityRenderState playerEntityRenderState, @Local SkinTextures skinTextures, @Local VertexConsumerProvider vertexConsumerProvider) { CustomCapes.render( playerEntityRenderState, vertexConsumer, RenderLayer.getEntitySolid(skinTextures.capeTexture()), vertexConsumerProvider, + matrixStack, updatedConsumer -> { original.call(instance, matrixStack, updatedConsumer, light, overlay); return Unit.INSTANCE; diff --git a/src/main/java/moe/nea/firmament/mixins/render/IncreaseStackLimitSizeInDrawContext.java b/src/main/java/moe/nea/firmament/mixins/render/IncreaseStackLimitSizeInDrawContext.java new file mode 100644 index 0000000..61ad8a3 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/render/IncreaseStackLimitSizeInDrawContext.java @@ -0,0 +1,20 @@ +package moe.nea.firmament.mixins.render; + +import net.minecraft.client.gui.DrawContext; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +@Mixin(DrawContext.class) +public class IncreaseStackLimitSizeInDrawContext { + // [22:00:57] [Render thread/ERROR] (Minecraft) Couldn't compile program for pipeline firmament:gui_textured_overlay_tris_circle: + // net.minecraft.client.gl.ShaderLoader$LoadException: Error encountered when linking program containing + // VS minecraft:core/position_tex_color and FS firmament:circle_discard_color. + // Log output: error: declarations for uniform `ColorModulator` are inside block `DynamicTransforms` and outside a block + @ModifyArg( + method = "<init>(Lnet/minecraft/client/MinecraftClient;Lnet/minecraft/client/gui/render/state/GuiRenderState;)V", + at = @At(value = "INVOKE", target = "Lorg/joml/Matrix3x2fStack;<init>(I)V")) + private static int increaseStackSize(int stackSize) { + return Math.max(stackSize, 48); + } +} diff --git a/src/main/java/moe/nea/firmament/mixins/render/renderer/MultipleSpecialGuiRenderStates.java b/src/main/java/moe/nea/firmament/mixins/render/renderer/MultipleSpecialGuiRenderStates.java new file mode 100644 index 0000000..cc79591 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/render/renderer/MultipleSpecialGuiRenderStates.java @@ -0,0 +1,68 @@ +/* + * SPDX-License-Identifier: LGPL-3.0-or-later + * SPDX-FileCopyrightText: 2025 azureaaron via Skyblocker + */ + +package moe.nea.firmament.mixins.render.renderer; + +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import moe.nea.firmament.util.render.MultiSpecialGuiRenderState; +import moe.nea.firmament.util.render.MultiSpecialGuiRenderer; +import net.minecraft.client.gui.render.GuiRenderer; +import net.minecraft.client.gui.render.SpecialGuiElementRenderer; +import net.minecraft.client.gui.render.state.GuiRenderState; +import net.minecraft.client.gui.render.state.special.SpecialGuiElementRenderState; +import net.minecraft.client.render.VertexConsumerProvider; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * The structure of this class was roughly taken from SkyBlocker, retrieved 29.07.2025 + */ +@Mixin(GuiRenderer.class) +public class MultipleSpecialGuiRenderStates { + @Shadow + @Final + private VertexConsumerProvider.Immediate vertexConsumers; + @Shadow + @Final + GuiRenderState state; + @Unique + Map<MultiSpecialGuiRenderState, MultiSpecialGuiRenderer<?>> multiRenderers = new HashMap<>(); + + @Inject(method = "prepareSpecialElement", at = @At("HEAD"), cancellable = true) + private <T extends SpecialGuiElementRenderState> void onPrepareElement(T elementState, int windowScaleFactor, CallbackInfo ci) { + if (elementState instanceof MultiSpecialGuiRenderState multiState) { + @SuppressWarnings({"resource", "unchecked"}) + var renderer = (SpecialGuiElementRenderer<T>) multiRenderers + .computeIfAbsent(multiState, elementState$ -> elementState$.createRenderer(this.vertexConsumers)); + renderer.render(elementState, state, windowScaleFactor); + ci.cancel(); + } + } + + @Inject(method = "close", at = @At("TAIL")) + private void onClose(CallbackInfo ci) { + multiRenderers.values().forEach(SpecialGuiElementRenderer::close); + } + + @Inject(method = "render(Lcom/mojang/blaze3d/buffers/GpuBufferSlice;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/render/GuiRenderer;clearOversizedItems()V")) + private void onAfterRender(GpuBufferSlice fogBuffer, CallbackInfo ci) { + multiRenderers.values().removeIf(it -> { + if (it.consumeRender()) { + return false; + } else { + it.close(); + return true; + } + }); + } +} diff --git a/src/main/kotlin/Firmament.kt b/src/main/kotlin/Firmament.kt index b00546a..83cc259 100644 --- a/src/main/kotlin/Firmament.kt +++ b/src/main/kotlin/Firmament.kt @@ -74,6 +74,7 @@ object Firmament { prettyPrint = DEBUG isLenient = true allowTrailingComma = true + allowComments = true ignoreUnknownKeys = true encodeDefaults = true prettyPrintIndent = if (prettyPrint) "\t" else DEFAULT_JSON_INDENT @@ -91,7 +92,6 @@ object Firmament { prettyPrint = false // Reset pretty print indent back to default to prevent getting yelled at by json prettyPrintIndent = DEFAULT_JSON_INDENT - encodeDefaults = false explicitNulls = false } diff --git a/src/main/kotlin/features/chat/ChatLinks.kt b/src/main/kotlin/features/chat/ChatLinks.kt index 1fb12e1..28c526f 100644 --- a/src/main/kotlin/features/chat/ChatLinks.kt +++ b/src/main/kotlin/features/chat/ChatLinks.kt @@ -8,6 +8,7 @@ import java.net.URL import java.util.Collections import java.util.concurrent.atomic.AtomicInteger import moe.nea.jarvis.api.Point +import org.joml.Vector2i import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async @@ -27,6 +28,7 @@ import moe.nea.firmament.events.ModifyChatEvent import moe.nea.firmament.events.ScreenRenderPostEvent import moe.nea.firmament.features.FirmamentFeature import moe.nea.firmament.gui.config.ManagedConfig +import moe.nea.firmament.jarvis.JarvisIntegration import moe.nea.firmament.util.MC import moe.nea.firmament.util.render.drawTexture import moe.nea.firmament.util.transformEachRecursively @@ -42,7 +44,7 @@ object ChatLinks : FirmamentFeature { val allowAllHosts by toggle("allow-all-hosts") { false } val allowedHosts by string("allowed-hosts") { "cdn.discordapp.com,media.discordapp.com,media.discordapp.net,i.imgur.com" } val actualAllowedHosts get() = allowedHosts.split(",").map { it.trim() } - val position by position("position", 16 * 20, 9 * 20) { Point(0.0, 0.0) } + val position by position("position", 16 * 20, 9 * 20) { Vector2i(0, 0) } } private fun isHostAllowed(host: String) = @@ -110,11 +112,11 @@ object ChatLinks : FirmamentFeature { val imageFuture = imageCache[url] ?: return if (!imageFuture.isCompleted) return val image = imageFuture.getCompleted() ?: return - it.drawContext.matrices.push() + it.drawContext.matrices.pushMatrix() val pos = TConfig.position - pos.applyTransformations(it.drawContext.matrices) + pos.applyTransformations(JarvisIntegration.jarvis, it.drawContext.matrices) val scale = min(1F, min((9 * 20F) / image.height, (16 * 20F) / image.width)) - it.drawContext.matrices.scale(scale, scale, 1F) + it.drawContext.matrices.scale(scale, scale) it.drawContext.drawTexture( image.texture, 0, @@ -126,7 +128,7 @@ object ChatLinks : FirmamentFeature { image.width, image.height, ) - it.drawContext.matrices.pop() + it.drawContext.matrices.popMatrix() } @Subscribe diff --git a/src/main/kotlin/features/debug/ExportedTestConstantMeta.kt b/src/main/kotlin/features/debug/ExportedTestConstantMeta.kt index f0250dc..bdc1f9a 100644 --- a/src/main/kotlin/features/debug/ExportedTestConstantMeta.kt +++ b/src/main/kotlin/features/debug/ExportedTestConstantMeta.kt @@ -12,7 +12,7 @@ data class ExportedTestConstantMeta( ) { companion object { val current = ExportedTestConstantMeta( - SharedConstants.getGameVersion().saveVersion.id, + SharedConstants.getGameVersion().dataVersion().id, Optional.of("Firmament ${Firmament.version.friendlyString}") ) diff --git a/src/main/kotlin/features/debug/itemeditor/ItemExporter.kt b/src/main/kotlin/features/debug/itemeditor/ItemExporter.kt index 2a56204..386a741 100644 --- a/src/main/kotlin/features/debug/itemeditor/ItemExporter.kt +++ b/src/main/kotlin/features/debug/itemeditor/ItemExporter.kt @@ -51,7 +51,10 @@ object ItemExporter { nonOverlayCache.clear() val exporter = LegacyItemExporter.createExporter(itemStack) var json = exporter.exportJson() - val fileName = json.jsonObject["internalname"]!!.jsonPrimitive.content + val fileName = json.jsonObject["internalname"]?.jsonPrimitive?.takeIf { it.isString }?.content + if (fileName == null) { + return tr("firmament.repoexport.nointernalname", "Could not find internal name to export for this item (null.json)") + } val itemFile = RepoDownloadManager.repoSavedLocation.resolve("items").resolve("${fileName}.json") itemFile.createParentDirectories() if (itemFile.exists()) { diff --git a/src/main/kotlin/features/debug/itemeditor/LegacyItemData.kt b/src/main/kotlin/features/debug/itemeditor/LegacyItemData.kt index bc8c618..4b647c7 100644 --- a/src/main/kotlin/features/debug/itemeditor/LegacyItemData.kt +++ b/src/main/kotlin/features/debug/itemeditor/LegacyItemData.kt @@ -1,15 +1,13 @@ package moe.nea.firmament.features.debug.itemeditor import kotlinx.serialization.Serializable -import kotlin.jvm.optionals.getOrNull -import net.minecraft.item.ItemStack import net.minecraft.nbt.NbtCompound import net.minecraft.util.Identifier import moe.nea.firmament.Firmament import moe.nea.firmament.repo.ExpensiveItemCacheApi import moe.nea.firmament.repo.ItemCache -import moe.nea.firmament.util.MC import moe.nea.firmament.util.StringUtil.camelWords +import moe.nea.firmament.util.mc.loadItemFromNbt /** * Load data based on [prismarine.js' 1.8 item data](https://github.com/PrismarineJS/minecraft-data/blob/master/data/pc/1.8/items.json) @@ -68,8 +66,8 @@ object LegacyItemData { putByte("Count", 1) putShort("Damage", legacyItemType.metadata) })!! - val stack = ItemStack.fromNbt(MC.defaultRegistries, nbt).getOrNull() - ?: error("Could not transform ${legacyItemType}") + nbt.remove("components") + val stack = loadItemFromNbt(nbt) ?: error("Could not transform $legacyItemType: $nbt") stack.item to legacyItemType } }.toMap() diff --git a/src/main/kotlin/features/debug/itemeditor/LegacyItemExporter.kt b/src/main/kotlin/features/debug/itemeditor/LegacyItemExporter.kt index ecf3d2c..20ab2c3 100644 --- a/src/main/kotlin/features/debug/itemeditor/LegacyItemExporter.kt +++ b/src/main/kotlin/features/debug/itemeditor/LegacyItemExporter.kt @@ -33,6 +33,7 @@ import moe.nea.firmament.util.json.toJsonArray import moe.nea.firmament.util.mc.displayNameAccordingToNbt import moe.nea.firmament.util.mc.loreAccordingToNbt import moe.nea.firmament.util.mc.toNbtList +import moe.nea.firmament.util.modifyExtraAttributes import moe.nea.firmament.util.skyBlockId import moe.nea.firmament.util.skyblock.Rarity import moe.nea.firmament.util.transformEachRecursively @@ -45,6 +46,7 @@ class LegacyItemExporter private constructor(var itemStack: ItemStack) { } var lore = itemStack.loreAccordingToNbt + val originalId = itemStack.extraAttributes.getString("id") var name = itemStack.displayNameAccordingToNbt val extraAttribs = itemStack.extraAttributes.copy() val legacyNbt = NbtCompound() @@ -195,8 +197,12 @@ class LegacyItemExporter private constructor(var itemStack: ItemStack) { } fun exportModernSnbt(): NbtElement { - val overlay = ItemStack.CODEC.encodeStart(NbtOps.INSTANCE, itemStack) - .orThrow + val overlay = ItemStack.CODEC.encodeStart(NbtOps.INSTANCE, itemStack.copy().also { + it.modifyExtraAttributes { attribs -> + originalId.ifPresent { attribs.putString("id", it) } + attribs + } + }).orThrow val overlayWithVersion = ExportedTestConstantMeta.SOURCE_CODEC.encode(ExportedTestConstantMeta.current, NbtOps.INSTANCE, overlay) .orThrow @@ -284,7 +290,7 @@ class LegacyItemExporter private constructor(var itemStack: ItemStack) { fun copyLegacySkullNbt() { val profile = itemStack.get(DataComponentTypes.PROFILE) ?: return legacyNbt.put("SkullOwner", NbtCompound().apply { - profile.id.ifPresent { + profile.uuid.ifPresent { putString("Id", it.toString()) } putBoolean("hypixelPopulated", true) diff --git a/src/main/kotlin/features/debug/itemeditor/PromptScreen.kt b/src/main/kotlin/features/debug/itemeditor/PromptScreen.kt deleted file mode 100644 index 187b70b..0000000 --- a/src/main/kotlin/features/debug/itemeditor/PromptScreen.kt +++ /dev/null @@ -1,15 +0,0 @@ -package moe.nea.firmament.features.debug.itemeditor - -import io.github.notenoughupdates.moulconfig.gui.CloseEventListener -import io.github.notenoughupdates.moulconfig.gui.GuiComponentWrapper -import io.github.notenoughupdates.moulconfig.gui.GuiContext -import io.github.notenoughupdates.moulconfig.gui.component.CenterComponent -import io.github.notenoughupdates.moulconfig.gui.component.ColumnComponent -import io.github.notenoughupdates.moulconfig.gui.component.PanelComponent -import io.github.notenoughupdates.moulconfig.gui.component.TextComponent -import io.github.notenoughupdates.moulconfig.gui.component.TextFieldComponent -import io.github.notenoughupdates.moulconfig.observer.GetSetter -import kotlin.reflect.KMutableProperty0 -import moe.nea.firmament.gui.FirmButtonComponent -import moe.nea.firmament.util.MoulConfigUtils - diff --git a/src/main/kotlin/features/diana/AncestralSpadeSolver.kt b/src/main/kotlin/features/diana/AncestralSpadeSolver.kt index ff85c00..48004e8 100644 --- a/src/main/kotlin/features/diana/AncestralSpadeSolver.kt +++ b/src/main/kotlin/features/diana/AncestralSpadeSolver.kt @@ -106,13 +106,11 @@ object AncestralSpadeSolver : SubscriptionOwner { nextGuess?.let { tinyBlock(it, 1f, 0x80FFFFFF.toInt()) // TODO: replace this - color(1f, 1f, 0f, 1f) - tracer(it, lineWidth = 3f) + tracer(it, lineWidth = 3f, color = 0x80FFFFFF.toInt()) } if (particlePositions.size > 2 && lastDing.passedTime() < 10.seconds && nextGuess != null) { // TODO: replace this // TODO: add toggle - color(0f, 1f, 0f, 0.7f) - line(particlePositions) + line(particlePositions, color = 0x80FFFFFF.toInt()) } } } diff --git a/src/main/kotlin/features/events/anniversity/AnniversaryFeatures.kt b/src/main/kotlin/features/events/anniversity/AnniversaryFeatures.kt index 0cfaeba..0f0316a 100644 --- a/src/main/kotlin/features/events/anniversity/AnniversaryFeatures.kt +++ b/src/main/kotlin/features/events/anniversity/AnniversaryFeatures.kt @@ -4,6 +4,7 @@ package moe.nea.firmament.features.events.anniversity import io.github.notenoughupdates.moulconfig.observer.ObservableList import io.github.notenoughupdates.moulconfig.xml.Bind import moe.nea.jarvis.api.Point +import org.joml.Vector2i import kotlin.time.Duration.Companion.seconds import net.minecraft.entity.passive.PigEntity import net.minecraft.util.math.BlockPos @@ -31,7 +32,7 @@ object AnniversaryFeatures : FirmamentFeature { object TConfig : ManagedConfig(identifier, Category.EVENTS) { val enableShinyPigTracker by toggle("shiny-pigs") {true} - val trackPigCooldown by position("pig-hud", 200, 300) { Point(0.1, 0.2) } + val trackPigCooldown by position("pig-hud", 200, 300) { Vector2i(100, 200) } } override val config: ManagedConfig? diff --git a/src/main/kotlin/features/events/carnival/MinesweeperHelper.kt b/src/main/kotlin/features/events/carnival/MinesweeperHelper.kt index cfc05cc..3baf5a5 100644 --- a/src/main/kotlin/features/events/carnival/MinesweeperHelper.kt +++ b/src/main/kotlin/features/events/carnival/MinesweeperHelper.kt @@ -2,7 +2,7 @@ package moe.nea.firmament.features.events.carnival import io.github.notenoughupdates.moulconfig.observer.ObservableList -import io.github.notenoughupdates.moulconfig.platform.ModernItemStack +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform import io.github.notenoughupdates.moulconfig.xml.Bind import java.util.UUID import net.minecraft.block.Blocks @@ -120,7 +120,7 @@ object MinesweeperHelper { .setSkyBlockFirmamentUiId("MINESWEEPER_$name") @Bind - fun getIcon() = ModernItemStack.of(itemStack) + fun getIcon() = MoulConfigPlatform.wrap(itemStack) @Bind fun pieceLabel() = fruitColor.formattingCode + fruitName @@ -158,7 +158,7 @@ object MinesweeperHelper { ; @Bind("itemType") - fun getItemStack() = ModernItemStack.of(ItemStack(itemType)) + fun getItemStack() = MoulConfigPlatform.wrap(ItemStack(itemType)) companion object { val id = SkyblockId("CARNIVAL_SHOVEL") diff --git a/src/main/kotlin/features/fixes/Fixes.kt b/src/main/kotlin/features/fixes/Fixes.kt index 0105624..b002dbd 100644 --- a/src/main/kotlin/features/fixes/Fixes.kt +++ b/src/main/kotlin/features/fixes/Fixes.kt @@ -1,6 +1,7 @@ package moe.nea.firmament.features.fixes import moe.nea.jarvis.api.Point +import org.joml.Vector2i import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable import net.minecraft.client.MinecraftClient import net.minecraft.client.option.KeyBinding @@ -22,7 +23,7 @@ object Fixes : FirmamentFeature { var autoSprint by toggle("auto-sprint") { false } val autoSprintKeyBinding by keyBindingWithDefaultUnbound("auto-sprint-keybinding") val autoSprintUnderWater by toggle("auto-sprint-underwater") { true } - val autoSprintHud by position("auto-sprint-hud", 80, 10) { Point(0.0, 1.0) } + val autoSprintHud by position("auto-sprint-hud", 80, 10) { Vector2i() } val peekChat by keyBindingWithDefaultUnbound("peek-chat") val hidePotionEffects by toggle("hide-mob-effects") { false } val hidePotionEffectsHud by toggle("hide-potion-effects-hud") { false } @@ -50,7 +51,7 @@ object Fixes : FirmamentFeature { @Subscribe fun onRenderHud(it: HudRenderEvent) { if (!TConfig.autoSprintKeyBinding.isBound) return - it.context.matrices.push() + it.context.matrices.pushMatrix() TConfig.autoSprintHud.applyTransformations(it.context.matrices) it.context.drawText( MC.font, ( @@ -66,7 +67,7 @@ object Fixes : FirmamentFeature { } ), 0, 0, -1, true ) - it.context.matrices.pop() + it.context.matrices.popMatrix() } @Subscribe diff --git a/src/main/kotlin/features/inventory/ItemRarityCosmetics.kt b/src/main/kotlin/features/inventory/ItemRarityCosmetics.kt index fdc378a..9dae118 100644 --- a/src/main/kotlin/features/inventory/ItemRarityCosmetics.kt +++ b/src/main/kotlin/features/inventory/ItemRarityCosmetics.kt @@ -1,6 +1,7 @@ package moe.nea.firmament.features.inventory import java.awt.Color +import net.minecraft.client.gl.RenderPipelines import net.minecraft.client.gui.DrawContext import net.minecraft.client.render.RenderLayer import net.minecraft.item.ItemStack @@ -38,7 +39,7 @@ object ItemRarityCosmetics : FirmamentFeature { val rarity = Rarity.fromItem(item) ?: return val rgb = rarityToColor[rarity] ?: 0xFF00FF80.toInt() drawContext.drawGuiTexture( - RenderLayer::getGuiTextured, + RenderPipelines.GUI_TEXTURED, Identifier.of("firmament:item_rarity_background"), x, y, 16, 16, diff --git a/src/main/kotlin/features/inventory/PetFeatures.kt b/src/main/kotlin/features/inventory/PetFeatures.kt index 9393b03..701d30c 100644 --- a/src/main/kotlin/features/inventory/PetFeatures.kt +++ b/src/main/kotlin/features/inventory/PetFeatures.kt @@ -1,6 +1,6 @@ package moe.nea.firmament.features.inventory -import moe.nea.jarvis.api.Point +import org.joml.Vector2i import net.minecraft.item.ItemStack import net.minecraft.text.Text import net.minecraft.util.Formatting @@ -10,6 +10,7 @@ import moe.nea.firmament.events.HudRenderEvent import moe.nea.firmament.events.SlotRenderEvents import moe.nea.firmament.features.FirmamentFeature import moe.nea.firmament.gui.config.ManagedConfig +import moe.nea.firmament.jarvis.JarvisIntegration import moe.nea.firmament.util.FirmFormatters.formatPercent import moe.nea.firmament.util.FirmFormatters.shortFormat import moe.nea.firmament.util.MC @@ -31,7 +32,9 @@ object PetFeatures : FirmamentFeature { object TConfig : ManagedConfig(identifier, Category.INVENTORY) { val highlightEquippedPet by toggle("highlight-pet") { true } var petOverlay by toggle("pet-overlay") { false } - val petOverlayHud by position("pet-overlay-hud", 80, 10) { Point(0.5, 1.0) } + val petOverlayHud by position("pet-overlay-hud", 80, 10) { + Vector2i() + } } val petMenuTitle = "Pets(?: \\([0-9]+/[0-9]+\\))?".toPattern() @@ -43,12 +46,12 @@ object PetFeatures : FirmamentFeature { val stack = event.slot.stack if (stack.petData?.active == true) petMenuTitle.useMatch(MC.screenName ?: return) { - petItemStack = stack - event.context.drawGuiTexture( - Firmament.identifier("selected_pet_background"), - event.slot.x, event.slot.y, 16, 16, - ) - } + petItemStack = stack + event.context.drawGuiTexture( + Firmament.identifier("selected_pet_background"), + event.slot.x, event.slot.y, 16, 16, + ) + } } @Subscribe @@ -62,25 +65,48 @@ object PetFeatures : FirmamentFeature { val petType = titleCase(petData.type) val heldItem = petData.heldItem?.let { item -> "Held Item: ${titleCase(item)}" } - it.context.matrices.push() - TConfig.petOverlayHud.applyTransformations(it.context.matrices) + it.context.matrices.pushMatrix() + TConfig.petOverlayHud.applyTransformations(JarvisIntegration.jarvis, it.context.matrices) val lines = mutableListOf<Text>() - it.context.matrices.push() - it.context.matrices.translate(-0.5, -0.5, 0.0) - it.context.matrices.scale(2f, 2f, 1f) + it.context.matrices.pushMatrix() + it.context.matrices.translate(-0.5F, -0.5F) + it.context.matrices.scale(2f, 2f) it.context.drawItem(itemStack, 0, 0) - it.context.matrices.pop() + it.context.matrices.popMatrix() lines.add(Text.literal("[Lvl ${xp.currentLevel}] ").append(Text.literal(petType).withColor(rarityCode))) if (heldItem != null) lines.add(Text.literal(heldItem)) - if (xp.currentLevel != xp.maxLevel) lines.add(Text.literal("Required L${xp.currentLevel + 1}: ${shortFormat(xp.expInCurrentLevel.toDouble())}/${shortFormat(xp.expRequiredForNextLevel.toDouble())} (${formatPercent(xp.percentageToNextLevel.toDouble())})")) - lines.add(Text.literal("Required L100: ${shortFormat(xp.expTotal.toDouble())}/${shortFormat(xp.expRequiredForMaxLevel.toDouble())} (${formatPercent(xp.percentageToMaxLevel.toDouble())})")) + if (xp.currentLevel != xp.maxLevel) lines.add( + Text.literal( + "Required L${xp.currentLevel + 1}: ${shortFormat(xp.expInCurrentLevel.toDouble())}/${ + shortFormat( + xp.expRequiredForNextLevel.toDouble() + ) + } (${formatPercent(xp.percentageToNextLevel.toDouble())})" + ) + ) + lines.add( + Text.literal( + "Required L100: ${shortFormat(xp.expTotal.toDouble())}/${shortFormat(xp.expRequiredForMaxLevel.toDouble())} (${ + formatPercent( + xp.percentageToMaxLevel.toDouble() + ) + })" + ) + ) for ((index, line) in lines.withIndex()) { - it.context.drawText(MC.font, line.copy().withColor(Formatting.GRAY), 36, MC.font.fontHeight * index, -1, true) + it.context.drawText( + MC.font, + line.copy().withColor(Formatting.GRAY), + 36, + MC.font.fontHeight * index, + -1, + true + ) } - it.context.matrices.pop() + it.context.matrices.popMatrix() } } diff --git a/src/main/kotlin/features/inventory/REIDependencyWarner.kt b/src/main/kotlin/features/inventory/REIDependencyWarner.kt index 476759a..6bf2928 100644 --- a/src/main/kotlin/features/inventory/REIDependencyWarner.kt +++ b/src/main/kotlin/features/inventory/REIDependencyWarner.kt @@ -31,7 +31,7 @@ object REIDependencyWarner { var sentWarning = false fun modrinthLink(slug: String) = - "https://modrinth.com/mod/$slug/versions?g=${SharedConstants.getGameVersion().name}&l=fabric" + "https://modrinth.com/mod/$slug/versions?g=${SharedConstants.getGameVersion().name()}&l=fabric" fun downloadButton(modName: String, modId: String, slug: String): Text { val alreadyDownloaded = FabricLoader.getInstance().isModLoaded(modId) diff --git a/src/main/kotlin/features/inventory/SlotLocking.kt b/src/main/kotlin/features/inventory/SlotLocking.kt index 0a3f01b..eefc6d1 100644 --- a/src/main/kotlin/features/inventory/SlotLocking.kt +++ b/src/main/kotlin/features/inventory/SlotLocking.kt @@ -2,6 +2,7 @@ package moe.nea.firmament.features.inventory +import com.mojang.blaze3d.pipeline.RenderPipeline import java.util.UUID import org.lwjgl.glfw.GLFW import kotlinx.serialization.KSerializer @@ -16,6 +17,7 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.int import kotlinx.serialization.serializer +import net.minecraft.client.gl.RenderPipelines import net.minecraft.client.gui.screen.ingame.HandledScreen import net.minecraft.client.render.RenderLayer import net.minecraft.entity.player.PlayerInventory @@ -429,7 +431,7 @@ object SlotLocking : FirmamentFeature { return if (isHotbar()) { x + 9 to y } else { - x + 9 to y + 17 + x + 9 to y + 16 } } @@ -484,7 +486,7 @@ object SlotLocking : FirmamentFeature { val isUUIDLocked = (it.slot.stack?.skyblockUUID) in (lockedUUIDs ?: setOf()) if (isSlotLocked || isUUIDLocked) { it.context.drawGuiTexture( - RenderLayer::getGuiTexturedOverlay, + RenderPipelines.GUI_TEXTURED, when { isSlotLocked -> (Identifier.of("firmament:slot_locked")) diff --git a/src/main/kotlin/features/inventory/buttons/InventoryButtonEditor.kt b/src/main/kotlin/features/inventory/buttons/InventoryButtonEditor.kt index eecbd17..7334c82 100644 --- a/src/main/kotlin/features/inventory/buttons/InventoryButtonEditor.kt +++ b/src/main/kotlin/features/inventory/buttons/InventoryButtonEditor.kt @@ -2,8 +2,8 @@ package moe.nea.firmament.features.inventory.buttons import io.github.notenoughupdates.moulconfig.common.IItemStack import io.github.notenoughupdates.moulconfig.gui.component.PanelComponent -import io.github.notenoughupdates.moulconfig.platform.ModernItemStack -import io.github.notenoughupdates.moulconfig.platform.ModernRenderContext +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform +import io.github.notenoughupdates.moulconfig.platform.MoulConfigRenderContext import io.github.notenoughupdates.moulconfig.xml.Bind import me.shedaniel.math.Point import me.shedaniel.math.Rectangle @@ -35,7 +35,7 @@ class InventoryButtonEditor( @Bind fun getItemIcon(): IItemStack { save() - return ModernItemStack.of(InventoryButton.getItemForName(icon)) + return MoulConfigPlatform.wrap(InventoryButton.getItemForName(icon)) } @Bind @@ -122,7 +122,9 @@ class InventoryButtonEditor( ButtonWidget.builder(Text.translatable("firmament.inventory-buttons.simple-preset")) { // Preset from NEU // Credit: https://github.com/NotEnoughUpdates/NotEnoughUpdates/blob/9b1fcfebc646e9fb69f99006327faa3e734e5f51/src/main/resources/assets/notenoughupdates/invbuttons/presets.json#L900-L1348 - val newButtons = InventoryButtonTemplates.loadTemplate("TkVVQlVUVE9OUy9bIntcblx0XCJ4XCI6IDE2MCxcblx0XCJ5XCI6IC0yMCxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcImJvbmVcIixcblx0XCJjb21tYW5kXCI6IFwicGV0c1wiXG59Iiwie1xuXHRcInhcIjogMTQwLFxuXHRcInlcIjogLTIwLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiBmYWxzZSxcblx0XCJpY29uXCI6IFwiYXJtb3Jfc3RhbmRcIixcblx0XCJjb21tYW5kXCI6IFwid2FyZHJvYmVcIlxufSIsIntcblx0XCJ4XCI6IDEyMCxcblx0XCJ5XCI6IC0yMCxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcImVuZGVyX2NoZXN0XCIsXG5cdFwiY29tbWFuZFwiOiBcInN0b3JhZ2VcIlxufSIsIntcblx0XCJ4XCI6IDEwMCxcblx0XCJ5XCI6IC0yMCxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcInNrdWxsOmQ3Y2M2Njg3NDIzZDA1NzBkNTU2YWM1M2UwNjc2Y2I1NjNiYmRkOTcxN2NkODI2OWJkZWJlZDZmNmQ0ZTdiZjhcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBpc2xhbmRcIlxufSIsIntcblx0XCJ4XCI6IDgwLFxuXHRcInlcIjogLTIwLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiBmYWxzZSxcblx0XCJpY29uXCI6IFwic2t1bGw6MzVmNGI0MGNlZjllMDE3Y2Q0MTEyZDI2YjYyNTU3ZjhjMWQ1YjE4OWRhMmU5OTUzNDIyMmJjOGNlYzdkOTE5NlwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGh1YlwiXG59Il0=") + val newButtons = InventoryButtonTemplates.loadTemplate( + "TkVVQlVUVE9OUy9bIntcblx0XCJ4XCI6IDE2MCxcblx0XCJ5XCI6IC0yMCxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcImJvbmVcIixcblx0XCJjb21tYW5kXCI6IFwicGV0c1wiXG59Iiwie1xuXHRcInhcIjogMTQwLFxuXHRcInlcIjogLTIwLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiBmYWxzZSxcblx0XCJpY29uXCI6IFwiYXJtb3Jfc3RhbmRcIixcblx0XCJjb21tYW5kXCI6IFwid2FyZHJvYmVcIlxufSIsIntcblx0XCJ4XCI6IDEyMCxcblx0XCJ5XCI6IC0yMCxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcImVuZGVyX2NoZXN0XCIsXG5cdFwiY29tbWFuZFwiOiBcInN0b3JhZ2VcIlxufSIsIntcblx0XCJ4XCI6IDEwMCxcblx0XCJ5XCI6IC0yMCxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcInNrdWxsOmQ3Y2M2Njg3NDIzZDA1NzBkNTU2YWM1M2UwNjc2Y2I1NjNiYmRkOTcxN2NkODI2OWJkZWJlZDZmNmQ0ZTdiZjhcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBpc2xhbmRcIlxufSIsIntcblx0XCJ4XCI6IDgwLFxuXHRcInlcIjogLTIwLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiBmYWxzZSxcblx0XCJpY29uXCI6IFwic2t1bGw6MzVmNGI0MGNlZjllMDE3Y2Q0MTEyZDI2YjYyNTU3ZjhjMWQ1YjE4OWRhMmU5OTUzNDIyMmJjOGNlYzdkOTE5NlwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGh1YlwiXG59Il0=" + ) if (newButtons != null) buttons = moveButtons(newButtons.map { it.copy(command = it.command?.removePrefix("/")) }) } @@ -134,7 +136,9 @@ class InventoryButtonEditor( ButtonWidget.builder(Text.translatable("firmament.inventory-buttons.all-warps-preset")) { // Preset from NEU // Credit: https://github.com/NotEnoughUpdates/NotEnoughUpdates/blob/9b1fcfebc646e9fb69f99006327faa3e734e5f51/src/main/resources/assets/notenoughupdates/invbuttons/presets.json#L1817-L2276 - val newButtons = InventoryButtonTemplates.loadTemplate("TkVVQlVUVE9OUy9bIntcblx0XCJ4XCI6IDIsXG5cdFwieVwiOiAtODQsXG5cdFwiYW5jaG9yUmlnaHRcIjogdHJ1ZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6YzljODg4MWU0MjkxNWE5ZDI5YmI2MWExNmZiMjZkMDU5OTEzMjA0ZDI2NWRmNWI0MzliM2Q3OTJhY2Q1NlwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGhvbWVcIlxufSIsIntcblx0XCJ4XCI6IDIsXG5cdFwieVwiOiAtNjQsXG5cdFwiYW5jaG9yUmlnaHRcIjogdHJ1ZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6ZDdjYzY2ODc0MjNkMDU3MGQ1NTZhYzUzZTA2NzZjYjU2M2JiZGQ5NzE3Y2Q4MjY5YmRlYmVkNmY2ZDRlN2JmOFwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGh1YlwiXG59Iiwie1xuXHRcInhcIjogMixcblx0XCJ5XCI6IC00NCxcblx0XCJhbmNob3JSaWdodFwiOiB0cnVlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDo5YjU2ODk1Yjk2NTk4OTZhZDY0N2Y1ODU5OTIzOGFmNTMyZDQ2ZGI5YzFiMDM4OWI4YmJlYjcwOTk5ZGFiMzNkXCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgZHVuZ2Vvbl9odWJcIlxufSIsIntcblx0XCJ4XCI6IDIsXG5cdFwieVwiOiAtMjQsXG5cdFwiYW5jaG9yUmlnaHRcIjogdHJ1ZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6Nzg0MGI4N2Q1MjI3MWQyYTc1NWRlZGM4Mjg3N2UwZWQzZGY2N2RjYzQyZWE0NzllYzE0NjE3NmIwMjc3OWE1XCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgZW5kXCJcbn0iLCJ7XG5cdFwieFwiOiAxMDksXG5cdFwieVwiOiAtMTksXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IGZhbHNlLFxuXHRcImljb25cIjogXCJza3VsbDo4NmYwNmVhYTMwMDRhZWVkMDliM2Q1YjQ1ZDk3NmRlNTg0ZTY5MWMwZTljYWRlMTMzNjM1ZGU5M2QyM2I5ZWRiXCIsXG5cdFwiY29tbWFuZFwiOiBcImhvdG1cIlxufSIsIntcblx0XCJ4XCI6IDEzMCxcblx0XCJ5XCI6IC0xOSxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcIkVOREVSX0NIRVNUXCIsXG5cdFwiY29tbWFuZFwiOiBcInN0b3JhZ2VcIlxufSIsIntcblx0XCJ4XCI6IDE1MSxcblx0XCJ5XCI6IC0xOSxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcIkJPTkVcIixcblx0XCJjb21tYW5kXCI6IFwicGV0c1wiXG59Iiwie1xuXHRcInhcIjogLTE5LFxuXHRcInlcIjogMixcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcIkdPTERfQkxPQ0tcIixcblx0XCJjb21tYW5kXCI6IFwiYWhcIlxufSIsIntcblx0XCJ4XCI6IC0xOSxcblx0XCJ5XCI6IDIyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiBmYWxzZSxcblx0XCJpY29uXCI6IFwiR09MRF9CQVJESU5HXCIsXG5cdFwiY29tbWFuZFwiOiBcImJ6XCJcbn0iLCJ7XG5cdFwieFwiOiAtMTksXG5cdFwieVwiOiAtODQsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjQzOGNmM2Y4ZTU0YWZjM2IzZjkxZDIwYTQ5ZjMyNGRjYTE0ODYwMDdmZTU0NTM5OTA1NTUyNGMxNzk0MWY0ZGNcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBtdXNldW1cIlxufSIsIntcblx0XCJ4XCI6IC0xOSxcblx0XCJ5XCI6IC02NCxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6ZjQ4ODBkMmMxZTdiODZlODc1MjJlMjA4ODI2NTZmNDViYWZkNDJmOTQ5MzJiMmM1ZTBkNmVjYWE0OTBjYjRjXCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgZ2FyZGVuXCJcbn0iLCJ7XG5cdFwieFwiOiAtMTksXG5cdFwieVwiOiAtNDQsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjRkM2E2YmQ5OGFjMTgzM2M2NjRjNDkwOWZmOGQyZGM2MmNlODg3YmRjZjNjYzViMzg0ODY1MWFlNWFmNmJcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBiYXJuXCJcbn0iLCJ7XG5cdFwieFwiOiAtMTksXG5cdFwieVwiOiAtMjQsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjUxNTM5ZGRkZjllZDI1NWVjZTYzNDgxOTNjZDc1MDEyYzgyYzkzYWVjMzgxZjA1NTcyY2VjZjczNzk3MTFiM2JcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBkZXNlcnRcIlxufSIsIntcblx0XCJ4XCI6IDQsXG5cdFwieVwiOiAyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDo3M2JjOTY1ZDU3OWMzYzYwMzlmMGExN2ViN2MyZTZmYWY1MzhjN2E1ZGU4ZTYwZWM3YTcxOTM2MGQwYTg1N2E5XCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgZ29sZFwiXG59Iiwie1xuXHRcInhcIjogMjUsXG5cdFwieVwiOiAyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDo1NjlhMWYxMTQxNTFiNDUyMTM3M2YzNGJjMTRjMjk2M2E1MDExY2RjMjVhNjU1NGM0OGM3MDhjZDk2ZWJmY1wiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGRlZXBcIlxufSIsIntcblx0XCJ4XCI6IDQ2LFxuXHRcInlcIjogMixcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6MjFkYmUzMGIwMjdhY2JjZWI2MTI1NjNiZDg3N2NkN2ViYjcxOWVhNmVkMTM5OTAyN2RjZWU1OGJiOTA0OWQ0YVwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGNyeXN0YWxzXCJcbn0iLCJ7XG5cdFwieFwiOiA2Nyxcblx0XCJ5XCI6IDIsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjVjYmQ5ZjVlYzFlZDAwNzI1OTk5NjQ5MWU2OWZmNjQ5YTMxMDZjZjkyMDIyN2IxYmIzYTcxZWU3YTg5ODYzZlwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGZvcmdlXCJcbn0iLCJ7XG5cdFwieFwiOiA4OCxcblx0XCJ5XCI6IDIsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjZiMjBiMjNjMWFhMmJlMDI3MGYwMTZiNGM5MGQ2ZWU2YjgzMzBhMTdjZmVmODc4NjlkNmFkNjBiMmZmYmYzYjVcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBtaW5lc1wiXG59Iiwie1xuXHRcInhcIjogMTA5LFxuXHRcInlcIjogMixcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6YTIyMWY4MTNkYWNlZTBmZWY4YzU5Zjc2ODk0ZGJiMjY0MTU0NzhkOWRkZmM0NGMyZTcwOGE2ZDNiNzU0OWJcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBwYXJrXCJcbn0iLCJ7XG5cdFwieFwiOiAxMzAsXG5cdFwieVwiOiAyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDo5ZDdlM2IxOWFjNGYzZGVlOWM1Njc3YzEzNTMzM2I5ZDM1YTdmNTY4YjYzZDFlZjRhZGE0YjA2OGI1YTI1XCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgc3BpZGVyXCJcbn0iLCJ7XG5cdFwieFwiOiAxNTEsXG5cdFwieVwiOiAyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDpjMzY4N2UyNWM2MzJiY2U4YWE2MWUwZDY0YzI0ZTY5NGMzZWVhNjI5ZWE5NDRmNGNmMzBkY2ZiNGZiY2UwNzFcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBuZXRoZXJcIlxufSJd") + val newButtons = InventoryButtonTemplates.loadTemplate( + "TkVVQlVUVE9OUy9bIntcblx0XCJ4XCI6IDIsXG5cdFwieVwiOiAtODQsXG5cdFwiYW5jaG9yUmlnaHRcIjogdHJ1ZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6YzljODg4MWU0MjkxNWE5ZDI5YmI2MWExNmZiMjZkMDU5OTEzMjA0ZDI2NWRmNWI0MzliM2Q3OTJhY2Q1NlwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGhvbWVcIlxufSIsIntcblx0XCJ4XCI6IDIsXG5cdFwieVwiOiAtNjQsXG5cdFwiYW5jaG9yUmlnaHRcIjogdHJ1ZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6ZDdjYzY2ODc0MjNkMDU3MGQ1NTZhYzUzZTA2NzZjYjU2M2JiZGQ5NzE3Y2Q4MjY5YmRlYmVkNmY2ZDRlN2JmOFwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGh1YlwiXG59Iiwie1xuXHRcInhcIjogMixcblx0XCJ5XCI6IC00NCxcblx0XCJhbmNob3JSaWdodFwiOiB0cnVlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDo5YjU2ODk1Yjk2NTk4OTZhZDY0N2Y1ODU5OTIzOGFmNTMyZDQ2ZGI5YzFiMDM4OWI4YmJlYjcwOTk5ZGFiMzNkXCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgZHVuZ2Vvbl9odWJcIlxufSIsIntcblx0XCJ4XCI6IDIsXG5cdFwieVwiOiAtMjQsXG5cdFwiYW5jaG9yUmlnaHRcIjogdHJ1ZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6Nzg0MGI4N2Q1MjI3MWQyYTc1NWRlZGM4Mjg3N2UwZWQzZGY2N2RjYzQyZWE0NzllYzE0NjE3NmIwMjc3OWE1XCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgZW5kXCJcbn0iLCJ7XG5cdFwieFwiOiAxMDksXG5cdFwieVwiOiAtMTksXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IGZhbHNlLFxuXHRcImljb25cIjogXCJza3VsbDo4NmYwNmVhYTMwMDRhZWVkMDliM2Q1YjQ1ZDk3NmRlNTg0ZTY5MWMwZTljYWRlMTMzNjM1ZGU5M2QyM2I5ZWRiXCIsXG5cdFwiY29tbWFuZFwiOiBcImhvdG1cIlxufSIsIntcblx0XCJ4XCI6IDEzMCxcblx0XCJ5XCI6IC0xOSxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcIkVOREVSX0NIRVNUXCIsXG5cdFwiY29tbWFuZFwiOiBcInN0b3JhZ2VcIlxufSIsIntcblx0XCJ4XCI6IDE1MSxcblx0XCJ5XCI6IC0xOSxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcIkJPTkVcIixcblx0XCJjb21tYW5kXCI6IFwicGV0c1wiXG59Iiwie1xuXHRcInhcIjogLTE5LFxuXHRcInlcIjogMixcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogZmFsc2UsXG5cdFwiaWNvblwiOiBcIkdPTERfQkxPQ0tcIixcblx0XCJjb21tYW5kXCI6IFwiYWhcIlxufSIsIntcblx0XCJ4XCI6IC0xOSxcblx0XCJ5XCI6IDIyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiBmYWxzZSxcblx0XCJpY29uXCI6IFwiR09MRF9CQVJESU5HXCIsXG5cdFwiY29tbWFuZFwiOiBcImJ6XCJcbn0iLCJ7XG5cdFwieFwiOiAtMTksXG5cdFwieVwiOiAtODQsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjQzOGNmM2Y4ZTU0YWZjM2IzZjkxZDIwYTQ5ZjMyNGRjYTE0ODYwMDdmZTU0NTM5OTA1NTUyNGMxNzk0MWY0ZGNcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBtdXNldW1cIlxufSIsIntcblx0XCJ4XCI6IC0xOSxcblx0XCJ5XCI6IC02NCxcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6ZjQ4ODBkMmMxZTdiODZlODc1MjJlMjA4ODI2NTZmNDViYWZkNDJmOTQ5MzJiMmM1ZTBkNmVjYWE0OTBjYjRjXCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgZ2FyZGVuXCJcbn0iLCJ7XG5cdFwieFwiOiAtMTksXG5cdFwieVwiOiAtNDQsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjRkM2E2YmQ5OGFjMTgzM2M2NjRjNDkwOWZmOGQyZGM2MmNlODg3YmRjZjNjYzViMzg0ODY1MWFlNWFmNmJcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBiYXJuXCJcbn0iLCJ7XG5cdFwieFwiOiAtMTksXG5cdFwieVwiOiAtMjQsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjUxNTM5ZGRkZjllZDI1NWVjZTYzNDgxOTNjZDc1MDEyYzgyYzkzYWVjMzgxZjA1NTcyY2VjZjczNzk3MTFiM2JcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBkZXNlcnRcIlxufSIsIntcblx0XCJ4XCI6IDQsXG5cdFwieVwiOiAyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDo3M2JjOTY1ZDU3OWMzYzYwMzlmMGExN2ViN2MyZTZmYWY1MzhjN2E1ZGU4ZTYwZWM3YTcxOTM2MGQwYTg1N2E5XCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgZ29sZFwiXG59Iiwie1xuXHRcInhcIjogMjUsXG5cdFwieVwiOiAyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDo1NjlhMWYxMTQxNTFiNDUyMTM3M2YzNGJjMTRjMjk2M2E1MDExY2RjMjVhNjU1NGM0OGM3MDhjZDk2ZWJmY1wiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGRlZXBcIlxufSIsIntcblx0XCJ4XCI6IDQ2LFxuXHRcInlcIjogMixcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6MjFkYmUzMGIwMjdhY2JjZWI2MTI1NjNiZDg3N2NkN2ViYjcxOWVhNmVkMTM5OTAyN2RjZWU1OGJiOTA0OWQ0YVwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGNyeXN0YWxzXCJcbn0iLCJ7XG5cdFwieFwiOiA2Nyxcblx0XCJ5XCI6IDIsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjVjYmQ5ZjVlYzFlZDAwNzI1OTk5NjQ5MWU2OWZmNjQ5YTMxMDZjZjkyMDIyN2IxYmIzYTcxZWU3YTg5ODYzZlwiLFxuXHRcImNvbW1hbmRcIjogXCJ3YXJwIGZvcmdlXCJcbn0iLCJ7XG5cdFwieFwiOiA4OCxcblx0XCJ5XCI6IDIsXG5cdFwiYW5jaG9yUmlnaHRcIjogZmFsc2UsXG5cdFwiYW5jaG9yQm90dG9tXCI6IHRydWUsXG5cdFwiaWNvblwiOiBcInNrdWxsOjZiMjBiMjNjMWFhMmJlMDI3MGYwMTZiNGM5MGQ2ZWU2YjgzMzBhMTdjZmVmODc4NjlkNmFkNjBiMmZmYmYzYjVcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBtaW5lc1wiXG59Iiwie1xuXHRcInhcIjogMTA5LFxuXHRcInlcIjogMixcblx0XCJhbmNob3JSaWdodFwiOiBmYWxzZSxcblx0XCJhbmNob3JCb3R0b21cIjogdHJ1ZSxcblx0XCJpY29uXCI6IFwic2t1bGw6YTIyMWY4MTNkYWNlZTBmZWY4YzU5Zjc2ODk0ZGJiMjY0MTU0NzhkOWRkZmM0NGMyZTcwOGE2ZDNiNzU0OWJcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBwYXJrXCJcbn0iLCJ7XG5cdFwieFwiOiAxMzAsXG5cdFwieVwiOiAyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDo5ZDdlM2IxOWFjNGYzZGVlOWM1Njc3YzEzNTMzM2I5ZDM1YTdmNTY4YjYzZDFlZjRhZGE0YjA2OGI1YTI1XCIsXG5cdFwiY29tbWFuZFwiOiBcIndhcnAgc3BpZGVyXCJcbn0iLCJ7XG5cdFwieFwiOiAxNTEsXG5cdFwieVwiOiAyLFxuXHRcImFuY2hvclJpZ2h0XCI6IGZhbHNlLFxuXHRcImFuY2hvckJvdHRvbVwiOiB0cnVlLFxuXHRcImljb25cIjogXCJza3VsbDpjMzY4N2UyNWM2MzJiY2U4YWE2MWUwZDY0YzI0ZTY5NGMzZWVhNjI5ZWE5NDRmNGNmMzBkY2ZiNGZiY2UwNzFcIixcblx0XCJjb21tYW5kXCI6IFwid2FycCBuZXRoZXJcIlxufSJd" + ) if (newButtons != null) buttons = moveButtons(newButtons.map { it.copy(command = it.command?.removePrefix("/")) }) } @@ -188,31 +192,24 @@ class InventoryButtonEditor( return newButtons } - override fun renderBackground(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { - context.matrices.push() - context.matrices.translate(0F, 0F, -15F) - super.renderBackground(context, mouseX, mouseY, delta) - context.matrices.pop() - } - override fun render(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { super.render(context, mouseX, mouseY, delta) - context.matrices.push() - context.matrices.translate(0f, 0f, -10f) + context.matrices.pushMatrix() PanelComponent.DefaultBackgroundRenderer.VANILLA .render( - ModernRenderContext(context), + MoulConfigRenderContext(context), lastGuiRect.minX, lastGuiRect.minY, lastGuiRect.width, lastGuiRect.height, ) - context.matrices.pop() + context.matrices.popMatrix() for (button in buttons) { val buttonPosition = button.getBounds(lastGuiRect) - context.matrices.push() - context.matrices.translate(buttonPosition.minX.toFloat(), buttonPosition.minY.toFloat(), 0F) + context.matrices.pushMatrix() + context.matrices.translate(buttonPosition.minX.toFloat(), buttonPosition.minY.toFloat()) button.render(context) - context.matrices.pop() + context.matrices.popMatrix() } + renderPopup(context, mouseX, mouseY, delta) } override fun keyPressed(keyCode: Int, scanCode: Int, modifiers: Int): Boolean { @@ -228,8 +225,15 @@ class InventoryButtonEditor( if (super.mouseReleased(mouseX, mouseY, button)) return true val clickedButton = buttons.firstOrNull { it.getBounds(lastGuiRect).contains(Point(mouseX, mouseY)) } if (clickedButton != null && !justPerformedAClickAction) { - if (InputUtil.isKeyPressed(MC.window.handle, InputUtil.GLFW_KEY_LEFT_CONTROL)) Editor(clickedButton).delete() - else createPopup(MoulConfigUtils.loadGui("button_editor_fragment", Editor(clickedButton)), Point(mouseX, mouseY)) + if (InputUtil.isKeyPressed( + MC.window.handle, + InputUtil.GLFW_KEY_LEFT_CONTROL + ) + ) Editor(clickedButton).delete() + else createPopup( + MoulConfigUtils.loadGui("button_editor_fragment", Editor(clickedButton)), + Point(mouseX, mouseY) + ) return true } justPerformedAClickAction = false diff --git a/src/main/kotlin/features/inventory/buttons/InventoryButtons.kt b/src/main/kotlin/features/inventory/buttons/InventoryButtons.kt index ab80d97..46e91b2 100644 --- a/src/main/kotlin/features/inventory/buttons/InventoryButtons.kt +++ b/src/main/kotlin/features/inventory/buttons/InventoryButtons.kt @@ -76,10 +76,10 @@ object InventoryButtons { var hoveredComponent: InventoryButton? = null for (button in getValidButtons(it.screen)) { val buttonBounds = button.getBounds(bounds) - it.context.matrices.push() - it.context.matrices.translate(buttonBounds.minX.toFloat(), buttonBounds.minY.toFloat(), 0F) + it.context.matrices.pushMatrix() + it.context.matrices.translate(buttonBounds.minX.toFloat(), buttonBounds.minY.toFloat()) button.render(it.context) - it.context.matrices.pop() + it.context.matrices.popMatrix() if (buttonBounds.contains(it.mouseX, it.mouseY) && TConfig.hoverText && hoveredComponent == null) { hoveredComponent = button diff --git a/src/main/kotlin/features/inventory/storageoverlay/StorageOverlayScreen.kt b/src/main/kotlin/features/inventory/storageoverlay/StorageOverlayScreen.kt index 267799d..a023ce6 100644 --- a/src/main/kotlin/features/inventory/storageoverlay/StorageOverlayScreen.kt +++ b/src/main/kotlin/features/inventory/storageoverlay/StorageOverlayScreen.kt @@ -20,7 +20,6 @@ import net.minecraft.item.ItemStack import net.minecraft.screen.slot.Slot import net.minecraft.text.Text import net.minecraft.util.Identifier -import moe.nea.firmament.annotations.Subscribe import moe.nea.firmament.events.SlotRenderEvents import moe.nea.firmament.gui.EmptyComponent import moe.nea.firmament.gui.FirmButtonComponent @@ -182,7 +181,7 @@ class StorageOverlayScreen : Screen(Text.literal("")) { val searchField = TextFieldComponent( searchText, 100, GetSetter.constant(true), tr("firmament.storage-overlay.search.suggestion", "Search...").string, - IMinecraft.instance.defaultFontRenderer + IMinecraft.INSTANCE.defaultFontRenderer ) val controlComponent = PanelComponent( ColumnComponent( @@ -384,7 +383,7 @@ class StorageOverlayScreen : Screen(Text.literal("")) { controlComponent, measurements.controlX, measurements.controlY, CONTROL_WIDTH, CONTROL_HEIGHT, - KeyboardEvent.KeyPressed(keyCode, false) + KeyboardEvent.KeyPressed(keyCode, scanCode, false) ) ) { return true @@ -401,7 +400,7 @@ class StorageOverlayScreen : Screen(Text.literal("")) { controlComponent, measurements.controlX, measurements.controlY, CONTROL_WIDTH, CONTROL_HEIGHT, - KeyboardEvent.KeyPressed(keyCode, true) + KeyboardEvent.KeyPressed(keyCode, scanCode, true) ) ) { return true @@ -498,7 +497,7 @@ class StorageOverlayScreen : Screen(Text.literal("")) { return 18 } assertTrueOr(slots == null || slots.size == inv.stacks.size) { return 0 } - val name = page.defaultName() + val name = inventory.title val pageHeight = inv.rows * SLOT_SIZE + 8 + textRenderer.fontHeight if (slots != null && StorageOverlay.TConfig.outlineActiveStoragePage) context.drawBorder( @@ -522,8 +521,8 @@ class StorageOverlayScreen : Screen(Text.literal("")) { inv.stacks.forEachIndexed { index, stack -> val slotX = (index % 9) * SLOT_SIZE + x + 3 val slotY = (index / 9) * SLOT_SIZE + y + 5 + textRenderer.fontHeight + 1 - val fakeSlot = FakeSlot(stack, slotX, slotY) if (slots == null) { + val fakeSlot = FakeSlot(stack, slotX, slotY) SlotRenderEvents.Before.publish(SlotRenderEvents.Before(context, fakeSlot)) context.drawItem(stack, slotX, slotY) context.drawStackOverlay(textRenderer, stack, slotX, slotY) diff --git a/src/main/kotlin/features/inventory/storageoverlay/StorageOverviewScreen.kt b/src/main/kotlin/features/inventory/storageoverlay/StorageOverviewScreen.kt index 3462d3d..e383d29 100644 --- a/src/main/kotlin/features/inventory/storageoverlay/StorageOverviewScreen.kt +++ b/src/main/kotlin/features/inventory/storageoverlay/StorageOverviewScreen.kt @@ -44,10 +44,10 @@ class StorageOverviewScreen() : Screen(Text.empty()) { super.render(context, mouseX, mouseY, delta) context.fill(0, 0, width, height, 0x90000000.toInt()) layoutedForEach { (key, value), offsetX, offsetY -> - context.matrices.push() - context.matrices.translate(offsetX.toFloat(), offsetY.toFloat(), 0F) + context.matrices.pushMatrix() + context.matrices.translate(offsetX.toFloat(), offsetY.toFloat()) renderStoragePage(context, value, mouseX - offsetX, mouseY - offsetY) - context.matrices.pop() + context.matrices.popMatrix() } } diff --git a/src/main/kotlin/features/items/BonemerangOverlay.kt b/src/main/kotlin/features/items/BonemerangOverlay.kt index ffdffe3..6483b7a 100644 --- a/src/main/kotlin/features/items/BonemerangOverlay.kt +++ b/src/main/kotlin/features/items/BonemerangOverlay.kt @@ -2,6 +2,7 @@ package moe.nea.firmament.features.items import me.shedaniel.math.Color import moe.nea.jarvis.api.Point +import org.joml.Vector2i import net.minecraft.entity.LivingEntity import net.minecraft.entity.decoration.ArmorStandEntity import net.minecraft.entity.player.PlayerEntity @@ -25,7 +26,7 @@ object BonemerangOverlay : FirmamentFeature { object TConfig : ManagedConfig(identifier, Category.ITEMS) { var bonemerangOverlay by toggle("bonemerang-overlay") { false } - val bonemerangOverlayHud by position("bonemerang-overlay-hud", 80, 10) { Point(0.1, 1.0) } + val bonemerangOverlayHud by position("bonemerang-overlay-hud", 80, 10) { Vector2i() } var highlightHitEntities by toggle("highlight-hit-entities") { false } } @@ -87,7 +88,7 @@ object BonemerangOverlay : FirmamentFeature { val entities = getEntities() - it.context.matrices.push() + it.context.matrices.pushMatrix() TConfig.bonemerangOverlayHud.applyTransformations(it.context.matrices) it.context.drawText( MC.font, String.format( @@ -96,6 +97,6 @@ object BonemerangOverlay : FirmamentFeature { ).string, entities.size ), 0, 0, -1, true ) - it.context.matrices.pop() + it.context.matrices.popMatrix() } } diff --git a/src/main/kotlin/features/macros/ComboProcessor.kt b/src/main/kotlin/features/macros/ComboProcessor.kt index 5c5ac0e..1f77ff6 100644 --- a/src/main/kotlin/features/macros/ComboProcessor.kt +++ b/src/main/kotlin/features/macros/ComboProcessor.kt @@ -56,12 +56,11 @@ object ComboProcessor { fun onRender(event: HudRenderEvent) { if (!isInputting) return if (!event.isRenderingHud) return - event.context.matrices.push() + event.context.matrices.pushMatrix() val width = 120 event.context.matrices.translate( (MC.window.scaledWidth - width) / 2F, - (MC.window.scaledHeight) / 2F + 8, - 0F + (MC.window.scaledHeight) / 2F + 8 ) val breadCrumbText = breadCrumbs.joinToString(" > ") event.context.drawText( @@ -72,7 +71,7 @@ object ComboProcessor { -1, true ) - event.context.matrices.translate(0F, MC.font.fontHeight + 2F, 0F) + event.context.matrices.translate(0F, MC.font.fontHeight + 2F) for ((key, value) in activeTrie.nodes) { event.context.drawText( MC.font, @@ -82,9 +81,9 @@ object ComboProcessor { -1, true ) - event.context.matrices.translate(0F, MC.font.fontHeight + 1F, 0F) + event.context.matrices.translate(0F, MC.font.fontHeight + 1F) } - event.context.matrices.pop() + event.context.matrices.popMatrix() } @Subscribe diff --git a/src/main/kotlin/features/macros/MacroUI.kt b/src/main/kotlin/features/macros/MacroUI.kt index 8c22c5c..5a7d406 100644 --- a/src/main/kotlin/features/macros/MacroUI.kt +++ b/src/main/kotlin/features/macros/MacroUI.kt @@ -1,7 +1,9 @@ package moe.nea.firmament.features.macros +import io.github.notenoughupdates.moulconfig.common.text.StructuredText import io.github.notenoughupdates.moulconfig.gui.CloseEventListener import io.github.notenoughupdates.moulconfig.observer.ObservableList +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform import io.github.notenoughupdates.moulconfig.xml.Bind import moe.nea.firmament.annotations.Subscribe import moe.nea.firmament.commands.thenExecute @@ -62,6 +64,9 @@ class MacroUI { val parent: Wheel, ) { @Bind + fun textR() = StructuredText.of(text) + + @Bind fun delete() { parent.editableCommands.removeIf { it === this } parent.editableCommands.update() @@ -82,7 +87,7 @@ class MacroUI { } @Bind("keyCombo") - fun text() = binding.format().string + fun text() = MoulConfigPlatform.wrap(binding.format()) @field:Bind("commands") val commands = commands.mapTo(ObservableList(mutableListOf())) { Command(it.command, this) } @@ -246,12 +251,15 @@ class MacroUI { @field:Bind("command") var command: String = (action.action as CommandAction).command + @Bind + fun commandR() = StructuredText.of(command) + @field:Bind("combo") val combo = action.keys.map { KeyBindingEditor(it, this) }.toObservableList() @Bind fun formattedCombo() = - combo.joinToString(" > ") { it.binding.toString() } + StructuredText.of(combo.joinToString(" > ") { it.binding.toString() }) // TODO: this can be joined without .toString() @Bind fun addStep() { diff --git a/src/main/kotlin/features/macros/RadialMenu.kt b/src/main/kotlin/features/macros/RadialMenu.kt index 9e5222f..5134994 100644 --- a/src/main/kotlin/features/macros/RadialMenu.kt +++ b/src/main/kotlin/features/macros/RadialMenu.kt @@ -63,11 +63,10 @@ object RadialMenuViewer { fun onRender(event: HudRenderEvent) { val menu = activeMenu ?: return val mat = event.context.matrices - mat.push() + mat.pushMatrix() mat.translate( (MC.window.scaledWidth) / 2F, (MC.window.scaledHeight) / 2F, - 0F ) val sliceWidth = (τ / menu.options.size).toFloat() var selectedAngle = wrapAngle(atan2(delta.y, delta.x)) @@ -75,8 +74,8 @@ object RadialMenuViewer { selectedAngle = Float.NaN for ((idx, option) in menu.options.withIndex()) { val range = (sliceWidth * idx)..(sliceWidth * (idx + 1)) - mat.push() - mat.scale(64F, 64F, 1F) + mat.pushMatrix() + mat.scale(64F, 64F) val cutout = INNER_CIRCLE_RADIUS / 64F / 2 RenderCircleProgress.renderCircularSlice( event.context, @@ -86,16 +85,16 @@ object RadialMenuViewer { color = if (selectedAngle in range) 0x70A0A0A0 else 0x70FFFFFF, innerCutoutRadius = cutout ) - mat.pop() - mat.push() + mat.popMatrix() + mat.pushMatrix() val centreAngle = lerpAngle(range.start, range.endInclusive, 0.5F) val vec = Vector2f(cos(centreAngle), sin(centreAngle)).mul(40F) - mat.translate(vec.x, vec.y, 0F) + mat.translate(vec.x, vec.y) option.renderSlice(event.context) - mat.pop() + mat.popMatrix() } event.context.drawLine(1, 1, delta.x.toInt(), delta.y.toInt(), me.shedaniel.math.Color.ofOpaque(0x00FF00)) - mat.pop() + mat.popMatrix() } @Subscribe diff --git a/src/main/kotlin/features/mining/MiningBlockInfoUi.kt b/src/main/kotlin/features/mining/MiningBlockInfoUi.kt index e8ea4f4..5b58d4f 100644 --- a/src/main/kotlin/features/mining/MiningBlockInfoUi.kt +++ b/src/main/kotlin/features/mining/MiningBlockInfoUi.kt @@ -2,7 +2,7 @@ package moe.nea.firmament.features.mining import io.github.notenoughupdates.moulconfig.observer.ObservableList import io.github.notenoughupdates.moulconfig.observer.Property -import io.github.notenoughupdates.moulconfig.platform.ModernItemStack +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform import io.github.notenoughupdates.moulconfig.xml.Bind import net.minecraft.client.gui.screen.Screen import net.minecraft.item.ItemStack @@ -31,7 +31,7 @@ object MiningBlockInfoUi { class BlockInfo(val block: MiningRepoData.Block189, val info: MiningInfo) { @get:Bind("item") - val item = ModernItemStack.of(block.block?.let { ItemStack(it) } ?: ItemStack.EMPTY) + val item = MoulConfigPlatform.wrap(block.block?.let { ItemStack(it) } ?: ItemStack.EMPTY) @get:Bind("isSelected") val isSelected get() = info.search.let { block.isActiveIn(SkyBlockIsland.forMode(it)) } diff --git a/src/main/kotlin/features/mining/PickaxeAbility.kt b/src/main/kotlin/features/mining/PickaxeAbility.kt index a049001..df683de 100644 --- a/src/main/kotlin/features/mining/PickaxeAbility.kt +++ b/src/main/kotlin/features/mining/PickaxeAbility.kt @@ -231,14 +231,14 @@ object PickaxeAbility : FirmamentFeature { if (ao != ability.name && ao != null) { ability = PickaxeAbilityData(ao, defaultAbilityDurations[ao] ?: 120.seconds) } - event.context.matrices.push() - event.context.matrices.translate(MC.window.scaledWidth / 2F, MC.window.scaledHeight / 2F, 0F) - event.context.matrices.scale(TConfig.cooldownScale.toFloat(), TConfig.cooldownScale.toFloat(), 1F) + event.context.matrices.pushMatrix() + event.context.matrices.translate(MC.window.scaledWidth / 2F, MC.window.scaledHeight / 2F) + event.context.matrices.scale(TConfig.cooldownScale.toFloat(), TConfig.cooldownScale.toFloat()) RenderCircleProgress.renderCircle( event.context, Identifier.of("firmament", "textures/gui/circle.png"), getCooldownPercentage(ability.name, ability.cooldown).toFloat(), 0f, 1f, 0f, 1f ) - event.context.matrices.pop() + event.context.matrices.popMatrix() } } diff --git a/src/main/kotlin/features/mining/PristineProfitTracker.kt b/src/main/kotlin/features/mining/PristineProfitTracker.kt index 377a470..eb3cba6 100644 --- a/src/main/kotlin/features/mining/PristineProfitTracker.kt +++ b/src/main/kotlin/features/mining/PristineProfitTracker.kt @@ -2,6 +2,7 @@ package moe.nea.firmament.features.mining import io.github.notenoughupdates.moulconfig.xml.Bind import moe.nea.jarvis.api.Point +import org.joml.Vector2i import kotlinx.serialization.Serializable import kotlinx.serialization.serializer import kotlin.time.Duration.Companion.seconds @@ -57,7 +58,7 @@ object PristineProfitTracker : FirmamentFeature { object TConfig : ManagedConfig(identifier, Category.MINING) { val timeout by duration("timeout", 0.seconds, 120.seconds) { 30.seconds } - val gui by position("position", 100, 30) { Point(0.05, 0.2) } + val gui by position("position", 100, 30) { Vector2i() } val useFineGemstones by toggle("fine-gemstones") { false } } diff --git a/src/main/kotlin/features/misc/CustomCapes.kt b/src/main/kotlin/features/misc/CustomCapes.kt index dc5187a..77a5c2d 100644 --- a/src/main/kotlin/features/misc/CustomCapes.kt +++ b/src/main/kotlin/features/misc/CustomCapes.kt @@ -1,8 +1,13 @@ package moe.nea.firmament.features.misc +import com.mojang.blaze3d.buffers.GpuBuffer +import com.mojang.blaze3d.buffers.Std140Builder import com.mojang.blaze3d.systems.RenderSystem +import java.nio.ByteBuffer +import java.nio.ByteOrder import java.util.OptionalDouble import java.util.OptionalInt +import org.joml.Vector4f import util.render.CustomRenderPipelines import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds @@ -14,12 +19,14 @@ import net.minecraft.client.render.VertexConsumerProvider import net.minecraft.client.render.entity.state.PlayerEntityRenderState import net.minecraft.client.util.BufferAllocator import net.minecraft.client.util.SkinTextures +import net.minecraft.client.util.math.MatrixStack import net.minecraft.util.Identifier import moe.nea.firmament.Firmament import moe.nea.firmament.features.FirmamentFeature import moe.nea.firmament.gui.config.ManagedConfig import moe.nea.firmament.util.MC import moe.nea.firmament.util.TimeMark +import moe.nea.firmament.util.mc.CustomRenderPassHelper object CustomCapes : FirmamentFeature { override val identifier: String @@ -36,6 +43,7 @@ object CustomCapes : FirmamentFeature { fun replaceRender( renderLayer: RenderLayer, vertexConsumerProvider: VertexConsumerProvider, + matrixStack: MatrixStack, model: (VertexConsumer) -> Unit ) } @@ -46,6 +54,7 @@ object CustomCapes : FirmamentFeature { override fun replaceRender( renderLayer: RenderLayer, vertexConsumerProvider: VertexConsumerProvider, + matrixStack: MatrixStack, model: (VertexConsumer) -> Unit ) { model(vertexConsumerProvider.getBuffer(RenderLayer.getEntitySolid(location))) @@ -61,37 +70,27 @@ object CustomCapes : FirmamentFeature { override fun replaceRender( renderLayer: RenderLayer, vertexConsumerProvider: VertexConsumerProvider, + matrixStack: MatrixStack, model: (VertexConsumer) -> Unit ) { - BufferAllocator(2048).use { allocator -> - val bufferBuilder = BufferBuilder(allocator, renderLayer.drawMode, renderLayer.vertexFormat) - model(bufferBuilder) - bufferBuilder.end().use { buffer -> - val commandEncoder = RenderSystem.getDevice().createCommandEncoder() - val vertexBuffer = renderLayer.vertexFormat.uploadImmediateVertexBuffer(buffer.buffer) - val indexBufferConstructor = RenderSystem.getSequentialBuffer(renderLayer.drawMode) - val indexBuffer = indexBufferConstructor.getIndexBuffer(buffer.drawParameters.indexCount) - val templateTexture = MC.textureManager.getTexture(template) - val backgroundTexture = MC.textureManager.getTexture(background) - val foregroundTexture = MC.textureManager.getTexture(overlay) - commandEncoder.createRenderPass( - MC.instance.framebuffer.colorAttachment, - OptionalInt.empty(), - MC.instance.framebuffer.depthAttachment, - OptionalDouble.empty(), - ).use { renderPass -> - // TODO: account for lighting - renderPass.setPipeline(CustomRenderPipelines.PARALLAX_CAPE_SHADER) - renderPass.bindSampler("Sampler0", templateTexture.glTexture) - renderPass.bindSampler("Sampler1", backgroundTexture.glTexture) - renderPass.bindSampler("Sampler3", foregroundTexture.glTexture) - val animationValue = (startTime.passedTime() / animationSpeed).mod(1F) - renderPass.setUniform("Animation", animationValue.toFloat()) - renderPass.setIndexBuffer(indexBuffer, indexBufferConstructor.indexType) - renderPass.setVertexBuffer(0, vertexBuffer) - renderPass.drawIndexed(0, buffer.drawParameters.indexCount) - } + val animationValue = (startTime.passedTime() / animationSpeed).mod(1F) + CustomRenderPassHelper( + { "Firmament Cape Renderer" }, + renderLayer.drawMode, + renderLayer.vertexFormat, + MC.instance.framebuffer, + true, + ).use { renderPass -> + renderPass.setPipeline(CustomRenderPipelines.PARALLAX_CAPE_SHADER) + renderPass.setAllDefaultUniforms() + renderPass.setUniform("Animation", 4) { + it.putFloat(animationValue.toFloat()) } + renderPass.bindSampler("Sampler0", template) + renderPass.bindSampler("Sampler1", background) + renderPass.bindSampler("Sampler3", overlay) + renderPass.uploadVertices(2048, model) + renderPass.draw() } } } @@ -122,7 +121,10 @@ object CustomCapes : FirmamentFeature { 110.seconds ) ), - + UNPLEASANT_GRADIENT( + "unpleasant_gradient", + TexturedCapeRenderer(Firmament.identifier("textures/cape/unpleasant_gradient.png")) + ), FURFSKY_STATIC( "FurfSky", TexturedCapeRenderer(Firmament.identifier("textures/cape/fsr_static.png")) @@ -141,7 +143,7 @@ object CustomCapes : FirmamentFeature { val byUuid = listOf( listOf( - Devs.nea to AllCapes.FIRMAMENT_ANIMATED, + Devs.nea to AllCapes.UNPLEASANT_GRADIENT, Devs.kath to AllCapes.FIRMAMENT_STATIC, Devs.jani to AllCapes.FIRMAMENT_ANIMATED, ), @@ -154,12 +156,13 @@ object CustomCapes : FirmamentFeature { vertexConsumer: VertexConsumer, renderLayer: RenderLayer, vertexConsumerProvider: VertexConsumerProvider, + matrixStack: MatrixStack, model: (VertexConsumer) -> Unit ) { val capeStorage = CapeStorage.cast(playerEntityRenderState) val firmCape = capeStorage.cape_firmament if (firmCape != null) { - firmCape.render.replaceRender(renderLayer, vertexConsumerProvider, model) + firmCape.render.replaceRender(renderLayer, vertexConsumerProvider, matrixStack, model) } else { model(vertexConsumer) } diff --git a/src/main/kotlin/features/misc/Hud.kt b/src/main/kotlin/features/misc/Hud.kt index 9661fc5..8c785ab 100644 --- a/src/main/kotlin/features/misc/Hud.kt +++ b/src/main/kotlin/features/misc/Hud.kt @@ -7,6 +7,7 @@ import moe.nea.firmament.gui.config.ManagedConfig import moe.nea.firmament.util.MC import moe.nea.firmament.util.tr import moe.nea.jarvis.api.Point +import org.joml.Vector2i import net.minecraft.client.network.PlayerListEntry import net.minecraft.text.Text @@ -16,11 +17,11 @@ object Hud : FirmamentFeature { object TConfig : ManagedConfig(identifier, Category.MISC) { var dayCount by toggle("day-count") { false } - val dayCountHud by position("day-count-hud", 80, 10) { Point(0.5, 0.8) } + val dayCountHud by position("day-count-hud", 80, 10) { Vector2i() } var fpsCount by toggle("fps-count") { false } - val fpsCountHud by position("fps-count-hud", 80, 10) { Point(0.5, 0.9) } + val fpsCountHud by position("fps-count-hud", 80, 10) { Vector2i() } var pingCount by toggle("ping-count") { false } - val pingCountHud by position("ping-count-hud", 80, 10) { Point(0.5, 1.0) } + val pingCountHud by position("ping-count-hud", 80, 10) { Vector2i() } } override val config: ManagedConfig @@ -29,7 +30,7 @@ object Hud : FirmamentFeature { @Subscribe fun onRenderHud(it: HudRenderEvent) { if (TConfig.dayCount) { - it.context.matrices.push() + it.context.matrices.pushMatrix() TConfig.dayCountHud.applyTransformations(it.context.matrices) val day = (MC.world?.timeOfDay ?: 0L) / 24000 it.context.drawText( @@ -40,11 +41,11 @@ object Hud : FirmamentFeature { -1, true ) - it.context.matrices.pop() + it.context.matrices.popMatrix() } if (TConfig.fpsCount) { - it.context.matrices.push() + it.context.matrices.pushMatrix() TConfig.fpsCountHud.applyTransformations(it.context.matrices) it.context.drawText( MC.font, Text.literal( @@ -53,11 +54,11 @@ object Hud : FirmamentFeature { ) ), 36, MC.font.fontHeight, -1, true ) - it.context.matrices.pop() + it.context.matrices.popMatrix() } if (TConfig.pingCount) { - it.context.matrices.push() + it.context.matrices.pushMatrix() TConfig.pingCountHud.applyTransformations(it.context.matrices) val ping = MC.player?.let { val entry: PlayerListEntry? = MC.networkHandler?.getPlayerListEntry(it.uuid) @@ -71,7 +72,7 @@ object Hud : FirmamentFeature { ), 36, MC.font.fontHeight, -1, true ) - it.context.matrices.pop() + it.context.matrices.popMatrix() } } } diff --git a/src/main/kotlin/features/world/FairySouls.kt b/src/main/kotlin/features/world/FairySouls.kt index d4bf560..699aafc 100644 --- a/src/main/kotlin/features/world/FairySouls.kt +++ b/src/main/kotlin/features/world/FairySouls.kt @@ -103,7 +103,6 @@ object FairySouls : FirmamentFeature { currentMissingSouls.forEach { block(it.blockPos, Color.ofRGBA(176, 0, 255, 128).color) } - color(1f, 0f, 1f, 1f) currentLocationSouls.forEach { wireframeCube(it.blockPos) } diff --git a/src/main/kotlin/features/world/Waypoints.kt b/src/main/kotlin/features/world/Waypoints.kt index b4f91b0..205d5eb 100644 --- a/src/main/kotlin/features/world/Waypoints.kt +++ b/src/main/kotlin/features/world/Waypoints.kt @@ -53,8 +53,7 @@ object Waypoints : FirmamentFeature { } else { orderedIndex %= w.waypoints.size val firstColor = Color.ofRGBA(0, 200, 40, 180) - color(firstColor) - tracer(w.waypoints[orderedIndex].blockPos.toCenterPos(), lineWidth = 3f) + tracer(w.waypoints[orderedIndex].blockPos.toCenterPos(), color = firstColor.color, lineWidth = 3f) w.waypoints.withIndex().toList().wrappingWindow(orderedIndex, 3).zip(listOf( firstColor, Color.ofRGBA(180, 200, 40, 150), diff --git a/src/main/kotlin/gui/BarComponent.kt b/src/main/kotlin/gui/BarComponent.kt index da781da..751ea39 100644 --- a/src/main/kotlin/gui/BarComponent.kt +++ b/src/main/kotlin/gui/BarComponent.kt @@ -6,8 +6,10 @@ import io.github.notenoughupdates.moulconfig.common.RenderContext import io.github.notenoughupdates.moulconfig.gui.GuiComponent import io.github.notenoughupdates.moulconfig.gui.GuiImmediateContext import io.github.notenoughupdates.moulconfig.observer.GetSetter -import io.github.notenoughupdates.moulconfig.platform.ModernRenderContext +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform +import io.github.notenoughupdates.moulconfig.platform.MoulConfigRenderContext import me.shedaniel.math.Color +import net.minecraft.client.gl.RenderPipelines import net.minecraft.client.gui.DrawContext import net.minecraft.client.render.RenderLayer import net.minecraft.util.Identifier @@ -33,7 +35,7 @@ class BarComponent( ) { fun draw(context: DrawContext, x: Int, y: Int, width: Int, height: Int, color: Color) { context.drawTexturedQuad( - RenderLayer::getGuiTextured, + RenderPipelines.GUI_TEXTURED, identifier, x, y, x + width, x + height, u1, u2, v1, v2, @@ -81,7 +83,7 @@ class BarComponent( } override fun render(context: GuiImmediateContext) { - val renderContext = (context.renderContext as ModernRenderContext).drawContext + val renderContext = (context.renderContext as MoulConfigRenderContext).drawContext var i = 0 val x = 0 val y = 0 @@ -104,7 +106,6 @@ class BarComponent( (context.width - 4) * total.get() / context.width, total.get() ) - RenderSystem.setShaderColor(1F, 1F, 1F, 1F) } diff --git a/src/main/kotlin/gui/CheckboxComponent.kt b/src/main/kotlin/gui/CheckboxComponent.kt index fc48661..7a9f2ef 100644 --- a/src/main/kotlin/gui/CheckboxComponent.kt +++ b/src/main/kotlin/gui/CheckboxComponent.kt @@ -4,7 +4,8 @@ import io.github.notenoughupdates.moulconfig.gui.GuiComponent import io.github.notenoughupdates.moulconfig.gui.GuiImmediateContext import io.github.notenoughupdates.moulconfig.gui.MouseEvent import io.github.notenoughupdates.moulconfig.observer.GetSetter -import io.github.notenoughupdates.moulconfig.platform.ModernRenderContext +import io.github.notenoughupdates.moulconfig.platform.MoulConfigRenderContext +import net.minecraft.client.gl.RenderPipelines import net.minecraft.client.render.RenderLayer import moe.nea.firmament.Firmament @@ -25,9 +26,9 @@ class CheckboxComponent<T>( } override fun render(context: GuiImmediateContext) { - val ctx = (context.renderContext as ModernRenderContext).drawContext + val ctx = (context.renderContext as MoulConfigRenderContext).drawContext ctx.drawGuiTexture( - RenderLayer::getGuiTextured, + RenderPipelines.GUI_TEXTURED, if (isEnabled()) Firmament.identifier("widget/checkbox_checked") else Firmament.identifier("widget/checkbox_unchecked"), 0, 0, diff --git a/src/main/kotlin/gui/FirmHoverComponent.kt b/src/main/kotlin/gui/FirmHoverComponent.kt index e38582a..eed795a 100644 --- a/src/main/kotlin/gui/FirmHoverComponent.kt +++ b/src/main/kotlin/gui/FirmHoverComponent.kt @@ -1,5 +1,6 @@ package moe.nea.firmament.gui +import io.github.notenoughupdates.moulconfig.common.text.StructuredText import io.github.notenoughupdates.moulconfig.gui.GuiComponent import io.github.notenoughupdates.moulconfig.gui.GuiImmediateContext import io.github.notenoughupdates.moulconfig.gui.KeyboardEvent @@ -31,7 +32,8 @@ class FirmHoverComponent( override fun render(context: GuiImmediateContext) { if (context.isHovered && (permaHover || lastMouseMove.passedTime() > hoverDelay)) { - context.renderContext.scheduleDrawTooltip(context.mouseX, context.mouseY, hoverLines.get()) + context.renderContext.scheduleDrawTooltip(context.mouseX, context.mouseY, hoverLines.get() + .map { it -> StructuredText.of(it) }) permaHover = true } else { permaHover = false diff --git a/src/main/kotlin/gui/config/DurationHandler.kt b/src/main/kotlin/gui/config/DurationHandler.kt index 8d485b1..32bec25 100644 --- a/src/main/kotlin/gui/config/DurationHandler.kt +++ b/src/main/kotlin/gui/config/DurationHandler.kt @@ -3,6 +3,7 @@ package moe.nea.firmament.gui.config import io.github.notenoughupdates.moulconfig.common.IMinecraft +import io.github.notenoughupdates.moulconfig.common.text.StructuredText import io.github.notenoughupdates.moulconfig.gui.component.RowComponent import io.github.notenoughupdates.moulconfig.gui.component.SliderComponent import io.github.notenoughupdates.moulconfig.gui.component.TextComponent @@ -31,8 +32,8 @@ class DurationHandler(val config: ManagedConfig, val min: Duration, val max: Dur guiAppender.appendLabeledRow( opt.labelText, RowComponent( - TextComponent(IMinecraft.instance.defaultFontRenderer, - { FirmFormatters.formatTimespan(opt.value) }, + TextComponent(IMinecraft.INSTANCE.defaultFontRenderer, + { StructuredText.of(FirmFormatters.formatTimespan(opt.value)) }, 40, TextComponent.TextAlignment.CENTER, true, diff --git a/src/main/kotlin/gui/config/HudMetaHandler.kt b/src/main/kotlin/gui/config/HudMetaHandler.kt index a9659ee..0637351 100644 --- a/src/main/kotlin/gui/config/HudMetaHandler.kt +++ b/src/main/kotlin/gui/config/HudMetaHandler.kt @@ -8,18 +8,25 @@ import kotlinx.serialization.json.encodeToJsonElement import net.minecraft.client.gui.screen.Screen import net.minecraft.text.MutableText import net.minecraft.text.Text +import moe.nea.firmament.Firmament import moe.nea.firmament.gui.FirmButtonComponent import moe.nea.firmament.jarvis.JarvisIntegration import moe.nea.firmament.util.MC -class HudMetaHandler(val config: ManagedConfig, val label: MutableText, val width: Int, val height: Int) : +class HudMetaHandler( + val config: ManagedConfig, + val propertyName: String, + val label: MutableText, + val width: Int, + val height: Int +) : ManagedConfig.OptionHandler<HudMeta> { override fun toJson(element: HudMeta): JsonElement? { return Json.encodeToJsonElement(element.position) } override fun fromJson(element: JsonElement): HudMeta { - return HudMeta(Json.decodeFromJsonElement(element), label, width, height) + return HudMeta(Json.decodeFromJsonElement(element), Firmament.identifier(propertyName), label, width, height) } fun openEditor(option: ManagedOption<HudMeta>, oldScreen: Screen) { @@ -34,7 +41,8 @@ class HudMetaHandler(val config: ManagedConfig, val label: MutableText, val widt opt.labelText, FirmButtonComponent( TextComponent( - Text.stringifiedTranslatable("firmament.hud.edit", label).string), + Text.stringifiedTranslatable("firmament.hud.edit", label).string + ), ) { openEditor(opt, guiAppender.screenAccessor()) }) diff --git a/src/main/kotlin/gui/config/IntegerHandler.kt b/src/main/kotlin/gui/config/IntegerHandler.kt index 31ce90f..fd10447 100644 --- a/src/main/kotlin/gui/config/IntegerHandler.kt +++ b/src/main/kotlin/gui/config/IntegerHandler.kt @@ -3,6 +3,7 @@ package moe.nea.firmament.gui.config import io.github.notenoughupdates.moulconfig.common.IMinecraft +import io.github.notenoughupdates.moulconfig.common.text.StructuredText import io.github.notenoughupdates.moulconfig.gui.component.RowComponent import io.github.notenoughupdates.moulconfig.gui.component.SliderComponent import io.github.notenoughupdates.moulconfig.gui.component.TextComponent @@ -26,8 +27,8 @@ class IntegerHandler(val config: ManagedConfig, val min: Int, val max: Int) : Ma guiAppender.appendLabeledRow( opt.labelText, RowComponent( - TextComponent(IMinecraft.instance.defaultFontRenderer, - { FirmFormatters.formatCommas(opt.value, 0) }, + TextComponent(IMinecraft.INSTANCE.defaultFontRenderer, + { StructuredText.of(FirmFormatters.formatCommas(opt.value, 0)) }, 40, TextComponent.TextAlignment.CENTER, true, diff --git a/src/main/kotlin/gui/config/JAnyHud.kt b/src/main/kotlin/gui/config/JAnyHud.kt index 35c4eb2..1cde4f9 100644 --- a/src/main/kotlin/gui/config/JAnyHud.kt +++ b/src/main/kotlin/gui/config/JAnyHud.kt @@ -1,48 +1,67 @@ - - package moe.nea.firmament.gui.config import moe.nea.jarvis.api.JarvisHud -import moe.nea.jarvis.api.JarvisScalable +import org.joml.Matrix3x2f +import org.joml.Vector2i +import org.joml.Vector2ic import kotlinx.serialization.Serializable import net.minecraft.text.Text +import net.minecraft.util.Identifier +import moe.nea.firmament.jarvis.JarvisIntegration @Serializable data class HudPosition( - var x: Double, - var y: Double, - var scale: Float, + var x: Int, + var y: Int, + var scale: Float, ) data class HudMeta( - val position: HudPosition, - private val label: Text, - private val width: Int, - private val height: Int, -) : JarvisScalable, JarvisHud { - override fun getX(): Double = position.x + val position: HudPosition, + private val id: Identifier, + private val label: Text, + private val width: Int, + private val height: Int, +) : JarvisHud, JarvisHud.Scalable { + override fun getLabel(): Text = label + override fun getUnscaledWidth(): Int { + return width + } + + override fun getUnscaledHeight(): Int { + return height + } - override fun setX(newX: Double) { - position.x = newX - } + override fun getHudId(): Identifier { + return id + } - override fun getY(): Double = position.y + override fun getPosition(): Vector2ic { + return Vector2i(position.x, position.y) + } - override fun setY(newY: Double) { - position.y = newY - } + override fun setPosition(p0: Vector2ic) { + position.x = p0.x() + position.y = p0.y() + } - override fun getLabel(): Text = label + override fun isEnabled(): Boolean { + return true // TODO: this should be actually truthful, if possible + } - override fun getWidth(): Int = width + override fun isVisible(): Boolean { + return true // TODO: this should be actually truthful, if possible + } - override fun getHeight(): Int = height + override fun getScale(): Float = position.scale - override fun getScale(): Float = position.scale + override fun setScale(newScale: Float) { + position.scale = newScale + } - override fun setScale(newScale: Float) { - position.scale = newScale - } + fun applyTransformations(matrix4f: Matrix3x2f) { + applyTransformations(JarvisIntegration.jarvis, matrix4f) + } } diff --git a/src/main/kotlin/gui/config/KeyBindingStateManager.kt b/src/main/kotlin/gui/config/KeyBindingStateManager.kt index 1528ac4..49a4465 100644 --- a/src/main/kotlin/gui/config/KeyBindingStateManager.kt +++ b/src/main/kotlin/gui/config/KeyBindingStateManager.kt @@ -6,6 +6,7 @@ import io.github.notenoughupdates.moulconfig.deps.libninepatch.NinePatch import io.github.notenoughupdates.moulconfig.gui.GuiImmediateContext import io.github.notenoughupdates.moulconfig.gui.KeyboardEvent import io.github.notenoughupdates.moulconfig.gui.component.TextComponent +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform import org.lwjgl.glfw.GLFW import net.minecraft.text.Text import net.minecraft.util.Formatting @@ -116,8 +117,8 @@ class KeyBindingStateManager( fun createButton(): FirmButtonComponent { return object : FirmButtonComponent( TextComponent( - IMinecraft.instance.defaultFontRenderer, - { this@KeyBindingStateManager.label.string }, + IMinecraft.INSTANCE.defaultFontRenderer, + { MoulConfigPlatform.wrap(this@KeyBindingStateManager.label) }, 130, TextComponent.TextAlignment.LEFT, false, diff --git a/src/main/kotlin/gui/config/ManagedConfig.kt b/src/main/kotlin/gui/config/ManagedConfig.kt index 12b82d6..2f4144c 100644 --- a/src/main/kotlin/gui/config/ManagedConfig.kt +++ b/src/main/kotlin/gui/config/ManagedConfig.kt @@ -3,7 +3,6 @@ package moe.nea.firmament.gui.config import com.mojang.serialization.Codec import io.github.notenoughupdates.moulconfig.ChromaColour import io.github.notenoughupdates.moulconfig.gui.CloseEventListener -import io.github.notenoughupdates.moulconfig.gui.GuiComponentWrapper import io.github.notenoughupdates.moulconfig.gui.GuiContext import io.github.notenoughupdates.moulconfig.gui.component.CenterComponent import io.github.notenoughupdates.moulconfig.gui.component.ColumnComponent @@ -11,7 +10,9 @@ import io.github.notenoughupdates.moulconfig.gui.component.PanelComponent import io.github.notenoughupdates.moulconfig.gui.component.RowComponent import io.github.notenoughupdates.moulconfig.gui.component.ScrollPanelComponent import io.github.notenoughupdates.moulconfig.gui.component.TextComponent +import io.github.notenoughupdates.moulconfig.platform.MoulConfigScreenComponent import moe.nea.jarvis.api.Point +import org.joml.Vector2i import org.lwjgl.glfw.GLFW import kotlinx.serialization.encodeToString import kotlinx.serialization.json.JsonElement @@ -119,7 +120,7 @@ abstract class ManagedConfig( return option(propertyName, default, BooleanHandler(this)) } - protected fun colour(propertyName: String, default: ()-> ChromaColour) : ManagedOption<ChromaColour> { + protected fun colour(propertyName: String, default: () -> ChromaColour): ManagedOption<ChromaColour> { return option(propertyName, default, ColourHandler(this)) } @@ -172,13 +173,13 @@ abstract class ManagedConfig( propertyName: String, width: Int, height: Int, - default: () -> Point, + default: () -> Vector2i, ): ManagedOption<HudMeta> { val label = Text.translatable("firmament.config.${name}.${propertyName}") return option(propertyName, { val p = default() - HudMeta(HudPosition(p.x, p.y, 1F), label, width, height) - }, HudMetaHandler(this, label, width, height)) + HudMeta(HudPosition(p.x(), p.y(), 1F), Firmament.identifier(propertyName), label, width, height) + }, HudMetaHandler(this, propertyName, label, width, height)) } protected fun keyBinding( @@ -228,7 +229,8 @@ abstract class ManagedConfig( var screen: Screen? = null val guiapp = GuiAppender(400) { requireNotNull(screen) { "Screen Accessor called too early" } } latestGuiAppender = guiapp - guiapp.appendFullRow(RowComponent( + guiapp.appendFullRow( + RowComponent( FirmButtonComponent(TextComponent("←")) { if (parent != null) { save() @@ -240,12 +242,16 @@ abstract class ManagedConfig( )) sortedOptions.forEach { it.appendToGui(guiapp) } guiapp.reloadables.forEach { it() } - val component = CenterComponent(PanelComponent(ScrollPanelComponent(400, 300, ColumnComponent(guiapp.panel)), - 10, - PanelComponent.DefaultBackgroundRenderer.VANILLA)) - screen = object : GuiComponentWrapper(GuiContext(component)) { + val component = CenterComponent( + PanelComponent( + ScrollPanelComponent(400, 300, ColumnComponent(guiapp.panel)), + 10, + PanelComponent.DefaultBackgroundRenderer.VANILLA + ) + ) + screen = object : MoulConfigScreenComponent(Text.empty(), GuiContext(component), parent) { override fun close() { - if (context.onBeforeClose() == CloseEventListener.CloseAction.NO_OBJECTIONS_TO_CLOSE) { + if (guiContext.onBeforeClose() == CloseEventListener.CloseAction.NO_OBJECTIONS_TO_CLOSE) { client!!.setScreen(parent) } } diff --git a/src/main/kotlin/gui/entity/EntityRenderer.kt b/src/main/kotlin/gui/entity/EntityRenderer.kt index a1b2577..435c628 100644 --- a/src/main/kotlin/gui/entity/EntityRenderer.kt +++ b/src/main/kotlin/gui/entity/EntityRenderer.kt @@ -30,10 +30,11 @@ object EntityRenderer { "Armadillo" to t(EntityType.ARMADILLO), "ArmorStand" to t(EntityType.ARMOR_STAND), "Axolotl" to t(EntityType.AXOLOTL), - "BREEZE" to t(EntityType.BREEZE), "Bat" to t(EntityType.BAT), "Bee" to t(EntityType.BEE), "Blaze" to t(EntityType.BLAZE), + "Bogged" to t(EntityType.BOGGED), + "Breeze" to t(EntityType.BREEZE), "CaveSpider" to t(EntityType.CAVE_SPIDER), "Chicken" to t(EntityType.CHICKEN), "Cod" to t(EntityType.COD), @@ -121,7 +122,8 @@ object EntityRenderer { for (modifierJson in modifiers) { val modifier = ErrorUtil.notNullOr( modifierJson["type"]?.asString?.let(entityModifiers::get), - "Could not create entity with id $entityId. Failed to apply modifier $modifierJson") { return null } + "Could not create entity with id $entityId. Failed to apply modifier $modifierJson" + ) { return null } entity = modifier.apply(entity, modifierJson) } return entity @@ -217,8 +219,8 @@ object EntityRenderer { val vector3f = Vector3f(0.0f, (entity.height / 2.0f + bottomOffset).toFloat(), 0.0f) InventoryScreen.drawEntity( context, - centerX, - centerY, + x1, y1, + x2, y2, size.toFloat(), vector3f, rotateToFaceTheFront, diff --git a/src/main/kotlin/gui/hud/MoulConfigHud.kt b/src/main/kotlin/gui/hud/MoulConfigHud.kt index e99b069..8259ebe 100644 --- a/src/main/kotlin/gui/hud/MoulConfigHud.kt +++ b/src/main/kotlin/gui/hud/MoulConfigHud.kt @@ -1,66 +1,68 @@ - package moe.nea.firmament.gui.hud -import io.github.notenoughupdates.moulconfig.gui.GuiComponentWrapper import io.github.notenoughupdates.moulconfig.gui.GuiContext import io.github.notenoughupdates.moulconfig.gui.component.TextComponent +import io.github.notenoughupdates.moulconfig.platform.MoulConfigScreenComponent import net.minecraft.resource.ResourceManager import net.minecraft.resource.SynchronousResourceReloader +import net.minecraft.text.Text import moe.nea.firmament.events.FinalizeResourceManagerEvent import moe.nea.firmament.events.HudRenderEvent import moe.nea.firmament.gui.config.HudMeta +import moe.nea.firmament.jarvis.JarvisIntegration import moe.nea.firmament.util.MC import moe.nea.firmament.util.MoulConfigUtils abstract class MoulConfigHud( - val name: String, - val hudMeta: HudMeta, + val name: String, + val hudMeta: HudMeta, ) { - companion object { - private val componentWrapper by lazy { - object : GuiComponentWrapper(GuiContext(TextComponent("§cERROR"))) { - init { - this.client = MC.instance - } - } - } - } + companion object { + private val componentWrapper by lazy { + object : MoulConfigScreenComponent(Text.empty(), GuiContext(TextComponent("§cERROR")), null) { + init { + this.client = MC.instance + } + } + } + } - private var fragment: GuiContext? = null + private var fragment: GuiContext? = null - fun forceInit() { - } + fun forceInit() { + } - open fun shouldRender(): Boolean { - return true - } + open fun shouldRender(): Boolean { + return true + } - init { - require(name.matches("^[a-z_/]+$".toRegex())) - HudRenderEvent.subscribe("MoulConfigHud:render") { - if (!shouldRender()) return@subscribe - val renderContext = componentWrapper.createContext(it.context) - if (fragment == null) - loadFragment() - it.context.matrices.push() - hudMeta.applyTransformations(it.context.matrices) - val renderContextTranslated = - renderContext.translated(hudMeta.absoluteX, hudMeta.absoluteY, hudMeta.width, hudMeta.height) - .scaled(hudMeta.scale) - fragment!!.root.render(renderContextTranslated) - it.context.matrices.pop() - } - FinalizeResourceManagerEvent.subscribe("MoulConfigHud:finalizeResourceManager") { - MC.resourceManager.registerReloader(object : SynchronousResourceReloader { - override fun reload(manager: ResourceManager?) { - fragment = null - } - }) - } - } + init { + require(name.matches("^[a-z_/]+$".toRegex())) + HudRenderEvent.subscribe("MoulConfigHud:render") { + if (!shouldRender()) return@subscribe + val renderContext = componentWrapper.createContext(it.context) + if (fragment == null) + loadFragment() + it.context.matrices.pushMatrix() + hudMeta.applyTransformations(it.context.matrices) + val pos = hudMeta.getEffectivePosition(JarvisIntegration.jarvis) + val renderContextTranslated = + renderContext.translated(pos.x(), pos.y(), hudMeta.effectiveWidth, hudMeta.effectiveHeight) + .scaled(hudMeta.scale) + fragment!!.root.render(renderContextTranslated) + it.context.matrices.popMatrix() + } + FinalizeResourceManagerEvent.subscribe("MoulConfigHud:finalizeResourceManager") { + MC.resourceManager.registerReloader(object : SynchronousResourceReloader { + override fun reload(manager: ResourceManager?) { + fragment = null + } + }) + } + } - fun loadFragment() { - fragment = MoulConfigUtils.loadGui(name, this) - } + fun loadFragment() { + fragment = MoulConfigUtils.loadGui(name, this) + } } diff --git a/src/main/kotlin/repo/ItemCache.kt b/src/main/kotlin/repo/ItemCache.kt index 14decd8..72549e9 100644 --- a/src/main/kotlin/repo/ItemCache.kt +++ b/src/main/kotlin/repo/ItemCache.kt @@ -47,6 +47,7 @@ import moe.nea.firmament.util.directLiteralStringContent import moe.nea.firmament.util.mc.FirmamentDataComponentTypes import moe.nea.firmament.util.mc.appendLore import moe.nea.firmament.util.mc.displayNameAccordingToNbt +import moe.nea.firmament.util.mc.loadItemFromNbt import moe.nea.firmament.util.mc.loreAccordingToNbt import moe.nea.firmament.util.mc.modifyLore import moe.nea.firmament.util.mc.setCustomName @@ -70,7 +71,7 @@ object ItemCache : IReloadable { @ExpensiveItemCacheApi private fun NbtCompound.transformFrom10809ToModern() = convert189ToModern(this@transformFrom10809ToModern) - val currentSaveVersion = SharedConstants.getGameVersion().saveVersion.id + val currentSaveVersion = SharedConstants.getGameVersion().dataVersion().id @ExpensiveItemCacheApi fun convert189ToModern(nbtComponent: NbtCompound): NbtCompound? = @@ -171,7 +172,7 @@ object ItemCache : IReloadable { ?: return brokenItemStack(this) } val itemInstance = - ItemStack.fromNbt(MC.defaultRegistries, modernItemTag).getOrNull() ?: return brokenItemStack(this) + loadItemFromNbt( modernItemTag) ?: return brokenItemStack(this) if (usedOldNbt) { val tag = oldItemTag.getCompound("tag") val extraAttributes = tag.flatMap { it.getCompound("ExtraAttributes") } diff --git a/src/main/kotlin/repo/MiningRepoData.kt b/src/main/kotlin/repo/MiningRepoData.kt index e96a241..055253f 100644 --- a/src/main/kotlin/repo/MiningRepoData.kt +++ b/src/main/kotlin/repo/MiningRepoData.kt @@ -23,6 +23,7 @@ import moe.nea.firmament.util.SkyBlockIsland import moe.nea.firmament.util.SkyblockId import moe.nea.firmament.util.mc.FirmamentDataComponentTypes import moe.nea.firmament.util.mc.displayNameAccordingToNbt +import moe.nea.firmament.util.mc.loadItemFromNbt import moe.nea.firmament.util.skyblockId class MiningRepoData : IReloadable { @@ -118,7 +119,7 @@ class MiningRepoData : IReloadable { putString("id", itemId) putShort("Damage", damage) }) ?: return null - val itemStack = ItemStack.fromNbt(MC.defaultRegistries, newCompound).getOrNull() ?: return null + val itemStack = loadItemFromNbt(newCompound) ?: return null val blockItem = itemStack.item as? BlockItem ?: return null return blockItem.block } diff --git a/src/main/kotlin/util/FragmentGuiScreen.kt b/src/main/kotlin/util/FragmentGuiScreen.kt index 5e13d51..de53ac0 100644 --- a/src/main/kotlin/util/FragmentGuiScreen.kt +++ b/src/main/kotlin/util/FragmentGuiScreen.kt @@ -19,13 +19,9 @@ abstract class FragmentGuiScreen( popup = MoulConfigFragment(context, position) { popup = null } } - override fun render(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { - super.render(context, mouseX, mouseY, delta) - context.matrices.push() - context.matrices.translate(0f, 0f, 1000f) - popup?.render(context, mouseX, mouseY, delta) - context.matrices.pop() - } + fun renderPopup(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { + popup?.render(context, mouseX, mouseY, delta) + } private inline fun ifPopup(ifYes: (MoulConfigFragment) -> Unit): Boolean { val p = popup ?: return false @@ -65,7 +61,7 @@ abstract class FragmentGuiScreen( return ifPopup { if (!Rectangle( it.position, - Dimension(it.context.root.width, it.context.root.height) + Dimension(it.guiContext.root.width, it.guiContext.root.height) ).contains(Point(mouseX, mouseY)) && dismissOnOutOfBounds ) { diff --git a/src/main/kotlin/util/HoveredItemStack.kt b/src/main/kotlin/util/HoveredItemStack.kt index 526820a..1b54562 100644 --- a/src/main/kotlin/util/HoveredItemStack.kt +++ b/src/main/kotlin/util/HoveredItemStack.kt @@ -6,22 +6,33 @@ import net.minecraft.item.ItemStack import moe.nea.firmament.mixins.accessor.AccessorHandledScreen import moe.nea.firmament.util.compatloader.CompatLoader -interface HoveredItemStackProvider { +interface HoveredItemStackProvider : Comparable<HoveredItemStackProvider> { fun provideHoveredItemStack(screen: HandledScreen<*>): ItemStack? + override fun compareTo(other: HoveredItemStackProvider): Int { + return compareValues(this.prio, other.prio) + } + + val prio: Int get() = 0 - companion object : CompatLoader<HoveredItemStackProvider>(HoveredItemStackProvider::class) + companion object : CompatLoader<HoveredItemStackProvider>(HoveredItemStackProvider::class) { + val sorted = HoveredItemStackProvider.allValidInstances.sorted() + } } @AutoService(HoveredItemStackProvider::class) class VanillaScreenProvider : HoveredItemStackProvider { + override fun provideHoveredItemStack(screen: HandledScreen<*>): ItemStack? { screen as AccessorHandledScreen val vanillaSlot = screen.focusedSlot_Firmament?.stack return vanillaSlot } + + override val prio: Int + get() = -1 } val HandledScreen<*>.focusedItemStack: ItemStack? get() = - HoveredItemStackProvider.allValidInstances + HoveredItemStackProvider.sorted .firstNotNullOfOrNull { it.provideHoveredItemStack(this)?.takeIf { !it.isEmpty } } diff --git a/src/main/kotlin/util/MC.kt b/src/main/kotlin/util/MC.kt index e85b119..7ab0cbb 100644 --- a/src/main/kotlin/util/MC.kt +++ b/src/main/kotlin/util/MC.kt @@ -1,7 +1,7 @@ package moe.nea.firmament.util import io.github.moulberry.repo.data.Coordinate -import io.github.notenoughupdates.moulconfig.gui.GuiComponentWrapper +import io.github.notenoughupdates.moulconfig.platform.MoulConfigScreenComponent import java.util.concurrent.ConcurrentLinkedQueue import kotlin.jvm.optionals.getOrNull import net.minecraft.client.MinecraftClient @@ -16,11 +16,13 @@ import net.minecraft.client.world.ClientWorld import net.minecraft.entity.Entity import net.minecraft.item.Item import net.minecraft.item.ItemStack +import net.minecraft.nbt.NbtOps import net.minecraft.network.packet.c2s.play.CommandExecutionC2SPacket import net.minecraft.registry.BuiltinRegistries import net.minecraft.registry.Registry import net.minecraft.registry.RegistryKey import net.minecraft.registry.RegistryKeys +import net.minecraft.registry.RegistryOps import net.minecraft.registry.RegistryWrapper import net.minecraft.resource.ReloadableResourceManagerImpl import net.minecraft.text.Text @@ -74,7 +76,7 @@ object MC { fun sendCommand(command: String) { // TODO: add a queue to this and sendServerChat ErrorUtil.softCheck("Server commands have an implied /", !command.startsWith("/")) - player?.networkHandler?.sendCommand(command) + player?.networkHandler?.sendChatCommand(command) } fun onMainThread(block: () -> Unit) { @@ -117,6 +119,7 @@ object MC { inline val window get() = instance.window inline val currentRegistries: RegistryWrapper.WrapperLookup? get() = world?.registryManager val defaultRegistries: RegistryWrapper.WrapperLookup by lazy { BuiltinRegistries.createWrapperLookup() } + val defaultRegistryNbtOps by lazy { RegistryOps.of(NbtOps.INSTANCE, defaultRegistries) } inline val currentOrDefaultRegistries get() = currentRegistries ?: defaultRegistries val defaultItems: RegistryWrapper.Impl<Item> by lazy { defaultRegistries.getOrThrow(RegistryKeys.ITEM) } var currentTick = 0 @@ -128,7 +131,7 @@ object MC { private set val currentMoulConfigContext - get() = (screen as? GuiComponentWrapper)?.context + get() = (screen as? MoulConfigScreenComponent)?.guiContext fun openUrl(uri: String) { Util.getOperatingSystem().open(uri) diff --git a/src/main/kotlin/util/MoulConfigFragment.kt b/src/main/kotlin/util/MoulConfigFragment.kt index 28ccfd0..7e7f5db 100644 --- a/src/main/kotlin/util/MoulConfigFragment.kt +++ b/src/main/kotlin/util/MoulConfigFragment.kt @@ -1,44 +1,43 @@ - - package moe.nea.firmament.util -import io.github.notenoughupdates.moulconfig.gui.GuiComponentWrapper import io.github.notenoughupdates.moulconfig.gui.GuiContext import io.github.notenoughupdates.moulconfig.gui.GuiImmediateContext +import io.github.notenoughupdates.moulconfig.platform.MoulConfigScreenComponent import me.shedaniel.math.Point import net.minecraft.client.gui.DrawContext +import net.minecraft.text.Text class MoulConfigFragment( - context: GuiContext, - val position: Point, - val dismiss: () -> Unit -) : GuiComponentWrapper(context) { - init { - this.init(MC.instance, MC.screen!!.width, MC.screen!!.height) - } - - override fun createContext(drawContext: DrawContext?): GuiImmediateContext { - val oldContext = super.createContext(drawContext) - return oldContext.translated( - position.x, - position.y, - context.root.width, - context.root.height, - ) - } - - - override fun render(drawContext: DrawContext?, i: Int, j: Int, f: Float) { - val ctx = createContext(drawContext) - val m = drawContext!!.matrices - m.push() - m.translate(position.x.toFloat(), position.y.toFloat(), 0F) - context.root.render(ctx) - m.pop() - ctx.renderContext.renderExtraLayers() - } - - override fun close() { - dismiss() - } + context: GuiContext, + val position: Point, + val dismiss: () -> Unit +) : MoulConfigScreenComponent(Text.empty(), context, null) { + init { + this.init(MC.instance, MC.screen!!.width, MC.screen!!.height) + } + + override fun createContext(drawContext: DrawContext?): GuiImmediateContext { + val oldContext = super.createContext(drawContext) + return oldContext.translated( + position.x, + position.y, + guiContext.root.width, + guiContext.root.height, + ) + } + + + override fun render(drawContext: DrawContext, i: Int, j: Int, f: Float) { + val ctx = createContext(drawContext) + val m = drawContext.matrices + m.pushMatrix() + m.translate(position.x.toFloat(), position.y.toFloat()) + guiContext.root.render(ctx) + m.popMatrix() + ctx.renderContext.renderExtraLayers() + } + + override fun close() { + dismiss() + } } diff --git a/src/main/kotlin/util/MoulConfigUtils.kt b/src/main/kotlin/util/MoulConfigUtils.kt index 51ff340..2f2fd5c 100644 --- a/src/main/kotlin/util/MoulConfigUtils.kt +++ b/src/main/kotlin/util/MoulConfigUtils.kt @@ -4,13 +4,14 @@ import io.github.notenoughupdates.moulconfig.common.IMinecraft import io.github.notenoughupdates.moulconfig.common.MyResourceLocation import io.github.notenoughupdates.moulconfig.gui.CloseEventListener import io.github.notenoughupdates.moulconfig.gui.GuiComponent -import io.github.notenoughupdates.moulconfig.gui.GuiComponentWrapper import io.github.notenoughupdates.moulconfig.gui.GuiContext import io.github.notenoughupdates.moulconfig.gui.GuiImmediateContext import io.github.notenoughupdates.moulconfig.gui.KeyboardEvent import io.github.notenoughupdates.moulconfig.gui.MouseEvent import io.github.notenoughupdates.moulconfig.observer.GetSetter -import io.github.notenoughupdates.moulconfig.platform.ModernRenderContext +import io.github.notenoughupdates.moulconfig.platform.MoulConfigPlatform +import io.github.notenoughupdates.moulconfig.platform.MoulConfigRenderContext +import io.github.notenoughupdates.moulconfig.platform.MoulConfigScreenComponent import io.github.notenoughupdates.moulconfig.xml.ChildCount import io.github.notenoughupdates.moulconfig.xml.XMLContext import io.github.notenoughupdates.moulconfig.xml.XMLGuiLoader @@ -26,6 +27,7 @@ import kotlin.time.Duration.Companion.seconds import net.minecraft.client.gui.DrawContext import net.minecraft.client.gui.screen.Screen import net.minecraft.client.util.InputUtil +import net.minecraft.text.Text import moe.nea.firmament.gui.BarComponent import moe.nea.firmament.gui.FirmButtonComponent import moe.nea.firmament.gui.FirmHoverComponent @@ -226,9 +228,9 @@ object MoulConfigUtils { } fun wrapScreen(guiContext: GuiContext, parent: Screen?, onClose: () -> Unit = {}): Screen { - return object : GuiComponentWrapper(guiContext) { + return object : MoulConfigScreenComponent(Text.empty(), guiContext, null) { override fun close() { - if (context.onBeforeClose() == CloseEventListener.CloseAction.NO_OBJECTIONS_TO_CLOSE) { + if (guiContext.onBeforeClose() == CloseEventListener.CloseAction.NO_OBJECTIONS_TO_CLOSE) { client!!.setScreen(parent) onClose() } @@ -264,7 +266,7 @@ object MoulConfigUtils { h: Int, keyboardEvent: KeyboardEvent ): Boolean { - val immContext = createInPlaceFullContext(null, IMinecraft.instance.mouseX, IMinecraft.instance.mouseY) + val immContext = createInPlaceFullContext(null, IMinecraft.INSTANCE.mouseX, IMinecraft.INSTANCE.mouseY) if (component.keyboardEvent(keyboardEvent, immContext.translated(x, y, w, h))) return true if (component.context.getFocusedElement() != null) { @@ -292,9 +294,12 @@ object MoulConfigUtils { } fun createInPlaceFullContext(drawContext: DrawContext?, mouseX: Int, mouseY: Int): GuiImmediateContext { - assert(drawContext?.isUntranslatedGuiDrawContext() != false) - val context = drawContext?.let(::ModernRenderContext) - ?: IMinecraft.instance.provideTopLevelRenderContext() + ErrorUtil.softCheck( + "created moulconfig context with pre-existing translations.", + drawContext?.isUntranslatedGuiDrawContext() != false + ) + val context = drawContext?.let(::MoulConfigRenderContext) + ?: IMinecraft.INSTANCE.provideTopLevelRenderContext() val immContext = GuiImmediateContext( context, 0, 0, 0, 0, @@ -316,10 +321,10 @@ object MoulConfigUtils { mouseY: Int ) { val immContext = createInPlaceFullContext(this, mouseX, mouseY) - matrices.push() - matrices.translate(x.toFloat(), y.toFloat(), 0F) + matrices.pushMatrix() + matrices.translate(x.toFloat(), y.toFloat()) component.render(immContext.translated(x, y, w, h)) - matrices.pop() + matrices.popMatrix() } diff --git a/src/main/kotlin/util/SkyblockId.kt b/src/main/kotlin/util/SkyblockId.kt index 051ca86..03b8bf4 100644 --- a/src/main/kotlin/util/SkyblockId.kt +++ b/src/main/kotlin/util/SkyblockId.kt @@ -146,9 +146,9 @@ val ItemStack.skyblockUUIDString: String? private val timestampFormat = //"10/11/21 3:39 PM" DateTimeFormatterBuilder().apply { - appendValue(ChronoField.MONTH_OF_YEAR, 2) + appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NOT_NEGATIVE) appendLiteral("/") - appendValue(ChronoField.DAY_OF_MONTH, 2) + appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NOT_NEGATIVE) appendLiteral("/") appendValueReduced(ChronoField.YEAR, 2, 2, 1950) appendLiteral(" ") diff --git a/src/main/kotlin/util/json/CodecSerializer.kt b/src/main/kotlin/util/json/CodecSerializer.kt new file mode 100644 index 0000000..9ea08ad --- /dev/null +++ b/src/main/kotlin/util/json/CodecSerializer.kt @@ -0,0 +1,26 @@ +package util.json + +import com.mojang.serialization.Codec +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.JsonElement +import moe.nea.firmament.util.json.KJsonOps + +abstract class CodecSerializer<T>(val codec: Codec<T>) : KSerializer<T> { + override val descriptor: SerialDescriptor + get() = JsonElement.serializer().descriptor + + override fun serialize(encoder: Encoder, value: T) { + encoder.encodeSerializableValue( + JsonElement.serializer(), + codec.encodeStart(KJsonOps.INSTANCE, value).orThrow + ) + } + + override fun deserialize(decoder: Decoder): T { + return codec.decode(KJsonOps.INSTANCE, decoder.decodeSerializableValue(JsonElement.serializer())) + .orThrow.first + } +} diff --git a/src/main/kotlin/util/mc/CustomRenderPassHelper.kt b/src/main/kotlin/util/mc/CustomRenderPassHelper.kt new file mode 100644 index 0000000..295f727 --- /dev/null +++ b/src/main/kotlin/util/mc/CustomRenderPassHelper.kt @@ -0,0 +1,160 @@ +package moe.nea.firmament.util.mc + +import com.mojang.blaze3d.buffers.GpuBuffer +import com.mojang.blaze3d.buffers.GpuBufferSlice +import com.mojang.blaze3d.buffers.Std140Builder +import com.mojang.blaze3d.pipeline.RenderPipeline +import com.mojang.blaze3d.systems.RenderPass +import com.mojang.blaze3d.systems.RenderSystem +import com.mojang.blaze3d.vertex.VertexFormat +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.OptionalDouble +import java.util.OptionalInt +import org.joml.Vector4f +import net.minecraft.client.gl.Framebuffer +import net.minecraft.client.render.BufferBuilder +import net.minecraft.client.render.BuiltBuffer +import net.minecraft.client.texture.AbstractTexture +import net.minecraft.client.util.BufferAllocator +import net.minecraft.util.Identifier +import net.minecraft.util.math.MathHelper +import moe.nea.firmament.util.ErrorUtil +import moe.nea.firmament.util.MC + + +class CustomRenderPassHelper( + val labelSupplier: () -> String, + val drawMode: VertexFormat.DrawMode, + val vertexFormat: VertexFormat, + val frameBuffer: Framebuffer, + val hasDepth: Boolean, +) : AutoCloseable { + private val scope = mutableListOf<AutoCloseable>() + private val preparations = mutableListOf<(RenderPass) -> Unit>() + val device = RenderSystem.getDevice() + private var hasPipelineAction = false + private var hasSetDefaultUniforms = false + val commandEncoder = device.createCommandEncoder() + fun setPipeline(pipeline: RenderPipeline) { + ErrorUtil.softCheck("Already has a pipeline", !hasPipelineAction) + hasPipelineAction = true + queueAction { + it.setPipeline(pipeline) + } + } + + fun bindSampler(name: String, texture: Identifier) { + bindSampler(name, MC.textureManager.getTexture(texture)) + } + + fun bindSampler(name: String, texture: AbstractTexture) { + queueAction { it.bindSampler(name, texture.glTextureView) } + } + + + fun dontSetDefaultUniforms() { + hasSetDefaultUniforms = true + } + + fun setAllDefaultUniforms() { + hasSetDefaultUniforms = true + queueAction { + RenderSystem.bindDefaultUniforms(it) + } + setUniform( + "DynamicTransforms", RenderSystem.getDynamicUniforms() + .write( + RenderSystem.getModelViewMatrix(), + Vector4f(1.0F, 1.0F, 1.0F, 1.0F), + RenderSystem.getModelOffset(), + RenderSystem.getTextureMatrix(), + RenderSystem.getShaderLineWidth() + ) + ) + } + + fun setUniform(name: String, slice: GpuBufferSlice) = queueAction { it.setUniform(name, slice) } + fun setUniform(name: String, slice: GpuBuffer) = queueAction { it.setUniform(name, slice) } + + fun setUniform(name: String, size: Int, labelSupplier: () -> String = { name }, init: (Std140Builder) -> Unit) { + val buffer = createUniformBuffer(labelSupplier, allocateByteBuf(size, init)) + setUniform(name, buffer) + } + + var vertices: BuiltBuffer? = null + + fun uploadVertices(size: Int, init: (BufferBuilder) -> Unit) { + uploadVertices( + BufferBuilder(queueClose(BufferAllocator(size)), drawMode, vertexFormat) + .also(init) + .end() + ) + } + + fun uploadVertices(buffer: BuiltBuffer) { + queueClose(buffer) + ErrorUtil.softCheck("Vertices have already been uploaded", vertices == null) + vertices = buffer + val vertexBuffer = vertexFormat.uploadImmediateVertexBuffer(buffer.buffer) + val indexBufferConstructor = RenderSystem.getSequentialBuffer(drawMode) + val indexBuffer = indexBufferConstructor.getIndexBuffer(buffer.drawParameters.indexCount) + queueAction { + it.setIndexBuffer(indexBuffer, indexBufferConstructor.indexType) + it.setVertexBuffer(0, vertexBuffer) + } + } + + fun createUniformBuffer(labelSupplier: () -> String, buffer: ByteBuffer): GpuBuffer { + return queueClose( + device.createBuffer( + labelSupplier::invoke, + GpuBuffer.USAGE_UNIFORM or GpuBuffer.USAGE_MAP_READ, + buffer + ) + ) + } + + fun allocateByteBuf(size: Int, init: (Std140Builder) -> Unit): ByteBuffer { + return Std140Builder.intoBuffer( // TODO: i really dont know about this 16 align? but it seems to be generally correct. + ByteBuffer + .allocateDirect(MathHelper.roundUpToMultiple(size, 16)) + .order(ByteOrder.nativeOrder()) + ).also(init).get() + } + + fun queueAction(action: (RenderPass) -> Unit) { + preparations.add(action) + } + + fun <T : AutoCloseable> queueClose(t: T): T = t.also { scope.add(it) } + override fun close() { + scope.reversed().forEach { it.close() } + } + + object DrawToken + + fun draw(): DrawToken { + val vertexData = (ErrorUtil.notNullOr(vertices, "No vertex data uploaded") { return DrawToken }) + ErrorUtil.softCheck("Missing default uniforms", hasSetDefaultUniforms) + ErrorUtil.softCheck("Missing a pipeline", hasPipelineAction) + val renderPass = queueClose( + commandEncoder.createRenderPass( + labelSupplier::invoke, + RenderSystem.outputColorTextureOverride ?: frameBuffer.getColorAttachmentView(), + OptionalInt.empty(), + (RenderSystem.outputDepthTextureOverride + ?: frameBuffer.getDepthAttachmentView()).takeIf { frameBuffer.useDepthAttachment && hasDepth }, + OptionalDouble.empty() + ) + ) + preparations.forEach { it(renderPass) } + renderPass.drawIndexed( + 0, + 0, + vertexData.drawParameters.indexCount, + 1 + ) + return DrawToken + } +} diff --git a/src/main/kotlin/util/mc/ItemUtil.kt b/src/main/kotlin/util/mc/ItemUtil.kt index 13519cf..3cabb8e 100644 --- a/src/main/kotlin/util/mc/ItemUtil.kt +++ b/src/main/kotlin/util/mc/ItemUtil.kt @@ -1,20 +1,30 @@ package moe.nea.firmament.util.mc +import kotlin.jvm.optionals.getOrNull import net.minecraft.item.ItemStack +import net.minecraft.nbt.NbtCompound +import net.minecraft.nbt.NbtOps +import net.minecraft.registry.RegistryOps +import net.minecraft.registry.RegistryWrapper import net.minecraft.text.Text +import moe.nea.firmament.util.MC fun ItemStack.appendLore(args: List<Text>) { - if (args.isEmpty()) return - modifyLore { - val loreList = loreAccordingToNbt.toMutableList() - for (arg in args) { - loreList.add(arg) - } - loreList - } + if (args.isEmpty()) return + modifyLore { + val loreList = loreAccordingToNbt.toMutableList() + for (arg in args) { + loreList.add(arg) + } + loreList + } } fun ItemStack.modifyLore(update: (List<Text>) -> List<Text>) { - val loreList = loreAccordingToNbt - loreAccordingToNbt = update(loreList) + val loreList = loreAccordingToNbt + loreAccordingToNbt = update(loreList) +} + +fun loadItemFromNbt(nbt: NbtCompound, registries: RegistryWrapper.WrapperLookup = MC.defaultRegistries): ItemStack? { + return ItemStack.CODEC.decode(RegistryOps.of(NbtOps.INSTANCE, registries), nbt).result().getOrNull()?.first } diff --git a/src/main/kotlin/util/render/CustomRenderLayers.kt b/src/main/kotlin/util/render/CustomRenderLayers.kt index 2da1de7..d88a1e4 100644 --- a/src/main/kotlin/util/render/CustomRenderLayers.kt +++ b/src/main/kotlin/util/render/CustomRenderLayers.kt @@ -11,7 +11,6 @@ import net.minecraft.client.render.RenderLayer import net.minecraft.client.render.RenderPhase import net.minecraft.client.render.VertexFormats import net.minecraft.util.Identifier -import net.minecraft.util.TriState import net.minecraft.util.Util import moe.nea.firmament.Firmament @@ -31,7 +30,7 @@ object CustomRenderPipelines { .withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST) .build() val COLORED_OMNIPRESENT_QUADS = - RenderPipeline.builder(RenderPipelines.MATRICES_COLOR_SNIPPET)// TODO: split this up to support better transparent ordering. + RenderPipeline.builder(RenderPipelines.TRANSFORMS_AND_PROJECTION_SNIPPET)// TODO: split this up to support better transparent ordering. .withLocation(Firmament.identifier("colored_omnipresent_quads")) .withVertexShader("core/position_color") .withFragmentShader("core/position_color") @@ -46,9 +45,9 @@ object CustomRenderPipelines { RenderPipeline.builder(RenderPipelines.POSITION_TEX_COLOR_SNIPPET) .withVertexFormat(VertexFormats.POSITION_TEXTURE_COLOR, DrawMode.TRIANGLES) .withLocation(Firmament.identifier("gui_textured_overlay_tris_circle")) - .withUniform("InnerCutoutRadius", UniformType.FLOAT) + .withUniform("CutoutRadius", UniformType.UNIFORM_BUFFER) .withFragmentShader(Firmament.identifier("circle_discard_color")) - .withBlend(BlendFunction.TRANSLUCENT) +// .withBlend(BlendFunction.TRANSLUCENT) .build() val PARALLAX_CAPE_SHADER = RenderPipeline.builder(RenderPipelines.ENTITY_SNIPPET) @@ -57,12 +56,12 @@ object CustomRenderPipelines { .withSampler("Sampler0") .withSampler("Sampler1") .withSampler("Sampler3") - .withUniform("Animation", UniformType.FLOAT) + .withUniform("Animation", UniformType.UNIFORM_BUFFER) .build() } object CustomRenderLayers { - inline fun memoizeTextured(crossinline func: (Identifier) -> RenderLayer) = memoize(func) + inline fun memoizeTextured(crossinline func: (Identifier) -> RenderLayer.MultiPhase) = memoize(func) inline fun <T, R> memoize(crossinline func: (T) -> R): Function<T, R> { return Util.memoize { it: T -> func(it) } } @@ -73,7 +72,7 @@ object CustomRenderLayers { RenderLayer.DEFAULT_BUFFER_SIZE, CustomRenderPipelines.GUI_TEXTURED_NO_DEPTH_TRIS, RenderLayer.MultiPhaseParameters.builder().texture( - RenderPhase.Texture(texture, TriState.DEFAULT, false) + RenderPhase.Texture(texture, false) ) .build(false) ) diff --git a/src/main/kotlin/util/render/DrawContextExt.kt b/src/main/kotlin/util/render/DrawContextExt.kt index a833c86..e63bf5f 100644 --- a/src/main/kotlin/util/render/DrawContextExt.kt +++ b/src/main/kotlin/util/render/DrawContextExt.kt @@ -2,26 +2,31 @@ package moe.nea.firmament.util.render import com.mojang.blaze3d.systems.RenderSystem import me.shedaniel.math.Color -import org.joml.Matrix4f +import org.joml.Vector2f +import org.joml.Vector3f import util.render.CustomRenderLayers +import kotlin.math.abs +import net.minecraft.client.gl.RenderPipelines import net.minecraft.client.gui.DrawContext -import net.minecraft.client.render.RenderLayer +import net.minecraft.client.gui.ScreenRect +import net.minecraft.client.render.VertexConsumerProvider +import net.minecraft.client.util.math.MatrixStack import net.minecraft.util.Identifier import moe.nea.firmament.util.MC fun DrawContext.isUntranslatedGuiDrawContext(): Boolean { - return (matrices.peek().positionMatrix.properties() and Matrix4f.PROPERTY_IDENTITY.toInt()) != 0 + return matrices.m00 == 1F && matrices.m11 == 1f && matrices.m01 == 0F && matrices.m10 == 0F && matrices.m20 == 0F && matrices.m21 == 0F } @Deprecated("Use the other drawGuiTexture") fun DrawContext.drawGuiTexture( x: Int, y: Int, z: Int, width: Int, height: Int, sprite: Identifier -) = this.drawGuiTexture(RenderLayer::getGuiTextured, sprite, x, y, width, height) +) = this.drawGuiTexture(RenderPipelines.GUI_TEXTURED, sprite, x, y, width, height) fun DrawContext.drawGuiTexture( sprite: Identifier, x: Int, y: Int, width: Int, height: Int -) = this.drawGuiTexture(RenderLayer::getGuiTextured, sprite, x, y, width, height) +) = this.drawGuiTexture(RenderPipelines.GUI_TEXTURED, sprite, x, y, width, height) fun DrawContext.drawTexture( sprite: Identifier, @@ -34,35 +39,130 @@ fun DrawContext.drawTexture( textureWidth: Int, textureHeight: Int ) { - this.drawTexture(RenderLayer::getGuiTextured, - sprite, - x, - y, - u, - v, - width, - height, - width, - height, - textureWidth, - textureHeight) + this.drawTexture( + RenderPipelines.GUI_TEXTURED, + sprite, + x, + y, + u, + v, + width, + height, + width, + height, + textureWidth, + textureHeight + ) } -fun DrawContext.drawLine(fromX: Int, fromY: Int, toX: Int, toY: Int, color: Color) { - // TODO: push scissors - // TODO: use matrix translations and a different render layer +data class LineRenderState( + override val x1: Int, + override val x2: Int, + override val y1: Int, + override val y2: Int, + override val scale: Float, + override val bounds: ScreenRect, + val lineWidth: Float, + val w: Int, + val h: Int, + val color: Int, + val direction: LineDirection, +) : MultiSpecialGuiRenderState() { + enum class LineDirection { + TOP_LEFT_TO_BOTTOM_RIGHT, + BOTTOM_LEFT_TO_TOP_RIGHT, + } + + override fun createRenderer(vertexConsumers: VertexConsumerProvider.Immediate): MultiSpecialGuiRenderer<out MultiSpecialGuiRenderState> { + return LineRenderer(vertexConsumers) + } + + override val scissorArea = null +} + +class LineRenderer(vertexConsumers: VertexConsumerProvider.Immediate) : + MultiSpecialGuiRenderer<LineRenderState>(vertexConsumers) { + override fun getElementClass(): Class<LineRenderState> { + return LineRenderState::class.java + } + + override fun getYOffset(height: Int, windowScaleFactor: Int): Float { + return height / 2F + } + + override fun render( + state: LineRenderState, + matrices: MatrixStack + ) { + val gr = MC.instance.gameRenderer + val client = MC.instance + gr.globalSettings + .set( + state.bounds.width, + state.bounds.height, + client.options.glintStrength.getValue(), + client.world?.time ?: 0L, + client.renderTickCounter, + client.options.menuBackgroundBlurrinessValue + ) + + RenderSystem.lineWidth(state.lineWidth) + val buf = vertexConsumers.getBuffer(CustomRenderLayers.LINES) + val matrix = matrices.peek() + val wh = state.w / 2F + val hh = state.h / 2F + val lowX = -wh + val lowY = if (state.direction == LineRenderState.LineDirection.BOTTOM_LEFT_TO_TOP_RIGHT) hh else -hh + val highX = wh + val highY = -lowY + val norm = Vector3f(highX - lowX, highY - lowY, 0F).normalize() + buf.vertex(matrix, lowX, lowY, 0F).color(state.color) + .normal(matrix, norm) + buf.vertex(matrix, highX, highY, 0F).color(state.color) + .normal(matrix, norm) + vertexConsumers.draw() + gr.globalSettings + .set( + client.window.framebufferWidth, + client.window.framebufferHeight, + client.options.glintStrength.getValue(), + client.world?.getTime() ?: 0L, + client.renderTickCounter, + client.options.menuBackgroundBlurrinessValue + ) + + } + + override fun getName(): String? { + return "Firmament Line Renderer" + } +} + + +fun DrawContext.drawLine(fromX: Int, fromY: Int, toX: Int, toY: Int, color: Color, lineWidth: Float = 1F) { if (toY < fromY) { drawLine(toX, toY, fromX, fromY, color) return } - RenderSystem.lineWidth(MC.window.scaleFactor.toFloat()) - draw { vertexConsumers -> - val buf = vertexConsumers.getBuffer(CustomRenderLayers.LINES) - val matrix = this.matrices.peek() - buf.vertex(matrix, fromX.toFloat(), fromY.toFloat(), 0F).color(color.color) - .normal(toX - fromX.toFloat(), toY - fromY.toFloat(), 0F) - buf.vertex(matrix, toX.toFloat(), toY.toFloat(), 0F).color(color.color) - .normal(toX - fromX.toFloat(), toY - fromY.toFloat(), 0F) - } + val originalRect = ScreenRect( + minOf(fromX, toX), minOf(toY, fromY), + abs(toX - fromX), abs(toY - fromY) + ).transform(matrices) + val expansionFactor = 3 + val rect = ScreenRect( + originalRect.left - expansionFactor, + originalRect.top - expansionFactor, + originalRect.width + expansionFactor * 2, + originalRect.height + expansionFactor * 2 + ) + // TODO: expand the bounds so that the thickness of the line can be used + // TODO: fix this up to work with scissorarea + state.addSpecialElement( + LineRenderState( + rect.left, rect.right, rect.top, rect.bottom, 1F, rect, lineWidth, + originalRect.width, originalRect.height, color.color, + if (fromX < toX) LineRenderState.LineDirection.TOP_LEFT_TO_BOTTOM_RIGHT else LineRenderState.LineDirection.BOTTOM_LEFT_TO_TOP_RIGHT + ) + ) } diff --git a/src/main/kotlin/util/render/DumpTexture.kt b/src/main/kotlin/util/render/DumpTexture.kt new file mode 100644 index 0000000..a7b4e78 --- /dev/null +++ b/src/main/kotlin/util/render/DumpTexture.kt @@ -0,0 +1,34 @@ +package moe.nea.firmament.util.render + +import com.mojang.blaze3d.buffers.GpuBuffer +import com.mojang.blaze3d.systems.RenderSystem +import com.mojang.blaze3d.textures.GpuTexture +import java.io.File +import net.minecraft.client.texture.NativeImage + +fun dumpTexture(gpuTexture: GpuTexture, name: String) { + val w = gpuTexture.getWidth(0) + val h = gpuTexture.getHeight(0) + val buffer = RenderSystem.getDevice() + .createBuffer( + { "Dump Buffer" }, + GpuBuffer.USAGE_COPY_DST or GpuBuffer.USAGE_MAP_READ, + w * h * gpuTexture.getFormat().pixelSize() + ) + val commandEncoder = RenderSystem.getDevice().createCommandEncoder() + commandEncoder.copyTextureToBuffer( + gpuTexture, buffer, 0, { + val nativeImage = NativeImage(w, h, false) + commandEncoder.mapBuffer(buffer, true, false).use { mappedView -> + for (i in 0..<w) { + for (j in 0..<h) { + val color = mappedView.data().getInt((j + i * w) * gpuTexture.format.pixelSize()) + nativeImage.setColor(j, h - i - 1, color) + } + } + } + buffer.close() + nativeImage.writeTo(File("$name.png")) + }, 0 + ) +} diff --git a/src/main/kotlin/util/render/FacingThePlayerContext.kt b/src/main/kotlin/util/render/FacingThePlayerContext.kt index 670beb6..76270c5 100644 --- a/src/main/kotlin/util/render/FacingThePlayerContext.kt +++ b/src/main/kotlin/util/render/FacingThePlayerContext.kt @@ -1,11 +1,13 @@ package moe.nea.firmament.util.render -import io.github.notenoughupdates.moulconfig.platform.next import org.joml.Matrix4f +import util.render.CustomRenderLayers import net.minecraft.client.font.TextRenderer import net.minecraft.client.render.LightmapTextureManager import net.minecraft.client.render.RenderLayer +import net.minecraft.client.render.RenderLayers +import net.minecraft.client.render.TexturedRenderLayers import net.minecraft.client.render.VertexConsumer import net.minecraft.text.Text import net.minecraft.util.Identifier @@ -38,14 +40,14 @@ class FacingThePlayerContext(val worldContext: RenderInWorldContext) { worldContext.vertexConsumers.getBuffer(RenderLayer.getTextBackgroundSeeThrough()) val matrix4f = worldContext.matrixStack.peek().positionMatrix vertexConsumer.vertex(matrix4f, -1.0f, -1.0f, 0.0f).color(background) - .light(LightmapTextureManager.MAX_BLOCK_LIGHT_COORDINATE).next() + .light(LightmapTextureManager.MAX_BLOCK_LIGHT_COORDINATE) vertexConsumer.vertex(matrix4f, -1.0f, MC.font.fontHeight.toFloat(), 0.0f).color(background) - .light(LightmapTextureManager.MAX_BLOCK_LIGHT_COORDINATE).next() + .light(LightmapTextureManager.MAX_BLOCK_LIGHT_COORDINATE) vertexConsumer.vertex(matrix4f, width.toFloat(), MC.font.fontHeight.toFloat(), 0.0f) .color(background) - .light(LightmapTextureManager.MAX_BLOCK_LIGHT_COORDINATE).next() + .light(LightmapTextureManager.MAX_BLOCK_LIGHT_COORDINATE) vertexConsumer.vertex(matrix4f, width.toFloat(), -1.0f, 0.0f).color(background) - .light(LightmapTextureManager.MAX_BLOCK_LIGHT_COORDINATE).next() + .light(LightmapTextureManager.MAX_BLOCK_LIGHT_COORDINATE) worldContext.matrixStack.translate(0F, 0F, 0.01F) MC.font.draw( @@ -70,22 +72,22 @@ class FacingThePlayerContext(val worldContext: RenderInWorldContext) { u1: Float, v1: Float, u2: Float, v2: Float, ) { - val buf = worldContext.vertexConsumers.getBuffer(RenderLayer.getGuiTexturedOverlay(texture)) + val buf = worldContext.vertexConsumers.getBuffer(CustomRenderLayers.GUI_TEXTURED_NO_DEPTH_TRIS.apply(texture)) // TODO: this is strictly an incorrect render layer val hw = width / 2F val hh = height / 2F val matrix4f: Matrix4f = worldContext.matrixStack.peek().positionMatrix buf.vertex(matrix4f, -hw, -hh, 0F) .color(-1) - .texture(u1, v1).next() + .texture(u1, v1) buf.vertex(matrix4f, -hw, +hh, 0F) .color(-1) - .texture(u1, v2).next() + .texture(u1, v2) buf.vertex(matrix4f, +hw, +hh, 0F) .color(-1) - .texture(u2, v2).next() + .texture(u2, v2) buf.vertex(matrix4f, +hw, -hh, 0F) .color(-1) - .texture(u2, v1).next() + .texture(u2, v1) worldContext.vertexConsumers.draw() } diff --git a/src/main/kotlin/util/render/MultiSpecialGuiRenderState.kt b/src/main/kotlin/util/render/MultiSpecialGuiRenderState.kt new file mode 100644 index 0000000..ce56df3 --- /dev/null +++ b/src/main/kotlin/util/render/MultiSpecialGuiRenderState.kt @@ -0,0 +1,48 @@ +package moe.nea.firmament.util.render + +import org.joml.Matrix3x2f +import net.minecraft.client.gui.ScreenRect +import net.minecraft.client.gui.render.SpecialGuiElementRenderer +import net.minecraft.client.gui.render.state.GuiRenderState +import net.minecraft.client.gui.render.state.special.SpecialGuiElementRenderState +import net.minecraft.client.render.VertexConsumerProvider + +abstract class MultiSpecialGuiRenderState : SpecialGuiElementRenderState { + // I wish i had manifolds @Self type here... Maybe i should switch to java after all :( + abstract fun createRenderer(vertexConsumers: VertexConsumerProvider.Immediate): MultiSpecialGuiRenderer<out MultiSpecialGuiRenderState> + abstract val x1: Int + abstract val x2: Int + abstract val y1: Int + abstract val y2: Int + abstract val scale: Float + abstract val bounds: ScreenRect? + abstract val scissorArea: ScreenRect? + override fun x1(): Int = x1 + + override fun x2(): Int = x2 + + override fun y1(): Int = y1 + + override fun y2(): Int = y2 + + override fun scale(): Float = scale + + override fun scissorArea(): ScreenRect? = scissorArea + + override fun bounds(): ScreenRect? = bounds + +} + +abstract class MultiSpecialGuiRenderer<T : MultiSpecialGuiRenderState>( + vertexConsumers: VertexConsumerProvider.Immediate +) : SpecialGuiElementRenderer<T>(vertexConsumers) { + var wasUsedThisFrame = false + fun consumeRender(): Boolean { + return wasUsedThisFrame.also { wasUsedThisFrame = false } + } + + override fun renderElement(element: T, state: GuiRenderState) { + wasUsedThisFrame = true + super.renderElement(element, state) + } +} diff --git a/src/main/kotlin/util/render/RenderCircleProgress.kt b/src/main/kotlin/util/render/RenderCircleProgress.kt index 81dde6f..301eec4 100644 --- a/src/main/kotlin/util/render/RenderCircleProgress.kt +++ b/src/main/kotlin/util/render/RenderCircleProgress.kt @@ -1,25 +1,126 @@ package moe.nea.firmament.util.render -import com.mojang.blaze3d.systems.RenderSystem import com.mojang.blaze3d.vertex.VertexFormat -import io.github.notenoughupdates.moulconfig.platform.next -import java.util.OptionalInt -import org.joml.Matrix4f +import org.joml.Matrix3x2f import util.render.CustomRenderLayers import net.minecraft.client.gui.DrawContext +import net.minecraft.client.gui.ScreenRect import net.minecraft.client.render.BufferBuilder import net.minecraft.client.render.RenderLayer +import net.minecraft.client.render.VertexConsumerProvider import net.minecraft.client.util.BufferAllocator +import net.minecraft.client.util.math.MatrixStack import net.minecraft.util.Identifier import moe.nea.firmament.util.MC import moe.nea.firmament.util.collections.nonNegligibleSubSectionsAlignedWith import moe.nea.firmament.util.math.Projections +import moe.nea.firmament.util.mc.CustomRenderPassHelper object RenderCircleProgress { + + data class State( + override val x1: Int, + override val x2: Int, + override val y1: Int, + override val y2: Int, + val layer: RenderLayer.MultiPhase, + val u1: Float, + val u2: Float, + val v1: Float, + val v2: Float, + val angleRadians: ClosedFloatingPointRange<Float>, + val color: Int, + val innerCutoutRadius: Float, + override val scale: Float, + override val bounds: ScreenRect?, + override val scissorArea: ScreenRect?, + ) : MultiSpecialGuiRenderState() { + override fun createRenderer(vertexConsumers: VertexConsumerProvider.Immediate): MultiSpecialGuiRenderer<out MultiSpecialGuiRenderState> { + return Renderer(vertexConsumers) + } + } + + class Renderer(vertexConsumers: VertexConsumerProvider.Immediate) : + MultiSpecialGuiRenderer<State>(vertexConsumers) { + override fun render( + state: State, + matrices: MatrixStack + ) { + matrices.push() + matrices.translate(0F, -1F, 0F) + val sections = state.angleRadians.nonNegligibleSubSectionsAlignedWith((τ / 8f).toFloat()) + .zipWithNext().toList() + val u1 = state.u1 + val u2 = state.u2 + val v1 = state.v1 + val v2 = state.v2 + val color = state.color + val matrix = matrices.peek().positionMatrix + BufferAllocator(state.layer.vertexFormat.vertexSize * sections.size * 3).use { allocator -> + + val bufferBuilder = BufferBuilder(allocator, VertexFormat.DrawMode.TRIANGLES, state.layer.vertexFormat) + + for ((sectionStart, sectionEnd) in sections) { + val firstPoint = Projections.Two.projectAngleOntoUnitBox(sectionStart.toDouble()) + val secondPoint = Projections.Two.projectAngleOntoUnitBox(sectionEnd.toDouble()) + fun ilerp(f: Float): Float = + ilerp(-1f, 1f, f) + + bufferBuilder + .vertex(matrix, secondPoint.x, secondPoint.y, 0F) + .texture(lerp(u1, u2, ilerp(secondPoint.x)), lerp(v1, v2, ilerp(secondPoint.y))) + .color(color) + + bufferBuilder + .vertex(matrix, firstPoint.x, firstPoint.y, 0F) + .texture(lerp(u1, u2, ilerp(firstPoint.x)), lerp(v1, v2, ilerp(firstPoint.y))) + .color(color) + + bufferBuilder + .vertex(matrix, 0F, 0F, 0F) + .texture(lerp(u1, u2, ilerp(0F)), lerp(v1, v2, ilerp(0F))) + .color(color) + + } + + bufferBuilder.end().use { buffer -> + if (state.innerCutoutRadius <= 0) { + state.layer.draw(buffer) + return + } + CustomRenderPassHelper( + { "RenderCircleProgress" }, + VertexFormat.DrawMode.TRIANGLES, + state.layer.vertexFormat, + MC.instance.framebuffer, + false, + ).use { renderPass -> + renderPass.uploadVertices(buffer) + renderPass.setAllDefaultUniforms() + renderPass.setPipeline(state.layer.pipeline) + renderPass.setUniform("CutoutRadius", 4) { + it.putFloat(state.innerCutoutRadius) + } + renderPass.draw() + } + } + } + matrices.pop() + } + + override fun getElementClass(): Class<State> { + return State::class.java + } + + override fun getName(): String { + return "Firmament Circle" + } + } + fun renderCircularSlice( drawContext: DrawContext, - layer: RenderLayer, + layer: RenderLayer.MultiPhase, u1: Float, u2: Float, v1: Float, @@ -28,58 +129,21 @@ object RenderCircleProgress { color: Int = -1, innerCutoutRadius: Float = 0F ) { - drawContext.draw() - val sections = angleRadians.nonNegligibleSubSectionsAlignedWith((τ / 8f).toFloat()) - .zipWithNext().toList() - BufferAllocator(layer.vertexFormat.vertexSize * sections.size * 3).use { allocator -> - - val bufferBuilder = BufferBuilder(allocator, VertexFormat.DrawMode.TRIANGLES, layer.vertexFormat) - val matrix: Matrix4f = drawContext.matrices.peek().positionMatrix - - for ((sectionStart, sectionEnd) in sections) { - val firstPoint = Projections.Two.projectAngleOntoUnitBox(sectionStart.toDouble()) - val secondPoint = Projections.Two.projectAngleOntoUnitBox(sectionEnd.toDouble()) - fun ilerp(f: Float): Float = - ilerp(-1f, 1f, f) - - bufferBuilder - .vertex(matrix, secondPoint.x, secondPoint.y, 0F) - .texture(lerp(u1, u2, ilerp(secondPoint.x)), lerp(v1, v2, ilerp(secondPoint.y))) - .color(color) - .next() - bufferBuilder - .vertex(matrix, firstPoint.x, firstPoint.y, 0F) - .texture(lerp(u1, u2, ilerp(firstPoint.x)), lerp(v1, v2, ilerp(firstPoint.y))) - .color(color) - .next() - bufferBuilder - .vertex(matrix, 0F, 0F, 0F) - .texture(lerp(u1, u2, ilerp(0F)), lerp(v1, v2, ilerp(0F))) - .color(color) - .next() - } - - bufferBuilder.end().use { buffer -> - // TODO: write a better utility to pass uniforms :sob: ill even take a mixin at this point - if (innerCutoutRadius <= 0) { - layer.draw(buffer) - return - } - val vertexBuffer = layer.vertexFormat.uploadImmediateVertexBuffer(buffer.buffer) - val indexBufferConstructor = RenderSystem.getSequentialBuffer(VertexFormat.DrawMode.TRIANGLES) - val indexBuffer = indexBufferConstructor.getIndexBuffer(buffer.drawParameters.indexCount) - RenderSystem.getDevice().createCommandEncoder().createRenderPass( - MC.instance.framebuffer.colorAttachment, - OptionalInt.empty(), - ).use { renderPass -> - renderPass.setPipeline(layer.pipeline) - renderPass.setUniform("InnerCutoutRadius", innerCutoutRadius) - renderPass.setIndexBuffer(indexBuffer, indexBufferConstructor.indexType) - renderPass.setVertexBuffer(0, vertexBuffer) - renderPass.drawIndexed(0, buffer.drawParameters.indexCount) - } - } - } + val screenRect = ScreenRect(-1, -1, 2, 2).transform(drawContext.matrices) + drawContext.state.addSpecialElement( + State( + screenRect.left, screenRect.right, + screenRect.top, screenRect.bottom, + layer, + u1, u2, v1, v2, + angleRadians, + color, + innerCutoutRadius, + screenRect.width / 2F, + screenRect, + null + ) + ) } fun renderCircle( diff --git a/src/main/kotlin/util/render/RenderInWorldContext.kt b/src/main/kotlin/util/render/RenderInWorldContext.kt index c30ee19..0898190 100644 --- a/src/main/kotlin/util/render/RenderInWorldContext.kt +++ b/src/main/kotlin/util/render/RenderInWorldContext.kt @@ -1,7 +1,6 @@ package moe.nea.firmament.util.render import com.mojang.blaze3d.systems.RenderSystem -import io.github.notenoughupdates.moulconfig.platform.next import java.lang.Math.pow import org.joml.Matrix4f import org.joml.Vector3f @@ -28,18 +27,6 @@ class RenderInWorldContext private constructor( private val tickCounter: RenderTickCounter, val vertexConsumers: VertexConsumerProvider.Immediate, ) { - - - @Deprecated("stateful color management is no longer a thing") - fun color(color: me.shedaniel.math.Color) { - color(color.red / 255F, color.green / 255f, color.blue / 255f, color.alpha / 255f) - } - - @Deprecated("stateful color management is no longer a thing") - fun color(red: Float, green: Float, blue: Float, alpha: Float) { - RenderSystem.setShaderColor(red, green, blue, alpha) - } - fun block(blockPos: BlockPos, color: Int) { matrixStack.push() matrixStack.translate(blockPos.x.toFloat(), blockPos.y.toFloat(), blockPos.z.toFloat()) @@ -156,6 +143,7 @@ class RenderInWorldContext private constructor( fun wireframeCube(blockPos: BlockPos, lineWidth: Float = 10F) { val buf = vertexConsumers.getBuffer(RenderLayer.LINES) matrixStack.push() + // TODO: add color arg to this // TODO: this does not render through blocks (or water layers) anymore RenderSystem.lineWidth(lineWidth / pow(camera.pos.squaredDistanceTo(blockPos.toCenterPos()), 0.25).toFloat()) matrixStack.translate(blockPos.x.toFloat(), blockPos.y.toFloat(), blockPos.z.toFloat()) @@ -164,16 +152,16 @@ class RenderInWorldContext private constructor( vertexConsumers.draw() } - fun line(vararg points: Vec3d, lineWidth: Float = 10F) { - line(points.toList(), lineWidth) + fun line(vararg points: Vec3d, color: Int, lineWidth: Float = 10F) { + line(points.toList(), color, lineWidth) } - fun tracer(toWhere: Vec3d, lineWidth: Float = 3f) { + fun tracer(toWhere: Vec3d, color: Int, lineWidth: Float = 3f) { val cameraForward = Vector3f(0f, 0f, -1f).rotate(camera.rotation) - line(camera.pos.add(Vec3d(cameraForward)), toWhere, lineWidth = lineWidth) + line(camera.pos.add(Vec3d(cameraForward)), toWhere, color = color, lineWidth = lineWidth) } - fun line(points: List<Vec3d>, lineWidth: Float = 10F) { + fun line(points: List<Vec3d>, color: Int, lineWidth: Float = 10F) { RenderSystem.lineWidth(lineWidth) val buffer = vertexConsumers.getBuffer(CustomRenderLayers.LINES) @@ -188,11 +176,11 @@ class RenderInWorldContext private constructor( buffer.vertex(matrix.positionMatrix, a.x.toFloat(), a.y.toFloat(), a.z.toFloat()) .color(-1) .normal(matrix, lastNormal0.x, lastNormal0.y, lastNormal0.z) - .next() + buffer.vertex(matrix.positionMatrix, b.x.toFloat(), b.y.toFloat(), b.z.toFloat()) .color(-1) .normal(matrix, normal.x, normal.y, normal.z) - .next() + } } @@ -215,11 +203,11 @@ class RenderInWorldContext private constructor( buf.vertex(matrix.positionMatrix, i, j, k) .normal(matrix, normal.x, normal.y, normal.z) .color(-1) - .next() + buf.vertex(matrix.positionMatrix, x, y, z) .normal(matrix, normal.x, normal.y, normal.z) .color(-1) - .next() + } @@ -287,12 +275,6 @@ class RenderInWorldContext private constructor( } fun renderInWorld(event: WorldRenderLastEvent, block: RenderInWorldContext. () -> Unit) { - // TODO: there should be *no more global state*. the only thing we should be doing is render layers. that includes settings like culling, blending, shader color, and depth testing - // For now i will let these functions remain, but this needs to go before i do a full (non-beta) release -// RenderSystem.disableDepthTest() -// RenderSystem.enableBlend() -// RenderSystem.defaultBlendFunc() -// RenderSystem.disableCull() event.matrices.push() event.matrices.translate(-event.camera.pos.x, -event.camera.pos.y, -event.camera.pos.z) @@ -308,7 +290,6 @@ class RenderInWorldContext private constructor( event.matrices.pop() event.vertexConsumers.draw() - RenderSystem.setShaderColor(1F, 1F, 1F, 1F) } } } diff --git a/src/main/kotlin/util/render/TranslatedScissors.kt b/src/main/kotlin/util/render/TranslatedScissors.kt index 8f8bdcf..a091648 100644 --- a/src/main/kotlin/util/render/TranslatedScissors.kt +++ b/src/main/kotlin/util/render/TranslatedScissors.kt @@ -1,26 +1,27 @@ - package moe.nea.firmament.util.render -import org.joml.Matrix4f +import org.joml.Matrix3x2f +import org.joml.Vector3f import org.joml.Vector4f import net.minecraft.client.gui.DrawContext fun DrawContext.enableScissorWithTranslation(x1: Float, y1: Float, x2: Float, y2: Float) { - enableScissor(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt()) + enableScissor(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt()) } + fun DrawContext.enableScissorWithoutTranslation(x1: Float, y1: Float, x2: Float, y2: Float) { - val pMat = matrices.peek().positionMatrix.invert(Matrix4f()) - val target = Vector4f() + val pMat = Matrix3x2f(matrices).invert() + var target = Vector3f() - target.set(x1, y1, 0f, 1f) - target.mul(pMat) - val scissorX1 = target.x - val scissorY1 = target.y + target.set(x1, y1, 1F) + target.mul(pMat) + val scissorX1 = target.x + val scissorY1 = target.y - target.set(x2, y2, 0f, 1f) - target.mul(pMat) - val scissorX2 = target.x - val scissorY2 = target.y + target.set(x2, y2, 1F) + target.mul(pMat) + val scissorX2 = target.x + val scissorY2 = target.y - enableScissor(scissorX1.toInt(), scissorY1.toInt(), scissorX2.toInt(), scissorY2.toInt()) + enableScissor(scissorX1.toInt(), scissorY1.toInt(), scissorX2.toInt(), scissorY2.toInt()) } diff --git a/src/main/kotlin/util/textutil.kt b/src/main/kotlin/util/textutil.kt index cfda2e9..177b0af 100644 --- a/src/main/kotlin/util/textutil.kt +++ b/src/main/kotlin/util/textutil.kt @@ -179,10 +179,11 @@ fun Text.transformEachRecursively(function: (Text) -> Text): Text { val c = this.content if (c is TranslatableTextContent) { return Text.translatableWithFallback(c.key, c.fallback, *c.args.map { - (if (it is Text) it else Text.literal(it.toString())).transformEachRecursively(function) + (it as? Text ?: Text.literal(it.toString())).transformEachRecursively(function) }.toTypedArray()).also { new -> new.style = this.style new.siblings.clear() + val new = function(new) this.siblings.forEach { child -> new.siblings.add(child.transformEachRecursively(function)) } diff --git a/src/main/resources/assets/firmament/gui/config/macros/combos.xml b/src/main/resources/assets/firmament/gui/config/macros/combos.xml index 5141125..91edae3 100644 --- a/src/main/resources/assets/firmament/gui/config/macros/combos.xml +++ b/src/main/resources/assets/firmament/gui/config/macros/combos.xml @@ -11,7 +11,7 @@ <Panel background="VANILLA" insets="6"> <Column> <Row> - <Text text="@command" width="280"/> + <Text text="@commandR" width="280"/> </Row> <Row> <Text text="@formattedCombo" width="250"/> diff --git a/src/main/resources/assets/firmament/gui/config/macros/wheel.xml b/src/main/resources/assets/firmament/gui/config/macros/wheel.xml index 19922fe..80826c9 100644 --- a/src/main/resources/assets/firmament/gui/config/macros/wheel.xml +++ b/src/main/resources/assets/firmament/gui/config/macros/wheel.xml @@ -24,7 +24,7 @@ </Align> </Row> <Array data="@commands"> - <Text text="@text" width="280"/> + <Text text="@textR" width="280"/> </Array> </Column> </Panel> diff --git a/src/main/resources/assets/firmament/shaders/cape/parallax.fsh b/src/main/resources/assets/firmament/shaders/cape/parallax.fsh index bc9a440..5ee269d 100644 --- a/src/main/resources/assets/firmament/shaders/cape/parallax.fsh +++ b/src/main/resources/assets/firmament/shaders/cape/parallax.fsh @@ -1,19 +1,20 @@ #version 150 #moj_import <minecraft:fog.glsl> +#moj_import <minecraft:dynamictransforms.glsl> + #define M_PI 3.1415926535897932384626433832795 #define M_TAU (2.0 * M_PI) uniform sampler2D Sampler0; uniform sampler2D Sampler1; uniform sampler2D Sampler3; -uniform vec4 ColorModulator; -uniform float FogStart; -uniform float FogEnd; -uniform vec4 FogColor; -uniform float Animation; +layout(std140) uniform Animation { + float AnimationPosition; +}; -in float vertexDistance; +in float sphericalVertexDistance; +in float cylindricalVertexDistance; in vec4 vertexColor; in vec4 lightMapColor; in vec4 overlayColor; @@ -35,13 +36,13 @@ void main() { vec4 color = texture(Sampler0, texCoord0); if (color.g > 0.99) { // TODO: maybe this speed in each direction should be a uniform - color = texture(Sampler1, texCoord0 + Animation * vec2(3.0, -2.0)); + color = texture(Sampler1, texCoord0 + AnimationPosition * vec2(3.0, -2.0)); } vec4 highlightColor = texture(Sampler3, texCoord0); if (highlightColor.a > 0.5) { color = highlightColor; - float animationHighlight = highlightDistance(texCoord0, vec2(-12.0, 2.0), Animation); + float animationHighlight = highlightDistance(texCoord0, vec2(-12.0, 2.0), AnimationPosition); color.rgb += (animationHighlight); } #ifdef ALPHA_CUTOUT @@ -49,5 +50,5 @@ void main() { discard; } #endif - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); + fragColor = apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, FogColor); } diff --git a/src/main/resources/assets/firmament/shaders/circle_discard_color.fsh b/src/main/resources/assets/firmament/shaders/circle_discard_color.fsh index ae46059..8fcd99f 100644 --- a/src/main/resources/assets/firmament/shaders/circle_discard_color.fsh +++ b/src/main/resources/assets/firmament/shaders/circle_discard_color.fsh @@ -3,8 +3,9 @@ in vec4 vertexColor; in vec2 texCoord0; -uniform vec4 ColorModulator; -uniform float InnerCutoutRadius; +layout(std140) uniform CutoutRadius { + float InnerCutoutRadius; +}; out vec4 fragColor; @@ -18,5 +19,5 @@ void main() { { discard; } - fragColor = color * ColorModulator; + fragColor = color; } diff --git a/src/main/resources/assets/firmament/textures/cape/unpleasant_gradient.png b/src/main/resources/assets/firmament/textures/cape/unpleasant_gradient.png Binary files differnew file mode 100644 index 0000000..da2eb85 --- /dev/null +++ b/src/main/resources/assets/firmament/textures/cape/unpleasant_gradient.png diff --git a/src/main/resources/firmament.accesswidener b/src/main/resources/firmament.accesswidener index 0b7b830..e600936 100644 --- a/src/main/resources/firmament.accesswidener +++ b/src/main/resources/firmament.accesswidener @@ -14,7 +14,7 @@ accessible method net/minecraft/client/render/model/ModelBaker$BakerImpl <init> accessible field net/minecraft/entity/mob/CreeperEntity CHARGED Lnet/minecraft/entity/data/TrackedData; accessible method net/minecraft/entity/decoration/ArmorStandEntity setSmall (Z)V accessible method net/minecraft/resource/NamespaceResourceManager loadMetadata (Lnet/minecraft/resource/InputSupplier;)Lnet/minecraft/resource/metadata/ResourceMetadata; -accessible method net/minecraft/client/gui/DrawContext drawTexturedQuad (Ljava/util/function/Function;Lnet/minecraft/util/Identifier;IIIIFFFFI)V +accessible method net/minecraft/client/gui/DrawContext drawTexturedQuad (Lcom/mojang/blaze3d/pipeline/RenderPipeline;Lnet/minecraft/util/Identifier;IIIIFFFFI)V accessible class net/minecraft/client/render/model/BlockStatesLoader$LoadedBlockStateDefinition accessible field net/minecraft/client/render/model/BlockStatesLoader FINDER Lnet/minecraft/resource/ResourceFinder; @@ -32,5 +32,6 @@ accessible method net/minecraft/client/render/RenderPhase$Texture getId ()Ljava/ accessible field net/minecraft/client/render/RenderLayer$MultiPhase phases Lnet/minecraft/client/render/RenderLayer$MultiPhaseParameters; accessible field net/minecraft/client/render/RenderLayer$MultiPhaseParameters texture Lnet/minecraft/client/render/RenderPhase$TextureBase; accessible field net/minecraft/client/network/ClientPlayerInteractionManager currentBreakingPos Lnet/minecraft/util/math/BlockPos; +accessible field net/minecraft/client/render/RenderLayer$MultiPhase pipeline Lcom/mojang/blaze3d/pipeline/RenderPipeline; mutable field net/minecraft/client/render/entity/state/LivingEntityRenderState headItemRenderState Lnet/minecraft/client/render/item/ItemRenderState; diff --git a/src/test/kotlin/MixinTest.kt b/src/test/kotlin/MixinTest.kt index 55aa7c2..37d79c6 100644 --- a/src/test/kotlin/MixinTest.kt +++ b/src/test/kotlin/MixinTest.kt @@ -9,18 +9,7 @@ import moe.nea.firmament.init.MixinPlugin class MixinTest { @Test fun mixinAudit() { - FirmTestBootstrap.bootstrapMinecraft() - MixinEnvironment.getCurrentEnvironment().audit() - val mp = MixinPlugin.instances.single() - Assertions.assertEquals( - mp.expectedFullPathMixins, - mp.appliedFullPathMixins, - ) - Assertions.assertNotEquals( - 0, - mp.mixins.size - ) - + // Moved to GameTest } @Test diff --git a/src/test/kotlin/testutil/ItemResources.kt b/src/test/kotlin/testutil/ItemResources.kt index e996fc2..60925c7 100644 --- a/src/test/kotlin/testutil/ItemResources.kt +++ b/src/test/kotlin/testutil/ItemResources.kt @@ -60,7 +60,7 @@ object ItemResources { typ, Dynamic(NbtOps.INSTANCE, wrappedNbtSource), source.get().dataVersion, - SharedConstants.getGameVersion().saveVersion.id + SharedConstants.getGameVersion().dataVersion().id ).value } else { wrappedNbtSource diff --git a/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomGlobalArmorOverrides.kt b/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomGlobalArmorOverrides.kt index 8a2bde5..f731982 100644 --- a/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomGlobalArmorOverrides.kt +++ b/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomGlobalArmorOverrides.kt @@ -85,7 +85,9 @@ object CustomGlobalArmorOverrides { false, false, false, - false + false, + false, + null ) } diff --git a/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomScreenLayouts.kt b/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomScreenLayouts.kt index 4785e90..69a1c7e 100644 --- a/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomScreenLayouts.kt +++ b/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomScreenLayouts.kt @@ -4,6 +4,7 @@ import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import net.minecraft.client.font.TextRenderer +import net.minecraft.client.gl.RenderPipelines import net.minecraft.client.gui.DrawContext import net.minecraft.client.gui.screen.Screen import net.minecraft.client.gui.screen.ingame.HandledScreen @@ -82,7 +83,7 @@ object CustomScreenLayouts : SinglePreparationResourceReloader<List<CustomScreen val textureWidth = this.width val textureHeight = this.height context.drawTexture( - RenderLayer::getGuiTextured, + RenderPipelines.GUI_TEXTURED, this.texture, modifiedX, modifiedY, diff --git a/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomTextReplacements.kt b/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomTextReplacements.kt new file mode 100644 index 0000000..8f7fc06 --- /dev/null +++ b/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomTextReplacements.kt @@ -0,0 +1,56 @@ +package moe.nea.firmament.features.texturepack + +import net.minecraft.resource.ResourceManager +import net.minecraft.resource.SinglePreparationResourceReloader +import net.minecraft.text.Text +import net.minecraft.util.profiler.Profiler +import moe.nea.firmament.Firmament +import moe.nea.firmament.annotations.Subscribe +import moe.nea.firmament.events.FinalizeResourceManagerEvent +import moe.nea.firmament.util.ErrorUtil.intoCatch + +object CustomTextReplacements : SinglePreparationResourceReloader<List<TreeishTextReplacer>>() { + + override fun prepare( + manager: ResourceManager, + profiler: Profiler + ): List<TreeishTextReplacer> { + return manager.findResources("overrides/texts") { it.namespace == "firmskyblock" && it.path.endsWith(".json") } + .mapNotNull { + Firmament.tryDecodeJsonFromStream<TreeishTextReplacer>(it.value.inputStream) + .intoCatch("Failed to load text override from ${it.key}").orNull() + } + } + + var textReplacers: List<TreeishTextReplacer> = listOf() + + override fun apply( + prepared: List<TreeishTextReplacer>, + manager: ResourceManager, + profiler: Profiler + ) { + this.textReplacers = prepared + } + + @JvmStatic + fun replaceTexts(texts: List<Text>): List<Text> { + return texts.map { replaceText(it) } + } + + @JvmStatic + fun replaceText(text: Text): Text { + // TODO: add a config option for this + val rawText = text.string + var text = text + for (replacer in textReplacers) { + if (!replacer.match.matches(rawText)) continue + text = replacer.replaceText(text) + } + return text + } + + @Subscribe + fun onReloadStart(event: FinalizeResourceManagerEvent) { + event.resourceManager.registerReloader(this) + } +} diff --git a/src/texturePacks/java/moe/nea/firmament/features/texturepack/StringMatcher.kt b/src/texturePacks/java/moe/nea/firmament/features/texturepack/StringMatcher.kt index dd28d9f..863ca3b 100644 --- a/src/texturePacks/java/moe/nea/firmament/features/texturepack/StringMatcher.kt +++ b/src/texturePacks/java/moe/nea/firmament/features/texturepack/StringMatcher.kt @@ -1,4 +1,3 @@ - package moe.nea.firmament.features.texturepack import com.google.gson.JsonArray @@ -13,148 +12,191 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder -import kotlin.jvm.optionals.getOrNull import net.minecraft.nbt.NbtString import net.minecraft.text.Text -import moe.nea.firmament.util.MC import moe.nea.firmament.util.removeColorCodes @Serializable(with = StringMatcher.Serializer::class) interface StringMatcher { - fun matches(string: String): Boolean - fun matches(text: Text): Boolean { - return matches(text.string) - } - - fun matches(nbt: NbtString): Boolean { - val string = nbt.value - val jsonStart = string.indexOf('{') - val stringStart = string.indexOf('"') - val isString = stringStart >= 0 && string.subSequence(0, stringStart).isBlank() - val isJson = jsonStart >= 0 && string.subSequence(0, jsonStart).isBlank() - if (isString || isJson) - return matches(Text.Serialization.fromJson(string, MC.defaultRegistries) ?: return false) - return matches(string) - } - - class Equals(input: String, val stripColorCodes: Boolean) : StringMatcher { - private val expected = if (stripColorCodes) input.removeColorCodes() else input - override fun matches(string: String): Boolean { - return expected == (if (stripColorCodes) string.removeColorCodes() else string) - } - - override fun toString(): String { - return "Equals($expected, stripColorCodes = $stripColorCodes)" - } - } - - class Pattern(val patternWithColorCodes: String, val stripColorCodes: Boolean) : StringMatcher { - private val regex: Predicate<String> = patternWithColorCodes.toPattern().asMatchPredicate() - override fun matches(string: String): Boolean { - return regex.test(if (stripColorCodes) string.removeColorCodes() else string) - } - - override fun toString(): String { - return "Pattern($patternWithColorCodes, stripColorCodes = $stripColorCodes)" - } - } - - object Serializer : KSerializer<StringMatcher> { - val delegateSerializer = kotlinx.serialization.json.JsonElement.serializer() - override val descriptor: SerialDescriptor - get() = SerialDescriptor("StringMatcher", delegateSerializer.descriptor) - - override fun deserialize(decoder: Decoder): StringMatcher { - val delegate = decoder.decodeSerializableValue(delegateSerializer) - val gsonDelegate = delegate.intoGson() - return parse(gsonDelegate) - } - - override fun serialize(encoder: Encoder, value: StringMatcher) { - encoder.encodeSerializableValue(delegateSerializer, serialize(value).intoKotlinJson()) - } - - } - - companion object { - fun serialize(stringMatcher: StringMatcher): JsonElement { - TODO("Cannot serialize string matchers rn") - } - - fun parse(jsonElement: JsonElement): StringMatcher { - if (jsonElement is JsonPrimitive) { - return Equals(jsonElement.asString, true) - } - if (jsonElement is JsonObject) { - val regex = jsonElement["regex"] as JsonPrimitive? - val text = jsonElement["equals"] as JsonPrimitive? - val shouldStripColor = when (val color = (jsonElement["color"] as JsonPrimitive?)?.asString) { - "preserve" -> false - "strip", null -> true - else -> error("Unknown color preservation mode: $color") - } - if ((regex == null) == (text == null)) error("Could not parse $jsonElement as string matcher") - if (regex != null) - return Pattern(regex.asString, shouldStripColor) - if (text != null) - return Equals(text.asString, shouldStripColor) - } - error("Could not parse $jsonElement as a string matcher") - } - } + fun matches(string: String): Boolean + fun matches(text: Text): Boolean { + return matches(text.string) + } + + val asRegex: java.util.regex.Pattern + + fun matchWithGroups(string: String): MatchNamedGroupCollection? + + fun matches(nbt: NbtString): Boolean { + val string = nbt.value + val jsonStart = string.indexOf('{') + val stringStart = string.indexOf('"') + val isString = stringStart >= 0 && string.subSequence(0, stringStart).isBlank() + val isJson = jsonStart >= 0 && string.subSequence(0, jsonStart).isBlank() + if (isString || isJson) { + // TODO: return matches(TextCodecs.CODEC.parse(MC.defaultRegistryNbtOps, string) ?: return false) + } + return matches(string) + } + + class Equals(input: String, val stripColorCodes: Boolean) : StringMatcher { + override val asRegex by lazy(LazyThreadSafetyMode.PUBLICATION) { input.toPattern(java.util.regex.Pattern.LITERAL) } + private val expected = if (stripColorCodes) input.removeColorCodes() else input + override fun matches(string: String): Boolean { + return expected == (if (stripColorCodes) string.removeColorCodes() else string) + } + + override fun matchWithGroups(string: String): MatchNamedGroupCollection? { + if (matches(string)) + return object : MatchNamedGroupCollection { + override fun get(name: String): MatchGroup? { + return null + } + + override fun get(index: Int): MatchGroup? { + return null + } + + override val size: Int + get() = 0 + + override fun isEmpty(): Boolean { + return true + } + + override fun contains(element: MatchGroup?): Boolean { + return false + } + + override fun iterator(): Iterator<MatchGroup?> { + return emptyList<MatchGroup>().iterator() + } + + override fun containsAll(elements: Collection<MatchGroup?>): Boolean { + return elements.isEmpty() + } + } + return null + } + + override fun toString(): String { + return "Equals($expected, stripColorCodes = $stripColorCodes)" + } + } + + class Pattern(val patternWithColorCodes: String, val stripColorCodes: Boolean) : StringMatcher { + private val pattern = patternWithColorCodes.toRegex() + override val asRegex = pattern.toPattern() + override fun matches(string: String): Boolean { + return pattern.matches(if (stripColorCodes) string.removeColorCodes() else string) + } + + override fun matchWithGroups(string: String): MatchNamedGroupCollection? { + return pattern.matchEntire(if (stripColorCodes) string.removeColorCodes() else string)?.groups as MatchNamedGroupCollection? + } + + override fun toString(): String { + return "Pattern($patternWithColorCodes, stripColorCodes = $stripColorCodes)" + } + } + + object Serializer : KSerializer<StringMatcher> { + val delegateSerializer = kotlinx.serialization.json.JsonElement.serializer() + override val descriptor: SerialDescriptor + get() = SerialDescriptor("StringMatcher", delegateSerializer.descriptor) + + override fun deserialize(decoder: Decoder): StringMatcher { + val delegate = decoder.decodeSerializableValue(delegateSerializer) + val gsonDelegate = delegate.intoGson() + return parse(gsonDelegate) + } + + override fun serialize(encoder: Encoder, value: StringMatcher) { + encoder.encodeSerializableValue(delegateSerializer, serialize(value).intoKotlinJson()) + } + + } + + companion object { + fun serialize(stringMatcher: StringMatcher): JsonElement { + TODO("Cannot serialize string matchers rn") + } + + fun parse(jsonElement: JsonElement): StringMatcher { + if (jsonElement is JsonPrimitive) { + return Equals(jsonElement.asString, true) + } + if (jsonElement is JsonObject) { + val regex = jsonElement["regex"] as JsonPrimitive? + val text = jsonElement["equals"] as JsonPrimitive? + val shouldStripColor = when (val color = (jsonElement["color"] as JsonPrimitive?)?.asString) { + "preserve" -> false + "strip", null -> true + else -> error("Unknown color preservation mode: $color") + } + if ((regex == null) == (text == null)) error("Could not parse $jsonElement as string matcher") + if (regex != null) + return Pattern(regex.asString, shouldStripColor) + if (text != null) + return Equals(text.asString, shouldStripColor) + } + error("Could not parse $jsonElement as a string matcher") + } + } } fun JsonElement.intoKotlinJson(): kotlinx.serialization.json.JsonElement { - when (this) { - is JsonNull -> return kotlinx.serialization.json.JsonNull - is JsonObject -> { - return kotlinx.serialization.json.JsonObject(this.entrySet() - .associate { it.key to it.value.intoKotlinJson() }) - } - - is JsonArray -> { - return kotlinx.serialization.json.JsonArray(this.map { it.intoKotlinJson() }) - } - - is JsonPrimitive -> { - if (this.isString) - return kotlinx.serialization.json.JsonPrimitive(this.asString) - if (this.isBoolean) - return kotlinx.serialization.json.JsonPrimitive(this.asBoolean) - return kotlinx.serialization.json.JsonPrimitive(this.asNumber) - } - - else -> error("Unknown json variant $this") - } + when (this) { + is JsonNull -> return kotlinx.serialization.json.JsonNull + is JsonObject -> { + return kotlinx.serialization.json.JsonObject( + this.entrySet() + .associate { it.key to it.value.intoKotlinJson() }) + } + + is JsonArray -> { + return kotlinx.serialization.json.JsonArray(this.map { it.intoKotlinJson() }) + } + + is JsonPrimitive -> { + if (this.isString) + return kotlinx.serialization.json.JsonPrimitive(this.asString) + if (this.isBoolean) + return kotlinx.serialization.json.JsonPrimitive(this.asBoolean) + return kotlinx.serialization.json.JsonPrimitive(this.asNumber) + } + + else -> error("Unknown json variant $this") + } } fun kotlinx.serialization.json.JsonElement.intoGson(): JsonElement { - when (this) { - is kotlinx.serialization.json.JsonNull -> return JsonNull.INSTANCE - is kotlinx.serialization.json.JsonPrimitive -> { - if (this.isString) - return JsonPrimitive(this.content) - if (this.content == "true") - return JsonPrimitive(true) - if (this.content == "false") - return JsonPrimitive(false) - return JsonPrimitive(LazilyParsedNumber(this.content)) - } - - is kotlinx.serialization.json.JsonObject -> { - val obj = JsonObject() - for ((k, v) in this) { - obj.add(k, v.intoGson()) - } - return obj - } - - is kotlinx.serialization.json.JsonArray -> { - val arr = JsonArray() - for (v in this) { - arr.add(v.intoGson()) - } - return arr - } - } + when (this) { + is kotlinx.serialization.json.JsonNull -> return JsonNull.INSTANCE + is kotlinx.serialization.json.JsonPrimitive -> { + if (this.isString) + return JsonPrimitive(this.content) + if (this.content == "true") + return JsonPrimitive(true) + if (this.content == "false") + return JsonPrimitive(false) + return JsonPrimitive(LazilyParsedNumber(this.content)) + } + + is kotlinx.serialization.json.JsonObject -> { + val obj = JsonObject() + for ((k, v) in this) { + obj.add(k, v.intoGson()) + } + return obj + } + + is kotlinx.serialization.json.JsonArray -> { + val arr = JsonArray() + for (v in this) { + arr.add(v.intoGson()) + } + return arr + } + } } diff --git a/src/texturePacks/java/moe/nea/firmament/features/texturepack/TreeishTextReplacer.kt b/src/texturePacks/java/moe/nea/firmament/features/texturepack/TreeishTextReplacer.kt new file mode 100644 index 0000000..a9ac6d9 --- /dev/null +++ b/src/texturePacks/java/moe/nea/firmament/features/texturepack/TreeishTextReplacer.kt @@ -0,0 +1,79 @@ +package moe.nea.firmament.features.texturepack + +import java.util.regex.Matcher +import util.json.CodecSerializer +import kotlinx.serialization.Serializable +import net.minecraft.text.Style +import net.minecraft.text.Text +import net.minecraft.text.TextCodecs +import moe.nea.firmament.util.directLiteralStringContent +import moe.nea.firmament.util.transformEachRecursively + +@Serializable +data class TreeishTextReplacer( + val match: StringMatcher, + val replacements: List<SubPartReplacement> +) { + @Serializable + data class SubPartReplacement( + val match: StringMatcher, + val style: @Serializable(StyleSerializer::class) Style? = null, + val replace: @Serializable(TextSerializer::class) Text, + ) + + object TextSerializer : CodecSerializer<Text>(TextCodecs.CODEC) + object StyleSerializer : CodecSerializer<Style>(Style.Codecs.CODEC) + companion object { + val pattern = "[$]\\{(?<name>[^}]+)}".toPattern() + fun injectMatchResults(text: Text, matches: Matcher): Text { + return text.transformEachRecursively { it -> + val content = it.directLiteralStringContent ?: return@transformEachRecursively it + val matcher = pattern.matcher(content) + val builder = StringBuilder() + while (matcher.find()) { + matcher.appendReplacement(builder, matches.group(matcher.group("name")).toString()) + } + matcher.appendTail(builder) + Text.literal(builder.toString()).setStyle(it.style) + } + } + } + + fun match(text: Text): Boolean { + return match.matches(text) + } + + fun replaceText(text: Text): Text { + return text.transformEachRecursively { part -> + var part: Text = part + for (replacement in replacements) { + val rawPartText = part.string + replacement.style?.let { expectedStyle -> + val parentStyle = part.style + val parented = expectedStyle.withParent(parentStyle) + if (parented.isStrikethrough != parentStyle.isStrikethrough + || parented.isObfuscated != parentStyle.isObfuscated + || parented.isBold != parentStyle.isBold + || parented.isUnderlined != parentStyle.isUnderlined + || parented.isItalic != parentStyle.isItalic + || parented.color?.rgb != parentStyle.color?.rgb) + continue + } + val matcher = replacement.match.asRegex.matcher(rawPartText) + if (!matcher.find()) continue + val p = Text.literal("") + p.setStyle(part.style) + var lastAppendPosition = 0 + do { + p.append(rawPartText.substring(lastAppendPosition, matcher.start())) + lastAppendPosition = matcher.end() + p.append(injectMatchResults(replacement.replace, matcher)) + } while (matcher.find()) + p.append(rawPartText.substring(lastAppendPosition)) + part = p + } + part + } + } + +} diff --git a/src/texturePacks/java/moe/nea/firmament/features/texturepack/predicates/SkullPredicate.kt b/src/texturePacks/java/moe/nea/firmament/features/texturepack/predicates/SkullPredicate.kt index 416e86c..f17582d 100644 --- a/src/texturePacks/java/moe/nea/firmament/features/texturepack/predicates/SkullPredicate.kt +++ b/src/texturePacks/java/moe/nea/firmament/features/texturepack/predicates/SkullPredicate.kt @@ -42,7 +42,7 @@ class SkullPredicate( } when { profileId != null - && profileId != profile.id.getOrNull() -> + && profileId != profile.uuid.getOrNull() -> return false textureValue != null diff --git a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/CustomSkullTexturePatch.java b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/CustomSkullTexturePatch.java index fede766..cc59d99 100644 --- a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/CustomSkullTexturePatch.java +++ b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/CustomSkullTexturePatch.java @@ -16,11 +16,11 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(SkullBlockEntityRenderer.class) public class CustomSkullTexturePatch { @Inject( - method = "getRenderLayer(Lnet/minecraft/block/SkullBlock$SkullType;Lnet/minecraft/component/type/ProfileComponent;Lnet/minecraft/util/Identifier;)Lnet/minecraft/client/render/RenderLayer;", + method = "getRenderLayer", at = @At("HEAD"), cancellable = true ) - private static void onGetRenderLayer(SkullBlock.SkullType type, ProfileComponent profile, Identifier texture, CallbackInfoReturnable<RenderLayer> cir) { + private static void onGetRenderLayer(SkullBlock.SkullType type, ProfileComponent profile, CallbackInfoReturnable<RenderLayer> cir) { CustomSkyBlockTextures.INSTANCE.modifySkullTexture(type, profile, cir); } } diff --git a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/ReplaceTextsInDrawContext.java b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/ReplaceTextsInDrawContext.java new file mode 100644 index 0000000..faf15cc --- /dev/null +++ b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/ReplaceTextsInDrawContext.java @@ -0,0 +1,55 @@ +package moe.nea.firmament.mixins.custommodels; + +import com.llamalad7.mixinextras.injector.ModifyExpressionValue; +import moe.nea.firmament.features.texturepack.CustomTextReplacements; +import net.minecraft.client.gui.DrawContext; +import net.minecraft.text.StringVisitable; +import net.minecraft.text.Text; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +import java.util.stream.Stream; + +@Mixin(DrawContext.class) +public class ReplaceTextsInDrawContext { + // I HATE THIS SO MUCH WHY CANT I JUST OPERATE ON ORDEREDTEXTS!!! + // JUNE I WILL RIP ALL OF THIS OUT AND MAKE YOU REWRITE EVERYTHING + // TODO: be in a mood to rewrite this + + @ModifyVariable(method = "drawText(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;IIIZ)V", at = @At("HEAD"), argsOnly = true) + private Text replaceTextInDrawText(Text text) { + return CustomTextReplacements.replaceText(text); + } + + @ModifyVariable(method = "drawCenteredTextWithShadow(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;III)V", at = @At("HEAD"), argsOnly = true) + private Text replaceTextInDrawCenteredTextWithShadow(Text text) { + return CustomTextReplacements.replaceText(text); + } + + @ModifyVariable(method = "drawWrappedText", at = @At("HEAD"), argsOnly = true) + private StringVisitable replaceTextInDrawWrappedText(StringVisitable stringVisitable) { + return stringVisitable instanceof Text text ? CustomTextReplacements.replaceText(text) : stringVisitable; + } + + @ModifyExpressionValue(method = "drawTooltip(Lnet/minecraft/client/font/TextRenderer;Ljava/util/List;IILnet/minecraft/util/Identifier;)V", at = @At(value = "INVOKE", target = "Ljava/util/List;stream()Ljava/util/stream/Stream;")) + private Stream<Text> replaceTextInDrawTooltipListText(Stream<Text> original) { + return original.map(CustomTextReplacements::replaceText); + } + + @ModifyExpressionValue(method = "drawTooltip(Lnet/minecraft/client/font/TextRenderer;Ljava/util/List;Ljava/util/Optional;IILnet/minecraft/util/Identifier;)V", at = @At(value = "INVOKE", target = "Ljava/util/List;stream()Ljava/util/stream/Stream;")) + private Stream<Text> replaceTextInDrawTooltipListTextWithOptional(Stream<Text> original) { + return original.map(CustomTextReplacements::replaceText); + } + + @ModifyVariable(method = "drawTooltip(Lnet/minecraft/text/Text;II)V", at = @At("HEAD"), argsOnly = true) + private Text replaceTextInDrawTooltipSingle(Text text) { + return CustomTextReplacements.replaceText(text); + } + + @ModifyExpressionValue(method = "drawHoverEvent", at = @At(value = "INVOKE", target = "Lnet/minecraft/text/HoverEvent$ShowText;value()Lnet/minecraft/text/Text;")) + private Text replaceShowTextInHover(Text text) { + return CustomTextReplacements.replaceText(text); + } + +} diff --git a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/SupplyFakeModelPatch.java b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/SupplyFakeModelPatch.java index 75cedf8..8687088 100644 --- a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/SupplyFakeModelPatch.java +++ b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/SupplyFakeModelPatch.java @@ -17,6 +17,7 @@ import net.minecraft.resource.ResourceManager; import net.minecraft.resource.ResourcePack; import net.minecraft.util.Identifier; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import java.io.InputStreamReader; @@ -44,6 +45,7 @@ public class SupplyFakeModelPatch { return original.thenCompose(oldModels -> CompletableFuture.supplyAsync(() -> supplyExtraModels(resourceManager, oldModels), executor)); } + @Unique private static ItemAssetsLoader.Result supplyExtraModels(ResourceManager resourceManager, ItemAssetsLoader.Result oldModels) { if (!CustomSkyBlockTextures.TConfig.INSTANCE.getEnableLegacyMinecraftCompat()) return oldModels; Map<Identifier, ItemAsset> newModels = new HashMap<>(oldModels.contents()); @@ -72,13 +74,14 @@ public class SupplyFakeModelPatch { .orElse(true)) { newModels.put(itemModelId, new ItemAsset( unbakedModel, - new ItemAsset.Properties(true) + new ItemAsset.Properties(true, true) )); } } return new ItemAssetsLoader.Result(newModels); } + @Unique private static boolean isResourcePackNewer( ResourceManager manager, ResourcePack null_, ResourcePack proposal) { @@ -88,6 +91,7 @@ public class SupplyFakeModelPatch { return pack.orElse(null_) != null_; } + @Unique private static <T> Collector<T, ?, Optional<T>> findLast() { return Collectors.reducing(Optional.empty(), Optional::of, (left, right) -> right.isPresent() ? right : left); diff --git a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceAnvilScreen.java b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceAnvilScreen.java index 7c5dc45..5dbdc8e 100644 --- a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceAnvilScreen.java +++ b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceAnvilScreen.java @@ -42,11 +42,11 @@ public abstract class ReplaceAnvilScreen extends ForgingScreen<AnvilScreenHandle } @WrapOperation(method = "drawForeground", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;drawTextWithShadow(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;III)I"), + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;drawTextWithShadow(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;III)V"), allow = 1) - private int onDrawRepairCost(DrawContext instance, TextRenderer textRenderer, Text text, int x, int y, int color, Operation<Integer> original) { + private void onDrawRepairCost(DrawContext instance, TextRenderer textRenderer, Text text, int x, int y, int color, Operation<Void> original) { var textOverride = CustomScreenLayouts.getTextMover(CustomScreenLayouts.CustomScreenLayout::getRepairCostTitle); - return original.call(instance, textRenderer, + original.call(instance, textRenderer, textOverride.replaceText(text), textOverride.replaceX(textRenderer, text, x), textOverride.replaceY(y), diff --git a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceFurnaceBackgrounds.java b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceFurnaceBackgrounds.java index 6b076db..4c84143 100644 --- a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceFurnaceBackgrounds.java +++ b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceFurnaceBackgrounds.java @@ -1,6 +1,7 @@ package moe.nea.firmament.mixins.custommodels.screenlayouts; import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; +import com.mojang.blaze3d.pipeline.RenderPipeline; import moe.nea.firmament.features.texturepack.CustomScreenLayouts; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.ingame.AbstractFurnaceScreen; @@ -21,8 +22,8 @@ public abstract class ReplaceFurnaceBackgrounds<T extends AbstractFurnaceScreenH super(handler, recipeBook, inventory, title); } - @WrapWithCondition(method = "drawBackground", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;drawTexture(Ljava/util/function/Function;Lnet/minecraft/util/Identifier;IIFFIIII)V"), allow = 1) - private boolean onDrawBackground(DrawContext instance, Function<Identifier, RenderLayer> renderLayers, Identifier sprite, int x, int y, float u, float v, int width, int height, int textureWidth, int textureHeight) { + @WrapWithCondition(method = "drawBackground", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;drawTexture(Lcom/mojang/blaze3d/pipeline/RenderPipeline;Lnet/minecraft/util/Identifier;IIFFIIII)V"), allow = 1) + private boolean onDrawBackground(DrawContext instance, RenderPipeline pipeline, Identifier sprite, int x, int y, float u, float v, int width, int height, int textureWidth, int textureHeight) { final var override = CustomScreenLayouts.getActiveScreenOverride(); if (override == null || override.getBackground() == null) return true; override.getBackground().renderGeneric(instance, this); diff --git a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplacePlayerBackgrounds.java b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplacePlayerBackgrounds.java index e02a821..9ae2e2f 100644 --- a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplacePlayerBackgrounds.java +++ b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplacePlayerBackgrounds.java @@ -3,6 +3,7 @@ package moe.nea.firmament.mixins.custommodels.screenlayouts; import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.mojang.blaze3d.pipeline.RenderPipeline; import moe.nea.firmament.features.texturepack.CustomScreenLayouts; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.gui.DrawContext; @@ -28,10 +29,10 @@ public abstract class ReplacePlayerBackgrounds extends RecipeBookScreen<PlayerSc @WrapOperation(method = "drawForeground", allow = 1, - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;drawText(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;IIIZ)I")) - private int onDrawForegroundText(DrawContext instance, TextRenderer textRenderer, Text text, int x, int y, int color, boolean shadow, Operation<Integer> original) { + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;drawText(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;IIIZ)V")) + private void onDrawForegroundText(DrawContext instance, TextRenderer textRenderer, Text text, int x, int y, int color, boolean shadow, Operation<Void> original) { var textOverride = CustomScreenLayouts.getTextMover(CustomScreenLayouts.CustomScreenLayout::getContainerTitle); - return original.call(instance, textRenderer, + original.call(instance, textRenderer, textOverride.replaceText(text), textOverride.replaceX(textRenderer, text, x), textOverride.replaceY(y), @@ -39,8 +40,8 @@ public abstract class ReplacePlayerBackgrounds extends RecipeBookScreen<PlayerSc shadow); } - @WrapWithCondition(method = "drawBackground", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;drawTexture(Ljava/util/function/Function;Lnet/minecraft/util/Identifier;IIFFIIII)V")) - private boolean onDrawBackground(DrawContext instance, Function<Identifier, RenderLayer> renderLayers, Identifier sprite, int x, int y, float u, float v, int width, int height, int textureWidth, int textureHeight) { + @WrapWithCondition(method = "drawBackground", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/DrawContext;drawTexture(Lcom/mojang/blaze3d/pipeline/RenderPipeline;Lnet/minecraft/util/Identifier;IIFFIIII)V")) + private boolean onDrawBackground(DrawContext instance, RenderPipeline pipeline, Identifier sprite, int x, int y, float u, float v, int width, int height, int textureWidth, int textureHeight) { final var override = CustomScreenLayouts.getActiveScreenOverride(); if (override == null || override.getBackground() == null) return true; override.getBackground().renderGeneric(instance, this); diff --git a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceTextColorInHandledScreen.java b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceTextColorInHandledScreen.java index 4f0905a..392d532 100644 --- a/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceTextColorInHandledScreen.java +++ b/src/texturePacks/java/moe/nea/firmament/mixins/custommodels/screenlayouts/ReplaceTextColorInHandledScreen.java @@ -5,12 +5,7 @@ import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import moe.nea.firmament.features.texturepack.CustomScreenLayouts; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.screen.ingame.AnvilScreen; -import net.minecraft.client.gui.screen.ingame.BeaconScreen; -import net.minecraft.client.gui.screen.ingame.CreativeInventoryScreen; import net.minecraft.client.gui.screen.ingame.HandledScreen; -import net.minecraft.client.gui.screen.ingame.InventoryScreen; -import net.minecraft.client.gui.screen.ingame.MerchantScreen; import net.minecraft.text.Text; import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.Mixin; @@ -25,16 +20,16 @@ public class ReplaceTextColorInHandledScreen { method = "drawForeground", at = @At( value = "INVOKE", - target = "Lnet/minecraft/client/gui/DrawContext;drawText(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;IIIZ)I"), + target = "Lnet/minecraft/client/gui/DrawContext;drawText(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;IIIZ)V"), slice = @Slice( from = @At(value = "FIELD", target = "Lnet/minecraft/client/gui/screen/ingame/HandledScreen;title:Lnet/minecraft/text/Text;", opcode = Opcodes.GETFIELD), to = @At(value = "FIELD", target = "Lnet/minecraft/client/gui/screen/ingame/HandledScreen;playerInventoryTitle:Lnet/minecraft/text/Text;", opcode = Opcodes.GETFIELD) ), allow = 1, require = 1) - private int replaceContainerTitle(DrawContext instance, TextRenderer textRenderer, Text text, int x, int y, int color, boolean shadow, Operation<Integer> original) { + private void replaceContainerTitle(DrawContext instance, TextRenderer textRenderer, Text text, int x, int y, int color, boolean shadow, Operation<Void> original) { var textOverride = CustomScreenLayouts.getTextMover(CustomScreenLayouts.CustomScreenLayout::getContainerTitle); - return original.call(instance, textRenderer, + original.call(instance, textRenderer, textOverride.replaceText(text), textOverride.replaceX(textRenderer, text, x), textOverride.replaceY(y), @@ -46,16 +41,16 @@ public class ReplaceTextColorInHandledScreen { method = "drawForeground", at = @At( value = "INVOKE", - target = "Lnet/minecraft/client/gui/DrawContext;drawText(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;IIIZ)I"), + target = "Lnet/minecraft/client/gui/DrawContext;drawText(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/Text;IIIZ)V"), slice = @Slice( from = @At(value = "FIELD", target = "Lnet/minecraft/client/gui/screen/ingame/HandledScreen;playerInventoryTitle:Lnet/minecraft/text/Text;", opcode = Opcodes.GETFIELD), to = @At(value = "TAIL") ), allow = 1, require = 1) - private int replacePlayerTitle(DrawContext instance, TextRenderer textRenderer, Text text, int x, int y, int color, boolean shadow, Operation<Integer> original) { + private void replacePlayerTitle(DrawContext instance, TextRenderer textRenderer, Text text, int x, int y, int color, boolean shadow, Operation<Void> original) { var textOverride = CustomScreenLayouts.getTextMover(CustomScreenLayouts.CustomScreenLayout::getPlayerTitle); - return original.call(instance, textRenderer, + original.call(instance, textRenderer, textOverride.replaceText(text), textOverride.replaceX(textRenderer, text, x), textOverride.replaceY(y), diff --git a/web/src/pages/docs/_texture-pack-format.md b/web/src/pages/docs/_texture-pack-format.md index 3575cfc..26274c2 100644 --- a/web/src/pages/docs/_texture-pack-format.md +++ b/web/src/pages/docs/_texture-pack-format.md @@ -719,6 +719,100 @@ Available options | `<extraComponent>.width` | false | The new width of the component | | `<extraComponent>.height` | false | The new height of the component | +## Text Replacements + +> [!WARNING] +> This syntax is _experimental_ and may be reworked with no backwards compatibility guarantees. If you have a use case for this syntax, please contact me so that I can figure out what kind of features are needed for the final version of this API. + +Firmament allows you to replace arbitrary texts with other texts during rendering. This only affects rendering, not what other mods see. + +To do this, place a text override in `firmskyblock:overrides/texts/<my-override>.json`: + +```json +{ + "match": { + "regex": ".*Strength.*" + }, + "replacements": [ + { + "match": "❁", + "replace": { + "text": "<newIcon>", + "color": "#ff0000" + } + } + ] +} +``` + +There are notably two separate "match" sections. This is important. The first (top-level) match checks against the entire text element, while the replacement match operates on each individual subcomponent. Let's look at an example: + +```json +{ + "italic": false, + "text": "", + "extra": [ + " ", + { + "color": "red", + "text": "❁ Strength " + }, + { + "color": "white", + "text": "510.45" + } + ] +} +``` + +In this the entire text rendered out looks like `" ❁ Strength 510.45"` and the top-level match (`".*Strength.*"`) needs to match that line. + +Then each replacement (in the `replacements` array) is matched against each subcomponent. +First, it tries to find `"❁"` in the empty root element `""`. Then it tries the first child (`" "`) and fails again. Then it tries the `"❁ Strength "` component and finds one match. It then splits the `"❁ Strength "` component into multiple subsubcomponents and replaces just the `❁` part with the one specified in the replacements array. Afterwards, it fails to match the `"510.45"` component and returns. + +Our finalized text looks like this: + +```json +{ + "italic": false, + "text": "", + "extra": [ + " ", + { + "color": "red", + "text": "", + "extra": [ + { + "text": "<newIcon>", + "color": "#ff0000" + }, + " Strength " + ] + }, + { + "color": "white", + "text": "510.45" + } + ] +} +``` + +Which rendered out looks like ` <newIcon> Strength 510.45`, with all colours original, except the `<newIcon>` which not only has new text but also a new colour. + +| Field | Required | Description | +|--------------------------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `match` | yes | A top level [string matcher](#string-matcher). Allows for testing parts of the text unrelated to the replacement and improves performance. | +| `replacements` | yes | A list of replacements to apply to each part of the text | +| `replacements.*.match` | yes | A [string matcher](#string-matcher) substring to replace in each component of the text. Notabene: Unlike most string matchers, this one is not anchored to the beginning and end of the element, so if the entire component needs to be matched a regex with `^$` needs to be used. | +| `replacements.*.style` | yes | A vanilla [style](https://minecraft.wiki/w/Text_component_format#Java_Edition) (where only the fields `color`, `italic`, `bold`, `underlined`, `strikethrough` and `obfuscated` are set). Checks if this specific subcomponent is of the correct style | +| `replacements.*.style.color` | no | A vanilla color name (as set in a text) that checks that the subcomponent is of that colour. | +| `replacements.*.style.italic` | no | A boolean that can be set `true` or `false` to require this text to be italic or not. | +| `replacements.*.style.bold` | no | A boolean that can be set `true` or `false` to require this text to be bold or not. | +| `replacements.*.style.underlined` | no | A boolean that can be set `true` or `false` to require this text to be underlined or not. | +| `replacements.*.style.strikethrough` | no | A boolean that can be set `true` or `false` to require this text to be strikethrough or not. | +| `replacements.*.style.obfuscated` | no | A boolean that can be set `true` or `false` to require this text to be obfuscated or not. | +| `replacements.*.replace` | yes | A vanilla [text](https://minecraft.wiki/w/Text_component_format#Java_Edition) that is inserted to replace the substring matched in the match. If literal texts (not translated texts) are used, then `${name}` can be used to access named groups in the match regex (if a regex matcher was used). | + ## Global Item Texture Replacement |
