diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml deleted file mode 100644 index 3550b9b89..000000000 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ /dev/null @@ -1,63 +0,0 @@ -name: Iris Bug Report -description: File a bug report for Iris -labels: [ bug ] -body: - - type: markdown - attributes: - value: | - Thank you for taking the time to fill this out! - If this does not work for you, feel free to use the [blank](https://github.com/VolmitSoftware/Iris/issues/new) format. - - type: textarea - id: how - attributes: - label: Problem - description: Please give a text description of how you reached the problem - value: | - 1. Install Iris... - 2. Do this... - 3. Do that... - 4. Observe the error... - validations: - required: true - - type: textarea - id: what - attributes: - label: Solution - description: Explain where you think the problem comes from (optional) - placeholder: The code to place a is missing b and c... - validations: - required: false - - type: dropdown - id: mcversion - attributes: - label: Minecraft Version - description: What version of Minecraft is the server on? - options: - - 1.14.X - - 1.15.X - - 1.16.X - - 1.17 - - 1.17.1 - - 1.18 - validations: - required: true - - type: input - id: irisversion - attributes: - label: Iris Version - description: What version of Iris are you running? (see console) - placeholder: DO NOT SAY "LATEST" - validations: - required: true - - type: input - id: logs - attributes: - label: Log - description: Paste a full log. Always use [mclogs](https://mclo.gs) Or [Pastebin](https://pastebin.com/). Must not be a crash report. Must be a full log. Must not be a screenshot of a log. - placeholder: https://mslog.gs/... - validations: - required: true - - type: markdown - id: thanks - attributes: - value: "Thank you for filling out the form! We will be with you soon. Please do not ask support to review your report." diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml deleted file mode 100644 index 3994c8103..000000000 --- a/.github/ISSUE_TEMPLATE/feature.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Iris Feature Request -description: File a feature request for Iris. If you want to report a bug this is not the place. -labels: [ feature ] -body: - - type: markdown - attributes: - value: | - Thank you for taking the time to fill this out! - If this does not work for you, feel free to use the [blank](https://github.com/VolmitSoftware/Iris/issues/new) format. - - type: dropdown - id: arc - attributes: - label: Adding, Removing, or Changing - description: What are you doing - options: - - Adding - - Removing - - Changing - validations: - required: true - - type: input - id: atype - attributes: - label: Type of Modification - description: What is it for? - value: I want to ... - validations: - required: true - - type: textarea - id: desc - attributes: - label: What are you trying to modify - description: Give as detailed of a description as you can for the modification that you want done (include pictures if applicable) - value: The way I would implement this is ... - validations: - required: true - - type: textarea - id: alternative - attributes: - label: Alternatives - description: What alternatives have you considered? - value: If this could not be implemented I would ... - - type: markdown - id: thanks - attributes: - value: "Thank you for filling out the form! We will be with you soon. Please do not ask support to review your report." diff --git a/IRIS.png b/IRIS.png deleted file mode 100644 index 80bf479cd..000000000 Binary files a/IRIS.png and /dev/null differ diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index 0a74fe454..000000000 --- a/LICENSE.md +++ /dev/null @@ -1,518 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - -Copyright (C) 2007 Free Software Foundation, Inc. -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. - - - Copyright (C) - - 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 . - -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: - - Copyright (C) - 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 -. - -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 -. diff --git a/build.gradle b/build.gradle deleted file mode 100644 index b1fd3587d..000000000 --- a/build.gradle +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2021 Arcane Arts (Volmit Software) - * - * 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 . - */ - -plugins { - id 'java' - id 'java-library' - id "io.freefair.lombok" version "6.3.0" - id "com.github.johnrengelman.shadow" version "7.1.2" - id "de.undercouch.download" version "5.0.1" -} - -version '2.2.1-1.19' // Needs to be version specific -def nmsVersion = "1.19" -def apiVersion = '1.19' -def spigotJarVersion = '1.19-R0.1-SNAPSHOT' -def name = getRootProject().getName() // Defined in settings.gradle -def main = 'com.volmit.iris.Iris' - -// ADD YOURSELF AS A NEW LINE IF YOU WANT YOUR OWN BUILD TASK GENERATED -// ======================== WINDOWS ============================= -registerCustomOutputTask('Cyberpwn', 'C://Users/cyberpwn/Documents/development/server/plugins') -registerCustomOutputTask('Psycho', 'D://Dan/MinecraftDevelopment/server/plugins') -registerCustomOutputTask('ArcaneArts', 'C://Users/arcane/Documents/development/server/plugins') -registerCustomOutputTask('Coco', 'D://Documents/MC/plugins') -registerCustomOutputTask('Strange', 'D://Servers/1.17 Test Server/plugins') -registerCustomOutputTask('Vatuu', 'D://Minecraft/Servers/1.19/plugins') -// ========================== UNIX ============================== -registerCustomOutputTaskUnix('CyberpwnLT', '/Users/danielmills/development/server/plugins') -registerCustomOutputTaskUnix('PsychoLT', '/Users/brianfopiano/Desktop/REMOTES/RemoteMinecraft/plugins') -// ============================================================== - -/** - * Gradle is weird sometimes, we need to delete the plugin yml from the build folder to actually filter properly. - */ -file(jar.archiveFile.get().getAsFile().getParentFile().getParentFile().getParentFile().getAbsolutePath() + '/build/resources/main/plugin.yml').delete() - -/** - * Expand properties into plugin yml - */ -processResources { - filesMatching('**/plugin.yml') { - expand( - 'name': name.toString(), - 'version': version.toString(), - 'main': main.toString(), - 'apiversion': apiVersion.toString() - ) - } -} - -/** - * Unified repo - */ -repositories { - mavenLocal { - content { - includeGroup("org.bukkit") - includeGroup("org.spigotmc") - } - } - maven { url "https://dl.cloudsmith.io/public/arcane/archive/maven/" } - maven { url "https://maven.enginehub.org/repo/" } - mavenCentral() - mavenLocal() - maven { url "https://jitpack.io"} -} - -/** - * We need parameter meta for the decree command system - */ -compileJava { - options.compilerArgs << '-parameters' -} - -/** - * Configure Iris for shading - */ -shadowJar { - //minimize() - append("plugin.yml") - relocate 'com.dfsek.paralithic', 'com.volmit.iris.util.paralithic' - relocate 'io.papermc.lib', 'com.volmit.iris.util.paper' - relocate 'net.kyori', 'com.volmit.iris.util.kyori' - dependencies { - include(dependency('io.papermc:paperlib')) - include(dependency('com.dfsek:Paralithic')) - include(dependency('net.kyori:')) - } -} - -configurations.all { - resolutionStrategy.cacheChangingModulesFor 60, 'minutes' - resolutionStrategy.cacheDynamicVersionsFor 60, 'minutes' -} - -/** - * Dependencies. - * - * Provided or classpath dependencies are not shaded and are available on the runtime classpath - * - * Shaded dependencies are not available at runtime, nor are they available on mvn central so they - * need to be shaded into the jar (increasing binary size) - * - * Dynamically loaded dependencies are defined in the plugin.yml (updating these must be updated in the - * plugin.yml also, otherwise they wont be available). These do not increase binary size). Only declare - * these dependencies if they are available on mvn central. - */ -dependencies { - // Provided or Classpath - compileOnly 'org.projectlombok:lombok:1.18.24' - annotationProcessor 'org.projectlombok:lombok:1.18.24' - implementation 'org.spigotmc:spigot-api:1.19-R0.1-SNAPSHOT' - implementation 'me.clip:placeholderapi:2.11.1' - implementation 'io.th0rgal:oraxen:1.94.0' - implementation 'org.bukkit:craftbukkit:1.19-R0.1-SNAPSHOT:remapped-mojang' - implementation 'com.github.LoneDev6:api-itemsadder:3.1.0b' - - // Shaded - implementation 'com.dfsek:Paralithic:0.4.0' - implementation 'io.papermc:paperlib:1.0.5' - implementation "net.kyori:adventure-text-minimessage:4.11.0" - implementation 'net.kyori:adventure-platform-bukkit:4.1.0' - implementation 'net.kyori:adventure-api:4.11.0' - - // Dynamically Loaded - implementation 'io.timeandspace:smoothie-map:2.0.2' - implementation 'it.unimi.dsi:fastutil:8.5.8' - implementation 'com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2' - implementation 'org.zeroturnaround:zt-zip:1.14' - implementation 'com.google.code.gson:gson:2.9.0' - implementation 'org.ow2.asm:asm:9.2' - implementation 'com.google.guava:guava:31.1-jre' - implementation 'bsf:bsf:2.4.0' - implementation 'rhino:js:1.7R2' - implementation 'com.github.ben-manes.caffeine:caffeine:3.0.6' - implementation 'org.apache.commons:commons-lang3:3.12.0' -} - -if (JavaVersion.current().toString() != "17") { - System.err.println() - System.err.println("=========================================================================================================") - System.err.println("You must run gradle on Java 17. You are using " + JavaVersion.current()) - System.err.println() - System.err.println("=== For IDEs ===") - System.err.println("1. Configure the project for Java 17") - System.err.println("2. Configure the bundled gradle to use Java 17 in settings") - System.err.println() - System.err.println("=== For Command Line (gradlew) ===") - System.err.println("1. Install JDK 17 from https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html") - System.err.println("2. Set JAVA_HOME environment variable to the new jdk installation folder such as C:\\Program Files\\Java\\jdk-17.0.1") - System.err.println("3. Open a new command prompt window to get the new environment variables if need be.") - System.err.println("=========================================================================================================") - System.err.println() - System.exit(69); -} - -def buildToolsJar = new File(buildDir, "buildtools/BuildTools.jar"); -def specialSourceJar = new File(buildDir, "specialsource/SpecialSource.jar"); -def buildToolsFolder = new File(buildDir, "buildtools"); -def specialSourceFolder = new File(buildDir, "specialsource"); -def buildToolsHint = new File(buildDir, "buildtools/craftbukkit-" + nmsVersion + ".jar"); -def outputShadeJar = new File(buildDir, "libs/Iris-" + version + "-all.jar"); -def ssiJar = new File(buildDir, "specialsource/Iris-" + version + "-all.jar"); -def ssobfJar = new File(buildDir, "specialsource/Iris-" + version + "-rmo.jar"); -def ssJar = new File(buildDir, "specialsource/Iris-" + version + "-rma.jar"); -def homePath = System.properties['user.home'] -def m2 = new File(homePath + "/.m2/repository") -def m2s = m2.getAbsolutePath(); - -// ======================== Building Mapped Jars ============================= -task downloadBuildtools(type: Download) { - group "remapping" - src 'https://hub.spigotmc.org/jenkins/job/BuildTools/lastSuccessfulBuild/artifact/target/BuildTools.jar' - dest buildToolsJar - onlyIf { - !buildToolsJar.exists() - } -} - -task downloadSpecialSource(type: Download) { - group "remapping" - src 'https://repo.maven.apache.org/maven2/net/md-5/SpecialSource/1.10.0/SpecialSource-1.10.0-shaded.jar' - dest specialSourceJar - onlyIf { - !specialSourceJar.exists() - } -} - -task executeBuildTools(dependsOn: downloadBuildtools, type: JavaExec) -{ - group "remapping" - classpath = files(buildToolsJar) - workingDir = buildToolsFolder - args = [ - "--rev", - nmsVersion, - "--compile", - "craftbukkit", - "--remap" - ] - onlyIf { - !buildToolsHint.exists() - } -} - -task copyBuildToSpecialSource(type: Copy) -{ - group "remapping" - from outputShadeJar - into specialSourceFolder - dependsOn(downloadSpecialSource, shadowJar) -} - -task specialSourceRemapObfuscate(type: JavaExec) -{ - group "remapping" - dependsOn(copyBuildToSpecialSource, downloadSpecialSource, shadowJar) - workingDir = specialSourceFolder - classpath = files(specialSourceJar, - new File(m2s + "/org/spigotmc/spigot/" + spigotJarVersion + "/spigot-" + spigotJarVersion + "-remapped-mojang.jar")) - mainClass = "net.md_5.specialsource.SpecialSource" - args = [ - "--live", - "-i", - ssiJar.getName(), - "-o", - ssobfJar.getName(), - "-m", - m2s + "/org/spigotmc/minecraft-server/" + spigotJarVersion + "/minecraft-server-" + spigotJarVersion + "-maps-mojang.txt", - "--reverse", - ] -} - -task specialSourceRemap(type: JavaExec) -{ - group "remapping" - dependsOn(specialSourceRemapObfuscate) - workingDir = specialSourceFolder - classpath = files(specialSourceJar, - new File(m2s + "/org/spigotmc/spigot/" + spigotJarVersion + "/spigot-" + spigotJarVersion + "-remapped-obf.jar")) - mainClass = "net.md_5.specialsource.SpecialSource" - args = [ - "--live", - "-i", - ssobfJar.getName(), - "-o", - ssJar.getName(), - "-m", - m2s + "/org/spigotmc/minecraft-server/" + spigotJarVersion + "/minecraft-server-" + spigotJarVersion + "-maps-spigot.csrg" - ] -} - -tasks.compileJava.dependsOn(executeBuildTools) - -compileJava { - options.encoding = "UTF-8" -} - -task setup() -{ - group("iris") - dependsOn(clean, executeBuildTools) -} - -task iris(type: Copy) -{ - group "iris" - from ssJar - into buildDir - rename { String fileName -> - fileName.replace('Iris-' + version + '-rma.jar', "Iris-" + version + ".jar") - } - dependsOn(specialSourceRemap) -} - -def registerCustomOutputTask(name, path) { - if (!System.properties['os.name'].toLowerCase().contains('windows')) { - return; - } - - tasks.register('build' + name, Copy) { - group('development') - outputs.upToDateWhen { false } - dependsOn(iris) - from(new File(buildDir, "Iris-" + version + ".jar")) - into(file(path)) - rename { String fileName -> - fileName.replace("Iris-" + version + ".jar", "Iris.jar") - } - } -} - -def registerCustomOutputTaskUnix(name, path) { - if (System.properties['os.name'].toLowerCase().contains('windows')) { - return; - } - - tasks.register('build' + name, Copy) { - group('development') - outputs.upToDateWhen { false } - dependsOn(iris) - from(new File(buildDir, "Iris-" + version + ".jar")) - into(file(path)) - rename { String fileName -> - fileName.replace("Iris-" + version + ".jar", "Iris.jar") - } - } -} diff --git a/gradle.properties b/gradle.properties deleted file mode 100644 index e6344586b..000000000 --- a/gradle.properties +++ /dev/null @@ -1,22 +0,0 @@ -# -# Iris is a World Generator for Minecraft Bukkit Servers -# Copyright (c) 2022 Arcane Arts (Volmit Software) -# -# 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 . -# -org.gradle.daemon=true -org.gradle.parallel=true -org.gradle.jvmargs=-Xmx3072m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -org.gradle.caching=true -org.gradle.configureondemand=false \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 7454180f2..000000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 2e6e5897b..000000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew deleted file mode 100755 index 1b6c78733..000000000 --- a/gradlew +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index ac1b06f93..000000000 --- a/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/icon.png b/icon.png deleted file mode 100644 index 01440638c..000000000 Binary files a/icon.png and /dev/null differ diff --git a/listing.json b/listing.json deleted file mode 100644 index be6166b3c..000000000 --- a/listing.json +++ /dev/null @@ -1,10 +0,0 @@ -[ - "overworld IrisDimensions/overworld", - "vanilla IrisDimensions/vanilla", - "flat IrisDimensions/flat", - "redstone IrisDimensions/redstone", - "mars IrisDimensions/mars", - "example IrisDimensions/example" - "newhorizons IrisDimensions/newhorizons", - "theend IrisDimensions/theend" -] diff --git a/lombok.config b/lombok.config deleted file mode 100644 index 6aa51d71e..000000000 --- a/lombok.config +++ /dev/null @@ -1,2 +0,0 @@ -# This file is generated by the 'io.freefair.lombok' Gradle plugin -config.stopBubbling = true diff --git a/out/production/resources/plugin.yml b/out/production/resources/plugin.yml deleted file mode 100644 index 59767aa97..000000000 --- a/out/production/resources/plugin.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: ${name} -version: ${version} -main: ${main} -load: STARTUP -authors: [ cyberpwn, NextdoorPsycho ] -website: volmit.com -description: More than a Dimension! -libraries: - - org.zeroturnaround:zt-zip:1.14 - - com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2 - - org.ow2.asm:asm:9.2 - - com.google.code.gson:gson:2.8.7 - - it.unimi.dsi:fastutil:8.5.4 - - com.google.guava:guava:30.1.1-jre - - bsf:bsf:2.4.0 - - rhino:js:1.7R2 -commands: - iris: - aliases: [ ir, irs ] -api-version: ${apiversion} -hotload-dependencies: false \ No newline at end of file diff --git a/packignore.ignore b/packignore.ignore deleted file mode 100644 index 9bdafae07..000000000 --- a/packignore.ignore +++ /dev/null @@ -1,3 +0,0 @@ -.DS_Store -*.code-workspace -*.txt \ No newline at end of file diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index a3e1f97cb..000000000 --- a/settings.gradle +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2021 Arcane Arts (Volmit Software) - * - * 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 . - */ -pluginManagement { - repositories { - mavenLocal() - mavenCentral() - gradlePluginPortal() - maven { url "https://dl.cloudsmith.io/public/arcane/archive/maven/" } - } -} -rootProject.name = 'Iris' \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/Iris.java b/src/main/java/com/volmit/iris/Iris.java deleted file mode 100644 index 2ab745545..000000000 --- a/src/main/java/com/volmit/iris/Iris.java +++ /dev/null @@ -1,729 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonParser; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.ServerConfigurator; -import com.volmit.iris.core.link.*; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.EnginePanic; -import com.volmit.iris.engine.object.IrisCompat; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisWorld; -import com.volmit.iris.engine.platform.BukkitChunkGenerator; -import com.volmit.iris.engine.platform.DummyChunkGenerator; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.exceptions.IrisException; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.function.NastyRunnable; -import com.volmit.iris.util.io.*; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.plugin.Metrics; -import com.volmit.iris.util.plugin.VolmitPlugin; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.reflect.ShadeFix; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.Queue; -import com.volmit.iris.util.scheduling.ShurikenQueue; -import io.papermc.lib.PaperLib; -import net.kyori.adventure.platform.bukkit.BukkitAudiences; -import net.kyori.adventure.text.serializer.ComponentSerializer; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.WorldCreator; -import org.bukkit.block.data.BlockData; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.generator.BiomeProvider; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.IllegalPluginAccessException; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.*; -import java.lang.annotation.Annotation; -import java.net.URL; -import java.util.Date; -import java.util.Map; -import java.util.Objects; - -@SuppressWarnings("CanBeFinal") -public class Iris extends VolmitPlugin implements Listener { - private static final Queue syncJobs = new ShurikenQueue<>(); - public static Iris instance; - public static BukkitAudiences audiences; - public static MultiverseCoreLink linkMultiverseCore; - public static MythicMobsLink linkMythicMobs; - public static IrisCompat compat; - public static FileWatcher configWatcher; - private static VolmitSender sender; - - static { - try { - fixShading(); - InstanceState.updateInstanceId(); - } catch(Throwable ignored) { - - } - } - - private final KList postShutdown = new KList<>(); - private KMap, IrisService> services; - - public static VolmitSender getSender() { - return sender; - } - - @SuppressWarnings("unchecked") - public static T service(Class c) { - return (T) instance.services.get(c); - } - - public static void callEvent(Event e) { - if(!e.isAsynchronous()) { - J.s(() -> Bukkit.getPluginManager().callEvent(e)); - } else { - Bukkit.getPluginManager().callEvent(e); - } - } - - public static KList initialize(String s, Class slicedClass) { - JarScanner js = new JarScanner(instance.getJarFile(), s); - KList v = new KList<>(); - J.attempt(js::scan); - for(Class i : js.getClasses()) { - if(slicedClass == null || i.isAnnotationPresent(slicedClass)) { - try { - v.add(i.getDeclaredConstructor().newInstance()); - } catch(Throwable ignored) { - - } - } - } - - return v; - } - - public static KList> getClasses(String s, Class slicedClass) { - JarScanner js = new JarScanner(instance.getJarFile(), s); - KList> v = new KList<>(); - J.attempt(js::scan); - for(Class i : js.getClasses()) { - if(slicedClass == null || i.isAnnotationPresent(slicedClass)) { - try { - v.add(i); - } catch(Throwable ignored) { - - } - } - } - - return v; - } - - public static KList initialize(String s) { - return initialize(s, null); - } - - public static void sq(Runnable r) { - synchronized(syncJobs) { - syncJobs.queue(r); - } - } - - public static File getTemp() { - return instance.getDataFolder("cache", "temp"); - } - - public static void msg(String string) { - try { - sender.sendMessage(string); - } catch(Throwable e) { - try { - System.out.println(instance.getTag() + string.replaceAll("(<([^>]+)>)", "")); - } catch(Throwable ignored1) { - - } - } - } - public static File getCached(String name, String url) { - String h = IO.hash(name + "@" + url); - File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); - - if(!f.exists()) { - try(BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) { - byte[] dataBuffer = new byte[1024]; - int bytesRead; - while((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { - fileOutputStream.write(dataBuffer, 0, bytesRead); - Iris.verbose("Aquiring " + name); - } - } catch(IOException e) { - Iris.reportError(e); - } - } - - return f.exists() ? f : null; - } - - public static String getNonCached(String name, String url) { - String h = IO.hash(name + "*" + url); - File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); - - try(BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) { - byte[] dataBuffer = new byte[1024]; - int bytesRead; - while((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { - fileOutputStream.write(dataBuffer, 0, bytesRead); - } - } catch(IOException e) { - Iris.reportError(e); - } - - try { - return IO.readAll(f); - } catch(IOException e) { - Iris.reportError(e); - } - - return ""; - } - - public static File getNonCachedFile(String name, String url) { - String h = IO.hash(name + "*" + url); - File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); - Iris.verbose("Download " + name + " -> " + url); - try(BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) { - byte[] dataBuffer = new byte[1024]; - int bytesRead; - while((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { - fileOutputStream.write(dataBuffer, 0, bytesRead); - } - - fileOutputStream.flush(); - } catch(IOException e) { - e.printStackTrace(); - Iris.reportError(e); - } - - return f; - } - - public static void warn(String format, Object... objs) { - msg(C.YELLOW + String.format(format, objs)); - } - - public static void error(String format, Object... objs) { - msg(C.RED + String.format(format, objs)); - } - - public static void debug(String string) { - if(!IrisSettings.get().getGeneral().isDebug()) { - return; - } - - try { - throw new RuntimeException(); - } catch(Throwable e) { - try { - String[] cc = e.getStackTrace()[1].getClassName().split("\\Q.\\E"); - - if(cc.length > 5) { - debug(cc[3] + "/" + cc[4] + "/" + cc[cc.length - 1], e.getStackTrace()[1].getLineNumber(), string); - } else { - debug(cc[3] + "/" + cc[4], e.getStackTrace()[1].getLineNumber(), string); - } - } catch(Throwable ex) { - debug("Origin", -1, string); - } - } - } - - public static void debug(String category, int line, String string) { - if(!IrisSettings.get().getGeneral().isDebug()) { - return; - } - if(IrisSettings.get().getGeneral().isUseConsoleCustomColors()) { - msg("" + category + " <#bf3b76>" + line + " " + C.LIGHT_PURPLE + string.replaceAll("\\Q<\\E", "[").replaceAll("\\Q>\\E", "]")); - } else { - msg(C.BLUE + category + ":" + C.AQUA + line + C.RESET + C.LIGHT_PURPLE + " " + string.replaceAll("\\Q<\\E", "[").replaceAll("\\Q>\\E", "]")); - - } - } - - public static void verbose(String string) { - debug(string); - } - - public static void success(String string) { - msg(C.IRIS + string); - } - - public static void info(String string) { - msg(C.WHITE + string); - } - - @SuppressWarnings("deprecation") - public static void later(NastyRunnable object) { - try { - Bukkit.getScheduler().scheduleAsyncDelayedTask(instance, () -> - { - try { - object.run(); - } catch(Throwable e) { - e.printStackTrace(); - Iris.reportError(e); - } - }, RNG.r.i(100, 1200)); - } catch(IllegalPluginAccessException ignored) { - - } - } - - public static int jobCount() { - return syncJobs.size(); - } - - public static void clearQueues() { - synchronized(syncJobs) { - syncJobs.clear(); - } - } - - private static int getJavaVersion() { - String version = System.getProperty("java.version"); - if(version.startsWith("1.")) { - version = version.substring(2, 3); - } else { - int dot = version.indexOf("."); - if(dot != -1) { - version = version.substring(0, dot); - } - } - return Integer.parseInt(version); - } - - public static void reportErrorChunk(int x, int z, Throwable e, String extra) { - if(IrisSettings.get().getGeneral().isDebug()) { - File f = instance.getDataFile("debug", "chunk-errors", "chunk." + x + "." + z + ".txt"); - - if(!f.exists()) { - J.attempt(() -> { - PrintWriter pw = new PrintWriter(f); - pw.println("Thread: " + Thread.currentThread().getName()); - pw.println("First: " + new Date(M.ms())); - e.printStackTrace(pw); - pw.close(); - }); - } - - Iris.debug("Chunk " + x + "," + z + " Exception Logged: " + e.getClass().getSimpleName() + ": " + C.RESET + "" + C.LIGHT_PURPLE + e.getMessage()); - } - } - - public static void reportError(Throwable e) { - if(IrisSettings.get().getGeneral().isDebug()) { - String n = e.getClass().getCanonicalName() + "-" + e.getStackTrace()[0].getClassName() + "-" + e.getStackTrace()[0].getLineNumber(); - - if(e.getCause() != null) { - n += "-" + e.getCause().getStackTrace()[0].getClassName() + "-" + e.getCause().getStackTrace()[0].getLineNumber(); - } - - File f = instance.getDataFile("debug", "caught-exceptions", n + ".txt"); - - if(!f.exists()) { - J.attempt(() -> { - PrintWriter pw = new PrintWriter(f); - pw.println("Thread: " + Thread.currentThread().getName()); - pw.println("First: " + new Date(M.ms())); - e.printStackTrace(pw); - pw.close(); - }); - } - - Iris.debug("Exception Logged: " + e.getClass().getSimpleName() + ": " + C.RESET + "" + C.LIGHT_PURPLE + e.getMessage()); - } - } - - private void enable() { - instance = this; - services = new KMap<>(); - initialize("com.volmit.iris.core.service").forEach((i) -> services.put((Class) i.getClass(), (IrisService) i)); - INMS.get(); - IO.delete(new File("iris")); - setupAudience(); - sender = new VolmitSender(Bukkit.getConsoleSender()); - sender.setTag(getTag()); - instance = this; - compat = IrisCompat.configured(getDataFile("compat.json")); - linkMultiverseCore = new MultiverseCoreLink(); - linkMythicMobs = new MythicMobsLink(); - configWatcher = new FileWatcher(getDataFile("settings.json")); - services.values().forEach(IrisService::onEnable); - services.values().forEach(this::registerListener); - J.s(() -> { - J.a(() -> PaperLib.suggestPaper(this)); - J.a(() -> IO.delete(getTemp())); - J.a(this::bstats); - J.ar(this::checkConfigHotload, 60); - J.sr(this::tickQueue, 0); - J.s(this::setupPapi); - J.a(ServerConfigurator::configure, 20); - splash(); - autoStartStudio(); - checkForBukkitWorlds(); - IrisToolbelt.retainMantleDataForSlice(String.class.getCanonicalName()); - IrisToolbelt.retainMantleDataForSlice(BlockData.class.getCanonicalName()); - }); - } - - private void checkForBukkitWorlds() { - FileConfiguration fc = new YamlConfiguration(); - try { - fc.load(new File("bukkit.yml")); - searching: for(String i : fc.getKeys(true)) - { - if(i.startsWith("worlds.") && i.endsWith(".generator")) { - String worldName = i.split("\\Q.\\E")[1]; - String generator = IrisSettings.get().getGenerator().getDefaultWorldType(); - if(fc.getString(i).startsWith("Iris:")) { - generator = fc.getString(i).split("\\Q:\\E")[1]; - } else if(fc.getString(i).equals("Iris")) { - generator = IrisSettings.get().getGenerator().getDefaultWorldType(); - } else { - continue; - } - - for(World j : Bukkit.getWorlds()) - { - if(j.getName().equals(worldName)) - { - continue searching; - } - } - - Iris.warn("Detected an Iris World in the bukkit yml '" + worldName + "' using Iris that was not loaded by bukkit. Good Guy Iris will load it up for you!"); - Iris.info(C.LIGHT_PURPLE + "Preparing Spawn for " + worldName + "' using Iris:" + generator); - World world = new WorldCreator(worldName) - .generator(getDefaultWorldGenerator(worldName, generator)) - .environment(IrisData.loadAnyDimension(generator).getEnvironment()) - .createWorld(); - Iris.info(C.LIGHT_PURPLE + "Loaded " + worldName + "!"); - } - } - } catch(Throwable e) { - e.printStackTrace(); - } - } - - private void autoStartStudio() { - if(IrisSettings.get().getStudio().isAutoStartDefaultStudio()) { - Iris.info("Starting up auto Studio!"); - try { - Player r = new KList<>(getServer().getOnlinePlayers()).getRandom(); - Iris.service(StudioSVC.class).open(r != null ? new VolmitSender(r) : sender, 1337, IrisSettings.get().getGenerator().getDefaultWorldType(), (w) -> { - J.s(() -> { - for(Player i : getServer().getOnlinePlayers()) { - i.setGameMode(GameMode.SPECTATOR); - i.teleport(new Location(w, 0, 200, 0)); - } - }); - }); - } catch(IrisException e) { - e.printStackTrace(); - } - } - } - - private void setupAudience() { - try { - audiences = BukkitAudiences.create(this); - } catch(Throwable e) { - e.printStackTrace(); - IrisSettings.get().getGeneral().setUseConsoleCustomColors(false); - IrisSettings.get().getGeneral().setUseCustomColorsIngame(false); - Iris.error("Failed to setup Adventure API... No custom colors :("); - } - } - - public static void dump() { - try { - File fi = Iris.instance.getDataFile("dump", "td-" + new java.sql.Date(M.ms()) + ".txt"); - FileOutputStream fos = new FileOutputStream(fi); - Map f = Thread.getAllStackTraces(); - PrintWriter pw = new PrintWriter(fos); - for(Thread i : f.keySet()) { - pw.println("========================================"); - pw.println("Thread: '" + i.getName() + "' ID: " + i.getId() + " STATUS: " + i.getState().name()); - - for(StackTraceElement j : f.get(i)) { - pw.println(" @ " + j.toString()); - } - - pw.println("========================================"); - pw.println(); - pw.println(); - } - - pw.close(); - System.out.println("DUMPED! See " + fi.getAbsolutePath()); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - public void postShutdown(Runnable r) { - postShutdown.add(r); - } - - public static void panic() { - EnginePanic.panic(); - } - - public static void addPanic(String s, String v) { - EnginePanic.add(s, v); - } - - public void onEnable() { - enable(); - super.onEnable(); - Bukkit.getPluginManager().registerEvents(this, this); - } - - public void onDisable() { - services.values().forEach(IrisService::onDisable); - Bukkit.getScheduler().cancelTasks(this); - HandlerList.unregisterAll((Plugin) this); - postShutdown.forEach(Runnable::run); - services.clear(); - MultiBurst.burst.close(); - super.onDisable(); - } - - private static void fixShading() { - ShadeFix.fix(ComponentSerializer.class); - } - - private void setupPapi() { - if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { - new IrisPapiExpansion().register(); - } - } - - @Override - public void start() { - - } - - @Override - public void stop() { - - } - - @Override - public String getTag(String subTag) { - return C.BOLD + "" + C.DARK_GRAY + "[" + C.BOLD + "" + C.IRIS + "Iris" + C.BOLD + C.DARK_GRAY + "]" + C.RESET + "" + C.GRAY + ": "; - } - - private void checkConfigHotload() { - if(configWatcher.checkModified()) { - IrisSettings.invalidate(); - IrisSettings.get(); - configWatcher.checkModified(); - Iris.info("Hotloaded settings.json "); - } - } - - private void tickQueue() { - synchronized(Iris.syncJobs) { - if(!Iris.syncJobs.hasNext()) { - return; - } - - long ms = M.ms(); - - while(Iris.syncJobs.hasNext() && M.ms() - ms < 25) { - try { - Iris.syncJobs.next().run(); - } catch(Throwable e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - } - } - - private void bstats() { - if(IrisSettings.get().getGeneral().isPluginMetrics()) { - J.s(() -> new Metrics(Iris.instance, 8757)); - } - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - return super.onCommand(sender, command, label, args); - } - - public void imsg(CommandSender s, String msg) { - s.sendMessage(C.IRIS + "[" + C.DARK_GRAY + "Iris" + C.IRIS + "]" + C.GRAY + ": " + msg); - } - - @Nullable - @Override - public BiomeProvider getDefaultBiomeProvider(@NotNull String worldName, @Nullable String id) { - Iris.debug("Biome Provider Called for " + worldName + " using ID: " + id); - return super.getDefaultBiomeProvider(worldName, id); - } - - @Override - public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { - Iris.debug("Default World Generator Called for " + worldName + " using ID: " + id); - if(worldName.equals("test")) { - try { - throw new RuntimeException(); - } catch(Throwable e) { - Iris.info(e.getStackTrace()[1].getClassName()); - if(e.getStackTrace()[1].getClassName().contains("com.onarandombox.MultiverseCore")) { - Iris.debug("MVC Test detected, Quick! Send them the dummy!"); - return new DummyChunkGenerator(); - } - } - } - - IrisDimension dim; - if(id == null || id.isEmpty()) { - dim = IrisData.loadAnyDimension(IrisSettings.get().getGenerator().getDefaultWorldType()); - } else { - dim = IrisData.loadAnyDimension(id); - } - Iris.debug("Generator ID: " + id + " requested by bukkit/plugin"); - - if(dim == null) { - Iris.warn("Unable to find dimension type " + id + " Looking for online packs..."); - - service(StudioSVC.class).downloadSearch(new VolmitSender(Bukkit.getConsoleSender()), id, true); - dim = IrisData.loadAnyDimension(id); - - if(dim == null) { - throw new RuntimeException("Can't find dimension " + id + "!"); - } else { - Iris.info("Resolved missing dimension, proceeding with generation."); - } - } - - Iris.debug("Assuming IrisDimension: " + dim.getName()); - - IrisWorld w = IrisWorld.builder() - .name(worldName) - .seed(1337) - .environment(dim.getEnvironment()) - .worldFolder(new File(worldName)) - .minHeight(dim.getMinHeight()) - .maxHeight(dim.getMaxHeight()) - .build(); - - Iris.debug("Generator Config: " + w.toString()); - - File ff = new File(w.worldFolder(), "iris/pack"); - if(!ff.exists() || ff.listFiles().length == 0) { - ff.mkdirs(); - service(StudioSVC.class).installIntoWorld(sender, dim.getLoadKey(), ff.getParentFile()); - } - - return new BukkitChunkGenerator(w, false, ff, dim.getLoadKey()); - } - - public void splash() { - if(!IrisSettings.get().getGeneral().isSplashLogoStartup()) { - return; - } - - // @NoArgsConstructor - String padd = Form.repeat(" ", 8); - String padd2 = Form.repeat(" ", 4); - String[] info = {"", "", "", "", "", padd2 + C.IRIS + " Iris", padd2 + C.GRAY + " by " + "Volmit Software", padd2 + C.GRAY + " v" + C.IRIS + getDescription().getVersion(), - }; - String[] splash = { - padd + C.GRAY + " @@@@@@@@@@@@@@" + C.DARK_GRAY + "@@@", - padd + C.GRAY + " @@&&&&&&&&&" + C.DARK_GRAY + "&&&&&&" + C.IRIS + " .(((()))). ", - padd + C.GRAY + "@@@&&&&&&&&" + C.DARK_GRAY + "&&&&&" + C.IRIS + " .((((((())))))). ", - padd + C.GRAY + "@@@&&&&&" + C.DARK_GRAY + "&&&&&&&" + C.IRIS + " ((((((((())))))))) " + C.GRAY + " @", - padd + C.GRAY + "@@@&&&&" + C.DARK_GRAY + "@@@@@&" + C.IRIS + " ((((((((-))))))))) " + C.GRAY + " @@", - padd + C.GRAY + "@@@&&" + C.IRIS + " ((((((({ })))))))) " + C.GRAY + " &&@@@", - padd + C.GRAY + "@@" + C.IRIS + " ((((((((-))))))))) " + C.DARK_GRAY + "&@@@@@" + C.GRAY + "&&&&@@@", - padd + C.GRAY + "@" + C.IRIS + " ((((((((())))))))) " + C.DARK_GRAY + "&&&&&" + C.GRAY + "&&&&&&&@@@", - padd + C.GRAY + "" + C.IRIS + " '((((((()))))))' " + C.DARK_GRAY + "&&&&&" + C.GRAY + "&&&&&&&&@@@", - padd + C.GRAY + "" + C.IRIS + " '(((())))' " + C.DARK_GRAY + "&&&&&&&&" + C.GRAY + "&&&&&&&@@", - padd + C.GRAY + " " + C.DARK_GRAY + "@@@" + C.GRAY + "@@@@@@@@@@@@@@" - }; - //@done - Iris.info("Server type & version: " + Bukkit.getVersion()); - Iris.info("Bukkit version: " + Bukkit.getBukkitVersion()); - Iris.info("Java version: " + getJavaVersion()); - Iris.info("Custom Biomes: " + INMS.get().countCustomBiomes()); - printPacks(); - - for(int i = 0; i < info.length; i++) { - splash[i] += info[i]; - } - - Iris.info("\n\n " + new KList<>(splash).toString("\n") + "\n"); - } - - private void printPacks() { - File packFolder = Iris.service(StudioSVC.class).getWorkspaceFolder(); - File[] packs = packFolder.listFiles(File::isDirectory); - if(packs == null || packs.length == 0) - return; - Iris.info("Custom Dimensions: " + packs.length); - for(File f : packs) - printPack(f); - } - - private void printPack(File pack) { - String dimName = pack.getName(); - String version = "???"; - try(FileReader r = new FileReader(new File(pack, "dimensions/" + dimName + ".json"))) { - JsonObject json = JsonParser.parseReader(r).getAsJsonObject(); - if(json.has("version")) - version = json.get("version").getAsString(); - } catch(IOException | JsonParseException ignored) { } - Iris.info(" " + dimName + " v" + version); - } -} diff --git a/src/main/java/com/volmit/iris/core/IrisSettings.java b/src/main/java/com/volmit/iris/core/IrisSettings.java deleted file mode 100644 index 877440f45..000000000 --- a/src/main/java/com/volmit/iris/core/IrisSettings.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core; - -import com.google.gson.Gson; -import com.volmit.iris.Iris; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONException; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.Data; - -import java.io.File; -import java.io.IOException; - -@SuppressWarnings("SynchronizeOnNonFinalField") -@Data -public class IrisSettings { - public static IrisSettings settings; - private IrisSettingsGeneral general = new IrisSettingsGeneral(); - private IrisSettingsWorld world = new IrisSettingsWorld(); - private IrisSettingsGUI gui = new IrisSettingsGUI(); - private IrisSettingsAutoconfiguration autoConfiguration = new IrisSettingsAutoconfiguration(); - private IrisSettingsGenerator generator = new IrisSettingsGenerator(); - private IrisSettingsConcurrency concurrency = new IrisSettingsConcurrency(); - private IrisSettingsStudio studio = new IrisSettingsStudio(); - private IrisSettingsPerformance performance = new IrisSettingsPerformance(); - - public static int getThreadCount(int c) { - return switch(c) { - case -1, -2, -4 -> Runtime.getRuntime().availableProcessors() / -c; - case 0, 1, 2 -> 1; - default -> Math.max(c, 2); - }; - } - - @Data - public static class IrisSettingsAutoconfiguration { - public boolean configureSpigotTimeoutTime = true; - public boolean configurePaperWatchdogDelay = true; - public boolean autoRestartOnCustomBiomeInstall = true; - } - - @Data - public static class IrisAsyncTeleport { - public boolean enabled = false; - public int loadViewDistance = 2; - public boolean urgent = false; - } - - @Data - public static class IrisSettingsWorld { - public IrisAsyncTeleport asyncTeleport = new IrisAsyncTeleport(); - public boolean postLoadBlockUpdates = true; - public boolean forcePersistEntities = true; - public boolean anbientEntitySpawningSystem = true; - public long asyncTickIntervalMS = 700; - public double targetSpawnEntitiesPerChunk = 0.95; - public boolean markerEntitySpawningSystem = true; - public boolean effectSystem = true; - public boolean worldEditWandCUI = true; - } - - @Data - public static class IrisSettingsConcurrency { - public int parallelism = -1; - } - - @Data - public static class IrisSettingsPerformance { - public boolean trimMantleInStudio = false; - public int mantleKeepAlive = 30; - public int cacheSize = 4_096; - public int resourceLoaderCacheSize = 1_024; - public int objectLoaderCacheSize = 4_096; - public int scriptLoaderCacheSize = 512; - } - - @Data - public static class IrisSettingsGeneral { - public boolean commandSounds = true; - public boolean debug = false; - public boolean disableNMS = false; - public boolean pluginMetrics = true; - public boolean splashLogoStartup = true; - public boolean useConsoleCustomColors = true; - public boolean useCustomColorsIngame = true; - public String forceMainWorld = ""; - public int spinh = -20; - public int spins = 7; - public int spinb = 8; - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean canUseCustomColors(VolmitSender volmitSender) { - return volmitSender.isPlayer() ? useCustomColorsIngame : useConsoleCustomColors; - } - } - - @Data - public static class IrisSettingsGUI { - public boolean useServerLaunchedGuis = true; - public boolean maximumPregenGuiFPS = false; - } - - @Data - public static class IrisSettingsGenerator { - public String defaultWorldType = "overworld"; - public int maxBiomeChildDepth = 4; - public boolean preventLeafDecay = true; - } - - @Data - public static class IrisSettingsStudio { - public boolean studio = true; - public boolean openVSCode = true; - public boolean disableTimeAndWeather = true; - public boolean autoStartDefaultStudio = false; - } - - public static IrisSettings get() { - if(settings != null) { - return settings; - } - - settings = new IrisSettings(); - - File s = Iris.instance.getDataFile("settings.json"); - - if(!s.exists()) { - try { - IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); - } catch(JSONException | IOException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } else { - try { - String ss = IO.readAll(s); - settings = new Gson().fromJson(ss, IrisSettings.class); - try { - IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); - } catch(IOException e) { - e.printStackTrace(); - } - } catch(Throwable ee) { - // Iris.reportError(ee); causes a self-reference & stackoverflow - Iris.error("Configuration Error in settings.json! " + ee.getClass().getSimpleName() + ": " + ee.getMessage()); - } - } - - return settings; - } - - public static void invalidate() { - synchronized(settings) { - settings = null; - } - } - - public void forceSave() { - File s = Iris.instance.getDataFile("settings.json"); - - try { - IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); - } catch(JSONException | IOException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } -} diff --git a/src/main/java/com/volmit/iris/core/ServerConfigurator.java b/src/main/java/com/volmit/iris/core/ServerConfigurator.java deleted file mode 100644 index 0d08255e2..000000000 --- a/src/main/java/com/volmit/iris/core/ServerConfigurator.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisBiomeCustom; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; - -import java.io.File; -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -public class ServerConfigurator { - public static void configure() { - IrisSettings.IrisSettingsAutoconfiguration s = IrisSettings.get().getAutoConfiguration(); - if(s.isConfigureSpigotTimeoutTime()) { - J.attempt(ServerConfigurator::increaseKeepAliveSpigot); - } - - if(s.isConfigurePaperWatchdogDelay()) { - J.attempt(ServerConfigurator::increasePaperWatchdog); - } - - installDataPacks(true); - } - - private static void increaseKeepAliveSpigot() throws IOException, InvalidConfigurationException { - File spigotConfig = new File("config/spigot.yml"); - FileConfiguration f = new YamlConfiguration(); - f.load(spigotConfig); - long tt = f.getLong("settings.timeout-time"); - - if(tt < TimeUnit.MINUTES.toSeconds(5)) { - Iris.warn("Updating spigot.yml timeout-time: " + tt + " -> " + TimeUnit.MINUTES.toSeconds(5) + " (5 minutes)"); - Iris.warn("You can disable this change (autoconfigureServer) in Iris settings, then change back the value."); - f.set("settings.timeout-time", TimeUnit.MINUTES.toSeconds(5)); - f.save(spigotConfig); - } - } - - private static void increasePaperWatchdog() throws IOException, InvalidConfigurationException { - File spigotConfig = new File("config/paper-global.yml"); - FileConfiguration f = new YamlConfiguration(); - f.load(spigotConfig); - long tt = f.getLong("watchdog.early-warning-delay"); - - if(tt < TimeUnit.MINUTES.toMillis(3)) { - Iris.warn("Updating paper.yml watchdog early-warning-delay: " + tt + " -> " + TimeUnit.MINUTES.toMillis(3) + " (3 minutes)"); - Iris.warn("You can disable this change (autoconfigureServer) in Iris settings, then change back the value."); - f.set("watchdog.early-warning-delay", TimeUnit.MINUTES.toMillis(3)); - f.save(spigotConfig); - } - } - - private static File getDatapacksFolder() { - if(!IrisSettings.get().getGeneral().forceMainWorld.isEmpty()) { - return new File(IrisSettings.get().getGeneral().forceMainWorld + "/datapacks"); - } - - File props = new File("server.properties"); - - if(props.exists()) { - try { - KList m = new KList<>(IO.readAll(props).split("\\Q\n\\E")); - - for(String i : m) { - if(i.trim().startsWith("level-name=")) { - return new File(i.trim().split("\\Q=\\E")[1] + "/datapacks"); - } - } - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - return null; - } - - public static void installDataPacks(boolean fullInstall) { - Iris.info("Checking Data Packs..."); - boolean reboot = false; - File packs = new File("plugins/Iris/packs"); - File dpacks = getDatapacksFolder(); - - if(dpacks == null) { - Iris.error("Cannot find the datapacks folder! Please try generating a default world first maybe? Is this a new server?"); - return; - } - - if(packs.exists()) { - for(File i : packs.listFiles()) { - if(i.isDirectory()) { - Iris.verbose("Checking Pack: " + i.getPath()); - IrisData data = IrisData.get(i); - File dims = new File(i, "dimensions"); - - if(dims.exists()) { - for(File j : dims.listFiles()) { - if(j.getName().endsWith(".json")) { - IrisDimension dim = data.getDimensionLoader().load(j.getName().split("\\Q.\\E")[0]); - - if(dim == null) { - continue; - } - - Iris.verbose(" Checking Dimension " + dim.getLoadFile().getPath()); - if(dim.installDataPack(() -> data, dpacks)) { - reboot = true; - } - } - } - } - } - } - } - - Iris.info("Data Packs Setup!"); - - if(fullInstall) { - verifyDataPacksPost(IrisSettings.get().getAutoConfiguration().isAutoRestartOnCustomBiomeInstall()); - } - } - - private static void verifyDataPacksPost(boolean allowRestarting) { - File packs = new File("plugins/Iris/packs"); - File dpacks = getDatapacksFolder(); - - if(dpacks == null) { - Iris.error("Cannot find the datapacks folder! Please try generating a default world first maybe? Is this a new server?"); - return; - } - - boolean bad = false; - if(packs.exists()) { - for(File i : packs.listFiles()) { - if(i.isDirectory()) { - Iris.verbose("Checking Pack: " + i.getPath()); - IrisData data = IrisData.get(i); - File dims = new File(i, "dimensions"); - - if(dims.exists()) { - for(File j : dims.listFiles()) { - if(j.getName().endsWith(".json")) { - IrisDimension dim = data.getDimensionLoader().load(j.getName().split("\\Q.\\E")[0]); - - if(dim == null) { - Iris.error("Failed to load " + j.getPath() + " "); - continue; - } - - if(!verifyDataPackInstalled(dim)) { - bad = true; - } - } - } - } - } - } - } - - if(bad) { - if(allowRestarting) { - restart(); - } else if(INMS.get().supportsDataPacks()) { - Iris.error("============================================================================"); - Iris.error(C.ITALIC + "You need to restart your server to properly generate custom biomes."); - Iris.error(C.ITALIC + "By continuing, Iris will use backup biomes in place of the custom biomes."); - Iris.error("----------------------------------------------------------------------------"); - Iris.error(C.UNDERLINE + "IT IS HIGHLY RECOMMENDED YOU RESTART THE SERVER BEFORE GENERATING!"); - Iris.error("============================================================================"); - - for(Player i : Bukkit.getOnlinePlayers()) { - if(i.isOp() || i.hasPermission("iris.all")) { - VolmitSender sender = new VolmitSender(i, Iris.instance.getTag("WARNING")); - sender.sendMessage("There are some Iris Packs that have custom biomes in them"); - sender.sendMessage("You need to restart your server to use these packs."); - } - } - - J.sleep(3000); - } - } - } - - public static void restart() { - J.s(() -> { - Iris.warn("New data pack entries have been installed in Iris! Restarting server!"); - Iris.warn("This will only happen when your pack changes (updates/first time setup)"); - Iris.warn("(You can disable this auto restart in iris settings)"); - J.s(() -> { - Iris.warn("Looks like the restart command diddn't work. Stopping the server instead!"); - Bukkit.shutdown(); - }, 100); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "restart"); - }); - } - - public static boolean verifyDataPackInstalled(IrisDimension dimension) { - IrisData idm = IrisData.get(Iris.instance.getDataFolder("packs", dimension.getLoadKey())); - KSet keys = new KSet<>(); - boolean warn = false; - - for(IrisBiome i : dimension.getAllBiomes(() -> idm)) { - if(i.isCustom()) { - for(IrisBiomeCustom j : i.getCustomDerivitives()) { - keys.add(dimension.getLoadKey() + ":" + j.getId()); - } - } - } - - if(!INMS.get().supportsDataPacks()) { - if(!keys.isEmpty()) { - Iris.warn("==================================================================================="); - Iris.warn("Pack " + dimension.getLoadKey() + " has " + keys.size() + " custom biome(s). "); - Iris.warn("Your server version does not yet support datapacks for iris."); - Iris.warn("The world will generate these biomes as backup biomes."); - Iris.warn("===================================================================================="); - } - - return true; - } - - for(String i : keys) { - Object o = INMS.get().getCustomBiomeBaseFor(i); - - if(o == null) { - Iris.warn("The Biome " + i + " is not registered on the server."); - warn = true; - } - } - - if(warn) { - Iris.error("The Pack " + dimension.getLoadKey() + " is INCAPABLE of generating custom biomes"); - Iris.error("If not done automatically, restart your server before generating with this pack!"); - } - - return !warn; - } -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandEdit.java b/src/main/java/com/volmit/iris/core/commands/CommandEdit.java deleted file mode 100644 index e1cb05399..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandEdit.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisCave; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisJigsawPiece; -import com.volmit.iris.engine.object.IrisJigsawPool; -import com.volmit.iris.engine.object.IrisJigsawStructure; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.decree.DecreeExecutor; -import com.volmit.iris.util.decree.DecreeOrigin; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.format.C; - -import java.awt.Desktop; - - -@Decree(name = "edit", origin = DecreeOrigin.PLAYER, studio = true, description = "Edit something") -public class CommandEdit implements DecreeExecutor { - - private boolean noStudio() { - if(!sender().isPlayer()) { - sender().sendMessage(C.RED + "Players only!"); - return true; - } - if(!Iris.service(StudioSVC.class).isProjectOpen()) { - sender().sendMessage(C.RED + "No studio world is open!"); - return true; - } - if(!engine().isStudio()) { - sender().sendMessage(C.RED + "You must be in a studio world!"); - return true; - } - return false; - } - - - @Decree(description = "Edit the biome you specified", aliases = {"b"}, origin = DecreeOrigin.PLAYER) - public void biome(@Param(contextual = false, description = "The biome to edit") IrisBiome biome) { - if(noStudio()) { - return; - } - try { - if(biome == null || biome.getLoadFile() == null) { - sender().sendMessage(C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"); - return; - } - Desktop.getDesktop().open(biome.getLoadFile()); - sender().sendMessage(C.GREEN + "Opening " + biome.getTypeName() + " " + biome.getLoadFile().getName().split("\\Q.\\E")[0] + " in VSCode! "); - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage(C.RED + "Cant find the file. Or registrant does not exist"); - } - } - - @Decree(description = "Edit the region you specified", aliases = {"r"}, origin = DecreeOrigin.PLAYER) - public void region(@Param(contextual = false, description = "The region to edit") IrisRegion region) { - if(noStudio()) { - return; - } - try { - if(region == null || region.getLoadFile() == null) { - sender().sendMessage(C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"); - return; - } - Desktop.getDesktop().open(region.getLoadFile()); - sender().sendMessage(C.GREEN + "Opening " + region.getTypeName() + " " + region.getLoadFile().getName().split("\\Q.\\E")[0] + " in VSCode! "); - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage(C.RED + "Cant find the file. Or registrant does not exist"); - } - } - - @Decree(description = "Edit the dimension you specified", aliases = {"d"}, origin = DecreeOrigin.PLAYER) - public void dimension(@Param(contextual = false, description = "The dimension to edit") IrisDimension dimension) { - if(noStudio()) { - return; - } - try { - if(dimension == null || dimension.getLoadFile() == null) { - sender().sendMessage(C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"); - return; - } - Desktop.getDesktop().open(dimension.getLoadFile()); - sender().sendMessage(C.GREEN + "Opening " + dimension.getTypeName() + " " + dimension.getLoadFile().getName().split("\\Q.\\E")[0] + " in VSCode! "); - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage(C.RED + "Cant find the file. Or registrant does not exist"); - } - } - - @Decree(description = "Edit the cave file you specified", aliases = {"c"}, origin = DecreeOrigin.PLAYER) - public void cave(@Param(contextual = false, description = "The cave to edit") IrisCave cave) { - if(noStudio()) { - return; - } - try { - if(cave == null || cave.getLoadFile() == null) { - sender().sendMessage(C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"); - return; - } - Desktop.getDesktop().open(cave.getLoadFile()); - sender().sendMessage(C.GREEN + "Opening " + cave.getTypeName() + " " + cave.getLoadFile().getName().split("\\Q.\\E")[0] + " in VSCode! "); - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage(C.RED + "Cant find the file. Or registrant does not exist"); - } - } - - @Decree(description = "Edit the structure file you specified", aliases = {"jigsawstructure", "structure"}, origin = DecreeOrigin.PLAYER) - public void jigsaw(@Param(contextual = false, description = "The jigsaw structure to edit") IrisJigsawStructure jigsaw) { - if(noStudio()) { - return; - } - try { - if(jigsaw == null || jigsaw.getLoadFile() == null) { - sender().sendMessage(C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"); - return; - } - Desktop.getDesktop().open(jigsaw.getLoadFile()); - sender().sendMessage(C.GREEN + "Opening " + jigsaw.getTypeName() + " " + jigsaw.getLoadFile().getName().split("\\Q.\\E")[0] + " in VSCode! "); - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage(C.RED + "Cant find the file. Or registrant does not exist"); - } - } - - @Decree(description = "Edit the pool file you specified", aliases = {"jigsawpool", "pool"}, origin = DecreeOrigin.PLAYER) - public void jigsawPool(@Param(contextual = false, description = "The jigsaw pool to edit") IrisJigsawPool pool) { - if(noStudio()) { - return; - } - try { - if(pool == null || pool.getLoadFile() == null) { - sender().sendMessage(C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"); - return; - } - Desktop.getDesktop().open(pool.getLoadFile()); - sender().sendMessage(C.GREEN + "Opening " + pool.getTypeName() + " " + pool.getLoadFile().getName().split("\\Q.\\E")[0] + " in VSCode! "); - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage(C.RED + "Cant find the file. Or registrant does not exist"); - } - } - - @Decree(description = "Edit the jigsaw piece file you specified", aliases = {"jigsawpiece", "piece"}, origin = DecreeOrigin.PLAYER) - public void jigsawPiece(@Param(contextual = false, description = "The jigsaw piece to edit") IrisJigsawPiece piece) { - if(noStudio()) { - return; - } - try { - if(piece == null || piece.getLoadFile() == null) { - sender().sendMessage(C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"); - return; - } - Desktop.getDesktop().open(piece.getLoadFile()); - sender().sendMessage(C.GREEN + "Opening " + piece.getTypeName() + " " + piece.getLoadFile().getName().split("\\Q.\\E")[0] + " in VSCode! "); - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage(C.RED + "Cant find the file. Or registrant does not exist"); - } - } - -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandFind.java b/src/main/java/com/volmit/iris/core/commands/CommandFind.java deleted file mode 100644 index 45380aee2..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandFind.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisJigsawStructure; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.decree.DecreeExecutor; -import com.volmit.iris.util.decree.DecreeOrigin; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.decree.specialhandlers.ObjectHandler; -import com.volmit.iris.util.format.C; - -@Decree(name = "find", origin = DecreeOrigin.PLAYER, description = "Iris Find commands", aliases = "goto") -public class CommandFind implements DecreeExecutor { - @Decree(description = "Find a biome") - public void biome( - @Param(description = "The biome to look for") - IrisBiome biome - ) { - Engine e = engine(); - - if(e == null) { - sender().sendMessage(C.GOLD + "Not in an Iris World!"); - return; - } - - e.gotoBiome(biome, player()); - } - - @Decree(description = "Find a region") - public void region( - @Param(description = "The region to look for") - IrisRegion region - ) { - Engine e = engine(); - - if(e == null) { - sender().sendMessage(C.GOLD + "Not in an Iris World!"); - return; - } - - e.gotoRegion(region, player()); - } - - @Decree(description = "Find a structure") - public void structure( - @Param(description = "The structure to look for") - IrisJigsawStructure structure - ) { - Engine e = engine(); - - if(e == null) { - sender().sendMessage(C.GOLD + "Not in an Iris World!"); - return; - } - - e.gotoJigsaw(structure, player()); - } - - @Decree(description = "Find an object") - public void object( - @Param(description = "The object to look for", customHandler = ObjectHandler.class) - String object - ) { - Engine e = engine(); - - if(e == null) { - sender().sendMessage(C.GOLD + "Not in an Iris World!"); - return; - } - - e.gotoObject(object, player()); - } -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandIris.java b/src/main/java/com/volmit/iris/core/commands/CommandIris.java deleted file mode 100644 index 80c35e463..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandIris.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.platform.PlatformChunkGenerator; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeContext; -import com.volmit.iris.util.decree.DecreeExecutor; -import com.volmit.iris.util.decree.DecreeOrigin; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.jobs.QueueJob; -import org.bukkit.Chunk; -import org.bukkit.World; - -import java.io.File; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -@Decree(name = "iris", aliases = {"ir", "irs"}, description = "Basic Command") -public class CommandIris implements DecreeExecutor { - private CommandStudio studio; - private CommandPregen pregen; - private CommandSettings settings; - private CommandObject object; - private CommandJigsaw jigsaw; - private CommandWhat what; - private CommandEdit edit; - private CommandFind find; - - @Decree(description = "Create a new world", aliases = {"+", "c"}) - public void create( - @Param(aliases = "world-name", description = "The name of the world to create") - String name, - @Param(aliases = "dimension", description = "The dimension type to create the world with", defaultValue = "default") - IrisDimension type, - @Param(description = "The seed to generate the world with", defaultValue = "1337") - long seed - ) { - if(name.equals("iris")) { - sender().sendMessage(C.RED + "You cannot use the world name \"iris\" for creating worlds as Iris uses this directory for studio worlds."); - sender().sendMessage(C.RED + "May we suggest the name \"IrisWorld\" instead?"); - return; - } - - if(new File(name).exists()) { - sender().sendMessage(C.RED + "That folder already exists!"); - return; - } - - sender().sendMessage(C.RED + "You should not be using this command to create new worlds. Instead, use the tutorial: https://docs.volmit.com/iris/getting-started"); - - try { - IrisToolbelt.createWorld() - .dimension(type.getLoadKey()) - .name(name) - .seed(seed) - .sender(sender()) - .studio(false) - .create(); - } catch(Throwable e) { - sender().sendMessage(C.RED + "Exception raised during creation. See the console for more details."); - Iris.error("Exception raised during world creation: " + e.getMessage()); - Iris.reportError(e); - return; - } - - sender().sendMessage(C.GREEN + "Successfully created your world!"); - } - - @Decree(description = "Print version information") - public void version() { - sender().sendMessage(C.GREEN + "Iris v" + Iris.instance.getDescription().getVersion() + " by Volmit Software"); - } - - @Decree(description = "Print world height information", origin = DecreeOrigin.PLAYER) - public void height() { - sender().sendMessage(C.GREEN + "" + sender().player().getWorld().getMinHeight() + " to " + sender().player().getWorld().getMaxHeight()); - sender().sendMessage(C.GREEN + "Total Height: " + (sender().player().getWorld().getMaxHeight() - sender().player().getWorld().getMinHeight())); - } - - @Decree(description = "Set aura spins") - public void aura( - @Param(description = "The h color value", defaultValue = "-20") - int h, - @Param(description = "The s color value", defaultValue = "7") - int s, - @Param(description = "The b color value", defaultValue = "8") - int b - ) { - IrisSettings.get().getGeneral().setSpinh(h); - IrisSettings.get().getGeneral().setSpins(s); - IrisSettings.get().getGeneral().setSpinb(b); - IrisSettings.get().forceSave(); - sender().sendMessage("Aura Spins updated to " + h + " " + s + " " + b); - } - - @Decree(description = "Bitwise calculations") - public void bitwise( - @Param(description = "The first value to run calculations on") - int value1, - @Param(description = "The operator: | & ^ ≺≺ ≻≻ %") - String operator, - @Param(description = "The second value to run calculations on") - int value2 - ) { - Integer v = null; - switch(operator) { - case "|" -> v = value1 | value2; - case "&" -> v = value1 & value2; - case "^" -> v = value1 ^ value2; - case "%" -> v = value1 % value2; - case ">>" -> v = value1 >> value2; - case "<<" -> v = value1 << value2; - } - if(v == null) { - sender().sendMessage(C.RED + "The operator you entered: (" + operator + ") is invalid!"); - return; - } - sender().sendMessage(C.GREEN + "" + value1 + " " + C.GREEN + operator.replaceAll("<", "≺").replaceAll(">", "≻").replaceAll("%", "%") + " " + C.GREEN + value2 + C.GREEN + " returns " + C.GREEN + v); - } - - @Decree(description = "Toggle debug") - public void debug( - @Param(name = "on", description = "Whether or not debug should be on", defaultValue = "other") - Boolean on - ) { - boolean to = on == null ? !IrisSettings.get().getGeneral().isDebug() : on; - IrisSettings.get().getGeneral().setDebug(to); - IrisSettings.get().forceSave(); - sender().sendMessage(C.GREEN + "Set debug to: " + to); - } - - @Decree(description = "Download a project.", aliases = "dl") - public void download( - @Param(name = "pack", description = "The pack to download", defaultValue = "overworld", aliases = "project") - String pack, - @Param(name = "branch", description = "The branch to download from", defaultValue = "main") - String branch, - @Param(name = "trim", description = "Whether or not to download a trimmed version (do not enable when editing)", defaultValue = "false") - boolean trim, - @Param(name = "overwrite", description = "Whether or not to overwrite the pack with the downloaded one", aliases = "force", defaultValue = "false") - boolean overwrite - ) { - branch = pack.equals("overworld") ? "stable" : branch; - sender().sendMessage(C.GREEN + "Downloading pack: " + pack + "/" + branch + (trim ? " trimmed" : "") + (overwrite ? " overwriting" : "")); - Iris.service(StudioSVC.class).downloadSearch(sender(), "IrisDimensions/" + pack + "/" + branch, trim, overwrite); - } - - @Decree(description = "Get metrics for your world", aliases = "measure", origin = DecreeOrigin.PLAYER) - public void metrics() { - if(!IrisToolbelt.isIrisWorld(world())) { - sender().sendMessage(C.RED + "You must be in an Iris world"); - return; - } - sender().sendMessage(C.GREEN + "Sending metrics..."); - engine().printMetrics(sender()); - } - - @Decree(description = "Reload configuration file (this is also done automatically)") - public void reload() { - IrisSettings.invalidate(); - IrisSettings.get(); - sender().sendMessage(C.GREEN + "Hotloaded settings"); - } - - @Decree(name = "regen", description = "Regenerate nearby chunks.", aliases = "rg", sync = true, origin = DecreeOrigin.PLAYER) - public void regen( - @Param(name = "radius", description = "The radius of nearby cunks", defaultValue = "5") - int radius - ) { - if(IrisToolbelt.isIrisWorld(player().getWorld())) { - VolmitSender sender = sender(); - J.a(() -> { - DecreeContext.touch(sender); - PlatformChunkGenerator plat = IrisToolbelt.access(player().getWorld()); - Engine engine = plat.getEngine(); - try { - Chunk cx = player().getLocation().getChunk(); - KList js = new KList<>(); - BurstExecutor b = MultiBurst.burst.burst(); - b.setMulticore(false); - int rad = engine.getMantle().getRealRadius(); - for(int i = -(radius + rad); i <= radius + rad; i++) { - for(int j = -(radius + rad); j <= radius + rad; j++) { - engine.getMantle().getMantle().deleteChunk(i + cx.getX(), j + cx.getZ()); - } - } - - for(int i = -radius; i <= radius; i++) { - for(int j = -radius; j <= radius; j++) { - int finalJ = j; - int finalI = i; - b.queue(() -> plat.injectChunkReplacement(player().getWorld(), finalI + cx.getX(), finalJ + cx.getZ(), (f) -> { - synchronized(js) { - js.add(f); - } - })); - } - } - - b.complete(); - sender().sendMessage(C.GREEN + "Regenerating " + Form.f(js.size()) + " Sections"); - QueueJob r = new QueueJob<>() { - final KList> futures = new KList<>(); - - @Override - public void execute(Runnable runnable) { - futures.add(J.sfut(runnable)); - - if(futures.size() > 64) { - while(futures.isNotEmpty()) { - try { - futures.remove(0).get(); - } catch(InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - } - } - } - - @Override - public String getName() { - return "Regenerating"; - } - }; - r.queue(js); - r.execute(sender()); - } catch(Throwable e) { - sender().sendMessage("Unable to parse view-distance"); - } - }); - } else { - sender().sendMessage(C.RED + "You must be in an Iris World to use regen!"); - } - } - - @Decree(description = "Update the pack of a world (UNSAFE!)", name = "^world", aliases = "update-world") - public void updateWorld( - @Param(description = "The world to update", contextual = true) - World world, - @Param(description = "The pack to install into the world", contextual = true, aliases = "dimension") - IrisDimension pack, - @Param(description = "Make sure to make a backup & read the warnings first!", defaultValue = "false", aliases = "c") - boolean confirm, - @Param(description = "Should Iris download the pack again for you", defaultValue = "false", name = "fresh-download", aliases = {"fresh", "new"}) - boolean freshDownload - ) { - if(!confirm) { - sender().sendMessage(new String[] { - C.RED + "You should always make a backup before using this", - C.YELLOW + "Issues caused by this can be, but are not limited to:", - C.YELLOW + " - Broken chunks (cut-offs) between old and new chunks (before & after the update)", - C.YELLOW + " - Regenerated chunks that do not fit in with the old chunks", - C.YELLOW + " - Structures not spawning again when regenerating", - C.YELLOW + " - Caves not lining up", - C.YELLOW + " - Terrain layers not lining up", - C.RED + "Now that you are aware of the risks, and have made a back-up:", - C.RED + "/iris ^world confirm=true" - }); - return; - } - - File folder = world.getWorldFolder(); - folder.mkdirs(); - - if(freshDownload) { - Iris.service(StudioSVC.class).downloadSearch(sender(), pack.getLoadKey(), false, true); - } - - Iris.service(StudioSVC.class).installIntoWorld(sender(), pack.getLoadKey(), folder); - } -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandJigsaw.java b/src/main/java/com/volmit/iris/core/commands/CommandJigsaw.java deleted file mode 100644 index 81e08ab90..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandJigsaw.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.edit.JigsawEditor; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.jigsaw.PlannedStructure; -import com.volmit.iris.engine.object.IrisJigsawPiece; -import com.volmit.iris.engine.object.IrisJigsawStructure; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.decree.DecreeExecutor; -import com.volmit.iris.util.decree.DecreeOrigin; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.decree.specialhandlers.ObjectHandler; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; - -import java.io.File; - -@Decree(name = "jigsaw", origin = DecreeOrigin.PLAYER, studio = true, description = "Iris jigsaw commands") -public class CommandJigsaw implements DecreeExecutor { - @Decree(description = "Edit a jigsaw piece") - public void edit( - @Param(description = "The jigsaw piece to edit") - IrisJigsawPiece piece - ) { - File dest = piece.getLoadFile(); - new JigsawEditor(player(), piece, IrisData.loadAnyObject(piece.getObject()), dest); - } - - @Decree(description = "Place a jigsaw structure") - public void place( - @Param(description = "The jigsaw structure to place") - IrisJigsawStructure structure - ) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - PlannedStructure ps = new PlannedStructure(structure, new IrisPosition(player().getLocation()), new RNG()); - sender().sendMessage(C.GREEN + "Generated " + ps.getPieces().size() + " pieces in " + Form.duration(p.getMilliseconds(), 2)); - ps.place(world()); - } - - @Decree(description = "Create a jigsaw piece") - public void create( - @Param(description = "The name of the jigsaw piece") - String piece, - @Param(description = "The project to add the jigsaw piece to") - String project, - @Param(description = "The object to use for this piece", customHandler = ObjectHandler.class) - String object - ) { - IrisObject o = IrisData.loadAnyObject(object); - - if(object == null) { - sender().sendMessage(C.RED + "Failed to find existing object"); - return; - } - - File dest = Iris.instance.getDataFile("packs", project, "jigsaw-pieces", piece + ".json"); - new JigsawEditor(player(), null, o, dest); - sender().sendMessage(C.GRAY + "* Right Click blocks to make them connectors"); - sender().sendMessage(C.GRAY + "* Right Click connectors to orient them"); - sender().sendMessage(C.GRAY + "* Shift + Right Click connectors to remove them"); - sender().sendMessage(C.GREEN + "Remember to use /iris jigsaw save"); - } - - @Decree(description = "Exit the current jigsaw editor") - public void exit() { - JigsawEditor editor = JigsawEditor.editors.get(player()); - - if(editor == null) { - sender().sendMessage(C.GOLD + "You don't have any pieces open to exit!"); - return; - } - - editor.exit(); - sender().sendMessage(C.GREEN + "Exited Jigsaw Editor"); - } - - @Decree(description = "Save & Exit the current jigsaw editor") - public void save() { - JigsawEditor editor = JigsawEditor.editors.get(player()); - - if(editor == null) { - sender().sendMessage(C.GOLD + "You don't have any pieces open to save!"); - return; - } - - editor.close(); - sender().sendMessage(C.GREEN + "Saved & Exited Jigsaw Editor"); - } -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandObject.java b/src/main/java/com/volmit/iris/core/commands/CommandObject.java deleted file mode 100644 index 4f6c2d15e..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandObject.java +++ /dev/null @@ -1,530 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.link.WorldEditLink; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.service.ObjectSVC; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.core.service.WandSVC; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IObjectPlacer; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.IrisObjectPlacementScaleInterpolator; -import com.volmit.iris.engine.object.IrisObjectRotation; -import com.volmit.iris.engine.object.TileData; -import com.volmit.iris.util.data.Cuboid; -import com.volmit.iris.util.decree.DecreeExecutor; -import com.volmit.iris.util.decree.DecreeOrigin; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.decree.specialhandlers.ObjectHandler; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.math.Direction; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.Queue; -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; - -import java.io.File; -import java.io.IOException; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - -@Decree(name = "object", aliases = "o", origin = DecreeOrigin.PLAYER, studio = true, description = "Iris object manipulation") -public class CommandObject implements DecreeExecutor { - - private static final Set skipBlocks = Set.of(Material.GRASS, Material.SNOW, Material.VINE, Material.TORCH, Material.DEAD_BUSH, - Material.POPPY, Material.DANDELION); - - public static IObjectPlacer createPlacer(World world, Map futureBlockChanges) { - - return new IObjectPlacer() { - @Override - public int getHighest(int x, int z, IrisData data) { - return world.getHighestBlockYAt(x, z); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return world.getHighestBlockYAt(x, z, ignoreFluid ? HeightMap.OCEAN_FLOOR : HeightMap.MOTION_BLOCKING); - } - - @Override - public void set(int x, int y, int z, BlockData d) { - Block block = world.getBlockAt(x, y, z); - - //Prevent blocks being set in or bellow bedrock - if(y <= world.getMinHeight() || block.getType() == Material.BEDROCK) return; - - futureBlockChanges.put(block, block.getBlockData()); - - block.setBlockData(d); - } - - @Override - public BlockData get(int x, int y, int z) { - return world.getBlockAt(x, y, z).getBlockData(); - } - - @Override - public boolean isPreventingDecay() { - return false; - } - - @Override - public boolean isCarved(int x, int y, int z) { - return false; - } - - @Override - public boolean isSolid(int x, int y, int z) { - return world.getBlockAt(x, y, z).getType().isSolid(); - } - - @Override - public boolean isUnderwater(int x, int z) { - return false; - } - - @Override - public int getFluidHeight() { - return 63; - } - - @Override - public boolean isDebugSmartBore() { - return false; - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - BlockState state = world.getBlockAt(xx, yy, zz).getState(); - tile.toBukkitTry(state); - state.update(); - } - - @Override - public Engine getEngine() { - return null; - } - }; - } - - @Decree(description = "Check the composition of an object") - public void analyze( - @Param(description = "The object to analyze", customHandler = ObjectHandler.class) - String object - ) { - IrisObject o = IrisData.loadAnyObject(object); - sender().sendMessage("Object Size: " + o.getW() + " * " + o.getH() + " * " + o.getD() + ""); - sender().sendMessage("Blocks Used: " + NumberFormat.getIntegerInstance().format(o.getBlocks().size())); - - Queue queue = o.getBlocks().enqueueValues(); - Map> unsorted = new HashMap<>(); - Map amounts = new HashMap<>(); - Map materials = new HashMap<>(); - while(queue.hasNext()) { - BlockData block = queue.next(); - - //unsorted.put(block.getMaterial(), block); - - if(!amounts.containsKey(block)) { - amounts.put(block, 1); - - - } else - amounts.put(block, amounts.get(block) + 1); - - if(!materials.containsKey(block.getMaterial())) { - materials.put(block.getMaterial(), 1); - unsorted.put(block.getMaterial(), new HashSet<>()); - unsorted.get(block.getMaterial()).add(block); - } else { - materials.put(block.getMaterial(), materials.get(block.getMaterial()) + 1); - unsorted.get(block.getMaterial()).add(block); - } - - } - - List sortedMatsList = amounts.keySet().stream().map(BlockData::getMaterial) - .sorted().collect(Collectors.toList()); - Set sortedMats = new TreeSet<>(Comparator.comparingInt(materials::get).reversed()); - sortedMats.addAll(sortedMatsList); - sender().sendMessage("== Blocks in object =="); - - int n = 0; - for(Material mat : sortedMats) { - int amount = materials.get(mat); - List set = new ArrayList<>(unsorted.get(mat)); - set.sort(Comparator.comparingInt(amounts::get).reversed()); - BlockData data = set.get(0); - int dataAmount = amounts.get(data); - - String string = " - " + mat.toString() + "*" + amount; - if(data.getAsString(true).contains("[")) { - string = string + " --> [" + data.getAsString(true).split("\\[")[1] - .replaceAll("true", ChatColor.GREEN + "true" + ChatColor.GRAY) - .replaceAll("false", ChatColor.RED + "false" + ChatColor.GRAY) + "*" + dataAmount; - } - - sender().sendMessage(string); - - n++; - - if(n >= 10) { - sender().sendMessage(" + " + (sortedMats.size() - n) + " other block types"); - return; - } - } - } - - @Decree(description = "Get a powder that reveals objects", studio = true, aliases = "d") - public void dust() { - player().getInventory().addItem(WandSVC.createDust()); - sender().playSound(Sound.AMBIENT_SOUL_SAND_VALLEY_ADDITIONS, 1f, 1.5f); - } - - @Decree(description = "Contract a selection based on your looking direction", aliases = "-") - public void contract( - @Param(description = "The amount to inset by", defaultValue = "1") - int amount - ) { - if(!WandSVC.isHoldingWand(player())) { - sender().sendMessage("Hold your wand."); - return; - } - - - Location[] b = WandSVC.getCuboid(player()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); - Direction d = Direction.closest(player().getLocation().getDirection()).reverse(); - assert d != null; - cursor = cursor.expand(d, -amount); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - player().getInventory().setItemInMainHand(WandSVC.createWand(b[0], b[1])); - player().updateInventory(); - sender().playSound(Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); - } - - @Decree(description = "Set point 1 to look", aliases = "p1") - public void position1( - @Param(description = "Whether to use your current position, or where you look", defaultValue = "true") - boolean here - ) { - if(!WandSVC.isHoldingWand(player())) { - sender().sendMessage("Ready your Wand."); - return; - } - - if(WandSVC.isHoldingWand(player())) { - Location[] g = WandSVC.getCuboid(player()); - - if(!here) { - // TODO: WARNING HEIGHT - g[1] = player().getTargetBlock(null, 256).getLocation().clone(); - } else { - g[1] = player().getLocation().getBlock().getLocation().clone().add(0, -1, 0); - } - player().setItemInHand(WandSVC.createWand(g[0], g[1])); - } - } - - @Decree(description = "Set point 2 to look", aliases = "p2") - public void position2( - @Param(description = "Whether to use your current position, or where you look", defaultValue = "true") - boolean here - ) { - if(!WandSVC.isHoldingWand(player())) { - sender().sendMessage("Ready your Wand."); - return; - } - - if(WandSVC.isHoldingIrisWand(player())) { - Location[] g = WandSVC.getCuboid(player()); - - if(!here) { - // TODO: WARNING HEIGHT - g[0] = player().getTargetBlock(null, 256).getLocation().clone(); - } else { - g[0] = player().getLocation().getBlock().getLocation().clone().add(0, -1, 0); - } - player().setItemInHand(WandSVC.createWand(g[0], g[1])); - } - } - - @Decree(description = "Paste an object", sync = true) - public void paste( - @Param(description = "The object to paste", customHandler = ObjectHandler.class) - String object, - @Param(description = "Whether or not to edit the object (need to hold wand)", defaultValue = "false") - boolean edit, - @Param(description = "The amount of degrees to rotate by", defaultValue = "0") - int rotate, - @Param(description = "The factor by which to scale the object placement", defaultValue = "1") - double scale -// , -// @Param(description = "The scale interpolator to use", defaultValue = "none") -// IrisObjectPlacementScaleInterpolator interpolator - ) { - IrisObject o = IrisData.loadAnyObject(object); - double maxScale = Double.max(10 - o.getBlocks().size() / 10000d, 1); - if(scale > maxScale) { - sender().sendMessage(C.YELLOW + "Indicated scale exceeds maximum. Downscaled to maximum: " + maxScale); - scale = maxScale; - } - - sender().playSound(Sound.BLOCK_ENCHANTMENT_TABLE_USE, 1f, 1.5f); - - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.setRotation(IrisObjectRotation.of(0, rotate, 0)); - - ItemStack wand = player().getInventory().getItemInMainHand(); - Location block = player().getTargetBlock(skipBlocks, 256).getLocation().clone().add(0, 1, 0); - - Map futureChanges = new HashMap<>(); - - if(scale != 1) - { - o = o.scaled(scale, IrisObjectPlacementScaleInterpolator.TRICUBIC); - } - - o.place(block.getBlockX(), block.getBlockY() + (int) o.getCenter().getY(), block.getBlockZ(), createPlacer(block.getWorld(), futureChanges), placement, new RNG(), null); - - Iris.service(ObjectSVC.class).addChanges(futureChanges); - - if(edit) { - ItemStack newWand = WandSVC.createWand(block.clone().subtract(o.getCenter()).add(o.getW() - 1, - o.getH() + o.getCenter().clone().getY() - 1, o.getD() - 1), block.clone().subtract(o.getCenter().clone().setY(0))); - if(WandSVC.isWand(wand)) { - wand = newWand; - player().getInventory().setItemInMainHand(wand); - sender().sendMessage("Updated wand for " + "objects/" + o.getLoadKey() + ".iob "); - } else { - int slot = WandSVC.findWand(player().getInventory()); - if(slot == -1) { - player().getInventory().addItem(newWand); - sender().sendMessage("Given new wand for " + "objects/" + o.getLoadKey() + ".iob "); - } else { - player().getInventory().setItem(slot, newWand); - sender().sendMessage("Updated wand for " + "objects/" + o.getLoadKey() + ".iob "); - } - } - } else { - sender().sendMessage("Placed " + object); - } - } - - @Decree(description = "Save an object") - public void save( - @Param(description = "The dimension to store the object in", contextual = true) - IrisDimension dimension, - @Param(description = "The file to store it in, can use / for subfolders") - String name, - @Param(description = "Overwrite existing object files", defaultValue = "false", aliases = "force") - boolean overwrite - ) { - IrisObject o = WandSVC.createSchematic(player()); - - if(o == null) { - sender().sendMessage(C.YELLOW + "You need to hold your wand!"); - return; - } - - File file = Iris.service(StudioSVC.class).getWorkspaceFile(dimension.getLoadKey(), "objects", name + ".iob"); - - if(file.exists() && !overwrite) { - sender().sendMessage(C.RED + "File already exists. Set overwrite=true to overwrite it."); - return; - } - try { - o.write(file); - } catch(IOException e) { - sender().sendMessage(C.RED + "Failed to save object because of an IOException: " + e.getMessage()); - Iris.reportError(e); - } - - sender().playSound(Sound.BLOCK_ENCHANTMENT_TABLE_USE, 1f, 1.5f); - sender().sendMessage(C.GREEN + "Successfully object to saved: " + dimension.getLoadKey() + "/objects/" + name); - } - - @Decree(description = "Shift a selection in your looking direction", aliases = "-") - public void shift( - @Param(description = "The amount to shift by", defaultValue = "1") - int amount - ) { - if(!WandSVC.isHoldingWand(player())) { - sender().sendMessage("Hold your wand."); - return; - } - - Location[] b = WandSVC.getCuboid(player()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Direction d = Direction.closest(player().getLocation().getDirection()).reverse(); - a1.add(d.toVector().multiply(amount)); - a2.add(d.toVector().multiply(amount)); - Cuboid cursor = new Cuboid(a1, a2); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - player().getInventory().setItemInMainHand(WandSVC.createWand(b[0], b[1])); - player().updateInventory(); - sender().playSound(Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); - } - - @Decree(description = "Undo a number of pastes", aliases = "-") - public void undo( - @Param(description = "The amount of pastes to undo", defaultValue = "1") - int amount - ) { - ObjectSVC service = Iris.service(ObjectSVC.class); - int actualReverts = Math.min(service.getUndos().size(), amount); - service.revertChanges(actualReverts); - sender().sendMessage("Reverted " + actualReverts + " pastes!"); - } - - @Decree(description = "Gets an object wand and grabs the current WorldEdit selection.", aliases = "we", origin = DecreeOrigin.PLAYER, studio = true) - public void we() { - if(!Bukkit.getPluginManager().isPluginEnabled("WorldEdit")) { - sender().sendMessage(C.RED + "You can't get a WorldEdit selection without WorldEdit, you know."); - return; - } - - Cuboid locs = WorldEditLink.getSelection(sender().player()); - - if(locs == null) - { - sender().sendMessage(C.RED + "You don't have a WorldEdit selection in this world."); - return; - } - - sender().player().getInventory().addItem(WandSVC.createWand(locs.getLowerNE(), locs.getUpperSW())); - sender().sendMessage(C.GREEN + "A fresh wand with your current WorldEdit selection on it!"); - } - - @Decree(description = "Get an object wand", sync = true) - public void wand() { - player().getInventory().addItem(WandSVC.createWand()); - sender().playSound(Sound.ITEM_ARMOR_EQUIP_NETHERITE, 1f, 1.5f); - sender().sendMessage(C.GREEN + "Poof! Good luck building!"); - } - - @Decree(name = "x&y", description = "Autoselect up, down & out", sync = true) - public void xay() { - if(!WandSVC.isHoldingWand(player())) { - sender().sendMessage(C.YELLOW + "Hold your wand!"); - return; - } - - Location[] b = WandSVC.getCuboid(player()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Location a1x = b[0].clone(); - Location a2x = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); - Cuboid cursorx = new Cuboid(a1, a2); - - while(!cursor.containsOnly(Material.AIR)) { - a1.add(new org.bukkit.util.Vector(0, 1, 0)); - a2.add(new org.bukkit.util.Vector(0, 1, 0)); - cursor = new Cuboid(a1, a2); - } - - a1.add(new org.bukkit.util.Vector(0, -1, 0)); - a2.add(new org.bukkit.util.Vector(0, -1, 0)); - - while(!cursorx.containsOnly(Material.AIR)) { - a1x.add(new org.bukkit.util.Vector(0, -1, 0)); - a2x.add(new org.bukkit.util.Vector(0, -1, 0)); - cursorx = new Cuboid(a1x, a2x); - } - - a1x.add(new org.bukkit.util.Vector(0, 1, 0)); - a2x.add(new Vector(0, 1, 0)); - b[0] = a1; - b[1] = a2x; - cursor = new Cuboid(b[0], b[1]); - cursor = cursor.contract(Cuboid.CuboidDirection.North); - cursor = cursor.contract(Cuboid.CuboidDirection.South); - cursor = cursor.contract(Cuboid.CuboidDirection.East); - cursor = cursor.contract(Cuboid.CuboidDirection.West); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - player().getInventory().setItemInMainHand(WandSVC.createWand(b[0], b[1])); - player().updateInventory(); - sender().playSound(Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); - sender().sendMessage(C.GREEN + "Auto-select complete!"); - } - - @Decree(name = "x+y", description = "Autoselect up & out", sync = true) - public void xpy() { - if(!WandSVC.isHoldingWand(player())) { - sender().sendMessage(C.YELLOW + "Hold your wand!"); - return; - } - - Location[] b = WandSVC.getCuboid(player()); - b[0].add(new Vector(0, 1, 0)); - b[1].add(new Vector(0, 1, 0)); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); - - while(!cursor.containsOnly(Material.AIR)) { - a1.add(new Vector(0, 1, 0)); - a2.add(new Vector(0, 1, 0)); - cursor = new Cuboid(a1, a2); - } - - a1.add(new Vector(0, -1, 0)); - a2.add(new Vector(0, -1, 0)); - b[0] = a1; - a2 = b[1]; - cursor = new Cuboid(a1, a2); - cursor = cursor.contract(Cuboid.CuboidDirection.North); - cursor = cursor.contract(Cuboid.CuboidDirection.South); - cursor = cursor.contract(Cuboid.CuboidDirection.East); - cursor = cursor.contract(Cuboid.CuboidDirection.West); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - player().getInventory().setItemInMainHand(WandSVC.createWand(b[0], b[1])); - player().updateInventory(); - sender().playSound(Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); - sender().sendMessage(C.GREEN + "Auto-select complete!"); - } -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandPregen.java b/src/main/java/com/volmit/iris/core/commands/CommandPregen.java deleted file mode 100644 index 6d48640ae..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandPregen.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.gui.PregeneratorJob; -import com.volmit.iris.core.pregenerator.PregenTask; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.util.decree.DecreeExecutor; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.math.Position2; -import org.bukkit.World; -import org.bukkit.util.Vector; - -@Decree(name = "pregen", aliases = "pregenerate", description = "Pregenerate your Iris worlds!") -public class CommandPregen implements DecreeExecutor { - @Decree(description = "Pregenerate a world") - public void start( - @Param(description = "The radius of the pregen in blocks", aliases = "size") - int radius, - @Param(description = "The world to pregen", contextual = true) - World world, - @Param(aliases = "middle", description = "The center location of the pregen. Use \"me\" for your current location", defaultValue = "0,0") - Vector center - ) { - try { - if(sender().isPlayer() && access() == null) { - sender().sendMessage(C.RED + "The engine access for this world is null!"); - sender().sendMessage(C.RED + "Please make sure the world is loaded & the engine is initialized. Generate a new chunk, for example."); - } - radius = Math.max(radius, 1024); - int w = (radius >> 9 + 1) * 2; - IrisToolbelt.pregenerate(PregenTask - .builder() - .center(new Position2(center)) - .width(w) - .height(w) - .build(), world); - String msg = C.GREEN + "Pregen started in " + C.GOLD + world.getName() + C.GREEN + " of " + C.GOLD + (radius * 2) + C.GREEN + " by " + C.GOLD + (radius * 2) + C.GREEN + " blocks from " + C.GOLD + center.getX() + "," + center.getZ(); - sender().sendMessage(msg); - Iris.info(msg); - } catch(Throwable e) { - sender().sendMessage(C.RED + "Epic fail. See console."); - Iris.reportError(e); - e.printStackTrace(); - } - } - - @Decree(description = "Stop the active pregeneration task", aliases = "x") - public void stop() { - if(PregeneratorJob.shutdownInstance()) { - sender().sendMessage(C.GREEN + "Stopped pregeneration task"); - } else { - sender().sendMessage(C.YELLOW + "No active pregeneration tasks to stop"); - } - } - - @Decree(description = "Pause / continue the active pregeneration task", aliases = {"t", "resume", "unpause"}) - public void pause() { - if(PregeneratorJob.pauseResume()) { - sender().sendMessage(C.GREEN + "Paused/unpaused pregeneration task, now: " + (PregeneratorJob.isPaused() ? "Paused" : "Running") + "."); - } else { - sender().sendMessage(C.YELLOW + "No active pregeneration tasks to pause/unpause."); - } - } -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandSettings.java b/src/main/java/com/volmit/iris/core/commands/CommandSettings.java deleted file mode 100644 index e1da7efd7..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandSettings.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.util.decree.DecreeExecutor; - -public class CommandSettings implements DecreeExecutor { - -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandStudio.java b/src/main/java/com/volmit/iris/core/commands/CommandStudio.java deleted file mode 100644 index 4bc370c21..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandStudio.java +++ /dev/null @@ -1,900 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.gui.NoiseExplorerGUI; -import com.volmit.iris.core.gui.VisionGUI; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.project.IrisProject; -import com.volmit.iris.core.service.ConversionSVC; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.InventorySlotType; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisBiomePaletteLayer; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisEntity; -import com.volmit.iris.engine.object.IrisGenerator; -import com.volmit.iris.engine.object.IrisInterpolator; -import com.volmit.iris.engine.object.IrisLootTable; -import com.volmit.iris.engine.object.IrisNoiseGenerator; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.engine.object.IrisScript; -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.decree.DecreeExecutor; -import com.volmit.iris.util.decree.DecreeOrigin; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.NoiseProvider; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONArray; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.math.Spiraler; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.O; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import com.volmit.iris.util.scheduling.jobs.Job; -import com.volmit.iris.util.scheduling.jobs.JobCollection; -import com.volmit.iris.util.scheduling.jobs.QueueJob; -import com.volmit.iris.util.scheduling.jobs.SingleJob; -import io.papermc.lib.PaperLib; - -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.FluidCollisionMode; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.util.BlockVector; -import org.bukkit.util.Vector; - -import java.awt.*; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.attribute.FileTime; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.Date; -import java.util.Objects; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.function.Consumer; -import java.util.function.Supplier; - -@Decree(name = "studio", aliases = {"std", "s"}, description = "Studio Commands", studio = true) -public class CommandStudio implements DecreeExecutor { - public static String hrf(Duration duration) { - return duration.toString().substring(2).replaceAll("(\\d[HMS])(?!$)", "$1 ").toLowerCase(); - } - - private CommandFind find; - private CommandEdit edit; - - - @Decree(description = "Download a project.", aliases = "dl") - public void download( - @Param(name = "pack", description = "The pack to download", defaultValue = "overworld", aliases = "project") - String pack, - @Param(name = "branch", description = "The branch to download from", defaultValue = "master") - String branch, - @Param(name = "trim", description = "Whether or not to download a trimmed version (do not enable when editing)", defaultValue = "false") - boolean trim, - @Param(name = "overwrite", description = "Whether or not to overwrite the pack with the downloaded one", aliases = "force", defaultValue = "false") - boolean overwrite - ) { - new CommandIris().download(pack, branch, trim, overwrite); - } - - @Decree(description = "Open a new studio world", aliases = "o", sync = true) - public void open( - @Param(defaultValue = "default", description = "The dimension to open a studio for", aliases = "dim") - IrisDimension dimension, - @Param(defaultValue = "1337", description = "The seed to generate the studio with", aliases = "s") - long seed) { - sender().sendMessage(C.GREEN + "Opening studio for the \"" + dimension.getName() + "\" pack (seed: " + seed + ")"); - Iris.service(StudioSVC.class).open(sender(), seed, dimension.getLoadKey()); - } - - @Decree(description = "Open VSCode for a dimension", aliases = {"vsc", "edit"}) - public void vscode( - @Param(defaultValue = "default", description = "The dimension to open VSCode for", aliases = "dim") - IrisDimension dimension - ) { - sender().sendMessage(C.GREEN + "Opening VSCode for the \"" + dimension.getName() + "\" pack"); - Iris.service(StudioSVC.class).openVSCode(sender(), dimension.getLoadKey()); - } - - @Decree(description = "Close an open studio project", aliases = {"x", "c"}, sync = true) - public void close() { - if(!Iris.service(StudioSVC.class).isProjectOpen()) { - sender().sendMessage(C.RED + "No open studio projects."); - return; - } - - Iris.service(StudioSVC.class).close(); - sender().sendMessage(C.GREEN + "Project Closed."); - } - - @Decree(description = "Create a new studio project", aliases = "+", sync = true) - public void create( - @Param(description = "The name of this new Iris Project.") - String name, - @Param(description = "Copy the contents of an existing project in your packs folder and use it as a template in this new project.", contextual = true) - IrisDimension template) { - if(template != null) { - Iris.service(StudioSVC.class).create(sender(), name, template.getLoadKey()); - } else { - Iris.service(StudioSVC.class).create(sender(), name); - } - } - - @Decree(description = "Clean an Iris Project, optionally beautifying JSON & fixing block ids with missing keys. Also rebuilds the vscode schemas. ") - public void clean( - @Param(description = "The project to update", contextual = true) - IrisDimension project, - - @Param(defaultValue = "true", description = "Filters all valid JSON files with a beautifier (indentation: 4)") - boolean beautify, - - @Param(name = "fix-ids", defaultValue = "true", description = "Fixes any block ids used such as \"dirt\" will be converted to \"minecraft:dirt\"") - boolean fixIds, - - @Param(name = "rewrite-objects", defaultValue = "false", description = "Imports all objects and re-writes them cleaning up positions & block data in the process.") - boolean rewriteObjects - ) { - KList jobs = new KList<>(); - KList files = new KList(); - files(Iris.instance.getDataFolder("packs", project.getLoadKey()), files); - MultiBurst burst = MultiBurst.burst; - - jobs.add(new SingleJob("Updating Workspace", () -> { - if(!new IrisProject(Iris.service(StudioSVC.class).getWorkspaceFolder(project.getLoadKey())).updateWorkspace()) { - sender().sendMessage(C.GOLD + "Invalid project: " + project.getLoadKey() + ". Try deleting the code-workspace file and try again."); - } - J.sleep(250); - })); - - sender().sendMessage("Files: " + files.size()); - - if(fixIds) { - QueueJob r = new QueueJob<>() { - @Override - public void execute(File f) { - try { - JSONObject p = new JSONObject(IO.readAll(f)); - fixBlocks(p); - J.sleep(1); - IO.writeAll(f, p.toString(4)); - - } catch(IOException e) { - e.printStackTrace(); - } - } - - @Override - public String getName() { - return "Fixing IDs"; - } - }; - - r.queue(files); - jobs.add(r); - } - - if(beautify) { - QueueJob r = new QueueJob<>() { - @Override - public void execute(File f) { - try { - JSONObject p = new JSONObject(IO.readAll(f)); - IO.writeAll(f, p.toString(4)); - J.sleep(1); - } catch(IOException e) { - e.printStackTrace(); - } - } - - @Override - public String getName() { - return "Beautify"; - } - }; - - r.queue(files); - jobs.add(r); - } - - if(rewriteObjects) { - QueueJob q = new QueueJob<>() { - @Override - public void execute(Runnable runnable) { - runnable.run(); - J.sleep(50); - } - - @Override - public String getName() { - return "Rewriting Objects"; - } - }; - - IrisData data = IrisData.get(Iris.service(StudioSVC.class).getWorkspaceFolder(project.getLoadKey())); - for(String f : data.getObjectLoader().getPossibleKeys()) { - Future gg = burst.complete(() -> { - File ff = data.getObjectLoader().findFile(f); - IrisObject oo = new IrisObject(0, 0, 0); - try { - oo.read(ff); - } catch(Throwable e) { - Iris.error("FAILER TO READ: " + f); - return; - } - - try { - oo.write(ff); - } catch(IOException e) { - Iris.error("FAILURE TO WRITE: " + oo.getLoadFile()); - } - }); - - q.queue(() -> { - try { - gg.get(); - } catch(InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - }); - } - - jobs.add(q); - } - - new JobCollection("Cleaning", jobs).execute(sender()); - } - - @Decree(description = "Get the version of a pack") - public void version( - @Param(defaultValue = "default", description = "The dimension get the version of", aliases = "dim", contextual = true) - IrisDimension dimension - ) { - sender().sendMessage(C.GREEN + "The \"" + dimension.getName() + "\" pack has version: " + dimension.getVersion()); - } - - @Decree(description = "Convert objects in the \"convert\" folder") - public void convert() { - Iris.service(ConversionSVC.class).check(sender()); - } - - - @Decree(description = "Execute a script", aliases = "run", origin = DecreeOrigin.PLAYER) - public void execute( - @Param(description = "The script to run") - IrisScript script - ) { - engine().getExecution().execute(script.getLoadKey()); - } - - @Decree(description = "Open the noise explorer (External GUI)", aliases = {"nmap", "n"}) - public void noise() { - if(noGUI()) return; - sender().sendMessage(C.GREEN + "Opening Noise Explorer!"); - NoiseExplorerGUI.launch(); - } - - @Decree(description = "Charges all spawners in the area", aliases = "zzt", origin = DecreeOrigin.PLAYER) - public void charge() { - if(!IrisToolbelt.isIrisWorld(world())) { - sender().sendMessage(C.RED + "You must be in an Iris world to charge spawners!"); - return; - } - sender().sendMessage(C.GREEN + "Charging spawners!"); - engine().getWorldManager().chargeEnergy(); - } - - @Decree(description = "Preview noise gens (External GUI)", aliases = {"generator", "gen"}) - public void explore( - @Param(description = "The generator to explore", contextual = true) - IrisGenerator generator, - @Param(description = "The seed to generate with", defaultValue = "12345") - long seed - ) { - if(noGUI()) return; - sender().sendMessage(C.GREEN + "Opening Noise Explorer!"); - - Supplier> l = () -> { - - if(generator == null) { - return (x, z) -> 0D; - } - - return (x, z) -> generator.getHeight(x, z, new RNG(seed).nextParallelRNG(3245).lmax()); - }; - NoiseExplorerGUI.launch(l, "Custom Generator"); - } - - @Decree(description = "Hotload a studio", aliases = {"reload", "h"}) - public void hotload() { - if(!Iris.service(StudioSVC.class).isProjectOpen()) { - sender().sendMessage(C.RED + "No studio world open!"); - return; - } - Iris.service(StudioSVC.class).getActiveProject().getActiveProvider().getEngine().hotload(); - sender().sendMessage(C.GREEN + "Hotloaded"); - } - - @Decree(description = "Show loot if a chest were right here", origin = DecreeOrigin.PLAYER, sync = true) - public void loot( - @Param(description = "Fast insertion of items in virtual inventory (may cause performance drop)", defaultValue = "false") - boolean fast, - @Param(description = "Whether or not to append to the inventory currently open (if false, clears opened inventory)", defaultValue = "true") - boolean add - ) { - if(noStudio()) return; - - KList tables = engine().getLootTables(RNG.r, player().getLocation().getBlock()); - Inventory inv = Bukkit.createInventory(null, 27 * 2); - - try { - engine().addItems(true, inv, RNG.r, tables, InventorySlotType.STORAGE, player().getLocation().getBlockX(), player().getLocation().getBlockY(), player().getLocation().getBlockZ(), 1); - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage(C.RED + "Cannot add items to virtual inventory because of: " + e.getMessage()); - return; - } - - - O ta = new O<>(); - ta.set(-1); - - ta.set(Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, () -> - { - if(!player().getOpenInventory().getType().equals(InventoryType.CHEST)) { - Bukkit.getScheduler().cancelTask(ta.get()); - sender().sendMessage(C.GREEN + "Opened inventory!"); - return; - } - - if(!add) { - inv.clear(); - } - - engine().addItems(true, inv, new RNG(RNG.r.imax()), tables, InventorySlotType.STORAGE, player().getLocation().getBlockX(), player().getLocation().getBlockY(), player().getLocation().getBlockZ(), 1); - }, 0, fast ? 5 : 35)); - - sender().sendMessage(C.GREEN + "Opening inventory now!"); - player().openInventory(inv); - } - - @Decree(description = "Render a world map (External GUI)", aliases = "render") - public void map( - @Param(name = "world", description = "The world to open the generator for", contextual = true) - World world - ) { - if(noGUI()) return; - - if(!IrisToolbelt.isIrisWorld(world)) { - sender().sendMessage(C.RED + "You need to be in or specify an Iris-generated world!"); - return; - } - - VisionGUI.launch(IrisToolbelt.access(world).getEngine(), 0); - sender().sendMessage(C.GREEN + "Opening map!"); - } - - @Decree(description = "Package a dimension into a compressed format", aliases = "package") - public void pkg( - @Param(name = "dimension", description = "The dimension pack to compress", contextual = true, defaultValue = "default") - IrisDimension dimension, - @Param(name = "obfuscate", description = "Whether or not to obfuscate the pack", defaultValue = "false") - boolean obfuscate, - @Param(name = "minify", description = "Whether or not to minify the pack", defaultValue = "true") - boolean minify - ) { - Iris.service(StudioSVC.class).compilePackage(sender(), dimension.getLoadKey(), obfuscate, minify); - } - - @Decree(description = "Profiles the performance of a dimension", origin = DecreeOrigin.PLAYER) - public void profile( - @Param(description = "The dimension to profile", contextual = true, defaultValue = "default") - IrisDimension dimension - ) { - File pack = dimension.getLoadFile().getParentFile().getParentFile(); - File report = Iris.instance.getDataFile("profile.txt"); - IrisProject project = new IrisProject(pack); - IrisData data = IrisData.get(pack); - - KList fileText = new KList<>(); - - KMap styleTimings = new KMap<>(); - KMap interpolatorTimings = new KMap<>(); - KMap generatorTimings = new KMap<>(); - KMap biomeTimings = new KMap<>(); - KMap regionTimings = new KMap<>(); - - sender().sendMessage("Calculating Performance Metrics for Noise generators"); - - for(NoiseStyle i : NoiseStyle.values()) { - CNG c = i.create(new RNG(i.hashCode())); - - for(int j = 0; j < 3000; j++) { - c.noise(j, j + 1000, j * j); - c.noise(j, -j); - } - - PrecisionStopwatch px = PrecisionStopwatch.start(); - - for(int j = 0; j < 100000; j++) { - c.noise(j, j + 1000, j * j); - c.noise(j, -j); - } - - styleTimings.put(i, px.getMilliseconds()); - } - - fileText.add("Noise Style Performance Impacts: "); - - for(NoiseStyle i : styleTimings.sortKNumber()) { - fileText.add(i.name() + ": " + styleTimings.get(i)); - } - - fileText.add(""); - - sender().sendMessage("Calculating Interpolator Timings..."); - - for(InterpolationMethod i : InterpolationMethod.values()) { - IrisInterpolator in = new IrisInterpolator(); - in.setFunction(i); - in.setHorizontalScale(8); - - NoiseProvider np = (x, z) -> Math.random(); - - for(int j = 0; j < 3000; j++) { - in.interpolate(j, -j, np); - } - - PrecisionStopwatch px = PrecisionStopwatch.start(); - - for(int j = 0; j < 100000; j++) { - in.interpolate(j + 10000, -j - 100000, np); - } - - interpolatorTimings.put(i, px.getMilliseconds()); - } - - fileText.add("Noise Interpolator Performance Impacts: "); - - for(InterpolationMethod i : interpolatorTimings.sortKNumber()) { - fileText.add(i.name() + ": " + interpolatorTimings.get(i)); - } - - fileText.add(""); - - sender().sendMessage("Processing Generator Scores: "); - - KMap> btx = new KMap<>(); - - for(String i : data.getGeneratorLoader().getPossibleKeys()) { - KList vv = new KList<>(); - IrisGenerator g = data.getGeneratorLoader().load(i); - KList composites = g.getAllComposites(); - double score = 0; - int m = 0; - for(IrisNoiseGenerator j : composites) { - m++; - score += styleTimings.get(j.getStyle().getStyle()); - vv.add("Composite Noise Style " + m + " " + j.getStyle().getStyle().name() + ": " + styleTimings.get(j.getStyle().getStyle())); - } - - score += interpolatorTimings.get(g.getInterpolator().getFunction()); - vv.add("Interpolator " + g.getInterpolator().getFunction().name() + ": " + interpolatorTimings.get(g.getInterpolator().getFunction())); - generatorTimings.put(i, score); - btx.put(i, vv); - } - - fileText.add("Project Generator Performance Impacts: "); - - for(String i : generatorTimings.sortKNumber()) { - fileText.add(i + ": " + generatorTimings.get(i)); - - btx.get(i).forEach((ii) -> fileText.add(" " + ii)); - } - - fileText.add(""); - - KMap> bt = new KMap<>(); - - for(String i : data.getBiomeLoader().getPossibleKeys()) { - KList vv = new KList<>(); - IrisBiome b = data.getBiomeLoader().load(i); - double score = 0; - - int m = 0; - for(IrisBiomePaletteLayer j : b.getLayers()) { - m++; - score += styleTimings.get(j.getStyle().getStyle()); - vv.add("Palette Layer " + m + ": " + styleTimings.get(j.getStyle().getStyle())); - } - - score += styleTimings.get(b.getBiomeStyle().getStyle()); - vv.add("Biome Style: " + styleTimings.get(b.getBiomeStyle().getStyle())); - score += styleTimings.get(b.getChildStyle().getStyle()); - vv.add("Child Style: " + styleTimings.get(b.getChildStyle().getStyle())); - biomeTimings.put(i, score); - bt.put(i, vv); - } - - fileText.add("Project Biome Performance Impacts: "); - - for(String i : biomeTimings.sortKNumber()) { - fileText.add(i + ": " + biomeTimings.get(i)); - - bt.get(i).forEach((ff) -> fileText.add(" " + ff)); - } - - fileText.add(""); - - for(String i : data.getRegionLoader().getPossibleKeys()) { - IrisRegion b = data.getRegionLoader().load(i); - double score = 0; - - score += styleTimings.get(b.getLakeStyle().getStyle()); - score += styleTimings.get(b.getRiverStyle().getStyle()); - regionTimings.put(i, score); - } - - fileText.add("Project Region Performance Impacts: "); - - for(String i : regionTimings.sortKNumber()) { - fileText.add(i + ": " + regionTimings.get(i)); - } - - fileText.add(""); - - double m = 0; - for(double i : biomeTimings.v()) { - m += i; - } - m /= biomeTimings.size(); - double mm = 0; - for(double i : generatorTimings.v()) { - mm += i; - } - mm /= generatorTimings.size(); - m += mm; - double mmm = 0; - for(double i : regionTimings.v()) { - mmm += i; - } - mmm /= regionTimings.size(); - m += mmm; - - fileText.add("Average Score: " + m); - sender().sendMessage("Score: " + Form.duration(m, 0)); - - try { - IO.writeAll(report, fileText.toString("\n")); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - - sender().sendMessage(C.GREEN + "Done! " + report.getPath()); - } - - @Decree(description = "Summon an Iris Entity", origin = DecreeOrigin.PLAYER) - public void summon( - @Param(description = "The Iris Entity to spawn") - IrisEntity entity, - @Param(description = "The location at which to spawn the entity", defaultValue = "self") - Vector location - ) { - if(!sender().isPlayer()) { - sender().sendMessage(C.RED + "Players only (this is a config error. Ask support to add DecreeOrigin.PLAYER to the command you tried to run)"); - return; - } - - sender().sendMessage(C.GREEN + "Spawning entity"); - entity.spawn(engine(), new Location(world(), location.getX(), location.getY(), location.getZ())); - } - - @Decree(description = "Teleport to the active studio world", aliases = "stp", origin = DecreeOrigin.PLAYER, sync = true) - public void tpstudio() { - if(!Iris.service(StudioSVC.class).isProjectOpen()) { - sender().sendMessage(C.RED + "No studio world is open!"); - return; - } - - if(IrisToolbelt.isIrisWorld(world()) && engine().isStudio()) { - sender().sendMessage(C.RED + "You are already in a studio world!"); - return; - } - - sender().sendMessage(C.GREEN + "Sending you to the studio world!"); - player().teleport(Iris.service(StudioSVC.class).getActiveProject().getActiveProvider().getTarget().getWorld().spawnLocation()); - player().setGameMode(GameMode.SPECTATOR); - } - - @Decree(description = "Update your dimension projects VSCode workspace") - public void update( - @Param(description = "The dimension to update the workspace of", contextual = true, defaultValue = "default") - IrisDimension dimension - ) { - sender().sendMessage(C.GOLD + "Updating Code Workspace for " + dimension.getName() + "..."); - if(new IrisProject(dimension.getLoader().getDataFolder()).updateWorkspace()) { - sender().sendMessage(C.GREEN + "Updated Code Workspace for " + dimension.getName()); - } else { - sender().sendMessage(C.RED + "Invalid project: " + dimension.getName() + ". Try deleting the code-workspace file and try again."); - } - } - - @Decree(aliases = "find-objects", description = "Get information about nearby structures") - public void objects() { - if(!IrisToolbelt.isIrisWorld(player().getWorld())) { - sender().sendMessage(C.RED + "You must be in an Iris world"); - return; - } - - World world = player().getWorld(); - - if(!IrisToolbelt.isIrisWorld(world)) { - sender().sendMessage("You must be in an iris world."); - return; - } - KList chunks = new KList<>(); - int bx = player().getLocation().getChunk().getX(); - int bz = player().getLocation().getChunk().getZ(); - - try { - Location l = player().getTargetBlockExact(48, FluidCollisionMode.NEVER).getLocation(); - - int cx = l.getChunk().getX(); - int cz = l.getChunk().getZ(); - new Spiraler(3, 3, (x, z) -> chunks.addIfMissing(world.getChunkAt(x + cx, z + cz))).drain(); - } catch(Throwable e) { - Iris.reportError(e); - } - - new Spiraler(3, 3, (x, z) -> chunks.addIfMissing(world.getChunkAt(x + bx, z + bz))).drain(); - sender().sendMessage("Capturing IGenData from " + chunks.size() + " nearby chunks."); - try { - File ff = Iris.instance.getDataFile("reports/" + M.ms() + ".txt"); - PrintWriter pw = new PrintWriter(ff); - pw.println("=== Iris Chunk Report ==="); - pw.println("== General Info =="); - pw.println("Iris Version: " + Iris.instance.getDescription().getVersion()); - pw.println("Bukkit Version: " + Bukkit.getBukkitVersion()); - pw.println("MC Version: " + Bukkit.getVersion()); - pw.println("PaperSpigot: " + (PaperLib.isPaper() ? "Yup!" : "Nope!")); - pw.println("Report Captured At: " + new Date()); - pw.println("Chunks: (" + chunks.size() + "): "); - - for(Chunk i : chunks) { - pw.println("- [" + i.getX() + ", " + i.getZ() + "]"); - } - - int regions = 0; - long size = 0; - String age = "No idea..."; - - try { - for(File i : Objects.requireNonNull(new File(world.getWorldFolder(), "region").listFiles())) { - if(i.isFile()) { - size += i.length(); - } - } - } catch(Throwable e) { - Iris.reportError(e); - } - - try { - FileTime creationTime = (FileTime) Files.getAttribute(world.getWorldFolder().toPath(), "creationTime"); - age = hrf(Duration.of(M.ms() - creationTime.toMillis(), ChronoUnit.MILLIS)); - } catch(IOException e) { - Iris.reportError(e); - } - - KList biomes = new KList<>(); - KList caveBiomes = new KList<>(); - KMap>> objects = new KMap<>(); - - for(Chunk i : chunks) { - for(int j = 0; j < 16; j += 3) { - - for(int k = 0; k < 16; k += 3) { - - assert engine() != null; - IrisBiome bb = engine().getSurfaceBiome((i.getX() * 16) + j, (i.getZ() * 16) + k); - IrisBiome bxf = engine().getCaveBiome((i.getX() * 16) + j, (i.getZ() * 16) + k); - biomes.addIfMissing(bb.getName() + " [" + Form.capitalize(bb.getInferredType().name().toLowerCase()) + "] " + " (" + bb.getLoadFile().getName() + ")"); - caveBiomes.addIfMissing(bxf.getName() + " (" + bxf.getLoadFile().getName() + ")"); - exportObjects(bb, pw, engine(), objects); - exportObjects(bxf, pw, engine(), objects); - } - } - } - - regions = Objects.requireNonNull(new File(world.getWorldFolder().getPath() + "/region").list()).length; - - pw.println(); - pw.println("== World Info =="); - pw.println("World Name: " + world.getName()); - pw.println("Age: " + age); - pw.println("Folder: " + world.getWorldFolder().getPath()); - pw.println("Regions: " + Form.f(regions)); - pw.println("Chunks: max. " + Form.f(regions * 32 * 32)); - pw.println("World Size: min. " + Form.fileSize(size)); - pw.println(); - pw.println("== Biome Info =="); - pw.println("Found " + biomes.size() + " Biome(s): "); - - for(String i : biomes) { - pw.println("- " + i); - } - pw.println(); - - pw.println("== Object Info =="); - - for(String i : objects.k()) { - pw.println("- " + i); - - for(String j : objects.get(i).k()) { - pw.println(" @ " + j); - - for(String k : objects.get(i).get(j)) { - pw.println(" * " + k); - } - } - } - - pw.println(); - pw.close(); - - sender().sendMessage("Reported to: " + ff.getPath()); - } catch(FileNotFoundException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - - private void exportObjects(IrisBiome bb, PrintWriter pw, Engine g, KMap>> objects) { - String n1 = bb.getName() + " [" + Form.capitalize(bb.getInferredType().name().toLowerCase()) + "] " + " (" + bb.getLoadFile().getName() + ")"; - int m = 0; - KSet stop = new KSet<>(); - for(IrisObjectPlacement f : bb.getObjects()) { - m++; - String n2 = "Placement #" + m + " (" + f.getPlace().size() + " possible objects)"; - - for(String i : f.getPlace()) { - String nn3 = i + ": [ERROR] Failed to find object!"; - - try { - if(stop.contains(i)) { - continue; - } - - File ff = g.getData().getObjectLoader().findFile(i); - BlockVector sz = IrisObject.sampleSize(ff); - nn3 = i + ": size=[" + sz.getBlockX() + "," + sz.getBlockY() + "," + sz.getBlockZ() + "] location=[" + ff.getPath() + "]"; - stop.add(i); - } catch(Throwable e) { - Iris.reportError(e); - } - - String n3 = nn3; - objects.computeIfAbsent(n1, (k1) -> new KMap<>()) - .computeIfAbsent(n2, (k) -> new KList<>()).addIfMissing(n3); - } - } - } - - /** - * @return true if server GUIs are not enabled - */ - private boolean noGUI() { - if(!IrisSettings.get().getGui().isUseServerLaunchedGuis()) { - sender().sendMessage(C.RED + "You must have server launched GUIs enabled in the settings!"); - return true; - } - return false; - } - - /** - * @return true if no studio is open or the player is not in one - */ - private boolean noStudio() { - if(!sender().isPlayer()) { - sender().sendMessage(C.RED + "Players only!"); - return true; - } - if(!Iris.service(StudioSVC.class).isProjectOpen()) { - sender().sendMessage(C.RED + "No studio world is open!"); - return true; - } - if(!engine().isStudio()) { - sender().sendMessage(C.RED + "You must be in a studio world!"); - return true; - } - return false; - } - - - public void files(File clean, KList files) { - if(clean.isDirectory()) { - for(File i : clean.listFiles()) { - files(i, files); - } - } else if(clean.getName().endsWith(".json")) { - try { - files.add(clean); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Failed to beautify " + clean.getAbsolutePath() + " You may have errors in your json!"); - } - } - } - - private void fixBlocks(JSONObject obj) { - for(String i : obj.keySet()) { - Object o = obj.get(i); - - if(i.equals("block") && o instanceof String && !o.toString().trim().isEmpty() && !o.toString().contains(":")) { - obj.put(i, "minecraft:" + o); - } - - if(o instanceof JSONObject) { - fixBlocks((JSONObject) o); - } else if(o instanceof JSONArray) { - fixBlocks((JSONArray) o); - } - } - } - - private void fixBlocks(JSONArray obj) { - for(int i = 0; i < obj.length(); i++) { - Object o = obj.get(i); - - if(o instanceof JSONObject) { - fixBlocks((JSONObject) o); - } else if(o instanceof JSONArray) { - fixBlocks((JSONArray) o); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/core/commands/CommandWhat.java b/src/main/java/com/volmit/iris/core/commands/CommandWhat.java deleted file mode 100644 index 9423ed3c5..000000000 --- a/src/main/java/com/volmit/iris/core/commands/CommandWhat.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.commands; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.edit.BlockSignal; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.decree.DecreeExecutor; -import com.volmit.iris.util.decree.DecreeOrigin; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.matter.MatterMarker; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Chunk; -import org.bukkit.FluidCollisionMode; -import org.bukkit.Material; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -import java.util.concurrent.atomic.AtomicInteger; - -@Decree(name = "what", origin = DecreeOrigin.PLAYER, studio = true, description = "Iris What?") -public class CommandWhat implements DecreeExecutor { - @Decree(description = "What is in my hand?", origin = DecreeOrigin.PLAYER) - public void hand() { - try { - BlockData bd = player().getInventory().getItemInMainHand().getType().createBlockData(); - if(!bd.getMaterial().equals(Material.AIR)) { - sender().sendMessage("Material: " + C.GREEN + bd.getMaterial().name()); - sender().sendMessage("Full: " + C.WHITE + bd.getAsString(true)); - } else { - sender().sendMessage("Please hold a block/item"); - } - } catch(Throwable e) { - Iris.reportError(e); - Material bd = player().getInventory().getItemInMainHand().getType(); - if(!bd.equals(Material.AIR)) { - sender().sendMessage("Material: " + C.GREEN + bd.name()); - } else { - sender().sendMessage("Please hold a block/item"); - } - } - } - - @Decree(description = "What biome am i in?", origin = DecreeOrigin.PLAYER) - public void biome() { - try { - IrisBiome b = engine().getBiome(player().getLocation().getBlockX(), player().getLocation().getBlockY(), player().getLocation().getBlockZ()); - sender().sendMessage("IBiome: " + b.getLoadKey() + " (" + b.getDerivative().name() + ")"); - - } catch(Throwable e) { - Iris.reportError(e); - sender().sendMessage("Non-Iris Biome: " + player().getLocation().getBlock().getBiome().name()); - - if(player().getLocation().getBlock().getBiome().equals(Biome.CUSTOM)) { - try { - sender().sendMessage("Data Pack Biome: " + INMS.get().getTrueBiomeBaseKey(player().getLocation()) + " (ID: " + INMS.get().getTrueBiomeBaseId(INMS.get().getTrueBiomeBase(player().getLocation())) + ")"); - } catch(Throwable ee) { - Iris.reportError(ee); - } - } - } - } - - @Decree(description = "What block am i looking at?", origin = DecreeOrigin.PLAYER) - public void block() { - BlockData bd; - try { - bd = player().getTargetBlockExact(128, FluidCollisionMode.NEVER).getBlockData(); - } catch(NullPointerException e) { - Iris.reportError(e); - sender().sendMessage("Please look at any block, not at the sky"); - bd = null; - } - - if(bd != null) { - sender().sendMessage("Material: " + C.GREEN + bd.getMaterial().name()); - sender().sendMessage("Full: " + C.WHITE + bd.getAsString(true)); - - if(B.isStorage(bd)) { - sender().sendMessage(C.YELLOW + "* Storage Block (Loot Capable)"); - } - - if(B.isLit(bd)) { - sender().sendMessage(C.YELLOW + "* Lit Block (Light Capable)"); - } - - if(B.isFoliage(bd)) { - sender().sendMessage(C.YELLOW + "* Foliage Block"); - } - - if(B.isDecorant(bd)) { - sender().sendMessage(C.YELLOW + "* Decorant Block"); - } - - if(B.isFluid(bd)) { - sender().sendMessage(C.YELLOW + "* Fluid Block"); - } - - if(B.isFoliagePlantable(bd)) { - sender().sendMessage(C.YELLOW + "* Plantable Foliage Block"); - } - - if(B.isSolid(bd)) { - sender().sendMessage(C.YELLOW + "* Solid Block"); - } - } - } - - @Decree(description = "Show markers in chunk", origin = DecreeOrigin.PLAYER) - public void markers(@Param(description = "Marker name such as cave_floor or cave_ceiling") String marker) { - Chunk c = player().getLocation().getChunk(); - - if(IrisToolbelt.isIrisWorld(c.getWorld())) { - int m = 1; - AtomicInteger v = new AtomicInteger(0); - - for(int xxx = c.getX() - 4; xxx <= c.getX() + 4; xxx++) { - for(int zzz = c.getZ() - 4; zzz <= c.getZ() + 4; zzz++) { - IrisToolbelt.access(c.getWorld()).getEngine().getMantle().findMarkers(xxx, zzz, new MatterMarker(marker)) - .convert((i) -> i.toLocation(c.getWorld())).forEach((i) -> { - J.s(() -> BlockSignal.of(i.getBlock(), 100)); - v.incrementAndGet(); - }); - } - } - - sender().sendMessage("Found " + v.get() + " Nearby Markers (" + marker + ")"); - } else { - sender().sendMessage("Iris worlds only."); - } - } -} diff --git a/src/main/java/com/volmit/iris/core/edit/BlockEditor.java b/src/main/java/com/volmit/iris/core/edit/BlockEditor.java deleted file mode 100644 index 0df8f32af..000000000 --- a/src/main/java/com/volmit/iris/core/edit/BlockEditor.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.edit; - -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -import java.io.Closeable; - -public interface BlockEditor extends Closeable { - long last(); - - void set(int x, int y, int z, BlockData d); - - BlockData get(int x, int y, int z); - - void setBiome(int x, int z, Biome b); - - void setBiome(int x, int y, int z, Biome b); - - @Override - void close(); - - Biome getBiome(int x, int y, int z); - - Biome getBiome(int x, int z); -} diff --git a/src/main/java/com/volmit/iris/core/edit/BlockSignal.java b/src/main/java/com/volmit/iris/core/edit/BlockSignal.java deleted file mode 100644 index cd4b8d639..000000000 --- a/src/main/java/com/volmit/iris/core/edit/BlockSignal.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.edit; - -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.SR; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.FallingBlock; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import java.util.concurrent.atomic.AtomicInteger; - -@SuppressWarnings("InstantiationOfUtilityClass") -public class BlockSignal { - public static final AtomicInteger active = new AtomicInteger(0); - - public BlockSignal(Block block, int ticks) { - active.incrementAndGet(); - Location tg = block.getLocation().clone().add(0.5, 0, 0.5); - FallingBlock e = block.getWorld().spawnFallingBlock(tg, block.getBlockData()); - e.setGravity(false); - e.setInvulnerable(true); - e.setGlowing(true); - e.setDropItem(false); - e.setHurtEntities(false); - e.setSilent(true); - e.setTicksLived(1); - e.setVelocity(new Vector(0, 0, 0)); - J.s(() -> { - e.remove(); - active.decrementAndGet(); - BlockData type = block.getBlockData(); - MultiBurst.burst.lazy(() -> { - for(Player i : block.getWorld().getPlayers()) { - i.sendBlockChange(block.getLocation(), block.getBlockData()); - } - }); - }, ticks); - } - - public static void of(Block block, int ticks) { - new BlockSignal(block, ticks); - } - - public static void of(Block block) { - of(block, 100); - } - - public static Runnable forever(Block block) { - Location tg = block.getLocation().clone().add(0.5, 0, 0.5).clone(); - FallingBlock e = block.getWorld().spawnFallingBlock(tg.clone(), block.getBlockData()); - e.setGravity(false); - e.setInvulnerable(true); - e.setGlowing(true); - e.teleport(tg.clone()); - e.setDropItem(false); - e.setHurtEntities(false); - e.setSilent(true); - e.setTicksLived(1); - e.setVelocity(new Vector(0, 0, 0)); - - new SR(20) { - @Override - public void run() { - if(e.isDead()) { - cancel(); - return; - } - - e.setTicksLived(1); - e.teleport(tg.clone()); - e.setVelocity(new Vector(0, 0, 0)); - } - }; - - return () -> { - e.remove(); - BlockData type = block.getBlockData(); - - MultiBurst.burst.lazy(() -> { - for(Player i : block.getWorld().getPlayers()) { - i.sendBlockChange(block.getLocation(), block.getBlockData()); - } - }); - }; - } -} diff --git a/src/main/java/com/volmit/iris/core/edit/BukkitBlockEditor.java b/src/main/java/com/volmit/iris/core/edit/BukkitBlockEditor.java deleted file mode 100644 index 9ef3ce600..000000000 --- a/src/main/java/com/volmit/iris/core/edit/BukkitBlockEditor.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.edit; - -import com.volmit.iris.util.math.M; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -@SuppressWarnings("ClassCanBeRecord") -public class BukkitBlockEditor implements BlockEditor { - private final World world; - - public BukkitBlockEditor(World world) { - this.world = world; - } - - @Override - public void set(int x, int y, int z, BlockData d) { - world.getBlockAt(x, y, z).setBlockData(d, false); - } - - @Override - public BlockData get(int x, int y, int z) { - return world.getBlockAt(x, y, z).getBlockData(); - } - - @Override - public void close() { - - } - - @Override - public long last() { - return M.ms(); - } - - @SuppressWarnings("deprecation") - @Override - public void setBiome(int x, int z, Biome b) { - world.setBiome(x, z, b); - } - - @Override - public void setBiome(int x, int y, int z, Biome b) { - world.setBiome(x, y, z, b); - } - - @Override - public Biome getBiome(int x, int y, int z) { - return world.getBiome(x, y, z); - } - - @SuppressWarnings("deprecation") - @Override - public Biome getBiome(int x, int z) { - return world.getBiome(x, z); - } -} diff --git a/src/main/java/com/volmit/iris/core/edit/DustRevealer.java b/src/main/java/com/volmit/iris/core/edit/DustRevealer.java deleted file mode 100644 index f04ec80cc..000000000 --- a/src/main/java/com/volmit/iris/core/edit/DustRevealer.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.edit; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import lombok.Data; -import org.bukkit.Sound; -import org.bukkit.World; -import org.bukkit.block.Block; - -@SuppressWarnings("ALL") -@Data -public class DustRevealer { - private final Engine engine; - private final World world; - private final BlockPosition block; - private final String key; - private final KList hits; - - public DustRevealer(Engine engine, World world, BlockPosition block, String key, KList hits) { - this.engine = engine; - this.world = world; - this.block = block; - this.key = key; - this.hits = hits; - - J.s(() -> { - new BlockSignal(world.getBlockAt(block.getX(), block.getY(), block.getZ()), 10); - if(M.r(0.25)) { - world.playSound(block.toBlock(world).getLocation(), Sound.BLOCK_AMETHYST_BLOCK_CHIME, 1f, RNG.r.f(0.2f, 2f)); - } - J.a(() -> { - while(BlockSignal.active.get() > 128) { - J.sleep(5); - } - - try { - is(new BlockPosition(block.getX() + 1, block.getY(), block.getZ())); - is(new BlockPosition(block.getX() - 1, block.getY(), block.getZ())); - is(new BlockPosition(block.getX(), block.getY() + 1, block.getZ())); - is(new BlockPosition(block.getX(), block.getY() - 1, block.getZ())); - is(new BlockPosition(block.getX(), block.getY(), block.getZ() + 1)); - is(new BlockPosition(block.getX(), block.getY(), block.getZ() - 1)); - is(new BlockPosition(block.getX() + 1, block.getY(), block.getZ() + 1)); - is(new BlockPosition(block.getX() + 1, block.getY(), block.getZ() - 1)); - is(new BlockPosition(block.getX() - 1, block.getY(), block.getZ() + 1)); - is(new BlockPosition(block.getX() - 1, block.getY(), block.getZ() - 1)); - is(new BlockPosition(block.getX() + 1, block.getY() + 1, block.getZ())); - is(new BlockPosition(block.getX() + 1, block.getY() - 1, block.getZ())); - is(new BlockPosition(block.getX() - 1, block.getY() + 1, block.getZ())); - is(new BlockPosition(block.getX() - 1, block.getY() - 1, block.getZ())); - is(new BlockPosition(block.getX(), block.getY() + 1, block.getZ() - 1)); - is(new BlockPosition(block.getX(), block.getY() + 1, block.getZ() + 1)); - is(new BlockPosition(block.getX(), block.getY() - 1, block.getZ() - 1)); - is(new BlockPosition(block.getX(), block.getY() - 1, block.getZ() + 1)); - is(new BlockPosition(block.getX() - 1, block.getY() + 1, block.getZ() - 1)); - is(new BlockPosition(block.getX() - 1, block.getY() + 1, block.getZ() + 1)); - is(new BlockPosition(block.getX() - 1, block.getY() - 1, block.getZ() - 1)); - is(new BlockPosition(block.getX() - 1, block.getY() - 1, block.getZ() + 1)); - is(new BlockPosition(block.getX() + 1, block.getY() + 1, block.getZ() - 1)); - is(new BlockPosition(block.getX() + 1, block.getY() + 1, block.getZ() + 1)); - is(new BlockPosition(block.getX() + 1, block.getY() - 1, block.getZ() - 1)); - is(new BlockPosition(block.getX() + 1, block.getY() - 1, block.getZ() + 1)); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - }); - }, RNG.r.i(2, 8)); - } - - public static void spawn(Block block, VolmitSender sender) { - World world = block.getWorld(); - Engine access = IrisToolbelt.access(world).getEngine(); - - if(access != null) { - String a = access.getObjectPlacementKey(block.getX(), block.getY() - block.getWorld().getMinHeight(), block.getZ()); - if(a != null) { - world.playSound(block.getLocation(), Sound.ITEM_LODESTONE_COMPASS_LOCK, 1f, 0.1f); - - sender.sendMessage("Found object " + a); - J.a(() -> { - new DustRevealer(access, world, new BlockPosition(block.getX(), block.getY(), block.getZ()), a, new KList<>()); - }); - } - } - } - - private boolean is(BlockPosition a) { - int betterY = a.getY() - world.getMinHeight(); - if(isValidTry(a) && engine.getObjectPlacementKey(a.getX(), betterY, a.getZ()) != null && engine.getObjectPlacementKey(a.getX(), betterY, a.getZ()).equals(key)) { - hits.add(a); - new DustRevealer(engine, world, a, key, hits); - return true; - } - - return false; - } - - private boolean isValidTry(BlockPosition b) { - return !hits.contains(b); - } -} diff --git a/src/main/java/com/volmit/iris/core/edit/JigsawEditor.java b/src/main/java/com/volmit/iris/core/edit/JigsawEditor.java deleted file mode 100644 index d4b2db1f4..000000000 --- a/src/main/java/com/volmit/iris/core/edit/JigsawEditor.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.edit; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.WandSVC; -import com.volmit.iris.engine.object.IrisDirection; -import com.volmit.iris.engine.object.IrisJigsawPiece; -import com.volmit.iris.engine.object.IrisJigsawPieceConnector; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.Cuboid; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.Sound; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.util.Vector; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.concurrent.ExecutionException; - -public class JigsawEditor implements Listener { - public static final KMap editors = new KMap<>(); - private final Player player; - private final IrisObject object; - private final File targetSaveLocation; - private final IrisJigsawPiece piece; - private final Location origin; - private final Cuboid cuboid; - private final int ticker; - private final KMap falling = new KMap<>(); - private final ChronoLatch cl = new ChronoLatch(100); - private Location target; - - public JigsawEditor(Player player, IrisJigsawPiece piece, IrisObject object, File saveLocation) { - if(editors.containsKey(player)) { - editors.get(player).close(); - } - - editors.put(player, this); - if(object == null) - { - throw new RuntimeException("Object is null! " + piece.getObject()); - } - this.object = object; - this.player = player; - origin = player.getLocation().clone().add(0, 7, 0); - target = origin; - this.targetSaveLocation = saveLocation; - this.piece = piece == null ? new IrisJigsawPiece() : piece; - this.piece.setObject(object.getLoadKey()); - cuboid = new Cuboid(origin.clone(), origin.clone().add(object.getW() - 1, object.getH() - 1, object.getD() - 1)); - ticker = J.sr(this::onTick, 0); - J.s(() -> object.placeCenterY(origin)); - Iris.instance.registerListener(this); - } - - @EventHandler - public void on(PlayerMoveEvent e) { - if(e.getPlayer().equals(player)) { - try { - target = player.getTargetBlockExact(7).getLocation(); - } catch(Throwable ex) { - Iris.reportError(ex); - target = player.getLocation(); - return; - } - - if(cuboid.contains(target)) { - for(IrisPosition i : falling.k()) { - Location at = toLocation(i); - - if(at.equals(target)) { - falling.remove(i).run(); - } - } - } - } - } - - public Location toLocation(IrisPosition i) { - return origin.clone() - .add(new Vector(i.getX(), i.getY(), i.getZ())) - .add(object.getCenter()) - .getBlock() - .getLocation(); - } - - public IrisPosition toPosition(Location l) { - return new IrisPosition(l.clone().getBlock().getLocation() - .subtract(origin.clone()) - .subtract(object.getCenter()) - .add(1, 1, 1) - .toVector()); - } - - @EventHandler - public void on(PlayerInteractEvent e) { - if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { - if(e.getClickedBlock() != null && cuboid.contains(e.getClickedBlock().getLocation()) && e.getPlayer().equals(player)) { - IrisPosition pos = toPosition(e.getClickedBlock().getLocation()); - IrisJigsawPieceConnector connector = null; - for(IrisJigsawPieceConnector i : piece.getConnectors()) { - if(i.getPosition().equals(pos)) { - connector = i; - break; - } - } - - if(!player.isSneaking() && connector == null) { - connector = new IrisJigsawPieceConnector(); - connector.setDirection(IrisDirection.getDirection(e.getBlockFace())); - connector.setPosition(pos); - piece.getConnectors().add(connector); - player.playSound(e.getClickedBlock().getLocation(), Sound.ENTITY_ITEM_FRAME_ADD_ITEM, 1f, 1f); - } else if(player.isSneaking() && connector != null) { - piece.getConnectors().remove(connector); - player.playSound(e.getClickedBlock().getLocation(), Sound.ENTITY_ITEM_FRAME_REMOVE_ITEM, 1f, 1f); - } else if(connector != null && !player.isSneaking()) { - connector.setDirection(IrisDirection.getDirection(e.getBlockFace())); - player.playSound(e.getClickedBlock().getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 1f); - } - } - } - } - - private void removeKey(JSONObject o, String... path) - { - if(path.length == 1) - { - o.remove(path[0]); - return; - } - - List s = new java.util.ArrayList<>(List.of(path)); - s.remove(0); - removeKey(o.getJSONObject(path[0]), s.toArray(new String[0])); - } - - private List getObjectsInArray(JSONObject a, String key) - { - KList o = new KList<>(); - - for(int i = 0; i < a.getJSONArray(key).length(); i++) - { - o.add(a.getJSONArray(key).getJSONObject(i)); - } - - return o; - } - - public void close() { - exit(); - try { - JSONObject j = new JSONObject(new Gson().toJson(piece)); - // Remove sub-key - removeKey(j, "placementOptions", "translateCenter"); // should work - J.attempt(() -> j.getJSONObject("placementOptions").remove("translateCenter")); // otherwise - - // remove root key - removeKey(j, "placementOptions"); // should work - j.remove("placementOptions"); // otherwise - - // Remove key in all objects in array - for(JSONObject i : getObjectsInArray(j, "connectors")) - { - removeKey(i, "rotateConnector"); - } - - IO.writeAll(targetSaveLocation, j.toString(4)); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - public void exit() { - J.car(ticker); - Iris.instance.unregisterListener(this); - try { - J.sfut(() -> { - object.unplaceCenterY(origin); - falling.v().forEach(Runnable::run); - }).get(); - } catch(InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - editors.remove(player); - } - - public void onTick() { - if(cl.flip()) { - Iris.service(WandSVC.class).draw(cuboid, player); - - f: - for(IrisPosition i : falling.k()) { - for(IrisJigsawPieceConnector j : piece.getConnectors()) { - if(j.getPosition().equals(i)) { - continue f; - } - } - - falling.remove(i).run(); - } - - for(IrisJigsawPieceConnector i : piece.getConnectors()) { - IrisPosition pos = i.getPosition(); - Location at = toLocation(pos); - - Vector dir = i.getDirection().toVector().clone(); - - - for(int ix = 0; ix < RNG.r.i(1, 3); ix++) { - at.getWorld().spawnParticle(Particle.SOUL_FIRE_FLAME, at.clone().getBlock().getLocation().add(0.25, 0.25, 0.25).add(RNG.r.d(0.5), RNG.r.d(0.5), RNG.r.d(0.5)), 0, dir.getX(), dir.getY(), dir.getZ(), 0.092 + RNG.r.d(-0.03, 0.08)); - } - - if(at.getBlock().getLocation().equals(target)) { - continue; - } - - if(!falling.containsKey(pos)) { - if(at.getBlock().getType().isAir()) { - at.getBlock().setType(Material.STONE); - } - - falling.put(pos, BlockSignal.forever(at.getBlock())); - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/core/events/IrisEngineEvent.java b/src/main/java/com/volmit/iris/core/events/IrisEngineEvent.java deleted file mode 100644 index 5651823c7..000000000 --- a/src/main/java/com/volmit/iris/core/events/IrisEngineEvent.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.events; - -import com.volmit.iris.engine.framework.Engine; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -@EqualsAndHashCode(callSuper = true) -@Data -@AllArgsConstructor -public class IrisEngineEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - private Engine engine; - - public IrisEngineEvent() { - super(true); - } - - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} diff --git a/src/main/java/com/volmit/iris/core/events/IrisEngineHotloadEvent.java b/src/main/java/com/volmit/iris/core/events/IrisEngineHotloadEvent.java deleted file mode 100644 index 7b3afe4c1..000000000 --- a/src/main/java/com/volmit/iris/core/events/IrisEngineHotloadEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.events; - -import com.volmit.iris.engine.framework.Engine; -import org.bukkit.event.HandlerList; - -public class IrisEngineHotloadEvent extends IrisEngineEvent { - private static final HandlerList handlers = new HandlerList(); - - public IrisEngineHotloadEvent(Engine engine) { - super(engine); - } - - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} diff --git a/src/main/java/com/volmit/iris/core/gui/NoiseExplorerGUI.java b/src/main/java/com/volmit/iris/core/gui/NoiseExplorerGUI.java deleted file mode 100644 index b254fb96f..000000000 --- a/src/main/java/com/volmit/iris/core/gui/NoiseExplorerGUI.java +++ /dev/null @@ -1,350 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.gui; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.events.IrisEngineHotloadEvent; -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.math.RollingSequence; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -import javax.imageio.ImageIO; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.JViewport; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Supplier; - -public class NoiseExplorerGUI extends JPanel implements MouseWheelListener, Listener { - - private static final long serialVersionUID = 2094606939770332040L; - - static JComboBox combo; - @SuppressWarnings("CanBeFinal") - static boolean hd = false; - static double ascale = 10; - static double oxp = 0; - static double ozp = 0; - static double mxx = 0; - static double mzz = 0; - @SuppressWarnings("CanBeFinal") - static boolean down = false; - @SuppressWarnings("CanBeFinal") - RollingSequence r = new RollingSequence(20); - @SuppressWarnings("CanBeFinal") - boolean colorMode = true; - double scale = 1; - CNG cng = NoiseStyle.STATIC.create(new RNG(RNG.r.nextLong())); - @SuppressWarnings("CanBeFinal") - MultiBurst gx = MultiBurst.burst; - ReentrantLock l = new ReentrantLock(); - BufferedImage img; - int w = 0; - int h = 0; - Function2 generator; - Supplier> loader; - double ox = 0; //Offset X - double oz = 0; //Offset Y - double mx = 0; - double mz = 0; - double lx = Double.MAX_VALUE; //MouseX - double lz = Double.MAX_VALUE; //MouseY - double t; - double tz; - - public NoiseExplorerGUI() { - Iris.instance.registerListener(this); - addMouseWheelListener(this); - addMouseMotionListener(new MouseMotionListener() { - @Override - public void mouseMoved(MouseEvent e) { - Point cp = e.getPoint(); - - lx = (cp.getX()); - lz = (cp.getY()); - mx = lx; - mz = lz; - } - - @Override - public void mouseDragged(MouseEvent e) { - Point cp = e.getPoint(); - ox += (lx - cp.getX()) * scale; - oz += (lz - cp.getY()) * scale; - lx = cp.getX(); - lz = cp.getY(); - } - }); - } - - private static void createAndShowGUI(Supplier> loader, String genName) { - JFrame frame = new JFrame("Noise Explorer: " + genName); - NoiseExplorerGUI nv = new NoiseExplorerGUI(); - frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - JLayeredPane pane = new JLayeredPane(); - nv.setSize(new Dimension(1440, 820)); - pane.add(nv, 1, 0); - nv.loader = loader; - nv.generator = loader.get(); - frame.add(pane); - File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); - - if(file != null) { - try { - frame.setIconImage(ImageIO.read(file)); - } catch(IOException e) { - Iris.reportError(e); - } - } - frame.setSize(1440, 820); - frame.setVisible(true); - } - - private static void createAndShowGUI() { - JFrame frame = new JFrame("Noise Explorer"); - NoiseExplorerGUI nv = new NoiseExplorerGUI(); - frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - KList li = new KList<>(NoiseStyle.values()).toStringList(); - combo = new JComboBox<>(li.toArray(new String[0])); - combo.setSelectedItem("STATIC"); - combo.setFocusable(false); - combo.addActionListener(e -> { - @SuppressWarnings("unchecked") - String b = (String) (((JComboBox) e.getSource()).getSelectedItem()); - NoiseStyle s = NoiseStyle.valueOf(b); - nv.cng = s.create(RNG.r.nextParallelRNG(RNG.r.imax())); - }); - - combo.setSize(500, 30); - JLayeredPane pane = new JLayeredPane(); - nv.setSize(new Dimension(1440, 820)); - pane.add(nv, 1, 0); - pane.add(combo, 2, 0); - frame.add(pane); - File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); - - if(file != null) { - try { - frame.setIconImage(ImageIO.read(file)); - } catch(IOException e) { - Iris.reportError(e); - } - } - frame.setSize(1440, 820); - frame.setVisible(true); - frame.addWindowListener(new java.awt.event.WindowAdapter() { - @Override - public void windowClosing(java.awt.event.WindowEvent windowEvent) { - Iris.instance.unregisterListener(nv); - } - }); - } - - public static void launch(Supplier> gen, String genName) { - EventQueue.invokeLater(() -> createAndShowGUI(gen, genName)); - } - - public static void launch() { - EventQueue.invokeLater(NoiseExplorerGUI::createAndShowGUI); - } - - @EventHandler - public void on(IrisEngineHotloadEvent e) { - if(generator != null) - generator = loader.get(); - } - - public void mouseWheelMoved(MouseWheelEvent e) { - - int notches = e.getWheelRotation(); - if(e.isControlDown()) { - t = t + ((0.0025 * t) * notches); - return; - } - - scale = scale + ((0.044 * scale) * notches); - scale = Math.max(scale, 0.00001); - } - - @Override - public void paint(Graphics g) { - if(scale < ascale) { - ascale -= Math.abs(scale - ascale) * 0.16; - } - - if(scale > ascale) { - ascale += Math.abs(ascale - scale) * 0.16; - } - - if(t < tz) { - tz -= Math.abs(t - tz) * 0.29; - } - - if(t > tz) { - tz += Math.abs(tz - t) * 0.29; - } - - if(ox < oxp) { - oxp -= Math.abs(ox - oxp) * 0.16; - } - - if(ox > oxp) { - oxp += Math.abs(oxp - ox) * 0.16; - } - - if(oz < ozp) { - ozp -= Math.abs(oz - ozp) * 0.16; - } - - if(oz > ozp) { - ozp += Math.abs(ozp - oz) * 0.16; - } - - if(mx < mxx) { - mxx -= Math.abs(mx - mxx) * 0.16; - } - - if(mx > mxx) { - mxx += Math.abs(mxx - mx) * 0.16; - } - - if(mz < mzz) { - mzz -= Math.abs(mz - mzz) * 0.16; - } - - if(mz > mzz) { - mzz += Math.abs(mzz - mz) * 0.16; - } - - PrecisionStopwatch p = PrecisionStopwatch.start(); - int accuracy = hd ? 1 : M.clip((r.getAverage() / 12D), 2D, 128D).intValue(); - accuracy = down ? accuracy * 4 : accuracy; - int v = 1000; - - if(g instanceof Graphics2D gg) { - - if(getParent().getWidth() != w || getParent().getHeight() != h) { - w = getParent().getWidth(); - h = getParent().getHeight(); - img = null; - } - - if(img == null) { - img = new BufferedImage(w / accuracy, h / accuracy, BufferedImage.TYPE_INT_RGB); - } - - BurstExecutor e = gx.burst(w); - - for(int x = 0; x < w / accuracy; x++) { - int xx = x; - - int finalAccuracy = accuracy; - e.queue(() -> { - for(int z = 0; z < h / finalAccuracy; z++) { - double n = generator != null ? generator.apply(((xx * finalAccuracy) * ascale) + oxp, ((z * finalAccuracy) * ascale) + ozp) : cng.noise(((xx * finalAccuracy) * ascale) + oxp, ((z * finalAccuracy) * ascale) + ozp); - n = n > 1 ? 1 : n < 0 ? 0 : n; - - try { - Color color = colorMode ? Color.getHSBColor((float) (n), 1f - (float) (n * n * n * n * n * n), 1f - (float) n) : Color.getHSBColor(0f, 0f, (float) n); - int rgb = color.getRGB(); - img.setRGB(xx, z, rgb); - } catch(Throwable xxx) { - - } - } - }); - } - - e.complete(); - gg.drawImage(img, 0, 0, getParent().getWidth() * accuracy, getParent().getHeight() * accuracy, (img, infoflags, x, y, width, height) -> true); - } - - p.end(); - - t += 1D; - r.put(p.getMilliseconds()); - - if(!isVisible()) { - return; - } - - if(!getParent().isVisible()) { - return; - } - - if(!getParent().getParent().isVisible()) { - return; - } - - EventQueue.invokeLater(() -> - { - J.sleep((long) Math.max(0, 32 - r.getAverage())); - repaint(); - }); - } - - static class HandScrollListener extends MouseAdapter { - private static final Point pp = new Point(); - - @Override - public void mouseDragged(MouseEvent e) { - JViewport vport = (JViewport) e.getSource(); - JComponent label = (JComponent) vport.getView(); - Point cp = e.getPoint(); - Point vp = vport.getViewPosition(); - vp.translate(pp.x - cp.x, pp.y - cp.y); - label.scrollRectToVisible(new Rectangle(vp, vport.getSize())); - - pp.setLocation(cp); - } - - @Override - public void mousePressed(MouseEvent e) { - pp.setLocation(e.getPoint()); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/core/gui/PregeneratorJob.java b/src/main/java/com/volmit/iris/core/gui/PregeneratorJob.java deleted file mode 100644 index 66137de22..000000000 --- a/src/main/java/com/volmit/iris/core/gui/PregeneratorJob.java +++ /dev/null @@ -1,441 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.gui; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.pregenerator.IrisPregenerator; -import com.volmit.iris.core.pregenerator.PregenListener; -import com.volmit.iris.core.pregenerator.PregenTask; -import com.volmit.iris.core.pregenerator.PregeneratorMethod; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.format.MemoryMonitor; -import com.volmit.iris.util.function.Consumer2; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; - -import javax.swing.JFrame; -import javax.swing.JPanel; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.image.BufferedImage; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Consumer; - -public class PregeneratorJob implements PregenListener { - private static final Color COLOR_EXISTS = parseColor("#4d7d5b"); - private static final Color COLOR_BLACK = parseColor("#4d7d5b"); - private static final Color COLOR_MANTLE = parseColor("#3c2773"); - private static final Color COLOR_GENERATING = parseColor("#66967f"); - private static final Color COLOR_NETWORK = parseColor("#a863c2"); - private static final Color COLOR_NETWORK_GENERATING = parseColor("#836b8c"); - private static final Color COLOR_GENERATED = parseColor("#65c295"); - private static final Color COLOR_CLEANED = parseColor("#34eb93"); - public static PregeneratorJob instance; - private final MemoryMonitor monitor; - private final PregenTask task; - private final boolean saving; - private final KList> onProgress = new KList<>(); - private final KList whenDone = new KList<>(); - private final IrisPregenerator pregenerator; - private final Position2 min; - private final Position2 max; - private JFrame frame; - private PregenRenderer renderer; - private int rgc = 0; - private final ChronoLatch cl = new ChronoLatch(TimeUnit.MINUTES.toMillis(1)); - private String[] info; - private final Engine engine; - - public PregeneratorJob(PregenTask task, PregeneratorMethod method, Engine engine) { - this.engine = engine; - instance = this; - monitor = new MemoryMonitor(50); - saving = false; - info = new String[] {"Initializing..."}; - this.task = task; - this.pregenerator = new IrisPregenerator(task, method, this); - max = new Position2(0, 0); - min = new Position2(0, 0); - KList draw = new KList<>(); - task.iterateRegions((xx, zz) -> { - min.setX(Math.min(xx << 5, min.getX())); - min.setZ(Math.min(zz << 5, min.getZ())); - max.setX(Math.max((xx << 5) + 31, max.getX())); - max.setZ(Math.max((zz << 5) + 31, max.getZ())); - }); - - if(IrisSettings.get().getGui().isUseServerLaunchedGuis()) { - open(); - } - - J.a(this.pregenerator::start, 20); - } - - public Mantle getMantle() { - return pregenerator.getMantle(); - } - - public static boolean shutdownInstance() { - if(instance == null) { - return false; - } - - J.a(() -> instance.pregenerator.close()); - return true; - } - - public static PregeneratorJob getInstance() { - return instance; - } - - public static boolean pauseResume() { - if(instance == null) { - return false; - } - - if(isPaused()) { - instance.pregenerator.resume(); - } else { - instance.pregenerator.pause(); - } - return true; - } - - public static boolean isPaused() { - if(instance == null) { - return true; - } - - return instance.paused(); - } - - private static Color parseColor(String c) { - String v = (c.startsWith("#") ? c : "#" + c).trim(); - try { - return Color.decode(v); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Error Parsing 'color', (" + c + ")"); - } - - return Color.RED; - } - - public PregeneratorJob onProgress(Consumer c) { - onProgress.add(c); - return this; - } - - public PregeneratorJob whenDone(Runnable r) { - whenDone.add(r); - return this; - } - - public void drawRegion(int x, int z, Color color) { - J.a(() -> { - PregenTask.iterateRegion(x, z, (xx, zz) -> { - draw(xx, zz, color); - J.sleep(3); - }); - }); - } - - public void draw(int x, int z, Color color) { - try { - if(renderer != null && frame != null && frame.isVisible()) { - renderer.func.accept(new Position2(x, z), color); - } - } catch(Throwable ignored) { - - } - } - - public void stop() { - J.a(() -> { - pregenerator.close(); - close(); - instance = null; - }); - } - - public void close() { - J.a(() -> { - try { - monitor.close(); - J.sleep(3000); - frame.setVisible(false); - } catch(Throwable e) { - - } - }); - } - - public void open() { - J.a(() -> { - try { - frame = new JFrame("Pregen View"); - renderer = new PregenRenderer(); - frame.addKeyListener(renderer); - renderer.l = new ReentrantLock(); - renderer.frame = frame; - renderer.job = this; - renderer.func = (c, b) -> - { - renderer.l.lock(); - renderer.order.add(() -> renderer.draw(c, b, renderer.bg)); - renderer.l.unlock(); - }; - frame.add(renderer); - frame.setSize(1000, 1000); - frame.setVisible(true); - } catch(Throwable e) { - - } - }); - } - - @Override - public void onTick(double chunksPerSecond, double chunksPerMinute, double regionsPerMinute, double percent, int generated, int totalChunks, int chunksRemaining, long eta, long elapsed, String method) { - info = new String[] { - (paused() ? "PAUSED" : (saving ? "Saving... " : "Generating")) + " " + Form.f(generated) + " of " + Form.f(totalChunks) + " (" + Form.pc(percent, 0) + " Complete)", - "Speed: " + Form.f(chunksPerSecond, 0) + " Chunks/s, " + Form.f(regionsPerMinute, 1) + " Regions/m, " + Form.f(chunksPerMinute, 0) + " Chunks/m", - Form.duration(eta, 2) + " Remaining " + " (" + Form.duration(elapsed, 2) + " Elapsed)", - "Generation Method: " + method, - "Memory: " + Form.memSize(monitor.getUsedBytes(), 2) + " (" + Form.pc(monitor.getUsagePercent(), 0) + ") Pressure: " + Form.memSize(monitor.getPressure(), 0) + "/s", - - }; - - for(Consumer i : onProgress) { - i.accept(percent); - } - } - - @Override - public void onChunkGenerating(int x, int z) { - if(engine != null) { - return; - } - - draw(x, z, COLOR_GENERATING); - } - - @Override - public void onChunkGenerated(int x, int z) { - if(engine != null) { - draw(x, z, engine.draw((x << 4) + 8, (z << 4) + 8)); - return; - } - - draw(x, z, COLOR_GENERATED); - } - - @Override - public void onRegionGenerated(int x, int z) { - shouldGc(); - rgc++; - } - - private void shouldGc() { - if(cl.flip() && rgc > 16) { - System.gc(); - } - } - - @Override - public void onRegionGenerating(int x, int z) { - - } - - @Override - public void onChunkCleaned(int x, int z) { - //draw(x, z, COLOR_CLEANED); - } - - @Override - public void onRegionSkipped(int x, int z) { - - } - - @Override - public void onNetworkStarted(int x, int z) { - drawRegion(x, z, COLOR_NETWORK); - } - - @Override - public void onNetworkFailed(int x, int z) { - - } - - @Override - public void onNetworkReclaim(int revert) { - - } - - @Override - public void onNetworkGeneratedChunk(int x, int z) { - draw(x, z, COLOR_NETWORK_GENERATING); - } - - @Override - public void onNetworkDownloaded(int x, int z) { - drawRegion(x, z, COLOR_NETWORK); - } - - @Override - public void onClose() { - close(); - instance = null; - whenDone.forEach(Runnable::run); - } - - @Override - public void onSaving() { - - } - - @Override - public void onChunkExistsInRegionGen(int x, int z) { - if(engine != null) { - draw(x, z, engine.draw((x << 4) + 8, (z << 4) + 8)); - return; - } - - draw(x, z, COLOR_EXISTS); - } - - private Position2 getMax() { - return max; - } - - private Position2 getMin() { - return min; - } - - private boolean paused() { - return pregenerator.paused(); - } - - private String[] getProgress() { - return info; - } - - public static class PregenRenderer extends JPanel implements KeyListener { - private static final long serialVersionUID = 2094606939770332040L; - private final KList order = new KList<>(); - private final int res = 512; - private final BufferedImage image = new BufferedImage(res, res, BufferedImage.TYPE_INT_RGB); - Graphics2D bg; - private PregeneratorJob job; - private ReentrantLock l; - private Consumer2 func; - private JFrame frame; - - public PregenRenderer() { - - } - - public void paint(int x, int z, Color c) { - func.accept(new Position2(x, z), c); - } - - @Override - public void paint(Graphics gx) { - Graphics2D g = (Graphics2D) gx; - bg = (Graphics2D) image.getGraphics(); - l.lock(); - - while(order.isNotEmpty()) { - try { - order.pop().run(); - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - l.unlock(); - g.drawImage(image, 0, 0, getParent().getWidth(), getParent().getHeight(), (img, infoflags, x, y, width, height) -> true); - g.setColor(Color.WHITE); - g.setFont(new Font("Hevetica", Font.BOLD, 13)); - String[] prog = job.getProgress(); - int h = g.getFontMetrics().getHeight() + 5; - int hh = 20; - - if(job.paused()) { - g.drawString("PAUSED", 20, hh += h); - - g.drawString("Press P to Resume", 20, hh += h); - } else { - for(String i : prog) { - g.drawString(i, 20, hh += h); - } - - g.drawString("Press P to Pause", 20, hh += h); - } - - J.sleep(IrisSettings.get().getGui().isMaximumPregenGuiFPS() ? 4 : 250); - repaint(); - } - - private void draw(Position2 p, Color c, Graphics2D bg) { - double pw = M.lerpInverse(job.getMin().getX(), job.getMax().getX(), p.getX()); - double ph = M.lerpInverse(job.getMin().getZ(), job.getMax().getZ(), p.getZ()); - double pwa = M.lerpInverse(job.getMin().getX(), job.getMax().getX(), p.getX() + 1); - double pha = M.lerpInverse(job.getMin().getZ(), job.getMax().getZ(), p.getZ() + 1); - int x = (int) M.lerp(0, res, pw); - int z = (int) M.lerp(0, res, ph); - int xa = (int) M.lerp(0, res, pwa); - int za = (int) M.lerp(0, res, pha); - bg.setColor(c); - bg.fillRect(x, z, xa - x, za - z); - } - - @Override - public void keyTyped(KeyEvent e) { - - } - - @Override - public void keyPressed(KeyEvent e) { - - } - - @Override - public void keyReleased(KeyEvent e) { - if(e.getKeyCode() == KeyEvent.VK_P) { - PregeneratorJob.pauseResume(); - } - } - - public void close() { - frame.setVisible(false); - } - } -} diff --git a/src/main/java/com/volmit/iris/core/gui/VisionGUI.java b/src/main/java/com/volmit/iris/core/gui/VisionGUI.java deleted file mode 100644 index 4677cfc55..000000000 --- a/src/main/java/com/volmit/iris/core/gui/VisionGUI.java +++ /dev/null @@ -1,845 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.gui; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.gui.components.IrisRenderer; -import com.volmit.iris.core.gui.components.RenderType; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.engine.object.IrisWorld; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RollingSequence; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.O; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import org.bukkit.Location; -import org.bukkit.attribute.Attribute; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; - -import javax.imageio.ImageIO; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.event.MouseInputListener; -import java.awt.*; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.Locale; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.function.BiFunction; - -public class VisionGUI extends JPanel implements MouseWheelListener, KeyListener, MouseMotionListener, MouseInputListener { - private static final long serialVersionUID = 2094606939770332040L; - private final KList lastEntities = new KList<>(); - private final KMap notifications = new KMap<>(); - private final ChronoLatch centities = new ChronoLatch(1000); - private final RollingSequence rs = new RollingSequence(512); - private final O m = new O<>(); - private final KMap positions = new KMap<>(); - private final KMap fastpositions = new KMap<>(); - private final KSet working = new KSet<>(); - private final KSet workingfast = new KSet<>(); - double tfps = 240D; - int ltc = 3; - private RenderType currentType = RenderType.BIOME; - private boolean help = true; - private boolean helpIgnored = false; - private boolean shift = false; - private Player player = null; - private boolean debug = false; - private boolean control = false; - private boolean eco = false; - private boolean lowtile = false; - private boolean follow = false; - private boolean alt = false; - private IrisRenderer renderer; - private IrisWorld world; - private double velocity = 0; - private int lowq = 12; - private double scale = 128; - private double mscale = 4D; - private int w = 0; - private int h = 0; - private double lx = 0; - private double lz = 0; - private double ox = 0; - private double oz = 0; - private double hx = 0; - private double hz = 0; - private double oxp = 0; - private double ozp = 0; - private Engine engine; - private int tid = 0; - private final ExecutorService e = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), r -> { - tid++; - Thread t = new Thread(r); - t.setName("Iris HD Renderer " + tid); - t.setPriority(Thread.MIN_PRIORITY); - t.setUncaughtExceptionHandler((et, e) -> - { - Iris.info("Exception encountered in " + et.getName()); - e.printStackTrace(); - }); - - return t; - }); - - private final ExecutorService eh = Executors.newFixedThreadPool(ltc, r -> { - tid++; - Thread t = new Thread(r); - t.setName("Iris Renderer " + tid); - t.setPriority(Thread.NORM_PRIORITY); - t.setUncaughtExceptionHandler((et, e) -> - { - Iris.info("Exception encountered in " + et.getName()); - e.printStackTrace(); - }); - - return t; - }); - private BufferedImage texture; - - public VisionGUI(JFrame frame) { - m.set(8); - rs.put(1); - addMouseWheelListener(this); - addMouseMotionListener(this); - addMouseListener(this); - frame.addKeyListener(this); - J.a(() -> { - J.sleep(10000); - - if(!helpIgnored && help) { - help = false; - } - }); - frame.addWindowListener(new java.awt.event.WindowAdapter() { - @Override - public void windowClosing(java.awt.event.WindowEvent windowEvent) { - e.shutdown(); - eh.shutdown(); - } - }); - } - - private static void createAndShowGUI(Engine r, int s, IrisWorld world) { - JFrame frame = new JFrame("Vision"); - VisionGUI nv = new VisionGUI(frame); - nv.world = world; - nv.engine = r; - nv.renderer = new IrisRenderer(r); - frame.add(nv); - frame.setSize(1440, 820); - frame.setVisible(true); - File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); - - if(file != null) { - try { - nv.texture = ImageIO.read(file); - frame.setIconImage(ImageIO.read(file)); - } catch(IOException e) { - Iris.reportError(e); - - } - } - } - - public static void launch(Engine g, int i) { - J.a(() -> - createAndShowGUI(g, i, g.getWorld())); - } - - public boolean updateEngine() { - if(engine.isClosed()) { - if(world.hasRealWorld()) { - try { - engine = IrisToolbelt.access(world.realWorld()).getEngine(); - return !engine.isClosed(); - } catch(Throwable e) { - - } - } - } - - return false; - } - - @Override - public void mouseMoved(MouseEvent e) { - Point cp = e.getPoint(); - lx = (cp.getX()); - lz = (cp.getY()); - } - - @Override - public void mouseDragged(MouseEvent e) { - Point cp = e.getPoint(); - ox += (lx - cp.getX()) * scale; - oz += (lz - cp.getY()) * scale; - lx = cp.getX(); - lz = cp.getY(); - } - - public int getColor(double wx, double wz) { - BiFunction colorFunction = (d, dx) -> Color.black.getRGB(); - - switch(currentType) { - case BIOME, DECORATOR_LOAD, OBJECT_LOAD, LAYER_LOAD -> colorFunction = (x, z) -> engine.getComplex().getTrueBiomeStream().get(x, z).getColor(engine, currentType).getRGB(); - case BIOME_LAND -> colorFunction = (x, z) -> engine.getComplex().getLandBiomeStream().get(x, z).getColor(engine, currentType).getRGB(); - case BIOME_SEA -> colorFunction = (x, z) -> engine.getComplex().getSeaBiomeStream().get(x, z).getColor(engine, currentType).getRGB(); - case REGION -> colorFunction = (x, z) -> engine.getComplex().getRegionStream().get(x, z).getColor(engine.getComplex(), currentType).getRGB(); - case CAVE_LAND -> colorFunction = (x, z) -> engine.getComplex().getCaveBiomeStream().get(x, z).getColor(engine, currentType).getRGB(); - case HEIGHT -> colorFunction = (x, z) -> Color.getHSBColor(engine.getComplex().getHeightStream().get(x, z).floatValue(), 100, 100).getRGB(); - } - - return colorFunction.apply(wx, wz); - } - - public void notify(String s) { - notifications.put(s, M.ms() + 2500); - } - - @Override - public void keyTyped(KeyEvent e) { - - } - - @Override - public void keyPressed(KeyEvent e) { - if(e.getKeyCode() == KeyEvent.VK_SHIFT) { - shift = true; - } - if(e.getKeyCode() == KeyEvent.VK_CONTROL) { - control = true; - } - if(e.getKeyCode() == KeyEvent.VK_SEMICOLON) { - debug = true; - } - if(e.getKeyCode() == KeyEvent.VK_SLASH) { - help = true; - helpIgnored = true; - } - if(e.getKeyCode() == KeyEvent.VK_ALT) { - alt = true; - } - } - - @Override - public void keyReleased(KeyEvent e) { - if(e.getKeyCode() == KeyEvent.VK_SEMICOLON) { - debug = false; - } - if(e.getKeyCode() == KeyEvent.VK_SHIFT) { - shift = false; - } - - if(e.getKeyCode() == KeyEvent.VK_CONTROL) { - control = false; - } - if(e.getKeyCode() == KeyEvent.VK_SLASH) { - help = false; - helpIgnored = true; - } - if(e.getKeyCode() == KeyEvent.VK_ALT) { - alt = false; - } - - // Pushes - if(e.getKeyCode() == KeyEvent.VK_F) { - follow = !follow; - - if(player != null && follow) { - notify("Following " + player.getName() + ". Press F to disable"); - } else if(follow) { - notify("Can't follow, no one is in the world"); - follow = false; - } else { - notify("Follow Off"); - } - - return; - } - - if(e.getKeyCode() == KeyEvent.VK_R) { - dump(); - notify("Refreshing Chunks"); - return; - } - - if(e.getKeyCode() == KeyEvent.VK_P) { - lowtile = !lowtile; - dump(); - notify("Rendering " + (lowtile ? "Low" : "High") + " Quality Tiles"); - return; - } - if(e.getKeyCode() == KeyEvent.VK_E) { - eco = !eco; - dump(); - notify("Using " + (eco ? "60" : "Uncapped") + " FPS Limit"); - return; - } - if(e.getKeyCode() == KeyEvent.VK_EQUALS) { - mscale = mscale + ((0.044 * mscale) * -3); - mscale = Math.max(mscale, 0.00001); - dump(); - return; - } - if(e.getKeyCode() == KeyEvent.VK_MINUS) { - mscale = mscale + ((0.044 * mscale) * 3); - mscale = Math.max(mscale, 0.00001); - dump(); - return; - } - - if(e.getKeyCode() == KeyEvent.VK_BACK_SLASH) { - mscale = 1D; - dump(); - notify("Zoom Reset"); - return; - } - - int currentMode = currentType.ordinal(); - - for(RenderType i : RenderType.values()) { - if(e.getKeyChar() == String.valueOf(i.ordinal() + 1).charAt(0)) { - if(i.ordinal() != currentMode) { - currentType = i; - dump(); - notify("Rendering " + Form.capitalizeWords(currentType.name().toLowerCase().replaceAll("\\Q_\\E", " "))); - return; - } - } - } - - if(e.getKeyCode() == KeyEvent.VK_M) { - currentType = RenderType.values()[(currentMode + 1) % RenderType.values().length]; - notify("Rendering " + Form.capitalizeWords(currentType.name().toLowerCase().replaceAll("\\Q_\\E", " "))); - dump(); - } - } - - private void dump() { - positions.clear(); - fastpositions.clear(); - } - - public BufferedImage getTile(KSet fg, int div, int x, int z, O m) { - BlockPosition key = new BlockPosition((int) mscale, Math.floorDiv(x, div), Math.floorDiv(z, div)); - fg.add(key); - - if(positions.containsKey(key)) { - return positions.get(key); - } - - if(fastpositions.containsKey(key)) { - if(!working.contains(key) && working.size() < 9) { - m.set(m.get() - 1); - - if(m.get() >= 0 && velocity < 50) { - working.add(key); - double mk = mscale; - double mkd = scale; - e.submit(() -> - { - PrecisionStopwatch ps = PrecisionStopwatch.start(); - BufferedImage b = renderer.render(x * mscale, z * mscale, div * mscale, div / (lowtile ? 3 : 1), currentType); - rs.put(ps.getMilliseconds()); - working.remove(key); - - if(mk == mscale && mkd == scale) { - positions.put(key, b); - } - }); - } - } - - return fastpositions.get(key); - } - - if(workingfast.contains(key) || workingfast.size() > Runtime.getRuntime().availableProcessors()) { - return null; - } - - workingfast.add(key); - double mk = mscale; - double mkd = scale; - eh.submit(() -> - { - PrecisionStopwatch ps = PrecisionStopwatch.start(); - BufferedImage b = renderer.render(x * mscale, z * mscale, div * mscale, div / lowq, currentType); - rs.put(ps.getMilliseconds()); - workingfast.remove(key); - - if(mk == mscale && mkd == scale) { - fastpositions.put(key, b); - } - }); - return null; - } - - private double getWorldX(double screenX) { - //return (mscale * screenX) + ((oxp / scale) * mscale); - return (mscale * screenX) + ((oxp / scale)); - } - - private double getWorldZ(double screenZ) { - return (mscale * screenZ) + ((ozp / scale) * mscale); - } - - private double getScreenX(double x) { - return (x / mscale) - ((oxp / scale)); - } - - private double getScreenZ(double z) { - return (z / mscale) - ((ozp / scale)); - } - - @Override - public void paint(Graphics gx) { - - if(engine.isClosed()) { - EventQueue.invokeLater(() -> { - try - { - setVisible(false); - } - - catch(Throwable e) - { - - } - }); - - return; - } - - if(updateEngine()) { - dump(); - } - - if(ox < oxp) { - velocity = Math.abs(ox - oxp) * 0.36; - oxp -= velocity; - } - - if(ox > oxp) { - velocity = Math.abs(oxp - ox) * 0.36; - oxp += velocity; - } - - if(oz < ozp) { - velocity = Math.abs(oz - ozp) * 0.36; - ozp -= velocity; - } - - if(oz > ozp) { - velocity = Math.abs(ozp - oz) * 0.36; - ozp += velocity; - } - - if(lx < hx) { - hx -= Math.abs(lx - hx) * 0.36; - } - - if(lx > hx) { - hx += Math.abs(hx - lx) * 0.36; - } - - if(lz < hz) { - hz -= Math.abs(lz - hz) * 0.36; - } - - if(lz > hz) { - hz += Math.abs(hz - lz) * 0.36; - } - - if(centities.flip()) { - J.s(() -> { - synchronized(lastEntities) { - lastEntities.clear(); - lastEntities.addAll(world.getEntitiesByClass(LivingEntity.class)); - } - }); - } - lowq = Math.max(Math.min((int) M.lerp(8, 28, velocity / 1000D), 28), 8); - PrecisionStopwatch p = PrecisionStopwatch.start(); - Graphics2D g = (Graphics2D) gx; - w = getWidth(); - h = getHeight(); - double vscale = scale; - scale = w / 12D; - - if(scale != vscale) { - positions.clear(); - } - - KSet gg = new KSet<>(); - int iscale = (int) scale; - g.setColor(Color.white); - g.clearRect(0, 0, w, h); - int posX = (int) oxp; - int posZ = (int) ozp; - m.set(3); - - for(int r = 0; r < Math.max(w, h); r += iscale) { - for(int i = -iscale; i < w + iscale; i += iscale) { - for(int j = -iscale; j < h + iscale; j += iscale) { - int a = i - (w / 2); - int b = j - (h / 2); - if(a * a + b * b <= r * r) { - BufferedImage t = getTile(gg, iscale, Math.floorDiv((posX / iscale) + i, iscale) * iscale, Math.floorDiv((posZ / iscale) + j, iscale) * iscale, m); - - if(t != null) { - g.drawImage(t, i - ((posX / iscale) % (iscale)), j - ((posZ / iscale) % (iscale)), iscale, iscale, (img, infoflags, x, y, width, height) -> true); - } - } - } - } - } - - p.end(); - - for(BlockPosition i : positions.k()) { - if(!gg.contains(i)) { - positions.remove(i); - } - } - - hanleFollow(); - renderOverlays(g); - - if(!isVisible()) { - return; - } - - if(!getParent().isVisible()) { - return; - } - - if(!getParent().getParent().isVisible()) { - return; - } - - J.a(() -> - { - J.sleep(eco ? 15 : 1); - repaint(); - }); - } - - private void hanleFollow() { - if(follow && player != null) { - animateTo(player.getLocation().getX(), player.getLocation().getZ()); - } - } - - private void renderOverlays(Graphics2D g) { - renderPlayer(g); - - if(help) { - renderOverlayHelp(g); - } else if(debug) { - renderOverlayDebug(g); - } - - renderOverlayLegend(g); - - renderHoverOverlay(g, shift); - if(!notifications.isEmpty()) { - renderNotification(g); - } - } - - private void renderOverlayLegend(Graphics2D g) { - KList l = new KList<>(); - l.add("Zoom: " + Form.pc(mscale, 0)); - l.add("Blocks: " + Form.f((int) mscale * w) + " by " + Form.f((int) mscale * h)); - l.add("BPP: " + Form.f(mscale, 1)); - l.add("Render Mode: " + Form.capitalizeWords(currentType.name().toLowerCase().replaceAll("\\Q_\\E", " "))); - - drawCardBR(g, l); - } - - private void renderNotification(Graphics2D g) { - drawCardCB(g, notifications.k()); - - for(String i : notifications.k()) { - if(M.ms() > notifications.get(i)) { - notifications.remove(i); - } - } - } - - private void renderPlayer(Graphics2D g) { - Player b = null; - - for(Player i : world.getPlayers()) { - b = i; - renderPosition(g, i.getLocation().getX(), i.getLocation().getZ()); - } - - synchronized(lastEntities) { - double dist = Double.MAX_VALUE; - LivingEntity h = null; - - for(LivingEntity i : lastEntities) { - if(i instanceof Player) { - continue; - } - - renderMobPosition(g, i, i.getLocation().getX(), i.getLocation().getZ()); - if(shift) { - double d = i.getLocation().distanceSquared(new Location(i.getWorld(), getWorldX(hx), i.getLocation().getY(), getWorldZ(hz))); - - if(d < dist) { - dist = d; - h = i; - } - } - } - - if(h != null && shift) { - g.setColor(Color.red); - g.fillRoundRect((int) getScreenX(h.getLocation().getX()) - 10, (int) getScreenZ(h.getLocation().getZ()) - 10, 20, 20, 20, 20); - KList k = new KList<>(); - k.add(Form.capitalizeWords(h.getType().name().toLowerCase(Locale.ROOT).replaceAll("\\Q_\\E", " ")) + h.getEntityId()); - - k.add("Pos: " + h.getLocation().getBlockX() + ", " + h.getLocation().getBlockY() + ", " + h.getLocation().getBlockZ()); - k.add("UUID: " + h.getUniqueId()); - k.add("HP: " + h.getHealth() + " / " + h.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()); - - drawCardTR(g, k); - } - } - - player = b; - } - - private void animateTo(double wx, double wz) { - double cx = getWorldX(getWidth() / 2); - double cz = getWorldZ(getHeight() / 2); - ox += (wx - cx); - oz += (wz - cz); - } - - private void renderPosition(Graphics2D g, double x, double z) { - if(texture != null) { - g.drawImage(texture, (int) getScreenX(x), (int) getScreenZ(z), 66, 66, (img, infoflags, xx, xy, width, height) -> true); - } else { - g.setColor(Color.darkGray); - g.fillRoundRect((int) getScreenX(x) - 15, (int) getScreenZ(z) - 15, 30, 30, 15, 15); - g.setColor(Color.cyan.darker().darker()); - g.fillRoundRect((int) getScreenX(x) - 10, (int) getScreenZ(z) - 10, 20, 20, 10, 10); - } - } - - private void renderMobPosition(Graphics2D g, LivingEntity e, double x, double z) { - g.setColor(Color.red.darker().darker()); - g.fillRoundRect((int) getScreenX(x) - 2, (int) getScreenZ(z) - 2, 4, 4, 4, 4); - } - - private void renderHoverOverlay(Graphics2D g, boolean detailed) { - IrisBiome biome = engine.getComplex().getTrueBiomeStream().get(getWorldX(hx), getWorldZ(hz)); - IrisRegion region = engine.getComplex().getRegionStream().get(getWorldX(hx), getWorldZ(hz)); - KList l = new KList<>(); - l.add("Biome: " + biome.getName()); - l.add("Region: " + region.getName() + "(" + region.getLoadKey() + ")"); - l.add("Block " + (int) getWorldX(hx) + ", " + (int) getWorldZ(hz)); - if(detailed) { - l.add("Chunk " + ((int) getWorldX(hx) >> 4) + ", " + ((int) getWorldZ(hz) >> 4)); - l.add("Region " + (((int) getWorldX(hx) >> 4) >> 5) + ", " + (((int) getWorldZ(hz) >> 4) >> 5)); - l.add("Key: " + biome.getLoadKey()); - l.add("File: " + biome.getLoadFile()); - } - - drawCardAt((float) hx, (float) hz, 0, 0, g, l); - } - - private void renderOverlayDebug(Graphics2D g) { - KList l = new KList<>(); - l.add("Velocity: " + (int) velocity); - l.add("Center Pos: " + Form.f((int) getWorldX(getWidth() / 2)) + ", " + Form.f((int) getWorldZ(getHeight() / 2))); - drawCardBL(g, l); - } - - private void renderOverlayHelp(Graphics2D g) { - KList l = new KList<>(); - l.add("/ to show this help screen"); - l.add("R to repaint the screen"); - l.add("F to follow first player"); - l.add("+/- to Change Zoom"); - l.add("\\ to reset zoom to 1"); - l.add("M to cycle render modes"); - l.add("P to toggle Tile Quality Mode"); - l.add("E to toggle Eco FPS Mode"); - - int ff = 0; - for(RenderType i : RenderType.values()) { - ff++; - l.add(ff + " to view " + Form.capitalizeWords(i.name().toLowerCase().replaceAll("\\Q_\\E", " "))); - } - - l.add("Shift for additional biome details (at cursor)"); - l.add("CTRL + Click to teleport to location"); - l.add("ALT + Click to open biome in VSCode"); - drawCardTL(g, l); - } - - private void drawCardTL(Graphics2D g, KList text) { - drawCardAt(0, 0, 0, 0, g, text); - } - - private void drawCardBR(Graphics2D g, KList text) { - drawCardAt(getWidth(), getHeight(), 1, 1, g, text); - } - - private void drawCardBL(Graphics2D g, KList text) { - drawCardAt(0, getHeight(), 0, 1, g, text); - } - - private void drawCardTR(Graphics2D g, KList text) { - drawCardAt(getWidth(), 0, 1, 0, g, text); - } - - private void open() { - IrisComplex complex = engine.getComplex(); - File r = null; - switch(currentType) { - case BIOME, LAYER_LOAD, DECORATOR_LOAD, OBJECT_LOAD, HEIGHT -> r = complex.getTrueBiomeStream().get(getWorldX(hx), getWorldZ(hz)).openInVSCode(); - case BIOME_LAND -> r = complex.getLandBiomeStream().get(getWorldX(hx), getWorldZ(hz)).openInVSCode(); - case BIOME_SEA -> r = complex.getSeaBiomeStream().get(getWorldX(hx), getWorldZ(hz)).openInVSCode(); - case REGION -> r = complex.getRegionStream().get(getWorldX(hx), getWorldZ(hz)).openInVSCode(); - case CAVE_LAND -> r = complex.getCaveBiomeStream().get(getWorldX(hx), getWorldZ(hz)).openInVSCode(); - } - - notify("Opening " + r.getPath() + " in VSCode"); - } - - private void teleport() { - J.s(() -> { - if(player != null) { - int xx = (int) getWorldX(hx); - int zz = (int) getWorldZ(hz); - int h = engine.getComplex().getRoundedHeighteightStream().get(xx, zz); - player.teleport(new Location(player.getWorld(), xx, h, zz)); - notify("Teleporting to " + xx + ", " + h + ", " + zz); - } else { - notify("No player in world, can't teleport."); - } - }); - } - - private void drawCardCB(Graphics2D g, KList text) { - drawCardAt(getWidth() / 2, getHeight(), 0.5, 1, g, text); - } - - private void drawCardCT(Graphics2D g, KList text) { - drawCardAt(getWidth() / 2, 0, 0.5, 0, g, text); - } - - private void drawCardAt(float x, float y, double pushX, double pushZ, Graphics2D g, KList text) { - g.setFont(new Font("Hevetica", Font.BOLD, 16)); - int h = 0; - int w = 0; - - for(String i : text) { - h += g.getFontMetrics().getHeight(); - w = Math.max(w, g.getFontMetrics().stringWidth(i)); - } - - w += 28; - h += 14; - - int cw = (int) ((w + 26) * pushX); - int ch = (int) ((h + 26) * pushZ); - - g.setColor(Color.darkGray); - g.fillRect((int) x + 7 + 2 - cw, (int) y + 12 + 2 - ch, w + 7, h); // Shadow - g.setColor(Color.gray); - g.fillRect((int) x + 7 + 1 - cw, (int) y + 12 + 1 - ch, w + 7, h); // Shadow - g.setColor(Color.white); - g.fillRect((int) x + 7 - cw, (int) y + 12 - ch, w + 7, h); - - g.setColor(Color.black); - int m = 0; - for(String i : text) { - g.drawString(i, x + 14 - cw, y + 14 - ch + (++m * g.getFontMetrics().getHeight())); - } - } - - public void mouseWheelMoved(MouseWheelEvent e) { - int notches = e.getWheelRotation(); - if(e.isControlDown()) { - return; - } - - //Iris.info("Blocks/Pixel: " + (mscale) + ", Blocks Wide: " + (w * mscale)); - positions.clear(); - fastpositions.clear(); - mscale = mscale + ((0.25 * mscale) * notches); - mscale = Math.max(mscale, 0.00001); - } - - @Override - public void mouseClicked(MouseEvent e) { - if(control) { - teleport(); - } else if(alt) { - open(); - } - } - - @Override - public void mousePressed(MouseEvent e) { - - } - - @Override - public void mouseReleased(MouseEvent e) { - - } - - @Override - public void mouseEntered(MouseEvent e) { - - } - - @Override - public void mouseExited(MouseEvent e) { - - } -} diff --git a/src/main/java/com/volmit/iris/core/gui/components/IrisRenderer.java b/src/main/java/com/volmit/iris/core/gui/components/IrisRenderer.java deleted file mode 100644 index f7bfe2dc3..000000000 --- a/src/main/java/com/volmit/iris/core/gui/components/IrisRenderer.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.gui.components; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.util.interpolation.IrisInterpolation; - -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.util.function.BiFunction; - -@SuppressWarnings("ClassCanBeRecord") -public class IrisRenderer { - private final Engine renderer; - - public IrisRenderer(Engine renderer) { - this.renderer = renderer; - } - - public BufferedImage render(double sx, double sz, double size, int resolution, RenderType currentType) { - BufferedImage image = new BufferedImage(resolution, resolution, BufferedImage.TYPE_INT_RGB); - BiFunction colorFunction = (d, dx) -> Color.black.getRGB(); - - switch(currentType) { - case BIOME, DECORATOR_LOAD, OBJECT_LOAD, LAYER_LOAD -> colorFunction = (x, z) -> renderer.getComplex().getTrueBiomeStream().get(x, z).getColor(renderer, currentType).getRGB(); - case BIOME_LAND -> colorFunction = (x, z) -> renderer.getComplex().getLandBiomeStream().get(x, z).getColor(renderer, currentType).getRGB(); - case BIOME_SEA -> colorFunction = (x, z) -> renderer.getComplex().getSeaBiomeStream().get(x, z).getColor(renderer, currentType).getRGB(); - case REGION -> colorFunction = (x, z) -> renderer.getComplex().getRegionStream().get(x, z).getColor(renderer.getComplex(), currentType).getRGB(); - case CAVE_LAND -> colorFunction = (x, z) -> renderer.getComplex().getCaveBiomeStream().get(x, z).getColor(renderer, currentType).getRGB(); - case HEIGHT -> colorFunction = (x, z) -> Color.getHSBColor(renderer.getComplex().getHeightStream().get(x, z).floatValue(), 100, 100).getRGB(); - } - - double x, z; - int i, j; - for(i = 0; i < resolution; i++) { - x = IrisInterpolation.lerp(sx, sx + size, (double) i / (double) (resolution)); - - for(j = 0; j < resolution; j++) { - z = IrisInterpolation.lerp(sz, sz + size, (double) j / (double) (resolution)); - image.setRGB(i, j, colorFunction.apply(x, z)); - } - } - - return image; - } -} diff --git a/src/main/java/com/volmit/iris/core/gui/components/RenderType.java b/src/main/java/com/volmit/iris/core/gui/components/RenderType.java deleted file mode 100644 index b473222ad..000000000 --- a/src/main/java/com/volmit/iris/core/gui/components/RenderType.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.gui.components; - -public enum RenderType { - BIOME, BIOME_LAND, BIOME_SEA, REGION, CAVE_LAND, HEIGHT, OBJECT_LOAD, DECORATOR_LOAD, LAYER_LOAD -} diff --git a/src/main/java/com/volmit/iris/core/gui/components/Renderer.java b/src/main/java/com/volmit/iris/core/gui/components/Renderer.java deleted file mode 100644 index b236d52db..000000000 --- a/src/main/java/com/volmit/iris/core/gui/components/Renderer.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.gui.components; - -import java.awt.Color; - -@FunctionalInterface -public interface Renderer { - Color draw(double x, double z); -} diff --git a/src/main/java/com/volmit/iris/core/gui/components/TileRender.java b/src/main/java/com/volmit/iris/core/gui/components/TileRender.java deleted file mode 100644 index 54fa5481d..000000000 --- a/src/main/java/com/volmit/iris/core/gui/components/TileRender.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.gui.components; - -import lombok.Builder; -import lombok.Data; - -import java.awt.image.BufferedImage; - -@Builder -@Data -public class TileRender { - private BufferedImage image; - private int quality; -} diff --git a/src/main/java/com/volmit/iris/core/link/ExternalDataProvider.java b/src/main/java/com/volmit/iris/core/link/ExternalDataProvider.java deleted file mode 100644 index 4725a5c90..000000000 --- a/src/main/java/com/volmit/iris/core/link/ExternalDataProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.volmit.iris.core.link; - -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import org.bukkit.Bukkit; -import org.bukkit.NamespacedKey; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; - -import java.util.MissingResourceException; - -@RequiredArgsConstructor -public abstract class ExternalDataProvider { - - @Getter - private final String pluginId; - - public Plugin getPlugin() { - return Bukkit.getPluginManager().getPlugin(pluginId); - } - - public boolean isPresent() { - return getPlugin() != null; - } - - public abstract void init(); - - public abstract BlockData getBlockData(NamespacedKey blockId) throws MissingResourceException; - - public abstract ItemStack getItemStack(NamespacedKey itemId) throws MissingResourceException; - - public abstract NamespacedKey[] getBlockTypes(); - - public abstract boolean isValidProvider(NamespacedKey namespace); -} diff --git a/src/main/java/com/volmit/iris/core/link/IrisPapiExpansion.java b/src/main/java/com/volmit/iris/core/link/IrisPapiExpansion.java deleted file mode 100644 index 116eb4839..000000000 --- a/src/main/java/com/volmit/iris/core/link/IrisPapiExpansion.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.link; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.platform.PlatformChunkGenerator; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; - -// See/update https://app.gitbook.com/@volmitsoftware/s/iris/compatability/papi/ -public class IrisPapiExpansion extends PlaceholderExpansion { - @Override - public String getIdentifier() { - return "iris"; - } - - @Override - public String getAuthor() { - return "Volmit Software"; - } - - @Override - public String getVersion() { - return Iris.instance.getDescription().getVersion(); - } - - @Override - public boolean persist() { - return false; - } - - @Override - public String onRequest(OfflinePlayer player, String p) { - Location l = null; - PlatformChunkGenerator a = null; - - if(player.isOnline()) { - l = player.getPlayer().getLocation(); - a = IrisToolbelt.access(l.getWorld()); - } - - if(p.equalsIgnoreCase("biome_name")) { - if(a != null) { - return a.getEngine().getBiome(l).getName(); - } - } else if(p.equalsIgnoreCase("biome_id")) { - if(a != null) { - return a.getEngine().getBiome(l).getLoadKey(); - } - } else if(p.equalsIgnoreCase("biome_file")) { - if(a != null) { - return a.getEngine().getBiome(l).getLoadFile().getPath(); - } - } else if(p.equalsIgnoreCase("region_name")) { - if(a != null) { - return a.getEngine().getRegion(l).getName(); - } - } else if(p.equalsIgnoreCase("region_id")) { - if(a != null) { - return a.getEngine().getRegion(l).getLoadKey(); - } - } else if(p.equalsIgnoreCase("region_file")) { - if(a != null) { - return a.getEngine().getRegion(l).getLoadFile().getPath(); - } - } else if(p.equalsIgnoreCase("terrain_slope")) { - if(a != null) { - return (a.getEngine()) - .getComplex().getSlopeStream() - .get(l.getX(), l.getZ()) + ""; - } - } else if(p.equalsIgnoreCase("terrain_height")) { - if(a != null) { - return Math.round(a.getEngine().getHeight(l.getBlockX(), l.getBlockZ())) + ""; - } - } else if(p.equalsIgnoreCase("world_mode")) { - if(a != null) { - return a.isStudio() ? "Studio" : "Production"; - } - } else if(p.equalsIgnoreCase("world_seed")) { - if(a != null) { - return a.getEngine().getSeedManager().getSeed() + ""; - } - } else if(p.equalsIgnoreCase("world_speed")) { - if(a != null) { - return a.getEngine().getGeneratedPerSecond() + "/s"; - } - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/core/link/ItemAdderDataProvider.java b/src/main/java/com/volmit/iris/core/link/ItemAdderDataProvider.java deleted file mode 100644 index d05ca3cf4..000000000 --- a/src/main/java/com/volmit/iris/core/link/ItemAdderDataProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.volmit.iris.core.link; - -import com.volmit.iris.util.collection.KList; -import dev.lone.itemsadder.api.CustomBlock; -import dev.lone.itemsadder.api.CustomStack; -import dev.lone.itemsadder.api.ItemsAdder; -import org.bukkit.NamespacedKey; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; - -import java.util.MissingResourceException; - -public class ItemAdderDataProvider extends ExternalDataProvider { - - public ItemAdderDataProvider() { - super("ItemsAdder"); - } - - @Override - public void init() { } - - @Override - public BlockData getBlockData(NamespacedKey blockId) throws MissingResourceException { - return CustomBlock.getBaseBlockData(blockId.toString()); - } - - @Override - public ItemStack getItemStack(NamespacedKey itemId) throws MissingResourceException { - CustomStack stack = CustomStack.getInstance(itemId.toString()); - if(stack == null) - throw new MissingResourceException("Failed to find ItemData!", itemId.getNamespace(), itemId.getKey()); - return stack.getItemStack(); - } - - @Override - public NamespacedKey[] getBlockTypes() { - KList keys = new KList<>(); - for(String s : ItemsAdder.getNamespacedBlocksNamesInConfig()) - keys.add(NamespacedKey.fromString(s)); - return keys.toArray(new NamespacedKey[0]); - } - - @Override - public boolean isValidProvider(NamespacedKey blockId) { - for(NamespacedKey k : getBlockTypes()) - if(k.equals(blockId)) { - return true; - } - return false; - } -} diff --git a/src/main/java/com/volmit/iris/core/link/MultiverseCoreLink.java b/src/main/java/com/volmit/iris/core/link/MultiverseCoreLink.java deleted file mode 100644 index 0a2d4f025..000000000 --- a/src/main/java/com/volmit/iris/core/link/MultiverseCoreLink.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.link; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.util.collection.KMap; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.WorldType; -import org.bukkit.plugin.Plugin; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Map; - -public class MultiverseCoreLink { - private final KMap worldNameTypes = new KMap<>(); - - public MultiverseCoreLink() { - - } - - public boolean addWorld(String worldName, IrisDimension dim, String seed) { - if(!isSupported()) { - return false; - } - - try { - Plugin p = getMultiverse(); - Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); - Method m = mvWorldManager.getClass().getDeclaredMethod("addWorld", - - String.class, World.Environment.class, String.class, WorldType.class, Boolean.class, String.class, boolean.class); - boolean b = (boolean) m.invoke(mvWorldManager, worldName, dim.getEnvironment(), seed, WorldType.NORMAL, false, "Iris", false); - saveConfig(); - return b; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return false; - } - - @SuppressWarnings("unchecked") - public Map getList() { - try { - Plugin p = getMultiverse(); - Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); - Field f = mvWorldManager.getClass().getDeclaredField("worldsFromTheConfig"); - f.setAccessible(true); - return (Map) f.get(mvWorldManager); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return null; - } - - public void removeFromConfig(World world) { - if(!isSupported()) { - return; - } - - getList().remove(world.getName()); - saveConfig(); - } - - public void removeFromConfig(String world) { - if(!isSupported()) { - return; - } - - getList().remove(world); - saveConfig(); - } - - public void saveConfig() { - try { - Plugin p = getMultiverse(); - Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); - mvWorldManager.getClass().getDeclaredMethod("saveWorldsConfig").invoke(mvWorldManager); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - public void assignWorldType(String worldName, String type) { - worldNameTypes.put(worldName, type); - } - - public String getWorldNameType(String worldName, String defaultType) { - try { - String t = worldNameTypes.get(worldName); - return t == null ? defaultType : t; - } catch(Throwable e) { - Iris.reportError(e); - return defaultType; - } - } - - public boolean isSupported() { - return getMultiverse() != null; - } - - public Plugin getMultiverse() { - - return Bukkit.getPluginManager().getPlugin("Multiverse-Core"); - } - - public String envName(World.Environment environment) { - if(environment == null) { - return "normal"; - } - - return switch(environment) { - case NORMAL -> "normal"; - case NETHER -> "nether"; - case THE_END -> "end"; - default -> environment.toString().toLowerCase(); - }; - - } -} diff --git a/src/main/java/com/volmit/iris/core/link/MythicMobsLink.java b/src/main/java/com/volmit/iris/core/link/MythicMobsLink.java deleted file mode 100644 index 96aabbb96..000000000 --- a/src/main/java/com/volmit/iris/core/link/MythicMobsLink.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.link; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.plugin.Plugin; - -import javax.annotation.Nullable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.function.BiFunction; - -public class MythicMobsLink { - - private Collection mobs; - private BiFunction spawnMobFunction; - - public MythicMobsLink() { - - } - - public boolean isEnabled() { - return getPlugin() != null; - } - - public Plugin getPlugin() { - return Bukkit.getPluginManager().getPlugin("MythicMobs"); - } - - /** - * Spawn a mythic mob at this location - * - * @param mob - * The mob - * @param location - * The location - * @return The mob, or null if it can't be spawned - */ - public @Nullable - Entity spawnMob(String mob, Location location) { - if(!isEnabled()) return null; - - if(spawnMobFunction != null) { - return spawnMobFunction.apply(mob, location); - } - - try { - Class mythicMobClass = Class.forName("io.lumine.mythic.bukkit.MythicBukkit"); - Method getInst = mythicMobClass.getDeclaredMethod("inst"); - Object inst = getInst.invoke(null); - Method getAPIHelper = mythicMobClass.getDeclaredMethod("getAPIHelper"); - Object apiHelper = getAPIHelper.invoke(inst); - Method spawnMobMethod = apiHelper.getClass().getDeclaredMethod("spawnMythicMob", String.class, Location.class); - - spawnMobFunction = (str, loc) -> { - try { - return (Entity) spawnMobMethod.invoke(apiHelper, str, loc); - } catch(InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - }; - - return spawnMobFunction.apply(mob, location); - } catch(Exception e) { - e.printStackTrace(); - - } - return null; - } - - public Collection getMythicMobTypes() { - if(mobs != null) { - return mobs; - } - - if(isEnabled()) { - - try { - Class mythicMobClass = Class.forName("io.lumine.xikage.mythicmobs.MythicMobs"); - Method getInst = mythicMobClass.getDeclaredMethod("inst"); - Object inst = getInst.invoke(null); - Method getMobManager = mythicMobClass.getDeclaredMethod("getMobManager"); - Object mobManager = getMobManager.invoke(inst); - Method getMobNames = mobManager.getClass().getDeclaredMethod("getMobNames"); - mobs = (Collection) getMobNames.invoke(mobManager); - return mobs; - } catch(ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } - - return new ArrayList<>(); - } -} diff --git a/src/main/java/com/volmit/iris/core/link/OraxenDataProvider.java b/src/main/java/com/volmit/iris/core/link/OraxenDataProvider.java deleted file mode 100644 index 138cecaa7..000000000 --- a/src/main/java/com/volmit/iris/core/link/OraxenDataProvider.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.link; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import io.th0rgal.oraxen.items.ItemBuilder; -import io.th0rgal.oraxen.items.OraxenItems; -import io.th0rgal.oraxen.mechanics.MechanicFactory; -import io.th0rgal.oraxen.mechanics.MechanicsManager; -import io.th0rgal.oraxen.mechanics.provided.gameplay.block.BlockMechanic; -import io.th0rgal.oraxen.mechanics.provided.gameplay.block.BlockMechanicFactory; -import io.th0rgal.oraxen.mechanics.provided.gameplay.noteblock.NoteBlockMechanicFactory; -import io.th0rgal.oraxen.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.MultipleFacing; -import org.bukkit.inventory.ItemStack; - -import java.lang.reflect.Field; -import java.util.Map; -import java.util.MissingResourceException; -import java.util.Optional; - -public class OraxenDataProvider extends ExternalDataProvider { - - private static final String FIELD_FACTORIES_MAP = "FACTORIES_BY_MECHANIC_ID"; - - private Map factories; - - public OraxenDataProvider() { super("Oraxen"); } - - @Override - public void init() { - try { - Field f = MechanicsManager.class.getDeclaredField(FIELD_FACTORIES_MAP); - f.setAccessible(true); - factories = (Map) f.get(null); - } catch(NoSuchFieldException | IllegalAccessException e) { - Iris.error("Failed to set up Oraxen Link:"); - Iris.error("\t" + e.getClass().getSimpleName()); - } - } - - @Override - public BlockData getBlockData(NamespacedKey blockId) throws MissingResourceException { - MechanicFactory f = getFactory(blockId); - if(f instanceof NoteBlockMechanicFactory) - return ((NoteBlockMechanicFactory)f).createNoteBlockData(blockId.getKey()); - else if(f instanceof BlockMechanicFactory) { - MultipleFacing newBlockData = (MultipleFacing) Bukkit.createBlockData(Material.MUSHROOM_STEM); - Utils.setBlockFacing(newBlockData, ((BlockMechanic)f.getMechanic(blockId.getKey())).getCustomVariation()); - return newBlockData; - } else - throw new MissingResourceException("Failed to find BlockData!", blockId.getNamespace(), blockId.getKey()); - } - - @Override - public ItemStack getItemStack(NamespacedKey itemId) throws MissingResourceException { - Optional opt = OraxenItems.getOptionalItemById(itemId.getKey()); - return opt.orElseThrow(() -> new MissingResourceException("Failed to find ItemData!", itemId.getNamespace(), itemId.getKey())).build(); - } - - @Override - public NamespacedKey[] getBlockTypes() { - KList names = new KList<>(); - for(String name : OraxenItems.getItemNames()) { - try { - NamespacedKey key = new NamespacedKey("oraxen", name); - if(getBlockData(key) != null) - names.add(key); - } catch(MissingResourceException ignored) { } - } - - return names.toArray(new NamespacedKey[0]); - } - - @Override - public boolean isPresent() { - return super.isPresent() && factories != null; - } - - @Override - public boolean isValidProvider(NamespacedKey key) { - return key.getNamespace().equalsIgnoreCase("oraxen"); - } - - private MechanicFactory getFactory(NamespacedKey key) throws MissingResourceException { - return factories.values().stream() - .filter(i -> i.getItems().contains(key.getKey())) - .findFirst() - .orElseThrow(() -> new MissingResourceException("Failed to find BlockData!", key.getNamespace(), key.getKey())); - } -} diff --git a/src/main/java/com/volmit/iris/core/link/WorldEditLink.java b/src/main/java/com/volmit/iris/core/link/WorldEditLink.java deleted file mode 100644 index 903842093..000000000 --- a/src/main/java/com/volmit/iris/core/link/WorldEditLink.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.volmit.iris.core.link; - -import com.volmit.iris.util.data.Cuboid; -import org.bukkit.World; -import org.bukkit.entity.Player; - -public class WorldEditLink { - public static Cuboid getSelection(Player p) - { - try - { - Object instance = Class.forName("com.sk89q.worldedit.WorldEdit").getDeclaredMethod("getInstance").invoke(null); - Object sessionManager = instance.getClass().getDeclaredMethod("getSessionManager").invoke(instance); - Object player = Class.forName("com.sk89q.worldedit.bukkit.BukkitAdapter").getDeclaredMethod("adapt", Player.class).invoke(null, p); - Object localSession = sessionManager.getClass().getDeclaredMethod("getIfPresent", Class.forName("com.sk89q.worldedit.session.SessionOwner")).invoke(sessionManager, player); - Object world = Class.forName("com.sk89q.worldedit.bukkit.BukkitAdapter").getDeclaredMethod("adapt", World.class).invoke(null, p.getWorld()); - Object region = localSession.getClass().getDeclaredMethod("getSelection", world.getClass()).invoke(localSession, world); - Object min = region.getClass().getDeclaredMethod("getMinimumPoint").invoke(region); - Object max = region.getClass().getDeclaredMethod("getMaximumPoint").invoke(region); - return new Cuboid(p.getWorld(), - (int)min.getClass().getDeclaredMethod("getX").invoke(min), - (int)min.getClass().getDeclaredMethod("getY").invoke(min), - (int)min.getClass().getDeclaredMethod("getZ").invoke(min), - (int)min.getClass().getDeclaredMethod("getX").invoke(max), - (int)min.getClass().getDeclaredMethod("getY").invoke(max), - (int)min.getClass().getDeclaredMethod("getZ").invoke(max) - ); - } - - catch(Throwable e) - { - - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/core/loader/ImageResourceLoader.java b/src/main/java/com/volmit/iris/core/loader/ImageResourceLoader.java deleted file mode 100644 index 142b3a2dd..000000000 --- a/src/main/java/com/volmit/iris/core/loader/ImageResourceLoader.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.loader; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.engine.object.IrisImage; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.data.KCache; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.File; - -public class ImageResourceLoader extends ResourceLoader { - public ImageResourceLoader(File root, IrisData idm, String folderName, String resourceTypeName) { - super(root, idm, folderName, resourceTypeName, IrisImage.class); - loadCache = new KCache<>(this::loadRaw, IrisSettings.get().getPerformance().getObjectLoaderCacheSize()); - } - - public boolean supportsSchemas() { - return false; - } - - public long getSize() { - return loadCache.getSize(); - } - - public long getTotalStorage() { - return getSize(); - } - - protected IrisImage loadFile(File j, String name) { - try { - PrecisionStopwatch p = PrecisionStopwatch.start(); - BufferedImage bu = ImageIO.read(j); - IrisImage img = new IrisImage(bu); - img.setLoadFile(j); - img.setLoader(manager); - img.setLoadKey(name); - logLoad(j, img); - tlt.addAndGet(p.getMilliseconds()); - return img; - } catch(Throwable e) { - Iris.reportError(e); - Iris.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage()); - return null; - } - } - - public String[] getPossibleKeys() { - if(possibleKeys != null) { - return possibleKeys; - } - - Iris.debug("Building " + resourceTypeName + " Possibility Lists"); - KSet m = new KSet<>(); - - for(File i : getFolders()) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".png")) { - m.add(j.getName().replaceAll("\\Q.png\\E", "")); - } else if(j.isDirectory()) { - for(File k : j.listFiles()) { - if(k.isFile() && k.getName().endsWith(".png")) { - m.add(j.getName() + "/" + k.getName().replaceAll("\\Q.png\\E", "")); - } else if(k.isDirectory()) { - for(File l : k.listFiles()) { - if(l.isFile() && l.getName().endsWith(".png")) { - m.add(j.getName() + "/" + k.getName() + "/" + l.getName().replaceAll("\\Q.png\\E", "")); - } - } - } - } - } - } - } - - KList v = new KList<>(m); - possibleKeys = v.toArray(new String[0]); - return possibleKeys; - } - - public File findFile(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".png") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return j; - } - } - - File file = new File(i, name + ".png"); - - if(file.exists()) { - return file; - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - public IrisImage load(String name) { - return load(name, true); - } - - private IrisImage loadRaw(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".png") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return loadFile(j, name); - } - } - - File file = new File(i, name + ".png"); - - if(file.exists()) { - return loadFile(file, name); - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - public IrisImage load(String name, boolean warn) { - return loadCache.get(name); - } -} diff --git a/src/main/java/com/volmit/iris/core/loader/IrisData.java b/src/main/java/com/volmit/iris/core/loader/IrisData.java deleted file mode 100644 index 3b3ff757a..000000000 --- a/src/main/java/com/volmit/iris/core/loader/IrisData.java +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.loader; - -import com.google.gson.ExclusionStrategy; -import com.google.gson.FieldAttributes; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; -import com.google.gson.stream.JsonWriter; -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.*; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.engine.object.matter.IrisMatterObject; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import lombok.Data; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.Objects; -import java.util.function.Function; - -@Data -public class IrisData implements ExclusionStrategy, TypeAdapterFactory { - private static final KMap dataLoaders = new KMap<>(); - private final File dataFolder; - private final int id; - private boolean closed = false; - private ResourceLoader biomeLoader; - private ResourceLoader lootLoader; - private ResourceLoader regionLoader; - private ResourceLoader dimensionLoader; - private ResourceLoader generatorLoader; - private ResourceLoader jigsawPieceLoader; - private ResourceLoader jigsawPoolLoader; - private ResourceLoader jigsawStructureLoader; - private ResourceLoader entityLoader; - private ResourceLoader markerLoader; - private ResourceLoader spawnerLoader; - private ResourceLoader modLoader; - private ResourceLoader blockLoader; - private ResourceLoader expressionLoader; - private ResourceLoader objectLoader; - private ResourceLoader matterLoader; - private ResourceLoader imageLoader; - private ResourceLoader scriptLoader; - private ResourceLoader caveLoader; - private ResourceLoader ravineLoader; - private ResourceLoader matterObjectLoader; - private KMap> possibleSnippets; - private Gson gson; - private Gson snippetLoader; - private GsonBuilder builder; - private KMap, ResourceLoader> loaders = new KMap<>(); - private Engine engine; - - private IrisData(File dataFolder) { - this.engine = null; - this.dataFolder = dataFolder; - this.id = RNG.r.imax(); - hotloaded(); - } - - public static IrisData get(File dataFolder) { - return dataLoaders.computeIfAbsent(dataFolder, IrisData::new); - } - - public static void dereference() { - dataLoaders.v().forEach(IrisData::cleanupEngine); - } - - public static int cacheSize() { - int m = 0; - for(IrisData i : dataLoaders.values()) { - for(ResourceLoader j : i.getLoaders().values()) { - m += j.getLoadCache().getSize(); - } - } - - return m; - } - - private static void printData(ResourceLoader rl) { - Iris.warn(" " + rl.getResourceTypeName() + " @ /" + rl.getFolderName() + ": Cache=" + rl.getLoadCache().getSize() + " Folders=" + rl.getFolders().size()); - } - - public static IrisObject loadAnyObject(String key) { - return loadAny(key, (dm) -> dm.getObjectLoader().load(key, false)); - } - public static IrisMatterObject loadAnyMatter(String key) { - return loadAny(key, (dm) -> dm.getMatterLoader().load(key, false)); - } - - public static IrisBiome loadAnyBiome(String key) { - return loadAny(key, (dm) -> dm.getBiomeLoader().load(key, false)); - } - - public static IrisExpression loadAnyExpression(String key) { - return loadAny(key, (dm) -> dm.getExpressionLoader().load(key, false)); - } - - public static IrisMod loadAnyMod(String key) { - return loadAny(key, (dm) -> dm.getModLoader().load(key, false)); - } - - public static IrisJigsawPiece loadAnyJigsawPiece(String key) { - return loadAny(key, (dm) -> dm.getJigsawPieceLoader().load(key, false)); - } - - public static IrisJigsawPool loadAnyJigsawPool(String key) { - return loadAny(key, (dm) -> dm.getJigsawPoolLoader().load(key, false)); - } - - public static IrisEntity loadAnyEntity(String key) { - return loadAny(key, (dm) -> dm.getEntityLoader().load(key, false)); - } - - public static IrisLootTable loadAnyLootTable(String key) { - return loadAny(key, (dm) -> dm.getLootLoader().load(key, false)); - } - - public static IrisBlockData loadAnyBlock(String key) { - return loadAny(key, (dm) -> dm.getBlockLoader().load(key, false)); - } - - public static IrisSpawner loadAnySpaner(String key) { - return loadAny(key, (dm) -> dm.getSpawnerLoader().load(key, false)); - } - - public static IrisScript loadAnyScript(String key) { - return loadAny(key, (dm) -> dm.getScriptLoader().load(key, false)); - } - - public static IrisRavine loadAnyRavine(String key) { - return loadAny(key, (dm) -> dm.getRavineLoader().load(key, false)); - } - - public static IrisRegion loadAnyRegion(String key) { - return loadAny(key, (dm) -> dm.getRegionLoader().load(key, false)); - } - - public static IrisMarker loadAnyMarker(String key) { - return loadAny(key, (dm) -> dm.getMarkerLoader().load(key, false)); - } - - public static IrisCave loadAnyCave(String key) { - return loadAny(key, (dm) -> dm.getCaveLoader().load(key, false)); - } - - public static IrisImage loadAnyImage(String key) { - return loadAny(key, (dm) -> dm.getImageLoader().load(key, false)); - } - - public static IrisDimension loadAnyDimension(String key) { - return loadAny(key, (dm) -> dm.getDimensionLoader().load(key, false)); - } - - public static IrisJigsawStructure loadAnyJigsawStructure(String key) { - return loadAny(key, (dm) -> dm.getJigsawStructureLoader().load(key, false)); - } - - public static IrisGenerator loadAnyGenerator(String key) { - return loadAny(key, (dm) -> dm.getGeneratorLoader().load(key, false)); - } - - public static T loadAny(String key, Function v) { - try { - for(File i : Objects.requireNonNull(Iris.instance.getDataFolder("packs").listFiles())) { - if(i.isDirectory()) { - IrisData dm = get(i); - T t = v.apply(dm); - - if(t != null) { - return t; - } - } - } - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return null; - } - - public ResourceLoader getTypedLoaderFor(File f) { - String[] k = f.getPath().split("\\Q" + File.separator + "\\E"); - - for(String i : k) { - for(ResourceLoader j : loaders.values()) { - if(j.getFolderName().equals(i)) { - return j; - } - } - } - - return null; - } - - public void cleanupEngine() { - if(engine != null && engine.isClosed()) { - engine = null; - Iris.debug("Dereferenced Data " + getId() + " " + getDataFolder()); - } - } - - public void preprocessObject(IrisRegistrant t) { - try { - IrisContext ctx = IrisContext.get(); - Engine engine = this.engine; - - if(engine == null && ctx != null && ctx.getEngine() != null) { - engine = ctx.getEngine(); - } - - if(engine == null && t.getPreprocessors().isNotEmpty()) { - Iris.error("Failed to preprocess object " + t.getLoadKey() + " because there is no engine context here. (See stack below)"); - try { - throw new RuntimeException(); - } catch(Throwable ex) { - ex.printStackTrace(); - } - } - - if(engine != null && t.getPreprocessors().isNotEmpty()) { - synchronized(this) { - engine.getExecution().getAPI().setPreprocessorObject(t); - - for(String i : t.getPreprocessors()) { - engine.getExecution().execute(i); - Iris.debug("Loader<" + C.GREEN + t.getTypeName() + C.LIGHT_PURPLE + "> iprocess " + C.YELLOW + t.getLoadKey() + C.LIGHT_PURPLE + " in " + i); - } - } - } - } catch(Throwable e) { - Iris.error("Failed to preprocess object!"); - e.printStackTrace(); - } - } - - public void close() { - closed = true; - dump(); - } - - public IrisData copy() { - return IrisData.get(dataFolder); - } - - private ResourceLoader registerLoader(Class registrant) { - try { - IrisRegistrant rr = registrant.getConstructor().newInstance(); - ResourceLoader r = null; - if(registrant.equals(IrisObject.class)) { - r = (ResourceLoader) new ObjectResourceLoader(dataFolder, this, rr.getFolderName(), - rr.getTypeName()); - } else if(registrant.equals(IrisMatterObject.class)) { - r = (ResourceLoader) new MatterObjectResourceLoader(dataFolder, this, rr.getFolderName(), - rr.getTypeName()); - } else if(registrant.equals(IrisScript.class)) { - r = (ResourceLoader) new ScriptResourceLoader(dataFolder, this, rr.getFolderName(), - rr.getTypeName()); - } else if(registrant.equals(IrisImage.class)) { - r = (ResourceLoader) new ImageResourceLoader(dataFolder, this, rr.getFolderName(), - rr.getTypeName()); - } else { - J.attempt(() -> registrant.getConstructor().newInstance().registerTypeAdapters(builder)); - r = new ResourceLoader<>(dataFolder, this, rr.getFolderName(), rr.getTypeName(), registrant); - } - - loaders.put(registrant, r); - - return r; - } catch(Throwable e) { - e.printStackTrace(); - Iris.error("Failed to create loader! " + registrant.getCanonicalName()); - } - - return null; - } - - public synchronized void hotloaded() { - possibleSnippets = new KMap<>(); - builder = new GsonBuilder() - .addDeserializationExclusionStrategy(this) - .addSerializationExclusionStrategy(this) - .setLenient() - .registerTypeAdapterFactory(this) - .setPrettyPrinting(); - loaders.clear(); - File packs = dataFolder; - packs.mkdirs(); - this.lootLoader = registerLoader(IrisLootTable.class); - this.spawnerLoader = registerLoader(IrisSpawner.class); - this.entityLoader = registerLoader(IrisEntity.class); - this.regionLoader = registerLoader(IrisRegion.class); - this.biomeLoader = registerLoader(IrisBiome.class); - this.modLoader = registerLoader(IrisMod.class); - this.dimensionLoader = registerLoader(IrisDimension.class); - this.jigsawPoolLoader = registerLoader(IrisJigsawPool.class); - this.jigsawStructureLoader = registerLoader(IrisJigsawStructure.class); - this.jigsawPieceLoader = registerLoader(IrisJigsawPiece.class); - this.generatorLoader = registerLoader(IrisGenerator.class); - this.caveLoader = registerLoader(IrisCave.class); - this.markerLoader = registerLoader(IrisMarker.class); - this.ravineLoader = registerLoader(IrisRavine.class); - this.blockLoader = registerLoader(IrisBlockData.class); - this.expressionLoader = registerLoader(IrisExpression.class); - this.objectLoader = registerLoader(IrisObject.class); - this.imageLoader = registerLoader(IrisImage.class); - this.scriptLoader = registerLoader(IrisScript.class); - this.matterObjectLoader = registerLoader(IrisMatterObject.class); - gson = builder.create(); - } - - public void dump() { - for(ResourceLoader i : loaders.values()) { - i.clearCache(); - } - } - - public void clearLists() { - for(ResourceLoader i : loaders.values()) { - i.clearList(); - } - } - - public String toLoadKey(File f) { - if(f.getPath().startsWith(getDataFolder().getPath())) { - String[] full = f.getPath().split("\\Q" + File.separator + "\\E"); - String[] df = getDataFolder().getPath().split("\\Q" + File.separator + "\\E"); - StringBuilder g = new StringBuilder(); - boolean m = true; - for(int i = 0; i < full.length; i++) { - if(i >= df.length) { - if(m) { - m = false; - continue; - } - - g.append("/").append(full[i]); - } - } - - String ff = g.substring(1).split("\\Q.\\E")[0]; - return ff; - } else { - Iris.error("Forign file from loader " + f.getPath() + " (loader realm: " + getDataFolder().getPath() + ")"); - } - - Iris.error("Failed to load " + f.getPath() + " (loader realm: " + getDataFolder().getPath() + ")"); - - return null; - } - - @Override - public boolean shouldSkipField(FieldAttributes f) { - return false; - } - - @Override - public boolean shouldSkipClass(Class c) { - if(c.equals(AtomicCache.class)) { - return true; - } else return c.equals(ChronoLatch.class); - } - - @Override - public TypeAdapter create(Gson gson, TypeToken typeToken) { - if(!typeToken.getRawType().isAnnotationPresent(Snippet.class)) { - return null; - } - - String snippetType = typeToken.getRawType().getDeclaredAnnotation(Snippet.class).value(); - - return new TypeAdapter<>() { - @Override - public void write(JsonWriter jsonWriter, T t) throws IOException { - gson.getDelegateAdapter(IrisData.this, typeToken).write(jsonWriter, t); - } - - @Override - public T read(JsonReader reader) throws IOException { - TypeAdapter adapter = gson.getDelegateAdapter(IrisData.this, typeToken); - - if(reader.peek().equals(JsonToken.STRING)) { - String r = reader.nextString(); - - if(r.startsWith("snippet/" + snippetType + "/")) { - File f = new File(getDataFolder(), r + ".json"); - - if(f.exists()) { - try { - JsonReader snippetReader = new JsonReader(new FileReader(f)); - return adapter.read(snippetReader); - } catch(Throwable e) { - Iris.error("Couldn't read snippet " + r + " in " + reader.getPath() + " (" + e.getMessage() + ")"); - } - } else { - Iris.error("Couldn't find snippet " + r + " in " + reader.getPath()); - } - } - - return null; - } - - try { - return adapter.read(reader); - } catch(Throwable e) { - Iris.error("Failed to read " + typeToken.getRawType().getCanonicalName() + "... faking objects a little to load the file at least."); - try { - return (T) typeToken.getRawType().getConstructor().newInstance(); - } catch(Throwable ignored) { - - } - } - return null; - } - }; - } - - public KList getPossibleSnippets(String f) { - return possibleSnippets.computeIfAbsent(f, (k) -> { - KList l = new KList<>(); - - File snippetFolder = new File(getDataFolder(), "snippet/" + f); - - if(snippetFolder.exists() && snippetFolder.isDirectory()) { - for(File i : snippetFolder.listFiles()) { - l.add("snippet/" + f + "/" + i.getName().split("\\Q.\\E")[0]); - } - } - - return l; - }); - } - - public boolean isClosed() { - return closed; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/core/loader/IrisRegistrant.java b/src/main/java/com/volmit/iris/core/loader/IrisRegistrant.java deleted file mode 100644 index 7625b9b46..000000000 --- a/src/main/java/com/volmit/iris/core/loader/IrisRegistrant.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.loader; - -import com.google.gson.GsonBuilder; -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.IrisScript; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.Data; - -import java.awt.Desktop; -import java.io.File; - -@Data -public abstract class IrisRegistrant { - @Desc("Preprocess this object in-memory when it's loaded, run scripts using the variable 'Iris.getPreprocessorObject()' and modify properties about this object before it's used.") - @RegistryListResource(IrisScript.class) - @ArrayType(min = 1, type = String.class) - private KList preprocessors = new KList<>(); - - private transient IrisData loader; - - private transient String loadKey; - - private transient File loadFile; - - public abstract String getFolderName(); - - public abstract String getTypeName(); - - public void registerTypeAdapters(GsonBuilder builder) { - - } - - public File openInVSCode() { - try { - Desktop.getDesktop().open(getLoadFile()); - } catch(Throwable e) { - Iris.reportError(e); - } - - return getLoadFile(); - } - - public abstract void scanForErrors(JSONObject p, VolmitSender sender); -} diff --git a/src/main/java/com/volmit/iris/core/loader/MatterObjectResourceLoader.java b/src/main/java/com/volmit/iris/core/loader/MatterObjectResourceLoader.java deleted file mode 100644 index 28ee0d1f6..000000000 --- a/src/main/java/com/volmit/iris/core/loader/MatterObjectResourceLoader.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.loader; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.engine.object.matter.IrisMatterObject; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.data.KCache; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; - -import java.io.File; - -public class MatterObjectResourceLoader extends ResourceLoader { - public MatterObjectResourceLoader(File root, IrisData idm, String folderName, String resourceTypeName) { - super(root, idm, folderName, resourceTypeName, IrisMatterObject.class); - loadCache = new KCache<>(this::loadRaw, IrisSettings.get().getPerformance().getObjectLoaderCacheSize()); - } - - public boolean supportsSchemas() { - return false; - } - - public long getSize() { - return loadCache.getSize(); - } - - public long getTotalStorage() { - return getSize(); - } - - protected IrisMatterObject loadFile(File j, String name) { - try { - PrecisionStopwatch p = PrecisionStopwatch.start(); - IrisMatterObject t = IrisMatterObject.from(j); - t.setLoadKey(name); - t.setLoader(manager); - t.setLoadFile(j); - logLoad(j, t); - tlt.addAndGet(p.getMilliseconds()); - return t; - } catch(Throwable e) { - Iris.reportError(e); - Iris.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage()); - return null; - } - } - - public String[] getPossibleKeys() { - if(possibleKeys != null) { - return possibleKeys; - } - - Iris.debug("Building " + resourceTypeName + " Possibility Lists"); - KSet m = new KSet<>(); - - for(File i : getFolders()) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".mat")) { - m.add(j.getName().replaceAll("\\Q.mat\\E", "")); - } else if(j.isDirectory()) { - for(File k : j.listFiles()) { - if(k.isFile() && k.getName().endsWith(".mat")) { - m.add(j.getName() + "/" + k.getName().replaceAll("\\Q.mat\\E", "")); - } else if(k.isDirectory()) { - for(File l : k.listFiles()) { - if(l.isFile() && l.getName().endsWith(".mat")) { - m.add(j.getName() + "/" + k.getName() + "/" + l.getName().replaceAll("\\Q.mat\\E", "")); - } - } - } - } - } - } - } - - KList v = new KList<>(m); - possibleKeys = v.toArray(new String[0]); - return possibleKeys; - } - - public File findFile(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".mat") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return j; - } - } - - File file = new File(i, name + ".mat"); - - if(file.exists()) { - return file; - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - public IrisMatterObject load(String name) { - return load(name, true); - } - - private IrisMatterObject loadRaw(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".mat") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return loadFile(j, name); - } - } - - File file = new File(i, name + ".mat"); - - if(file.exists()) { - return loadFile(file, name); - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - public IrisMatterObject load(String name, boolean warn) { - return loadCache.get(name); - } -} diff --git a/src/main/java/com/volmit/iris/core/loader/ObjectResourceLoader.java b/src/main/java/com/volmit/iris/core/loader/ObjectResourceLoader.java deleted file mode 100644 index 5f1be6ee0..000000000 --- a/src/main/java/com/volmit/iris/core/loader/ObjectResourceLoader.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.loader; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.data.KCache; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; - -import java.io.File; - -public class ObjectResourceLoader extends ResourceLoader { - public ObjectResourceLoader(File root, IrisData idm, String folderName, String resourceTypeName) { - super(root, idm, folderName, resourceTypeName, IrisObject.class); - loadCache = new KCache<>(this::loadRaw, IrisSettings.get().getPerformance().getObjectLoaderCacheSize()); - } - - public boolean supportsSchemas() { - return false; - } - - public long getSize() { - return loadCache.getSize(); - } - - public long getTotalStorage() { - return getSize(); - } - - protected IrisObject loadFile(File j, String name) { - try { - PrecisionStopwatch p = PrecisionStopwatch.start(); - IrisObject t = new IrisObject(0, 0, 0); - t.read(j); - t.setLoadKey(name); - t.setLoader(manager); - t.setLoadFile(j); - logLoad(j, t); - tlt.addAndGet(p.getMilliseconds()); - return t; - } catch(Throwable e) { - Iris.reportError(e); - Iris.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage()); - return null; - } - } - - public String[] getPossibleKeys() { - if(possibleKeys != null) { - return possibleKeys; - } - - Iris.debug("Building " + resourceTypeName + " Possibility Lists"); - KSet m = new KSet<>(); - - for(File i : getFolders()) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".iob")) { - m.add(j.getName().replaceAll("\\Q.iob\\E", "")); - } else if(j.isDirectory()) { - for(File k : j.listFiles()) { - if(k.isFile() && k.getName().endsWith(".iob")) { - m.add(j.getName() + "/" + k.getName().replaceAll("\\Q.iob\\E", "")); - } else if(k.isDirectory()) { - for(File l : k.listFiles()) { - if(l.isFile() && l.getName().endsWith(".iob")) { - m.add(j.getName() + "/" + k.getName() + "/" + l.getName().replaceAll("\\Q.iob\\E", "")); - } - } - } - } - } - } - } - - KList v = new KList<>(m); - possibleKeys = v.toArray(new String[0]); - return possibleKeys; - } - - public File findFile(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".iob") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return j; - } - } - - File file = new File(i, name + ".iob"); - - if(file.exists()) { - return file; - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - public IrisObject load(String name) { - return load(name, true); - } - - private IrisObject loadRaw(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".iob") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return loadFile(j, name); - } - } - - File file = new File(i, name + ".iob"); - - if(file.exists()) { - return loadFile(file, name); - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - public IrisObject load(String name, boolean warn) { - return loadCache.get(name); - } -} diff --git a/src/main/java/com/volmit/iris/core/loader/ResourceLoader.java b/src/main/java/com/volmit/iris/core/loader/ResourceLoader.java deleted file mode 100644 index e1e8f6a6f..000000000 --- a/src/main/java/com/volmit/iris/core/loader/ResourceLoader.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.loader; - -import com.google.common.util.concurrent.AtomicDouble; -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.project.SchemaBuilder; -import com.volmit.iris.core.service.PreservationSVC; -import com.volmit.iris.engine.framework.MeteredCache; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.data.KCache; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONArray; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.Data; - -import java.io.File; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.stream.Stream; - -@Data -public class ResourceLoader implements MeteredCache { - public static final AtomicDouble tlt = new AtomicDouble(0); - private static final int CACHE_SIZE = 100000; - protected File root; - protected String folderName; - protected String resourceTypeName; - protected KCache loadCache; - protected final AtomicReference> folderCache; - protected Class objectClass; - protected String cname; - protected String[] possibleKeys = null; - protected IrisData manager; - protected AtomicInteger loads; - protected ChronoLatch sec; - - public ResourceLoader(File root, IrisData manager, String folderName, String resourceTypeName, Class objectClass) { - this.manager = manager; - folderCache = new AtomicReference<>(); - sec = new ChronoLatch(5000); - loads = new AtomicInteger(); - this.objectClass = objectClass; - cname = objectClass.getCanonicalName(); - this.resourceTypeName = resourceTypeName; - this.root = root; - this.folderName = folderName; - loadCache = new KCache<>(this::loadRaw, IrisSettings.get().getPerformance().getResourceLoaderCacheSize()); - Iris.debug("Loader<" + C.GREEN + resourceTypeName + C.LIGHT_PURPLE + "> created in " + C.RED + "IDM/" + manager.getId() + C.LIGHT_PURPLE + " on " + C.GRAY + manager.getDataFolder().getPath()); - Iris.service(PreservationSVC.class).registerCache(this); - } - - public JSONObject buildSchema() { - Iris.debug("Building Schema " + objectClass.getSimpleName() + " " + root.getPath()); - JSONObject o = new JSONObject(); - KList fm = new KList<>(); - - for(int g = 1; g < 8; g++) { - fm.add("/" + folderName + Form.repeat("/*", g) + ".json"); - } - - o.put("fileMatch", new JSONArray(fm.toArray())); - o.put("url", "./.iris/schema/" + getFolderName() + "-schema.json"); - File a = new File(getManager().getDataFolder(), ".iris/schema/" + getFolderName() + "-schema.json"); - J.attemptAsync(() -> IO.writeAll(a, new SchemaBuilder(objectClass, manager).construct().toString(4))); - - return o; - } - - public File findFile(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".json") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return j; - } - } - - File file = new File(i, name + ".json"); - - if(file.exists()) { - return file; - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - public void logLoad(File path, T t) { - loads.getAndIncrement(); - - if(loads.get() == 1) { - sec.flip(); - } - - if(sec.flip()) { - J.a(() -> { - Iris.verbose("Loaded " + C.WHITE + loads.get() + " " + resourceTypeName + (loads.get() == 1 ? "" : "s") + C.GRAY + " (" + Form.f(getLoadCache().getSize()) + " " + resourceTypeName + (loadCache.getSize() == 1 ? "" : "s") + " Loaded)"); - loads.set(0); - }); - } - - Iris.debug("Loader<" + C.GREEN + resourceTypeName + C.LIGHT_PURPLE + "> iload " + C.YELLOW + t.getLoadKey() + C.LIGHT_PURPLE + " in " + C.GRAY + t.getLoadFile().getPath() + C.LIGHT_PURPLE + " TLT: " + C.RED + Form.duration(tlt.get(), 2)); - } - - public void failLoad(File path, Throwable e) { - J.a(() -> Iris.warn("Couldn't Load " + resourceTypeName + " file: " + path.getPath() + ": " + e.getMessage())); - } - - private KList matchAllFiles(File root, Predicate f) { - KList fx = new KList<>(); - matchFiles(root, fx, f); - return fx; - } - - private void matchFiles(File at, KList files, Predicate f) { - if(at.isDirectory()) { - for(File i : at.listFiles()) { - matchFiles(i, files, f); - } - } else { - if(f.test(at)) { - files.add(at); - } - } - } - - public String[] getPossibleKeys() { - if(possibleKeys != null) { - return possibleKeys; - } - - KSet m = new KSet<>(); - KList files = getFolders(); - - if(files == null) { - possibleKeys = new String[0]; - return possibleKeys; - } - - for(File i : files) { - for(File j : matchAllFiles(i, (f) -> f.getName().endsWith(".json"))) { - m.add(i.toURI().relativize(j.toURI()).getPath().replaceAll("\\Q.json\\E", "")); - } - } - - KList v = new KList<>(m); - possibleKeys = v.toArray(new String[0]); - return possibleKeys; - } - - public long count() { - return loadCache.getSize(); - } - - protected T loadFile(File j, String name) { - try { - PrecisionStopwatch p = PrecisionStopwatch.start(); - T t = getManager().getGson() - .fromJson(preprocess(new JSONObject(IO.readAll(j))).toString(0), objectClass); - t.setLoadKey(name); - t.setLoadFile(j); - t.setLoader(manager); - getManager().preprocessObject(t); - logLoad(j, t); - tlt.addAndGet(p.getMilliseconds()); - return t; - } catch(Throwable e) { - Iris.reportError(e); - failLoad(j, e); - return null; - } - } - - protected JSONObject preprocess(JSONObject j) { - return j; - } - - public Stream streamAll(Stream s) { - return s.map(this::load); - } - - public KList loadAll(KList s) { - KList m = new KList<>(); - - for(String i : s) { - T t = load(i); - - if(t != null) { - m.add(t); - } - } - - return m; - } - - public KList loadAll(KList s, Consumer postLoad) { - KList m = new KList<>(); - - for(String i : s) { - T t = load(i); - - if(t != null) { - m.add(t); - postLoad.accept(t); - } - } - - return m; - } - - public KList loadAll(String[] s) { - KList m = new KList<>(); - - for(String i : s) { - T t = load(i); - - if(t != null) { - m.add(t); - } - } - - return m; - } - - public T load(String name) { - return load(name, true); - } - - private T loadRaw(String name) { - for(File i : getFolders(name)) { - //noinspection ConstantConditions - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".json") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return loadFile(j, name); - } - } - - File file = new File(i, name + ".json"); - - if(file.exists()) { - return loadFile(file, name); - } - } - - return null; - } - - public T load(String name, boolean warn) { - if(name == null) { - return null; - } - - if(name.trim().isEmpty()) { - return null; - } - - return loadCache.get(name); - } - - public KList getFolders() { - - - synchronized(folderCache) { - if(folderCache.get() == null) { - KList fc = new KList<>(); - - for(File i : root.listFiles()) { - if(i.isDirectory()) { - if(i.getName().equals(folderName)) { - fc.add(i); - break; - } - } - } - - folderCache.set(fc); - } - } - - return folderCache.get(); - } - - public KList getFolders(String rc) { - KList folders = getFolders().copy(); - - if(rc.contains(":")) { - for(File i : folders.copy()) { - if(!rc.startsWith(i.getName() + ":")) { - folders.remove(i); - } - } - } - - return folders; - } - - public void clearCache() { - possibleKeys = null; - loadCache.invalidate(); - folderCache.set(null); - } - - public File fileFor(T b) { - for(File i : getFolders()) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".json") && j.getName().split("\\Q.\\E")[0].equals(b.getLoadKey())) { - return j; - } - } - - File file = new File(i, b.getLoadKey() + ".json"); - - if(file.exists()) { - return file; - } - } - - return null; - } - - public boolean isLoaded(String next) { - return loadCache.contains(next); - } - - public void clearList() { - folderCache.set(null); - possibleKeys = null; - } - - public KList getPossibleKeys(String arg) { - KList f = new KList<>(); - - for(String i : getPossibleKeys()) { - if(i.equalsIgnoreCase(arg) || i.toLowerCase(Locale.ROOT).startsWith(arg.toLowerCase(Locale.ROOT)) || i.toLowerCase(Locale.ROOT).contains(arg.toLowerCase(Locale.ROOT)) || arg.toLowerCase(Locale.ROOT).contains(i.toLowerCase(Locale.ROOT))) { - f.add(i); - } - } - - return f; - } - - public boolean supportsSchemas() { - return true; - } - - public void clean() { - - } - - public long getSize() { - return loadCache.getSize(); - } - - @Override - public KCache getRawCache() { - return loadCache; - } - - @Override - public long getMaxSize() { - return loadCache.getMaxSize(); - } - - @Override - public boolean isClosed() { - return getManager().isClosed(); - } - - public long getTotalStorage() { - return getSize(); - } -} diff --git a/src/main/java/com/volmit/iris/core/loader/ScriptResourceLoader.java b/src/main/java/com/volmit/iris/core/loader/ScriptResourceLoader.java deleted file mode 100644 index b68d15162..000000000 --- a/src/main/java/com/volmit/iris/core/loader/ScriptResourceLoader.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.loader; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.engine.object.IrisScript; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.data.KCache; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; - -import java.io.File; - -public class ScriptResourceLoader extends ResourceLoader { - public ScriptResourceLoader(File root, IrisData idm, String folderName, String resourceTypeName) { - super(root, idm, folderName, resourceTypeName, IrisScript.class); - loadCache = new KCache<>(this::loadRaw, IrisSettings.get().getPerformance().getScriptLoaderCacheSize()); - } - - public boolean supportsSchemas() { - return false; - } - - public long getSize() { - return loadCache.getSize(); - } - - protected IrisScript loadFile(File j, String name) { - try { - PrecisionStopwatch p = PrecisionStopwatch.start(); - IrisScript t = new IrisScript(IO.readAll(j)); - t.setLoadKey(name); - t.setLoader(manager); - t.setLoadFile(j); - logLoad(j, t); - tlt.addAndGet(p.getMilliseconds()); - return t; - } catch(Throwable e) { - Iris.reportError(e); - Iris.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage()); - return null; - } - } - - public String[] getPossibleKeys() { - if(possibleKeys != null) { - return possibleKeys; - } - - Iris.debug("Building " + resourceTypeName + " Possibility Lists"); - KSet m = new KSet<>(); - - for(File i : getFolders()) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".js")) { - m.add(j.getName().replaceAll("\\Q.js\\E", "")); - } else if(j.isDirectory()) { - for(File k : j.listFiles()) { - if(k.isFile() && k.getName().endsWith(".js")) { - m.add(j.getName() + "/" + k.getName().replaceAll("\\Q.js\\E", "")); - } else if(k.isDirectory()) { - for(File l : k.listFiles()) { - if(l.isFile() && l.getName().endsWith(".js")) { - m.add(j.getName() + "/" + k.getName() + "/" + l.getName().replaceAll("\\Q.js\\E", "")); - } - } - } - } - } - } - } - - KList v = new KList<>(m); - possibleKeys = v.toArray(new String[0]); - return possibleKeys; - } - - public File findFile(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".js") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return j; - } - } - - File file = new File(i, name + ".js"); - - if(file.exists()) { - return file; - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - private IrisScript loadRaw(String name) { - for(File i : getFolders(name)) { - for(File j : i.listFiles()) { - if(j.isFile() && j.getName().endsWith(".js") && j.getName().split("\\Q.\\E")[0].equals(name)) { - return loadFile(j, name); - } - } - - File file = new File(i, name + ".js"); - - if(file.exists()) { - return loadFile(file, name); - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - return null; - } - - public IrisScript load(String name, boolean warn) { - return loadCache.get(name); - } -} diff --git a/src/main/java/com/volmit/iris/core/nms/BiomeBaseInjector.java b/src/main/java/com/volmit/iris/core/nms/BiomeBaseInjector.java deleted file mode 100644 index 8f7062f99..000000000 --- a/src/main/java/com/volmit/iris/core/nms/BiomeBaseInjector.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.nms; - -@FunctionalInterface -public interface BiomeBaseInjector { - default void setBiome(int x, int z, Object biomeBase) { - setBiome(x, 0, z, biomeBase); - } - - void setBiome(int x, int y, int z, Object biomeBase); -} diff --git a/src/main/java/com/volmit/iris/core/nms/INMS.java b/src/main/java/com/volmit/iris/core/nms/INMS.java deleted file mode 100644 index 89d7ab4ab..000000000 --- a/src/main/java/com/volmit/iris/core/nms/INMS.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.nms; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.nms.v19_1.NMSBinding19_1; -import com.volmit.iris.core.nms.v1X.NMSBinding1X; -import com.volmit.iris.util.collection.KMap; -import org.bukkit.Bukkit; - -public class INMS { - //@builder - private static final KMap> bindings = new KMap>() - .qput("v1_19_R1", NMSBinding19_1.class); - //@done - private static final INMSBinding binding = bind(); - - public static INMSBinding get() { - return binding; - } - - public static String getNMSTag() { - if(IrisSettings.get().getGeneral().isDisableNMS()) { - return "BUKKIT"; - } - - try { - return Bukkit.getServer().getClass().getCanonicalName().split("\\Q.\\E")[3]; - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Failed to determine server nms version!"); - e.printStackTrace(); - } - - return "BUKKIT"; - } - - private static INMSBinding bind() { - String code = getNMSTag(); - Iris.info("Locating NMS Binding for " + code); - - if(bindings.containsKey(code)) { - try { - INMSBinding b = bindings.get(code).getConstructor().newInstance(); - Iris.info("Craftbukkit " + code + " <-> " + b.getClass().getSimpleName() + " Successfully Bound"); - - return b; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - Iris.info("Craftbukkit " + code + " <-> " + NMSBinding1X.class.getSimpleName() + " Successfully Bound"); - Iris.warn("Note: Some features of Iris may not work the same since you are on an unsupported version of Minecraft."); - Iris.warn("Note: If this is a new version, expect an update soon."); - - return new NMSBinding1X(); - } -} diff --git a/src/main/java/com/volmit/iris/core/nms/INMSBinding.java b/src/main/java/com/volmit/iris/core/nms/INMSBinding.java deleted file mode 100644 index 031766349..000000000 --- a/src/main/java/com/volmit/iris/core/nms/INMSBinding.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.nms; - -import com.volmit.iris.util.nbt.mca.palette.MCABiomeContainer; -import com.volmit.iris.util.nbt.mca.palette.MCAPaletteAccess; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.WorldCreator; -import org.bukkit.block.Biome; -import org.bukkit.entity.Entity; -import org.bukkit.generator.ChunkGenerator; - -public interface INMSBinding { - boolean hasTile(Location l); - - CompoundTag serializeTile(Location location); - - void deserializeTile(CompoundTag s, Location newPosition); - - CompoundTag serializeEntity(Entity location); - - Entity deserializeEntity(CompoundTag s, Location newPosition); - - boolean supportsCustomHeight(); - - Object getBiomeBaseFromId(int id); - - int getMinHeight(World world); - - boolean supportsCustomBiomes(); - - int getTrueBiomeBaseId(Object biomeBase); - - Object getTrueBiomeBase(Location location); - - String getTrueBiomeBaseKey(Location location); - - Object getCustomBiomeBaseFor(String mckey); - Object getCustomBiomeBaseHolderFor(String mckey); - - String getKeyForBiomeBase(Object biomeBase); - - Object getBiomeBase(World world, Biome biome); - - Object getBiomeBase(Object registry, Biome biome); - - boolean isBukkit(); - - int getBiomeId(Biome biome); - - MCABiomeContainer newBiomeContainer(int min, int max, int[] data); - - MCABiomeContainer newBiomeContainer(int min, int max); - - default World createWorld(WorldCreator c) { - return c.createWorld(); - } - - int countCustomBiomes(); - - void forceBiomeInto(int x, int y, int z, Object somethingVeryDirty, ChunkGenerator.BiomeGrid chunk); - - default boolean supportsDataPacks() { - return false; - } - - MCAPaletteAccess createPalette(); -} diff --git a/src/main/java/com/volmit/iris/core/nms/NMSVersion.java b/src/main/java/com/volmit/iris/core/nms/NMSVersion.java deleted file mode 100644 index 532562b20..000000000 --- a/src/main/java/com/volmit/iris/core/nms/NMSVersion.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.nms; - -import com.volmit.iris.Iris; - -import java.util.ArrayList; -import java.util.List; - -public enum NMSVersion { - R1_19_1, - R1_18_2, - R1_18, - R1_17, - R1_16, - R1_15, - R1_14, - R1_13, - R1_13_1, - R1_12, - R1_11, - R1_10, - R1_9_4, - R1_9_2, - R1_8; - - public static NMSVersion getMinimum() { - return values()[values().length - 1]; - } - - public static NMSVersion getMaximum() { - return values()[0]; - } - - public static NMSVersion current() { - if(tryVersion("1_8_R3")) { - return R1_8; - } - - if(tryVersion("1_9_R1")) { - return R1_9_2; - } - - if(tryVersion("1_9_R2")) { - return R1_9_4; - } - - if(tryVersion("1_10_R1")) { - return R1_10; - } - - if(tryVersion("1_11_R1")) { - return R1_11; - } - - if(tryVersion("1_12_R1")) { - return R1_12; - } - - if(tryVersion("1_13_R1")) { - return R1_13; - } - - if(tryVersion("1_13_R2")) { - return R1_13_1; - } - - if(tryVersion("1_14_R1")) { - return R1_14; - } - - if(tryVersion("1_15_R1")) { - return R1_15; - } - - if(tryVersion("1_16_R1")) { - return R1_16; - } - - if(tryVersion("1_17_R1")) { - return R1_17; - } - - if(tryVersion("1_18_R1")) { - return R1_18; - } - if(tryVersion("1_18_R2")) { - return R1_18_2; - } - if(tryVersion("1_19_R1")) { - return R1_19_1; - } - return null; - } - - private static boolean tryVersion(String v) { - try { - Class.forName("org.bukkit.craftbukkit.v" + v + ".CraftWorld"); - return true; - } catch(Throwable e) { - Iris.reportError(e); - - } - - return false; - } - - public List getAboveInclusive() { - List n = new ArrayList<>(); - - for(NMSVersion i : values()) { - if(i.ordinal() >= ordinal()) { - n.add(i); - } - } - - return n; - } - - public List betweenInclusive(NMSVersion other) { - List n = new ArrayList<>(); - - for(NMSVersion i : values()) { - if(i.ordinal() <= Math.max(other.ordinal(), ordinal()) && i.ordinal() >= Math.min(ordinal(), other.ordinal())) { - n.add(i); - } - } - - return n; - } - - public List getBelowInclusive() { - List n = new ArrayList<>(); - - for(NMSVersion i : values()) { - if(i.ordinal() <= ordinal()) { - n.add(i); - } - } - - return n; - } -} diff --git a/src/main/java/com/volmit/iris/core/nms/v19_1/NMSBinding19_1.java b/src/main/java/com/volmit/iris/core/nms/v19_1/NMSBinding19_1.java deleted file mode 100644 index 2e2713488..000000000 --- a/src/main/java/com/volmit/iris/core/nms/v19_1/NMSBinding19_1.java +++ /dev/null @@ -1,480 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.nms.v19_1; - - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.INMSBinding; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.nbt.io.NBTUtil; -import com.volmit.iris.util.nbt.mca.NBTWorld; -import com.volmit.iris.util.nbt.mca.palette.MCABiomeContainer; -import com.volmit.iris.util.nbt.mca.palette.MCAChunkBiomeContainer; -import com.volmit.iris.util.nbt.mca.palette.MCAGlobalPalette; -import com.volmit.iris.util.nbt.mca.palette.MCAIdMap; -import com.volmit.iris.util.nbt.mca.palette.MCAIdMapper; -import com.volmit.iris.util.nbt.mca.palette.MCAPalette; -import com.volmit.iris.util.nbt.mca.palette.MCAPaletteAccess; -import com.volmit.iris.util.nbt.mca.palette.MCAPalettedContainer; -import com.volmit.iris.util.nbt.mca.palette.MCAWrappedPalettedContainer; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import net.minecraft.core.*; -import net.minecraft.nbt.NbtIo; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.BitStorage; -import net.minecraft.util.Mth; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.LevelChunkSection; -import net.minecraft.world.level.chunk.Palette; -import net.minecraft.world.level.chunk.PalettedContainer; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - - -import org.bukkit.craftbukkit.v1_19_R1.CraftServer; -import org.bukkit.craftbukkit.v1_19_R1.CraftWorld; -import org.bukkit.craftbukkit.v1_19_R1.block.data.CraftBlockData; -import org.bukkit.entity.Entity; -import org.bukkit.generator.ChunkGenerator; -import org.jetbrains.annotations.NotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -public class NMSBinding19_1 implements INMSBinding { - - private final KMap baseBiomeCache = new KMap<>(); - private final BlockData AIR = Material.AIR.createBlockData(); - private final AtomicCache> biomeMapCache = new AtomicCache<>(); - private final AtomicCache> registryCache = new AtomicCache<>(); - private final AtomicCache> globalCache = new AtomicCache<>(); - private final AtomicCache registryAccess = new AtomicCache<>(); - private final AtomicCache byIdRef = new AtomicCache<>(); - private Field biomeStorageCache = null; - - @Override - public boolean hasTile(Location l) { - return ((CraftWorld) l.getWorld()).getHandle().getBlockEntity(new BlockPos(l.getBlockX(), l.getBlockY(), l.getBlockZ()), false) != null; - } - - @Override - public CompoundTag serializeTile(Location location) { - BlockEntity e = ((CraftWorld) location.getWorld()).getHandle().getBlockEntity(new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()), true); - - if(e == null) { - return null; - } - - net.minecraft.nbt.CompoundTag tag = e.saveWithFullMetadata(); - return convert(tag); - } - - private CompoundTag convert(net.minecraft.nbt.CompoundTag tag) { - try { - ByteArrayOutputStream boas = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(boas); - tag.write(dos); - dos.close(); - return (CompoundTag) NBTUtil.read(new ByteArrayInputStream(boas.toByteArray()), false).getTag(); - } catch(Throwable ex) { - ex.printStackTrace(); - } - - return null; - } - - private net.minecraft.nbt.CompoundTag convert(CompoundTag tag) { - try { - ByteArrayOutputStream boas = new ByteArrayOutputStream(); - NBTUtil.write(tag, boas, false); - DataInputStream din = new DataInputStream(new ByteArrayInputStream(boas.toByteArray())); - net.minecraft.nbt.CompoundTag c = NbtIo.read(din); - din.close(); - return c; - } catch(Throwable e) { - e.printStackTrace(); - } - - return null; - } - - @Override - public void deserializeTile(CompoundTag c, Location pos) { - ((CraftWorld) pos.getWorld()).getHandle().getChunkAt(new BlockPos(pos.getBlockX(), 0, pos.getBlockZ())).setBlockEntityNbt(convert(c)); - } - - @Override - public CompoundTag serializeEntity(Entity location) { - return null;// TODO: - } - - @Override - public Entity deserializeEntity(CompoundTag s, Location newPosition) { - return null;// TODO: - } - - @Override - public boolean supportsCustomHeight() { - return true; - } - - private RegistryAccess registry() { - return registryAccess.aquire(() -> (RegistryAccess) getFor(RegistryAccess.Frozen.class, ((CraftServer) Bukkit.getServer()).getHandle().getServer())); - } - - private Registry getCustomBiomeRegistry() { - - return registry().registry(Registry.BIOME_REGISTRY).orElse(null); - } - - private Registry getBlockRegistry() { - return registry().registry(Registry.BLOCK_REGISTRY).orElse(null); - } - - @Override - public Object getBiomeBaseFromId(int id) { - try { - return byIdRef.aquire(() -> { - for(Method i : IdMap.class.getDeclaredMethods()) { - if(i.getParameterCount() == 1 && i.getParameterTypes()[0].equals(int.class)) { - Iris.info("[NMS] Found byId method in " + IdMap.class.getSimpleName() + "." + i.getName() + "(int) => " + Biome.class.getSimpleName()); - return i; - } - } - - Iris.error("Cannot find byId method!"); - return null; - }).invoke(getCustomBiomeRegistry(), id); - } catch(IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - - return null; - } - - @Override - public int getMinHeight(World world) { - return world.getMinHeight(); - } - - @Override - public boolean supportsCustomBiomes() { - return true; - } - - @Override - public int getTrueBiomeBaseId(Object biomeBase) { - return getCustomBiomeRegistry().getId((net.minecraft.world.level.biome.Biome) biomeBase); - } - - @Override - public Object getTrueBiomeBase(Location location) { - return ((CraftWorld) location.getWorld()).getHandle().getBiome(new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ())); - } - - @Override - public String getTrueBiomeBaseKey(Location location) { - return getKeyForBiomeBase(getTrueBiomeBase(location)); - } - - @Override - public Object getCustomBiomeBaseFor(String mckey) { - return getCustomBiomeRegistry().get(new ResourceLocation(mckey)); - } - @Override - public Object getCustomBiomeBaseHolderFor(String mckey) { - return getCustomBiomeRegistry().getHolder(getTrueBiomeBaseId(getCustomBiomeRegistry().get(new ResourceLocation(mckey)))).get(); - } - - @Override - public String getKeyForBiomeBase(Object biomeBase) { - return getCustomBiomeRegistry().getKey((net.minecraft.world.level.biome.Biome) biomeBase).getPath(); // something, not something:something - } - - @Override - public Object getBiomeBase(World world, Biome biome) { - return getBiomeBase(((CraftWorld) world).getHandle().registryAccess().registry(Registry.BIOME_REGISTRY).orElse(null), biome); - } - - @Override - public Object getBiomeBase(Object registry, Biome biome) { - Object v = baseBiomeCache.get(biome); - - if(v != null) { - return v; - } - //noinspection unchecked - v = org.bukkit.craftbukkit.v1_19_R1.block.CraftBlock.biomeToBiomeBase((Registry) registry, biome); - if(v == null) { - // Ok so there is this new biome name called "CUSTOM" in Paper's new releases. - // But, this does NOT exist within CraftBukkit which makes it return an error. - // So, we will just return the ID that the plains biome returns instead. - //noinspection unchecked - return org.bukkit.craftbukkit.v1_19_R1.block.CraftBlock.biomeToBiomeBase((Registry) registry, Biome.PLAINS); - } - baseBiomeCache.put(biome, v); - return v; - } - - @Override - public boolean isBukkit() { - return true; - } - - @Override - public int getBiomeId(Biome biome) { - for(World i : Bukkit.getWorlds()) { - if(i.getEnvironment().equals(World.Environment.NORMAL)) { - Registry registry = ((CraftWorld) i).getHandle().registryAccess().registry(Registry.BIOME_REGISTRY).orElse(null); - return registry.getId((net.minecraft.world.level.biome.Biome) getBiomeBase(registry, biome)); - } - } - - return biome.ordinal(); - } - - private MCAIdMap getBiomeMapping() { - return biomeMapCache.aquire(() -> new MCAIdMap<>() { - @NotNull - @Override - public Iterator iterator() { - return getCustomBiomeRegistry().iterator(); - } - - @Override - public int getId(net.minecraft.world.level.biome.Biome paramT) { - return getCustomBiomeRegistry().getId(paramT); - } - - @Override - public net.minecraft.world.level.biome.Biome byId(int paramInt) { - return (net.minecraft.world.level.biome.Biome) getBiomeBaseFromId(paramInt); - } - }); - } - - @NotNull - private MCABiomeContainer getBiomeContainerInterface(MCAIdMap biomeMapping, MCAChunkBiomeContainer base) { - return new MCABiomeContainer() { - @Override - public int[] getData() { - return base.writeBiomes(); - } - - @Override - public void setBiome(int x, int y, int z, int id) { - base.setBiome(x, y, z, biomeMapping.byId(id)); - } - - @Override - public int getBiome(int x, int y, int z) { - return biomeMapping.getId(base.getBiome(x, y, z)); - } - }; - } - - @Override - public MCABiomeContainer newBiomeContainer(int min, int max) { - MCAChunkBiomeContainer base = new MCAChunkBiomeContainer<>(getBiomeMapping(), min, max); - return getBiomeContainerInterface(getBiomeMapping(), base); - } - - @Override - public MCABiomeContainer newBiomeContainer(int min, int max, int[] data) { - MCAChunkBiomeContainer base = new MCAChunkBiomeContainer<>(getBiomeMapping(), min, max, data); - return getBiomeContainerInterface(getBiomeMapping(), base); - } - - @Override - public int countCustomBiomes() { - AtomicInteger a = new AtomicInteger(0); - - getCustomBiomeRegistry().keySet().forEach((i) -> { - if(i.getNamespace().equals("minecraft")) { - return; - } - - a.incrementAndGet(); - Iris.debug("Custom Biome: " + i); - }); - - return a.get(); - } - - public boolean supportsDataPacks() { - return true; - } - - @Override - public void forceBiomeInto(int x, int y, int z, Object somethingVeryDirty, ChunkGenerator.BiomeGrid chunk) { - try { - ChunkAccess s = (ChunkAccess) getFieldForBiomeStorage(chunk).get(chunk); - Holder biome = (Holder) somethingVeryDirty; - s.setBiome(x, y, z, biome); - /*int l = QuartPos.fromBlock(s.getMinBuildHeight()); - int i1 = l + QuartPos.fromBlock(s.getHeight()) - 1; - PalettedContainer> palette = getPalette(s, s.getSectionIndex(QuartPos.toBlock(Mth.clamp(y, l, i1)))); - int index = getPaletteIndex(x, y, z, s, palette); - int data = getPaletteDataId(palette, biome); - setPaletteData(palette, index, data);*/ - } catch(IllegalAccessException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - private PalettedContainer> getPalette(ChunkAccess ca, int index) { - LevelChunkSection[] sections = fieldForClass(LevelChunkSection[].class, ChunkAccess.class, ca); - return fieldForClass(PalettedContainer.class, LevelChunkSection.class, sections[index]); - } - - private int getPaletteIndex(int x, int y, int z, ChunkAccess s, PalettedContainer palette) { - int l = QuartPos.fromBlock(s.getMinBuildHeight()); - int i1 = l + QuartPos.fromBlock(s.getHeight()) - 1; - int j1 = Mth.clamp(y, l, i1); - return fieldForClass(PalettedContainer.Strategy.class, PalettedContainer.class, palette).getIndex(x & 3, j1 & 3, z & 3); - } - - private > int getPaletteDataId(PalettedContainer palette, T data) throws ClassNotFoundException { - Class dataType = getClassType(PalettedContainer.class, 1); - Object paletteData = fieldFor(dataType, palette); - Palette fuckinFinally = fieldForClass(Palette.class,dataType, paletteData); - return fuckinFinally.idFor(data); - } - - private void setPaletteData(PalettedContainer palette, int index, int data) throws ClassNotFoundException { - Class dataType = getClassType(PalettedContainer.class, 1); - Object paletteData = fieldFor(dataType, palette); - BitStorage storage = fieldForClass(BitStorage.class, dataType, paletteData); - storage.set(index, data); - } - - private Field getFieldForBiomeStorage(Object storage) { - Field f = biomeStorageCache; - - if(f != null) { - return f; - } - try { - - f = storage.getClass().getDeclaredField("biome"); - f.setAccessible(true); - return f; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - Iris.error(storage.getClass().getCanonicalName()); - } - - biomeStorageCache = f; - return null; - } - - @Override - public MCAPaletteAccess createPalette() { - MCAIdMapper registry = registryCache.aquireNasty(() -> { - Field cf = net.minecraft.core.IdMapper.class.getDeclaredField("tToId"); - Field df = net.minecraft.core.IdMapper.class.getDeclaredField("idToT"); - Field bf = net.minecraft.core.IdMapper.class.getDeclaredField("nextId"); - cf.setAccessible(true); - df.setAccessible(true); - bf.setAccessible(true); - net.minecraft.core.IdMapper blockData = Block.BLOCK_STATE_REGISTRY; - int b = bf.getInt(blockData); - Object2IntMap c = (Object2IntMap) cf.get(blockData); - List d = (List) df.get(blockData); - return new MCAIdMapper(c, d, b); - }); - MCAPalette global = globalCache.aquireNasty(() -> new MCAGlobalPalette<>(registry, ((CraftBlockData) AIR).getState())); - MCAPalettedContainer container = new MCAPalettedContainer<>(global, registry, - i -> ((CraftBlockData) NBTWorld.getBlockData(i)).getState(), - i -> NBTWorld.getCompound(CraftBlockData.fromData(i)), - ((CraftBlockData) AIR).getState()); - return new MCAWrappedPalettedContainer<>(container, - i -> NBTWorld.getCompound(CraftBlockData.fromData(i)), - i -> ((CraftBlockData) NBTWorld.getBlockData(i)).getState()); - } - - private static Object getFor(Class type, Object source) { - Object o = fieldFor(type, source); - - if(o != null) { - return o; - } - - return invokeFor(type, source); - } - - private static Object invokeFor(Class returns, Object in) { - for(Method i : in.getClass().getMethods()) { - if(i.getReturnType().equals(returns)) { - i.setAccessible(true); - try { - Iris.debug("[NMS] Found " + returns.getSimpleName() + " in " + in.getClass().getSimpleName() + "." + i.getName() + "()"); - return i.invoke(in); - } catch(Throwable e) { - e.printStackTrace(); - } - } - } - - return null; - } - - private static Object fieldFor(Class returns, Object in) { - return fieldForClass(returns, in.getClass(), in); - } - - @SuppressWarnings("unchecked") - private static T fieldForClass(Class returnType, Class sourceType, Object in) { - for(Field i : sourceType.getDeclaredFields()) { - if(i.getType().equals(returnType)) { - i.setAccessible(true); - try { - Iris.debug("[NMS] Found " + returnType.getSimpleName() + " in " + sourceType.getSimpleName() + "." + i.getName()); - return (T) i.get(in); - } catch(IllegalAccessException e) { - e.printStackTrace(); - } - } - } - return null; - } - - private static Class getClassType(Class type, int ordinal) { - return type.getDeclaredClasses()[ordinal]; - } -} diff --git a/src/main/java/com/volmit/iris/core/nms/v1X/NMSBinding1X.java b/src/main/java/com/volmit/iris/core/nms/v1X/NMSBinding1X.java deleted file mode 100644 index 6db7933ca..000000000 --- a/src/main/java/com/volmit/iris/core/nms/v1X/NMSBinding1X.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.nms.v1X; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.INMSBinding; -import com.volmit.iris.util.nbt.mca.palette.MCABiomeContainer; -import com.volmit.iris.util.nbt.mca.palette.MCAPaletteAccess; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.entity.Entity; -import org.bukkit.generator.ChunkGenerator; - -public class NMSBinding1X implements INMSBinding { - private static final boolean supportsCustomHeight = testCustomHeight(); - - @SuppressWarnings("ConstantConditions") - private static boolean testCustomHeight() { - try { - if(World.class.getDeclaredMethod("getMaxHeight") != null && World.class.getDeclaredMethod("getMinHeight") != null) - ; - { - return true; - } - } catch(Throwable ignored) { - - } - - return false; - } - - @Override - public boolean hasTile(Location l) { - return false; - } - - @Override - public CompoundTag serializeTile(Location location) { - return null; - } - - @Override - public void deserializeTile(CompoundTag s, Location newPosition) { - - } - - @Override - public CompoundTag serializeEntity(Entity location) { - return null; - } - - @Override - public Entity deserializeEntity(CompoundTag s, Location newPosition) { - return null; - } - - @Override - public boolean supportsCustomHeight() { - return supportsCustomHeight; - } - - @Override - public Object getBiomeBaseFromId(int id) { - return null; - } - - @Override - public int getMinHeight(World world) { - return supportsCustomHeight ? world.getMinHeight() : 0; - } - - @Override - public boolean supportsCustomBiomes() { - return false; - } - - @Override - public int getTrueBiomeBaseId(Object biomeBase) { - return 0; - } - - @Override - public Object getTrueBiomeBase(Location location) { - return null; - } - - @Override - public String getTrueBiomeBaseKey(Location location) { - return null; - } - - @Override - public Object getCustomBiomeBaseFor(String mckey) { - return null; - } - - @Override - public Object getCustomBiomeBaseHolderFor(String mckey) { - return null; - } - - @Override - public String getKeyForBiomeBase(Object biomeBase) { - return null; - } - - public Object getBiomeBase(World world, Biome biome) { - return null; - } - - @Override - public Object getBiomeBase(Object registry, Biome biome) { - return null; - } - - @Override - public boolean isBukkit() { - return true; - } - - @Override - public int getBiomeId(Biome biome) { - return biome.ordinal(); - } - - @Override - public MCABiomeContainer newBiomeContainer(int min, int max) { - Iris.error("Cannot use the custom biome data! Iris is incapable of using MCA generation on this version of minecraft!"); - - return null; - } - - @Override - public MCABiomeContainer newBiomeContainer(int min, int max, int[] v) { - Iris.error("Cannot use the custom biome data! Iris is incapable of using MCA generation on this version of minecraft!"); - - return null; - } - - @Override - public int countCustomBiomes() { - return 0; - } - - @Override - public void forceBiomeInto(int x, int y, int z, Object somethingVeryDirty, ChunkGenerator.BiomeGrid chunk) { - - } - - @Override - public MCAPaletteAccess createPalette() { - Iris.error("Cannot use the global data palette! Iris is incapable of using MCA generation on this version of minecraft!"); - return null; - } -} diff --git a/src/main/java/com/volmit/iris/core/pack/IrisPack.java b/src/main/java/com/volmit/iris/core/pack/IrisPack.java deleted file mode 100644 index 83f2193be..000000000 --- a/src/main/java/com/volmit/iris/core/pack/IrisPack.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pack; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.ResourceLoader; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisWorld; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.exceptions.IrisException; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONArray; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.Data; -import org.bukkit.World; -import org.zeroturnaround.zip.commons.FileUtils; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Future; - -/** - * Represents an Iris pack that exists - */ -@Data -public class IrisPack { - private final File folder; - private final IrisData data; - - /** - * Create an iris pack backed by a data folder - * the data folder is assumed to be in the Iris/packs/NAME folder - * - * @param name - * the name - */ - public IrisPack(String name) { - this(packsPack(name)); - } - - /** - * Create an iris pack backed by a data folder - * - * @param folder - * the folder of the pack. Must be a directory - */ - public IrisPack(File folder) { - this.folder = folder; - - if(!folder.exists()) { - throw new RuntimeException("Cannot open Pack " + folder.getPath() + " (directory doesnt exist)"); - } - - if(!folder.isDirectory()) { - throw new RuntimeException("Cannot open Pack " + folder.getPath() + " (not a directory)"); - } - - this.data = IrisData.get(folder); - } - - /** - * Create a new pack from the input url - * - * @param sender - * the sender - * @param url - * the url, or name, or really anything see IrisPackRepository.from(String) - * @return the iris pack - * @throws IrisException - * fails - */ - public static Future from(VolmitSender sender, String url) throws IrisException { - IrisPackRepository repo = IrisPackRepository.from(url); - if(repo == null) { - throw new IrisException("Null Repo"); - } - - try { - return from(sender, repo); - } catch(MalformedURLException e) { - throw new IrisException("Malformed URL " + e.getMessage()); - } - } - - /** - * Create a pack from a repo - * - * @param sender - * the sender - * @param repo - * the repo - * @return the pack - * @throws MalformedURLException - * shit happens - */ - public static Future from(VolmitSender sender, IrisPackRepository repo) throws MalformedURLException { - CompletableFuture pack = new CompletableFuture<>(); - repo.install(sender, () -> { - pack.complete(new IrisPack(repo.getRepo())); - }); - return pack; - } - - /** - * Create a blank pack with a given name - * - * @param name - * the name of the pack - * @return the pack - * @throws IrisException - * if the pack already exists or another error - */ - public static IrisPack blank(String name) throws IrisException { - File f = packsPack(name); - - if(f.exists()) { - throw new IrisException("Already exists"); - } - - File fd = new File(f, "dimensions/" + name + ".json"); - fd.getParentFile().mkdirs(); - try { - IO.writeAll(fd, "{\n" + - " \"name\": \"" + Form.capitalize(name) + "\",\n" + - " \"version\": 1\n" + - "}\n"); - } catch(IOException e) { - throw new IrisException(e.getMessage(), e); - } - - IrisPack pack = new IrisPack(f); - pack.updateWorkspace(); - return pack; - } - - /** - * Get a packs pack folder for a name. Such that overworld would resolve as Iris/packs/overworld - * - * @param name - * the name - * @return the file path - */ - public static File packsPack(String name) { - return Iris.instance.getDataFolderNoCreate(StudioSVC.WORKSPACE_NAME, name); - } - - private static KList collectFiles(File f, String fileExtension) { - KList l = new KList<>(); - - if(f.isDirectory()) { - for(File i : f.listFiles()) { - l.addAll(collectFiles(i, fileExtension)); - } - } else if(f.getName().endsWith("." + fileExtension)) { - l.add(f); - } - - return l; - } - - /** - * Delete this pack. This invalidates this pack and you should - * probably no longer use this instance after deleting this pack - */ - public void delete() { - IO.delete(folder); - folder.delete(); - } - - /** - * Get the name of this pack - * - * @return the pack name - */ - public String getName() { - return folder.getName(); - } - - /** - * Get the file path of the workspace file - * - * @return the workspace file path - */ - public File getWorkspaceFile() { - return new File(getFolder(), getName() + ".code-workspace"); - } - - /** - * Update the workspace file - * - * @return true if it was updated - */ - public boolean updateWorkspace() { - getFolder().mkdirs(); - File ws = getWorkspaceFile(); - - try { - PrecisionStopwatch p = PrecisionStopwatch.start(); - Iris.debug("Building Workspace: " + ws.getPath()); - JSONObject j = generateWorkspaceConfig(); - IO.writeAll(ws, j.toString(4)); - p.end(); - Iris.debug("Building Workspace: " + ws.getPath() + " took " + Form.duration(p.getMilliseconds(), 2)); - return true; - } catch(Throwable e) { - Iris.reportError(e); - Iris.warn("Pack invalid: " + ws.getAbsolutePath() + " Re-creating. You may loose some vs-code workspace settings! But not your actual project!"); - ws.delete(); - try { - IO.writeAll(ws, generateWorkspaceConfig()); - } catch(IOException e1) { - Iris.reportError(e1); - e1.printStackTrace(); - } - } - - return false; - } - - /** - * Install this pack into a world - * - * @param world - * the world to install into (world/iris/pack) - * @return the installed pack - */ - public IrisPack install(World world) throws IrisException { - return install(new File(world.getWorldFolder(), "iris/pack")); - } - - /** - * Install this pack into a world - * - * @param world - * the world to install into (world/iris/pack) - * @return the installed pack - */ - public IrisPack install(IrisWorld world) throws IrisException { - return install(new File(world.worldFolder(), "iris/pack")); - } - - /** - * Install this pack into a world - * - * @param folder - * the folder to install this pack into - * @return the installed pack - */ - public IrisPack install(File folder) throws IrisException { - if(folder.exists()) { - throw new IrisException("Cannot install new pack because the folder " + folder.getName() + " already exists!"); - } - - folder.mkdirs(); - - try { - FileUtils.copyDirectory(getFolder(), folder); - } catch(IOException e) { - Iris.reportError(e); - } - - return new IrisPack(folder); - } - - /** - * Create a new pack using this pack as a template. The new pack will be renamed & have a renamed dimension - * to match it. - * - * @param newName - * the new pack name - * @return the new IrisPack - */ - public IrisPack install(String newName) throws IrisException { - File newPack = packsPack(newName); - - if(newPack.exists()) { - throw new IrisException("Cannot install new pack because the folder " + newName + " already exists!"); - } - - try { - FileUtils.copyDirectory(getFolder(), newPack); - } catch(IOException e) { - Iris.reportError(e); - } - - IrisData data = IrisData.get(newPack); - IrisDimension dim = data.getDimensionLoader().load(getDimensionKey()); - data.dump(); - File from = dim.getLoadFile(); - File to = new File(from.getParentFile(), newName + ".json"); - try { - FileUtils.moveFile(from, to); - new File(newPack, getWorkspaceFile().getName()).delete(); - } catch(Throwable e) { - throw new IrisException(e); - } - - IrisPack pack = new IrisPack(newPack); - pack.updateWorkspace(); - - return pack; - } - - /** - * The dimension's assumed loadkey - * - * @return getName() - */ - public String getDimensionKey() { - return getName(); - } - - /** - * Get the main dimension object - * - * @return the dimension (folder name as dim key) - */ - public IrisDimension getDimension() { - return getData().getDimensionLoader().load(getDimensionKey()); - } - - /** - * Find all files in this pack with the given extension - * - * @param fileExtension - * the extension - * @return the list of files - */ - public KList collectFiles(String fileExtension) { - return collectFiles(getFolder(), fileExtension); - } - - private JSONObject generateWorkspaceConfig() { - JSONObject ws = new JSONObject(); - JSONArray folders = new JSONArray(); - JSONObject folder = new JSONObject(); - folder.put("path", "."); - folders.put(folder); - ws.put("folders", folders); - JSONObject settings = new JSONObject(); - settings.put("workbench.colorTheme", "Monokai"); - settings.put("workbench.preferredDarkColorTheme", "Solarized Dark"); - settings.put("workbench.tips.enabled", false); - settings.put("workbench.tree.indent", 24); - settings.put("files.autoSave", "onFocusChange"); - JSONObject jc = new JSONObject(); - jc.put("editor.autoIndent", "brackets"); - jc.put("editor.acceptSuggestionOnEnter", "smart"); - jc.put("editor.cursorSmoothCaretAnimation", true); - jc.put("editor.dragAndDrop", false); - jc.put("files.trimTrailingWhitespace", true); - jc.put("diffEditor.ignoreTrimWhitespace", true); - jc.put("files.trimFinalNewlines", true); - jc.put("editor.suggest.showKeywords", false); - jc.put("editor.suggest.showSnippets", false); - jc.put("editor.suggest.showWords", false); - JSONObject st = new JSONObject(); - st.put("strings", true); - jc.put("editor.quickSuggestions", st); - jc.put("editor.suggest.insertMode", "replace"); - settings.put("[json]", jc); - settings.put("json.maxItemsComputed", 30000); - JSONArray schemas = new JSONArray(); - IrisData dm = IrisData.get(getFolder()); - - for(ResourceLoader r : dm.getLoaders().v()) { - if(r.supportsSchemas()) { - schemas.put(r.buildSchema()); - } - } - - settings.put("json.schemas", schemas); - ws.put("settings", settings); - - return ws; - } -} diff --git a/src/main/java/com/volmit/iris/core/pack/IrisPackRepository.java b/src/main/java/com/volmit/iris/core/pack/IrisPackRepository.java deleted file mode 100644 index fcf25d458..000000000 --- a/src/main/java/com/volmit/iris/core/pack/IrisPackRepository.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pack; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.jobs.DownloadJob; -import com.volmit.iris.util.scheduling.jobs.JobCollection; -import com.volmit.iris.util.scheduling.jobs.SingleJob; -import lombok.Builder; -import lombok.Data; -import org.zeroturnaround.zip.ZipUtil; -import org.zeroturnaround.zip.commons.FileUtils; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.UUID; - -@Data -@Builder -public class IrisPackRepository { - @Builder.Default - private String user = "IrisDimensions"; - - @Builder.Default - private String repo = "overworld"; - - @Builder.Default - private String branch = "master"; - - @Builder.Default - private String tag = ""; - - /** - * - */ - public static IrisPackRepository from(String g) { - // https://github.com/IrisDimensions/overworld - if(g.startsWith("https://github.com/")) { - String sub = g.split("\\Qgithub.com/\\E")[1]; - IrisPackRepository r = IrisPackRepository.builder() - .user(sub.split("\\Q/\\E")[0]) - .repo(sub.split("\\Q/\\E")[1]).build(); - - if(g.contains("/tree/")) { - r.setBranch(g.split("/tree/")[1]); - } - - return r; - } else if(g.contains("/")) { - String[] f = g.split("\\Q/\\E"); - - if(f.length == 1) { - return from(g); - } else if(f.length == 2) { - return IrisPackRepository.builder() - .user(f[0]) - .repo(f[1]) - .build(); - } else if(f.length >= 3) { - IrisPackRepository r = IrisPackRepository.builder() - .user(f[0]) - .repo(f[1]) - .build(); - - if(f[2].startsWith("#")) { - r.setTag(f[2].substring(1)); - } else { - r.setBranch(f[2]); - } - - return r; - } - } else { - return IrisPackRepository.builder() - .user("IrisDimensions") - .repo(g) - .branch(g.equals("overworld") ? "stable" : "master") - .build(); - } - - return null; - } - - public String toURL() { - if(!tag.trim().isEmpty()) { - return "https://codeload.github.com/" + user + "/" + repo + "/zip/refs/tags/" + tag; - } - - return "https://codeload.github.com/" + user + "/" + repo + "/zip/refs/heads/" + branch; - } - - public void install(VolmitSender sender, Runnable whenComplete) throws MalformedURLException { - File pack = Iris.instance.getDataFolderNoCreate(StudioSVC.WORKSPACE_NAME, getRepo()); - - if(!pack.exists()) { - File dl = new File(Iris.getTemp(), "dltk-" + UUID.randomUUID() + ".zip"); - File work = new File(Iris.getTemp(), "extk-" + UUID.randomUUID()); - new JobCollection(Form.capitalize(getRepo()), - new DownloadJob(toURL(), pack), - new SingleJob("Extracting", () -> ZipUtil.unpack(dl, work)), - new SingleJob("Installing", () -> { - try { - FileUtils.copyDirectory(work.listFiles()[0], pack); - } catch(IOException e) { - e.printStackTrace(); - } - })).execute(sender, whenComplete); - } else { - sender.sendMessage("Pack already exists!"); - } - } -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/IrisPregenerator.java b/src/main/java/com/volmit/iris/core/pregenerator/IrisPregenerator.java deleted file mode 100644 index a28628b46..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/IrisPregenerator.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.math.RollingSequence; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.Looper; - -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - -public class IrisPregenerator { - private final PregenTask task; - private final PregeneratorMethod generator; - private final PregenListener listener; - private final Looper ticker; - private final AtomicBoolean paused; - private final AtomicBoolean shutdown; - private final RollingSequence chunksPerSecond; - private final RollingSequence chunksPerMinute; - private final RollingSequence regionsPerMinute; - private final AtomicInteger generated; - private final AtomicInteger generatedLast; - private final AtomicInteger generatedLastMinute; - private final AtomicInteger totalChunks; - private final AtomicLong startTime; - private final ChronoLatch minuteLatch; - private final AtomicReference currentGeneratorMethod; - private final KSet generatedRegions; - private final KSet retry; - private final KSet net; - private final ChronoLatch cl; - - public IrisPregenerator(PregenTask task, PregeneratorMethod generator, PregenListener listener) { - this.listener = listenify(listener); - cl = new ChronoLatch(5000); - generatedRegions = new KSet<>(); - this.shutdown = new AtomicBoolean(false); - this.paused = new AtomicBoolean(false); - this.task = task; - this.generator = generator; - retry = new KSet<>(); - net = new KSet<>(); - currentGeneratorMethod = new AtomicReference<>("Void"); - minuteLatch = new ChronoLatch(60000, false); - chunksPerSecond = new RollingSequence(10); - chunksPerMinute = new RollingSequence(10); - regionsPerMinute = new RollingSequence(10); - generated = new AtomicInteger(0); - generatedLast = new AtomicInteger(0); - generatedLastMinute = new AtomicInteger(0); - totalChunks = new AtomicInteger(0); - task.iterateRegions((_a, _b) -> totalChunks.addAndGet(1024)); - startTime = new AtomicLong(M.ms()); - ticker = new Looper() { - @Override - protected long loop() { - long eta = computeETA(); - int secondGenerated = generated.get() - generatedLast.get(); - generatedLast.set(generated.get()); - chunksPerSecond.put(secondGenerated); - - if(minuteLatch.flip()) { - int minuteGenerated = generated.get() - generatedLastMinute.get(); - generatedLastMinute.set(generated.get()); - chunksPerMinute.put(minuteGenerated); - regionsPerMinute.put((double) minuteGenerated / 1024D); - } - - listener.onTick(chunksPerSecond.getAverage(), chunksPerMinute.getAverage(), - regionsPerMinute.getAverage(), - (double) generated.get() / (double) totalChunks.get(), - generated.get(), totalChunks.get(), - totalChunks.get() - generated.get(), - eta, M.ms() - startTime.get(), currentGeneratorMethod.get()); - - if(cl.flip()) { - Iris.info("Pregen: " + Form.f(generated.get()) + " of " + Form.f(totalChunks.get()) + " (" + Form.pc((double) generated.get() / (double) totalChunks.get(), 0) + ") " + Form.f((int) chunksPerSecond.getAverage()) + "/s ETA: " + Form.duration((double) eta, 2)); - } - - return 1000; - } - }; - } - - private long computeETA() { - return (long) ((totalChunks.get() - generated.get()) * - ((double) (M.ms() - startTime.get()) / (double) generated.get())); - } - - public void close() { - shutdown.set(true); - } - - public void start() { - init(); - ticker.start(); - checkRegions(); - task.iterateRegions((x, z) -> visitRegion(x, z, true)); - task.iterateRegions((x, z) -> visitRegion(x, z, false)); - shutdown(); - } - - private void checkRegions() { - task.iterateRegions(this::checkRegion); - } - - private void init() { - generator.init(); - generator.save(); - } - - private void shutdown() { - listener.onSaving(); - generator.close(); - ticker.interrupt(); - listener.onClose(); - } - - private void visitRegion(int x, int z, boolean regions) { - while(paused.get() && !shutdown.get()) { - J.sleep(50); - } - - if(shutdown.get()) { - listener.onRegionSkipped(x, z); - return; - } - - Position2 pos = new Position2(x, z); - - if(generatedRegions.contains(pos)) { - return; - } - - currentGeneratorMethod.set(generator.getMethod(x, z)); - boolean hit = false; - if(generator.supportsRegions(x, z, listener) && regions) { - hit = true; - listener.onRegionGenerating(x, z); - generator.generateRegion(x, z, listener); - } else if(!regions) { - hit = true; - listener.onRegionGenerating(x, z); - PregenTask.iterateRegion(x, z, (xx, zz) -> generator.generateChunk(xx, zz, listener)); - } - - if(hit) { - listener.onRegionGenerated(x, z); - listener.onSaving(); - generator.save(); - generatedRegions.add(pos); - checkRegions(); - } - } - - private void checkRegion(int x, int z) { - if(generatedRegions.contains(new Position2(x, z))) { - return; - } - - generator.supportsRegions(x, z, listener); - } - - public void pause() { - paused.set(true); - } - - public void resume() { - paused.set(false); - } - - private PregenListener listenify(PregenListener listener) { - return new PregenListener() { - @Override - public void onTick(double chunksPerSecond, double chunksPerMinute, double regionsPerMinute, double percent, int generated, int totalChunks, int chunksRemaining, long eta, long elapsed, String method) { - listener.onTick(chunksPerSecond, chunksPerMinute, regionsPerMinute, percent, generated, totalChunks, chunksRemaining, eta, elapsed, method); - } - - @Override - public void onChunkGenerating(int x, int z) { - listener.onChunkGenerating(x, z); - } - - @Override - public void onChunkGenerated(int x, int z) { - listener.onChunkGenerated(x, z); - generated.addAndGet(1); - } - - @Override - public void onRegionGenerated(int x, int z) { - listener.onRegionGenerated(x, z); - } - - @Override - public void onRegionGenerating(int x, int z) { - listener.onRegionGenerating(x, z); - } - - @Override - public void onChunkCleaned(int x, int z) { - listener.onChunkCleaned(x, z); - } - - @Override - public void onRegionSkipped(int x, int z) { - listener.onRegionSkipped(x, z); - } - - @Override - public void onNetworkStarted(int x, int z) { - net.add(new Position2(x, z)); - } - - @Override - public void onNetworkFailed(int x, int z) { - retry.add(new Position2(x, z)); - } - - @Override - public void onNetworkReclaim(int revert) { - generated.addAndGet(-revert); - } - - @Override - public void onNetworkGeneratedChunk(int x, int z) { - generated.addAndGet(1); - } - - @Override - public void onNetworkDownloaded(int x, int z) { - net.remove(new Position2(x, z)); - } - - @Override - public void onClose() { - listener.onClose(); - } - - @Override - public void onSaving() { - listener.onSaving(); - } - - @Override - public void onChunkExistsInRegionGen(int x, int z) { - listener.onChunkExistsInRegionGen(x, z); - } - }; - } - - public boolean paused() { - return paused.get(); - } - - public Mantle getMantle() { - return generator.getMantle(); - } -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/PregenListener.java b/src/main/java/com/volmit/iris/core/pregenerator/PregenListener.java deleted file mode 100644 index fb3ab3952..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/PregenListener.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator; - -public interface PregenListener { - void onTick(double chunksPerSecond, double chunksPerMinute, double regionsPerMinute, double percent, int generated, int totalChunks, int chunksRemaining, long eta, long elapsed, String method); - - void onChunkGenerating(int x, int z); - - void onChunkGenerated(int x, int z); - - void onRegionGenerated(int x, int z); - - void onRegionGenerating(int x, int z); - - void onChunkCleaned(int x, int z); - - void onRegionSkipped(int x, int z); - - void onNetworkStarted(int x, int z); - - void onNetworkFailed(int x, int z); - - void onNetworkReclaim(int revert); - - void onNetworkGeneratedChunk(int x, int z); - - void onNetworkDownloaded(int x, int z); - - void onClose(); - - void onSaving(); - - void onChunkExistsInRegionGen(int x, int z); -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/PregenTask.java b/src/main/java/com/volmit/iris/core/pregenerator/PregenTask.java deleted file mode 100644 index 0b228c4ca..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/PregenTask.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.math.Spiraled; -import com.volmit.iris.util.math.Spiraler; -import lombok.Builder; -import lombok.Data; - -import java.util.Comparator; - -@Builder -@Data -public class PregenTask { - private static final Position2 ZERO = new Position2(0, 0); - private static final KList ORDER_CENTER = computeChunkOrder(); - private static final KMap> ORDERS = new KMap<>(); - - @Builder.Default - private Position2 center = new Position2(0, 0); - @Builder.Default - private int width = 1; - @Builder.Default - private int height = 1; - - public static void iterateRegion(int xr, int zr, Spiraled s, Position2 pull) { - for(Position2 i : ORDERS.computeIfAbsent(pull, PregenTask::computeOrder)) { - s.on(i.getX() + (xr << 5), i.getZ() + (zr << 5)); - } - } - - public static void iterateRegion(int xr, int zr, Spiraled s) { - iterateRegion(xr, zr, s, new Position2(0, 0)); - } - - private static KList computeOrder(Position2 pull) { - KList p = new KList<>(); - new Spiraler(33, 33, (x, z) -> { - int xx = (x + 15); - int zz = (z + 15); - if(xx < 0 || xx > 31 || zz < 0 || zz > 31) { - return; - } - - p.add(new Position2(xx, zz)); - }).drain(); - p.sort(Comparator.comparing((i) -> i.distance(pull))); - - return p; - } - - private static KList computeChunkOrder() { - Position2 center = new Position2(15, 15); - KList p = new KList<>(); - new Spiraler(33, 33, (x, z) -> { - int xx = x + 15; - int zz = z + 15; - if(xx < 0 || xx > 31 || zz < 0 || zz > 31) { - return; - } - - p.add(new Position2(xx, zz)); - }).drain(); - p.sort(Comparator.comparing((i) -> i.distance(center))); - return p; - } - - public void iterateRegions(Spiraled s) { - new Spiraler(getWidth() * 2, getHeight() * 2, s) - .setOffset(center.getX(), center.getZ()).drain(); - } - - public void iterateAllChunks(Spiraled s) { - new Spiraler(getWidth() * 2, getHeight() * 2, (x, z) -> iterateRegion(x, z, s)) - .setOffset(center.getX(), center.getZ()).drain(); - } -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/PregeneratorMethod.java b/src/main/java/com/volmit/iris/core/pregenerator/PregeneratorMethod.java deleted file mode 100644 index 2205d83de..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/PregeneratorMethod.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator; - -import com.volmit.iris.util.mantle.Mantle; - -/** - * Represents something that is capable of generating in chunks or regions, or both - */ -public interface PregeneratorMethod { - /** - * This is called before any generate methods are called. Setup your generator here - */ - void init(); - - /** - * This is called after the pregenerator is done. Save your work and stop threads - */ - void close(); - - /** - * This is called every X amount of chunks or regions. Save work, - * but no need to save all of it. At the end, close() will still be called. - */ - void save(); - - /** - * Return true if regions can be generated - * - * @param x - * the x region - * @param z - * the z region - * @return true if they can be - */ - boolean supportsRegions(int x, int z, PregenListener listener); - - /** - * Return the name of the method being used - * - * @param x - * the x region - * @param z - * the z region - * @return the name - */ - String getMethod(int x, int z); - - /** - * Called to generate a region. Execute sync, if multicore internally, wait - * for the task to complete - * - * @param x - * the x - * @param z - * the z - * @param listener - * signal chunks generating & generated. Parallel capable. - */ - void generateRegion(int x, int z, PregenListener listener); - - /** - * Called to generate a chunk. You can go async so long as save will wait on the threads to finish - * - * @param x - * the x - * @param z - * the z - */ - void generateChunk(int x, int z, PregenListener listener); - - Mantle getMantle(); -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/methods/AsyncOrMedievalPregenMethod.java b/src/main/java/com/volmit/iris/core/pregenerator/methods/AsyncOrMedievalPregenMethod.java deleted file mode 100644 index f33fe2cdc..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/methods/AsyncOrMedievalPregenMethod.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator.methods; - -import com.volmit.iris.core.pregenerator.PregenListener; -import com.volmit.iris.core.pregenerator.PregeneratorMethod; -import com.volmit.iris.util.mantle.Mantle; -import io.papermc.lib.PaperLib; -import org.bukkit.World; - -public class AsyncOrMedievalPregenMethod implements PregeneratorMethod { - private final PregeneratorMethod method; - - public AsyncOrMedievalPregenMethod(World world, int threads) { - method = PaperLib.isPaper() ? new AsyncPregenMethod(world, threads) : new MedievalPregenMethod(world); - } - - @Override - public void init() { - method.init(); - } - - @Override - public void close() { - method.close(); - } - - @Override - public void save() { - method.save(); - } - - @Override - public String getMethod(int x, int z) { - return method.getMethod(x, z); - } - - @Override - public boolean supportsRegions(int x, int z, PregenListener listener) { - return false; - } - - @Override - public void generateRegion(int x, int z, PregenListener listener) { - throw new UnsupportedOperationException(); - } - - @Override - public void generateChunk(int x, int z, PregenListener listener) { - method.generateChunk(x, z, listener); - } - - @Override - public Mantle getMantle() { - return method.getMantle(); - } -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/methods/AsyncPregenMethod.java b/src/main/java/com/volmit/iris/core/pregenerator/methods/AsyncPregenMethod.java deleted file mode 100644 index 3bbb45be8..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/methods/AsyncPregenMethod.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator.methods; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.pregenerator.PregenListener; -import com.volmit.iris.core.pregenerator.PregeneratorMethod; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.scheduling.J; -import io.papermc.lib.PaperLib; -import org.bukkit.Chunk; -import org.bukkit.World; - -import java.util.concurrent.Future; - -public class AsyncPregenMethod implements PregeneratorMethod { - private final World world; - private final MultiBurst burst; - private final KList> future; - - public AsyncPregenMethod(World world, int threads) { - if(!PaperLib.isPaper()) { - throw new UnsupportedOperationException("Cannot use PaperAsync on non paper!"); - } - - this.world = world; - burst = MultiBurst.burst; - future = new KList<>(1024); - } - - private void unloadAndSaveAllChunks() { - try { - J.sfut(() -> { - if(world == null) { - Iris.warn("World was null somehow..."); - return; - } - - for(Chunk i : world.getLoadedChunks()) { - i.unload(true); - } - world.save(); - }).get(); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - private void completeChunk(int x, int z, PregenListener listener) { - try { - PaperLib.getChunkAtAsync(world, x, z, true).get(); - listener.onChunkGenerated(x, z); - listener.onChunkCleaned(x, z); - } catch(Throwable e) { - e.printStackTrace(); - J.sleep(5); - future.add(burst.complete(() -> completeChunk(x, z, listener))); - } - } - - private void waitForChunks() { - for(Future i : future.copy()) { - try { - i.get(); - future.remove(i); - } catch(Throwable e) { - e.printStackTrace(); - } - } - } - - @Override - public void init() { - unloadAndSaveAllChunks(); - } - - @Override - public String getMethod(int x, int z) { - return "Async"; - } - - @Override - public void close() { - waitForChunks(); - unloadAndSaveAllChunks(); - } - - @Override - public void save() { - waitForChunks(); - unloadAndSaveAllChunks(); - } - - @Override - public boolean supportsRegions(int x, int z, PregenListener listener) { - return false; - } - - @Override - public void generateRegion(int x, int z, PregenListener listener) { - throw new UnsupportedOperationException(); - } - - @Override - public void generateChunk(int x, int z, PregenListener listener) { - if(future.size() > IrisSettings.getThreadCount(IrisSettings.get().getConcurrency().getParallelism())) { // TODO: FIX - waitForChunks(); - } - - listener.onChunkGenerating(x, z); - future.add(burst.complete(() -> completeChunk(x, z, listener))); - } - - @Override - public Mantle getMantle() { - if(IrisToolbelt.isIrisWorld(world)) { - return IrisToolbelt.access(world).getEngine().getMantle().getMantle(); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/methods/DummyPregenMethod.java b/src/main/java/com/volmit/iris/core/pregenerator/methods/DummyPregenMethod.java deleted file mode 100644 index 9ff345fc3..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/methods/DummyPregenMethod.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator.methods; - -import com.volmit.iris.core.pregenerator.PregenListener; -import com.volmit.iris.core.pregenerator.PregeneratorMethod; -import com.volmit.iris.util.mantle.Mantle; - -public class DummyPregenMethod implements PregeneratorMethod { - @Override - public void init() { - - } - - @Override - public void close() { - - } - - @Override - public String getMethod(int x, int z) { - return "Dummy"; - } - - @Override - public void save() { - - } - - @Override - public boolean supportsRegions(int x, int z, PregenListener listener) { - return false; - } - - @Override - public void generateRegion(int x, int z, PregenListener listener) { - - } - - @Override - public void generateChunk(int x, int z, PregenListener listener) { - - } - - @Override - public Mantle getMantle() { - return null; - } -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/methods/HybridPregenMethod.java b/src/main/java/com/volmit/iris/core/pregenerator/methods/HybridPregenMethod.java deleted file mode 100644 index 4cb537a2d..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/methods/HybridPregenMethod.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator.methods; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.pregenerator.PregenListener; -import com.volmit.iris.core.pregenerator.PregeneratorMethod; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.math.Position2; -import org.bukkit.World; - -import java.io.File; - -public class HybridPregenMethod implements PregeneratorMethod { - private final PregeneratorMethod inWorld; - private final World world; - - public HybridPregenMethod(World world, int threads) { - this.world = world; - inWorld = new AsyncOrMedievalPregenMethod(world, threads); - } - - @Override - public String getMethod(int x, int z) { - return "Hybrid<" + inWorld.getMethod(x, z) + ">"; - } - - @Override - public void init() { - inWorld.init(); - } - - @Override - public void close() { - inWorld.close(); - } - - @Override - public void save() { - inWorld.save(); - } - - @Override - public boolean supportsRegions(int x, int z, PregenListener listener) { - return inWorld.supportsRegions(x, z, listener); - } - - @Override - public void generateRegion(int x, int z, PregenListener listener) { - inWorld.generateRegion(x, z, listener); - } - - @Override - public void generateChunk(int x, int z, PregenListener listener) { - inWorld.generateChunk(x, z, listener); - } - - @Override - public Mantle getMantle() { - return inWorld.getMantle(); - } -} diff --git a/src/main/java/com/volmit/iris/core/pregenerator/methods/MedievalPregenMethod.java b/src/main/java/com/volmit/iris/core/pregenerator/methods/MedievalPregenMethod.java deleted file mode 100644 index 5fdc77613..000000000 --- a/src/main/java/com/volmit/iris/core/pregenerator/methods/MedievalPregenMethod.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.pregenerator.methods; - -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.pregenerator.PregenListener; -import com.volmit.iris.core.pregenerator.PregeneratorMethod; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Chunk; -import org.bukkit.World; - -import java.util.concurrent.CompletableFuture; - -public class MedievalPregenMethod implements PregeneratorMethod { - private final World world; - private final KList> futures; - - public MedievalPregenMethod(World world) { - this.world = world; - futures = new KList<>(); - } - - private void waitForChunks() { - for(CompletableFuture i : futures) { - try { - i.get(); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - futures.clear(); - } - - private void unloadAndSaveAllChunks() { - waitForChunks(); - try { - J.sfut(() -> { - for(Chunk i : world.getLoadedChunks()) { - i.unload(true); - } - world.save(); - }).get(); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - @Override - public void init() { - unloadAndSaveAllChunks(); - } - - @Override - public void close() { - unloadAndSaveAllChunks(); - } - - @Override - public void save() { - unloadAndSaveAllChunks(); - } - - @Override - public boolean supportsRegions(int x, int z, PregenListener listener) { - return false; - } - - @Override - public void generateRegion(int x, int z, PregenListener listener) { - throw new UnsupportedOperationException(); - } - - @Override - public String getMethod(int x, int z) { - return "Medieval"; - } - - @Override - public void generateChunk(int x, int z, PregenListener listener) { - if(futures.size() > IrisSettings.getThreadCount(IrisSettings.get().getConcurrency().getParallelism())) { - waitForChunks(); - } - - listener.onChunkGenerating(x, z); - futures.add(J.sfut(() -> { - world.getChunkAt(x, z); - listener.onChunkGenerated(x, z); - listener.onChunkCleaned(x, z); - })); - } - - @Override - public Mantle getMantle() { - if(IrisToolbelt.isIrisWorld(world)) { - return IrisToolbelt.access(world).getEngine().getMantle().getMantle(); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/core/project/IrisProject.java b/src/main/java/com/volmit/iris/core/project/IrisProject.java deleted file mode 100644 index fd629970e..000000000 --- a/src/main/java/com/volmit/iris/core/project/IrisProject.java +++ /dev/null @@ -1,666 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.project; - -import com.google.gson.Gson; -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.core.loader.ResourceLoader; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisBlockData; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisEntity; -import com.volmit.iris.engine.object.IrisGenerator; -import com.volmit.iris.engine.object.IrisLootTable; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.engine.object.IrisSpawner; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.engine.platform.PlatformChunkGenerator; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.exceptions.IrisException; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONArray; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.O; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import com.volmit.iris.util.scheduling.jobs.Job; -import com.volmit.iris.util.scheduling.jobs.JobCollection; -import com.volmit.iris.util.scheduling.jobs.ParallelQueueJob; -import lombok.Data; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.World; -import org.zeroturnaround.zip.ZipUtil; - -import java.awt.Desktop; -import java.awt.GraphicsEnvironment; -import java.io.File; -import java.io.IOException; -import java.util.Objects; -import java.util.UUID; -import java.util.function.Consumer; - -@SuppressWarnings("ALL") -@Data -public class IrisProject { - private File path; - private String name; - private PlatformChunkGenerator activeProvider; - - public IrisProject(File path) { - this.path = path; - this.name = path.getName(); - } - - public static int clean(VolmitSender s, File clean) { - int c = 0; - if(clean.isDirectory()) { - for(File i : clean.listFiles()) { - c += clean(s, i); - } - } else if(clean.getName().endsWith(".json")) { - try { - clean(clean); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Failed to beautify " + clean.getAbsolutePath() + " You may have errors in your json!"); - } - - c++; - } - - return c; - } - - public static void clean(File clean) throws IOException { - JSONObject obj = new JSONObject(IO.readAll(clean)); - fixBlocks(obj, clean); - - IO.writeAll(clean, obj.toString(4)); - } - - public static void fixBlocks(JSONObject obj, File f) { - for(String i : obj.keySet()) { - Object o = obj.get(i); - - if(i.equals("block") && o instanceof String && !o.toString().trim().isEmpty() && !o.toString().contains(":")) { - obj.put(i, "minecraft:" + o); - Iris.debug("Updated Block Key: " + o + " to " + obj.getString(i) + " in " + f.getPath()); - } - - if(o instanceof JSONObject) { - fixBlocks((JSONObject) o, f); - } else if(o instanceof JSONArray) { - fixBlocks((JSONArray) o, f); - } - } - } - - public static void fixBlocks(JSONArray obj, File f) { - for(int i = 0; i < obj.length(); i++) { - Object o = obj.get(i); - - if(o instanceof JSONObject) { - fixBlocks((JSONObject) o, f); - } else if(o instanceof JSONArray) { - fixBlocks((JSONArray) o, f); - } - } - } - - public boolean isOpen() { - return activeProvider != null; - } - - public KList collectFiles(File f, String fileExtension) { - KList l = new KList<>(); - - if(f.isDirectory()) { - for(File i : f.listFiles()) { - l.addAll(collectFiles(i, fileExtension)); - } - } else if(f.getName().endsWith("." + fileExtension)) { - l.add(f); - } - - return l; - } - - public KList collectFiles(String json) { - return collectFiles(path, json); - } - - public void open(VolmitSender sender) throws IrisException { - open(sender, 1337, (w) -> - { - }); - } - - public void openVSCode(VolmitSender sender) { - - IrisDimension d = IrisData.loadAnyDimension(getName()); - J.attemptAsync(() -> - { - try { - if(d.getLoader() == null) { - sender.sendMessage("Could not get dimension loader"); - return; - } - File f = d.getLoader().getDataFolder(); - - if(!doOpenVSCode(f)) { - File ff = new File(d.getLoader().getDataFolder(), d.getLoadKey() + ".code-workspace"); - Iris.warn("Project missing code-workspace: " + ff.getAbsolutePath() + " Re-creating code workspace."); - - try { - IO.writeAll(ff, createCodeWorkspaceConfig()); - } catch(IOException e1) { - Iris.reportError(e1); - e1.printStackTrace(); - } - updateWorkspace(); - if(!doOpenVSCode(f)) { - Iris.warn("Tried creating code workspace but failed a second time. Your project is likely corrupt."); - } - } - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - }); - } - - private boolean doOpenVSCode(File f) throws IOException { - boolean foundWork = false; - for(File i : Objects.requireNonNull(f.listFiles())) { - if(i.getName().endsWith(".code-workspace")) { - foundWork = true; - J.a(() -> - { - updateWorkspace(); - }); - - if(IrisSettings.get().getStudio().isOpenVSCode()) { - if(!GraphicsEnvironment.isHeadless()) { - Iris.msg("Opening VSCode. You may see the output from VSCode."); - Iris.msg("VSCode output always starts with: '(node:#####) electron'"); - Desktop.getDesktop().open(i); - } - } - - break; - } - } - return foundWork; - } - - public void open(VolmitSender sender, long seed, Consumer onDone) throws IrisException { - if(isOpen()) { - close(); - } - - boolean hasError = false; - - if(hasError) { - return; - } - - IrisDimension d = IrisData.loadAnyDimension(getName()); - if(d == null) { - sender.sendMessage("Can't find dimension: " + getName()); - return; - } else if(sender.isPlayer()) { - sender.player().setGameMode(GameMode.SPECTATOR); - } - - openVSCode(sender); - - - J.a(() -> { - try { - activeProvider = (PlatformChunkGenerator) IrisToolbelt.createWorld() - .seed(seed) - .sender(sender) - .studio(true) - .name("iris/" + UUID.randomUUID()) - .dimension(d.getLoadKey()) - .create().getGenerator(); - onDone.accept(activeProvider.getTarget().getWorld().realWorld()); - } catch(IrisException e) { - e.printStackTrace(); - } - }); - } - - public void close() { - Iris.debug("Closing Active Provider"); - IrisToolbelt.evacuate(activeProvider.getTarget().getWorld().realWorld()); - activeProvider.close(); - File folder = activeProvider.getTarget().getWorld().worldFolder(); - Iris.linkMultiverseCore.removeFromConfig(activeProvider.getTarget().getWorld().name()); - Bukkit.unloadWorld(activeProvider.getTarget().getWorld().name(), false); - J.attemptAsync(() -> IO.delete(folder)); - Iris.debug("Closed Active Provider " + activeProvider.getTarget().getWorld().name()); - activeProvider = null; - } - - public File getCodeWorkspaceFile() { - return new File(path, getName() + ".code-workspace"); - } - - public boolean updateWorkspace() { - getPath().mkdirs(); - File ws = getCodeWorkspaceFile(); - - try { - PrecisionStopwatch p = PrecisionStopwatch.start(); - JSONObject j = createCodeWorkspaceConfig(); - IO.writeAll(ws, j.toString(4)); - p.end(); - return true; - } catch(Throwable e) { - Iris.reportError(e); - Iris.warn("Project invalid: " + ws.getAbsolutePath() + " Re-creating. You may loose some vs-code workspace settings! But not your actual project!"); - ws.delete(); - try { - IO.writeAll(ws, createCodeWorkspaceConfig()); - } catch(IOException e1) { - Iris.reportError(e1); - e1.printStackTrace(); - } - } - - return false; - } - - public JSONObject createCodeWorkspaceConfig() { - JSONObject ws = new JSONObject(); - JSONArray folders = new JSONArray(); - JSONObject folder = new JSONObject(); - folder.put("path", "."); - folders.put(folder); - ws.put("folders", folders); - JSONObject settings = new JSONObject(); - settings.put("workbench.colorTheme", "Monokai"); - settings.put("workbench.preferredDarkColorTheme", "Solarized Dark"); - settings.put("workbench.tips.enabled", false); - settings.put("workbench.tree.indent", 24); - settings.put("files.autoSave", "onFocusChange"); - JSONObject jc = new JSONObject(); - jc.put("editor.autoIndent", "brackets"); - jc.put("editor.acceptSuggestionOnEnter", "smart"); - jc.put("editor.cursorSmoothCaretAnimation", true); - jc.put("editor.dragAndDrop", false); - jc.put("files.trimTrailingWhitespace", true); - jc.put("diffEditor.ignoreTrimWhitespace", true); - jc.put("files.trimFinalNewlines", true); - jc.put("editor.suggest.showKeywords", false); - jc.put("editor.suggest.showSnippets", false); - jc.put("editor.suggest.showWords", false); - JSONObject st = new JSONObject(); - st.put("strings", true); - jc.put("editor.quickSuggestions", st); - jc.put("editor.suggest.insertMode", "replace"); - settings.put("[json]", jc); - settings.put("json.maxItemsComputed", 30000); - JSONArray schemas = new JSONArray(); - IrisData dm = IrisData.get(getPath()); - - for(ResourceLoader r : dm.getLoaders().v()) { - if(r.supportsSchemas()) { - schemas.put(r.buildSchema()); - } - } - - for(Class i : Iris.getClasses("com.volmit.iris.engine.object.", Snippet.class)) { - try { - String snipType = i.getDeclaredAnnotation(Snippet.class).value(); - JSONObject o = new JSONObject(); - KList fm = new KList<>(); - - for(int g = 1; g < 8; g++) { - fm.add("/snippet/" + snipType + Form.repeat("/*", g) + ".json"); - } - - o.put("fileMatch", new JSONArray(fm.toArray())); - o.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json"); - schemas.put(o); - File a = new File(dm.getDataFolder(), ".iris/schema/snippet/" + snipType + "-schema.json"); - J.attemptAsync(() -> { - try { - IO.writeAll(a, new SchemaBuilder(i, dm).construct().toString(4)); - } catch(Throwable e) { - e.printStackTrace(); - } - }); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - settings.put("json.schemas", schemas); - ws.put("settings", settings); - - return ws; - } - - public File compilePackage(VolmitSender sender, boolean obfuscate, boolean minify) { - String dimm = getName(); - IrisData dm = IrisData.get(path); - IrisDimension dimension = dm.getDimensionLoader().load(dimm); - File folder = new File(Iris.instance.getDataFolder(), "exports/" + dimension.getLoadKey()); - folder.mkdirs(); - Iris.info("Packaging Dimension " + dimension.getName() + " " + (obfuscate ? "(Obfuscated)" : "")); - KSet regions = new KSet<>(); - KSet biomes = new KSet<>(); - KSet entities = new KSet<>(); - KSet spawners = new KSet<>(); - KSet generators = new KSet<>(); - KSet loot = new KSet<>(); - KSet blocks = new KSet<>(); - - for(String i : dm.getDimensionLoader().getPossibleKeys()) { - blocks.add(dm.getBlockLoader().load(i)); - } - - dimension.getRegions().forEach((i) -> regions.add(dm.getRegionLoader().load(i))); - dimension.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i))); - regions.forEach((i) -> biomes.addAll(i.getAllBiomes(null))); - regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i)))); - regions.forEach((r) -> r.getEntitySpawners().forEach((sp) -> spawners.add(dm.getSpawnerLoader().load(sp)))); - dimension.getEntitySpawners().forEach((sp) -> spawners.add(dm.getSpawnerLoader().load(sp))); - biomes.forEach((i) -> i.getGenerators().forEach((j) -> generators.add(j.getCachedGenerator(null)))); - biomes.forEach((r) -> r.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i)))); - biomes.forEach((r) -> r.getEntitySpawners().forEach((sp) -> spawners.add(dm.getSpawnerLoader().load(sp)))); - spawners.forEach((i) -> i.getSpawns().forEach((j) -> entities.add(dm.getEntityLoader().load(j.getEntity())))); - KMap renameObjects = new KMap<>(); - String a; - StringBuilder b = new StringBuilder(); - StringBuilder c = new StringBuilder(); - sender.sendMessage("Serializing Objects"); - - for(IrisBiome i : biomes) { - for(IrisObjectPlacement j : i.getObjects()) { - b.append(j.hashCode()); - KList newNames = new KList<>(); - - for(String k : j.getPlace()) { - if(renameObjects.containsKey(k)) { - newNames.add(renameObjects.get(k)); - continue; - } - - String name = !obfuscate ? k : UUID.randomUUID().toString().replaceAll("-", ""); - b.append(name); - newNames.add(name); - renameObjects.put(k, name); - } - - j.setPlace(newNames); - } - } - - KMap> lookupObjects = renameObjects.flip(); - StringBuilder gb = new StringBuilder(); - ChronoLatch cl = new ChronoLatch(1000); - O ggg = new O<>(); - ggg.set(0); - biomes.forEach((i) -> i.getObjects().forEach((j) -> j.getPlace().forEach((k) -> - { - try { - File f = dm.getObjectLoader().findFile(lookupObjects.get(k).get(0)); - IO.copyFile(f, new File(folder, "objects/" + k + ".iob")); - gb.append(IO.hash(f)); - ggg.set(ggg.get() + 1); - - if(cl.flip()) { - int g = ggg.get(); - ggg.set(0); - sender.sendMessage("Wrote another " + g + " Objects"); - } - } catch(Throwable e) { - Iris.reportError(e); - } - }))); - - b.append(IO.hash(gb.toString())); - c.append(IO.hash(b.toString())); - b = new StringBuilder(); - - Iris.info("Writing Dimensional Scaffold"); - - try { - a = new JSONObject(new Gson().toJson(dimension)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "dimensions/" + dimension.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - - for(IrisGenerator i : generators) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "generators/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - c.append(IO.hash(b.toString())); - b = new StringBuilder(); - - for(IrisRegion i : regions) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "regions/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for(IrisBlockData i : blocks) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "blocks/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for(IrisBiome i : biomes) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "biomes/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for(IrisEntity i : entities) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "entities/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for(IrisLootTable i : loot) { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "loot/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - c.append(IO.hash(b.toString())); - String finalHash = IO.hash(c.toString()); - JSONObject meta = new JSONObject(); - meta.put("hash", finalHash); - meta.put("time", M.ms()); - meta.put("version", dimension.getVersion()); - IO.writeAll(new File(folder, "package.json"), meta.toString(minify ? 0 : 4)); - File p = new File(Iris.instance.getDataFolder(), "exports/" + dimension.getLoadKey() + ".iris"); - Iris.info("Compressing Package"); - ZipUtil.pack(folder, p, 9); - IO.delete(folder); - - sender.sendMessage("Package Compiled!"); - return p; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - sender.sendMessage("Failed!"); - return null; - } - - public void compile(VolmitSender sender) { - IrisData data = IrisData.get(getPath()); - KList jobs = new KList<>(); - KList files = new KList<>(); - KList objects = new KList<>(); - files(getPath(), files); - filesObjects(getPath(), objects); - - jobs.add(new ParallelQueueJob() { - @Override - public void execute(File f) { - try { - IrisObject o = new IrisObject(0, 0, 0); - o.read(f); - - if(o.getBlocks().isEmpty()) { - sender.sendMessageRaw("" + f.getPath() + - "'>- IOB " + f.getName() + " has 0 blocks!"); - } - - if(o.getW() == 0 || o.getH() == 0 || o.getD() == 0) { - sender.sendMessageRaw("" + f.getPath() + "\nThe width height or depth has a zero in it (bad format)" + - "'>- IOB " + f.getName() + " is not 3D!"); - } - } catch(IOException e) { - e.printStackTrace(); - } - } - - @Override - public String getName() { - return "IOB"; - } - }.queue(objects)); - - jobs.add(new ParallelQueueJob() { - @Override - public void execute(File f) { - try { - JSONObject p = new JSONObject(IO.readAll(f)); - fixBlocks(p); - scanForErrors(data, f, p, sender); - IO.writeAll(f, p.toString(4)); - - } catch(Throwable e) { - sender.sendMessageRaw("" + f.getPath() + - "\n" + e.getMessage() + - "'>- JSON Error " + f.getName()); - } - } - - @Override - public String getName() { - return "JSON"; - } - }.queue(files)); - - new JobCollection("Compile", jobs).execute(sender); - } - - private void scanForErrors(IrisData data, File f, JSONObject p, VolmitSender sender) { - String key = data.toLoadKey(f); - ResourceLoader loader = data.getTypedLoaderFor(f); - - if(loader == null) { - sender.sendMessageBasic("Can't find loader for " + f.getPath()); - return; - } - - IrisRegistrant load = loader.load(key); - compare(load.getClass(), p, sender, new KList<>()); - load.scanForErrors(p, sender); - } - - public void compare(Class c, JSONObject j, VolmitSender sender, KList path) { - try { - Object o = c.getClass().getConstructor().newInstance(); - } catch(Throwable e) { - - } - } - - public void files(File clean, KList files) { - if(clean.isDirectory()) { - for(File i : clean.listFiles()) { - files(i, files); - } - } else if(clean.getName().endsWith(".json")) { - try { - files.add(clean); - } catch(Throwable e) { - Iris.reportError(e); - } - } - } - - public void filesObjects(File clean, KList files) { - if(clean.isDirectory()) { - for(File i : clean.listFiles()) { - filesObjects(i, files); - } - } else if(clean.getName().endsWith(".iob")) { - try { - files.add(clean); - } catch(Throwable e) { - Iris.reportError(e); - } - } - } - - private void fixBlocks(JSONObject obj) { - for(String i : obj.keySet()) { - Object o = obj.get(i); - - if(i.equals("block") && o instanceof String && !o.toString().trim().isEmpty() && !o.toString().contains(":")) { - obj.put(i, "minecraft:" + o); - } - - if(o instanceof JSONObject) { - fixBlocks((JSONObject) o); - } else if(o instanceof JSONArray) { - fixBlocks((JSONArray) o); - } - } - } - - private void fixBlocks(JSONArray obj) { - for(int i = 0; i < obj.length(); i++) { - Object o = obj.get(i); - - if(o instanceof JSONObject) { - fixBlocks((JSONObject) o); - } else if(o instanceof JSONArray) { - fixBlocks((JSONArray) o); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/core/project/SchemaBuilder.java b/src/main/java/com/volmit/iris/core/project/SchemaBuilder.java deleted file mode 100644 index d7a89dbfe..000000000 --- a/src/main/java/com/volmit/iris/core/project/SchemaBuilder.java +++ /dev/null @@ -1,682 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.project; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.core.loader.ResourceLoader; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListBlockType; -import com.volmit.iris.engine.object.annotations.RegistryListFont; -import com.volmit.iris.engine.object.annotations.RegistryListItemType; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.RegistryListSpecialEntity; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.json.JSONArray; -import com.volmit.iris.util.json.JSONObject; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.potion.PotionEffectType; - -import java.awt.GraphicsEnvironment; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -public class SchemaBuilder { - private static final String SYMBOL_LIMIT__N = "*"; - private static final String SYMBOL_TYPE__N = ""; - private static final JSONArray POTION_TYPES = getPotionTypes(); - private static final JSONArray ENCHANT_TYPES = getEnchantmentTypes(); - private static final JSONArray ITEM_TYPES = new JSONArray(B.getItemTypes()); - private static final JSONArray FONT_TYPES = new JSONArray(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()); - private final KMap definitions; - private final Class root; - private final KList warnings; - private final IrisData data; - - public SchemaBuilder(Class root, IrisData data) { - this.data = data; - warnings = new KList<>(); - this.definitions = new KMap<>(); - this.root = root; - } - - private static JSONArray getEnchantmentTypes() { - JSONArray a = new JSONArray(); - - for(Field gg : Enchantment.class.getDeclaredFields()) { - a.put(gg.getName()); - } - - return a; - } - - private static JSONArray getPotionTypes() { - JSONArray a = new JSONArray(); - - for(PotionEffectType gg : PotionEffectType.values()) { - a.put(gg.getName().toUpperCase().replaceAll("\\Q \\E", "_")); - } - - return a; - } - - public JSONObject construct() { - JSONObject schema = new JSONObject(); - schema.put("$schema", "http://json-schema.org/draft-07/schema#"); - schema.put("$id", "https://volmit.com/iris-schema/" + root.getSimpleName().toLowerCase() + ".json"); - - JSONObject props = buildProperties(root); - - for(String i : props.keySet()) { - if(!schema.has(i)) { - schema.put(i, props.get(i)); - } - } - - JSONObject defs = new JSONObject(); - - for(Map.Entry entry : definitions.entrySet()) { - defs.put(entry.getKey(), entry.getValue()); - } - - schema.put("definitions", defs); - - for(String i : warnings) { - Iris.warn(root.getSimpleName() + ": " + i); - } - - return schema; - } - - private JSONObject buildProperties(Class c) { - JSONObject o = new JSONObject(); - JSONObject properties = new JSONObject(); - o.put("description", getDescription(c)); - o.put("type", getType(c)); - JSONArray required = new JSONArray(); - - if(c.isAssignableFrom(IrisRegistrant.class) || IrisRegistrant.class.isAssignableFrom(c)) { - for(Field k : IrisRegistrant.class.getDeclaredFields()) { - k.setAccessible(true); - - if(Modifier.isStatic(k.getModifiers()) || Modifier.isFinal(k.getModifiers()) || Modifier.isTransient(k.getModifiers())) { - continue; - } - - JSONObject property = buildProperty(k, c); - - if(property.getBoolean("!required")) { - required.put(k.getName()); - } - - property.remove("!required"); - properties.put(k.getName(), property); - } - } - - for(Field k : c.getDeclaredFields()) { - k.setAccessible(true); - - if(Modifier.isStatic(k.getModifiers()) || Modifier.isFinal(k.getModifiers()) || Modifier.isTransient(k.getModifiers())) { - continue; - } - - JSONObject property = buildProperty(k, c); - - property.remove("!required"); - properties.put(k.getName(), property); - } - - if(required.length() > 0) { - o.put("required", required); - } - - o.put("properties", properties); - - - if(c.isAnnotationPresent(Snippet.class)) { - JSONObject anyOf = new JSONObject(); - JSONArray arr = new JSONArray(); - JSONObject str = new JSONObject(); - str.put("type", "string"); - arr.put(o); - arr.put(str); - anyOf.put("anyOf", arr); - - return anyOf; - } - - return o; - } - - private JSONObject buildProperty(Field k, Class cl) { - JSONObject prop = new JSONObject(); - String type = getType(k.getType()); - KList description = new KList<>(); - prop.put("!required", k.isAnnotationPresent(Required.class)); - prop.put("type", type); - String fancyType = "Unknown Type"; - - switch(type) { - case "boolean" -> fancyType = "Boolean"; - case "integer" -> { - fancyType = "Integer"; - if(k.isAnnotationPresent(MinNumber.class)) { - int min = (int) k.getDeclaredAnnotation(MinNumber.class).value(); - prop.put("minimum", min); - description.add(SYMBOL_LIMIT__N + " Minimum allowed is " + min); - } - if(k.isAnnotationPresent(MaxNumber.class)) { - int max = (int) k.getDeclaredAnnotation(MaxNumber.class).value(); - prop.put("maximum", max); - description.add(SYMBOL_LIMIT__N + " Maximum allowed is " + max); - } - } - case "number" -> { - fancyType = "Number"; - if(k.isAnnotationPresent(MinNumber.class)) { - double min = k.getDeclaredAnnotation(MinNumber.class).value(); - prop.put("minimum", min); - description.add(SYMBOL_LIMIT__N + " Minimum allowed is " + min); - } - if(k.isAnnotationPresent(MaxNumber.class)) { - double max = k.getDeclaredAnnotation(MaxNumber.class).value(); - prop.put("maximum", max); - description.add(SYMBOL_LIMIT__N + " Maximum allowed is " + max); - } - } - case "string" -> { - fancyType = "Text"; - if(k.isAnnotationPresent(MinNumber.class)) { - int min = (int) k.getDeclaredAnnotation(MinNumber.class).value(); - prop.put("minLength", min); - description.add(SYMBOL_LIMIT__N + " Minimum Length allowed is " + min); - } - if(k.isAnnotationPresent(MaxNumber.class)) { - int max = (int) k.getDeclaredAnnotation(MaxNumber.class).value(); - prop.put("maxLength", max); - description.add(SYMBOL_LIMIT__N + " Maximum Length allowed is " + max); - } - - - if(k.isAnnotationPresent(RegistryListResource.class)) { - RegistryListResource rr = k.getDeclaredAnnotation(RegistryListResource.class); - ResourceLoader loader = data.getLoaders().get(rr.value()); - - if(loader != null) { - String key = "erz" + loader.getFolderName(); - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(loader.getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris " + loader.getResourceTypeName(); - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid " + loader.getFolderName() + " (use ctrl+space for auto complete!)"); - } else { - Iris.error("Cannot find Registry Loader for type " + rr.value() + " used in " + k.getDeclaringClass().getCanonicalName() + " in field " + k.getName()); - } - } else if(k.isAnnotationPresent(RegistryListBlockType.class)) { - String key = "enum-block-type"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - JSONArray ja = new JSONArray(); - - for(String i : data.getBlockLoader().getPossibleKeys()) { - ja.put(i); - } - - for(String i : B.getBlockTypes()) { - ja.put(i); - } - - j.put("enum", ja); - definitions.put(key, j); - } - - fancyType = "Block Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Block Type (use ctrl+space for auto complete!)"); - - } else if(k.isAnnotationPresent(RegistryListItemType.class)) { - String key = "enum-item-type"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", ITEM_TYPES); - definitions.put(key, j); - } - - fancyType = "Item Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Item Type (use ctrl+space for auto complete!)"); - - } else if(k.isAnnotationPresent(RegistryListSpecialEntity.class)) { - String key = "enum-reg-specialentity"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - KList list = new KList<>(); - list.addAll(Iris.linkMythicMobs.getMythicMobTypes().stream().map(s -> "MythicMobs:" + s).collect(Collectors.toList())); - //TODO add Citizens stuff here too - j.put("enum", list.toJSONStringArray()); - definitions.put(key, j); - } - - fancyType = "Mythic Mob Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Mythic Mob Type (use ctrl+space for auto complete!) Define mythic mobs with the mythic mobs plugin configuration files."); - } else if(k.isAnnotationPresent(RegistryListFont.class)) { - String key = "enum-font"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", FONT_TYPES); - definitions.put(key, j); - } - - fancyType = "Font Family"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Font Family (use ctrl+space for auto complete!)"); - - } else if(k.getType().equals(Enchantment.class)) { - String key = "enum-enchantment"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", ENCHANT_TYPES); - definitions.put(key, j); - } - - fancyType = "Enchantment Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Enchantment Type (use ctrl+space for auto complete!)"); - } else if(k.getType().equals(PotionEffectType.class)) { - String key = "enum-potion-effect-type"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", POTION_TYPES); - definitions.put(key, j); - } - - fancyType = "Potion Effect Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Potion Effect Type (use ctrl+space for auto complete!)"); - - } else if(k.getType().isEnum()) { - fancyType = k.getType().getSimpleName().replaceAll("\\QIris\\E", ""); - JSONArray a = new JSONArray(); - boolean advanced = k.getType().isAnnotationPresent(Desc.class); - for(Object gg : k.getType().getEnumConstants()) { - if(advanced) { - try { - JSONObject j = new JSONObject(); - String name = ((Enum) gg).name(); - j.put("const", name); - Desc dd = k.getType().getField(name).getAnnotation(Desc.class); - j.put("description", dd == null ? ("No Description for " + name) : dd.value()); - a.put(j); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } else { - a.put(((Enum) gg).name()); - } - } - - String key = (advanced ? "oneof-" : "") + "enum-" + k.getType().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put(advanced ? "oneOf" : "enum", a); - definitions.put(key, j); - } - - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid " + k.getType().getSimpleName().replaceAll("\\QIris\\E", "") + " (use ctrl+space for auto complete!)"); - - } - } - case "object" -> { - fancyType = k.getType().getSimpleName().replaceAll("\\QIris\\E", "") + " (Object)"; - String key = "obj-" + k.getType().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); - if(!definitions.containsKey(key)) { - definitions.put(key, new JSONObject()); - definitions.put(key, buildProperties(k.getType())); - } - prop.put("$ref", "#/definitions/" + key); - } - case "array" -> { - fancyType = "List of Something...?"; - ArrayType t = k.getDeclaredAnnotation(ArrayType.class); - if(t != null) { - if(t.min() > 0) { - prop.put("minItems", t.min()); - if(t.min() == 1) { - description.add(SYMBOL_LIMIT__N + " At least one entry must be defined, or just remove this list."); - } else { - description.add(SYMBOL_LIMIT__N + " Requires at least " + t.min() + " entries."); - } - } - - String arrayType = getType(t.type()); - - switch(arrayType) { - case "integer" -> fancyType = "List of Integers"; - case "number" -> fancyType = "List of Numbers"; - case "object" -> { - fancyType = "List of " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + "s (Objects)"; - String key = "obj-" + t.type().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); - if(!definitions.containsKey(key)) { - definitions.put(key, new JSONObject()); - definitions.put(key, buildProperties(t.type())); - } - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - } - case "string" -> { - fancyType = "List of Text"; - - if(k.isAnnotationPresent(RegistryListResource.class)) { - RegistryListResource rr = k.getDeclaredAnnotation(RegistryListResource.class); - ResourceLoader loader = data.getLoaders().get(rr.value()); - - if(loader != null) { - fancyType = "List<" + loader.getResourceTypeName() + ">"; - String key = "erz" + loader.getFolderName(); - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(loader.getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid " + loader.getResourceTypeName() + " (use ctrl+space for auto complete!)"); - } else { - Iris.error("Cannot find Registry Loader for type (list schema) " + rr.value() + " used in " + k.getDeclaringClass().getCanonicalName() + " in field " + k.getName()); - } - } else if(k.isAnnotationPresent(RegistryListBlockType.class)) { - fancyType = "List of Block Types"; - String key = "enum-block-type"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - JSONArray ja = new JSONArray(); - - for(String i : data.getBlockLoader().getPossibleKeys()) { - ja.put(i); - } - - for(String i : B.getBlockTypes()) { - ja.put(i); - } - - j.put("enum", ja); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Block Type (use ctrl+space for auto complete!)"); - } else if(k.isAnnotationPresent(RegistryListItemType.class)) { - fancyType = "List of Item Types"; - String key = "enum-item-type"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", ITEM_TYPES); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Item Type (use ctrl+space for auto complete!)"); - } else if(k.isAnnotationPresent(RegistryListFont.class)) { - String key = "enum-font"; - fancyType = "List of Font Families"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", FONT_TYPES); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Font Family (use ctrl+space for auto complete!)"); - } else if(t.type().equals(Enchantment.class)) { - fancyType = "List of Enchantment Types"; - String key = "enum-enchantment"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", ENCHANT_TYPES); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Enchantment Type (use ctrl+space for auto complete!)"); - } else if(t.type().equals(PotionEffectType.class)) { - fancyType = "List of Potion Effect Types"; - String key = "enum-potion-effect-type"; - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put("enum", POTION_TYPES); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Potion Effect Type (use ctrl+space for auto complete!)"); - } else if(t.type().isEnum()) { - fancyType = "List of " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + "s"; - JSONArray a = new JSONArray(); - boolean advanced = t.type().isAnnotationPresent(Desc.class); - for(Object gg : t.type().getEnumConstants()) { - if(advanced) { - try { - JSONObject j = new JSONObject(); - String name = ((Enum) gg).name(); - j.put("const", name); - Desc dd = t.type().getField(name).getAnnotation(Desc.class); - j.put("description", dd == null ? ("No Description for " + name) : dd.value()); - a.put(j); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } else { - a.put(((Enum) gg).name()); - } - } - - String key = (advanced ? "oneof-" : "") + "enum-" + t.type().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - j.put(advanced ? "oneOf" : "enum", a); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + " (use ctrl+space for auto complete!)"); - } - } - } - } else { - warnings.add("Undefined array type for field " + k.getName() + " (" + k.getType().getSimpleName() + ") in class " + cl.getSimpleName()); - } - } - default -> warnings.add("Unexpected Schema Type: " + type + " for field " + k.getName() + " (" + k.getType().getSimpleName() + ") in class " + cl.getSimpleName()); - } - - KList d = new KList<>(); - d.add(k.getName()); - d.add(getFieldDescription(k)); - d.add(" "); - d.add(fancyType); - d.add(getDescription(k.getType())); - - if(k.getType().isAnnotationPresent(Snippet.class)) { - String sm = k.getType().getDeclaredAnnotation(Snippet.class).value(); - d.add(" "); - d.add("You can instead specify \"snippet/" + sm + "/some-name.json\" to use a snippet file instead of specifying it here."); - } - - try { - k.setAccessible(true); - Object value = k.get(cl.newInstance()); - - if(value != null) { - if(value instanceof List) { - d.add(" "); - d.add("* Default Value is an empty list"); - } else if(!cl.isPrimitive() && !(value instanceof Number) && !(value instanceof String) && !(cl.isEnum())) { - d.add(" "); - d.add("* Default Value is a default object (create this object to see default properties)"); - } else { - d.add(" "); - d.add("* Default Value is " + value); - } - } - } catch(Throwable ignored) { - - } - - description.forEach((g) -> d.add(g.trim())); - prop.put("type", type); - prop.put("description", d.toString("\n")); - - if(k.getType().isAnnotationPresent(Snippet.class)) { - JSONObject anyOf = new JSONObject(); - JSONArray arr = new JSONArray(); - JSONObject str = new JSONObject(); - str.put("type", "string"); - String key = "enum-snippet-" + k.getType().getDeclaredAnnotation(Snippet.class).value(); - str.put("$ref", "#/definitions/" + key); - - if(!definitions.containsKey(key)) { - JSONObject j = new JSONObject(); - JSONArray snl = new JSONArray(); - data.getPossibleSnippets(k.getType().getDeclaredAnnotation(Snippet.class).value()).forEach(snl::put); - j.put("enum", snl); - definitions.put(key, j); - } - - arr.put(prop); - arr.put(str); - prop.put("description", d.toString("\n")); - str.put("description", d.toString("\n")); - anyOf.put("anyOf", arr); - anyOf.put("description", d.toString("\n")); - anyOf.put("!required", k.isAnnotationPresent(Required.class)); - - return anyOf; - } - - return prop; - } - - private String getType(Class c) { - if(c.equals(int.class) || c.equals(Integer.class) || c.equals(long.class) || c.equals(Long.class)) { - return "integer"; - } - - if(c.equals(float.class) || c.equals(double.class) || c.equals(Float.class) || c.equals(Double.class)) { - return "number"; - } - - if(c.equals(boolean.class) || c.equals(Boolean.class)) { - return "boolean"; - } - - if(c.equals(String.class) || c.isEnum() || c.equals(Enchantment.class) || c.equals(PotionEffectType.class)) { - return "string"; - } - - if(c.equals(KList.class)) { - return "array"; - } - - if(c.equals(KMap.class)) { - return "object"; - } - - if(!c.isAnnotationPresent(Desc.class) && c.getCanonicalName().startsWith("com.volmit.iris.")) { - warnings.addIfMissing("Unsupported Type: " + c.getCanonicalName() + " Did you forget @Desc?"); - } - - return "object"; - } - - private String getFieldDescription(Field r) { - - if(r.isAnnotationPresent(Desc.class)) { - return r.getDeclaredAnnotation(Desc.class).value(); - } - - // suppress warnings on bukkit classes - if(r.getDeclaringClass().getName().startsWith("org.bukkit.")) { - return "Bukkit package classes and enums have no descriptions"; - } - - warnings.addIfMissing("Missing @Desc on field " + r.getName() + " (" + r.getType() + ") in " + r.getDeclaringClass().getCanonicalName()); - return "No Field Description"; - } - - private String getDescription(Class r) { - if(r.isAnnotationPresent(Desc.class)) { - return r.getDeclaredAnnotation(Desc.class).value(); - } - - if(!r.isPrimitive() && !r.equals(KList.class) && !r.equals(KMap.class) && r.getCanonicalName().startsWith("com.volmit.")) { - warnings.addIfMissing("Missing @Desc on " + r.getSimpleName() + " in " + (r.getDeclaringClass() != null ? r.getDeclaringClass().getCanonicalName() : " NOSRC")); - } - return ""; - } -} diff --git a/src/main/java/com/volmit/iris/core/report/Report.java b/src/main/java/com/volmit/iris/core/report/Report.java deleted file mode 100644 index 67f665fee..000000000 --- a/src/main/java/com/volmit/iris/core/report/Report.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.report; - -import lombok.Builder; -import lombok.Data; - -@Data -@Builder -public class Report { - @Builder.Default - private final ReportType type = ReportType.NOTICE; - @Builder.Default - private final String title = "Problem..."; - @Builder.Default - private final String message = "No Message"; - @Builder.Default - private final String suggestion = "No Suggestion"; - - public String toString() { - return type + ": " + title + ": " + message + ": Suggestion: " + suggestion; - } -} diff --git a/src/main/java/com/volmit/iris/core/report/ReportType.java b/src/main/java/com/volmit/iris/core/report/ReportType.java deleted file mode 100644 index 5976010a0..000000000 --- a/src/main/java/com/volmit/iris/core/report/ReportType.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.report; - -public enum ReportType { - ERROR, - SEVERE_WARNING, - WARNING, - NOTICE, -} diff --git a/src/main/java/com/volmit/iris/core/service/BoardSVC.java b/src/main/java/com/volmit/iris/core/service/BoardSVC.java deleted file mode 100644 index 66850f3e2..000000000 --- a/src/main/java/com/volmit/iris/core/service/BoardSVC.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.util.board.BoardManager; -import com.volmit.iris.util.board.BoardProvider; -import com.volmit.iris.util.board.BoardSettings; -import com.volmit.iris.util.board.ScoreDirection; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.scheduling.J; -import lombok.Data; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerJoinEvent; - -import java.util.List; - -public class BoardSVC implements IrisService, BoardProvider { - private final KMap boards = new KMap<>(); - private com.volmit.iris.util.board.BoardManager manager; - - @Override - public void onEnable() { - J.ar(this::tick, 20); - manager = new BoardManager(Iris.instance, BoardSettings.builder() - .boardProvider(this) - .scoreDirection(ScoreDirection.DOWN) - .build()); - } - - @Override - public void onDisable() { - manager.onDisable(); - boards.clear(); - } - - @EventHandler - public void on(PlayerChangedWorldEvent e) { - J.s(() -> updatePlayer(e.getPlayer())); - } - - @EventHandler - public void on(PlayerJoinEvent e) { - J.s(() -> updatePlayer(e.getPlayer())); - } - - public void updatePlayer(Player p) { - if(IrisToolbelt.isIrisStudioWorld(p.getWorld())) { - manager.remove(p); - manager.setup(p); - } else { - manager.remove(p); - boards.remove(p); - } - } - - @Override - public String getTitle(Player player) { - return C.GREEN + "Iris"; - } - - public void tick() { - if(!Iris.service(StudioSVC.class).isProjectOpen()) { - return; - } - - boards.forEach((k, v) -> v.update()); - } - - @Override - public List getLines(Player player) { - PlayerBoard pb = boards.computeIfAbsent(player, PlayerBoard::new); - synchronized(pb.lines) { - return pb.lines; - } - } - - @Data - public static class PlayerBoard { - private final Player player; - private final KList lines; - - public PlayerBoard(Player player) { - this.player = player; - this.lines = new KList<>(); - update(); - } - - public void update() { - synchronized(lines) { - lines.clear(); - - if(!IrisToolbelt.isIrisStudioWorld(player.getWorld())) { - return; - } - - Engine engine = IrisToolbelt.access(player.getWorld()).getEngine(); - int x = player.getLocation().getBlockX(); - int y = player.getLocation().getBlockY() - player.getWorld().getMinHeight(); - int z = player.getLocation().getBlockZ(); - - lines.add("&7&m "); - lines.add(C.GREEN + "Speed" + C.GRAY + ": " + Form.f(engine.getGeneratedPerSecond(), 0) + "/s " + Form.duration(1000D / engine.getGeneratedPerSecond(), 0)); - lines.add(C.AQUA + "Cache" + C.GRAY + ": " + Form.f(IrisData.cacheSize())); - lines.add(C.AQUA + "Mantle" + C.GRAY + ": " + engine.getMantle().getLoadedRegionCount()); - lines.add("&7&m "); - lines.add(C.AQUA + "Region" + C.GRAY + ": " + engine.getRegion(x, z).getName()); - lines.add(C.AQUA + "Biome" + C.GRAY + ": " + engine.getBiomeOrMantle(x, y, z).getName()); - lines.add(C.AQUA + "Height" + C.GRAY + ": " + Math.round(engine.getHeight(x, z) + player.getWorld().getMinHeight())); - lines.add(C.AQUA + "Slope" + C.GRAY + ": " + Form.f(engine.getComplex().getSlopeStream().get(x, z), 2)); - lines.add(C.AQUA + "BUD/s" + C.GRAY + ": " + Form.f(engine.getBlockUpdatesPerSecond())); - lines.add("&7&m "); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/core/service/CommandSVC.java b/src/main/java/com/volmit/iris/core/service/CommandSVC.java deleted file mode 100644 index 2ee2c3807..000000000 --- a/src/main/java/com/volmit/iris/core/service/CommandSVC.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.commands.CommandIris; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeSystem; -import com.volmit.iris.util.decree.virtual.VirtualDecreeCommand; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.server.ServerCommandEvent; - -import java.util.Locale; -import java.util.concurrent.CompletableFuture; - -public class CommandSVC implements IrisService, DecreeSystem { - private final KMap> futures = new KMap<>(); - private CompletableFuture consoleFuture = null; - private final transient AtomicCache commandCache = new AtomicCache<>(); - - @Override - public void onEnable() { - Iris.instance.getCommand("iris").setExecutor(this); - J.a(() -> getRoot().cacheAll()); - } - - @Override - public void onDisable() { - - } - - @EventHandler - public void on(PlayerCommandPreprocessEvent e) { - String msg = e.getMessage().startsWith("/") ? e.getMessage().substring(1) : e.getMessage(); - - if(msg.startsWith("irisdecree ")) { - String[] args = msg.split("\\Q \\E"); - CompletableFuture future = futures.get(args[1]); - - if(future != null) { - future.complete(args[2]); - e.setCancelled(true); - return; - } - } - - if((msg.startsWith("locate ") || msg.startsWith("locatebiome ")) && IrisToolbelt.isIrisWorld(e.getPlayer().getWorld())) { - new VolmitSender(e.getPlayer()).sendMessage(C.RED + "Locating biomes & objects is disabled in Iris Worlds. Use /iris studio goto "); - e.setCancelled(true); - } - } - - @EventHandler - public void on(ServerCommandEvent e) { - if(consoleFuture != null && !consoleFuture.isCancelled() && !consoleFuture.isDone()) { - if(!e.getCommand().contains(" ")) { - String pick = e.getCommand().trim().toLowerCase(Locale.ROOT); - consoleFuture.complete(pick); - e.setCancelled(true); - } - } - } - - @Override - public VirtualDecreeCommand getRoot() { - return commandCache.aquireNastyPrint(() -> VirtualDecreeCommand.createRoot(new CommandIris())); - } - - public void post(String password, CompletableFuture future) { - futures.put(password, future); - } - - public void postConsole(CompletableFuture future) { - consoleFuture = future; - } -} diff --git a/src/main/java/com/volmit/iris/core/service/ConversionSVC.java b/src/main/java/com/volmit/iris/core/service/ConversionSVC.java deleted file mode 100644 index 3186f12b7..000000000 --- a/src/main/java/com/volmit/iris/core/service/ConversionSVC.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.google.gson.Gson; -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.IrisDirection; -import com.volmit.iris.engine.object.IrisJigsawPiece; -import com.volmit.iris.engine.object.IrisJigsawPieceConnector; -import com.volmit.iris.engine.object.IrisJigsawPool; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.function.Consumer2; -import com.volmit.iris.util.io.Converter; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.nbt.io.NBTUtil; -import com.volmit.iris.util.nbt.io.NamedTag; -import com.volmit.iris.util.nbt.mca.NBTWorld; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.IntTag; -import com.volmit.iris.util.nbt.tag.ListTag; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.Jigsaw; - -import java.io.File; -import java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; - -public class ConversionSVC implements IrisService { - private KList converters; - private File folder; - - @Override - public void onEnable() { - folder = Iris.instance.getDataFolder("convert"); - converters = new KList<>(); - - J.s(() -> - J.attemptAsync(() -> - { - - }), 5); - } - - @Override - public void onDisable() { - - } - - private String toPoolName(String poolReference) { - return poolReference.split("\\Q:\\E")[1]; - } - - public void convertStructures(File in, File out, VolmitSender s) { - KMap pools = new KMap<>(); - KList roots = new KList<>(); - AtomicInteger total = new AtomicInteger(0); - AtomicInteger at = new AtomicInteger(0); - File destPools = new File(out.getAbsolutePath() + "/jigsaw-pools"); - destPools.mkdirs(); - findAllNBT(in, (folder, file) -> { - total.getAndIncrement(); - if(roots.addIfMissing(folder)) { - String b = in.toURI().relativize(folder.toURI()).getPath(); - if(b.startsWith("/")) { - b = b.substring(1); - } - - if(b.endsWith("/")) { - b = b.substring(0, b.length() - 1); - } - - pools.put(b, new IrisJigsawPool()); - } - }); - findAllNBT(in, (folder, file) -> { - at.getAndIncrement(); - String b = in.toURI().relativize(folder.toURI()).getPath(); - if(b.startsWith("/")) { - b = b.substring(1); - } - - if(b.endsWith("/")) { - b = b.substring(0, b.length() - 1); - } - IrisJigsawPool jpool = pools.get(b); - File destObjects = new File(out.getAbsolutePath() + "/objects/" + in.toURI().relativize(folder.toURI()).getPath()); - File destPieces = new File(out.getAbsolutePath() + "/jigsaw-pieces/" + in.toURI().relativize(folder.toURI()).getPath()); - destObjects.mkdirs(); - destPieces.mkdirs(); - - try { - NamedTag tag = NBTUtil.read(file); - CompoundTag compound = (CompoundTag) tag.getTag(); - - if(compound.containsKey("blocks") && compound.containsKey("palette") && compound.containsKey("size")) { - String id = in.toURI().relativize(folder.toURI()).getPath() + file.getName().split("\\Q.\\E")[0]; - @SuppressWarnings("unchecked") ListTag size = (ListTag) compound.getListTag("size"); - int w = size.get(0).asInt(); - int h = size.get(1).asInt(); - int d = size.get(2).asInt(); - KList palette = new KList<>(); - @SuppressWarnings("unchecked") ListTag paletteList = (ListTag) compound.getListTag("palette"); - for(int i = 0; i < paletteList.size(); i++) { - CompoundTag cp = paletteList.get(i); - palette.add(NBTWorld.getBlockData(cp)); - } - IrisJigsawPiece piece = new IrisJigsawPiece(); - IrisObject object = new IrisObject(w, h, d); - @SuppressWarnings("unchecked") ListTag blockList = (ListTag) compound.getListTag("blocks"); - for(int i = 0; i < blockList.size(); i++) { - CompoundTag cp = blockList.get(i); - @SuppressWarnings("unchecked") ListTag pos = (ListTag) cp.getListTag("pos"); - int x = pos.get(0).asInt(); - int y = pos.get(1).asInt(); - int z = pos.get(2).asInt(); - BlockData bd = palette.get(cp.getInt("state")).clone(); - - if(bd.getMaterial().equals(Material.JIGSAW) && cp.containsKey("nbt")) { - piece.setObject(in.toURI().relativize(folder.toURI()).getPath() + file.getName().split("\\Q.\\E")[0]); - IrisPosition spos = new IrisPosition(object.getSigned(x, y, z)); - CompoundTag nbt = cp.getCompoundTag("nbt"); - CompoundTag finalState = new CompoundTag(); - finalState.putString("Name", nbt.getString("final_state")); - BlockData jd = bd.clone(); - bd = NBTWorld.getBlockData(finalState); - String joint = nbt.getString("joint"); - String pool = nbt.getString("pool"); - String poolId = toPoolName(pool); - String name = nbt.getString("name"); - String target = nbt.getString("target"); - pools.computeIfAbsent(poolId, (k) -> new IrisJigsawPool()); - IrisJigsawPieceConnector connector = new IrisJigsawPieceConnector(); - connector.setName(name); - connector.setTargetName(target); - connector.setRotateConnector(false); - connector.setPosition(spos); - connector.getPools().add(poolId); - connector.setDirection(IrisDirection.getDirection(((Jigsaw) jd).getOrientation())); - - if(target.equals("minecraft:building_entrance")) { - connector.setInnerConnector(true); - } - - piece.getConnectors().add(connector); - } - - if(!bd.getMaterial().equals(Material.STRUCTURE_VOID) && !bd.getMaterial().equals(Material.AIR)) { - object.setUnsigned(x, y, z, bd); - } - } - - jpool.getPieces().addIfMissing(id); - object.write(new File(destObjects, file.getName().split("\\Q.\\E")[0] + ".iob")); - IO.writeAll(new File(destPieces, file.getName().split("\\Q.\\E")[0] + ".json"), new JSONObject(new Gson().toJson(piece)).toString(4)); - Iris.info("[Jigsaw]: (" + Form.pc((double) at.get() / (double) total.get(), 0) + ") Exported Piece: " + id); - } - } catch(Throwable e) { - e.printStackTrace(); - Iris.reportError(e); - } - }); - - for(String i : pools.k()) { - try { - IO.writeAll(new File(destPools, i + ".json"), new JSONObject(new Gson().toJson(pools.get(i))).toString(4)); - } catch(IOException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - - Iris.info("Done! Exported " + Form.f((total.get() * 2) + pools.size()) + " Files!"); - } - - public void findAllNBT(File path, Consumer2 inFile) { - if(path == null) { - return; - } - - if(path.isFile() && path.getName().endsWith(".nbt")) { - inFile.accept(path.getParentFile(), path); - return; - } - - for(File i : path.listFiles()) { - if(i.isDirectory()) { - findAllNBT(i, inFile); - } else if(i.isFile() && i.getName().endsWith(".nbt")) { - inFile.accept(path, i); - } - } - } - - public void check(VolmitSender s) { - int m = 0; - Iris.instance.getDataFolder("convert"); - - for(File i : folder.listFiles()) { - for(Converter j : converters) { - if(i.getName().endsWith("." + j.getInExtension())) { - File out = new File(folder, i.getName().replaceAll("\\Q." + j.getInExtension() + "\\E", "." + j.getOutExtension())); - m++; - j.convert(i, out); - s.sendMessage("Converted " + i.getName() + " -> " + out.getName()); - } - } - - if(i.isDirectory() && i.getName().equals("structures")) { - File f = new File(folder, "jigsaw"); - - if(!f.exists()) { - s.sendMessage("Converting NBT Structures into Iris Jigsaw Structures..."); - f.mkdirs(); - J.a(() -> convertStructures(i, f, s)); - } - } - } - - s.sendMessage("Converted " + m + " File" + (m == 1 ? "" : "s")); - } -} diff --git a/src/main/java/com/volmit/iris/core/service/DolphinSVC.java b/src/main/java/com/volmit/iris/core/service/DolphinSVC.java deleted file mode 100644 index 093e410b2..000000000 --- a/src/main/java/com/volmit/iris/core/service/DolphinSVC.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.util.plugin.IrisService; -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerInteractEntityEvent; - -public class DolphinSVC implements IrisService { - @Override - public void onEnable() { - - } - - @Override - public void onDisable() { - - } - - /** - * Prevents dolphins from being fed, to locate a treasure map. - * Note: This results in odd dolphin behaviour, but it's the best we can do. - */ - @EventHandler - public void on(PlayerInteractEntityEvent event) { - if(!IrisToolbelt.isIrisWorld(event.getPlayer().getWorld())) { - return; - } - - Material hand = event.getPlayer().getInventory().getItem(event.getHand()).getType(); - if(event.getRightClicked().getType().equals(EntityType.DOLPHIN) && (hand.equals(Material.TROPICAL_FISH) || hand.equals(Material.PUFFERFISH) || hand.equals(Material.COD) || hand.equals(Material.SALMON))) { - event.setCancelled(true); - } - } -} diff --git a/src/main/java/com/volmit/iris/core/service/EditSVC.java b/src/main/java/com/volmit/iris/core/service/EditSVC.java deleted file mode 100644 index 886805328..000000000 --- a/src/main/java/com/volmit/iris/core/service/EditSVC.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.edit.BlockEditor; -import com.volmit.iris.core.edit.BukkitBlockEditor; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.plugin.IrisService; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.event.EventHandler; -import org.bukkit.event.world.WorldUnloadEvent; - -public class EditSVC implements IrisService { - private KMap editors; - - @Override - public void onEnable() { - this.editors = new KMap<>(); - Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, this::update, 1000, 1000); - } - - @Override - public void onDisable() { - flushNow(); - } - - public BlockData get(World world, int x, int y, int z) { - return open(world).get(x, y, z); - } - - public void set(World world, int x, int y, int z, BlockData d) { - open(world).set(x, y, z, d); - } - - public void setBiome(World world, int x, int y, int z, Biome d) { - open(world).setBiome(x, y, z, d); - } - - public void setBiome(World world, int x, int z, Biome d) { - open(world).setBiome(x, z, d); - } - - public Biome getBiome(World world, int x, int y, int z) { - return open(world).getBiome(x, y, z); - } - - public Biome getBiome(World world, int x, int z) { - return open(world).getBiome(x, z); - } - - @EventHandler - public void on(WorldUnloadEvent e) { - if(editors.containsKey(e.getWorld())) { - editors.remove(e.getWorld()).close(); - } - } - - public void update() { - for(World i : editors.k()) { - if(M.ms() - editors.get(i).last() > 1000) { - editors.remove(i).close(); - } - } - } - - public void flushNow() { - for(World i : editors.k()) { - editors.remove(i).close(); - } - } - - public BlockEditor open(World world) { - if(editors.containsKey(world)) { - return editors.get(world); - } - - BlockEditor e = new BukkitBlockEditor(world); - editors.put(world, e); - - return e; - } - -} diff --git a/src/main/java/com/volmit/iris/core/service/ExternalDataSVC.java b/src/main/java/com/volmit/iris/core/service/ExternalDataSVC.java deleted file mode 100644 index 6c96c3871..000000000 --- a/src/main/java/com/volmit/iris/core/service/ExternalDataSVC.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.link.ExternalDataProvider; -import com.volmit.iris.core.link.ItemAdderDataProvider; -import com.volmit.iris.core.link.OraxenDataProvider; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.plugin.IrisService; -import lombok.Data; -import org.bukkit.NamespacedKey; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; - -import java.util.MissingResourceException; -import java.util.Optional; - -@Data -public class ExternalDataSVC implements IrisService { - - private KList providers = new KList<>(); - - @Override - public void onEnable() { - addProvider(new OraxenDataProvider(), new ItemAdderDataProvider()); - } - - @Override - public void onDisable() { } - - public void addProvider(ExternalDataProvider... provider) { - for(ExternalDataProvider p : provider) { - if(p.getPlugin() != null) { - providers.add(p); - p.init(); - } - } - } - - public Optional getBlockData(NamespacedKey key) { - Optional provider = providers.stream().filter(p -> p.isPresent() && p.isValidProvider(key)).findFirst(); - if(provider.isEmpty()) - return Optional.empty(); - try { - return Optional.of(provider.get().getBlockData(key)); - } catch(MissingResourceException e) { - Iris.error(e.getMessage() + " - [" + e.getClassName() + ":" + e.getKey() + "]"); - return Optional.empty(); - } - } - - public Optional getItemStack(NamespacedKey key) { - Optional provider = providers.stream().filter(p -> p.isPresent() && p.isValidProvider(key)).findFirst(); - if(provider.isEmpty()) - return Optional.empty(); - try { - return Optional.of(provider.get().getItemStack(key)); - } catch(MissingResourceException e) { - Iris.error(e.getMessage() + " - [" + e.getClassName() + ":" + e.getKey() + "]"); - return Optional.empty(); - } - } - - public NamespacedKey[] getAllIdentifiers() { - KList names = new KList<>(); - providers.stream().filter(ExternalDataProvider::isPresent).forEach(p -> names.add(p.getBlockTypes())); - return names.toArray(new NamespacedKey[0]); - } -} diff --git a/src/main/java/com/volmit/iris/core/service/LogFilterSVC.java b/src/main/java/com/volmit/iris/core/service/LogFilterSVC.java deleted file mode 100644 index 7f86621c3..000000000 --- a/src/main/java/com/volmit/iris/core/service/LogFilterSVC.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.volmit.iris.core.service; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.plugin.IrisService; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.core.Filter; -import org.apache.logging.log4j.core.LogEvent; -import org.apache.logging.log4j.core.Logger; -import org.apache.logging.log4j.message.Message; - -public class LogFilterSVC implements IrisService, Filter { - - private static final String HEIGHTMAP_MISMATCH = "Ignoring heightmap data for chunk"; - private static final String RAID_PERSISTENCE = "Could not save data net.minecraft.world.entity.raid.PersistentRaid"; - private static final String DUPLICATE_ENTITY_UUID = "UUID of added entity already exists"; - - private static final KList FILTERS = new KList<>(); - - public void onEnable() { - FILTERS.add(HEIGHTMAP_MISMATCH, RAID_PERSISTENCE, DUPLICATE_ENTITY_UUID); - ((Logger)LogManager.getRootLogger()).addFilter(this); - } - - public void initialize() { } - public void start() { } - public void stop() { } - public void onDisable() { } - public boolean isStarted() { return true; } - public boolean isStopped() { return false; } - - public State getState() { - try { return State.STARTED; } - catch (Exception var2) { return null; } - } - - public Filter.Result getOnMatch() { return Result.NEUTRAL; } - public Filter.Result getOnMismatch() { return Result.NEUTRAL; } - - public Result filter(LogEvent event) { return check(event.getMessage().getFormattedMessage()); } - public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) { return check(msg.toString()); } - public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) { return check(msg.getFormattedMessage()); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object... params) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1, Object p2) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8) { return check(message); } - public Result filter(Logger logger, Level level, Marker marker, String message, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7, Object p8, Object p9) { return check(message); } - - private Result check(String string) { - if(FILTERS.stream().anyMatch(string::contains)) - return Result.DENY; - return Result.NEUTRAL; - } -} diff --git a/src/main/java/com/volmit/iris/core/service/ObjectSVC.java b/src/main/java/com/volmit/iris/core/service/ObjectSVC.java deleted file mode 100644 index 9a504804a..000000000 --- a/src/main/java/com/volmit/iris/core/service/ObjectSVC.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.scheduling.J; -import lombok.Getter; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; - -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.Iterator; -import java.util.Map; - -public class ObjectSVC implements IrisService { - - @Getter - private final Deque> undos = new ArrayDeque<>(); - - - @Override - public void onEnable() { - - } - - @Override - public void onDisable() { - - } - - public void addChanges(Map oldBlocks) { - undos.add(oldBlocks); - } - - public void revertChanges(int amount) { - loopChange(amount); - } - - private void loopChange(int amount) { - if(undos.size() > 0) { - revert(undos.pollLast()); - if(amount > 1) { - J.s(() -> loopChange(amount - 1), 2); - } - } - } - - /** - * Reverts all the block changes provided, 200 blocks per tick - * - * @param blocks - * The blocks to remove - */ - private void revert(Map blocks) { - int amount = 0; - Iterator> it = blocks.entrySet().iterator(); - while(it.hasNext()) { - Map.Entry entry = it.next(); - BlockData data = entry.getValue(); - entry.getKey().setBlockData(data, false); - it.remove(); - - amount++; - - if(amount > 200) { - J.s(() -> revert(blocks), 1); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/core/service/PreservationSVC.java b/src/main/java/com/volmit/iris/core/service/PreservationSVC.java deleted file mode 100644 index 2fac95881..000000000 --- a/src/main/java/com/volmit/iris/core/service/PreservationSVC.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.MeteredCache; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.data.KCache; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.scheduling.Looper; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutorService; -import java.util.stream.Collectors; - -public class PreservationSVC implements IrisService { - private final List threads = new CopyOnWriteArrayList<>(); - private final List services = new CopyOnWriteArrayList<>(); - private Looper dereferencer; - private final List caches = new CopyOnWriteArrayList<>(); - - public void register(Thread t) { - threads.add(t); - } - - public void register(MultiBurst burst) { - - } - - public void register(ExecutorService service) { - services.add(service); - } - - public void printCaches() { - long s = caches.stream().filter(i -> !i.isClosed()).mapToLong(MeteredCache::getSize).sum(); - long m = caches.stream().filter(i -> !i.isClosed()).mapToLong(MeteredCache::getMaxSize).sum(); - double p = 0; - double mf = 0; - - for(MeteredCache i : caches) { - if(i.isClosed()) { - continue; - } - - mf++; - p += i.getUsage(); - } - - mf = mf == 0 ? 1 : mf; - - Iris.info("Cached " + Form.f(s) + " / " + Form.f(m) + " (" + Form.pc(p / mf) + ") from " + caches.size() + " Caches"); - } - - public void dereference() { - IrisContext.dereference(); - IrisData.dereference(); - threads.removeIf((i) -> !i.isAlive()); - services.removeIf(ExecutorService::isShutdown); - updateCaches(); - } - - @Override - public void onEnable() { - /* - * Dereferences copies of Engine instances that are closed to prevent memory from - * hanging around and keeping copies of complex, caches and other dead objects. - */ - dereferencer = new Looper() { - @Override - protected long loop() { - dereference(); - return 60000; - } - }; - } - - @Override - public void onDisable() { - dereferencer.interrupt(); - dereference(); - - postShutdown(() -> { - for(Thread i : threads) { - if(i.isAlive()) { - try { - i.interrupt(); - Iris.info("Shutdown Thread " + i.getName()); - } catch(Throwable e) { - Iris.reportError(e); - } - } - } - - for(ExecutorService i : services) { - try { - i.shutdownNow(); - Iris.info("Shutdown Executor Service " + i); - } catch(Throwable e) { - Iris.reportError(e); - } - } - }); - } - - public void updateCaches() { - caches.removeIf(MeteredCache::isClosed); - } - - public void registerCache(MeteredCache cache) { - caches.add(cache); - } - - public List> caches() { - return caches.stream().map(MeteredCache::getRawCache).collect(Collectors.toList()); - } -} diff --git a/src/main/java/com/volmit/iris/core/service/StudioSVC.java b/src/main/java/com/volmit/iris/core/service/StudioSVC.java deleted file mode 100644 index d9ae1a9c6..000000000 --- a/src/main/java/com/volmit/iris/core/service/StudioSVC.java +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.ServerConfigurator; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.pack.IrisPack; -import com.volmit.iris.core.project.IrisProject; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.exceptions.IrisException; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONException; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.zeroturnaround.zip.ZipUtil; -import org.zeroturnaround.zip.commons.FileUtils; - -import java.io.File; -import java.io.IOException; -import java.util.UUID; -import java.util.function.Consumer; - -public class StudioSVC implements IrisService { - public static final String LISTING = "https://raw.githubusercontent.com/IrisDimensions/_listing/main/listing-v2.json"; - public static final String WORKSPACE_NAME = "packs"; - private static final AtomicCache counter = new AtomicCache<>(); - private final KMap cacheListing = null; - private IrisProject activeProject; - - @Override - public void onEnable() { - J.a(() -> { - String pack = IrisSettings.get().getGenerator().getDefaultWorldType(); - File f = IrisPack.packsPack(pack); - - if(!f.exists()) { - Iris.info("Downloading Default Pack " + pack); - downloadSearch(Iris.getSender(), pack, false); - } - }); - } - - @Override - public void onDisable() { - Iris.debug("Studio Mode Active: Closing Projects"); - - for(World i : Bukkit.getWorlds()) { - if(IrisToolbelt.isIrisWorld(i)) { - if(IrisToolbelt.isStudio(i)) { - IrisToolbelt.evacuate(i); - IrisToolbelt.access(i).close(); - } - } - } - } - - public IrisDimension installIntoWorld(VolmitSender sender, String type, File folder) { - sender.sendMessage("Looking for Package: " + type); - File iris = new File(folder, "iris"); - File irispack = new File(folder, "iris/pack"); - IrisDimension dim = IrisData.loadAnyDimension(type); - - if(dim == null) { - for(File i : getWorkspaceFolder().listFiles()) { - if(i.isFile() && i.getName().equals(type + ".iris")) { - sender.sendMessage("Found " + type + ".iris in " + WORKSPACE_NAME + " folder"); - ZipUtil.unpack(i, irispack); - break; - } - } - } else { - sender.sendMessage("Found " + type + " dimension in " + WORKSPACE_NAME + " folder. Repackaging"); - File f = new IrisProject(new File(getWorkspaceFolder(), type)).getPath(); - - try { - FileUtils.copyDirectory(f, irispack); - } catch(IOException e) { - Iris.reportError(e); - } - } - - File dimf = new File(irispack, "dimensions/" + type + ".json"); - - if(!dimf.exists() || !dimf.isFile()) { - downloadSearch(sender, type, false); - File downloaded = getWorkspaceFolder(type); - - for(File i : downloaded.listFiles()) { - if(i.isFile()) { - try { - FileUtils.copyFile(i, new File(irispack, i.getName())); - } catch(IOException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } else { - try { - FileUtils.copyDirectory(i, new File(irispack, i.getName())); - } catch(IOException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - } - - IO.delete(downloaded); - } - - if(!dimf.exists() || !dimf.isFile()) { - sender.sendMessage("Can't find the " + dimf.getName() + " in the dimensions folder of this pack! Failed!"); - return null; - } - - IrisData dm = IrisData.get(irispack); - dim = dm.getDimensionLoader().load(type); - - if(dim == null) { - sender.sendMessage("Can't load the dimension! Failed!"); - return null; - } - - sender.sendMessage(folder.getName() + " type installed. "); - return dim; - } - - public void downloadSearch(VolmitSender sender, String key, boolean trim) { - downloadSearch(sender, key, trim, false); - } - - public void downloadSearch(VolmitSender sender, String key, boolean trim, boolean forceOverwrite) { - String url = "?"; - - try { - url = getListing(false).get(key); - - if(url == null) { - Iris.warn("ITS ULL for " + key); - } - - url = url == null ? key : url; - Iris.info("Assuming URL " + url); - String branch = "master"; - String[] nodes = url.split("\\Q/\\E"); - String repo = nodes.length == 1 ? "IrisDimensions/" + nodes[0] : nodes[0] + "/" + nodes[1]; - branch = nodes.length > 2 ? nodes[2] : branch; - download(sender, repo, branch, trim, forceOverwrite); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - sender.sendMessage("Failed to download '" + key + "' from " + url + "."); - } - } - - public void download(VolmitSender sender, String repo, String branch, boolean trim) throws JsonSyntaxException, IOException { - download(sender, repo, branch, trim, false); - } - - public void download(VolmitSender sender, String repo, String branch, boolean trim, boolean forceOverwrite) throws JsonSyntaxException, IOException { - String url = "https://codeload.github.com/" + repo + "/zip/refs/heads/" + branch; - sender.sendMessage("Downloading " + url + " "); //The extra space stops a bug in adventure API from repeating the last letter of the URL - File zip = Iris.getNonCachedFile("pack-" + trim + "-" + repo, url); - File temp = Iris.getTemp(); - File work = new File(temp, "dl-" + UUID.randomUUID()); - File packs = getWorkspaceFolder(); - - if(zip == null || !zip.exists()) { - sender.sendMessage("Failed to find pack at " + url); - sender.sendMessage("Make sure you specified the correct repo and branch!"); - sender.sendMessage("For example: /iris download IrisDimensions/overworld branch=master"); - return; - } - sender.sendMessage("Unpacking " + repo); - try { - ZipUtil.unpack(zip, work); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - sender.sendMessage( - """ - Issue when unpacking. Please check/do the following: - 1. Do you have a functioning internet connection? - 2. Did the download corrupt? - 3. Try deleting the */plugins/iris/packs folder and re-download. - 4. Download the pack from the GitHub repo: https://github.com/IrisDimensions/overworld - 5. Contact support (if all other options do not help)""" - ); - } - File dir = null; - File[] zipFiles = work.listFiles(); - - if(zipFiles == null) { - sender.sendMessage("No files were extracted from the zip file."); - return; - } - - try { - dir = zipFiles.length == 1 && zipFiles[0].isDirectory() ? zipFiles[0] : null; - } catch(NullPointerException e) { - Iris.reportError(e); - sender.sendMessage("Error when finding home directory. Are there any non-text characters in the file name?"); - return; - } - - if(dir == null) { - sender.sendMessage("Invalid Format. Missing root folder or too many folders!"); - return; - } - - File dimensions = new File(dir, "dimensions"); - - if(!(dimensions.exists() && dimensions.isDirectory())) { - sender.sendMessage("Invalid Format. Missing dimensions folder"); - return; - } - - if(dimensions.listFiles() == null) { - sender.sendMessage("No dimension file found in the extracted zip file."); - sender.sendMessage("Check it is there on GitHub and report this to staff!"); - } else if(dimensions.listFiles().length != 1) { - sender.sendMessage("Dimensions folder must have 1 file in it"); - return; - } - - File dim = dimensions.listFiles()[0]; - - if(!dim.isFile()) { - sender.sendMessage("Invalid dimension (folder) in dimensions folder"); - return; - } - - String key = dim.getName().split("\\Q.\\E")[0]; - IrisDimension d = new Gson().fromJson(IO.readAll(dim), IrisDimension.class); - sender.sendMessage("Importing " + d.getName() + " (" + key + ")"); - File packEntry = new File(packs, key); - - if(forceOverwrite) { - IO.delete(packEntry); - } - - if(IrisData.loadAnyDimension(key) != null) { - sender.sendMessage("Another dimension in the packs folder is already using the key " + key + " IMPORT FAILED!"); - return; - } - - if(packEntry.exists() && packEntry.listFiles().length > 0) { - sender.sendMessage("Another pack is using the key " + key + ". IMPORT FAILED!"); - return; - } - - FileUtils.copyDirectory(dir, packEntry); - - if(trim) { - sender.sendMessage("Trimming " + key); - File cp = compilePackage(sender, key, false, false); - IO.delete(packEntry); - packEntry.mkdirs(); - ZipUtil.unpack(cp, packEntry); - } - - sender.sendMessage("Successfully Aquired " + d.getName()); - ServerConfigurator.installDataPacks(true); - } - - public KMap getListing(boolean cached) { - JSONObject a; - - if(cached) { - a = new JSONObject(Iris.getCached("cachedlisting", LISTING)); - } else { - a = new JSONObject(Iris.getNonCached(true + "listing", LISTING)); - } - - KMap l = new KMap<>(); - - for(String i : a.keySet()) { - if(a.get(i) instanceof String) - l.put(i, a.getString(i)); - } - - // TEMP FIX - l.put("IrisDimensions/overworld/master", "IrisDimensions/overworld/stable"); - l.put("overworld", "IrisDimensions/overworld/stable"); - return l; - } - - public boolean isProjectOpen() { - return activeProject != null && activeProject.isOpen(); - } - - public void open(VolmitSender sender, String dimm) { - open(sender, 1337, dimm); - } - - public void open(VolmitSender sender, long seed, String dimm) { - try { - open(sender, seed, dimm, (w) -> { - }); - } catch(Exception e) { - Iris.reportError(e); - sender.sendMessage("Error when creating studio world:"); - e.printStackTrace(); - } - } - - public void open(VolmitSender sender, long seed, String dimm, Consumer onDone) throws IrisException { - if(isProjectOpen()) { - close(); - } - - IrisProject project = new IrisProject(new File(getWorkspaceFolder(), dimm)); - activeProject = project; - project.open(sender, seed, onDone); - } - - public void openVSCode(VolmitSender sender, String dim) { - new IrisProject(new File(getWorkspaceFolder(), dim)).openVSCode(sender); - } - - public File getWorkspaceFolder(String... sub) { - return Iris.instance.getDataFolderList(WORKSPACE_NAME, sub); - } - - public File getWorkspaceFile(String... sub) { - return Iris.instance.getDataFileList(WORKSPACE_NAME, sub); - } - - public void close() { - if(isProjectOpen()) { - Iris.debug("Closing Active Project"); - activeProject.close(); - activeProject = null; - } - } - - public File compilePackage(VolmitSender sender, String d, boolean obfuscate, boolean minify) { - return new IrisProject(new File(getWorkspaceFolder(), d)).compilePackage(sender, obfuscate, minify); - } - - public void createFrom(String existingPack, String newName) { - File importPack = getWorkspaceFolder(existingPack); - File newPack = getWorkspaceFolder(newName); - - if(importPack.listFiles().length == 0) { - Iris.warn("Couldn't find the pack to create a new dimension from."); - return; - } - - try { - FileUtils.copyDirectory(importPack, newPack, pathname -> !pathname.getAbsolutePath().contains(".git"), false); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - - new File(importPack, existingPack + ".code-workspace").delete(); - File dimFile = new File(importPack, "dimensions/" + existingPack + ".json"); - File newDimFile = new File(newPack, "dimensions/" + newName + ".json"); - - try { - FileUtils.copyFile(dimFile, newDimFile); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - - new File(newPack, "dimensions/" + existingPack + ".json").delete(); - - try { - JSONObject json = new JSONObject(IO.readAll(newDimFile)); - - if(json.has("name")) { - json.put("name", Form.capitalizeWords(newName.replaceAll("\\Q-\\E", " "))); - IO.writeAll(newDimFile, json.toString(4)); - } - } catch(JSONException | IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - - try { - IrisProject p = new IrisProject(getWorkspaceFolder(newName)); - JSONObject ws = p.createCodeWorkspaceConfig(); - IO.writeAll(getWorkspaceFile(newName, newName + ".code-workspace"), ws.toString(0)); - } catch(JSONException | IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - public void create(VolmitSender sender, String s, String downloadable) { - boolean shouldDelete = false; - File importPack = getWorkspaceFolder(downloadable); - - if(importPack.listFiles().length == 0) { - downloadSearch(sender, downloadable, false); - - if(importPack.listFiles().length > 0) { - shouldDelete = true; - } - } - - if(importPack.listFiles().length == 0) { - sender.sendMessage("Couldn't find the pack to create a new dimension from."); - return; - } - - File importDimensionFile = new File(importPack, "dimensions/" + downloadable + ".json"); - - if(!importDimensionFile.exists()) { - sender.sendMessage("Missing Imported Dimension File"); - return; - } - - sender.sendMessage("Importing " + downloadable + " into new Project " + s); - createFrom(downloadable, s); - if(shouldDelete) { - importPack.delete(); - } - open(sender, s); - } - - public void create(VolmitSender sender, String s) { - create(sender, s, "example"); - } - - public IrisProject getActiveProject() { - return activeProject; - } - - public void updateWorkspace() { - if(isProjectOpen()) { - activeProject.updateWorkspace(); - } - } -} diff --git a/src/main/java/com/volmit/iris/core/service/TreeSVC.java b/src/main/java/com/volmit/iris/core/service/TreeSVC.java deleted file mode 100644 index fb9584e52..000000000 --- a/src/main/java/com/volmit/iris/core/service/TreeSVC.java +++ /dev/null @@ -1,377 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IObjectPlacer; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.engine.object.IrisTreeModes; -import com.volmit.iris.engine.object.IrisTreeSize; -import com.volmit.iris.engine.object.TileData; -import com.volmit.iris.engine.platform.PlatformChunkGenerator; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.Cuboid; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Bukkit; -import org.bukkit.HeightMap; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.TreeType; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.Sapling; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.world.StructureGrowEvent; - -import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; - -public class TreeSVC implements IrisService { - private boolean block = false; - - @Override - public void onEnable() { - - } - - @Override - public void onDisable() { - - } - - /** - * This function does the following - *
1. Is the sapling growing in an Iris world? No -> exit
- *
2. Is the Iris world accessible? No -> exit
- *
3. Is the sapling overwriting setting on in that dimension? No -> exit
- *
4. Check biome, region and dimension for overrides for that sapling type -> Found -> use
- *
5. Exit if none are found, cancel event if one or more are.
- * - * @param event - * Checks the given event for sapling overrides - */ - @EventHandler(priority = EventPriority.HIGHEST) - public void on(StructureGrowEvent event) { - if(block || event.isCancelled()) { - return; - } - Iris.debug(this.getClass().getName() + " received a structure grow event"); - - if(!IrisToolbelt.isIrisWorld(event.getWorld())) { - Iris.debug(this.getClass().getName() + " passed grow event off to vanilla since not an Iris world"); - return; - } - - PlatformChunkGenerator worldAccess = IrisToolbelt.access(event.getWorld()); - if(worldAccess == null) { - Iris.debug(this.getClass().getName() + " passed it off to vanilla because could not get IrisAccess for this world"); - Iris.reportError(new NullPointerException(event.getWorld().getName() + " could not be accessed despite being an Iris world")); - return; - } - - Engine engine = worldAccess.getEngine(); - - if(engine == null) { - Iris.debug(this.getClass().getName() + " passed it off to vanilla because could not get Engine for this world"); - Iris.reportError(new NullPointerException(event.getWorld().getName() + " could not be accessed despite being an Iris world")); - return; - } - - IrisDimension dimension = engine.getDimension(); - - if(dimension == null) { - Iris.debug(this.getClass().getName() + " passed it off to vanilla because could not get Dimension for this world"); - Iris.reportError(new NullPointerException(event.getWorld().getName() + " could not be accessed despite being an Iris world")); - return; - } - - if(!dimension.getTreeSettings().isEnabled()) { - Iris.debug(this.getClass().getName() + " cancelled because tree overrides are disabled"); - return; - } - - BlockData first = event.getLocation().getBlock().getBlockData().clone(); - Cuboid saplingPlane = getSaplings(event.getLocation(), blockData -> blockData instanceof Sapling && blockData.getMaterial().equals(first.getMaterial()), event.getWorld()); - - Iris.debug("Sapling grew @ " + event.getLocation() + " for " + event.getSpecies().name() + " usedBoneMeal is " + event.isFromBonemeal()); - Iris.debug("Sapling plane is: " + saplingPlane.getSizeX() + " by " + saplingPlane.getSizeZ()); - IrisObjectPlacement placement = getObjectPlacement(worldAccess, event.getLocation(), event.getSpecies(), new IrisTreeSize(1, 1)); - - if(placement == null) { - Iris.debug(this.getClass().getName() + " had options but did not manage to find objectPlacements for them"); - return; - } - - saplingPlane.forEach(block -> block.setType(Material.AIR)); - IrisObject object = worldAccess.getData().getObjectLoader().load(placement.getPlace().getRandom(RNG.r)); - List blockStateList = new KList<>(); - KMap dataCache = new KMap<>(); - // TODO: REAL CLASSES!!!! - - IObjectPlacer placer = new IObjectPlacer() { - - @Override - public int getHighest(int x, int z, IrisData data) { - return event.getWorld().getHighestBlockYAt(x, z); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return event.getWorld().getHighestBlockYAt(x, z, ignoreFluid ? HeightMap.OCEAN_FLOOR : HeightMap.WORLD_SURFACE); - } - - @Override - public void set(int x, int y, int z, BlockData d) { - Block b = event.getWorld().getBlockAt(x, y, z); - BlockState state = b.getState(); - state.setBlockData(d); - blockStateList.add(b.getState()); - dataCache.put(new Location(event.getWorld(), x, y, z), d); - } - - @Override - public BlockData get(int x, int y, int z) { - return event.getWorld().getBlockAt(x, y, z).getBlockData(); - } - - @Override - public boolean isPreventingDecay() { - return true; - } - - @Override - public boolean isCarved(int x, int y, int z) { - return false; - } - - @Override - public boolean isSolid(int x, int y, int z) { - return get(x, y, z).getMaterial().isSolid(); - } - - @Override - public boolean isUnderwater(int x, int z) { - return false; - } - - @Override - public int getFluidHeight() { - return worldAccess.getEngine().getDimension().getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return false; - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - - } - - @Override - public Engine getEngine() { - return engine; - } - }; - - object.place( - saplingPlane.getCenter().getBlockX(), - (saplingPlane.getCenter().getBlockY() + object.getH() / 2), - saplingPlane.getCenter().getBlockZ(), - placer, - placement, - RNG.r, - Objects.requireNonNull(worldAccess).getData() - ); - - event.setCancelled(true); - - J.s(() -> { - - StructureGrowEvent iGrow = new StructureGrowEvent(event.getLocation(), event.getSpecies(), event.isFromBonemeal(), event.getPlayer(), blockStateList); - block = true; - Bukkit.getServer().getPluginManager().callEvent(iGrow); - block = false; - - if(!iGrow.isCancelled()) { - for(BlockState block : iGrow.getBlocks()) { - Location l = block.getLocation(); - - if(dataCache.containsKey(l)) { - l.getBlock().setBlockData(dataCache.get(l), false); - } - } - } - }); - } - - /** - * Finds a single object placement (which may contain more than one object) for the requirements species, location & - * size - * - * @param worldAccess - * The world to access (check for biome, region, dimension, etc) - * @param location - * The location of the growth event (For biome/region finding) - * @param type - * The bukkit TreeType to match - * @param size - * The size of the sapling area - * @return An object placement which contains the matched tree, or null if none were found / it's disabled. - */ - private IrisObjectPlacement getObjectPlacement(PlatformChunkGenerator worldAccess, Location location, TreeType type, IrisTreeSize size) { - - KList placements = new KList<>(); - boolean isUseAll = worldAccess.getEngine().getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL); - - // Retrieve objectPlacements of type `species` from biome - IrisBiome biome = worldAccess.getEngine().getBiome(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - placements.addAll(matchObjectPlacements(biome.getObjects(), size, type)); - - // Add more or find any in the region - if(isUseAll || placements.isEmpty()) { - IrisRegion region = worldAccess.getEngine().getRegion(location.getBlockX(), location.getBlockZ()); - placements.addAll(matchObjectPlacements(region.getObjects(), size, type)); - } - - // Check if no matches were found, return a random one if they are - return placements.isNotEmpty() ? placements.getRandom() : null; - } - - /** - * Filters out mismatches and returns matches - * - * @param objects - * The object placements to check - * @param size - * The size of the sapling area to filter with - * @param type - * The type of the tree to filter with - * @return A list of objectPlacements that matched. May be empty. - */ - private KList matchObjectPlacements(KList objects, IrisTreeSize size, TreeType type) { - - KList p = new KList<>(); - - for(IrisObjectPlacement i : objects) { - if(i.matches(size, type)) { - p.add(i); - } - } - - return p; - } - - /** - * Get the Cuboid of sapling sizes at a location & blockData predicate - * - * @param at - * this location - * @param valid - * with this blockData predicate - * @param world - * the world to check in - * @return A cuboid containing only saplings - */ - public Cuboid getSaplings(Location at, Predicate valid, World world) { - KList blockPositions = new KList<>(); - grow(at.getWorld(), new BlockPosition(at.getBlockX(), at.getBlockY(), at.getBlockZ()), valid, blockPositions); - BlockPosition a = new BlockPosition(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); - BlockPosition b = new BlockPosition(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - - // Maximise the block position in x and z to get max cuboid bounds - for(BlockPosition blockPosition : blockPositions) { - a.max(blockPosition); - b.min(blockPosition); - } - - Iris.debug("Blocks: " + blockPositions.size()); - Iris.debug("Min: " + a + " Max: " + b); - - // Create a cuboid with the size calculated before - Cuboid cuboid = new Cuboid(a.toBlock(world).getLocation(), b.toBlock(world).getLocation()); - boolean cuboidIsValid = true; - - // Loop while the cuboid is larger than 2 - while(Math.min(cuboid.getSizeX(), cuboid.getSizeZ()) > 0) { - checking: - for(int i = cuboid.getLowerX(); i < cuboid.getUpperX(); i++) { - for(int j = cuboid.getLowerY(); j < cuboid.getUpperY(); j++) { - for(int k = cuboid.getLowerZ(); k < cuboid.getUpperZ(); k++) { - if(!blockPositions.contains(new BlockPosition(i, j, k))) { - cuboidIsValid = false; - break checking; - } - } - } - } - - // Return this cuboid if it's valid - if(cuboidIsValid) { - return cuboid; - } - - // Inset the cuboid and try again (revalidate) - cuboid = cuboid.inset(Cuboid.CuboidDirection.Horizontal, 1); - cuboidIsValid = true; - } - - return new Cuboid(at, at); - } - - /** - * Grows the blockPosition list by means of checking neighbours in - * - * @param world - * the world to check in - * @param center - * the location of this position - * @param valid - * validation on blockData to check block with - * @param l - * list of block positions to add new neighbors too - */ - private void grow(World world, BlockPosition center, Predicate valid, KList l) { - // Make sure size is less than 50, the block to check isn't already in, and make sure the blockData still matches - if(l.size() <= 50 && !l.contains(center) && valid.test(center.toBlock(world).getBlockData())) { - l.add(center); - grow(world, center.add(1, 0, 0), valid, l); - grow(world, center.add(-1, 0, 0), valid, l); - grow(world, center.add(0, 0, 1), valid, l); - grow(world, center.add(0, 0, -1), valid, l); - } - } -} diff --git a/src/main/java/com/volmit/iris/core/service/VillageSVC.java b/src/main/java/com/volmit/iris/core/service/VillageSVC.java deleted file mode 100644 index 06160b129..000000000 --- a/src/main/java/com/volmit/iris/core/service/VillageSVC.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisVillagerOverride; -import com.volmit.iris.engine.object.IrisVillagerTrade; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.plugin.VolmitSender; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.entity.Villager; -import org.bukkit.event.EventHandler; -import org.bukkit.event.entity.VillagerAcquireTradeEvent; -import org.bukkit.event.entity.VillagerCareerChangeEvent; - -import java.util.List; - -public class VillageSVC implements IrisService { - @Override - public void onEnable() { - - } - - @Override - public void onDisable() { - - } - - @EventHandler - public void on(VillagerCareerChangeEvent event) { - - if (!IrisToolbelt.isIrisWorld(event.getEntity().getWorld())) { - return; - } - - IrisDimension dim = IrisToolbelt.access(event.getEntity().getWorld()) - .getEngine().getDimension(); - - if (!dim.isRemoveCartographersDueToCrash()) { - return; - } - - if (event.getProfession().equals(Villager.Profession.CARTOGRAPHER)) { - event.setCancelled(true); - - Location eventLocation = event.getEntity().getLocation(); - - int radius = dim.getNotifyPlayersOfCartographerCancelledRadius(); - - if (radius == -1) { - return; - } - - List playersInWorld = event.getEntity().getWorld().getPlayers(); - - String message = C.GOLD + "Iris does not allow cartographers in its world due to crashes."; - - Iris.info("Cancelled Cartographer Villager to prevent server crash at " + eventLocation + "!"); - - if (radius == -2) { - playersInWorld.stream().map(VolmitSender::new).forEach(v -> v.sendMessage(message)); - } else { - playersInWorld.forEach(p -> { - if (p.getLocation().distance(eventLocation) < radius) { - new VolmitSender(p).sendMessage(message); - } - }); - } - - } - } - - /* - * Replace or disable villager trade add event to prevent explorer map - */ - /* Removed due to MC breaking stuff again. This event is now called after the cartographer maps are made, - so it can fuck right off. - @EventHandler - public void on(VillagerAcquireTradeEvent event) { - if(!IrisToolbelt.isIrisWorld((event.getEntity().getWorld()))) { - return; - } - - // Iris.info("Trade event: type " + event.getRecipe().getResult().getType() + " / meta " + event.getRecipe().getResult().getItemMeta() + " / data " + event.getRecipe().getResult().getData()); - if(!event.getRecipe().getResult().getType().equals(Material.FILLED_MAP)) { - return; - } - - IrisVillagerOverride override = IrisToolbelt.access(event.getEntity().getWorld()).getEngine() - .getDimension().getPatchCartographers(); - - if(override.isDisableTrade()) { - event.setCancelled(true); - Iris.debug("Cancelled cartographer trade @ " + event.getEntity().getLocation()); - return; - } - - if(override.getValidItems() == null) { - event.setCancelled(true); - Iris.debug("Cancelled cartographer trade because no override items are valid @ " + event.getEntity().getLocation()); - return; - } - - IrisVillagerTrade trade = override.getValidItems().getRandom(); - event.setRecipe(trade.convert()); - Iris.debug("Overrode cartographer trade with: " + trade + " to prevent allowing cartography map trades"); - } - */ -} diff --git a/src/main/java/com/volmit/iris/core/service/WandSVC.java b/src/main/java/com/volmit/iris/core/service/WandSVC.java deleted file mode 100644 index f86721180..000000000 --- a/src/main/java/com/volmit/iris/core/service/WandSVC.java +++ /dev/null @@ -1,475 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.service; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.edit.DustRevealer; -import com.volmit.iris.core.link.WorldEditLink; -import com.volmit.iris.core.wand.WandSelection; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.data.Cuboid; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.matter.Matter; -import com.volmit.iris.util.matter.WorldMatter; -import com.volmit.iris.util.plugin.IrisService; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.Sound; -import org.bukkit.block.Block; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.util.BlockVector; -import org.bukkit.util.Vector; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.Objects; - -public class WandSVC implements IrisService { - private static ItemStack dust; - - public static void pasteSchematic(IrisObject s, Location at) { - s.place(at); - } - - /** - * Creates an Iris Object from the 2 coordinates selected with a wand - * - * @param p - * The wand player - * @return The new object - */ - public static IrisObject createSchematic(Player p) { - if(!isHoldingWand(p)) { - return null; - } - - try { - Location[] f = getCuboid(p); - Cuboid c = new Cuboid(f[0], f[1]); - IrisObject s = new IrisObject(c.getSizeX(), c.getSizeY(), c.getSizeZ()); - for(Block b : c) { - if(b.getType().equals(Material.AIR)) { - continue; - } - - BlockVector bv = b.getLocation().subtract(c.getLowerNE().toVector()).toVector().toBlockVector(); - s.setUnsigned(bv.getBlockX(), bv.getBlockY(), bv.getBlockZ(), b); - } - - return s; - } catch(Throwable e) { - e.printStackTrace(); - Iris.reportError(e); - } - - return null; - } - - /** - * Creates an Iris Object from the 2 coordinates selected with a wand - * - * @return The new object - */ - public static Matter createMatterSchem(Player p) { - if(!isHoldingWand(p)) { - return null; - } - - try { - Location[] f = getCuboid(p); - - return WorldMatter.createMatter(p.getName(), f[0], f[1]); - } catch(Throwable e) { - e.printStackTrace(); - Iris.reportError(e); - } - - return null; - } - - /** - * Converts a user friendly location string to an actual Location - * - * @param s - * The string - * @return The location - */ - public static Location stringToLocation(String s) { - try { - String[] f = s.split("\\Q in \\E"); - String[] g = f[0].split("\\Q,\\E"); - return new Location(Bukkit.getWorld(f[1]), Integer.parseInt(g[0]), Integer.parseInt(g[1]), Integer.parseInt(g[2])); - } catch(Throwable e) { - Iris.reportError(e); - return null; - } - } - - /** - * Get a user friendly string of a location - * - * @param loc - * The location - * @return The string - */ - public static String locationToString(Location loc) { - if(loc == null) { - return "<#>"; - } - - return loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ() + " in " + loc.getWorld().getName(); - } - - /** - * Create a new blank Iris wand - * - * @return The wand itemstack - */ - public static ItemStack createWand() { - return createWand(null, null); - } - - /** - * Create a new dust itemstack - * - * @return The stack - */ - public static ItemStack createDust() { - ItemStack is = new ItemStack(Material.GLOWSTONE_DUST); - is.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); - ItemMeta im = is.getItemMeta(); - im.setDisplayName(C.BOLD + "" + C.YELLOW + "Dust of Revealing"); - im.setUnbreakable(true); - im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_ENCHANTS); - im.setLore(new KList().qadd("Right click on a block to reveal it's placement structure!")); - is.setItemMeta(im); - - return is; - } - - /** - * Finds an existing wand in a users inventory - * - * @param inventory - * The inventory to search - * @return The slot number the wand is in. Or -1 if none are found - */ - public static int findWand(Inventory inventory) { - ItemStack wand = createWand(); //Create blank wand - ItemMeta meta = wand.getItemMeta(); - meta.setLore(new ArrayList<>()); //We are resetting the lore as the lore differs between wands - wand.setItemMeta(meta); - - for(int s = 0; s < inventory.getSize(); s++) { - ItemStack stack = inventory.getItem(s); - if(stack == null) continue; - meta = stack.getItemMeta(); - meta.setLore(new ArrayList<>()); //Reset the lore on this too so we can compare them - stack.setItemMeta(meta); //We dont need to clone the item as items from .get are cloned - - if(wand.isSimilar(stack)) return s; //If the name, material and NBT is the same - } - return -1; - } - - /** - * Creates an Iris wand. The locations should be the currently selected locations, or null - * - * @param a - * Location A - * @param b - * Location B - * @return A new wand - */ - public static ItemStack createWand(Location a, Location b) { - ItemStack is = new ItemStack(Material.BLAZE_ROD); - is.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); - ItemMeta im = is.getItemMeta(); - im.setDisplayName(C.BOLD + "" + C.GOLD + "Wand of Iris"); - im.setUnbreakable(true); - im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_ENCHANTS); - im.setLore(new KList().add(locationToString(a), locationToString(b))); - is.setItemMeta(im); - - return is; - } - - public static Location[] getCuboidFromItem(ItemStack is) { - ItemMeta im = is.getItemMeta(); - return new Location[] {stringToLocation(im.getLore().get(0)), stringToLocation(im.getLore().get(1))}; - } - - public static Location[] getCuboid(Player p) { - if(isHoldingIrisWand(p)) - { - return getCuboidFromItem(p.getInventory().getItemInMainHand()); - } - - Cuboid c = WorldEditLink.getSelection(p); - - if(c != null) - { - return new Location[] {c.getLowerNE(), c.getUpperSW()}; - } - - return null; - } - - public static boolean isHoldingWand(Player p) { - return isHoldingIrisWand(p) || WorldEditLink.getSelection(p) != null; - } - - public static boolean isHoldingIrisWand(Player p) { - ItemStack is = p.getInventory().getItemInMainHand(); - return is != null && isWand(is); - } - - /** - * Is the itemstack passed an Iris wand - * - * @param is - * The itemstack - * @return True if it is - */ - public static boolean isWand(ItemStack is) { - ItemStack wand = createWand(); - if(is.getItemMeta() == null) return false; - return is.getType().equals(wand.getType()) && - is.getItemMeta().getDisplayName().equals(wand.getItemMeta().getDisplayName()) && - is.getItemMeta().getEnchants().equals(wand.getItemMeta().getEnchants()) && - is.getItemMeta().getItemFlags().equals(wand.getItemMeta().getItemFlags()); - } - - @Override - public void onEnable() { - ItemStack wand = createWand(); - dust = createDust(); - - J.ar(() -> { - for(Player i : Bukkit.getOnlinePlayers()) { - tick(i); - } - }, 0); - } - - @Override - public void onDisable() { - - } - - public void tick(Player p) { - try { - try { - if((IrisSettings.get().getWorld().worldEditWandCUI && isHoldingWand(p)) || isWand(p.getInventory().getItemInMainHand())) { - Location[] d = getCuboid(p); - new WandSelection(new Cuboid(d[0], d[1]), p).draw(); - } - } catch(Throwable e) { - Iris.reportError(e); - } - } catch(Throwable e) { - e.printStackTrace(); - } - } - - /** - * Draw the outline of a selected region - * - * @param d - * The cuboid - * @param p - * The player to show it to - */ - public void draw(Cuboid d, Player p) { - draw(new Location[] {d.getLowerNE(), d.getUpperSW()}, p); - } - - /** - * Draw the outline of a selected region - * - * @param d - * A pair of locations - * @param p - * The player to show them to - */ - public void draw(Location[] d, Player p) { - Vector gx = Vector.getRandom().subtract(Vector.getRandom()).normalize().clone().multiply(0.65); - d[0].getWorld().spawnParticle(Particle.CRIT_MAGIC, d[0], 1, 0.5 + gx.getX(), 0.5 + gx.getY(), 0.5 + gx.getZ(), 0, null, false); - Vector gxx = Vector.getRandom().subtract(Vector.getRandom()).normalize().clone().multiply(0.65); - d[1].getWorld().spawnParticle(Particle.CRIT, d[1], 1, 0.5 + gxx.getX(), 0.5 + gxx.getY(), 0.5 + gxx.getZ(), 0, null, false); - - if(!d[0].getWorld().equals(d[1].getWorld())) { - return; - } - - if(d[0].distanceSquared(d[1]) > 64 * 64) { - return; - } - - int minx = Math.min(d[0].getBlockX(), d[1].getBlockX()); - int miny = Math.min(d[0].getBlockY(), d[1].getBlockY()); - int minz = Math.min(d[0].getBlockZ(), d[1].getBlockZ()); - int maxx = Math.max(d[0].getBlockX(), d[1].getBlockX()); - int maxy = Math.max(d[0].getBlockY(), d[1].getBlockY()); - int maxz = Math.max(d[0].getBlockZ(), d[1].getBlockZ()); - - for(double j = minx - 1; j < maxx + 1; j += 0.25) { - for(double k = miny - 1; k < maxy + 1; k += 0.25) { - for(double l = minz - 1; l < maxz + 1; l += 0.25) { - if(M.r(0.2)) { - boolean jj = j == minx || j == maxx; - boolean kk = k == miny || k == maxy; - boolean ll = l == minz || l == maxz; - - if((jj && kk) || (jj && ll) || (ll && kk)) { - Vector push = new Vector(0, 0, 0); - - if(j == minx) { - push.add(new Vector(-0.55, 0, 0)); - } - - if(k == miny) { - push.add(new Vector(0, -0.55, 0)); - } - - if(l == minz) { - push.add(new Vector(0, 0, -0.55)); - } - - if(j == maxx) { - push.add(new Vector(0.55, 0, 0)); - } - - if(k == maxy) { - push.add(new Vector(0, 0.55, 0)); - } - - if(l == maxz) { - push.add(new Vector(0, 0, 0.55)); - } - - Location lv = new Location(d[0].getWorld(), j, k, l).clone().add(0.5, 0.5, 0.5).clone().add(push); - Color color = Color.getHSBColor((float) (0.5f + (Math.sin((j + k + l + (p.getTicksLived() / 2f)) / 20f) / 2)), 1, 1); - int r = color.getRed(); - int g = color.getGreen(); - int b = color.getBlue(); - p.spawnParticle(Particle.REDSTONE, lv.getX(), lv.getY(), lv.getZ(), 1, 0, 0, 0, 0, new Particle.DustOptions(org.bukkit.Color.fromRGB(r, g, b), 0.75f)); - } - } - } - } - } - } - - @EventHandler - public void on(PlayerInteractEvent e) { - if(e.getHand() != EquipmentSlot.HAND) - return; - try { - if(isHoldingWand(e.getPlayer())) { - if(e.getAction().equals(Action.LEFT_CLICK_BLOCK)) { - e.setCancelled(true); - e.getPlayer().getInventory().setItemInMainHand(update(true, Objects.requireNonNull(e.getClickedBlock()).getLocation(), e.getPlayer().getInventory().getItemInMainHand())); - e.getPlayer().playSound(e.getClickedBlock().getLocation(), Sound.BLOCK_END_PORTAL_FRAME_FILL, 1f, 0.67f); - e.getPlayer().updateInventory(); - } else if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { - e.setCancelled(true); - e.getPlayer().getInventory().setItemInMainHand(update(false, Objects.requireNonNull(e.getClickedBlock()).getLocation(), e.getPlayer().getInventory().getItemInMainHand())); - e.getPlayer().playSound(e.getClickedBlock().getLocation(), Sound.BLOCK_END_PORTAL_FRAME_FILL, 1f, 1.17f); - e.getPlayer().updateInventory(); - } - } - - if(isHoldingDust(e.getPlayer())) { - if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { - e.setCancelled(true); - e.getPlayer().playSound(Objects.requireNonNull(e.getClickedBlock()).getLocation(), Sound.ENTITY_ENDER_EYE_DEATH, 2f, 1.97f); - DustRevealer.spawn(e.getClickedBlock(), new VolmitSender(e.getPlayer(), Iris.instance.getTag())); - } - } - } catch(Throwable xx) { - Iris.reportError(xx); - } - } - - /** - * Is the player holding Dust? - * - * @param p - * The player - * @return True if they are - */ - public boolean isHoldingDust(Player p) { - ItemStack is = p.getInventory().getItemInMainHand(); - return is != null && isDust(is); - } - - /** - * Is the itemstack passed Iris dust? - * - * @param is - * The itemstack - * @return True if it is - */ - public boolean isDust(ItemStack is) { - return is.isSimilar(dust); - } - - /** - * Update the location on an Iris wand - * - * @param left - * True for first location, false for second - * @param a - * The location - * @param item - * The wand - * @return The updated wand - */ - public ItemStack update(boolean left, Location a, ItemStack item) { - if(!isWand(item)) { - return item; - } - - Location[] f = getCuboidFromItem(item); - Location other = left ? f[1] : f[0]; - - if(other != null && !other.getWorld().getName().equals(a.getWorld().getName())) { - other = null; - } - - return createWand(left ? a : other, left ? other : a); - } -} diff --git a/src/main/java/com/volmit/iris/core/tools/IrisCreator.java b/src/main/java/com/volmit/iris/core/tools/IrisCreator.java deleted file mode 100644 index 3581832e5..000000000 --- a/src/main/java/com/volmit/iris/core/tools/IrisCreator.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.tools; - -import com.google.common.util.concurrent.AtomicDouble; -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.pregenerator.PregenTask; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.platform.PlatformChunkGenerator; -import com.volmit.iris.util.exceptions.IrisException; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.O; -import lombok.Data; -import lombok.experimental.Accessors; -import org.bukkit.Bukkit; -import org.bukkit.GameRule; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.WorldCreator; - -import java.io.File; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Supplier; - -/** - * Makes it a lot easier to setup an engine, world, studio or whatever - */ -@Data -@Accessors(fluent = true, chain = true) -public class IrisCreator { - /** - * Specify an area to pregenerate during creation - */ - private PregenTask pregen; - - /** - * Specify a sender to get updates & progress info + tp when world is created. - */ - private VolmitSender sender; - - /** - * The seed to use for this generator - */ - private long seed = 1337; - - /** - * The dimension to use. This can be any online dimension, or a dimension in the - * packs folder - */ - private String dimension = IrisSettings.get().getGenerator().getDefaultWorldType(); - - /** - * The name of this world. - */ - private String name = "irisworld"; - - /** - * Studio mode makes the engine hotloadable and uses the dimension in - * your Iris/packs folder instead of copying the dimension files into - * the world itself. Studio worlds are deleted when they are unloaded. - */ - private boolean studio = false; - - /** - * Create the IrisAccess (contains the world) - * - * @return the IrisAccess - * @throws IrisException - * shit happens - */ - public World create() throws IrisException { - if(Bukkit.isPrimaryThread()) { - throw new IrisException("You cannot invoke create() on the main thread."); - } - - IrisDimension d = IrisToolbelt.getDimension(dimension()); - - if(d == null) { - throw new IrisException("Dimension cannot be found null for id " + dimension()); - } - - if(!studio()) { - Iris.service(StudioSVC.class).installIntoWorld(sender, d.getLoadKey(), new File(name())); - } - - PlatformChunkGenerator access = null; - AtomicReference world = new AtomicReference<>(); - AtomicDouble pp = new AtomicDouble(0); - O done = new O<>(); - done.set(false); - WorldCreator wc = new IrisWorldCreator() - .dimension(dimension) - .name(name) - .seed(seed) - .studio(studio) - .create(); - - access = (PlatformChunkGenerator) wc.generator(); - PlatformChunkGenerator finalAccess1 = access; - - J.a(() -> - { - int req = 441; - Supplier g = () -> { - if (finalAccess1 == null || finalAccess1.getEngine() == null) { - return 0; - } - return finalAccess1.getEngine().getGenerated(); - }; - while(g.get() < req) { - double v = (double) g.get() / (double) req; - - if(sender.isPlayer()) { - sender.sendProgress(v, "Generating"); - J.sleep(16); - } else { - sender.sendMessage(C.WHITE + "Generating " + Form.pc(v) + ((C.GRAY + " (" + (req - g.get()) + " Left)"))); - J.sleep(1000); - } - } - }); - - - try { - J.sfut(() -> { - world.set(wc.createWorld()); - }).get(); - } catch(Throwable e) { - e.printStackTrace(); - } - - if(access == null) { - throw new IrisException("Access is null. Something bad happened."); - } - - done.set(true); - - if(sender.isPlayer()) { - J.s(() -> { - sender.player().teleport(new Location(world.get(), 0, world.get().getHighestBlockYAt(0, 0), 0)); - }); - } - - if(studio) { - J.s(() -> { - Iris.linkMultiverseCore.removeFromConfig(world.get()); - - if(IrisSettings.get().getStudio().isDisableTimeAndWeather()) { - world.get().setGameRule(GameRule.DO_WEATHER_CYCLE, false); - world.get().setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false); - world.get().setTime(6000); - } - }); - } - - if(pregen != null) { - CompletableFuture ff = new CompletableFuture<>(); - - IrisToolbelt.pregenerate(pregen, access) - .onProgress(pp::set) - .whenDone(() -> ff.complete(true)); - - try { - AtomicBoolean dx = new AtomicBoolean(false); - - J.a(() -> { - while(!dx.get()) { - if(sender.isPlayer()) { - sender.sendProgress(pp.get(), "Pregenerating"); - J.sleep(16); - } else { - sender.sendMessage(C.WHITE + "Pregenerating " + Form.pc(pp.get())); - J.sleep(1000); - } - } - }); - - ff.get(); - dx.set(true); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - return world.get(); - } -} diff --git a/src/main/java/com/volmit/iris/core/tools/IrisReflectiveAPI.java b/src/main/java/com/volmit/iris/core/tools/IrisReflectiveAPI.java deleted file mode 100644 index c52076f7c..000000000 --- a/src/main/java/com/volmit/iris/core/tools/IrisReflectiveAPI.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.volmit.iris.core.tools; - -import com.volmit.iris.util.data.B; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; - -/** - * This class is used by an external IrisLib for other plugins to interact with Iris. Do not change - * existing methods or their parameters as it will break the library that uses these methods - * feel free to add more methods so long as you also add the reflective methods to the library - */ -public class IrisReflectiveAPI { - public static boolean isIrisWorld(World world) { - return IrisToolbelt.isIrisWorld(world); - } - - public static boolean isIrisStudioWorld(World world) { - return IrisToolbelt.isIrisStudioWorld(world); - } - - public static void registerCustomBlockData(String namespace, String key, BlockData blockData) { - B.registerCustomBlockData(namespace, key, blockData); - } - - public static void retainMantleData(String classname) { - IrisToolbelt.retainMantleDataForSlice(classname); - } - - public static void setMantleData(World world, int x, int y, int z, Object data) { - IrisToolbelt.access(world).getEngine().getMantle().getMantle().set(x, y, z, data); - } - - public static void deleteMantleData(World world, int x, int y, int z, Class c) { - IrisToolbelt.access(world).getEngine().getMantle().getMantle().remove(x, y, z, c); - } - - public static Object getMantleData(World world, int x, int y, int z, Class c) { - return IrisToolbelt.access(world).getEngine().getMantle().getMantle().get(x, y, z, c); - } -} diff --git a/src/main/java/com/volmit/iris/core/tools/IrisToolbelt.java b/src/main/java/com/volmit/iris/core/tools/IrisToolbelt.java deleted file mode 100644 index ece0c942d..000000000 --- a/src/main/java/com/volmit/iris/core/tools/IrisToolbelt.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.tools; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.gui.PregeneratorJob; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.pregenerator.PregenTask; -import com.volmit.iris.core.pregenerator.PregeneratorMethod; -import com.volmit.iris.core.pregenerator.methods.HybridPregenMethod; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.platform.PlatformChunkGenerator; -import com.volmit.iris.util.plugin.VolmitSender; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Player; - -import java.io.File; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -/** - * Something you really want to wear if working on Iris. Shit gets pretty hectic down there. - * Hope you packed snacks & road sodas. - */ -public class IrisToolbelt { - public static Map toolbeltConfiguration = new HashMap<>(); - - /** - * Will find / download / search for the dimension or return null - *

- * - You can provide a dimenson in the packs folder by the folder name - * - You can provide a github repo by using (assumes branch is master unless specified) - * - GithubUsername/repository - * - GithubUsername/repository/branch - * - * @param dimension - * the dimension id such as overworld or flat - * @return the IrisDimension or null - */ - public static IrisDimension getDimension(String dimension) { - File pack = Iris.instance.getDataFolder("packs", dimension); - - if(!pack.exists()) { - Iris.service(StudioSVC.class).downloadSearch(new VolmitSender(Bukkit.getConsoleSender(), Iris.instance.getTag()), dimension, false, false); - } - - if(!pack.exists()) { - return null; - } - - return IrisData.get(pack).getDimensionLoader().load(dimension); - } - - /** - * Create a world with plenty of options - * - * @return the creator builder - */ - public static IrisCreator createWorld() { - return new IrisCreator(); - } - - /** - * Checks if the given world is an Iris World (same as access(world) != null) - * - * @param world - * the world - * @return true if it is an Iris Access world - */ - public static boolean isIrisWorld(World world) { - if(world == null) { - return false; - } - - if(world.getGenerator() instanceof PlatformChunkGenerator f) { - f.touch(world); - return true; - } - - return false; - } - - public static boolean isIrisStudioWorld(World world) { - return isIrisWorld(world) && access(world).isStudio(); - } - - /** - * Get the Iris generator for the given world - * - * @param world - * the given world - * @return the IrisAccess or null if it's not an Iris World - */ - public static PlatformChunkGenerator access(World world) { - if(isIrisWorld(world)) { - return ((PlatformChunkGenerator) world.getGenerator()); - } /*else { - Iris.warn(""" - "---------- No World? --------------- - ⠀⣞⢽⢪⢣⢣⢣⢫⡺⡵⣝⡮⣗⢷⢽⢽⢽⣮⡷⡽⣜⣜⢮⢺⣜⢷⢽⢝⡽⣝ - ⠸⡸⠜⠕⠕⠁⢁⢇⢏⢽⢺⣪⡳⡝⣎⣏⢯⢞⡿⣟⣷⣳⢯⡷⣽⢽⢯⣳⣫⠇ - ⠀⠀⢀⢀⢄⢬⢪⡪⡎⣆⡈⠚⠜⠕⠇⠗⠝⢕⢯⢫⣞⣯⣿⣻⡽⣏⢗⣗⠏⠀ - ⠀⠪⡪⡪⣪⢪⢺⢸⢢⢓⢆⢤⢀⠀⠀⠀⠀⠈⢊⢞⡾⣿⡯⣏⢮⠷⠁⠀⠀ - ⠀⠀⠀⠈⠊⠆⡃⠕⢕⢇⢇⢇⢇⢇⢏⢎⢎⢆⢄⠀⢑⣽⣿⢝⠲⠉⠀⠀⠀⠀ - ⠀⠀⠀⠀⠀⡿⠂⠠⠀⡇⢇⠕⢈⣀⠀⠁⠡⠣⡣⡫⣂⣿⠯⢪⠰⠂⠀⠀⠀⠀ - ⠀⠀⠀⠀⡦⡙⡂⢀⢤⢣⠣⡈⣾⡃⠠⠄⠀⡄⢱⣌⣶⢏⢊⠂⠀⠀⠀⠀⠀⠀ - ⠀⠀⠀⠀⢝⡲⣜⡮⡏⢎⢌⢂⠙⠢⠐⢀⢘⢵⣽⣿⡿⠁⠁⠀⠀⠀⠀⠀⠀⠀ - ⠀⠀⠀⠀⠨⣺⡺⡕⡕⡱⡑⡆⡕⡅⡕⡜⡼⢽⡻⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ - ⠀⠀⠀⠀⣼⣳⣫⣾⣵⣗⡵⡱⡡⢣⢑⢕⢜⢕⡝⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ - ⠀⠀⠀⣴⣿⣾⣿⣿⣿⡿⡽⡑⢌⠪⡢⡣⣣⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ - ⠀⠀⠀⡟⡾⣿⢿⢿⢵⣽⣾⣼⣘⢸⢸⣞⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ - ⠀⠀⠀⠀⠁⠇⠡⠩⡫⢿⣝⡻⡮⣒⢽⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ - """); - }*/ - return null; - } - - /** - * Start a pregenerator task - * - * @param task - * the scheduled task - * @param method - * the method to execute the task - * @return the pregenerator job (already started) - */ - public static PregeneratorJob pregenerate(PregenTask task, PregeneratorMethod method, Engine engine) { - return new PregeneratorJob(task, method, engine); - } - - /** - * Start a pregenerator task. If the supplied generator is headless, headless mode is used, - * otherwise Hybrid mode is used. - * - * @param task - * the scheduled task - * @param gen - * the Iris Generator - * @return the pregenerator job (already started) - */ - public static PregeneratorJob pregenerate(PregenTask task, PlatformChunkGenerator gen) { - return pregenerate(task, new HybridPregenMethod(gen.getEngine().getWorld().realWorld(), - IrisSettings.getThreadCount(IrisSettings.get().getConcurrency().getParallelism())), gen.getEngine()); - } - - /** - * Start a pregenerator task. If the supplied generator is headless, headless mode is used, - * otherwise Hybrid mode is used. - * - * @param task - * the scheduled task - * @param world - * the World - * @return the pregenerator job (already started) - */ - public static PregeneratorJob pregenerate(PregenTask task, World world) { - if(isIrisWorld(world)) { - return pregenerate(task, access(world)); - } - - return pregenerate(task, new HybridPregenMethod(world, IrisSettings.getThreadCount(IrisSettings.get().getConcurrency().getParallelism())), null); - } - - /** - * Evacuate all players from the world into literally any other world. - * If there are no other worlds, kick them! Not the best but what's mine is mine sometimes... - * - * @param world - * the world to evac - */ - public static boolean evacuate(World world) { - for(World i : Bukkit.getWorlds()) { - if(!i.getName().equals(world.getName())) { - for(Player j : world.getPlayers()) { - new VolmitSender(j, Iris.instance.getTag()).sendMessage("You have been evacuated from this world."); - j.teleport(i.getSpawnLocation()); - } - - return true; - } - } - - return false; - } - - /** - * Evacuate all players from the world - * - * @param world - * the world to leave - * @param m - * the message - * @return true if it was evacuated. - */ - public static boolean evacuate(World world, String m) { - for(World i : Bukkit.getWorlds()) { - if(!i.getName().equals(world.getName())) { - for(Player j : world.getPlayers()) { - new VolmitSender(j, Iris.instance.getTag()).sendMessage("You have been evacuated from this world. " + m); - j.teleport(i.getSpawnLocation()); - } - - return true; - } - } - - return false; - } - - public static boolean isStudio(World i) { - return isIrisWorld(i) && access(i).isStudio(); - } - - public static void retainMantleDataForSlice(String className) { - toolbeltConfiguration.put("retain.mantle." + className, true); - } - - public static T getMantleData(World world, int x, int y, int z, Class of) { - PlatformChunkGenerator e = access(world); - if(e == null) {return null;} - return e.getEngine().getMantle().getMantle().get(x, y - world.getMinHeight(), z, of); - } - - public static void deleteMantleData(World world, int x, int y, int z, Class of) { - PlatformChunkGenerator e = access(world); - if(e == null) {return;} - e.getEngine().getMantle().getMantle().remove(x, y - world.getMinHeight(), z, of); - } -} diff --git a/src/main/java/com/volmit/iris/core/tools/IrisWorldCreator.java b/src/main/java/com/volmit/iris/core/tools/IrisWorldCreator.java deleted file mode 100644 index 2926335e2..000000000 --- a/src/main/java/com/volmit/iris/core/tools/IrisWorldCreator.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.tools; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisWorld; -import com.volmit.iris.engine.platform.BukkitChunkGenerator; -import org.bukkit.World; -import org.bukkit.WorldCreator; -import org.bukkit.generator.ChunkGenerator; - -import java.io.File; - -public class IrisWorldCreator { - private String name; - private boolean studio = false; - private String dimensionName = null; - private long seed = 1337; - - public IrisWorldCreator() { - - } - - public IrisWorldCreator dimension(String loadKey) { - this.dimensionName = loadKey; - return this; - } - - public IrisWorldCreator name(String name) { - this.name = name; - return this; - } - - public IrisWorldCreator seed(long seed) { - this.seed = seed; - return this; - } - - public IrisWorldCreator studioMode() { - this.studio = true; - return this; - } - - public IrisWorldCreator productionMode() { - this.studio = false; - return this; - } - - public WorldCreator create() { - IrisDimension dim = IrisData.loadAnyDimension(dimensionName); - - IrisWorld w = IrisWorld.builder() - .name(name) - .minHeight(dim.getMinHeight()) - .maxHeight(dim.getMaxHeight()) - .seed(seed) - .worldFolder(new File(name)) - .environment(findEnvironment()) - .build(); - ChunkGenerator g = new BukkitChunkGenerator(w, studio, studio - ? dim.getLoader().getDataFolder() : - new File(w.worldFolder(), "iris/pack"), dimensionName); - - return new WorldCreator(name) - .environment(findEnvironment()) - .generateStructures(true) - .generator(g).seed(seed); - } - - private World.Environment findEnvironment() { - IrisDimension dim = IrisData.loadAnyDimension(dimensionName); - if(dim == null || dim.getEnvironment() == null) { - return World.Environment.NORMAL; - } else { - return dim.getEnvironment(); - } - } - - public IrisWorldCreator studio(boolean studio) { - this.studio = studio; - return this; - } -} diff --git a/src/main/java/com/volmit/iris/core/wand/WandSelection.java b/src/main/java/com/volmit/iris/core/wand/WandSelection.java deleted file mode 100644 index 8321e3815..000000000 --- a/src/main/java/com/volmit/iris/core/wand/WandSelection.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.core.wand; - -import com.volmit.iris.util.data.Cuboid; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import java.awt.Color; - -public class WandSelection { - private final Cuboid c; - private final Player p; - - public WandSelection(Cuboid c, Player p) { - this.c = c; - this.p = p; - } - - public void draw() { - double accuracy = M.lerpInverse(0, 64 * 64, p.getLocation().distanceSquared(c.getCenter())); - double dist = M.lerp(0.125, 3.5, accuracy); - - for(double i = c.getLowerX() - 1; i < c.getUpperX() + 1; i += 0.25) { - for(double j = c.getLowerY() - 1; j < c.getUpperY() + 1; j += 0.25) { - for(double k = c.getLowerZ() - 1; k < c.getUpperZ() + 1; k += 0.25) { - boolean ii = i == c.getLowerX() || i == c.getUpperX(); - boolean jj = j == c.getLowerY() || j == c.getUpperY(); - boolean kk = k == c.getLowerZ() || k == c.getUpperZ(); - - if((ii && jj) || (ii && kk) || (kk && jj)) { - Vector push = new Vector(0, 0, 0); - - if(i == c.getLowerX()) { - push.add(new Vector(-0.55, 0, 0)); - } - - if(j == c.getLowerY()) { - push.add(new Vector(0, -0.55, 0)); - } - - if(k == c.getLowerZ()) { - push.add(new Vector(0, 0, -0.55)); - } - - if(i == c.getUpperX()) { - push.add(new Vector(0.55, 0, 0)); - } - - if(j == c.getUpperY()) { - push.add(new Vector(0, 0.55, 0)); - } - - if(k == c.getUpperZ()) { - push.add(new Vector(0, 0, 0.55)); - } - - Location a = new Location(c.getWorld(), i, j, k).add(0.5, 0.5, 0.5).add(push); - accuracy = M.lerpInverse(0, 64 * 64, p.getLocation().distanceSquared(a)); - dist = M.lerp(0.125, 3.5, accuracy); - - if(M.r(M.min(dist * 5, 0.9D) * 0.995)) { - continue; - } - - if(ii && jj) { - a.add(0, 0, RNG.r.d(-0.3, 0.3)); - } - - if(kk && jj) { - a.add(RNG.r.d(-0.3, 0.3), 0, 0); - } - - if(ii && kk) { - a.add(0, RNG.r.d(-0.3, 0.3), 0); - } - - if(p.getLocation().distanceSquared(a) < 256 * 256) { - Color color = Color.getHSBColor((float) (0.5f + (Math.sin((i + j + k + (p.getTicksLived() / 2f)) / (20f)) / 2)), 1, 1); - int r = color.getRed(); - int g = color.getGreen(); - int b = color.getBlue(); - - p.spawnParticle(Particle.REDSTONE, a.getX(), a.getY(), a.getZ(), - 1, 0, 0, 0, 0, - new Particle.DustOptions(org.bukkit.Color.fromRGB(r, g, b), - (float) dist * 3f)); - } - } - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/EnginePanic.java b/src/main/java/com/volmit/iris/engine/EnginePanic.java deleted file mode 100644 index fb5dfaa13..000000000 --- a/src/main/java/com/volmit/iris/engine/EnginePanic.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KMap; - -public class EnginePanic { - private static final KMap stuff = new KMap<>(); - private static KMap last = new KMap<>(); - - public static void add(String key, String value) { - stuff.put(key, value); - } - - public static void saveLast() { - last = stuff.copy(); - } - - public static void lastPanic() { - for(String i : last.keySet()) { - Iris.error("Last Panic " + i + ": " + stuff.get(i)); - } - } - - public static void panic() { - lastPanic(); - for(String i : stuff.keySet()) { - Iris.error("Engine Panic " + i + ": " + stuff.get(i)); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/IrisComplex.java b/src/main/java/com/volmit/iris/engine/IrisComplex.java deleted file mode 100644 index 6776a6773..000000000 --- a/src/main/java/com/volmit/iris/engine/IrisComplex.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.InferredType; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDecorationPart; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.engine.object.IrisGenerator; -import com.volmit.iris.engine.object.IrisInterpolator; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.data.DataProvider; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.stream.interpolation.Interpolated; -import lombok.Data; -import org.bukkit.Material; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -import java.util.UUID; - -@Data -public class IrisComplex implements DataProvider { - private static final BlockData AIR = Material.AIR.createBlockData(); - private RNG rng; - private double fluidHeight; - private IrisData data; - private KMap> generators; - private ProceduralStream regionStream; - private ProceduralStream regionStyleStream; - private ProceduralStream regionIdentityStream; - private ProceduralStream regionIDStream; - private ProceduralStream bridgeStream; - private ProceduralStream landBiomeStream; - private ProceduralStream caveBiomeStream; - private ProceduralStream seaBiomeStream; - private ProceduralStream shoreBiomeStream; - private ProceduralStream baseBiomeStream; - private ProceduralStream baseBiomeIDStream; - private ProceduralStream trueBiomeStream; - private ProceduralStream trueBiomeDerivativeStream; - private ProceduralStream heightStream; - private ProceduralStream roundedHeighteightStream; - private ProceduralStream maxHeightStream; - private ProceduralStream overlayStream; - private ProceduralStream heightFluidStream; - private ProceduralStream slopeStream; - private ProceduralStream topSurfaceStream; - private ProceduralStream terrainSurfaceDecoration; - private ProceduralStream terrainCeilingDecoration; - private ProceduralStream terrainCaveSurfaceDecoration; - private ProceduralStream terrainCaveCeilingDecoration; - private ProceduralStream seaSurfaceDecoration; - private ProceduralStream seaFloorDecoration; - private ProceduralStream shoreSurfaceDecoration; - private ProceduralStream rockStream; - private ProceduralStream fluidStream; - private IrisBiome focusBiome; - private IrisRegion focusRegion; - - public IrisComplex(Engine engine) { - this(engine, false); - } - - public IrisComplex(Engine engine, boolean simple) { - int cacheSize = IrisSettings.get().getPerformance().getCacheSize(); - IrisBiome emptyBiome = new IrisBiome(); - UUID focusUUID = UUID.nameUUIDFromBytes("focus".getBytes()); - this.rng = new RNG(engine.getSeedManager().getComplex()); - this.data = engine.getData(); - double height = engine.getMaxHeight(); - fluidHeight = engine.getDimension().getFluidHeight(); - generators = new KMap<>(); - focusBiome = engine.getFocus(); - focusRegion = engine.getFocusRegion(); - KMap> inferredStreams = new KMap<>(); - - if(focusBiome != null) { - focusBiome.setInferredType(InferredType.LAND); - focusRegion = findRegion(focusBiome, engine); - } - - //@builder - engine.getDimension().getRegions().forEach((i) -> data.getRegionLoader().load(i) - .getAllBiomes(this).forEach((b) -> b - .getGenerators() - .forEach((c) -> registerGenerator(c.getCachedGenerator(this))))); - overlayStream = ProceduralStream.ofDouble((x, z) -> 0.0D); - engine.getDimension().getOverlayNoise().forEach(i -> overlayStream = overlayStream.add((x, z) -> i.get(rng, getData(), x, z))); - rockStream = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), data).stream() - .select(engine.getDimension().getRockPalette().getBlockData(data)); - fluidStream = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream() - .select(engine.getDimension().getFluidPalette().getBlockData(data)); - regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), getData()).stream() - .zoom(engine.getDimension().getRegionZoom()); - regionIdentityStream = regionStyleStream.fit(Integer.MIN_VALUE, Integer.MAX_VALUE); - regionStream = focusRegion != null ? - ProceduralStream.of((x, z) -> focusRegion, - Interpolated.of(a -> 0D, a -> focusRegion)) - : regionStyleStream - .selectRarity(data.getRegionLoader().loadAll(engine.getDimension().getRegions())) - .cache2D("regionStream", engine, cacheSize); - regionIDStream = regionIdentityStream.convertCached((i) -> new UUID(Double.doubleToLongBits(i), String.valueOf(i * 38445).hashCode() * 3245556666L)); - caveBiomeStream = regionStream.convert((r) - -> engine.getDimension().getCaveBiomeStyle().create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), getData()).stream() - .zoom(r.getCaveBiomeZoom()) - .selectRarity(data.getBiomeLoader().loadAll(r.getCaveBiomes())) - .onNull(emptyBiome) - ).convertAware2D(ProceduralStream::get).cache2D("caveBiomeStream", engine, cacheSize); - inferredStreams.put(InferredType.CAVE, caveBiomeStream); - landBiomeStream = regionStream.convert((r) - -> engine.getDimension().getLandBiomeStyle().create(rng.nextParallelRNG(InferredType.LAND.ordinal()), getData()).stream() - .zoom(r.getLandBiomeZoom()) - .selectRarity(data.getBiomeLoader().loadAll(r.getLandBiomes(), (t) -> t.setInferredType(InferredType.LAND))) - ).convertAware2D(ProceduralStream::get) - .cache2D("landBiomeStream", engine, cacheSize); - inferredStreams.put(InferredType.LAND, landBiomeStream); - seaBiomeStream = regionStream.convert((r) - -> engine.getDimension().getSeaBiomeStyle().create(rng.nextParallelRNG(InferredType.SEA.ordinal()), getData()).stream() - .zoom(r.getSeaBiomeZoom()) - .selectRarity(data.getBiomeLoader().loadAll(r.getSeaBiomes(), (t) -> t.setInferredType(InferredType.SEA))) - ).convertAware2D(ProceduralStream::get) - .cache2D("seaBiomeStream", engine, cacheSize); - inferredStreams.put(InferredType.SEA, seaBiomeStream); - shoreBiomeStream = regionStream.convert((r) - -> engine.getDimension().getShoreBiomeStyle().create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), getData()).stream() - .zoom(r.getShoreBiomeZoom()) - .selectRarity(data.getBiomeLoader().loadAll(r.getShoreBiomes(), (t) -> t.setInferredType(InferredType.SHORE))) - ).convertAware2D(ProceduralStream::get).cache2D("shoreBiomeStream", engine, cacheSize); - inferredStreams.put(InferredType.SHORE, shoreBiomeStream); - bridgeStream = focusBiome != null ? ProceduralStream.of((x, z) -> focusBiome.getInferredType(), - Interpolated.of(a -> 0D, a -> focusBiome.getInferredType())) : - engine.getDimension().getContinentalStyle().create(rng.nextParallelRNG(234234565), getData()) - .bake().scale(1D / engine.getDimension().getContinentZoom()).bake().stream() - .convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND) - .cache2D("bridgeStream", engine, cacheSize); - baseBiomeStream = focusBiome != null ? ProceduralStream.of((x, z) -> focusBiome, - Interpolated.of(a -> 0D, a -> focusBiome)) : - bridgeStream.convertAware2D((t, x, z) -> inferredStreams.get(t).get(x, z)) - .convertAware2D(this::implode) - .cache2D("baseBiomeStream", engine, cacheSize); - heightStream = ProceduralStream.of((x, z) -> { - IrisBiome b = focusBiome != null ? focusBiome : baseBiomeStream.get(x, z); - return getHeight(engine, b, x, z, engine.getSeedManager().getHeight()); - }, Interpolated.DOUBLE).clamp(0, engine.getHeight()).cache2D("heightStream", engine, cacheSize); - roundedHeighteightStream = heightStream.round(); - slopeStream = heightStream.slope(3).cache2D("slopeStream", engine, cacheSize); - trueBiomeStream = focusBiome != null ? ProceduralStream.of((x, y) -> focusBiome, Interpolated.of(a -> 0D, - b -> focusBiome)) - .cache2D("trueBiomeStream-focus", engine, cacheSize) : heightStream - .convertAware2D((h, x, z) -> - fixBiomeType(h, baseBiomeStream.get(x, z), - regionStream.get(x, z), x, z, fluidHeight)) - .cache2D("trueBiomeStream", engine, cacheSize); - trueBiomeDerivativeStream = trueBiomeStream.convert(IrisBiome::getDerivative).cache2D("trueBiomeDerivativeStream", engine, cacheSize); - heightFluidStream = heightStream.max(fluidHeight).cache2D("heightFluidStream", engine, cacheSize); - maxHeightStream = ProceduralStream.ofDouble((x, z) -> height); - terrainSurfaceDecoration = trueBiomeStream - .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, IrisDecorationPart.NONE)).cache2D("terrainSurfaceDecoration", engine, cacheSize); - terrainCeilingDecoration = trueBiomeStream - .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, IrisDecorationPart.CEILING)).cache2D("terrainCeilingDecoration", engine, cacheSize); - terrainCaveSurfaceDecoration = caveBiomeStream - .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, IrisDecorationPart.NONE)).cache2D("terrainCaveSurfaceDecoration", engine, cacheSize); - terrainCaveCeilingDecoration = caveBiomeStream - .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, IrisDecorationPart.CEILING)).cache2D("terrainCaveCeilingDecoration", engine, cacheSize); - shoreSurfaceDecoration = trueBiomeStream - .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, IrisDecorationPart.SHORE_LINE)).cache2D("shoreSurfaceDecoration", engine, cacheSize); - seaSurfaceDecoration = trueBiomeStream - .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, IrisDecorationPart.SEA_SURFACE)).cache2D("seaSurfaceDecoration", engine, cacheSize); - seaFloorDecoration = trueBiomeStream - .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, IrisDecorationPart.SEA_FLOOR)).cache2D("seaFloorDecoration", engine, cacheSize); - baseBiomeIDStream = trueBiomeStream.convertAware2D((b, x, z) -> { - UUID d = regionIDStream.get(x, z); - return new UUID(b.getLoadKey().hashCode() * 818223L, - d.hashCode()); - }) - .cache2D("", engine, cacheSize); - //@done - } - - public ProceduralStream getBiomeStream(InferredType type) { - switch(type) { - case CAVE: - return caveBiomeStream; - case LAND: - return landBiomeStream; - case SEA: - return seaBiomeStream; - case SHORE: - return shoreBiomeStream; - case DEFER: - default: - break; - } - - return null; - } - - private IrisRegion findRegion(IrisBiome focus, Engine engine) { - for(IrisRegion i : engine.getDimension().getAllRegions(engine)) { - if(i.getAllBiomeIds().contains(focus.getLoadKey())) { - return i; - } - } - - return null; - } - - private IrisDecorator decorateFor(IrisBiome b, double x, double z, IrisDecorationPart part) { - RNG rngc = new RNG(Cache.key(((int) x), ((int) z))); - - for(IrisDecorator i : b.getDecorators()) { - if(!i.getPartOf().equals(part)) { - continue; - } - - BlockData block = i.getBlockData(b, rngc, x, z, data); - - if(block != null) { - return i; - } - } - - return null; - } - - private IrisBiome fixBiomeType(Double height, IrisBiome biome, IrisRegion region, Double x, Double z, double fluidHeight) { - double sh = region.getShoreHeight(x, z); - - if(height >= fluidHeight - 1 && height <= fluidHeight + sh && !biome.isShore()) { - return shoreBiomeStream.get(x, z); - } - - if(height > fluidHeight + sh && !biome.isLand()) { - return landBiomeStream.get(x, z); - } - - if(height < fluidHeight && !biome.isAquatic()) { - return seaBiomeStream.get(x, z); - } - - if(height == fluidHeight && !biome.isShore()) { - return shoreBiomeStream.get(x, z); - } - - return biome; - } - - private double interpolateGenerators(Engine engine, IrisInterpolator interpolator, KSet generators, double x, double z, long seed) { - if(generators.isEmpty()) { - return 0; - } - - double hi = interpolator.interpolate(x, z, (xx, zz) -> { - try { - IrisBiome bx = baseBiomeStream.get(xx, zz); - double b = 0; - - for(IrisGenerator gen : generators) { - b += bx.getGenLinkMax(gen.getLoadKey()); - } - - return b; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - Iris.error("Failed to sample hi biome at " + xx + " " + zz + "..."); - } - - return 0; - }); - - double lo = interpolator.interpolate(x, z, (xx, zz) -> { - try { - IrisBiome bx = baseBiomeStream.get(xx, zz); - double b = 0; - - for(IrisGenerator gen : generators) { - b += bx.getGenLinkMin(gen.getLoadKey()); - } - - return b; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - Iris.error("Failed to sample lo biome at " + xx + " " + zz + "..."); - } - - return 0; - }); - - double d = 0; - - for(IrisGenerator i : generators) { - d += M.lerp(lo, hi, i.getHeight(x, z, seed + 239945)); - } - - return d / generators.size(); - } - - private double getInterpolatedHeight(Engine engine, double x, double z, long seed) { - double h = 0; - - for(IrisInterpolator i : generators.keySet()) { - h += interpolateGenerators(engine, i, generators.get(i), x, z, seed); - } - - return h; - } - - private double getHeight(Engine engine, IrisBiome b, double x, double z, long seed) { - return Math.max(Math.min(getInterpolatedHeight(engine, x, z, seed) + fluidHeight + overlayStream.get(x, z), engine.getHeight()), 0); - } - - private void registerGenerator(IrisGenerator cachedGenerator) { - generators.computeIfAbsent(cachedGenerator.getInterpolator(), (k) -> new KSet<>()).add(cachedGenerator); - } - - private IrisBiome implode(IrisBiome b, Double x, Double z) { - if(b.getChildren().isEmpty()) { - return b; - } - - return implode(b, x, z, 3); - } - - private IrisBiome implode(IrisBiome b, Double x, Double z, int max) { - if(max < 0) { - return b; - } - - if(b.getChildren().isEmpty()) { - return b; - } - - CNG childCell = b.getChildrenGenerator(rng, 123, b.getChildShrinkFactor()); - KList chx = b.getRealChildren(this).copy(); - chx.add(b); - IrisBiome biome = childCell.fitRarity(chx, x, z); - biome.setInferredType(b.getInferredType()); - return implode(biome, x, z, max - 1); - } - - public void close() { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/IrisEngine.java b/src/main/java/com/volmit/iris/engine/IrisEngine.java deleted file mode 100644 index 049bd3e73..000000000 --- a/src/main/java/com/volmit/iris/engine/IrisEngine.java +++ /dev/null @@ -1,516 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine; - -import com.google.common.util.concurrent.AtomicDouble; -import com.google.gson.Gson; -import com.volmit.iris.Iris; -import com.volmit.iris.core.ServerConfigurator; -import com.volmit.iris.core.events.IrisEngineHotloadEvent; -import com.volmit.iris.core.gui.PregeneratorJob; -import com.volmit.iris.core.project.IrisProject; -import com.volmit.iris.core.service.PreservationSVC; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineEffects; -import com.volmit.iris.engine.framework.EngineMetrics; -import com.volmit.iris.engine.framework.EngineMode; -import com.volmit.iris.engine.framework.EngineTarget; -import com.volmit.iris.engine.framework.EngineWorldManager; -import com.volmit.iris.engine.framework.SeedManager; -import com.volmit.iris.engine.framework.WrongEngineBroException; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisBiomePaletteLayer; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.engine.object.IrisEngineData; -import com.volmit.iris.engine.object.IrisJigsawStructure; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.engine.scripting.EngineExecutionEnvironment; -import com.volmit.iris.util.atomics.AtomicRollingSequence; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.Data; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.command.CommandSender; - -import java.io.File; -import java.io.IOException; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -@Data -public class IrisEngine implements Engine { - private final AtomicInteger bud; - private final AtomicInteger buds; - private final AtomicInteger generated; - private final AtomicInteger generatedLast; - private final AtomicDouble perSecond; - private final AtomicLong lastGPS; - private final EngineTarget target; - private final IrisContext context; - private final EngineMantle mantle; - private final ChronoLatch perSecondLatch; - private final ChronoLatch perSecondBudLatch; - private final EngineMetrics metrics; - private final boolean studio; - private final AtomicRollingSequence wallClock; - private final int art; - private EngineMode mode; - private final AtomicCache engineData = new AtomicCache<>(); - private final AtomicBoolean cleaning; - private final ChronoLatch cleanLatch; - private final SeedManager seedManager; - private EngineEffects effects; - private EngineExecutionEnvironment execution; - private EngineWorldManager worldManager; - private volatile int parallelism; - private volatile int minHeight; - private boolean failing; - private boolean closed; - private int cacheId; - private double maxBiomeObjectDensity; - private double maxBiomeLayerDensity; - private double maxBiomeDecoratorDensity; - private IrisComplex complex; - - public IrisEngine(EngineTarget target, boolean studio) { - this.studio = studio; - this.target = target; - getEngineData(); - verifySeed(); - this.seedManager = new SeedManager(target.getWorld().getRawWorldSeed()); - bud = new AtomicInteger(0); - buds = new AtomicInteger(0); - metrics = new EngineMetrics(32); - cleanLatch = new ChronoLatch(10000); - generatedLast = new AtomicInteger(0); - perSecond = new AtomicDouble(0); - perSecondLatch = new ChronoLatch(1000, false); - perSecondBudLatch = new ChronoLatch(1000, false); - wallClock = new AtomicRollingSequence(32); - lastGPS = new AtomicLong(M.ms()); - generated = new AtomicInteger(0); - mantle = new IrisEngineMantle(this); - context = new IrisContext(this); - cleaning = new AtomicBoolean(false); - context.touch(); - Iris.info("Initializing Engine: " + target.getWorld().name() + "/" + target.getDimension().getLoadKey() + " (" + target.getDimension().getDimensionHeight() + " height) Seed: " + getSeedManager().getSeed()); - getData().setEngine(this); - minHeight = 0; - failing = false; - closed = false; - art = J.ar(this::tickRandomPlayer, 0); - setupEngine(); - Iris.debug("Engine Initialized " + getCacheID()); - } - - private void verifySeed() { - if(getEngineData().getSeed() != null && getEngineData().getSeed() != target.getWorld().getRawWorldSeed()) { - target.getWorld().setRawWorldSeed(getEngineData().getSeed()); - } - } - - private void tickRandomPlayer() { - if(perSecondBudLatch.flip()) { - buds.set(bud.get()); - bud.set(0); - } - - if(effects != null) { - effects.tickRandomPlayer(); - } - } - - private void prehotload() { - worldManager.close(); - complex.close(); - execution.close(); - effects.close(); - mode.close(); - - J.a(() -> new IrisProject(getData().getDataFolder()).updateWorkspace()); - } - - private void setupEngine() { - try { - Iris.debug("Setup Engine " + getCacheID()); - cacheId = RNG.r.nextInt(); - worldManager = new IrisWorldManager(this); - complex = new IrisComplex(this); - execution = new IrisExecutionEnvironment(this); - effects = new IrisEngineEffects(this); - setupMode(); - J.a(this::computeBiomeMaxes); - } catch(Throwable e) { - Iris.error("FAILED TO SETUP ENGINE!"); - e.printStackTrace(); - } - - Iris.debug("Engine Setup Complete " + getCacheID()); - } - - private void setupMode() { - if(mode != null) { - mode.close(); - } - - mode = getDimension().getMode().getType().create(this); - } - - @Override - public void generateMatter(int x, int z, boolean multicore) { - getMantle().generateMatter(x, z, multicore); - } - - @Override - public Set getObjectsAt(int x, int z) { - return getMantle().getObjectComponent().guess(x, z); - } - - @Override - public IrisJigsawStructure getStructureAt(int x, int z) { - return getMantle().getJigsawComponent().guess(x, z); - } - - private void warmupChunk(int x, int z) { - for(int i = 0; i < 16; i++) { - for(int j = 0; j < 16; j++) { - int xx = x + (i << 4); - int zz = z + (z << 4); - getComplex().getTrueBiomeStream().get(xx, zz); - getComplex().getHeightStream().get(xx, zz); - } - } - } - - @Override - public void hotload() { - hotloadSilently(); - Iris.callEvent(new IrisEngineHotloadEvent(this)); - } - - public void hotloadComplex() { - complex.close(); - complex = new IrisComplex(this); - } - - public void hotloadSilently() { - getData().dump(); - getData().clearLists(); - getTarget().setDimension(getData().getDimensionLoader().load(getDimension().getLoadKey())); - prehotload(); - setupEngine(); - J.a(() -> { synchronized(ServerConfigurator.class) { ServerConfigurator.installDataPacks(false); } }); - } - - @Override - public IrisEngineData getEngineData() { - World w = null; - - return engineData.aquire(() -> { - //TODO: Method this file - File f = new File(getWorld().worldFolder(), "iris/engine-data/" + getDimension().getLoadKey() + ".json"); - - if(!f.exists()) { - try { - f.getParentFile().mkdirs(); - IO.writeAll(f, new Gson().toJson(new IrisEngineData())); - } catch(IOException e) { - e.printStackTrace(); - } - } - - try { - return new Gson().fromJson(IO.readAll(f), IrisEngineData.class); - } catch(Throwable e) { - e.printStackTrace(); - } - - return new IrisEngineData(); - }); - } - - @Override - public int getGenerated() { - return generated.get(); - } - - @Override - public double getGeneratedPerSecond() { - if(perSecondLatch.flip()) { - double g = generated.get() - generatedLast.get(); - generatedLast.set(generated.get()); - - if(g == 0) { - return 0; - } - - long dur = M.ms() - lastGPS.get(); - lastGPS.set(M.ms()); - perSecond.set(g / ((double) (dur) / 1000D)); - } - - return perSecond.get(); - } - - @Override - public boolean isStudio() { - return studio; - } - - private void computeBiomeMaxes() { - for(IrisBiome i : getDimension().getAllBiomes(this)) { - double density = 0; - - for(IrisObjectPlacement j : i.getObjects()) { - density += j.getDensity() * j.getChance(); - } - - maxBiomeObjectDensity = Math.max(maxBiomeObjectDensity, density); - density = 0; - - for(IrisDecorator j : i.getDecorators()) { - density += Math.max(j.getStackMax(), 1) * j.getChance(); - } - - maxBiomeDecoratorDensity = Math.max(maxBiomeDecoratorDensity, density); - density = 0; - - for(IrisBiomePaletteLayer j : i.getLayers()) { - density++; - } - - maxBiomeLayerDensity = Math.max(maxBiomeLayerDensity, density); - } - } - - @Override - public int getBlockUpdatesPerSecond() { - return buds.get(); - } - - public void printMetrics(CommandSender sender) { - KMap totals = new KMap<>(); - KMap weights = new KMap<>(); - double masterWallClock = wallClock.getAverage(); - KMap timings = getMetrics().pull(); - double totalWeight = 0; - double wallClock = getMetrics().getTotal().getAverage(); - - for(double j : timings.values()) { - totalWeight += j; - } - - for(String j : timings.k()) { - weights.put(getName() + "." + j, (wallClock / totalWeight) * timings.get(j)); - } - - totals.put(getName(), wallClock); - - double mtotals = 0; - - for(double i : totals.values()) { - mtotals += i; - } - - for(String i : totals.k()) { - totals.put(i, (masterWallClock / mtotals) * totals.get(i)); - } - - double v = 0; - - for(double i : weights.values()) { - v += i; - } - - for(String i : weights.k()) { - weights.put(i, weights.get(i) / v); - } - - sender.sendMessage("Total: " + C.BOLD + C.WHITE + Form.duration(masterWallClock, 0)); - - for(String i : totals.k()) { - sender.sendMessage(" Engine " + C.UNDERLINE + C.GREEN + i + C.RESET + ": " + C.BOLD + C.WHITE + Form.duration(totals.get(i), 0)); - } - - sender.sendMessage("Details: "); - - for(String i : weights.sortKNumber().reverse()) { - String befb = C.UNDERLINE + "" + C.GREEN + "" + i.split("\\Q[\\E")[0] + C.RESET + C.GRAY + "["; - String num = C.GOLD + i.split("\\Q[\\E")[1].split("]")[0] + C.RESET + C.GRAY + "]."; - String afb = C.ITALIC + "" + C.AQUA + i.split("\\Q]\\E")[1].substring(1) + C.RESET + C.GRAY; - - sender.sendMessage(" " + befb + num + afb + ": " + C.BOLD + C.WHITE + Form.pc(weights.get(i), 0)); - } - } - - @Override - public void close() { - PregeneratorJob.shutdownInstance(); - closed = true; - J.car(art); - getWorldManager().close(); - getTarget().close(); - saveEngineData(); - getMantle().close(); - getComplex().close(); - mode.close(); - getData().dump(); - getData().clearLists(); - Iris.service(PreservationSVC.class).dereference(); - Iris.debug("Engine Fully Shutdown!"); - complex = null; - } - - @Override - public boolean isClosed() { - return closed; - } - - @Override - public void recycle() { - if(!cleanLatch.flip()) { - return; - } - - if(cleaning.get()) { - cleanLatch.flipDown(); - return; - } - - cleaning.set(true); - - J.a(() -> { - try { - getMantle().trim(); - getData().getObjectLoader().clean(); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Cleanup failed! Enable debug to see stacktrace."); - } - - cleaning.lazySet(false); - }); - } - - @BlockCoordinates - @Override - public void generate(int x, int z, Hunk vblocks, Hunk vbiomes, boolean multicore) throws WrongEngineBroException { - if(closed) { - throw new WrongEngineBroException(); - } - - context.touch(); - getEngineData().getStatistics().generatedChunk(); - try { - PrecisionStopwatch p = PrecisionStopwatch.start(); - Hunk blocks = vblocks.listen((xx, y, zz, t) -> catchBlockUpdates(x + xx, y + getMinHeight(), z + zz, t)); - - if(getDimension().isDebugChunkCrossSections() && ((x >> 4) % getDimension().getDebugCrossSectionsMod() == 0 || (z >> 4) % getDimension().getDebugCrossSectionsMod() == 0)) { - for(int i = 0; i < 16; i++) { - for(int j = 0; j < 16; j++) { - blocks.set(i, 0, j, Material.CRYING_OBSIDIAN.createBlockData()); - } - } - } else { - mode.generate(x, z, blocks, vbiomes, multicore); - } - - getMantle().getMantle().flag(x >> 4, z >> 4, MantleFlag.REAL, true); - getMetrics().getTotal().put(p.getMilliseconds()); - generated.incrementAndGet(); - recycle(); - } catch(Throwable e) { - Iris.reportError(e); - fail("Failed to generate " + x + ", " + z, e); - } - } - - @Override - public void saveEngineData() { - //TODO: Method this file - File f = new File(getWorld().worldFolder(), "iris/engine-data/" + getDimension().getLoadKey() + ".json"); - f.getParentFile().mkdirs(); - try { - IO.writeAll(f, new Gson().toJson(getEngineData())); - Iris.debug("Saved Engine Data"); - } catch(IOException e) { - Iris.error("Failed to save Engine Data"); - e.printStackTrace(); - } - } - - @Override - public void blockUpdatedMetric() { - bud.incrementAndGet(); - } - - @Override - public IrisBiome getFocus() { - if(getDimension().getFocus() == null || getDimension().getFocus().trim().isEmpty()) { - return null; - } - - return getData().getBiomeLoader().load(getDimension().getFocus()); - } - - @Override - public IrisRegion getFocusRegion() { - if(getDimension().getFocusRegion() == null || getDimension().getFocusRegion().trim().isEmpty()) { - return null; - } - - return getData().getRegionLoader().load(getDimension().getFocusRegion()); - } - - @Override - public void fail(String error, Throwable e) { - failing = true; - Iris.error(error); - e.printStackTrace(); - } - - @Override - public boolean hasFailed() { - return failing; - } - - @Override - public int getCacheID() { - return cacheId; - } -} diff --git a/src/main/java/com/volmit/iris/engine/IrisEngineEffects.java b/src/main/java/com/volmit/iris/engine/IrisEngineEffects.java deleted file mode 100644 index 9ad5d6724..000000000 --- a/src/main/java/com/volmit/iris/engine/IrisEngineEffects.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedComponent; -import com.volmit.iris.engine.framework.EngineEffects; -import com.volmit.iris.engine.framework.EnginePlayer; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import org.bukkit.entity.Player; - -import java.util.List; -import java.util.UUID; -import java.util.concurrent.Semaphore; - -public class IrisEngineEffects extends EngineAssignedComponent implements EngineEffects { - private final KMap players; - private final Semaphore limit; - - public IrisEngineEffects(Engine engine) { - super(engine, "FX"); - players = new KMap<>(); - limit = new Semaphore(1); - } - - @Override - public void updatePlayerMap() { - List pr = getEngine().getWorld().getPlayers(); - - if(pr == null) { - return; - } - - for(Player i : pr) { - boolean pcc = players.containsKey(i.getUniqueId()); - if(!pcc) { - players.put(i.getUniqueId(), new EnginePlayer(getEngine(), i)); - } - } - - for(UUID i : players.k()) { - if(!pr.contains(players.get(i).getPlayer())) { - players.remove(i); - } - } - } - - @Override - public void tickRandomPlayer() { - if(limit.tryAcquire()) { - if(M.r(0.02)) { - updatePlayerMap(); - limit.release(); - return; - } - - if(players.isEmpty()) { - limit.release(); - return; - } - - double limitms = 1.5; - int max = players.size(); - PrecisionStopwatch p = new PrecisionStopwatch(); - - while(max-- > 0 && M.ms() - p.getMilliseconds() < limitms) { - players.v().getRandom().tick(); - } - - limit.release(); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/IrisEngineMantle.java b/src/main/java/com/volmit/iris/engine/IrisEngineMantle.java deleted file mode 100644 index 7e1ad4c01..000000000 --- a/src/main/java/com/volmit/iris/engine/IrisEngineMantle.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.engine.mantle.MantleComponent; -import com.volmit.iris.engine.mantle.components.MantleCarvingComponent; -import com.volmit.iris.engine.mantle.components.MantleFluidBodyComponent; -import com.volmit.iris.engine.mantle.components.MantleJigsawComponent; -import com.volmit.iris.engine.mantle.components.MantleObjectComponent; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDepositGenerator; -import com.volmit.iris.engine.object.IrisJigsawStructurePlacement; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.IrisObjectScale; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.parallel.BurstExecutor; -import lombok.Data; -import org.bukkit.util.BlockVector; - -import java.io.File; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -@Data -public class IrisEngineMantle implements EngineMantle { - private final Engine engine; - private final Mantle mantle; - private final KList components; - private final int radius; - private final AtomicCache radCache = new AtomicCache<>(); - private final MantleObjectComponent object; - private final MantleJigsawComponent jigsaw; - - public IrisEngineMantle(Engine engine) { - this.engine = engine; - this.mantle = new Mantle(new File(engine.getWorld().worldFolder(), "mantle"), engine.getTarget().getHeight()); - radius = radCache.aquire(this::computeParallaxSize); - components = new KList<>(); - registerComponent(new MantleCarvingComponent(this)); - registerComponent(new MantleFluidBodyComponent(this)); - jigsaw = new MantleJigsawComponent(this); - registerComponent(jigsaw); - object = new MantleObjectComponent(this); - registerComponent(object); - } - - @Override - public void registerComponent(MantleComponent c) { - components.add(c); - } - - @Override - public MantleJigsawComponent getJigsawComponent() { - return jigsaw; - } - - @Override - public MantleObjectComponent getObjectComponent() { - return object; - } - - private KList getAllRegions() { - KList r = new KList<>(); - - for(String i : getEngine().getDimension().getRegions()) { - r.add(getEngine().getData().getRegionLoader().load(i)); - } - - return r; - } - - private KList getAllBiomes() { - KList r = new KList<>(); - - for(IrisRegion i : getAllRegions()) { - r.addAll(i.getAllBiomes(getEngine())); - } - - return r; - } - - private void warn(String ob, BlockVector bv) { - if(Math.max(bv.getBlockX(), bv.getBlockZ()) > 128) { - Iris.warn("Object " + ob + " has a large size (" + bv + ") and may increase memory usage!"); - } - } - - private void warnScaled(String ob, BlockVector bv, double ms) { - if(Math.max(bv.getBlockX(), bv.getBlockZ()) > 128) { - Iris.warn("Object " + ob + " has a large size (" + bv + ") and may increase memory usage! (Object scaled up to " + Form.pc(ms, 2) + ")"); - } - } - - private int computeParallaxSize() { - Iris.verbose("Calculating the Parallax Size in Parallel"); - AtomicInteger xg = new AtomicInteger(0); - AtomicInteger zg = new AtomicInteger(); - xg.set(0); - zg.set(0); - int jig = 0; - KSet objects = new KSet<>(); - KMap> scalars = new KMap<>(); - int x = xg.get(); - int z = zg.get(); - - if(getEngine().getDimension().isUseMantle()) { - KList r = getAllRegions(); - KList b = getAllBiomes(); - - for(IrisBiome i : b) { - for(IrisObjectPlacement j : i.getObjects()) { - if(j.getScale().canScaleBeyond()) { - scalars.put(j.getScale(), j.getPlace()); - } else { - objects.addAll(j.getPlace()); - } - } - - for(IrisJigsawStructurePlacement j : i.getJigsawStructures()) { - jig = Math.max(jig, getData().getJigsawStructureLoader().load(j.getStructure()).getMaxDimension()); - } - } - - for(IrisRegion i : r) { - for(IrisObjectPlacement j : i.getObjects()) { - if(j.getScale().canScaleBeyond()) { - scalars.put(j.getScale(), j.getPlace()); - } else { - objects.addAll(j.getPlace()); - } - } - - for(IrisJigsawStructurePlacement j : i.getJigsawStructures()) { - jig = Math.max(jig, getData().getJigsawStructureLoader().load(j.getStructure()).getMaxDimension()); - } - } - - for(IrisJigsawStructurePlacement j : getEngine().getDimension().getJigsawStructures()) { - jig = Math.max(jig, getData().getJigsawStructureLoader().load(j.getStructure()).getMaxDimension()); - } - - if(getEngine().getDimension().getStronghold() != null) { - try { - jig = Math.max(jig, getData().getJigsawStructureLoader().load(getEngine().getDimension().getStronghold()).getMaxDimension()); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - Iris.verbose("Checking sizes for " + Form.f(objects.size()) + " referenced objects."); - BurstExecutor e = getEngine().getTarget().getBurster().burst(objects.size()); - KMap sizeCache = new KMap<>(); - for(String i : objects) { - e.queue(() -> { - try { - BlockVector bv = sizeCache.computeIfAbsent(i, (k) -> { - try { - return IrisObject.sampleSize(getData().getObjectLoader().findFile(i)); - } catch(IOException ex) { - Iris.reportError(ex); - ex.printStackTrace(); - } - - return null; - }); - - if(bv == null) { - throw new RuntimeException(); - } - - warn(i, bv); - - synchronized(xg) { - xg.getAndSet(Math.max(bv.getBlockX(), xg.get())); - } - - synchronized(zg) { - zg.getAndSet(Math.max(bv.getBlockZ(), zg.get())); - } - } catch(Throwable ed) { - Iris.reportError(ed); - - } - }); - } - - for(Map.Entry> entry : scalars.entrySet()) { - double ms = entry.getKey().getMaximumScale(); - for(String j : entry.getValue()) { - e.queue(() -> { - try { - BlockVector bv = sizeCache.computeIfAbsent(j, (k) -> { - try { - return IrisObject.sampleSize(getData().getObjectLoader().findFile(j)); - } catch(IOException ioException) { - Iris.reportError(ioException); - ioException.printStackTrace(); - } - - return null; - }); - - if(bv == null) { - throw new RuntimeException(); - } - - warnScaled(j, bv, ms); - - synchronized(xg) { - xg.getAndSet((int) Math.max(Math.ceil(bv.getBlockX() * ms), xg.get())); - } - - synchronized(zg) { - zg.getAndSet((int) Math.max(Math.ceil(bv.getBlockZ() * ms), zg.get())); - } - } catch(Throwable ee) { - Iris.reportError(ee); - - } - }); - } - } - - e.complete(); - - x = xg.get(); - z = zg.get(); - - for(IrisDepositGenerator i : getEngine().getDimension().getDeposits()) { - int max = i.getMaxDimension(); - x = Math.max(max, x); - z = Math.max(max, z); - } - - for(IrisRegion v : r) { - for(IrisDepositGenerator i : v.getDeposits()) { - int max = i.getMaxDimension(); - x = Math.max(max, x); - z = Math.max(max, z); - } - } - - for(IrisBiome v : b) { - for(IrisDepositGenerator i : v.getDeposits()) { - int max = i.getMaxDimension(); - x = Math.max(max, x); - z = Math.max(max, z); - } - } - } else { - return 0; - } - - x = Math.max(z, x); - int u = x; - int c = Math.max(computeCarvingRange(), computeBodyRange()); - x = Math.max(jig, x); - x = Math.max(x, c); - x = (Math.max(x, 16) + 16) >> 4; - x = x % 2 == 0 ? x + 1 : x; - Iris.info("Mantle Size: " + x + " Chunks"); - Iris.info(" Object Mantle Size: " + u + " (" + ((Math.max(u, 16) + 16) >> 4) + ")"); - Iris.info(" Jigsaw Mantle Size: " + jig + " (" + ((Math.max(jig, 16) + 16) >> 4) + ")"); - Iris.info(" Carving Mantle Size: " + c + " (" + ((Math.max(c, 16) + 16) >> 4) + ")"); - - return x; - } - - private int computeBodyRange() { - int m = 0; - - m = Math.max(m, getDimension().getFluidBodies().getMaxRange(getData())); - - for(IrisRegion i : getDimension().getAllRegions(getEngine())) { - m = Math.max(m, i.getFluidBodies().getMaxRange(getData())); - } - - for(IrisBiome i : getDimension().getAllBiomes(getEngine())) { - m = Math.max(m, i.getFluidBodies().getMaxRange(getData())); - } - - return m; - } - - private int computeCarvingRange() { - int m = 0; - - m = Math.max(m, getDimension().getCarving().getMaxRange(getData())); - - for(IrisRegion i : getDimension().getAllRegions(getEngine())) { - m = Math.max(m, i.getCarving().getMaxRange(getData())); - } - - for(IrisBiome i : getDimension().getAllBiomes(getEngine())) { - m = Math.max(m, i.getCarving().getMaxRange(getData())); - } - - return m; - } -} diff --git a/src/main/java/com/volmit/iris/engine/IrisExecutionEnvironment.java b/src/main/java/com/volmit/iris/engine/IrisExecutionEnvironment.java deleted file mode 100644 index 5a7d9d72d..000000000 --- a/src/main/java/com/volmit/iris/engine/IrisExecutionEnvironment.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisScript; -import com.volmit.iris.engine.scripting.EngineExecutionEnvironment; -import com.volmit.iris.engine.scripting.IrisScriptingAPI; -import com.volmit.iris.util.format.C; -import lombok.Data; -import org.apache.bsf.BSFException; -import org.apache.bsf.BSFManager; -import org.apache.bsf.engines.javascript.JavaScriptEngine; - -@Data -public class IrisExecutionEnvironment implements EngineExecutionEnvironment { - private final BSFManager manager; - private final Engine engine; - private final IrisScriptingAPI api; - private JavaScriptEngine javaScriptEngine; - - public IrisExecutionEnvironment(Engine engine) { - this.engine = engine; - this.api = new IrisScriptingAPI(engine); - this.manager = new BSFManager(); - this.manager.setClassLoader(Iris.class.getClassLoader()); - try { - this.manager.declareBean("Iris", api, api.getClass()); - this.javaScriptEngine = (JavaScriptEngine) this.manager.loadScriptingEngine("javascript"); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - @Override - public IrisScriptingAPI getAPI() { - return api; - } - - public void execute(String script) { - execute(getEngine().getData().getScriptLoader().load(script)); - } - - public void execute(IrisScript script) { - Iris.debug("Execute Script (void) " + C.DARK_GREEN + script.getLoadKey()); - try { - javaScriptEngine.exec("", 0, 0, script); - } catch(BSFException e) { - e.printStackTrace(); - } - } - - public Object evaluate(String script) { - Iris.debug("Execute Script (for result) " + C.DARK_GREEN + script); - try { - return javaScriptEngine.eval("", 0, 0, getEngine().getData().getScriptLoader().load(script)); - } catch(BSFException e) { - e.printStackTrace(); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/engine/IrisWorldManager.java b/src/main/java/com/volmit/iris/engine/IrisWorldManager.java deleted file mode 100644 index 9e3b9b6a3..000000000 --- a/src/main/java/com/volmit/iris/engine/IrisWorldManager.java +++ /dev/null @@ -1,710 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedWorldManager; -import com.volmit.iris.engine.object.IRare; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisBlockDrops; -import com.volmit.iris.engine.object.IrisEngineChunkData; -import com.volmit.iris.engine.object.IrisEngineData; -import com.volmit.iris.engine.object.IrisEngineSpawnerCooldown; -import com.volmit.iris.engine.object.IrisEntitySpawn; -import com.volmit.iris.engine.object.IrisMarker; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.engine.object.IrisSpawner; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterMarker; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.plugin.Chunks; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.Looper; -import com.volmit.iris.util.scheduling.jobs.QueueJob; -import io.papermc.lib.PaperLib; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.inventory.ItemStack; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -@EqualsAndHashCode(callSuper = true) -@Data -public class IrisWorldManager extends EngineAssignedWorldManager { - private final Looper looper; - private final int id; - private final KList updateQueue = new KList<>(); - private final ChronoLatch cl; - private final ChronoLatch clw; - private final ChronoLatch ecl; - private final ChronoLatch cln; - private final ChronoLatch chunkUpdater; - private double energy = 25; - private int entityCount = 0; - private long charge = 0; - private int actuallySpawned = 0; - private int cooldown = 0; - private List precount = new KList<>(); - - public IrisWorldManager() { - super(null); - cl = null; - ecl = null; - cln = null; - clw = null; - looper = null; - chunkUpdater = null; - id = -1; - } - - public IrisWorldManager(Engine engine) { - super(engine); - chunkUpdater = new ChronoLatch(3000); - cln = new ChronoLatch(60000); - cl = new ChronoLatch(3000); - ecl = new ChronoLatch(250); - clw = new ChronoLatch(1000, true); - id = engine.getCacheID(); - energy = 25; - looper = new Looper() { - @Override - protected long loop() { - if(getEngine().isClosed() || getEngine().getCacheID() != id) { - interrupt(); - } - - if(!getEngine().getWorld().hasRealWorld() && clw.flip()) { - getEngine().getWorld().tryGetRealWorld(); - } - - if(!IrisSettings.get().getWorld().isMarkerEntitySpawningSystem() && !IrisSettings.get().getWorld().isAnbientEntitySpawningSystem()) { - return 3000; - } - - if(getEngine().getWorld().hasRealWorld()) { - if(getEngine().getWorld().getPlayers().isEmpty()) { - return 5000; - } - - if(chunkUpdater.flip()) { - updateChunks(); - } - - - if(getDimension().isInfiniteEnergy()) { - energy += 1000; - fixEnergy(); - } - - if(M.ms() < charge) { - energy += 70; - fixEnergy(); - } - - if(cln.flip()) { - engine.getEngineData().cleanup(getEngine()); - } - - if(precount != null) { - entityCount = 0; - for(Entity i : precount) { - if(i instanceof LivingEntity) { - if(!i.isDead()) { - entityCount++; - } - } - } - - precount = null; - } - - if(energy < 650) { - if(ecl.flip()) { - energy *= 1 + (0.02 * M.clip((1D - getEntitySaturation()), 0D, 1D)); - fixEnergy(); - } - } - - onAsyncTick(); - } - - return IrisSettings.get().getWorld().getAsyncTickIntervalMS(); - } - }; - looper.setPriority(Thread.MIN_PRIORITY); - looper.setName("Iris World Manager"); - looper.start(); - } - - private void updateChunks() { - for(Player i : getEngine().getWorld().realWorld().getPlayers()) { - int r = 1; - - Chunk c = i.getLocation().getChunk(); - for(int x = -r; x <= r; x++) { - for(int z = -r; z <= r; z++) { - if(c.getWorld().isChunkLoaded(c.getX() + x, c.getZ() + z) && Chunks.isSafe(getEngine().getWorld().realWorld(), c.getX() + x, c.getZ() + z)) { - - if(IrisSettings.get().getWorld().isPostLoadBlockUpdates()) { - getEngine().updateChunk(c.getWorld().getChunkAt(c.getX() + x, c.getZ() + z)); - } - - if(IrisSettings.get().getWorld().isMarkerEntitySpawningSystem()) { - Chunk cx = getEngine().getWorld().realWorld().getChunkAt(c.getX() + x, c.getZ() + z); - int finalX = c.getX() + x; - int finalZ = c.getZ() + z; - J.a(() -> getMantle().raiseFlag(finalX, finalZ, MantleFlag.INITIAL_SPAWNED_MARKER, - () -> { - J.a(() -> spawnIn(cx, true), RNG.r.i(5, 200)); - getSpawnersFromMarkers(cx).forEach((blockf, spawners) -> { - if(spawners.isEmpty()) { - return; - } - - IrisPosition block = new IrisPosition(blockf.getX(), blockf.getY() + getEngine().getWorld().minHeight(), blockf.getZ()); - IrisSpawner s = new KList<>(spawners).getRandom(); - spawn(block, s, true); - }); - })); - } - } - } - } - } - } - - private boolean onAsyncTick() { - if(getEngine().isClosed()) { - return false; - } - - actuallySpawned = 0; - - if(energy < 100) { - J.sleep(200); - return false; - } - - if(!getEngine().getWorld().hasRealWorld()) { - Iris.debug("Can't spawn. No real world"); - J.sleep(5000); - return false; - } - - double epx = getEntitySaturation(); - if(epx > IrisSettings.get().getWorld().getTargetSpawnEntitiesPerChunk()) { - Iris.debug("Can't spawn. The entity per chunk ratio is at " + Form.pc(epx, 2) + " > 100% (total entities " + entityCount + ")"); - J.sleep(5000); - return false; - } - - if(cl.flip()) { - try { - J.s(() -> precount = getEngine().getWorld().realWorld().getEntities()); - } catch(Throwable e) { - close(); - } - } - - int spawnBuffer = RNG.r.i(2, 12); - - Chunk[] cc = getEngine().getWorld().realWorld().getLoadedChunks(); - while(spawnBuffer-- > 0) { - if(cc.length == 0) { - Iris.debug("Can't spawn. No chunks!"); - return false; - } - - Chunk c = cc[RNG.r.nextInt(cc.length)]; - - if(!c.isLoaded() || !Chunks.isSafe(c.getWorld(), c.getX(), c.getZ())) { - continue; - } - - spawnIn(c, false); - } - - energy -= (actuallySpawned / 2D); - return actuallySpawned > 0; - } - - private void fixEnergy() { - energy = M.clip(energy, 1D, getDimension().getMaximumEnergy()); - } - - private void spawnIn(Chunk c, boolean initial) { - if(getEngine().isClosed()) { - return; - } - - if(initial) { - energy += 1.2; - } - - //@builder - IrisBiome biome = IrisSettings.get().getWorld().isAnbientEntitySpawningSystem() - ? getEngine().getSurfaceBiome(c) : null; - IrisEntitySpawn v = IrisSettings.get().getWorld().isAnbientEntitySpawningSystem() - ? spawnRandomly(Stream.concat(getData().getSpawnerLoader() - .loadAll(getDimension().getEntitySpawners()) - .shuffleCopy(RNG.r).stream() - .filter(this::canSpawn) - .filter((i) -> i.isValid(biome)) - .flatMap((i) -> stream(i, initial)), - Stream.concat(getData().getSpawnerLoader() - .loadAll(getEngine().getRegion(c.getX() << 4, c.getZ() << 4).getEntitySpawners()) - .shuffleCopy(RNG.r).stream().filter(this::canSpawn) - .flatMap((i) -> stream(i, initial)), - getData().getSpawnerLoader() - .loadAll(getEngine().getSurfaceBiome(c.getX() << 4, c.getZ() << 4).getEntitySpawners()) - .shuffleCopy(RNG.r).stream().filter(this::canSpawn) - .flatMap((i) -> stream(i, initial)))) - .collect(Collectors.toList())) - .popRandom(RNG.r) : null; - //@done - - if(IrisSettings.get().getWorld().isMarkerEntitySpawningSystem()) { - getSpawnersFromMarkers(c).forEach((blockf, spawners) -> { - if(spawners.isEmpty()) { - return; - } - - IrisPosition block = new IrisPosition(blockf.getX(), blockf.getY() + getEngine().getWorld().minHeight(), blockf.getZ()); - IrisSpawner s = new KList<>(spawners).getRandom(); - spawn(block, s, false); - J.a(() -> getMantle().raiseFlag(c.getX(), c.getZ(), MantleFlag.INITIAL_SPAWNED_MARKER, - () -> spawn(block, s, true))); - }); - } - - if(v != null && v.getReferenceSpawner() != null) { - int maxEntCount = v.getReferenceSpawner().getMaxEntitiesPerChunk(); - - for(Entity i : c.getEntities()) { - if(i instanceof LivingEntity) { - if(-maxEntCount <= 0) { - return; - } - } - } - - try { - spawn(c, v); - } catch(Throwable e) { - J.s(() -> spawn(c, v)); - } - } - } - - private void spawn(Chunk c, IrisEntitySpawn i) { - boolean allow = true; - - if(!i.getReferenceSpawner().getMaximumRatePerChunk().isInfinite()) { - allow = false; - IrisEngineChunkData cd = getEngine().getEngineData().getChunk(c.getX(), c.getZ()); - IrisEngineSpawnerCooldown sc = null; - for(IrisEngineSpawnerCooldown j : cd.getCooldowns()) { - if(j.getSpawner().equals(i.getReferenceSpawner().getLoadKey())) { - sc = j; - break; - } - } - - if(sc == null) { - sc = new IrisEngineSpawnerCooldown(); - sc.setSpawner(i.getReferenceSpawner().getLoadKey()); - cd.getCooldowns().add(sc); - } - - if(sc.canSpawn(i.getReferenceSpawner().getMaximumRatePerChunk())) { - sc.spawn(getEngine()); - allow = true; - } - } - - if(allow) { - int s = i.spawn(getEngine(), c, RNG.r); - actuallySpawned += s; - if(s > 0) { - getCooldown(i.getReferenceSpawner()).spawn(getEngine()); - energy -= s * ((i.getEnergyMultiplier() * i.getReferenceSpawner().getEnergyMultiplier() * 1)); - } - } - } - - private void spawn(IrisPosition c, IrisEntitySpawn i) { - boolean allow = true; - - if(!i.getReferenceSpawner().getMaximumRatePerChunk().isInfinite()) { - allow = false; - IrisEngineChunkData cd = getEngine().getEngineData().getChunk(c.getX() >> 4, c.getZ() >> 4); - IrisEngineSpawnerCooldown sc = null; - for(IrisEngineSpawnerCooldown j : cd.getCooldowns()) { - if(j.getSpawner().equals(i.getReferenceSpawner().getLoadKey())) { - sc = j; - break; - } - } - - if(sc == null) { - sc = new IrisEngineSpawnerCooldown(); - sc.setSpawner(i.getReferenceSpawner().getLoadKey()); - cd.getCooldowns().add(sc); - } - - if(sc.canSpawn(i.getReferenceSpawner().getMaximumRatePerChunk())) { - sc.spawn(getEngine()); - allow = true; - } - } - - if(allow) { - int s = i.spawn(getEngine(), c, RNG.r); - actuallySpawned += s; - if(s > 0) { - getCooldown(i.getReferenceSpawner()).spawn(getEngine()); - energy -= s * ((i.getEnergyMultiplier() * i.getReferenceSpawner().getEnergyMultiplier() * 1)); - } - } - } - - private Stream stream(IrisSpawner s, boolean initial) { - for(IrisEntitySpawn i : initial ? s.getInitialSpawns() : s.getSpawns()) { - i.setReferenceSpawner(s); - i.setReferenceMarker(s.getReferenceMarker()); - } - - return (initial ? s.getInitialSpawns() : s.getSpawns()).stream(); - } - - private KList spawnRandomly(List types) { - KList rarityTypes = new KList<>(); - int totalRarity = 0; - - for(IrisEntitySpawn i : types) { - totalRarity += IRare.get(i); - } - - for(IrisEntitySpawn i : types) { - rarityTypes.addMultiple(i, totalRarity / IRare.get(i)); - } - - return rarityTypes; - } - - public boolean canSpawn(IrisSpawner i) { - return i.isValid(getEngine().getWorld().realWorld()) - && getCooldown(i).canSpawn(i.getMaximumRate()); - } - - private IrisEngineSpawnerCooldown getCooldown(IrisSpawner i) { - IrisEngineData ed = getEngine().getEngineData(); - IrisEngineSpawnerCooldown cd = null; - - for(IrisEngineSpawnerCooldown j : ed.getSpawnerCooldowns()) { - if(j.getSpawner().equals(i.getLoadKey())) { - cd = j; - } - } - - if(cd == null) { - cd = new IrisEngineSpawnerCooldown(); - cd.setSpawner(i.getLoadKey()); - cd.setLastSpawn(M.ms() - i.getMaximumRate().getInterval()); - ed.getSpawnerCooldowns().add(cd); - } - - return cd; - } - - @Override - public void onTick() { - - } - - @Override - public void onSave() { - getEngine().getMantle().save(); - } - - @Override - public void onChunkLoad(Chunk e, boolean generated) { - if(getEngine().isClosed()) { - return; - } - - energy += 0.3; - fixEnergy(); - getEngine().cleanupMantleChunk(e.getX(), e.getZ()); - } - - private void spawn(IrisPosition block, IrisSpawner spawner, boolean initial) { - if(getEngine().isClosed()) { - return; - } - - if(spawner == null) { - return; - } - - KList s = initial ? spawner.getInitialSpawns() : spawner.getSpawns(); - if(s.isEmpty()) { - return; - } - - IrisEntitySpawn ss = spawnRandomly(s).getRandom(); - ss.setReferenceSpawner(spawner); - ss.setReferenceMarker(spawner.getReferenceMarker()); - spawn(block, ss); - } - - public Mantle getMantle() { - return getEngine().getMantle().getMantle(); - } - - @Override - public void chargeEnergy() { - charge = M.ms() + 3000; - } - - @Override - public void teleportAsync(PlayerTeleportEvent e) { - if(IrisSettings.get().getWorld().getAsyncTeleport().isEnabled()) { - e.setCancelled(true); - warmupAreaAsync(e.getPlayer(), e.getTo(), () -> J.s(() -> { - ignoreTP.set(true); - e.getPlayer().teleport(e.getTo(), e.getCause()); - ignoreTP.set(false); - })); - } - } - - private void warmupAreaAsync(Player player, Location to, Runnable r) { - J.a(() -> { - int viewDistance = IrisSettings.get().getWorld().getAsyncTeleport().getLoadViewDistance(); - KList> futures = new KList<>(); - for(int i = -viewDistance; i <= viewDistance; i++) { - for(int j = -viewDistance; j <= viewDistance; j++) { - int finalJ = j; - int finalI = i; - - if(to.getWorld().isChunkLoaded((to.getBlockX() >> 4) + i, (to.getBlockZ() >> 4) + j)) { - futures.add(CompletableFuture.completedFuture(null)); - continue; - } - - futures.add(MultiBurst.burst.completeValue(() - -> PaperLib.getChunkAtAsync(to.getWorld(), - (to.getBlockX() >> 4) + finalI, - (to.getBlockZ() >> 4) + finalJ, - true, IrisSettings.get().getWorld().getAsyncTeleport().isUrgent()).get())); - } - } - - new QueueJob>() { - @Override - public void execute(Future chunkFuture) { - try { - chunkFuture.get(); - } catch(InterruptedException | ExecutionException e) { - - } - } - - @Override - public String getName() { - return "Loading Chunks"; - } - }.queue(futures).execute(new VolmitSender(player), true, r); - }); - } - - public Map> getSpawnersFromMarkers(Chunk c) { - Map> p = new KMap<>(); - Set b = new KSet<>(); - getMantle().iterateChunk(c.getX(), c.getZ(), MatterMarker.class, (x, y, z, t) -> { - if(t.getTag().equals("cave_floor") || t.getTag().equals("cave_ceiling")) { - return; - } - - IrisMarker mark = getData().getMarkerLoader().load(t.getTag()); - IrisPosition pos = new IrisPosition((c.getX() << 4) + x, y, (c.getZ() << 4) + z); - - if(mark.isEmptyAbove()) { - AtomicBoolean remove = new AtomicBoolean(false); - - try { - J.sfut(() -> { - if(c.getBlock(x, y + 1, z).getBlockData().getMaterial().isSolid() || c.getBlock(x, y + 2, z).getBlockData().getMaterial().isSolid()) { - remove.set(true); - } - }).get(); - } catch(InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - - if(remove.get()) { - b.add(pos); - return; - } - } - - for(String i : mark.getSpawners()) { - IrisSpawner m = getData().getSpawnerLoader().load(i); - m.setReferenceMarker(mark); - - // This is so fucking incorrect its a joke - //noinspection ConstantConditions - if(m != null) { - p.computeIfAbsent(pos, (k) -> new KSet<>()).add(m); - } - } - }); - - for(IrisPosition i : b) { - getEngine().getMantle().getMantle().remove(i.getX(), i.getY(), i.getZ(), MatterMarker.class); - } - - return p; - } - - @Override - public void onBlockBreak(BlockBreakEvent e) { - if(e.getBlock().getWorld().equals(getTarget().getWorld().realWorld())) { - - J.a(() -> { - MatterMarker marker = getMantle().get(e.getBlock().getX(), e.getBlock().getY(), e.getBlock().getZ(), MatterMarker.class); - - if(marker != null) { - if(marker.getTag().equals("cave_floor") || marker.getTag().equals("cave_ceiling")) { - return; - } - - IrisMarker mark = getData().getMarkerLoader().load(marker.getTag()); - - if(mark == null || mark.isRemoveOnChange()) { - getMantle().remove(e.getBlock().getX(), e.getBlock().getY(), e.getBlock().getZ(), MatterMarker.class); - } - } - }); - - KList d = new KList<>(); - Runnable drop = () -> J.s(() -> d.forEach((i) -> e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation().clone().add(0.5, 0.5, 0.5), i))); - IrisBiome b = getEngine().getBiome(e.getBlock().getLocation()); - - if(dropItems(e, d, drop, b.getBlockDrops(), b)) { - return; - } - - IrisRegion r = getEngine().getRegion(e.getBlock().getLocation()); - - if(dropItems(e, d, drop, r.getBlockDrops(), b)) { - return; - } - - for(IrisBlockDrops i : getEngine().getDimension().getBlockDrops()) { - if(i.shouldDropFor(e.getBlock().getBlockData(), getData())) { - if(i.isReplaceVanillaDrops()) { - e.setDropItems(false); - } - - i.fillDrops(false, d); - - if(i.isSkipParents()) { - drop.run(); - return; - } - } - } - } - } - - private boolean dropItems(BlockBreakEvent e, KList d, Runnable drop, KList blockDrops, IrisBiome b) { - for(IrisBlockDrops i : blockDrops) { - if(i.shouldDropFor(e.getBlock().getBlockData(), getData())) { - if(i.isReplaceVanillaDrops()) { - e.setDropItems(false); - } - - i.fillDrops(false, d); - - if(i.isSkipParents()) { - drop.run(); - return true; - } - } - } - return false; - } - - @Override - public void onBlockPlace(BlockPlaceEvent e) { - - } - - @Override - public void close() { - super.close(); - looper.interrupt(); - } - - @Override - public int getChunkCount() { - return getEngine().getWorld().realWorld().getLoadedChunks().length; - } - - @Override - public double getEntitySaturation() { - if(!getEngine().getWorld().hasRealWorld()) { - return 1; - } - - return (double) entityCount / (getEngine().getWorld().realWorld().getLoadedChunks().length + 1) * 1.28; - } -} diff --git a/src/main/java/com/volmit/iris/engine/actuator/IrisBiomeActuator.java b/src/main/java/com/volmit/iris/engine/actuator/IrisBiomeActuator.java deleted file mode 100644 index d3634c91e..000000000 --- a/src/main/java/com/volmit/iris/engine/actuator/IrisBiomeActuator.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.actuator; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.engine.data.chunk.TerrainChunk; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedActuator; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisBiomeCustom; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.hunk.view.BiomeGridHunkView; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import io.papermc.lib.PaperLib; -import org.bukkit.block.Biome; -import org.bukkit.generator.ChunkGenerator; - -public class IrisBiomeActuator extends EngineAssignedActuator { - private final RNG rng; - private final ChronoLatch cl = new ChronoLatch(5000); - - public IrisBiomeActuator(Engine engine) { - super(engine, "Biome"); - rng = new RNG(engine.getSeedManager().getBiome()); - } - - @BlockCoordinates - private boolean injectBiome(Hunk h, int x, int y, int z, Object bb) { - try { - if(h instanceof BiomeGridHunkView hh) { - ChunkGenerator.BiomeGrid g = hh.getChunk(); - if(g instanceof TerrainChunk) { - ((TerrainChunk) g).getBiomeBaseInjector().setBiome(x, y, z, bb); - } else { - hh.forceBiomeBaseInto(x, y, z, bb); - } - return true; - } - } catch(Throwable e) { - e.printStackTrace(); - } - - return false; - } - - @BlockCoordinates - @Override - public void onActuate(int x, int z, Hunk h, boolean multicore) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - BurstExecutor burst = burst().burst(PaperLib.isPaper() && multicore); - - for(int xf = 0; xf < h.getWidth(); xf++) { - int finalXf = xf; - burst.queue(() -> { - IrisBiome ib; - for(int zf = 0; zf < h.getDepth(); zf++) { - ib = getComplex().getTrueBiomeStream().get(finalXf + x, zf + z); - int maxHeight = (int) (getComplex().getFluidHeight() + ib.getMaxWithObjectHeight(getData())); - if(ib.isCustom()) { - try { - IrisBiomeCustom custom = ib.getCustomBiome(rng, x, 0, z); - Object biomeBase = INMS.get().getCustomBiomeBaseHolderFor(getDimension().getLoadKey() + ":" + custom.getId()); - - if(biomeBase == null || !injectBiome(h, x, 0, z, biomeBase)) { - throw new RuntimeException("Cant inject biome!"); - } - - for(int i = 0; i < maxHeight; i++) { - injectBiome(h, finalXf, i, zf, biomeBase); - } - } catch(Throwable e) { - Iris.reportError(e); - Biome v = ib.getSkyBiome(rng, x, 0, z); - for(int i = 0; i < maxHeight; i++) { - h.set(finalXf, i, zf, v); - } - } - } else { - Biome v = ib.getSkyBiome(rng, x, 0, z); - - if(v != null) { - for(int i = 0; i < maxHeight; i++) { - h.set(finalXf, i, zf, v); - } - } else if(cl.flip()) { - Iris.error("No biome provided for " + ib.getLoadKey()); - } - } - } - }); - } - - burst.complete(); - getEngine().getMetrics().getBiome().put(p.getMilliseconds()); - } -} diff --git a/src/main/java/com/volmit/iris/engine/actuator/IrisDecorantActuator.java b/src/main/java/com/volmit/iris/engine/actuator/IrisDecorantActuator.java deleted file mode 100644 index af9f0aa87..000000000 --- a/src/main/java/com/volmit/iris/engine/actuator/IrisDecorantActuator.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.actuator; - -import com.volmit.iris.engine.decorator.IrisCeilingDecorator; -import com.volmit.iris.engine.decorator.IrisSeaFloorDecorator; -import com.volmit.iris.engine.decorator.IrisSeaSurfaceDecorator; -import com.volmit.iris.engine.decorator.IrisShoreLineDecorator; -import com.volmit.iris.engine.decorator.IrisSurfaceDecorator; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedActuator; -import com.volmit.iris.engine.framework.EngineDecorator; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.Getter; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; - -import java.util.function.Predicate; - -public class IrisDecorantActuator extends EngineAssignedActuator { - private static final Predicate PREDICATE_SOLID = (b) -> b != null && !b.getMaterial().isAir() && !b.getMaterial().equals(Material.WATER) && !b.getMaterial().equals(Material.LAVA); - private final RNG rng; - @Getter - private final EngineDecorator surfaceDecorator; - @Getter - private final EngineDecorator ceilingDecorator; - @Getter - private final EngineDecorator seaSurfaceDecorator; - @Getter - private final EngineDecorator seaFloorDecorator; - @Getter - private final EngineDecorator shoreLineDecorator; - private final boolean shouldRay; - - public IrisDecorantActuator(Engine engine) { - super(engine, "Decorant"); - shouldRay = shouldRayDecorate(); - this.rng = new RNG(engine.getSeedManager().getDecorator()); - surfaceDecorator = new IrisSurfaceDecorator(getEngine()); - ceilingDecorator = new IrisCeilingDecorator(getEngine()); - seaSurfaceDecorator = new IrisSeaSurfaceDecorator(getEngine()); - shoreLineDecorator = new IrisShoreLineDecorator(getEngine()); - seaFloorDecorator = new IrisSeaFloorDecorator(getEngine()); - } - - @BlockCoordinates - @Override - public void onActuate(int x, int z, Hunk output, boolean multicore) { - if(!getEngine().getDimension().isDecorate()) { - return; - } - - PrecisionStopwatch p = PrecisionStopwatch.start(); - BurstExecutor burst = burst().burst(multicore); - - for(int i = 0; i < output.getWidth(); i++) { - int finalI = i; - burst.queue(() -> { - int height; - int realX = Math.round(x + finalI); - int realZ; - IrisBiome biome, cave; - for(int j = 0; j < output.getDepth(); j++) { - boolean solid; - int emptyFor = 0; - int lastSolid = 0; - realZ = Math.round(z + j); - height = (int) Math.round(getComplex().getHeightStream().get(realX, realZ)); - biome = getComplex().getTrueBiomeStream().get(realX, realZ); - cave = shouldRay ? getComplex().getCaveBiomeStream().get(realX, realZ) : null; - - if(biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) { - continue; - } - - if(height < getDimension().getFluidHeight()) { - getSeaSurfaceDecorator().decorate(finalI, j, - realX, Math.round(finalI + 1), Math.round(x + finalI - 1), - realZ, Math.round(z + j + 1), Math.round(z + j - 1), - output, biome, getDimension().getFluidHeight(), getEngine().getHeight()); - getSeaFloorDecorator().decorate(finalI, j, - realX, realZ, output, biome, height + 1, - getDimension().getFluidHeight() + 1); - } - - if(height == getDimension().getFluidHeight()) { - getShoreLineDecorator().decorate(finalI, j, - realX, Math.round(x + finalI + 1), Math.round(x + finalI - 1), - realZ, Math.round(z + j + 1), Math.round(z + j - 1), - output, biome, height, getEngine().getHeight()); - } - - getSurfaceDecorator().decorate(finalI, j, realX, realZ, output, biome, height, getEngine().getHeight() - height); - - - if(cave != null && cave.getDecorators().isNotEmpty()) { - for(int k = height; k > 0; k--) { - solid = PREDICATE_SOLID.test(output.get(finalI, k, j)); - - if(solid) { - if(emptyFor > 0) { - getSurfaceDecorator().decorate(finalI, j, realX, realZ, output, cave, k, lastSolid); - getCeilingDecorator().decorate(finalI, j, realX, realZ, output, cave, lastSolid - 1, emptyFor); - emptyFor = 0; - } - lastSolid = k; - } else { - emptyFor++; - } - } - } - } - }); - } - - burst.complete(); - getEngine().getMetrics().getDecoration().put(p.getMilliseconds()); - - } - - private boolean shouldRayDecorate() { - return false; // TODO CAVES - } -} diff --git a/src/main/java/com/volmit/iris/engine/actuator/IrisTerrainNormalActuator.java b/src/main/java/com/volmit/iris/engine/actuator/IrisTerrainNormalActuator.java deleted file mode 100644 index 23624d976..000000000 --- a/src/main/java/com/volmit/iris/engine/actuator/IrisTerrainNormalActuator.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.actuator; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedActuator; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.Getter; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; - -public class IrisTerrainNormalActuator extends EngineAssignedActuator { - private static final BlockData AIR = Material.AIR.createBlockData(); - private static final BlockData BEDROCK = Material.BEDROCK.createBlockData(); - private static final BlockData LAVA = Material.LAVA.createBlockData(); - private static final BlockData GLASS = Material.GLASS.createBlockData(); - private static final BlockData CAVE_AIR = Material.CAVE_AIR.createBlockData(); - @Getter - private final RNG rng; - @Getter - private int lastBedrock = -1; - - public IrisTerrainNormalActuator(Engine engine) { - super(engine, "Terrain"); - rng = new RNG(engine.getSeedManager().getTerrain()); - } - - @BlockCoordinates - @Override - public void onActuate(int x, int z, Hunk h, boolean multicore) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - - BurstExecutor e = burst().burst(multicore); - for(int xf = 0; xf < h.getWidth(); xf++) { - int finalXf = xf; - e.queue(() -> terrainSliver(x, z, finalXf, h)); - } - - e.complete(); - - getEngine().getMetrics().getTerrain().put(p.getMilliseconds()); - } - - private int fluidOrHeight(int height) { - return Math.max(getDimension().getFluidHeight(), height); - } - - /** - * This is calling 1/16th of a chunk x/z slice. It is a plane from sky to bedrock 1 thick in the x direction. - * - * @param x - * the chunk x in blocks - * @param z - * the chunk z in blocks - * @param xf - * the current x slice - * @param h - * the blockdata - */ - @BlockCoordinates - public void terrainSliver(int x, int z, int xf, Hunk h) { - int zf, realX, realZ, hf, he; - IrisBiome biome; - IrisRegion region; - - for(zf = 0; zf < h.getDepth(); zf++) { - realX = xf + x; - realZ = zf + z; - biome = getComplex().getTrueBiomeStream().get(realX, realZ); - region = getComplex().getRegionStream().get(realX, realZ); - he = (int) Math.round(Math.min(h.getHeight(), getComplex().getHeightStream().get(realX, realZ))); - hf = Math.round(Math.max(Math.min(h.getHeight(), getDimension().getFluidHeight()), he)); - - if(hf < 0) { - continue; - } - - KList blocks = null; - KList fblocks = null; - int depth, fdepth; - for(int i = hf; i >= 0; i--) { - if(i >= h.getHeight()) { - continue; - } - - if(i == 0) { - if(getDimension().isBedrock()) { - h.set(xf, i, zf, BEDROCK); - lastBedrock = i; - continue; - } - } - - if(i > he && i <= hf) { - fdepth = hf - i; - - if(fblocks == null) { - fblocks = biome.generateSeaLayers(realX, realZ, rng, hf - he, getData()); - } - - if(fblocks.hasIndex(fdepth)) { - h.set(xf, i, zf, fblocks.get(fdepth)); - continue; - } - - h.set(xf, i, zf, getComplex().getFluidStream().get(realX, +realZ)); - continue; - } - - if(i <= he) { - depth = he - i; - if(blocks == null) { - blocks = biome.generateLayers(getDimension(), realX, realZ, rng, - he, - he, - getData(), - getComplex()); - } - - - if(blocks.hasIndex(depth)) { - h.set(xf, i, zf, blocks.get(depth)); - continue; - } - - BlockData ore = biome.generateOres(realX, i, realZ, rng, getData()); - ore = ore == null ? region.generateOres(realX, i, realZ, rng, getData()) : ore; - ore = ore == null ? getDimension().generateOres(realX, i, realZ, rng, getData()) : ore; - - if(ore != null) { - h.set(xf, i, zf, ore); - } else { - h.set(xf, i, zf, getComplex().getRockStream().get(realX, realZ)); - } - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/data/cache/AtomicCache.java b/src/main/java/com/volmit/iris/engine/data/cache/AtomicCache.java deleted file mode 100644 index 5f69b7a1f..000000000 --- a/src/main/java/com/volmit/iris/engine/data/cache/AtomicCache.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.cache; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.function.NastySupplier; - -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Supplier; - -public class AtomicCache { - private transient final AtomicReference t; - private transient final AtomicBoolean set; - private transient final ReentrantLock lock; - private transient final boolean nullSupport; - - public AtomicCache() { - this(false); - } - - public AtomicCache(boolean nullSupport) { - set = nullSupport ? new AtomicBoolean() : null; - t = new AtomicReference<>(); - lock = new ReentrantLock(); - this.nullSupport = nullSupport; - } - - public void reset() { - t.set(null); - - if(nullSupport) { - set.set(false); - } - } - - public T aquireNasty(NastySupplier t) { - return aquire(() -> { - try { - return t.get(); - } catch(Throwable e) { - return null; - } - }); - } - - public T aquireNastyPrint(NastySupplier t) { - return aquire(() -> { - try { - return t.get(); - } catch(Throwable e) { - e.printStackTrace(); - return null; - } - }); - } - - public T aquire(Supplier t) { - if(this.t.get() != null) { - return this.t.get(); - } else if(nullSupport && set.get()) { - return null; - } - - lock.lock(); - - if(this.t.get() != null) { - lock.unlock(); - return this.t.get(); - } else if(nullSupport && set.get()) { - lock.unlock(); - return null; - } - - try { - this.t.set(t.get()); - - if(nullSupport) { - set.set(true); - } - } catch(Throwable e) { - Iris.error("Atomic cache failure!"); - e.printStackTrace(); - } - - lock.unlock(); - - return this.t.get(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/data/cache/Cache.java b/src/main/java/com/volmit/iris/engine/data/cache/Cache.java deleted file mode 100644 index fa10c5dbb..000000000 --- a/src/main/java/com/volmit/iris/engine/data/cache/Cache.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.cache; - -import org.bukkit.Chunk; - -public interface Cache { - static long key(Chunk chunk) { - return key(chunk.getX(), chunk.getZ()); - } - - static long key(int x, int z) { - return (((long) x) << 32) | (z & 0xffffffffL); - } - - static int keyX(long key) { - return (int) (key >> 32); - } - - static int keyZ(long key) { - return (int) key; - } - - static int to1D(int x, int y, int z, int w, int h) { - return (z * w * h) + (y * w) + x; - } - - static int[] to3D(int idx, int w, int h) { - final int z = idx / (w * h); - idx -= (z * w * h); - final int y = idx / w; - final int x = idx % w; - return new int[] {x, y, z}; - } - - int getId(); - - V get(int x, int z); -} diff --git a/src/main/java/com/volmit/iris/engine/data/cache/Multicache.java b/src/main/java/com/volmit/iris/engine/data/cache/Multicache.java deleted file mode 100644 index e81b63ac4..000000000 --- a/src/main/java/com/volmit/iris/engine/data/cache/Multicache.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.cache; - -public interface Multicache { - Cache getCache(int id); - - Cache createCache(); -} - \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/engine/data/chunk/LinkedTerrainChunk.java b/src/main/java/com/volmit/iris/engine/data/chunk/LinkedTerrainChunk.java deleted file mode 100644 index 38e9535b4..000000000 --- a/src/main/java/com/volmit/iris/engine/data/chunk/LinkedTerrainChunk.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.chunk; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.BiomeBaseInjector; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.util.data.IrisBiomeStorage; -import lombok.Setter; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; -import org.bukkit.generator.ChunkGenerator.ChunkData; -import org.bukkit.material.MaterialData; - -@SuppressWarnings("deprecation") -public class LinkedTerrainChunk implements TerrainChunk { - private final IrisBiomeStorage biome3D; - private final BiomeGrid storage; - private ChunkData rawChunkData; - @Setter - private boolean unsafe = false; - - public LinkedTerrainChunk(World world) { - this(null, Bukkit.createChunkData(world)); - } - - public LinkedTerrainChunk(World world, BiomeGrid storage) { - this(storage, Bukkit.createChunkData(world)); - } - - public LinkedTerrainChunk(BiomeGrid storage, ChunkData data) { - this.storage = storage; - rawChunkData = data; - biome3D = storage != null ? null : new IrisBiomeStorage(); - } - - @Override - public BiomeBaseInjector getBiomeBaseInjector() { - - if(unsafe) { - return (a, b, c, d) -> { - }; - } - - return (x, y, z, bb) -> INMS.get().forceBiomeInto(x, y, z, bb, storage); - } - - - @Override - public Biome getBiome(int x, int z) { - if(storage != null) { - return storage.getBiome(x, z); - } - - return biome3D.getBiome(x, 0, z); - } - - - @Override - public Biome getBiome(int x, int y, int z) { - if(storage != null) { - return storage.getBiome(x, y, z); - } - - return biome3D.getBiome(x, y, z); - } - - @Override - public void setBiome(int x, int z, Biome bio) { - if(storage != null) { - storage.setBiome(x, z, bio); - return; - } - - biome3D.setBiome(x, 0, z, bio); - } - - public BiomeGrid getRawBiome() { - return storage; - } - - @Override - public void setBiome(int x, int y, int z, Biome bio) { - if(storage != null) { - storage.setBiome(x, y, z, bio); - return; - } - - biome3D.setBiome(x, y, z, bio); - } - - @Override - public int getMinHeight() { - return rawChunkData.getMinHeight(); - } - - @Override - public int getMaxHeight() { - return rawChunkData.getMaxHeight(); - } - - @Override - public synchronized void setBlock(int x, int y, int z, BlockData blockData) { - rawChunkData.setBlock(x, y, z, blockData); - } - - - @Override - public BlockData getBlockData(int x, int y, int z) { - return rawChunkData.getBlockData(x, y, z); - } - - @Deprecated - @Override - public synchronized void setBlock(int x, int y, int z, Material material) { - rawChunkData.setBlock(x, y, z, material); - } - - @Deprecated - @Override - public synchronized void setBlock(int x, int y, int z, MaterialData material) { - rawChunkData.setBlock(x, y, z, material); - } - - @Deprecated - @Override - public synchronized void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material) { - rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material); - } - - @Deprecated - @Override - public synchronized void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material) { - rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material); - } - - @Override - public synchronized void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockData blockData) { - rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, blockData); - } - - - @Deprecated - @Override - public synchronized Material getType(int x, int y, int z) { - return rawChunkData.getType(x, y, z); - } - - - @Deprecated - @Override - public MaterialData getTypeAndData(int x, int y, int z) { - return rawChunkData.getTypeAndData(x, y, z); - } - - @Deprecated - @Override - public byte getData(int x, int y, int z) { - return rawChunkData.getData(x, y, z); - } - - @Override - public ChunkData getRaw() { - return rawChunkData; - } - - @Override - public void setRaw(ChunkData data) { - rawChunkData = data; - } - - @Override - public void inject(BiomeGrid biome) { - if(biome3D != null) { - biome3D.inject(biome); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/data/chunk/MCATerrainChunk.java b/src/main/java/com/volmit/iris/engine/data/chunk/MCATerrainChunk.java deleted file mode 100644 index 836bcaddf..000000000 --- a/src/main/java/com/volmit/iris/engine/data/chunk/MCATerrainChunk.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.chunk; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.BiomeBaseInjector; -import com.volmit.iris.util.nbt.mca.Chunk; -import com.volmit.iris.util.nbt.mca.NBTWorld; -import lombok.AllArgsConstructor; -import lombok.Builder; -import org.bukkit.Material; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.material.MaterialData; - -@Builder -@AllArgsConstructor -public class MCATerrainChunk implements TerrainChunk { - private final NBTWorld writer; - private final BiomeBaseInjector injector; - private final int ox; - private final int oz; - private final int minHeight; - private final int maxHeight; - private final Chunk mcaChunk; - - @Override - public BiomeBaseInjector getBiomeBaseInjector() { - return injector; - } - - @Override - public Biome getBiome(int x, int z) { - return Biome.THE_VOID; - } - - @Override - public Biome getBiome(int x, int y, int z) { - return Biome.THE_VOID; - } - - @Override - public void setBiome(int x, int z, Biome bio) { - setBiome(ox + x, 0, oz + z, bio); - } - - @Override - public void setBiome(int x, int y, int z, Biome bio) { - mcaChunk.setBiomeAt((ox + x) & 15, y, (oz + z) & 15, writer.getBiomeId(bio)); - } - - @Override - public int getMinHeight() { - return minHeight; - } - - @Override - public int getMaxHeight() { - return maxHeight; - } - - @Override - public void setBlock(int x, int y, int z, BlockData blockData) { - int xx = (x + ox) & 15; - int zz = (z + oz) & 15; - - if(y > getMaxHeight() || y < getMinHeight()) { - return; - } - - if(blockData == null) { - Iris.error("NULL BD"); - } - - mcaChunk.setBlockStateAt(xx, y, zz, NBTWorld.getCompound(blockData), false); - } - - @Override - public org.bukkit.block.data.BlockData getBlockData(int x, int y, int z) { - if(y > getMaxHeight()) { - y = getMaxHeight(); - } - - if(y < getMinHeight()) { - y = getMinHeight(); - } - - return NBTWorld.getBlockData(mcaChunk.getBlockStateAt((x + ox) & 15, y, (z + oz) & 15)); - } - - @Override - public ChunkGenerator.ChunkData getRaw() { - return null; - } - - @Override - public void setRaw(ChunkGenerator.ChunkData data) { - - } - - @Override - public void inject(ChunkGenerator.BiomeGrid biome) { - - } - - @Override - public void setBlock(int x, int y, int z, Material material) { - - } - - @Override - public void setBlock(int x, int y, int z, MaterialData material) { - - } - - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material) { - - } - - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material) { - - } - - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockData blockData) { - - } - - - @Override - public Material getType(int x, int y, int z) { - return null; - } - - - @Override - public MaterialData getTypeAndData(int x, int y, int z) { - return null; - } - - @Override - public byte getData(int x, int y, int z) { - return 0; - } -} diff --git a/src/main/java/com/volmit/iris/engine/data/chunk/TerrainChunk.java b/src/main/java/com/volmit/iris/engine/data/chunk/TerrainChunk.java deleted file mode 100644 index 36a6508fe..000000000 --- a/src/main/java/com/volmit/iris/engine/data/chunk/TerrainChunk.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.chunk; - -import com.volmit.iris.core.nms.BiomeBaseInjector; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; -import org.bukkit.generator.ChunkGenerator.ChunkData; - -public interface TerrainChunk extends BiomeGrid, ChunkData { - static TerrainChunk create(World world) { - return new LinkedTerrainChunk(world); - } - - static TerrainChunk create(World world, BiomeGrid grid) { - return new LinkedTerrainChunk(world, grid); - } - - static TerrainChunk createUnsafe(World world, BiomeGrid grid) { - LinkedTerrainChunk ltc = new LinkedTerrainChunk(world, grid); - ltc.setUnsafe(true); - return ltc; - } - - static TerrainChunk create(ChunkData raw, BiomeGrid grid) { - return new LinkedTerrainChunk(grid, raw); - } - - BiomeBaseInjector getBiomeBaseInjector(); - - /** - * Get biome at x, z within chunk being generated - * - * @param x - * - 0-15 - * @param z - * - 0-15 - * @return Biome value - * @deprecated biomes are now 3-dimensional - */ - - @Deprecated - Biome getBiome(int x, int z); - - /** - * Get biome at x, z within chunk being generated - * - * @param x - * - 0-15 - * @param y - * - 0-255 - * @param z - * - 0-15 - * @return Biome value - */ - Biome getBiome(int x, int y, int z); - - /** - * Set biome at x, z within chunk being generated - * - * @param x - * - 0-15 - * @param z - * - 0-15 - * @param bio - * - Biome value - * @deprecated biomes are now 3-dimensional - */ - @Deprecated - void setBiome(int x, int z, Biome bio); - - /** - * Set biome at x, z within chunk being generated - * - * @param x - * - 0-15 - * @param y - * - 0-255 - * @param z - * - 0-15 - * @param bio - * - Biome value - */ - void setBiome(int x, int y, int z, Biome bio); - - /** - * Get the maximum height for the chunk. - *

- * Setting blocks at or above this height will do nothing. - * - * @return the maximum height - */ - int getMaxHeight(); - - /** - * Set the block at x,y,z in the chunk data to material. - *

- * Setting blocks outside the chunk's bounds does nothing. - * - * @param x - * the x location in the chunk from 0-15 inclusive - * @param y - * the y location in the chunk from 0 (inclusive) - maxHeight - * (exclusive) - * @param z - * the z location in the chunk from 0-15 inclusive - * @param blockData - * the type to set the block to - */ - void setBlock(int x, int y, int z, BlockData blockData); - - /** - * Get the type and data of the block at x, y, z. - *

- * Getting blocks outside the chunk's bounds returns air. - * - * @param x - * the x location in the chunk from 0-15 inclusive - * @param y - * the y location in the chunk from 0 (inclusive) - maxHeight - * (exclusive) - * @param z - * the z location in the chunk from 0-15 inclusive - * @return the data of the block or the BlockData for air if x, y or z are - * outside the chunk's bounds - */ - BlockData getBlockData(int x, int y, int z); - - ChunkData getRaw(); - - void setRaw(ChunkData data); - - void inject(BiomeGrid biome); -} diff --git a/src/main/java/com/volmit/iris/engine/data/io/Deserializer.java b/src/main/java/com/volmit/iris/engine/data/io/Deserializer.java deleted file mode 100644 index 5c758f97e..000000000 --- a/src/main/java/com/volmit/iris/engine/data/io/Deserializer.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.io; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; - -public interface Deserializer { - - T fromStream(InputStream stream) throws IOException; - - default T fromFile(File file) throws IOException { - try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { - return fromStream(bis); - } - } - - default T fromBytes(byte[] data) throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream(data); - return fromStream(stream); - } - - default T fromResource(Class clazz, String path) throws IOException { - try(InputStream stream = clazz.getClassLoader().getResourceAsStream(path)) { - if(stream == null) { - throw new IOException("resource \"" + path + "\" not found"); - } - return fromStream(stream); - } - } - - default T fromURL(URL url) throws IOException { - try(InputStream stream = url.openStream()) { - return fromStream(stream); - } - } - - -} diff --git a/src/main/java/com/volmit/iris/engine/data/io/ExceptionBiFunction.java b/src/main/java/com/volmit/iris/engine/data/io/ExceptionBiFunction.java deleted file mode 100644 index 1ac520d59..000000000 --- a/src/main/java/com/volmit/iris/engine/data/io/ExceptionBiFunction.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.io; - -@FunctionalInterface -public interface ExceptionBiFunction { - - R accept(T t, U u) throws E; -} diff --git a/src/main/java/com/volmit/iris/engine/data/io/ExceptionTriConsumer.java b/src/main/java/com/volmit/iris/engine/data/io/ExceptionTriConsumer.java deleted file mode 100644 index 047fde648..000000000 --- a/src/main/java/com/volmit/iris/engine/data/io/ExceptionTriConsumer.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.io; - -@FunctionalInterface -public interface ExceptionTriConsumer { - - void accept(T t, U u, V v) throws E; -} diff --git a/src/main/java/com/volmit/iris/engine/data/io/MaxDepthIO.java b/src/main/java/com/volmit/iris/engine/data/io/MaxDepthIO.java deleted file mode 100644 index c75572cd0..000000000 --- a/src/main/java/com/volmit/iris/engine/data/io/MaxDepthIO.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.io; - -public interface MaxDepthIO { - - default int decrementMaxDepth(int maxDepth) { - if(maxDepth < 0) { - throw new IllegalArgumentException("negative maximum depth is not allowed"); - } else if(maxDepth == 0) { - throw new MaxDepthReachedException("reached maximum depth of NBT structure"); - } - return --maxDepth; - } -} diff --git a/src/main/java/com/volmit/iris/engine/data/io/MaxDepthReachedException.java b/src/main/java/com/volmit/iris/engine/data/io/MaxDepthReachedException.java deleted file mode 100644 index c7a1a8d34..000000000 --- a/src/main/java/com/volmit/iris/engine/data/io/MaxDepthReachedException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.io; - -/** - * Exception indicating that the maximum (de-)serialization depth has been reached. - */ -@SuppressWarnings("serial") -public class MaxDepthReachedException extends RuntimeException { - - public MaxDepthReachedException(String msg) { - super(msg); - } -} diff --git a/src/main/java/com/volmit/iris/engine/data/io/Serializer.java b/src/main/java/com/volmit/iris/engine/data/io/Serializer.java deleted file mode 100644 index fad4e86a5..000000000 --- a/src/main/java/com/volmit/iris/engine/data/io/Serializer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.io; - -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public interface Serializer { - - void toStream(T object, OutputStream out) throws IOException; - - default void toFile(T object, File file) throws IOException { - try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { - toStream(object, bos); - } - } - - default byte[] toBytes(T object) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - toStream(object, bos); - bos.close(); - return bos.toByteArray(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/data/io/StringDeserializer.java b/src/main/java/com/volmit/iris/engine/data/io/StringDeserializer.java deleted file mode 100644 index 3b69e387f..000000000 --- a/src/main/java/com/volmit/iris/engine/data/io/StringDeserializer.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.io; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; - -public interface StringDeserializer extends Deserializer { - - T fromReader(Reader reader) throws IOException; - - default T fromString(String s) throws IOException { - return fromReader(new StringReader(s)); - } - - @Override - default T fromStream(InputStream stream) throws IOException { - try(Reader reader = new InputStreamReader(stream)) { - return fromReader(reader); - } - } - - @Override - default T fromFile(File file) throws IOException { - try(Reader reader = new FileReader(file)) { - return fromReader(reader); - } - } - - @Override - default T fromBytes(byte[] data) throws IOException { - return fromReader(new StringReader(new String(data))); - } -} diff --git a/src/main/java/com/volmit/iris/engine/data/io/StringSerializer.java b/src/main/java/com/volmit/iris/engine/data/io/StringSerializer.java deleted file mode 100644 index 021eea997..000000000 --- a/src/main/java/com/volmit/iris/engine/data/io/StringSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.data.io; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.StringWriter; -import java.io.Writer; - -public interface StringSerializer extends Serializer { - - void toWriter(T object, Writer writer) throws IOException; - - default String toString(T object) throws IOException { - Writer writer = new StringWriter(); - toWriter(object, writer); - writer.flush(); - return writer.toString(); - } - - @Override - default void toStream(T object, OutputStream stream) throws IOException { - Writer writer = new OutputStreamWriter(stream); - toWriter(object, writer); - writer.flush(); - } - - @Override - default void toFile(T object, File file) throws IOException { - try(Writer writer = new FileWriter(file)) { - toWriter(object, writer); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/decorator/IrisCeilingDecorator.java b/src/main/java/com/volmit/iris/engine/decorator/IrisCeilingDecorator.java deleted file mode 100644 index 2ae96f130..000000000 --- a/src/main/java/com/volmit/iris/engine/decorator/IrisCeilingDecorator.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.decorator; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDecorationPart; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.PointedDripstone; - -public class IrisCeilingDecorator extends IrisEngineDecorator { - public IrisCeilingDecorator(Engine engine) { - super(engine, "Ceiling", IrisDecorationPart.CEILING); - } - - @BlockCoordinates - @Override - public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { - IrisDecorator decorator = getDecorator(biome, realX, realZ); - - if(decorator != null) { - if(!decorator.isStacking()) { - if(height >= 0 || height < getEngine().getHeight()) { - data.set(x, height, z, decorator.getBlockData100(biome, getRng(), realX, height, realZ, getData())); - } - } else { - int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); - if(decorator.isScaleStack()) { - stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack()); - } else { - stack = Math.min(max, stack); - } - - if(stack == 1) { - data.set(x, height, z, decorator.getBlockDataForTop(biome, getRng(), realX, height, realZ, getData())); - return; - } - - for(int i = 0; i < stack; i++) { - int h = height - i; - if(h < getEngine().getMinHeight()) { - continue; - } - - double threshold = (((double) i) / (double) (stack - 1)); - - BlockData bd = threshold >= decorator.getTopThreshold() ? - decorator.getBlockDataForTop(biome, getRng(), realX, h, realZ, getData()) : - decorator.getBlockData100(biome, getRng(), realX, h, realZ, getData()); - - if(bd instanceof PointedDripstone) { - PointedDripstone.Thickness th = PointedDripstone.Thickness.BASE; - - if(stack == 2) { - th = PointedDripstone.Thickness.FRUSTUM; - - if(i == stack - 1) { - th = PointedDripstone.Thickness.TIP; - } - } else { - if(i == stack - 1) { - th = PointedDripstone.Thickness.TIP; - } else if(i == stack - 2) { - th = PointedDripstone.Thickness.FRUSTUM; - } - } - - - bd = Material.POINTED_DRIPSTONE.createBlockData(); - ((PointedDripstone) bd).setThickness(th); - ((PointedDripstone) bd).setVerticalDirection(BlockFace.DOWN); - } - - data.set(x, h, z, bd); - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/decorator/IrisEngineDecorator.java b/src/main/java/com/volmit/iris/engine/decorator/IrisEngineDecorator.java deleted file mode 100644 index 1208a546d..000000000 --- a/src/main/java/com/volmit/iris/engine/decorator/IrisEngineDecorator.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.decorator; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedComponent; -import com.volmit.iris.engine.framework.EngineDecorator; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDecorationPart; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import lombok.Getter; - -public abstract class IrisEngineDecorator extends EngineAssignedComponent implements EngineDecorator { - - @Getter - private final RNG rng; - - @Getter - private final IrisDecorationPart part; - - public IrisEngineDecorator(Engine engine, String name, IrisDecorationPart part) { - super(engine, name + " Decorator"); - this.part = part; - this.rng = new RNG(getSeed() + 29356788 - (part.ordinal() * 10439677L)); - } - - protected IrisDecorator getDecorator(IrisBiome biome, double realX, double realZ) { - KList v = new KList<>(); - RNG rng = new RNG(Cache.key((int) realX, (int) realZ)); - - for(IrisDecorator i : biome.getDecorators()) { - try { - if(i.getPartOf().equals(part) && i.getBlockData(biome, this.rng, realX, realZ, getData()) != null) { - v.add(i); - } - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("PART OF: " + biome.getLoadFile().getAbsolutePath() + " HAS AN INVALID DECORATOR near 'partOf'!!!"); - } - } - - if(v.isNotEmpty()) { - return v.get(rng.nextInt(v.size())); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/engine/decorator/IrisSeaFloorDecorator.java b/src/main/java/com/volmit/iris/engine/decorator/IrisSeaFloorDecorator.java deleted file mode 100644 index 07cdeac7e..000000000 --- a/src/main/java/com/volmit/iris/engine/decorator/IrisSeaFloorDecorator.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.decorator; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDecorationPart; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.block.data.BlockData; - -public class IrisSeaFloorDecorator extends IrisEngineDecorator { - public IrisSeaFloorDecorator(Engine engine) { - super(engine, "Sea Floor", IrisDecorationPart.SEA_FLOOR); - } - - @BlockCoordinates - @Override - public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { - IrisDecorator decorator = getDecorator(biome, realX, realZ); - - if(decorator != null) { - if(!decorator.isStacking()) { - if(height >= 0 || height < getEngine().getHeight()) { - data.set(x, height, z, decorator.getBlockData100(biome, getRng(), realX, height, realZ, getData())); - } - } else { - int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); - if(decorator.isScaleStack()) { - int maxStack = max - height; - stack = (int) Math.ceil((double) maxStack * ((double) stack / 100)); - } else stack = Math.min(stack, max - height); - - if(stack == 1) { - data.set(x, height, z, decorator.getBlockDataForTop(biome, getRng(), realX, height, realZ, getData())); - return; - } - - for(int i = 0; i < stack; i++) { - int h = height + i; - if(h > max || h > getEngine().getHeight()) { - continue; - } - - double threshold = ((double) i) / (stack - 1); - data.set(x, h, z, threshold >= decorator.getTopThreshold() ? - decorator.getBlockDataForTop(biome, getRng(), realX, h, realZ, getData()) : - decorator.getBlockData100(biome, getRng(), realX, h, realZ, getData())); - } - } - } - - } -} diff --git a/src/main/java/com/volmit/iris/engine/decorator/IrisSeaSurfaceDecorator.java b/src/main/java/com/volmit/iris/engine/decorator/IrisSeaSurfaceDecorator.java deleted file mode 100644 index 618b2c3e0..000000000 --- a/src/main/java/com/volmit/iris/engine/decorator/IrisSeaSurfaceDecorator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.decorator; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDecorationPart; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.block.data.BlockData; - -public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { - public IrisSeaSurfaceDecorator(Engine engine) { - super(engine, "Sea Surface", IrisDecorationPart.SEA_SURFACE); - } - - @BlockCoordinates - @Override - public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { - IrisDecorator decorator = getDecorator(biome, realX, realZ); - - if(decorator != null) { - if(!decorator.isStacking()) { - if(height >= 0 || height < getEngine().getHeight()) { - data.set(x, height + 1, z, decorator.getBlockData100(biome, getRng(), realX, height, realZ, getData())); - } - } else { - int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); - if(decorator.isScaleStack()) { - int maxStack = max - height; - stack = (int) Math.ceil((double) maxStack * ((double) stack / 100)); - } - - if(stack == 1) { - data.set(x, height, z, decorator.getBlockDataForTop(biome, getRng(), realX, height, realZ, getData())); - return; - } - - for(int i = 0; i < stack; i++) { - int h = height + i; - if(h >= max || h >= getEngine().getHeight()) { - continue; - } - - double threshold = ((double) i) / (stack - 1); - data.set(x, h + 1, z, threshold >= decorator.getTopThreshold() ? - decorator.getBlockDataForTop(biome, getRng().nextParallelRNG(i), realX, h, realZ, getData()) : - decorator.getBlockData100(biome, getRng().nextParallelRNG(i), realX, h, realZ, getData())); - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/decorator/IrisShoreLineDecorator.java b/src/main/java/com/volmit/iris/engine/decorator/IrisShoreLineDecorator.java deleted file mode 100644 index c155c1b2a..000000000 --- a/src/main/java/com/volmit/iris/engine/decorator/IrisShoreLineDecorator.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.decorator; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDecorationPart; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.block.data.BlockData; - -public class IrisShoreLineDecorator extends IrisEngineDecorator { - public IrisShoreLineDecorator(Engine engine) { - super(engine, "Shore Line", IrisDecorationPart.SHORE_LINE); - } - - @BlockCoordinates - @Override - public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { - - if(height == getDimension().getFluidHeight()) { - if(Math.round(getComplex().getHeightStream().get(realX1, realZ)) < getComplex().getFluidHeight() || - Math.round(getComplex().getHeightStream().get(realX_1, realZ)) < getComplex().getFluidHeight() || - Math.round(getComplex().getHeightStream().get(realX, realZ1)) < getComplex().getFluidHeight() || - Math.round(getComplex().getHeightStream().get(realX, realZ_1)) < getComplex().getFluidHeight() - ) { - IrisDecorator decorator = getDecorator(biome, realX, realZ); - - if(decorator != null) { - if(!decorator.isStacking()) { - data.set(x, height + 1, z, decorator.getBlockData100(biome, getRng(), realX, height, realZ, getData())); - } else { - int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); - if(decorator.isScaleStack()) { - int maxStack = max - height; - stack = (int) Math.ceil((double) maxStack * ((double) stack / 100)); - } else stack = Math.min(max - height, stack); - - if(stack == 1) { - data.set(x, height, z, decorator.getBlockDataForTop(biome, getRng(), realX, height, realZ, getData())); - return; - } - - for(int i = 0; i < stack; i++) { - int h = height + i; - double threshold = ((double) i) / (stack - 1); - data.set(x, h + 1, z, threshold >= decorator.getTopThreshold() ? - decorator.getBlockDataForTop(biome, getRng(), realX, h, realZ, getData()) : - decorator.getBlockData100(biome, getRng(), realX, h, realZ, getData())); - } - } - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/decorator/IrisSurfaceDecorator.java b/src/main/java/com/volmit/iris/engine/decorator/IrisSurfaceDecorator.java deleted file mode 100644 index 2364c30ef..000000000 --- a/src/main/java/com/volmit/iris/engine/decorator/IrisSurfaceDecorator.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.decorator; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.InferredType; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDecorationPart; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.PointedDripstone; - -public class IrisSurfaceDecorator extends IrisEngineDecorator { - public IrisSurfaceDecorator(Engine engine) { - super(engine, "Surface", IrisDecorationPart.NONE); - } - - @BlockCoordinates - @Override - public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { - if(biome.getInferredType().equals(InferredType.SHORE) && height < getDimension().getFluidHeight()) { - return; - } - - BlockData bd, bdx; - IrisDecorator decorator = getDecorator(biome, realX, realZ); - bdx = data.get(x, height, z); - boolean underwater = height < getDimension().getFluidHeight(); - - if(decorator != null) { - if(!decorator.isStacking()) { - bd = decorator.getBlockData100(biome, getRng(), realX, height, realZ, getData()); - - if(!underwater) { - if(!canGoOn(bd, bdx)) { - return; - } - } - - if(bd instanceof Bisected) { - bd = bd.clone(); - ((Bisected) bd).setHalf(Bisected.Half.TOP); - try { - data.set(x, height + 2, z, bd); - } catch(Throwable e) { - Iris.reportError(e); - } - bd = bd.clone(); - ((Bisected) bd).setHalf(Bisected.Half.BOTTOM); - } - - data.set(x, height + 1, z, bd); - - } else { - if(height < getDimension().getFluidHeight()) { - max = getDimension().getFluidHeight(); - } - - int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); - - if(decorator.isScaleStack()) { - stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack()); - } else { - stack = Math.min(max, stack); - } - - if(stack == 1) { - data.set(x, height, z, decorator.getBlockDataForTop(biome, getRng(), realX, height, realZ, getData())); - return; - } - - for(int i = 0; i < stack; i++) { - int h = height + i; - double threshold = ((double) i) / (stack - 1); - bd = threshold >= decorator.getTopThreshold() ? - decorator.getBlockDataForTop(biome, getRng(), realX, h, realZ, getData()) : - decorator.getBlockData100(biome, getRng(), realX, h, realZ, getData()); - - if(bd == null) { - break; - } - - if(i == 0 && !underwater && !canGoOn(bd, bdx)) { - break; - } - - if(underwater && height + 1 + i > getDimension().getFluidHeight()) { - break; - } - - if(bd instanceof PointedDripstone) { - PointedDripstone.Thickness th = PointedDripstone.Thickness.BASE; - - if(stack == 2) { - th = PointedDripstone.Thickness.FRUSTUM; - - if(i == stack - 1) { - th = PointedDripstone.Thickness.TIP; - } - } else { - if(i == stack - 1) { - th = PointedDripstone.Thickness.TIP; - } else if(i == stack - 2) { - th = PointedDripstone.Thickness.FRUSTUM; - } - } - - - bd = Material.POINTED_DRIPSTONE.createBlockData(); - ((PointedDripstone) bd).setThickness(th); - ((PointedDripstone) bd).setVerticalDirection(BlockFace.UP); - } - - data.set(x, height + 1 + i, z, bd); - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/BlockUpdater.java b/src/main/java/com/volmit/iris/engine/framework/BlockUpdater.java deleted file mode 100644 index 509794138..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/BlockUpdater.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.math.RNG; -import org.bukkit.Chunk; -import org.bukkit.block.data.BlockData; - -public interface BlockUpdater { - - void catchBlockUpdates(int x, int y, int z, BlockData data); - - void updateChunk(Chunk c); - - void update(int x, int y, int z, Chunk c, RNG rf); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/Engine.java b/src/main/java/com/volmit/iris/engine/framework/Engine.java deleted file mode 100644 index ab81bf7fb..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/Engine.java +++ /dev/null @@ -1,909 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.gui.components.RenderType; -import com.volmit.iris.core.gui.components.Renderer; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.data.chunk.TerrainChunk; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.engine.object.*; -import com.volmit.iris.engine.scripting.EngineExecutionEnvironment; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.data.DataProvider; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.matter.MatterUpdate; -import com.volmit.iris.util.matter.TileWrapper; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import com.volmit.iris.util.stream.ProceduralStream; -import io.papermc.lib.PaperLib; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; - -import java.awt.Color; -import java.util.Arrays; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -public interface Engine extends DataProvider, Fallible, LootProvider, BlockUpdater, Renderer, Hotloadable { - IrisComplex getComplex(); - - EngineMode getMode(); - - int getBlockUpdatesPerSecond(); - - void printMetrics(CommandSender sender); - - EngineMantle getMantle(); - - void hotloadSilently(); - - void hotloadComplex(); - - void recycle(); - - void close(); - - IrisContext getContext(); - - EngineExecutionEnvironment getExecution(); - - double getMaxBiomeObjectDensity(); - - double getMaxBiomeDecoratorDensity(); - - double getMaxBiomeLayerDensity(); - - boolean isClosed(); - - EngineWorldManager getWorldManager(); - - default UUID getBiomeID(int x, int z) { - return getComplex().getBaseBiomeIDStream().get(x, z); - } - - int getParallelism(); - - void setParallelism(int parallelism); - - EngineTarget getTarget(); - - default int getMaxHeight() { - return getTarget().getWorld().maxHeight(); - } - - default int getMinHeight() { - return getTarget().getWorld().minHeight(); - } - - void setMinHeight(int min); - - @BlockCoordinates - default void generate(int x, int z, TerrainChunk tc, boolean multicore) throws WrongEngineBroException { - generate(x, z, Hunk.view(tc), Hunk.view(tc, tc.getMinHeight(), tc.getMaxHeight()), multicore); - } - - @BlockCoordinates - void generate(int x, int z, Hunk blocks, Hunk biomes, boolean multicore) throws WrongEngineBroException; - - EngineMetrics getMetrics(); - - default void save() { - getMantle().save(); - getWorldManager().onSave(); - saveEngineData(); - } - - default void saveNow() { - getMantle().saveAllNow(); - saveEngineData(); - } - - SeedManager getSeedManager(); - - void saveEngineData(); - - default String getName() { - return getDimension().getName(); - } - - default IrisData getData() { - return getTarget().getData(); - } - - default IrisWorld getWorld() { - return getTarget().getWorld(); - } - - default IrisDimension getDimension() { - return getTarget().getDimension(); - } - - @BlockCoordinates - default Color draw(double x, double z) { - IrisRegion region = getRegion((int) x, (int) z); - IrisBiome biome = getSurfaceBiome((int) x, (int) z); - int height = getHeight((int) x, (int) z); - double heightFactor = M.lerpInverse(0, getTarget().getHeight(), height); - Color irc = region.getColor(this.getComplex(), RenderType.BIOME); - Color ibc = biome.getColor(this, RenderType.BIOME); - Color rc = irc != null ? irc : Color.GREEN.darker(); - Color bc = ibc != null ? ibc : biome.isAquatic() ? Color.BLUE : Color.YELLOW; - Color f = IrisColor.blend(rc, bc, bc, Color.getHSBColor(0, 0, (float) heightFactor)); - - return IrisColor.blend(rc, bc, bc, Color.getHSBColor(0, 0, (float) heightFactor)); - } - - @BlockCoordinates - default IrisRegion getRegion(int x, int z) { - return getComplex().getRegionStream().get(x, z); - } - - void generateMatter(int x, int z, boolean multicore); - - @BlockCoordinates - default IrisBiome getCaveOrMantleBiome(int x, int y, int z) { - MatterCavern m = getMantle().getMantle().get(x, y, z, MatterCavern.class); - - if(m != null && m.getCustomBiome() != null && !m.getCustomBiome().isEmpty()) { - IrisBiome biome = getData().getBiomeLoader().load(m.getCustomBiome()); - - if(biome != null) { - return biome; - } - } - - return getCaveBiome(x, z); - } - - @ChunkCoordinates - Set getObjectsAt(int x, int z); - - @ChunkCoordinates - IrisJigsawStructure getStructureAt(int x, int z); - - @BlockCoordinates - default IrisBiome getCaveBiome(int x, int z) { - return getComplex().getCaveBiomeStream().get(x, z); - } - - @BlockCoordinates - default IrisBiome getSurfaceBiome(int x, int z) { - return getComplex().getTrueBiomeStream().get(x, z); - } - - @BlockCoordinates - default int getHeight(int x, int z) { - return getHeight(x, z, true); - } - - @BlockCoordinates - default int getHeight(int x, int z, boolean ignoreFluid) { - return getMantle().getHighest(x, z, getData(), ignoreFluid); - } - - @BlockCoordinates - @Override - default void catchBlockUpdates(int x, int y, int z, BlockData data) { - if(data == null) { - return; - } - - if(B.isUpdatable(data)) { - getMantle().updateBlock(x, y, z); - } - } - - void blockUpdatedMetric(); - - @ChunkCoordinates - @Override - default void updateChunk(Chunk c) { - if(c.getWorld().isChunkLoaded(c.getX() + 1, c.getZ() + 1) - && c.getWorld().isChunkLoaded(c.getX(), c.getZ() + 1) - && c.getWorld().isChunkLoaded(c.getX() + 1, c.getZ()) - && c.getWorld().isChunkLoaded(c.getX() - 1, c.getZ() - 1) - && c.getWorld().isChunkLoaded(c.getX(), c.getZ() - 1) - && c.getWorld().isChunkLoaded(c.getX() - 1, c.getZ()) - && c.getWorld().isChunkLoaded(c.getX() + 1, c.getZ() - 1) - && c.getWorld().isChunkLoaded(c.getX() - 1, c.getZ() + 1) && getMantle().getMantle().isLoaded(c)) { - - getMantle().getMantle().raiseFlag(c.getX(), c.getZ(), MantleFlag.TILE, () -> J.s(() -> { - getMantle().getMantle().iterateChunk(c.getX(), c.getZ(), TileWrapper.class, (x, y, z, tile) -> { - int betterY = y + getWorld().minHeight(); - if(!TileData.setTileState(c.getBlock(x, betterY, z), tile.getData())) - Iris.warn("Failed to set tile entity data at [%d %d %d | %s] for tile %s!", x, betterY ,z, c.getBlock(x, betterY, z).getBlockData().getMaterial().getKey(), tile.getData().getTileId()); - }); - })); - - getMantle().getMantle().raiseFlag(c.getX(), c.getZ(), MantleFlag.UPDATE, () -> J.s(() -> { - PrecisionStopwatch p = PrecisionStopwatch.start(); - KMap updates = new KMap<>(); - RNG r = new RNG(Cache.key(c.getX(), c.getZ())); - getMantle().getMantle().iterateChunk(c.getX(), c.getZ(), MatterCavern.class, (x, yf, z, v) -> { - int y = yf + getWorld().minHeight(); - if(!B.isFluid(c.getBlock(x & 15, y, z & 15).getBlockData())) { - return; - } - boolean u = false; - if(B.isAir(c.getBlock(x & 15, y, z & 15).getRelative(BlockFace.DOWN).getBlockData())) { - u = true; - } else if(B.isAir(c.getBlock(x & 15, y, z & 15).getRelative(BlockFace.WEST).getBlockData())) { - u = true; - } else if(B.isAir(c.getBlock(x & 15, y, z & 15).getRelative(BlockFace.EAST).getBlockData())) { - u = true; - } else if(B.isAir(c.getBlock(x & 15, y, z & 15).getRelative(BlockFace.SOUTH).getBlockData())) { - u = true; - } else if(B.isAir(c.getBlock(x & 15, y, z & 15).getRelative(BlockFace.NORTH).getBlockData())) { - u = true; - } - - if(u) { - updates.compute(Cache.key(x & 15, z & 15), (k, vv) -> { - if(vv != null) { - return Math.max(vv, y); - } - - return y; - }); - } - }); - - updates.forEach((k, v) -> update(Cache.keyX(k), v, Cache.keyZ(k), c, r)); - getMantle().getMantle().iterateChunk(c.getX(), c.getZ(), MatterUpdate.class, (x, yf, z, v) -> { - int y = yf + getWorld().minHeight(); - if(v != null && v.isUpdate()) { - int vx = x & 15; - int vz = z & 15; - update(x, y, z, c, new RNG(Cache.key(c.getX(), c.getZ()))); - if(vx > 0 && vx < 15 && vz > 0 && vz < 15) { - updateLighting(x, y, z, c); - } - } - }); - getMantle().getMantle().deleteChunkSlice(c.getX(), c.getZ(), MatterUpdate.class); - getMetrics().getUpdates().put(p.getMilliseconds()); - }, RNG.r.i(0, 20))); - } - } - - @BlockCoordinates - default void updateLighting(int x, int y, int z, Chunk c) { - Block block = c.getBlock(x, y, z); - BlockData data = block.getBlockData(); - - if(B.isLit(data)) { - try { - block.setType(Material.AIR, false); - block.setBlockData(data, true); - } catch(Exception e) { - Iris.reportError(e); - } - } - } - - @BlockCoordinates - @Override - default void update(int x, int y, int z, Chunk c, RNG rf) { - Block block = c.getBlock(x, y, z); - BlockData data = block.getBlockData(); - blockUpdatedMetric(); - if(B.isStorage(data)) { - RNG rx = rf.nextParallelRNG(BlockPosition.toLong(x, y, z)); - InventorySlotType slot = null; - - if(B.isStorageChest(data)) { - slot = InventorySlotType.STORAGE; - } - - if(slot != null) { - KList tables = getLootTables(rx, block); - - try { - InventoryHolder m = (InventoryHolder) block.getState(); - addItems(false, m.getInventory(), rx, tables, slot, x, y, z, 15); - } catch(Throwable e) { - Iris.reportError(e); - } - } - } else { - block.setType(Material.AIR, false); - block.setBlockData(data, true); - } - } - - @Override - default void scramble(Inventory inventory, RNG rng) { - org.bukkit.inventory.ItemStack[] items = inventory.getContents(); - org.bukkit.inventory.ItemStack[] nitems = new org.bukkit.inventory.ItemStack[inventory.getSize()]; - System.arraycopy(items, 0, nitems, 0, items.length); - boolean packedFull = false; - - splitting: - for(int i = 0; i < nitems.length; i++) { - ItemStack is = nitems[i]; - - if(is != null && is.getAmount() > 1 && !packedFull) { - for(int j = 0; j < nitems.length; j++) { - if(nitems[j] == null) { - int take = rng.nextInt(is.getAmount()); - take = take == 0 ? 1 : take; - is.setAmount(is.getAmount() - take); - nitems[j] = is.clone(); - nitems[j].setAmount(take); - continue splitting; - } - } - - packedFull = true; - } - } - - for(int i = 0; i < 4; i++) { - try { - Arrays.parallelSort(nitems, (a, b) -> rng.nextInt()); - break; - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - inventory.setContents(nitems); - } - - @Override - default void injectTables(KList list, IrisLootReference r) { - if(r.getMode().equals(IrisLootMode.CLEAR) || r.getMode().equals(IrisLootMode.REPLACE)) { - list.clear(); - } - - list.addAll(r.getLootTables(getComplex())); - } - - @BlockCoordinates - @Override - default KList getLootTables(RNG rng, Block b) { - int rx = b.getX(); - int rz = b.getZ(); - double he = getComplex().getHeightStream().get(rx, rz); - PlacedObject po = getObjectPlacement(rx, b.getY(), rz); - if(po != null && po.getPlacement() != null) { - - if(B.isStorageChest(b.getBlockData())) { - IrisLootTable table = po.getPlacement().getTable(b.getBlockData(), getData()); - if(table != null) { - return new KList<>(table); - } - } - } - IrisRegion region = getComplex().getRegionStream().get(rx, rz); - IrisBiome biomeSurface = getComplex().getTrueBiomeStream().get(rx, rz); - IrisBiome biomeUnder = b.getY() < he ? getComplex().getCaveBiomeStream().get(rx, rz) : biomeSurface; - KList tables = new KList<>(); - double multiplier = 1D * getDimension().getLoot().getMultiplier() * region.getLoot().getMultiplier() * biomeSurface.getLoot().getMultiplier() * biomeUnder.getLoot().getMultiplier(); - injectTables(tables, getDimension().getLoot()); - injectTables(tables, region.getLoot()); - injectTables(tables, biomeSurface.getLoot()); - injectTables(tables, biomeUnder.getLoot()); - - if(tables.isNotEmpty()) { - int target = (int) Math.round(tables.size() * multiplier); - - while(tables.size() < target && tables.isNotEmpty()) { - tables.add(tables.get(rng.i(tables.size() - 1))); - } - - while(tables.size() > target && tables.isNotEmpty()) { - tables.remove(rng.i(tables.size() - 1)); - } - } - - return tables; - } - - @Override - default void addItems(boolean debug, Inventory inv, RNG rng, KList tables, InventorySlotType slot, int x, int y, int z, int mgf) { - KList items = new KList<>(); - - int b = 4; - for(IrisLootTable i : tables) { - if(i == null) - continue; - b++; - items.addAll(i.getLoot(debug, items.isEmpty(), rng, slot, x, y, z, b + b, mgf + b)); - } - - if(PaperLib.isPaper() && getWorld().hasRealWorld()) { - PaperLib.getChunkAtAsync(getWorld().realWorld(), x >> 4, z >> 4).thenAccept((c) -> { - Runnable r = () -> { - for(ItemStack i : items) { - inv.addItem(i); - } - - scramble(inv, rng); - }; - - if(Bukkit.isPrimaryThread()) { - r.run(); - } else { - J.s(r); - } - }); - } else { - for(ItemStack i : items) { - inv.addItem(i); - } - - scramble(inv, rng); - } - } - - EngineEffects getEffects(); - - default MultiBurst burst() { - return getTarget().getBurster(); - } - - default void clean() { - burst().lazy(() -> getMantle().trim()); - } - - @BlockCoordinates - default IrisBiome getBiome(Location l) { - return getBiome(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - } - - @BlockCoordinates - default IrisRegion getRegion(Location l) { - return getRegion(l.getBlockX(), l.getBlockZ()); - } - - IrisBiome getFocus(); - - IrisRegion getFocusRegion(); - - - IrisEngineData getEngineData(); - - default IrisBiome getSurfaceBiome(Chunk c) { - return getSurfaceBiome((c.getX() << 4) + 8, (c.getZ() << 4) + 8); - } - - default IrisRegion getRegion(Chunk c) { - return getRegion((c.getX() << 4) + 8, (c.getZ() << 4) + 8); - } - - default KList getAllBiomes() { - KMap v = new KMap<>(); - - IrisDimension dim = getDimension(); - dim.getAllBiomes(this).forEach((i) -> v.put(i.getLoadKey(), i)); - - return v.v(); - } - - int getGenerated(); - - default IrisPosition lookForStreamResult(T find, ProceduralStream stream, Function2 matcher, long timeout) { - AtomicInteger checked = new AtomicInteger(); - AtomicLong time = new AtomicLong(M.ms()); - AtomicReference r = new AtomicReference<>(); - BurstExecutor b = burst().burst(); - - while(M.ms() - time.get() < timeout && r.get() == null) { - b.queue(() -> { - for(int i = 0; i < 1000; i++) { - if(M.ms() - time.get() > timeout) { - return; - } - - int x = RNG.r.i(-29999970, 29999970); - int z = RNG.r.i(-29999970, 29999970); - checked.incrementAndGet(); - if(matcher.apply(stream.get(x, z), find)) { - r.set(new IrisPosition(x, 120, z)); - time.set(0); - } - } - }); - } - - return r.get(); - } - - default IrisPosition lookForBiome(IrisBiome biome, long timeout, Consumer triesc) { - if(!getWorld().hasRealWorld()) { - Iris.error("Cannot GOTO without a bound world (headless mode)"); - return null; - } - - ChronoLatch cl = new ChronoLatch(250, false); - long s = M.ms(); - int cpus = (Runtime.getRuntime().availableProcessors()); - - if(!getDimension().getAllBiomes(this).contains(biome)) { - return null; - } - - AtomicInteger tries = new AtomicInteger(0); - AtomicBoolean found = new AtomicBoolean(false); - AtomicBoolean running = new AtomicBoolean(true); - AtomicReference location = new AtomicReference<>(); - for(int i = 0; i < cpus; i++) { - J.a(() -> { - try { - Engine e; - IrisBiome b; - int x, z; - - while(!found.get() && running.get()) { - try { - x = RNG.r.i(-29999970, 29999970); - z = RNG.r.i(-29999970, 29999970); - b = getSurfaceBiome(x, z); - - if(b != null && b.getLoadKey() == null) { - continue; - } - - if(b != null && b.getLoadKey().equals(biome.getLoadKey())) { - found.lazySet(true); - location.lazySet(new IrisPosition(x, getHeight(x, z), z)); - } - - tries.getAndIncrement(); - } catch(Throwable ex) { - Iris.reportError(ex); - ex.printStackTrace(); - return; - } - } - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - }); - } - - while(!found.get() || location.get() == null) { - J.sleep(50); - - if(cl.flip()) { - triesc.accept(tries.get()); - } - - if(M.ms() - s > timeout) { - running.set(false); - return null; - } - } - - running.set(false); - return location.get(); - } - - default IrisPosition lookForRegion(IrisRegion reg, long timeout, Consumer triesc) { - if(getWorld().hasRealWorld()) { - Iris.error("Cannot GOTO without a bound world (headless mode)"); - return null; - } - - ChronoLatch cl = new ChronoLatch(3000, false); - long s = M.ms(); - int cpus = (Runtime.getRuntime().availableProcessors()); - - if(!getDimension().getRegions().contains(reg.getLoadKey())) { - return null; - } - - AtomicInteger tries = new AtomicInteger(0); - AtomicBoolean found = new AtomicBoolean(false); - AtomicBoolean running = new AtomicBoolean(true); - AtomicReference location = new AtomicReference<>(); - - for(int i = 0; i < cpus; i++) { - J.a(() -> { - Engine e; - IrisRegion b; - int x, z; - - while(!found.get() && running.get()) { - try { - x = RNG.r.i(-29999970, 29999970); - z = RNG.r.i(-29999970, 29999970); - b = getRegion(x, z); - - if(b != null && b.getLoadKey() != null && b.getLoadKey().equals(reg.getLoadKey())) { - found.lazySet(true); - location.lazySet(new IrisPosition(x, getHeight(x, z), z)); - } - - tries.getAndIncrement(); - } catch(Throwable xe) { - Iris.reportError(xe); - xe.printStackTrace(); - return; - } - } - }); - } - - while(!found.get() || location.get() != null) { - J.sleep(50); - - if(cl.flip()) { - triesc.accept(tries.get()); - } - - if(M.ms() - s > timeout) { - triesc.accept(tries.get()); - running.set(false); - return null; - } - } - - triesc.accept(tries.get()); - running.set(false); - return location.get(); - } - - double getGeneratedPerSecond(); - - default int getHeight() { - return getWorld().getHeight(); - } - - boolean isStudio(); - - default IrisBiome getBiome(int x, int y, int z) { - if(y <= getHeight(x, z) - 2) { - return getCaveBiome(x, z); - } - - return getSurfaceBiome(x, z); - } - - default IrisBiome getBiomeOrMantle(int x, int y, int z) { - if(y <= getHeight(x, z) - 2) { - return getCaveOrMantleBiome(x, y, z); - } - - return getSurfaceBiome(x, z); - } - - default String getObjectPlacementKey(int x, int y, int z) { - PlacedObject o = getObjectPlacement(x, y, z); - - if(o != null && o.getObject() != null) { - return o.getObject().getLoadKey() + "@" + o.getId(); - } - - return null; - } - - default PlacedObject getObjectPlacement(int x, int y, int z) { - String objectAt = getMantle().getMantle().get(x, y, z, String.class); - if(objectAt == null || objectAt.isEmpty()) { - return null; - } - - String[] v = objectAt.split("\\Q@\\E"); - String object = v[0]; - int id = Integer.parseInt(v[1]); - IrisRegion region = getRegion(x, z); - - for(IrisObjectPlacement i : region.getObjects()) { - if(i.getPlace().contains(object)) { - return new PlacedObject(i, getData().getObjectLoader().load(object), id, x, z); - } - } - - IrisBiome biome = getBiome(x, y, z); - - for(IrisObjectPlacement i : biome.getObjects()) { - if(i.getPlace().contains(object)) { - return new PlacedObject(i, getData().getObjectLoader().load(object), id, x, z); - } - } - - return new PlacedObject(null, getData().getObjectLoader().load(object), id, x, z); - } - - - int getCacheID(); - - default IrisBiome getBiomeOrMantle(Location l) { - return getBiomeOrMantle(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - } - - default void gotoBiome(IrisBiome biome, Player player) { - Set regionKeys = getDimension() - .getAllRegions(this).stream() - .filter((i) -> i.getAllBiomes(this).contains(biome)) - .map(IrisRegistrant::getLoadKey) - .collect(Collectors.toSet()); - Locator lb = Locator.surfaceBiome(biome.getLoadKey()); - Locator locator = (engine, chunk) - -> regionKeys.contains(getRegion((chunk.getX() << 4) + 8, (chunk.getZ() << 4) + 8).getLoadKey()) - && lb.matches(engine, chunk); - - if(!regionKeys.isEmpty()) { - locator.find(player); - } else { - player.sendMessage(C.RED + biome.getName() + " is not in any defined regions!"); - } - } - - default void gotoJigsaw(IrisJigsawStructure s, Player player) { - if(s.getLoadKey().equals(getDimension().getStronghold())) { - KList p = getDimension().getStrongholds(getSeedManager().getSpawn()); - - if(p.isEmpty()) { - player.sendMessage(C.GOLD + "No strongholds in world."); - } - - Position2 px = new Position2(player.getLocation().getBlockX(), player.getLocation().getBlockZ()); - Position2 pr = null; - double d = Double.MAX_VALUE; - - Iris.debug("Ps: " + p.size()); - - for(Position2 i : p) { - Iris.debug("- " + i.getX() + " " + i.getZ()); - } - - for(Position2 i : p) { - double dx = i.distance(px); - if(dx < d) { - d = dx; - pr = i; - } - } - - if(pr != null) { - Location ll = new Location(player.getWorld(), pr.getX(), 40, pr.getZ()); - J.s(() -> player.teleport(ll)); - } - - return; - } - - if(getDimension().getJigsawStructures().stream() - .map(IrisJigsawStructurePlacement::getStructure) - .collect(Collectors.toSet()).contains(s.getLoadKey())) { - Locator.jigsawStructure(s.getLoadKey()).find(player); - } else { - Set biomeKeys = getDimension().getAllBiomes(this).stream() - .filter((i) -> i.getJigsawStructures() - .stream() - .anyMatch((j) -> j.getStructure().equals(s.getLoadKey()))) - .map(IrisRegistrant::getLoadKey) - .collect(Collectors.toSet()); - Set regionKeys = getDimension().getAllRegions(this).stream() - .filter((i) -> i.getAllBiomeIds().stream().anyMatch(biomeKeys::contains) - || i.getJigsawStructures() - .stream() - .anyMatch((j) -> j.getStructure().equals(s.getLoadKey()))) - .map(IrisRegistrant::getLoadKey) - .collect(Collectors.toSet()); - - Locator sl = Locator.jigsawStructure(s.getLoadKey()); - Locator locator = (engine, chunk) -> { - if(biomeKeys.contains(getSurfaceBiome((chunk.getX() << 4) + 8, (chunk.getZ() << 4) + 8).getLoadKey())) { - return sl.matches(engine, chunk); - } else if(regionKeys.contains(getRegion((chunk.getX() << 4) + 8, (chunk.getZ() << 4) + 8).getLoadKey())) { - return sl.matches(engine, chunk); - } - return false; - }; - - if(!regionKeys.isEmpty()) { - locator.find(player); - } else { - player.sendMessage(C.RED + s.getLoadKey() + " is not in any defined regions, biomes or dimensions!"); - } - } - - } - - default void gotoObject(String s, Player player) { - Set biomeKeys = getDimension().getAllBiomes(this).stream() - .filter((i) -> i.getObjects().stream().anyMatch((f) -> f.getPlace().contains(s))) - .map(IrisRegistrant::getLoadKey) - .collect(Collectors.toSet()); - Set regionKeys = getDimension().getAllRegions(this).stream() - .filter((i) -> i.getAllBiomeIds().stream().anyMatch(biomeKeys::contains) - || i.getObjects().stream().anyMatch((f) -> f.getPlace().contains(s))) - .map(IrisRegistrant::getLoadKey) - .collect(Collectors.toSet()); - - Locator sl = Locator.object(s); - Locator locator = (engine, chunk) -> { - if(biomeKeys.contains(getSurfaceBiome((chunk.getX() << 4) + 8, (chunk.getZ() << 4) + 8).getLoadKey())) { - return sl.matches(engine, chunk); - } else if(regionKeys.contains(getRegion((chunk.getX() << 4) + 8, (chunk.getZ() << 4) + 8).getLoadKey())) { - return sl.matches(engine, chunk); - } - - return false; - }; - - if(!regionKeys.isEmpty()) { - locator.find(player); - } else { - player.sendMessage(C.RED + s + " is not in any defined regions or biomes!"); - } - } - - default void gotoRegion(IrisRegion r, Player player) { - if(!getDimension().getAllRegions(this).contains(r)) { - player.sendMessage(C.RED + r.getName() + " is not defined in the dimension!"); - return; - } - - Locator.region(r.getLoadKey()).find(player); - } - - default void cleanupMantleChunk(int x, int z) { - if(IrisSettings.get().getPerformance().isTrimMantleInStudio() || !isStudio()) { - J.a(() -> getMantle().cleanupChunk(x, z)); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineActuator.java b/src/main/java/com/volmit/iris/engine/framework/EngineActuator.java deleted file mode 100644 index 2582ccabd..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineActuator.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; - -public interface EngineActuator extends EngineComponent { - @BlockCoordinates - void actuate(int x, int z, Hunk output, boolean multicore); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedActuator.java b/src/main/java/com/volmit/iris/engine/framework/EngineAssignedActuator.java deleted file mode 100644 index cebc6f143..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedActuator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; - -public abstract class EngineAssignedActuator extends EngineAssignedComponent implements EngineActuator { - public EngineAssignedActuator(Engine engine, String name) { - super(engine, name); - } - - public abstract void onActuate(int x, int z, Hunk output, boolean multicore); - - @BlockCoordinates - @Override - public void actuate(int x, int z, Hunk output, boolean multicore) { - onActuate(x, z, output, multicore); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedBiModifier.java b/src/main/java/com/volmit/iris/engine/framework/EngineAssignedBiModifier.java deleted file mode 100644 index 0f29d67c6..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedBiModifier.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - - -import com.volmit.iris.util.hunk.Hunk; - -public abstract class EngineAssignedBiModifier extends EngineAssignedComponent implements EngineBiModifier { - public EngineAssignedBiModifier(Engine engine, String name) { - super(engine, name); - } - - public abstract void onModify(int x, int z, Hunk a, Hunk b); - - @Override - public void modify(int x, int z, Hunk a, Hunk b) { - onModify(x, z, a, b); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedComponent.java b/src/main/java/com/volmit/iris/engine/framework/EngineAssignedComponent.java deleted file mode 100644 index a9e83e95c..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedComponent.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.math.RollingSequence; -import lombok.Data; - -@Data -public class EngineAssignedComponent implements EngineComponent { - private final Engine engine; - private final RollingSequence metrics; - private final String name; - - public EngineAssignedComponent(Engine engine, String name) { - Iris.debug("Engine: " + engine.getCacheID() + " Starting " + name); - this.engine = engine; - this.metrics = new RollingSequence(16); - this.name = name; - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedModifier.java b/src/main/java/com/volmit/iris/engine/framework/EngineAssignedModifier.java deleted file mode 100644 index cfbed947c..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedModifier.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; - -public abstract class EngineAssignedModifier extends EngineAssignedComponent implements EngineModifier { - public EngineAssignedModifier(Engine engine, String name) { - super(engine, name); - } - - @BlockCoordinates - public abstract void onModify(int x, int z, Hunk output, boolean multicore); - - @BlockCoordinates - @Override - public void modify(int x, int z, Hunk output, boolean multicore) { - try { - onModify(x, z, output, multicore); - } catch(Throwable e) { - Iris.error("Modifier Failure: " + getName()); - e.printStackTrace(); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedWorldManager.java b/src/main/java/com/volmit/iris/engine/framework/EngineAssignedWorldManager.java deleted file mode 100644 index 4b591fef9..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineAssignedWorldManager.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.events.IrisEngineHotloadEvent; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.plugin.VolmitSender; -import io.papermc.lib.PaperLib; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Sound; -import org.bukkit.entity.EnderSignal; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.entity.EntitySpawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.world.ChunkLoadEvent; -import org.bukkit.event.world.WorldSaveEvent; -import org.bukkit.event.world.WorldUnloadEvent; - -import java.util.concurrent.atomic.AtomicBoolean; - -public abstract class EngineAssignedWorldManager extends EngineAssignedComponent implements EngineWorldManager, Listener { - private final int taskId; - - public EngineAssignedWorldManager() { - super(null, null); - taskId = -1; - } - - public EngineAssignedWorldManager(Engine engine) { - super(engine, "World"); - Iris.instance.registerListener(this); - taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, this::onTick, 0, 0); - } - - @EventHandler - public void on(IrisEngineHotloadEvent e) { - for(Player i : e.getEngine().getWorld().getPlayers()) { - i.playSound(i.getLocation(), Sound.BLOCK_AMETHYST_BLOCK_BREAK, 1f, 1.8f); - VolmitSender s = new VolmitSender(i); - s.sendTitle(C.IRIS + "Engine " + C.AQUA + "Hotloaded", 70, 60, 410); - } - } - - protected AtomicBoolean ignoreTP = new AtomicBoolean(false); - -// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) -// public void on(PlayerTeleportEvent e) { -// if(ignoreTP.get()) { -// System.out.println("IgTP1"); -// return; -// } -// -// if(!PaperLib.isPaper() || e.getTo() == null) { -// System.out.println("IgTP2"); -// -//// return; -// } -// -//// try { -//// System.out.println("IgTP3"); -//// -//// if(e.getTo().getWorld().equals(getTarget().getWorld().realWorld())) { -//// System.out.println("IgTP4"); -//// -//// getEngine().getWorldManager().teleportAsync(e); -//// } -//// } catch(Throwable ex) { -//// -//// } -// } - - @EventHandler - public void on(WorldSaveEvent e) { - if(e.getWorld().equals(getTarget().getWorld().realWorld())) { - getEngine().save(); - } - } - - @EventHandler - public void on(EntitySpawnEvent e) { - if(e.getEntity().getWorld().equals(getTarget().getWorld().realWorld())) { - if(e.getEntityType().equals(EntityType.ENDER_SIGNAL)) { - KList p = getEngine().getDimension().getStrongholds(getEngine().getSeedManager().getSpawn()); - Position2 px = new Position2(e.getEntity().getLocation().getBlockX(), e.getEntity().getLocation().getBlockZ()); - Position2 pr = null; - double d = Double.MAX_VALUE; - - Iris.debug("Ps: " + p.size()); - - for(Position2 i : p) { - Iris.debug("- " + i.getX() + " " + i.getZ()); - } - - for(Position2 i : p) { - double dx = i.distance(px); - if(dx < d) { - d = dx; - pr = i; - } - } - - if(pr != null) { - e.getEntity().getWorld().playSound(e.getEntity().getLocation(), Sound.ITEM_TRIDENT_THROW, 1f, 1.6f); - Location ll = new Location(e.getEntity().getWorld(), pr.getX(), 40, pr.getZ()); - Iris.debug("ESignal: " + ll.getBlockX() + " " + ll.getBlockZ()); - ((EnderSignal) e.getEntity()).setTargetLocation(ll); - } - } - } - } - - @EventHandler - public void on(WorldUnloadEvent e) { - if(e.getWorld().equals(getTarget().getWorld().realWorld())) { - getEngine().close(); - } - } - - @EventHandler - public void on(BlockBreakEvent e) { - if(e.getPlayer().getWorld().equals(getTarget().getWorld().realWorld())) { - onBlockBreak(e); - } - } - - @EventHandler - public void on(BlockPlaceEvent e) { - if(e.getPlayer().getWorld().equals(getTarget().getWorld().realWorld())) { - onBlockPlace(e); - } - } - - @EventHandler - public void on(ChunkLoadEvent e) { - if(e.getChunk().getWorld().equals(getTarget().getWorld().realWorld())) { - onChunkLoad(e.getChunk(), e.isNewChunk()); - } - } - - @Override - public void close() { - super.close(); - Iris.instance.unregisterListener(this); - Bukkit.getScheduler().cancelTask(taskId); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineBiModifier.java b/src/main/java/com/volmit/iris/engine/framework/EngineBiModifier.java deleted file mode 100644 index ecd9b894d..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineBiModifier.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - - -import com.volmit.iris.util.hunk.Hunk; - -public interface EngineBiModifier extends EngineComponent { - void modify(int x, int z, Hunk a, Hunk b); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineComponent.java b/src/main/java/com/volmit/iris/engine/framework/EngineComponent.java deleted file mode 100644 index a17e044a0..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineComponent.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.util.math.RollingSequence; -import com.volmit.iris.util.parallel.MultiBurst; -import org.bukkit.event.Listener; - -public interface EngineComponent { - Engine getEngine(); - - RollingSequence getMetrics(); - - String getName(); - - default MultiBurst burst() { - return getEngine().burst(); - } - - default void close() { - try { - if(this instanceof Listener) { - Iris.instance.unregisterListener((Listener) this); - } - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - default IrisData getData() { - return getEngine().getData(); - } - - default EngineTarget getTarget() { - return getEngine().getTarget(); - } - - default IrisDimension getDimension() { - return getEngine().getDimension(); - } - - default long getSeed() { - return getEngine().getSeedManager().getComponent(); - } - - default int getParallelism() { - return getEngine().getParallelism(); - } - - default IrisComplex getComplex() { - return getEngine().getComplex(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineData.java b/src/main/java/com/volmit/iris/engine/framework/EngineData.java deleted file mode 100644 index 5217f5bb2..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineData.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.google.gson.Gson; -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.io.IO; -import lombok.Data; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -@Data -public class EngineData { - private String dimension; - private String lastVersion; - private List strongholdPositions; - - public static EngineData load(File f) { - try { - f.getParentFile().mkdirs(); - return new Gson().fromJson(IO.readAll(f), EngineData.class); - } catch(Throwable e) { - Iris.reportError(e); - - } - - return new EngineData(); - } - - public void save(File f) { - try { - f.getParentFile().mkdirs(); - IO.writeAll(f, new Gson().toJson(this)); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineDecorator.java b/src/main/java/com/volmit/iris/engine/framework/EngineDecorator.java deleted file mode 100644 index ccbc16ae4..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineDecorator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.block.data.BlockData; - -public interface EngineDecorator extends EngineComponent { - - @BlockCoordinates - void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max); - - @BlockCoordinates - default void decorate(int x, int z, int realX, int realZ, Hunk data, IrisBiome biome, int height, int max) { - decorate(x, z, realX, realX, realX, realZ, realZ, realZ, data, biome, height, max); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - default boolean canGoOn(BlockData decorant, BlockData atop) { - if(atop == null || B.isAir(atop)) { - return false; - } - - return B.canPlaceOnto(decorant.getMaterial(), atop.getMaterial()); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineEffects.java b/src/main/java/com/volmit/iris/engine/framework/EngineEffects.java deleted file mode 100644 index ff6326985..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineEffects.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -public interface EngineEffects extends EngineComponent { - void updatePlayerMap(); - - void tickRandomPlayer(); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineMetrics.java b/src/main/java/com/volmit/iris/engine/framework/EngineMetrics.java deleted file mode 100644 index 691ef5d46..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineMetrics.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.atomics.AtomicRollingSequence; -import com.volmit.iris.util.collection.KMap; -import lombok.Data; - -@Data -public class EngineMetrics { - private final AtomicRollingSequence total; - private final AtomicRollingSequence updates; - private final AtomicRollingSequence terrain; - private final AtomicRollingSequence biome; - private final AtomicRollingSequence parallax; - private final AtomicRollingSequence parallaxInsert; - private final AtomicRollingSequence post; - private final AtomicRollingSequence perfection; - private final AtomicRollingSequence api; - private final AtomicRollingSequence decoration; - private final AtomicRollingSequence cave; - private final AtomicRollingSequence ravine; - private final AtomicRollingSequence deposit; - - public EngineMetrics(int mem) { - this.total = new AtomicRollingSequence(mem); - this.terrain = new AtomicRollingSequence(mem); - this.api = new AtomicRollingSequence(mem); - this.biome = new AtomicRollingSequence(mem); - this.perfection = new AtomicRollingSequence(mem); - this.parallax = new AtomicRollingSequence(mem); - this.parallaxInsert = new AtomicRollingSequence(mem); - this.post = new AtomicRollingSequence(mem); - this.decoration = new AtomicRollingSequence(mem); - this.updates = new AtomicRollingSequence(mem); - this.cave = new AtomicRollingSequence(mem); - this.ravine = new AtomicRollingSequence(mem); - this.deposit = new AtomicRollingSequence(mem); - } - - public KMap pull() { - KMap v = new KMap<>(); - v.put("total", total.getAverage()); - v.put("terrain", terrain.getAverage()); - v.put("biome", biome.getAverage()); - v.put("parallax", parallax.getAverage()); - v.put("parallax.insert", parallaxInsert.getAverage()); - v.put("post", post.getAverage()); - v.put("perfection", perfection.getAverage()); - v.put("decoration", decoration.getAverage()); - v.put("api", api.getAverage()); - v.put("updates", updates.getAverage()); - v.put("cave", cave.getAverage()); - v.put("ravine", ravine.getAverage()); - v.put("deposit", deposit.getAverage()); - - return v; - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineMode.java b/src/main/java/com/volmit/iris/engine/framework/EngineMode.java deleted file mode 100644 index 9cb721337..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineMode.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -public interface EngineMode extends Staged { - void close(); - - Engine getEngine(); - - default MultiBurst burst() { - return getEngine().burst(); - } - - default EngineStage burst(EngineStage... stages) { - return (x, z, blocks, biomes, multicore) -> { - BurstExecutor e = burst().burst(stages.length); - e.setMulticore(multicore); - - for(EngineStage i : stages) { - e.queue(() -> i.generate(x, z, blocks, biomes, multicore)); - } - - e.complete(); - }; - } - - default IrisComplex getComplex() { - return getEngine().getComplex(); - } - - default EngineMantle getMantle() { - return getEngine().getMantle(); - } - - default void generateMatter(int x, int z, boolean multicore) { - getMantle().generateMatter(x, z, multicore); - } - - @BlockCoordinates - default void generate(int x, int z, Hunk blocks, Hunk biomes, boolean multicore) { - for(EngineStage i : getStages()) { - i.generate(x, z, blocks, biomes, multicore); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineModifier.java b/src/main/java/com/volmit/iris/engine/framework/EngineModifier.java deleted file mode 100644 index cf7cdaa5a..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineModifier.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; - -public interface EngineModifier extends EngineComponent { - @BlockCoordinates - void modify(int x, int z, Hunk t, boolean multicore); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EnginePlayer.java b/src/main/java/com/volmit/iris/engine/framework/EnginePlayer.java deleted file mode 100644 index 0ea6f30ec..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EnginePlayer.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisEffect; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.scheduling.J; -import lombok.Data; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -@Data -public class EnginePlayer { - private final Engine engine; - private final Player player; - private IrisBiome biome; - private IrisRegion region; - private Location lastLocation; - private long lastSample; - - public EnginePlayer(Engine engine, Player player) { - this.engine = engine; - this.player = player; - lastLocation = player.getLocation().clone(); - lastSample = -1; - sample(); - } - - public void tick() { - sample(); - - J.a(() -> { - if(region != null) { - for(IrisEffect j : region.getEffects()) { - try { - j.apply(player, getEngine()); - } catch(Throwable e) { - Iris.reportError(e); - - } - } - } - - if(biome != null) { - for(IrisEffect j : biome.getEffects()) { - try { - j.apply(player, getEngine()); - } catch(Throwable e) { - Iris.reportError(e); - - } - } - } - }); - } - - public long ticksSinceLastSample() { - return M.ms() - lastSample; - } - - public void sample() { - try { - if(ticksSinceLastSample() > 55 && player.getLocation().distanceSquared(lastLocation) > 9 * 9) { - lastLocation = player.getLocation().clone(); - lastSample = M.ms(); - sampleBiomeRegion(); - } - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - private void sampleBiomeRegion() { - Location l = player.getLocation(); - biome = engine.getBiome(l); - region = engine.getRegion(l); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineStage.java b/src/main/java/com/volmit/iris/engine/framework/EngineStage.java deleted file mode 100644 index 82f6ce558..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineStage.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -public interface EngineStage { - @BlockCoordinates - void generate(int x, int z, Hunk blocks, Hunk biomes, boolean multicore); - - default void close() { - if(this instanceof EngineComponent c) { - c.close(); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineTarget.java b/src/main/java/com/volmit/iris/engine/framework/EngineTarget.java deleted file mode 100644 index cd33cf998..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineTarget.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisWorld; -import com.volmit.iris.util.parallel.MultiBurst; -import lombok.Data; - -@Data -public class EngineTarget { - private final MultiBurst burster; - private final IrisData data; - private IrisDimension dimension; - private IrisWorld world; - - public EngineTarget(IrisWorld world, IrisDimension dimension, IrisData data) { - this.world = world; - this.dimension = dimension; - this.data = data; - this.burster = MultiBurst.burst; - } - - public int getHeight() { - return world.maxHeight() - world.minHeight(); - } - - public void close() { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/EngineWorldManager.java b/src/main/java/com/volmit/iris/engine/framework/EngineWorldManager.java deleted file mode 100644 index 28403d6ac..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/EngineWorldManager.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import org.bukkit.Chunk; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerTeleportEvent; - -@SuppressWarnings("EmptyMethod") -public interface EngineWorldManager { - void close(); - - double getEnergy(); - - int getEntityCount(); - - int getChunkCount(); - - double getEntitySaturation(); - - void onTick(); - - void onSave(); - - void onBlockBreak(BlockBreakEvent e); - - void onBlockPlace(BlockPlaceEvent e); - - void onChunkLoad(Chunk e, boolean generated); - - void chargeEnergy(); - - void teleportAsync(PlayerTeleportEvent e); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/Fallible.java b/src/main/java/com/volmit/iris/engine/framework/Fallible.java deleted file mode 100644 index eb55a52a6..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/Fallible.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.Iris; - -public interface Fallible { - default void fail(String error) { - try { - throw new RuntimeException(); - } catch(Throwable e) { - Iris.reportError(e); - fail(error, e); - } - } - - default void fail(Throwable e) { - fail("Failed to generate", e); - } - - void fail(String error, Throwable e); - - boolean hasFailed(); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/Hotloadable.java b/src/main/java/com/volmit/iris/engine/framework/Hotloadable.java deleted file mode 100644 index 7a6605090..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/Hotloadable.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -public interface Hotloadable { - void hotload(); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/IrisEngineMode.java b/src/main/java/com/volmit/iris/engine/framework/IrisEngineMode.java deleted file mode 100644 index edddc71fe..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/IrisEngineMode.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.collection.KList; - -public abstract class IrisEngineMode implements EngineMode { - private final Engine engine; - private final KList stages; - private boolean closed; - - public IrisEngineMode(Engine engine) { - this.engine = engine; - this.stages = new KList<>(); - this.closed = false; - } - - @Override - public synchronized void close() { - if(closed) { - return; - } - - closed = true; - dump(); - } - - @Override - public Engine getEngine() { - return engine; - } - - @Override - public KList getStages() { - return stages; - } - - @Override - public void registerStage(EngineStage stage) { - stages.add(stage); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/Locator.java b/src/main/java/com/volmit/iris/engine/framework/Locator.java deleted file mode 100644 index 078d59626..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/Locator.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisJigsawStructure; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.math.Spiraler; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import com.volmit.iris.util.scheduling.jobs.SingleJob; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; - -@FunctionalInterface -public interface Locator { - boolean matches(Engine engine, Position2 chunk); - - static void cancelSearch() { - if(LocatorCanceller.cancel != null) { - LocatorCanceller.cancel.run(); - LocatorCanceller.cancel = null; - } - } - - default void find(Player player) { - find(player, 30_000); - } - - default void find(Player player, long timeout) { - AtomicLong checks = new AtomicLong(); - long ms = M.ms(); - new SingleJob("Searching", () -> { - try { - Position2 at = find(IrisToolbelt.access(player.getWorld()).getEngine(), new Position2(player.getLocation().getBlockX() >> 4, player.getLocation().getBlockZ() >> 4), timeout, checks::set).get(); - - if(at != null) { - J.s(() -> player.teleport(new Location(player.getWorld(), (at.getX() << 4) + 8, - IrisToolbelt.access(player.getWorld()).getEngine().getHeight( - (at.getX() << 4) + 8, - (at.getZ() << 4) + 8, false), - (at.getZ() << 4) + 8))); - } - } catch(WrongEngineBroException | InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - }) { - @Override - public String getName() { - return "Searched " + Form.f(checks.get()) + " Chunks"; - } - - @Override - public int getTotalWork() { - return (int) timeout; - } - - @Override - public int getWorkCompleted() { - return (int) Math.min(M.ms() - ms, timeout - 1); - } - }.execute(new VolmitSender(player)); - } - - default Future find(Engine engine, Position2 pos, long timeout, Consumer checks) throws WrongEngineBroException { - if(engine.isClosed()) { - throw new WrongEngineBroException(); - } - - cancelSearch(); - - return MultiBurst.burst.completeValue(() -> { - int tc = IrisSettings.getThreadCount(IrisSettings.get().getConcurrency().getParallelism()) * 17; - MultiBurst burst = MultiBurst.burst; - AtomicBoolean found = new AtomicBoolean(false); - Position2 cursor = pos; - AtomicInteger searched = new AtomicInteger(); - AtomicBoolean stop = new AtomicBoolean(false); - AtomicReference foundPos = new AtomicReference<>(); - PrecisionStopwatch px = PrecisionStopwatch.start(); - LocatorCanceller.cancel = () -> stop.set(true); - AtomicReference next = new AtomicReference<>(cursor); - Spiraler s = new Spiraler(100000, 100000, (x, z) -> next.set(new Position2(x, z))); - s.setOffset(cursor.getX(), cursor.getZ()); - s.next(); - while(!found.get() && !stop.get() && px.getMilliseconds() < timeout) { - BurstExecutor e = burst.burst(tc); - - for(int i = 0; i < tc; i++) { - Position2 p = next.get(); - s.next(); - e.queue(() -> { - if(matches(engine, p)) { - if(foundPos.get() == null) { - foundPos.set(p); - } - - found.set(true); - } - searched.incrementAndGet(); - }); - } - - e.complete(); - checks.accept(searched.get()); - } - - LocatorCanceller.cancel = null; - - if(found.get() && foundPos.get() != null) { - return foundPos.get(); - } - - return null; - }); - } - - static Locator region(String loadKey) { - return (e, c) -> e.getRegion((c.getX() << 4) + 8, (c.getZ() << 4) + 8).getLoadKey().equals(loadKey); - } - - static Locator jigsawStructure(String loadKey) { - return (e, c) -> { - IrisJigsawStructure s = e.getStructureAt(c.getX(), c.getZ()); - return s != null && s.getLoadKey().equals(loadKey); - }; - } - - static Locator object(String loadKey) { - return (e, c) -> e.getObjectsAt(c.getX(), c.getZ()).contains(loadKey); - } - - static Locator surfaceBiome(String loadKey) { - return (e, c) -> e.getSurfaceBiome((c.getX() << 4) + 8, (c.getZ() << 4) + 8).getLoadKey().equals(loadKey); - } - - static Locator caveBiome(String loadKey) { - return (e, c) -> e.getCaveBiome((c.getX() << 4) + 8, (c.getZ() << 4) + 8).getLoadKey().equals(loadKey); - } - - static Locator caveOrMantleBiome(String loadKey) { - return (e, c) -> { - AtomicBoolean found = new AtomicBoolean(false); - e.generateMatter(c.getX(), c.getZ(), true); - e.getMantle().getMantle().iterateChunk(c.getX(), c.getZ(), MatterCavern.class, (x, y, z, t) -> { - if(found.get()) { - return; - } - - if(t != null && t.getCustomBiome().equals(loadKey)) { - found.set(true); - } - }); - - return found.get(); - }; - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/LocatorCanceller.java b/src/main/java/com/volmit/iris/engine/framework/LocatorCanceller.java deleted file mode 100644 index 53ccaf2a8..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/LocatorCanceller.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -public class LocatorCanceller { - protected static Runnable cancel = null; -} diff --git a/src/main/java/com/volmit/iris/engine/framework/LootProvider.java b/src/main/java/com/volmit/iris/engine/framework/LootProvider.java deleted file mode 100644 index b24f2e3ae..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/LootProvider.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.engine.object.InventorySlotType; -import com.volmit.iris.engine.object.IrisLootReference; -import com.volmit.iris.engine.object.IrisLootTable; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import org.bukkit.block.Block; -import org.bukkit.inventory.Inventory; - -public interface LootProvider { - void scramble(Inventory inventory, RNG rng); - - void injectTables(KList list, IrisLootReference r); - - KList getLootTables(RNG rng, Block b); - - void addItems(boolean debug, Inventory inv, RNG rng, KList tables, InventorySlotType slot, int x, int y, int z, int mgf); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/MeteredCache.java b/src/main/java/com/volmit/iris/engine/framework/MeteredCache.java deleted file mode 100644 index 50f5accf2..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/MeteredCache.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.data.KCache; - -public interface MeteredCache { - long getSize(); - - KCache getRawCache(); - - long getMaxSize(); - - default double getUsage() { - return (double) getSize() / (double) getMaxSize(); - } - - boolean isClosed(); -} diff --git a/src/main/java/com/volmit/iris/engine/framework/PlacedObject.java b/src/main/java/com/volmit/iris/engine/framework/PlacedObject.java deleted file mode 100644 index e96155572..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/PlacedObject.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import lombok.AllArgsConstructor; -import lombok.Data; - -import javax.annotation.Nullable; - -@Data -@AllArgsConstructor -public class PlacedObject { - @Nullable - private IrisObjectPlacement placement; - @Nullable - private IrisObject object; - private int id; - private int xx; - private int zz; -} diff --git a/src/main/java/com/volmit/iris/engine/framework/PregeneratedData.java b/src/main/java/com/volmit/iris/engine/framework/PregeneratedData.java deleted file mode 100644 index c0b99bf7a..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/PregeneratedData.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.engine.data.chunk.TerrainChunk; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -import java.util.concurrent.atomic.AtomicBoolean; - -@Data -public class PregeneratedData { - private final Hunk blocks; - private final Hunk post; - private final Hunk biomes; - private final AtomicBoolean postMod; - - public PregeneratedData(int height) { - postMod = new AtomicBoolean(false); - blocks = Hunk.newAtomicHunk(16, height, 16); - biomes = Hunk.newAtomicHunk(16, height, 16); - Hunk p = Hunk.newMappedHunkSynced(16, height, 16); - post = p.trackWrite(postMod); - } - - public Runnable inject(TerrainChunk tc) { - blocks.iterateSync((x, y, z, b) -> { - if(b != null) { - tc.setBlock(x, y, z, b); - } - - Biome bf = biomes.get(x, y, z); - if(bf != null) { - tc.setBiome(x, y, z, bf); - } - }); - - if(postMod.get()) { - return () -> Hunk.view(tc).insertSoftly(0, 0, 0, post, (b) -> b == null || B.isAirOrFluid(b)); - } - - return () -> { - }; - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/SeedManager.java b/src/main/java/com/volmit/iris/engine/framework/SeedManager.java deleted file mode 100644 index cfd2996cc..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/SeedManager.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AccessLevel; -import lombok.Data; -import lombok.Setter; - -@Data -public class SeedManager { - //////////////////////////////////////////////////////////////////// - private static final String IRIS_SIGNATURE = "Iris World Generator"; - private static final long IRIS_TERRAIN_VERSION = 1; - //////////////////////////////////////////////////////////////////// - private final RNG rlock; - private final CNG soup; - private final long seed; - private final long complex; - private final long complexStreams; - private final long basic; - private final long height; - private final long component; - private final long script; - private final long mantle; - private final long entity; - private final long biome; - private final long decorator; - private final long terrain; - private final long spawn; - private final long jigsaw; - private final long carve; - private final long deposit; - private final long post; - private final long bodies; - private final long mode; - @Setter(AccessLevel.NONE) - private long fullMixedSeed; - - public SeedManager(long seed) { - soup = createSoup(seed); - rlock = new RNG(Double.doubleToLongBits(soup.fitDouble(Double.MIN_VALUE, Double.MAX_VALUE, seed + 1337, seed * 69, seed))); - this.seed = seed; - complex = of("complex"); - complexStreams = of("complex_streams"); - basic = of("basic"); - height = of("height"); - component = of("component"); - script = of("script"); - mantle = of("mantle"); - entity = of("entity"); - biome = of("biome"); - decorator = of("decorator"); - terrain = of("terrain"); - spawn = of("spawn"); - jigsaw = of("jigsaw"); - carve = of("carve"); - deposit = of("deposit"); - post = of("post"); - bodies = of("bodies"); - mode = of("mode"); - } - - private long of(String name) { - RNG rng = new RNG(name + IRIS_SIGNATURE + "::" + IRIS_TERRAIN_VERSION + ((seed + rlock.imax()) * rlock.lmax())); - long f = rlock.imax() * ((rlock.chance(0.5) ? 1 : -1) * (name.hashCode() + Double.doubleToLongBits(soup.fitDouble(Double.MIN_VALUE, Double.MAX_VALUE, rng.imax(), rng.imax(), rng.imax())))); - fullMixedSeed += (f * rlock.imax()); - return f; - } - - private CNG createSoup(long seed) { - RNG a = new RNG((seed - 2043905) * 4_385_677_888L); - RNG b = new RNG((seed * -305) + 45_858_458_555L); - RNG c = new RNG((seed * (a.lmax() - b.lmax())) + IRIS_SIGNATURE.hashCode()); - RNG d = new RNG((seed - (c.lmax() * -IRIS_TERRAIN_VERSION)) + IRIS_TERRAIN_VERSION); - RNG e = new RNG((IRIS_TERRAIN_VERSION * 42) + IRIS_SIGNATURE); - double gsoup = 0; - int gk = a.i(1_000, 10_000); - for(char i : (a.s(4) + b.s(4) + c.s(4) + d.s(4) + e.s(4)).toCharArray()) { - gsoup += ((gk * b.d(3, Math.PI)) / c.d(10, 18 * Math.E)) + 6_549; - gsoup *= d.d(90.5, 1_234_567); - gsoup += e.d(39.95, 99.25); - } - - return NoiseStyle.STATIC.create(new RNG(4_966_866 * Double.doubleToLongBits((gsoup * a.imax() + b.imax() + c.lmax() + d.lmax()) * e.lmax()))); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/Staged.java b/src/main/java/com/volmit/iris/engine/framework/Staged.java deleted file mode 100644 index 52a8b8e07..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/Staged.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -import com.volmit.iris.util.collection.KList; - -public interface Staged { - KList getStages(); - - void registerStage(EngineStage stage); - - default void dump() { - getStages().forEach(EngineStage::close); - getStages().clear(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/framework/WrongEngineBroException.java b/src/main/java/com/volmit/iris/engine/framework/WrongEngineBroException.java deleted file mode 100644 index 63db6f72f..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/WrongEngineBroException.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework; - -public class WrongEngineBroException extends Exception { -} diff --git a/src/main/java/com/volmit/iris/engine/framework/placer/HeightmapObjectPlacer.java b/src/main/java/com/volmit/iris/engine/framework/placer/HeightmapObjectPlacer.java deleted file mode 100644 index 189013a45..000000000 --- a/src/main/java/com/volmit/iris/engine/framework/placer/HeightmapObjectPlacer.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.framework.placer; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IObjectPlacer; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.TileData; -import com.volmit.iris.util.math.RNG; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; - -public class HeightmapObjectPlacer implements IObjectPlacer { - private final long s; - private final IrisObjectPlacement config; - private final IObjectPlacer oplacer; - - public HeightmapObjectPlacer(Engine engine, RNG rng, int x, int yv, int z, IrisObjectPlacement config, IObjectPlacer oplacer) { - s = rng.nextLong() + yv + z - x; - this.config = config; - this.oplacer = oplacer; - } - - public int getHighest(int param1Int1, int param1Int2, IrisData data) { - return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, data)); - } - - public int getHighest(int param1Int1, int param1Int2, IrisData data, boolean param1Boolean) { - return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, data)); - } - - public void set(int param1Int1, int param1Int2, int param1Int3, BlockData param1BlockData) { - oplacer.set(param1Int1, param1Int2, param1Int3, param1BlockData); - } - - public BlockData get(int param1Int1, int param1Int2, int param1Int3) { - return oplacer.get(param1Int1, param1Int2, param1Int3); - } - - public boolean isPreventingDecay() { - return oplacer.isPreventingDecay(); - } - - @Override - public boolean isCarved(int x, int y, int z) { - return false; - } - - public boolean isSolid(int param1Int1, int param1Int2, int param1Int3) { - return oplacer.isSolid(param1Int1, param1Int2, param1Int3); - } - - public boolean isUnderwater(int param1Int1, int param1Int2) { - return oplacer.isUnderwater(param1Int1, param1Int2); - } - - public int getFluidHeight() { - return oplacer.getFluidHeight(); - } - - public boolean isDebugSmartBore() { - return oplacer.isDebugSmartBore(); - } - - public void setTile(int param1Int1, int param1Int2, int param1Int3, TileData param1TileData) { - oplacer.setTile(param1Int1, param1Int2, param1Int3, param1TileData); - } - - @Override - public Engine getEngine() { - return null; - } -} diff --git a/src/main/java/com/volmit/iris/engine/jigsaw/PlannedPiece.java b/src/main/java/com/volmit/iris/engine/jigsaw/PlannedPiece.java deleted file mode 100644 index b33facb9e..000000000 --- a/src/main/java/com/volmit/iris/engine/jigsaw/PlannedPiece.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.jigsaw; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IObjectPlacer; -import com.volmit.iris.engine.object.InventorySlotType; -import com.volmit.iris.engine.object.IrisJigsawPiece; -import com.volmit.iris.engine.object.IrisJigsawPieceConnector; -import com.volmit.iris.engine.object.IrisLootTable; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectRotation; -import com.volmit.iris.engine.object.IrisObjectTranslate; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.engine.object.TileData; -import com.volmit.iris.engine.platform.PlatformChunkGenerator; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.math.AxisAlignedBB; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.math.RNG; -import lombok.Data; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.util.BlockVector; - -@SuppressWarnings("ALL") -@Data -public class PlannedPiece { - private IrisPosition position; - private IrisObject object; - private IrisObject ogObject; - private IrisJigsawPiece piece; - private IrisObjectRotation rotation; - private IrisData data; - private KList connected; - private boolean dead = false; - private AxisAlignedBB box; - private PlannedStructure structure; - - public PlannedPiece(PlannedStructure structure, IrisPosition position, IrisJigsawPiece piece) { - this(structure, position, piece, 0, 0, 0); - } - - public PlannedPiece(PlannedStructure structure, IrisPosition position, IrisJigsawPiece piece, int rx, int ry, int rz) { - this(structure, position, piece, IrisObjectRotation.of(rx * 90D, ry * 90D, rz * 90D)); - } - - public PlannedPiece(PlannedStructure structure, IrisPosition position, IrisJigsawPiece piece, IrisObjectRotation rot) { - this.structure = structure; - this.position = position; - this.data = piece.getLoader(); - this.setRotation(rot); - this.ogObject = data.getObjectLoader().load(piece.getObject()); - this.object = structure.rotated(piece, rotation); - this.piece = rotation.rotateCopy(piece); - this.piece.setLoadKey(piece.getLoadKey()); - this.object.setLoadKey(piece.getObject()); - this.ogObject.setLoadKey(piece.getObject()); - this.connected = new KList<>(); - } - - public void setPosition(IrisPosition p) { - this.position = p; - box = null; - } - - public String toString() { - return piece.getLoadKey() + "@(" + position.getX() + "," + position.getY() + "," + position.getZ() + ")[rot:" + rotation.toString() + "]"; - } - - public AxisAlignedBB getBox() { - if(box != null) { - return box; - } - - BlockVector v = getObject().getCenter(); - box = object.getAABB().shifted(position.add(new IrisPosition(object.getCenter()))); - return box; - } - - public boolean contains(IrisPosition p) { - return getBox().contains(p); - } - - public boolean collidesWith(PlannedPiece p) { - return getBox().intersects(p.getBox()); - } - - public KList getAvailableConnectors() { - if(connected.isEmpty()) { - return piece.getConnectors().copy(); - } - - if(connected.size() == piece.getConnectors().size()) { - return new KList<>(); - } - - KList c = new KList<>(); - - for(IrisJigsawPieceConnector i : piece.getConnectors()) { - if(!connected.contains(i)) { - c.add(i); - } - } - - return c; - } - - public boolean connect(IrisJigsawPieceConnector c) { - if(piece.getConnectors().contains(c)) { - return connected.addIfMissing(c); - } - - return false; - } - - public IrisPosition getWorldPosition(IrisJigsawPieceConnector c) { - return getWorldPosition(c.getPosition()); - } - - public IrisPosition getWorldPosition(IrisPosition position) { - return this.position.add(position).add(new IrisPosition(object.getCenter())); - } - - public boolean isFull() { - return connected.size() >= piece.getConnectors().size() || isDead(); - } - - public void place(World world) { - PlatformChunkGenerator a = IrisToolbelt.access(world); - - int minY = 0; - if(a != null) { - minY = a.getEngine().getMinHeight(); - - if(!a.getEngine().getDimension().isBedrock()) - minY--; //If the dimension has no bedrock, allow it to go a block lower - } - - getPiece().getPlacementOptions().setTranslate(new IrisObjectTranslate()); - getPiece().getPlacementOptions().setRotation(rotation); - int finalMinY = minY; - RNG rng = getStructure().getRng().nextParallelRNG(37555); - - // TODO: REAL CLASSES!!!!!!! - getOgObject().place(position.getX() + getObject().getCenter().getBlockX(), position.getY() + getObject().getCenter().getBlockY(), position.getZ() + getObject().getCenter().getBlockZ(), new IObjectPlacer() { - @Override - public int getHighest(int x, int z, IrisData data) { - return position.getY(); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return position.getY(); - } - - @Override - public void set(int x, int y, int z, BlockData d) { - Block block = world.getBlockAt(x, y, z); - - //Prevent blocks being set in or bellow bedrock - if(y <= finalMinY || block.getType() == Material.BEDROCK) return; - - block.setBlockData(d); - - if(a != null && getPiece().getPlacementOptions().getLoot().isNotEmpty() && - block.getState() instanceof InventoryHolder) { - - IrisLootTable table = getPiece().getPlacementOptions().getTable(block.getBlockData(), getData()); - if(table == null) return; - Engine engine = a.getEngine(); - engine.addItems(false, ((InventoryHolder) block.getState()).getInventory(), - rng.nextParallelRNG(BlockPosition.toLong(x, y, z)), - new KList<>(table), InventorySlotType.STORAGE, x, y, z, 15); - } - } - - @Override - public BlockData get(int x, int y, int z) { - return world.getBlockAt(x, y, z).getBlockData(); - } - - @Override - public boolean isPreventingDecay() { - return false; - } - - @Override - public boolean isCarved(int x, int y, int z) { - return false; - } - - @Override - public boolean isSolid(int x, int y, int z) { - return world.getBlockAt(x, y, z).getType().isSolid(); - } - - @Override - public boolean isUnderwater(int x, int z) { - return false; - } - - @Override - public int getFluidHeight() { - return 0; - } - - @Override - public boolean isDebugSmartBore() { - return false; - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - BlockState state = world.getBlockAt(xx, yy, zz).getState(); - tile.toBukkitTry(state); - state.update(); - } - - @Override - public Engine getEngine() { - if(IrisToolbelt.isIrisWorld(world)) { - return IrisToolbelt.access(world).getEngine(); - } - - return IrisContext.get().getEngine(); - } - }, piece.getPlacementOptions(), rng, getData()); - } -} diff --git a/src/main/java/com/volmit/iris/engine/jigsaw/PlannedStructure.java b/src/main/java/com/volmit/iris/engine/jigsaw/PlannedStructure.java deleted file mode 100644 index dfda4e11f..000000000 --- a/src/main/java/com/volmit/iris/engine/jigsaw/PlannedStructure.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.jigsaw; - -import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap; -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IObjectPlacer; -import com.volmit.iris.engine.object.IrisDirection; -import com.volmit.iris.engine.object.IrisJigsawPiece; -import com.volmit.iris.engine.object.IrisJigsawPieceConnector; -import com.volmit.iris.engine.object.IrisJigsawStructure; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.IrisObjectRotation; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.engine.object.ObjectPlaceMode; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.math.RNG; -import lombok.Data; -import org.bukkit.Axis; -import org.bukkit.World; - -@Data -public class PlannedStructure { - private static transient ConcurrentLinkedHashMap objectRotationCache - = new ConcurrentLinkedHashMap.Builder() - .initialCapacity(64) - .maximumWeightedCapacity(1024) - .concurrencyLevel(32) - .build(); - private KList pieces; - private IrisJigsawStructure structure; - private IrisPosition position; - private IrisData data; - private RNG rng; - private boolean verbose; - private boolean terminating; - - public PlannedStructure(IrisJigsawStructure structure, IrisPosition position, RNG rng) { - terminating = false; - verbose = true; - this.pieces = new KList<>(); - this.structure = structure; - this.position = position; - this.rng = rng; - this.data = structure.getLoader(); - generateStartPiece(); - - for(int i = 0; i < structure.getMaxDepth(); i++) { - generateOutwards(); - } - - generateTerminators(); - - Iris.debug("JPlace: ROOT @ relative " + position.toString()); - - for(PlannedPiece i : pieces) { - Iris.debug("Place: " + i.getObject().getLoadKey() + " at @ relative " + i.getPosition().toString()); - } - } - - public void place(IObjectPlacer placer, Mantle e, Engine eng) { - IrisObjectPlacement options = new IrisObjectPlacement(); - options.getRotation().setEnabled(false); - int startHeight = pieces.get(0).getPosition().getY(); - - for(PlannedPiece i : pieces) { - place(i, startHeight, options, placer, e, eng); - } - } - - public void place(PlannedPiece i, int startHeight, IrisObjectPlacement o, IObjectPlacer placer, Mantle e, Engine eng) { - IrisObjectPlacement options = o; - - if(i.getPiece().getPlacementOptions() != null) { - options = i.getPiece().getPlacementOptions(); - options.getRotation().setEnabled(false); - } else { - options.setMode(i.getPiece().getPlaceMode()); - } - - IrisObject vo = i.getOgObject(); - IrisObject v = i.getObject(); - int sx = (v.getW() / 2); - int sz = (v.getD() / 2); - int xx = i.getPosition().getX() + sx; - int zz = i.getPosition().getZ() + sz; - RNG rngf = new RNG(Cache.key(xx, zz)); - int offset = i.getPosition().getY() - startHeight; - int height = 0; - - if(i.getStructure().getStructure().getLockY() == -1) { - if(i.getStructure().getStructure().getOverrideYRange() != null) { - height = (int) i.getStructure().getStructure().getOverrideYRange().get(rng, xx, zz, getData()); - } else { - height = placer.getHighest(xx, zz, getData()); - } - } else { - height = i.getStructure().getStructure().getLockY(); - } - - height += offset + (v.getH() / 2); - - if(options.getMode().equals(ObjectPlaceMode.PAINT)) { - height = -1; - } - - int id = rng.i(0, Integer.MAX_VALUE); - vo.place(xx, height, zz, placer, options, rng, e.shouldReduce(eng) ? null : (b) - -> e.set(b.getX(), b.getY(), b.getZ(), v.getLoadKey() + "@" + id), null, getData()); - } - - public void place(World world) { - for(PlannedPiece i : pieces) { - Iris.sq(() -> i.place(world)); - } - } - - private void generateOutwards() { - for(PlannedPiece i : getPiecesWithAvailableConnectors().shuffle(rng)) { - if(!generatePieceOutwards(i)) { - i.setDead(true); - } - } - } - - private boolean generatePieceOutwards(PlannedPiece piece) { - boolean b = false; - - for(IrisJigsawPieceConnector i : piece.getAvailableConnectors().shuffleCopy(rng)) { - if(generateConnectorOutwards(piece, i)) { - b = true; - } - } - - return b; - } - - private boolean generateConnectorOutwards(PlannedPiece piece, IrisJigsawPieceConnector pieceConnector) { - for(IrisJigsawPiece i : getShuffledPiecesFor(pieceConnector)) { - if(generateRotatedPiece(piece, pieceConnector, i)) { - return true; - } - } - - return false; - } - - private boolean generateRotatedPiece(PlannedPiece piece, IrisJigsawPieceConnector pieceConnector, IrisJigsawPiece idea) { - if(!piece.getPiece().getPlacementOptions().getRotation().isEnabled()) { - if(generateRotatedPiece(piece, pieceConnector, idea, 0, 0, 0)) { - return true; - } - } - - KList forder1 = new KList().qadd(0).qadd(1).qadd(2).qadd(3).shuffle(rng); - KList forder2 = new KList().qadd(0).qadd(1).qadd(2).qadd(3).shuffle(rng); - - for(Integer i : forder1) { - if(pieceConnector.isRotateConnector()) { - assert pieceConnector.getDirection().getAxis() != null; - if(!pieceConnector.getDirection().getAxis().equals(Axis.Y)) { - for(Integer j : forder2) { - if(pieceConnector.getDirection().getAxis().equals(Axis.X) && generateRotatedPiece(piece, pieceConnector, idea, j, i, 0)) { - return true; - } - - if(pieceConnector.getDirection().getAxis().equals(Axis.Z) && generateRotatedPiece(piece, pieceConnector, idea, 0, i, j)) { - return true; - } - } - } - } - - if(generateRotatedPiece(piece, pieceConnector, idea, 0, i, 0)) { - return true; - } - } - - return false; - } - - private boolean generateRotatedPiece(PlannedPiece piece, IrisJigsawPieceConnector pieceConnector, IrisJigsawPiece idea, IrisObjectRotation rotation) { - if(!idea.getPlacementOptions().getRotation().isEnabled()) { - rotation = piece.getRotation(); - } - - PlannedPiece test = new PlannedPiece(this, piece.getPosition(), idea, rotation); - - for(IrisJigsawPieceConnector j : test.getPiece().getConnectors().shuffleCopy(rng)) { - if(generatePositionedPiece(piece, pieceConnector, test, j)) { - return true; - } - } - - return false; - } - - private boolean generateRotatedPiece(PlannedPiece piece, IrisJigsawPieceConnector pieceConnector, IrisJigsawPiece idea, int x, int y, int z) { - return generateRotatedPiece(piece, pieceConnector, idea, IrisObjectRotation.of(x, y, z)); - } - - private boolean generatePositionedPiece(PlannedPiece piece, - IrisJigsawPieceConnector pieceConnector, - PlannedPiece test, - IrisJigsawPieceConnector testConnector) { - test.setPosition(new IrisPosition(0, 0, 0)); - IrisPosition connector = piece.getWorldPosition(pieceConnector); - IrisDirection desiredDirection = pieceConnector.getDirection().reverse(); - IrisPosition desiredPosition = connector.sub(new IrisPosition(desiredDirection.toVector())); - - if(!pieceConnector.getTargetName().equals("*") && !pieceConnector.getTargetName().equals(testConnector.getName())) { - return false; - } - - if(!testConnector.getDirection().equals(desiredDirection)) { - return false; - } - - IrisPosition shift = test.getWorldPosition(testConnector); - test.setPosition(desiredPosition.sub(shift)); - - if(collidesWith(test, piece)) { - return false; - } - - piece.connect(pieceConnector); - test.connect(testConnector); - pieces.add(test); - - return true; - } - - private KList getShuffledPiecesFor(IrisJigsawPieceConnector c) { - KList p = new KList<>(); - - for(String i : c.getPools().shuffleCopy(rng)) { - for(String j : getData().getJigsawPoolLoader().load(i).getPieces().shuffleCopy(rng)) { - IrisJigsawPiece pi = getData().getJigsawPieceLoader().load(j); - - if(pi == null || (terminating && !pi.isTerminal())) { - continue; - } - - p.addIfMissing(pi); - } - } - return p.shuffle(rng); - } - - private void generateStartPiece() { - pieces.add(new PlannedPiece(this, position, getData().getJigsawPieceLoader().load(rng.pick(getStructure().getPieces())), 0, rng.nextInt(4), 0)); - } - - private void generateTerminators() { - if(getStructure().isTerminate()) { - terminating = true; - generateOutwards(); - } - } - - public KList getPiecesWithAvailableConnectors() { - return pieces.copy().removeWhere(PlannedPiece::isFull); - } - - public int getVolume() { - int v = 0; - - for(PlannedPiece i : pieces) { - v += i.getObject().getH() * i.getObject().getW() * i.getObject().getD(); - } - - return v; - } - - public int getMass() { - int v = 0; - - for(PlannedPiece i : pieces) { - v += i.getObject().getBlocks().size(); - } - - return v; - } - - public boolean collidesWith(PlannedPiece piece, PlannedPiece ignore) { - for(PlannedPiece i : pieces) { - if(i.equals(ignore)) { - continue; - } - - if(i.collidesWith(piece)) { - return true; - } - } - - return false; - } - - public boolean contains(IrisPosition p) { - for(PlannedPiece i : pieces) { - if(i.contains(p)) { - return true; - } - } - - return false; - } - - public IrisObject rotated(IrisJigsawPiece piece, IrisObjectRotation rotation) { - String key = piece.getObject() + "-" + rotation.hashCode(); - - return objectRotationCache.computeIfAbsent(key, (k) -> rotation.rotateCopy(data.getObjectLoader().load(piece.getObject()))); - } -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/EngineMantle.java b/src/main/java/com/volmit/iris/engine/mantle/EngineMantle.java deleted file mode 100644 index 127b37bd7..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/EngineMantle.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle; - -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineTarget; -import com.volmit.iris.engine.mantle.components.MantleJigsawComponent; -import com.volmit.iris.engine.mantle.components.MantleObjectComponent; -import com.volmit.iris.engine.object.IObjectPlacer; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.engine.object.TileData; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.mantle.MantleChunk; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.matter.*; -import com.volmit.iris.util.matter.slices.UpdateMatter; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; - -import java.util.concurrent.TimeUnit; - -// TODO: MOVE PLACER OUT OF MATTER INTO ITS OWN THING -public interface EngineMantle extends IObjectPlacer { - BlockData AIR = B.get("AIR"); - - Mantle getMantle(); - - Engine getEngine(); - - int getRadius(); - - KList getComponents(); - - void registerComponent(MantleComponent c); - - default int getHighest(int x, int z) { - return getHighest(x, z, getData()); - } - - @ChunkCoordinates - default KList findMarkers(int x, int z, MatterMarker marker) { - KList p = new KList<>(); - getMantle().iterateChunk(x, z, MatterMarker.class, (xx, yy, zz, mm) -> { - if(marker.equals(mm)) { - p.add(new IrisPosition(xx + (x << 4), yy, zz + (z << 4))); - } - }); - - return p; - } - - default int getHighest(int x, int z, boolean ignoreFluid) { - return getHighest(x, z, getData(), ignoreFluid); - } - - @Override - default int getHighest(int x, int z, IrisData data) { - return getHighest(x, z, data, false); - } - - @Override - default int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return ignoreFluid ? trueHeight(x, z) : Math.max(trueHeight(x, z), getEngine().getDimension().getFluidHeight()); - } - - default int trueHeight(int x, int z) { - return getComplex().getRoundedHeighteightStream().get(x, z); - } - - default boolean isCarved(int x, int h, int z) { - return getMantle().get(x, h, z, MatterCavern.class) != null; - } - - @Override - default void set(int x, int y, int z, BlockData d) { - getMantle().set(x, y, z, d == null ? AIR : d); - } - - @Override - default void setTile(int x, int y, int z, TileData d) { - getMantle().set(x, y, z, new TileWrapper(d)); - } - - @Override - default BlockData get(int x, int y, int z) { - BlockData block = getMantle().get(x, y, z, BlockData.class); - if(block == null) - return AIR; - return block; - } - - @Override - default boolean isPreventingDecay() { - return getEngine().getDimension().isPreventLeafDecay(); - } - - @Override - default boolean isSolid(int x, int y, int z) { - return B.isSolid(get(x, y, z)); - } - - @Override - default boolean isUnderwater(int x, int z) { - return getHighest(x, z, true) <= getFluidHeight(); - } - - @Override - default int getFluidHeight() { - return getEngine().getDimension().getFluidHeight(); - } - - @Override - default boolean isDebugSmartBore() { - return getEngine().getDimension().isDebugSmartBore(); - } - - default void trim(long dur) { - getMantle().trim(dur); - } - - default IrisData getData() { - return getEngine().getData(); - } - - default EngineTarget getTarget() { - return getEngine().getTarget(); - } - - default IrisDimension getDimension() { - return getEngine().getDimension(); - } - - default IrisComplex getComplex() { - return getEngine().getComplex(); - } - - default void close() { - getMantle().close(); - } - - default void saveAllNow() { - getMantle().saveAll(); - } - - default void save() { - - } - - default void trim() { - getMantle().trim(TimeUnit.SECONDS.toMillis(IrisSettings.get().getPerformance().getMantleKeepAlive())); - } - - default MultiBurst burst() { - return getEngine().burst(); - } - - default int getRealRadius() { - return (int) Math.ceil(getRadius() / 2D); - } - - - @ChunkCoordinates - default void generateMatter(int x, int z, boolean multicore) { - if(!getEngine().getDimension().isUseMantle()) { - return; - } - - int s = getRealRadius(); - BurstExecutor burst = burst().burst(multicore); - MantleWriter writer = getMantle().write(this, x, z, s * 2); - for(int i = -s; i <= s; i++) { - for(int j = -s; j <= s; j++) { - int xx = i + x; - int zz = j + z; - burst.queue(() -> { - IrisContext.touch(getEngine().getContext()); - getMantle().raiseFlag(xx, zz, MantleFlag.PLANNED, () -> { - MantleChunk mc = getMantle().getChunk(xx, zz); - - for(MantleComponent k : getComponents()) { - generateMantleComponent(writer, xx, zz, k, mc); - } - }); - }); - } - } - - burst.complete(); - } - - default void generateMantleComponent(MantleWriter writer, int x, int z, MantleComponent c, MantleChunk mc) { - mc.raiseFlag(c.getFlag(), () -> c.generateLayer(writer, x, z)); - } - - @ChunkCoordinates - default void insertMatter(int x, int z, Class t, Hunk blocks, boolean multicore) { - if(!getEngine().getDimension().isUseMantle()) { - return; - } - - getMantle().iterateChunk(x, z, t, blocks::set); - } - - @BlockCoordinates - default void updateBlock(int x, int y, int z) { - getMantle().set(x, y, z, UpdateMatter.ON); - } - - @BlockCoordinates - default void dropCavernBlock(int x, int y, int z) { - Matter matter = getMantle().getChunk(x & 15, z & 15).get(y & 15); - - if(matter != null) { - matter.slice(MatterCavern.class).set(x & 15, y & 15, z & 15, null); - } - } - - default boolean queueRegenerate(int x, int z) { - return false; // TODO: - } - - default boolean dequeueRegenerate(int x, int z) { - return false;// TODO: - } - - default int getLoadedRegionCount() { - return getMantle().getLoadedRegionCount(); - } - - MantleJigsawComponent getJigsawComponent(); - - MantleObjectComponent getObjectComponent(); - - default boolean isCovered(int x, int z) { - int s = getRealRadius(); - - for(int i = -s; i <= s; i++) { - for(int j = -s; j <= s; j++) { - int xx = i + x; - int zz = j + z; - if(!getMantle().hasFlag(xx, zz, MantleFlag.REAL)) { - return false; - } - } - } - - return true; - } - - default void cleanupChunk(int x, int z) { - if(!getMantle().hasFlag(x, z, MantleFlag.CLEANED) && isCovered(x, z)) { - getMantle().raiseFlag(x, z, MantleFlag.CLEANED, () -> { - getMantle().deleteChunkSlice(x, z, BlockData.class); - getMantle().deleteChunkSlice(x, z, String.class); - getMantle().deleteChunkSlice(x, z, MatterCavern.class); - getMantle().deleteChunkSlice(x, z, MatterFluidBody.class); - }); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/IrisMantleComponent.java b/src/main/java/com/volmit/iris/engine/mantle/IrisMantleComponent.java deleted file mode 100644 index 16c71652d..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/IrisMantleComponent.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle; - -import com.volmit.iris.util.mantle.MantleFlag; -import lombok.Data; - -@Data -public abstract class IrisMantleComponent implements MantleComponent { - private final EngineMantle engineMantle; - private final MantleFlag flag; -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/MantleComponent.java b/src/main/java/com/volmit/iris/engine/mantle/MantleComponent.java deleted file mode 100644 index de299f92f..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/MantleComponent.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.parallel.BurstExecutor; - -public interface MantleComponent { - default int getRadius() { - return getEngineMantle().getRealRadius(); - } - - default IrisData getData() { - return getEngineMantle().getData(); - } - - default IrisDimension getDimension() { - return getEngineMantle().getEngine().getDimension(); - } - - default IrisComplex getComplex() { - return getEngineMantle().getComplex(); - } - - default long seed() { - return getEngineMantle().getEngine().getSeedManager().getMantle(); - } - - default BurstExecutor burst() { - return getEngineMantle().getEngine().burst().burst(); - } - - EngineMantle getEngineMantle(); - - default Mantle getMantle() { - return getEngineMantle().getMantle(); - } - - MantleFlag getFlag(); - - @ChunkCoordinates - void generateLayer(MantleWriter writer, int x, int z); -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/MantleSized.java b/src/main/java/com/volmit/iris/engine/mantle/MantleSized.java deleted file mode 100644 index 724188574..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/MantleSized.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle; - -public interface MantleSized { - int getMaxChunkSize(); -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/MantleWriter.java b/src/main/java/com/volmit/iris/engine/mantle/MantleWriter.java deleted file mode 100644 index 7e25db679..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/MantleWriter.java +++ /dev/null @@ -1,694 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle; - -import com.google.common.collect.ImmutableList; -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IObjectPlacer; -import com.volmit.iris.engine.object.IrisGeneratorStyle; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.engine.object.TileData; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.mantle.MantleChunk; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.Matter; -import lombok.Data; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; -import org.bukkit.util.Vector; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -@Data -public class MantleWriter implements IObjectPlacer { - private final EngineMantle engineMantle; - private final Mantle mantle; - private final KMap cachedChunks; - private final int radius; - private final int x; - private final int z; - - public MantleWriter(EngineMantle engineMantle, Mantle mantle, int x, int z, int radius) { - this.engineMantle = engineMantle; - this.mantle = mantle; - this.cachedChunks = new KMap<>(); - this.radius = radius; - this.x = x; - this.z = z; - - for(int i = -radius; i <= radius; i++) { - for(int j = -radius; j <= radius; j++) { - cachedChunks.put(Cache.key(i + x, j + z), mantle.getChunk(i + x, j + z)); - } - } - } - - private static Set getBallooned(Set vset, double radius) { - Set returnset = new HashSet<>(); - int ceilrad = (int) Math.ceil(radius); - - for(IrisPosition v : vset) { - int tipx = v.getX(); - int tipy = v.getY(); - int tipz = v.getZ(); - - for(int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) { - for(int loopy = tipy - ceilrad; loopy <= tipy + ceilrad; loopy++) { - for(int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) { - if(hypot(loopx - tipx, loopy - tipy, loopz - tipz) <= radius) { - returnset.add(new IrisPosition(loopx, loopy, loopz)); - } - } - } - } - } - return returnset; - } - - private static Set getHollowed(Set vset) { - Set returnset = new KSet<>(); - for(IrisPosition v : vset) { - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); - if(!(vset.contains(new IrisPosition(x + 1, y, z)) - && vset.contains(new IrisPosition(x - 1, y, z)) - && vset.contains(new IrisPosition(x, y + 1, z)) - && vset.contains(new IrisPosition(x, y - 1, z)) - && vset.contains(new IrisPosition(x, y, z + 1)) - && vset.contains(new IrisPosition(x, y, z - 1)))) { - returnset.add(v); - } - } - return returnset; - } - - private static double hypot(double... pars) { - double sum = 0; - for(double d : pars) { - sum += Math.pow(d, 2); - } - return Math.sqrt(sum); - } - - private static double lengthSq(double x, double y, double z) { - return (x * x) + (y * y) + (z * z); - } - - private static double lengthSq(double x, double z) { - return (x * x) + (z * z); - } - - public void setDataWarped(int x, int y, int z, T t, RNG rng, IrisData data, IrisGeneratorStyle style) - { - setData((int)Math.round(style.warp(rng, data, x, x, y, -z)), - (int)Math.round(style.warp(rng, data, y, z, -x, y)), - (int)Math.round(style.warp(rng, data, z, -y, z, x)), t); - } - - public void setData(int x, int y, int z, T t) { - if(t == null) { - return; - } - - int cx = x >> 4; - int cz = z >> 4; - - if(y < 0 || y >= mantle.getWorldHeight()) { - return; - } - - if(cx >= this.x - radius && cx <= this.x + radius - && cz >= this.z - radius && cz <= this.z + radius) { - MantleChunk chunk = cachedChunks.get(Cache.key(cx, cz)); - - if(chunk == null) { - Iris.error("Mantle Writer Accessed " + cx + "," + cz + " and came up null (and yet within bounds!)"); - return; - } - - Matter matter = chunk.getOrCreate(y >> 4); - matter.slice(matter.getClass(t)).set(x & 15, y & 15, z & 15, t); - } - } - - @Override - public int getHighest(int x, int z, IrisData data) { - return engineMantle.getHighest(x, z, data); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { - return engineMantle.getHighest(x, z, data, ignoreFluid); - } - - @Override - public void set(int x, int y, int z, BlockData d) { - setData(x, y, z, d); - } - - @Override - public BlockData get(int x, int y, int z) { - return getEngineMantle().get(x, y, z); - } - - @Override - public boolean isPreventingDecay() { - return getEngineMantle().isPreventingDecay(); - } - - @Override - public boolean isCarved(int x, int y, int z) { - return getEngineMantle().isCarved(x, y, z); - } - - @Override - public boolean isSolid(int x, int y, int z) { - return getEngineMantle().isSolid(x, y, z); - } - - @Override - public boolean isUnderwater(int x, int z) { - return getEngineMantle().isUnderwater(x, z); - } - - @Override - public int getFluidHeight() { - return getEngineMantle().getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return getEngineMantle().isDebugSmartBore(); - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - getEngineMantle().setTile(xx, yy, zz, tile); - } - - @Override - public Engine getEngine() { - return getEngineMantle().getEngine(); - } - - /** - * Set a sphere into the mantle - * - * @param cx - * the center x - * @param cy - * the center y - * @param cz - * the center z - * @param radius - * the radius of this sphere - * @param fill - * should it be filled? or just the outer shell? - * @param data - * the data to set - * @param - * the type of data to apply to the mantle - */ - public void setSphere(int cx, int cy, int cz, double radius, boolean fill, T data) { - setElipsoid(cx, cy, cz, radius, radius, radius, fill, data); - } - - public void setElipsoid(int cx, int cy, int cz, double rx, double ry, double rz, boolean fill, T data) { - setElipsoidFunction(cx, cy, cz, rx, ry, rz, fill, (a, b, c) -> data); - } - - public void setElipsoidWarped(int cx, int cy, int cz, double rx, double ry, double rz, boolean fill, T data, RNG rng, IrisData idata, IrisGeneratorStyle style) { - setElipsoidFunctionWarped(cx, cy, cz, rx, ry, rz, fill, (a, b, c) -> data, rng, idata, style); - } - - /** - * Set an elipsoid into the mantle - * - * @param cx - * the center x - * @param cy - * the center y - * @param cz - * the center z - * @param rx - * the x radius - * @param ry - * the y radius - * @param rz - * the z radius - * @param fill - * should it be filled or just the outer shell? - * @param data - * the data to set - * @param - * the type of data to apply to the mantle - */ - public void setElipsoidFunction(int cx, int cy, int cz, double rx, double ry, double rz, boolean fill, Function3 data) { - rx += 0.5; - ry += 0.5; - rz += 0.5; - final double invRadiusX = 1 / rx; - final double invRadiusY = 1 / ry; - final double invRadiusZ = 1 / rz; - final int ceilRadiusX = (int) Math.ceil(rx); - final int ceilRadiusY = (int) Math.ceil(ry); - final int ceilRadiusZ = (int) Math.ceil(rz); - double nextXn = 0; - - forX: - for(int x = 0; x <= ceilRadiusX; ++x) { - final double xn = nextXn; - nextXn = (x + 1) * invRadiusX; - double nextYn = 0; - forY: - for(int y = 0; y <= ceilRadiusY; ++y) { - final double yn = nextYn; - nextYn = (y + 1) * invRadiusY; - double nextZn = 0; - for(int z = 0; z <= ceilRadiusZ; ++z) { - final double zn = nextZn; - nextZn = (z + 1) * invRadiusZ; - - double distanceSq = lengthSq(xn, yn, zn); - if(distanceSq > 1) { - if(z == 0) { - if(y == 0) { - break forX; - } - break forY; - } - break; - } - - if(!fill) { - if(lengthSq(nextXn, yn, zn) <= 1 && lengthSq(xn, nextYn, zn) <= 1 && lengthSq(xn, yn, nextZn) <= 1) { - continue; - } - } - - setData(x + cx, y + cy, z + cz, data.apply(x + cx, y + cy, z + cz)); - setData(-x + cx, y + cy, z + cz, data.apply(-x + cx, y + cy, z + cz)); - setData(x + cx, -y + cy, z + cz, data.apply(x + cx, -y + cy, z + cz)); - setData(x + cx, y + cy, -z + cz, data.apply(x + cx, y + cy, -z + cz)); - setData(-x + cx, y + cy, -z + cz, data.apply(-x + cx, y + cy, -z + cz)); - setData(-x + cx, -y + cy, z + cz, data.apply(-x + cx, -y + cy, z + cz)); - setData(x + cx, -y + cy, -z + cz, data.apply(x + cx, -y + cy, -z + cz)); - setData(-x + cx, y + cy, -z + cz, data.apply(-x + cx, y + cy, -z + cz)); - setData(-x + cx, -y + cy, -z + cz, data.apply(-x + cx, -y + cy, -z + cz)); - } - } - } - } - - public void setElipsoidFunctionWarped(int cx, int cy, int cz, double rx, double ry, double rz, boolean fill, Function3 data, RNG rng, IrisData idata, IrisGeneratorStyle style) { - rx += 0.5; - ry += 0.5; - rz += 0.5; - final double invRadiusX = 1 / rx; - final double invRadiusY = 1 / ry; - final double invRadiusZ = 1 / rz; - final int ceilRadiusX = (int) Math.ceil(rx); - final int ceilRadiusY = (int) Math.ceil(ry); - final int ceilRadiusZ = (int) Math.ceil(rz); - double nextXn = 0; - - forX: - for(int x = 0; x <= ceilRadiusX; ++x) { - final double xn = nextXn; - nextXn = (x + 1) * invRadiusX; - double nextYn = 0; - forY: - for(int y = 0; y <= ceilRadiusY; ++y) { - final double yn = nextYn; - nextYn = (y + 1) * invRadiusY; - double nextZn = 0; - for(int z = 0; z <= ceilRadiusZ; ++z) { - final double zn = nextZn; - nextZn = (z + 1) * invRadiusZ; - - double distanceSq = lengthSq(xn, yn, zn); - if(distanceSq > 1) { - if(z == 0) { - if(y == 0) { - break forX; - } - break forY; - } - break; - } - - if(!fill) { - if(lengthSq(nextXn, yn, zn) <= 1 && lengthSq(xn, nextYn, zn) <= 1 && lengthSq(xn, yn, nextZn) <= 1) { - continue; - } - } - - setDataWarped(x + cx, y + cy, z + cz, data.apply(x + cx, y + cy, z + cz), rng, idata, style); - setDataWarped(-x + cx, y + cy, z + cz, data.apply(-x + cx, y + cy, z + cz), rng, idata, style); - setDataWarped(x + cx, -y + cy, z + cz, data.apply(x + cx, -y + cy, z + cz), rng, idata, style); - setDataWarped(x + cx, y + cy, -z + cz, data.apply(x + cx, y + cy, -z + cz), rng, idata, style); - setDataWarped(-x + cx, y + cy, -z + cz, data.apply(-x + cx, y + cy, -z + cz), rng, idata, style); - setDataWarped(-x + cx, -y + cy, z + cz, data.apply(-x + cx, -y + cy, z + cz), rng, idata, style); - setDataWarped(x + cx, -y + cy, -z + cz, data.apply(x + cx, -y + cy, -z + cz), rng, idata, style); - setDataWarped(-x + cx, y + cy, -z + cz, data.apply(-x + cx, y + cy, -z + cz), rng, idata, style); - setDataWarped(-x + cx, -y + cy, -z + cz, data.apply(-x + cx, -y + cy, -z + cz), rng, idata, style); - } - } - } - } - - /** - * Set a cuboid of data in the mantle - * - * @param x1 - * the min x - * @param y1 - * the min y - * @param z1 - * the min z - * @param x2 - * the max x - * @param y2 - * the max y - * @param z2 - * the max z - * @param data - * the data to set - * @param - * the type of data to apply to the mantle - */ - public void setCuboid(int x1, int y1, int z1, int x2, int y2, int z2, T data) { - int j, k; - - for(int i = x1; i <= x2; i++) { - for(j = x1; j <= x2; j++) { - for(k = x1; k <= x2; k++) { - setData(i, j, k, data); - } - } - } - } - - /** - * Set a pyramid of data in the mantle - * - * @param cx - * the center x - * @param cy - * the base y - * @param cz - * the center z - * @param data - * the data to set - * @param size - * the size of the pyramid (width of base & height) - * @param filled - * should it be filled or hollow - * @param - * the type of data to apply to the mantle - */ - @SuppressWarnings("ConstantConditions") - public void setPyramid(int cx, int cy, int cz, T data, int size, boolean filled) { - int height = size; - - for(int y = 0; y <= height; ++y) { - size--; - for(int x = 0; x <= size; ++x) { - for(int z = 0; z <= size; ++z) { - if((filled && z <= size && x <= size) || z == size || x == size) { - setData(x + cx, y + cy, z + cz, data); - setData(-x + cx, y + cy, z + cz, data); - setData(x + cx, y + cy, -z + cz, data); - setData(-x + cx, y + cy, -z + cz, data); - } - } - } - } - } - - /** - * Set a 3d line - * - * @param a - * the first point - * @param b - * the second point - * @param radius - * the radius - * @param filled - * hollow or filled? - * @param data - * the data - * @param - * the type of data to apply to the mantle - */ - public void setLine(IrisPosition a, IrisPosition b, double radius, boolean filled, T data) { - setLine(ImmutableList.of(a, b), radius, filled, data); - } - - public void setLine(List vectors, double radius, boolean filled, T data) { - setLineConsumer(vectors, radius, filled, (_x, _y, _z) -> data); - } - - /** - * Set lines for points - * - * @param vectors - * the points - * @param radius - * the radius - * @param filled - * hollow or filled? - * @param data - * the data to set - * @param - * the type of data to apply to the mantle - */ - public void setLineConsumer(List vectors, double radius, boolean filled, Function3 data) { - Set vset = new KSet<>(); - - for(int i = 0; vectors.size() != 0 && i < vectors.size() - 1; i++) { - IrisPosition pos1 = vectors.get(i); - IrisPosition pos2 = vectors.get(i + 1); - int x1 = pos1.getX(); - int y1 = pos1.getY(); - int z1 = pos1.getZ(); - int x2 = pos2.getX(); - int y2 = pos2.getY(); - int z2 = pos2.getZ(); - int tipx = x1; - int tipy = y1; - int tipz = z1; - int dx = Math.abs(x2 - x1); - int dy = Math.abs(y2 - y1); - int dz = Math.abs(z2 - z1); - - if(dx + dy + dz == 0) { - vset.add(new IrisPosition(tipx, tipy, tipz)); - continue; - } - - int dMax = Math.max(Math.max(dx, dy), dz); - if(dMax == dx) { - for(int domstep = 0; domstep <= dx; domstep++) { - tipx = x1 + domstep * (x2 - x1 > 0 ? 1 : -1); - tipy = (int) Math.round(y1 + domstep * ((double) dy) / ((double) dx) * (y2 - y1 > 0 ? 1 : -1)); - tipz = (int) Math.round(z1 + domstep * ((double) dz) / ((double) dx) * (z2 - z1 > 0 ? 1 : -1)); - - vset.add(new IrisPosition(tipx, tipy, tipz)); - } - } else if(dMax == dy) { - for(int domstep = 0; domstep <= dy; domstep++) { - tipy = y1 + domstep * (y2 - y1 > 0 ? 1 : -1); - tipx = (int) Math.round(x1 + domstep * ((double) dx) / ((double) dy) * (x2 - x1 > 0 ? 1 : -1)); - tipz = (int) Math.round(z1 + domstep * ((double) dz) / ((double) dy) * (z2 - z1 > 0 ? 1 : -1)); - - vset.add(new IrisPosition(tipx, tipy, tipz)); - } - } else /* if (dMax == dz) */ { - for(int domstep = 0; domstep <= dz; domstep++) { - tipz = z1 + domstep * (z2 - z1 > 0 ? 1 : -1); - tipy = (int) Math.round(y1 + domstep * ((double) dy) / ((double) dz) * (y2 - y1 > 0 ? 1 : -1)); - tipx = (int) Math.round(x1 + domstep * ((double) dx) / ((double) dz) * (x2 - x1 > 0 ? 1 : -1)); - - vset.add(new IrisPosition(tipx, tipy, tipz)); - } - } - } - - vset = getBallooned(vset, radius); - - if(!filled) { - vset = getHollowed(vset); - } - - setConsumer(vset, data); - } - - /** - * Set a cylinder in the mantle - * - * @param cx - * the center x - * @param cy - * the base y - * @param cz - * the center z - * @param data - * the data to set - * @param radius - * the radius - * @param height - * the height of the cyl - * @param filled - * filled or not - */ - public void setCylinder(int cx, int cy, int cz, T data, double radius, int height, boolean filled) { - setCylinder(cx, cy, cz, data, radius, radius, height, filled); - } - - /** - * Set a cylinder in the mantle - * - * @param cx - * the center x - * @param cy - * the base y - * @param cz - * the center z - * @param data - * the data to set - * @param radiusX - * the x radius - * @param radiusZ - * the z radius - * @param height - * the height of this cyl - * @param filled - * filled or hollow? - */ - public void setCylinder(int cx, int cy, int cz, T data, double radiusX, double radiusZ, int height, boolean filled) { - int affected = 0; - radiusX += 0.5; - radiusZ += 0.5; - - if(height == 0) { - return; - } else if(height < 0) { - height = -height; - cy = cy - height; - } - - if(cy < 0) { - cy = 0; - } else if(cy + height - 1 > getMantle().getWorldHeight()) { - height = getMantle().getWorldHeight() - cy + 1; - } - - final double invRadiusX = 1 / radiusX; - final double invRadiusZ = 1 / radiusZ; - final int ceilRadiusX = (int) Math.ceil(radiusX); - final int ceilRadiusZ = (int) Math.ceil(radiusZ); - double nextXn = 0; - - forX: - for(int x = 0; x <= ceilRadiusX; ++x) { - final double xn = nextXn; - nextXn = (x + 1) * invRadiusX; - double nextZn = 0; - for(int z = 0; z <= ceilRadiusZ; ++z) { - final double zn = nextZn; - nextZn = (z + 1) * invRadiusZ; - double distanceSq = lengthSq(xn, zn); - - if(distanceSq > 1) { - if(z == 0) { - break forX; - } - - break; - } - - if(!filled) { - if(lengthSq(nextXn, zn) <= 1 && lengthSq(xn, nextZn) <= 1) { - continue; - } - } - - for(int y = 0; y < height; ++y) { - setData(cx + x, cy + y, cz + z, data); - setData(cx + -x, cy + y, cz + z, data); - setData(cx + x, cy + y, cz + -z, data); - setData(cx + -x, cy + y, cz + -z, data); - } - } - } - } - - public void set(IrisPosition pos, T data) { - try { - setData(pos.getX(), pos.getY(), pos.getZ(), data); - } catch(Throwable e) { - Iris.error("No set? " + data.toString() + " for " + pos.toString()); - } - } - - public void set(List positions, T data) { - for(IrisPosition i : positions) { - set(i, data); - } - } - - public void set(Set positions, T data) { - for(IrisPosition i : positions) { - set(i, data); - } - } - - public void setConsumer(Set positions, Function3 data) { - for(IrisPosition i : positions) { - set(i, data.apply(i.getX(), i.getY(), i.getZ())); - } - } - - public boolean isWithin(Vector pos) { - return isWithin(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); - } - - public boolean isWithin(int x, int y, int z) { - int cx = x >> 4; - int cz = z >> 4; - - if(y < 0 || y >= mantle.getWorldHeight()) { - return false; - } - - return cx >= this.x - radius && cx <= this.x + radius - && cz >= this.z - radius && cz <= this.z + radius; - } -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/components/MantleCarvingComponent.java b/src/main/java/com/volmit/iris/engine/mantle/components/MantleCarvingComponent.java deleted file mode 100644 index aec854302..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/components/MantleCarvingComponent.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle.components; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.engine.mantle.IrisMantleComponent; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisCarving; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.math.RNG; - -public class MantleCarvingComponent extends IrisMantleComponent { - public MantleCarvingComponent(EngineMantle engineMantle) { - super(engineMantle, MantleFlag.CARVED); - } - - @Override - public void generateLayer(MantleWriter writer, int x, int z) { - RNG rng = new RNG(Cache.key(x, z) + seed()); - int xxx = 8 + (x << 4); - int zzz = 8 + (z << 4); - IrisRegion region = getComplex().getRegionStream().get(xxx, zzz); - IrisBiome biome = getComplex().getTrueBiomeStream().get(xxx, zzz); - carve(writer, rng, x, z, region, biome); - } - - @ChunkCoordinates - private void carve(MantleWriter writer, RNG rng, int cx, int cz, IrisRegion region, IrisBiome biome) { - carve(getDimension().getCarving(), writer, new RNG((rng.nextLong() * cx) + 490495 + cz), cx, cz); - carve(biome.getCarving(), writer, new RNG((rng.nextLong() * cx) + 490495 + cz), cx, cz); - carve(region.getCarving(), writer, new RNG((rng.nextLong() * cx) + 490495 + cz), cx, cz); - } - - @ChunkCoordinates - private void carve(IrisCarving carving, MantleWriter writer, RNG rng, int cx, int cz) { - carving.doCarving(writer, rng, getEngineMantle().getEngine(), cx << 4, -1, cz << 4); - } -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/components/MantleFluidBodyComponent.java b/src/main/java/com/volmit/iris/engine/mantle/components/MantleFluidBodyComponent.java deleted file mode 100644 index 852be86d6..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/components/MantleFluidBodyComponent.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle.components; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.engine.mantle.IrisMantleComponent; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisFluidBodies; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.math.RNG; - -public class MantleFluidBodyComponent extends IrisMantleComponent { - public MantleFluidBodyComponent(EngineMantle engineMantle) { - super(engineMantle, MantleFlag.FLUID_BODIES); - } - - @Override - public void generateLayer(MantleWriter writer, int x, int z) { - RNG rng = new RNG(Cache.key(x, z) + seed() + 405666); - int xxx = 8 + (x << 4); - int zzz = 8 + (z << 4); - IrisRegion region = getComplex().getRegionStream().get(xxx, zzz); - IrisBiome biome = getComplex().getTrueBiomeStream().get(xxx, zzz); - generate(writer, rng, x, z, region, biome); - } - - @ChunkCoordinates - private void generate(MantleWriter writer, RNG rng, int cx, int cz, IrisRegion region, IrisBiome biome) { - generate(getDimension().getFluidBodies(), writer, new RNG((rng.nextLong() * cx) + 490495 + cz), cx, cz); - generate(biome.getFluidBodies(), writer, new RNG((rng.nextLong() * cx) + 490495 + cz), cx, cz); - generate(region.getFluidBodies(), writer, new RNG((rng.nextLong() * cx) + 490495 + cz), cx, cz); - } - - @ChunkCoordinates - private void generate(IrisFluidBodies bodies, MantleWriter writer, RNG rng, int cx, int cz) { - bodies.generate(writer, rng, getEngineMantle().getEngine(), cx << 4, -1, cz << 4); - } -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/components/MantleJigsawComponent.java b/src/main/java/com/volmit/iris/engine/mantle/components/MantleJigsawComponent.java deleted file mode 100644 index 5a7310aad..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/components/MantleJigsawComponent.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle.components; - -import com.volmit.iris.engine.jigsaw.PlannedStructure; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.engine.mantle.IrisMantleComponent; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisJigsawStructure; -import com.volmit.iris.engine.object.IrisJigsawStructurePlacement; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; - -import java.util.List; - -public class MantleJigsawComponent extends IrisMantleComponent { - private final CNG cng; - - public MantleJigsawComponent(EngineMantle engineMantle) { - super(engineMantle, MantleFlag.JIGSAW); - cng = NoiseStyle.STATIC.create(new RNG(engineMantle.getEngine().getSeedManager().getJigsaw())); - } - - @Override - public void generateLayer(MantleWriter writer, int x, int z) { - RNG rng = new RNG(cng.fit(-Integer.MAX_VALUE, Integer.MAX_VALUE, x, z)); - int xxx = 8 + (x << 4); - int zzz = 8 + (z << 4); - IrisRegion region = getComplex().getRegionStream().get(xxx, zzz); - IrisBiome biome = getComplex().getTrueBiomeStream().get(xxx, zzz); - generateJigsaw(writer, rng, x, z, biome, region); - } - - @ChunkCoordinates - private void generateJigsaw(MantleWriter writer, RNG rng, int x, int z, IrisBiome biome, IrisRegion region) { - boolean placed = false; - - if(getDimension().getStronghold() != null) { - List poss = getDimension().getStrongholds(seed()); - - if(poss != null) { - for(Position2 pos : poss) { - if(x == pos.getX() >> 4 && z == pos.getZ() >> 4) { - IrisJigsawStructure structure = getData().getJigsawStructureLoader().load(getDimension().getStronghold()); - place(writer, pos.toIris(), structure, rng); - placed = true; - } - } - } - } - - if(!placed) { - for(IrisJigsawStructurePlacement i : biome.getJigsawStructures()) { - if(rng.nextInt(i.getRarity()) == 0) { - IrisPosition position = new IrisPosition((x << 4) + rng.nextInt(15), 0, (z << 4) + rng.nextInt(15)); - IrisJigsawStructure structure = getData().getJigsawStructureLoader().load(i.getStructure()); - place(writer, position, structure, rng); - placed = true; - } - } - } - - if(!placed) { - for(IrisJigsawStructurePlacement i : region.getJigsawStructures()) { - if(rng.nextInt(i.getRarity()) == 0) { - IrisPosition position = new IrisPosition((x << 4) + rng.nextInt(15), 0, (z << 4) + rng.nextInt(15)); - IrisJigsawStructure structure = getData().getJigsawStructureLoader().load(i.getStructure()); - place(writer, position, structure, rng); - placed = true; - } - } - } - - if(!placed) { - for(IrisJigsawStructurePlacement i : getDimension().getJigsawStructures()) { - if(rng.nextInt(i.getRarity()) == 0) { - IrisPosition position = new IrisPosition((x << 4) + rng.nextInt(15), 0, (z << 4) + rng.nextInt(15)); - IrisJigsawStructure structure = getData().getJigsawStructureLoader().load(i.getStructure()); - place(writer, position, structure, rng); - } - } - } - } - - @ChunkCoordinates - public IrisJigsawStructure guess(int x, int z) { - RNG rng = new RNG(cng.fit(-Integer.MAX_VALUE, Integer.MAX_VALUE, x, z)); - IrisBiome biome = getEngineMantle().getEngine().getSurfaceBiome((x << 4) + 8, (z << 4) + 8); - IrisRegion region = getEngineMantle().getEngine().getRegion((x << 4) + 8, (z << 4) + 8); - - if(getDimension().getStronghold() != null) { - List poss = getDimension().getStrongholds(seed()); - - if(poss != null) { - for(Position2 pos : poss) { - if(x == pos.getX() >> 4 && z == pos.getZ() >> 4) { - return getData().getJigsawStructureLoader().load(getDimension().getStronghold()); - } - } - } - } - - for(IrisJigsawStructurePlacement i : biome.getJigsawStructures()) { - if(rng.nextInt(i.getRarity()) == 0) { - return getData().getJigsawStructureLoader().load(i.getStructure()); - } - } - - for(IrisJigsawStructurePlacement i : region.getJigsawStructures()) { - if(rng.nextInt(i.getRarity()) == 0) { - return getData().getJigsawStructureLoader().load(i.getStructure()); - } - } - - for(IrisJigsawStructurePlacement i : getDimension().getJigsawStructures()) { - if(rng.nextInt(i.getRarity()) == 0) { - return getData().getJigsawStructureLoader().load(i.getStructure()); - } - } - - return null; - } - - @BlockCoordinates - private void place(MantleWriter writer, IrisPosition position, IrisJigsawStructure structure, RNG rng) { - new PlannedStructure(structure, position, rng).place(writer, getMantle(), writer.getEngine()); - } -} diff --git a/src/main/java/com/volmit/iris/engine/mantle/components/MantleObjectComponent.java b/src/main/java/com/volmit/iris/engine/mantle/components/MantleObjectComponent.java deleted file mode 100644 index 432a6bb7b..000000000 --- a/src/main/java/com/volmit/iris/engine/mantle/components/MantleObjectComponent.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mantle.components; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.engine.mantle.IrisMantleComponent; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisObjectPlacement; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.mantle.MantleFlag; -import com.volmit.iris.util.math.RNG; - -import java.util.Set; - -public class MantleObjectComponent extends IrisMantleComponent { - public MantleObjectComponent(EngineMantle engineMantle) { - super(engineMantle, MantleFlag.OBJECT); - } - - @Override - public void generateLayer(MantleWriter writer, int x, int z) { - RNG rng = new RNG(Cache.key(x, z) + seed()); - int xxx = 8 + (x << 4); - int zzz = 8 + (z << 4); - IrisRegion region = getComplex().getRegionStream().get(xxx, zzz); - IrisBiome biome = getComplex().getTrueBiomeStream().get(xxx, zzz); - placeObjects(writer, rng, x, z, biome, region); - } - - @ChunkCoordinates - private void placeObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome biome, IrisRegion region) { - long s = Cache.key(x, z) + seed(); - RNG rnp = new RNG(s); - for(IrisObjectPlacement i : biome.getSurfaceObjects()) { - if(rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - try { - placeObject(writer, rnp, x << 4, z << 4, i); - rnp.setSeed(s); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Failed to place objects in the following biome: " + biome.getName()); - Iris.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); - Iris.error("Are these objects missing?"); - e.printStackTrace(); - } - } - } - - for(IrisObjectPlacement i : region.getSurfaceObjects()) { - if(rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - try { - placeObject(writer, rnp, x << 4, z << 4, i); - rnp.setSeed(s); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Failed to place objects in the following region: " + region.getName()); - Iris.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); - Iris.error("Are these objects missing?"); - e.printStackTrace(); - } - } - } - } - - @BlockCoordinates - private void placeObject(MantleWriter writer, RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { - for(int i = 0; i < objectPlacement.getDensity(rng, x, z, getData()); i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(getComplex(), rng)); - if(v == null) { - return; - } - int xx = rng.i(x, x + 15); - int zz = rng.i(z, z + 15); - int id = rng.i(0, Integer.MAX_VALUE); - v.place(xx, -1, zz, writer, objectPlacement, rng, - getMantle().shouldReduce(getEngineMantle().getEngine()) ? null : (b) -> writer.setData(b.getX(), b.getY(), b.getZ(), - v.getLoadKey() + "@" + id), null, getData()); - } - } - - @BlockCoordinates - private Set guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { - Set f = new KSet<>(); - for(int i = 0; i < objectPlacement.getDensity(rng, x, z, getData()); i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(getComplex(), rng)); - if(v == null) { - continue; - } - - f.add(v.getLoadKey()); - } - - return f; - } - - public Set guess(int x, int z) { - RNG rng = new RNG(Cache.key(x, z) + seed()); - long s = Cache.key(x, z) + seed(); - RNG rngd = new RNG(s); - IrisBiome biome = getEngineMantle().getEngine().getSurfaceBiome((x << 4) + 8, (z << 4) + 8); - IrisRegion region = getEngineMantle().getEngine().getRegion((x << 4) + 8, (z << 4) + 8); - Set v = new KSet<>(); - for(IrisObjectPlacement i : biome.getSurfaceObjects()) { - if(rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - v.addAll(guessPlacedKeys(rngd, x, z, i)); - rngd.setSeed(s); - } - } - - for(IrisObjectPlacement i : region.getSurfaceObjects()) { - if(rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - v.addAll(guessPlacedKeys(rngd, x, z, i)); - rngd.setSeed(s); - } - } - - return v; - } -} diff --git a/src/main/java/com/volmit/iris/engine/mode/ModeEnclosure.java b/src/main/java/com/volmit/iris/engine/mode/ModeEnclosure.java deleted file mode 100644 index c8005bc82..000000000 --- a/src/main/java/com/volmit/iris/engine/mode/ModeEnclosure.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mode; - -import com.volmit.iris.engine.actuator.IrisBiomeActuator; -import com.volmit.iris.engine.actuator.IrisTerrainNormalActuator; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineMode; -import com.volmit.iris.engine.framework.IrisEngineMode; - -public class ModeEnclosure extends IrisEngineMode implements EngineMode { - public ModeEnclosure(Engine engine) { - super(engine); - var terrain = new IrisTerrainNormalActuator(getEngine()); - var biome = new IrisBiomeActuator(getEngine()); - - registerStage(burst( - (x, z, k, p, m) -> terrain.actuate(x, z, k, m), - (x, z, k, p, m) -> biome.actuate(x, z, p, m) - )); - } -} diff --git a/src/main/java/com/volmit/iris/engine/mode/ModeIslands.java b/src/main/java/com/volmit/iris/engine/mode/ModeIslands.java deleted file mode 100644 index f3833852c..000000000 --- a/src/main/java/com/volmit/iris/engine/mode/ModeIslands.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mode; - -import com.volmit.iris.engine.actuator.IrisBiomeActuator; -import com.volmit.iris.engine.actuator.IrisTerrainNormalActuator; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineMode; -import com.volmit.iris.engine.framework.IrisEngineMode; - -public class ModeIslands extends IrisEngineMode implements EngineMode { - public ModeIslands(Engine engine) { - super(engine); - var terrain = new IrisTerrainNormalActuator(getEngine()); - var biome = new IrisBiomeActuator(getEngine()); - - registerStage(burst( - (x, z, k, p, m) -> terrain.actuate(x, z, k, m), - (x, z, k, p, m) -> biome.actuate(x, z, p, m) - )); - } -} diff --git a/src/main/java/com/volmit/iris/engine/mode/ModeOverworld.java b/src/main/java/com/volmit/iris/engine/mode/ModeOverworld.java deleted file mode 100644 index d00ec09ff..000000000 --- a/src/main/java/com/volmit/iris/engine/mode/ModeOverworld.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mode; - -import com.volmit.iris.engine.actuator.IrisBiomeActuator; -import com.volmit.iris.engine.actuator.IrisDecorantActuator; -import com.volmit.iris.engine.actuator.IrisTerrainNormalActuator; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineMode; -import com.volmit.iris.engine.framework.IrisEngineMode; -import com.volmit.iris.engine.modifier.IrisCarveModifier; -import com.volmit.iris.engine.modifier.IrisDepositModifier; -import com.volmit.iris.engine.modifier.IrisPerfectionModifier; -import com.volmit.iris.engine.modifier.IrisPostModifier; -import org.bukkit.block.data.BlockData; - - -public class ModeOverworld extends IrisEngineMode implements EngineMode { - public ModeOverworld(Engine engine) { - super(engine); - var terrain = new IrisTerrainNormalActuator(getEngine()); - var biome = new IrisBiomeActuator(getEngine()); - var decorant = new IrisDecorantActuator(getEngine()); - var cave = new IrisCarveModifier(getEngine()); - var post = new IrisPostModifier(getEngine()); - var deposit = new IrisDepositModifier(getEngine()); - var perfection = new IrisPerfectionModifier(getEngine()); - - registerStage(burst( - (x, z, k, p, m) -> generateMatter(x >> 4, z >> 4, m), - (x, z, k, p, m) -> terrain.actuate(x, z, k, m), - (x, z, k, p, m) -> biome.actuate(x, z, p, m) - )); - registerStage((x, z, k, p, m) -> cave.modify(x >> 4, z >> 4, k, m)); - registerStage((x, z, k, p, m) -> deposit.modify(x, z, k, m)); - registerStage((x, z, k, p, m) -> decorant.actuate(x, z, k, m)); - registerStage((x, z, k, p, m) -> post.modify(x, z, k, m)); - registerStage((x, z, K, p, m) -> getMantle().insertMatter(x >> 4, z >> 4, BlockData.class, K, m)); - registerStage((x, z, k, p, m) -> perfection.modify(x, z, k, m)); - } -} diff --git a/src/main/java/com/volmit/iris/engine/mode/ModeSuperFlat.java b/src/main/java/com/volmit/iris/engine/mode/ModeSuperFlat.java deleted file mode 100644 index 10c0d8d42..000000000 --- a/src/main/java/com/volmit/iris/engine/mode/ModeSuperFlat.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.mode; - -import com.volmit.iris.engine.actuator.IrisBiomeActuator; -import com.volmit.iris.engine.actuator.IrisTerrainNormalActuator; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineMode; -import com.volmit.iris.engine.framework.IrisEngineMode; - -public class ModeSuperFlat extends IrisEngineMode implements EngineMode { - public ModeSuperFlat(Engine engine) { - super(engine); - var terrain = new IrisTerrainNormalActuator(getEngine()); - var biome = new IrisBiomeActuator(getEngine()); - - registerStage(burst( - (x, z, k, p, m) -> terrain.actuate(x, z, k, m), - (x, z, k, p, m) -> biome.actuate(x, z, p, m) - )); - } -} diff --git a/src/main/java/com/volmit/iris/engine/modifier/IrisCarveModifier.java b/src/main/java/com/volmit/iris/engine/modifier/IrisCarveModifier.java deleted file mode 100644 index 880c49297..000000000 --- a/src/main/java/com/volmit/iris/engine/modifier/IrisCarveModifier.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.modifier; - -import com.volmit.iris.engine.actuator.IrisDecorantActuator; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedModifier; -import com.volmit.iris.engine.object.InferredType; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDecorationPart; -import com.volmit.iris.engine.object.IrisDecorator; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.mantle.MantleChunk; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.matter.slices.MarkerMatter; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.Data; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; - -public class IrisCarveModifier extends EngineAssignedModifier { - private final RNG rng; - private final BlockData AIR = Material.CAVE_AIR.createBlockData(); - private final BlockData WATER = Material.WATER.createBlockData(); - private final BlockData LAVA = Material.LAVA.createBlockData(); - private final IrisDecorantActuator decorant; - - public IrisCarveModifier(Engine engine) { - super(engine, "Carve"); - rng = new RNG(getEngine().getSeedManager().getCarve()); - decorant = new IrisDecorantActuator(engine); - } - - @Override - public void onModify(int x, int z, Hunk output, boolean multicore) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - Mantle mantle = getEngine().getMantle().getMantle(); - MantleChunk mc = getEngine().getMantle().getMantle().getChunk(x, z); - KMap> positions = new KMap<>(); - KMap walls = new KMap<>(); - Consumer4 iterator = (xx, yy, zz, c) -> { - if(c == null) { - return; - } - - if(yy >= getEngine().getWorld().maxHeight() - getEngine().getWorld().minHeight() || yy <= 0) { // Yes, skip bedrock - return; - } - - int rx = xx & 15; - int rz = zz & 15; - - BlockData current = output.get(rx, yy, rz); - - if(B.isFluid(current)) { - return; - } - - positions.computeIfAbsent(Cache.key(rx, rz), (k) -> new KList<>()).qadd(yy); - - //todo: Fix chunk decoration not working on chunk's border - - if(rz < 15 && mantle.get(xx, yy, zz + 1, MatterCavern.class) == null) { - walls.put(new IrisPosition(rx, yy, rz + 1), c); - } - - if(rx < 15 && mantle.get(xx + 1, yy, zz, MatterCavern.class) == null) { - walls.put(new IrisPosition(rx + 1, yy, rz), c); - } - - if(rz > 0 && mantle.get(xx, yy, zz - 1, MatterCavern.class) == null) { - walls.put(new IrisPosition(rx, yy, rz - 1), c); - } - - if(rx > 0 && mantle.get(xx - 1, yy, zz, MatterCavern.class) == null) { - walls.put(new IrisPosition(rx - 1, yy, rz), c); - } - - if(current.getMaterial().isAir()) { - return; - } - - if(c.isWater()) { - output.set(rx, yy, rz, WATER); - } else if(c.isLava()) { - output.set(rx, yy, rz, LAVA); - } else { - if(getEngine().getDimension().getCaveLavaHeight() > yy) { - output.set(rx, yy, rz, LAVA); - } else { - output.set(rx, yy, rz, AIR); - } - } - }; - - mc.iterate(MatterCavern.class, iterator); - - walls.forEach((i, v) -> { - IrisBiome biome = v.getCustomBiome().isEmpty() - ? getEngine().getCaveBiome(i.getX() + (x << 4), i.getZ() + (z << 4)) - : getEngine().getData().getBiomeLoader().load(v.getCustomBiome()); - - if(biome != null) { - biome.setInferredType(InferredType.CAVE); - BlockData d = biome.getWall().get(rng, i.getX() + (x << 4), i.getY(), i.getZ() + (z << 4), getData()); - - if(d != null && B.isSolid(output.get(i.getX(), i.getY(), i.getZ())) && i.getY() <= getComplex().getHeightStream().get(i.getX() + (x << 4), i.getZ() + (z << 4))) { - output.set(i.getX(), i.getY(), i.getZ(), d); - } - } - }); - - positions.forEach((k, v) -> { - if(v.isEmpty()) { - return; - } - - int rx = Cache.keyX(k); - int rz = Cache.keyZ(k); - v.sort(Integer::compare); - CaveZone zone = new CaveZone(); - zone.setFloor(v.get(0)); - int buf = v.get(0) - 1; - - for(Integer i : v) { - if(i < 0 || i > getEngine().getHeight()) { - continue; - } - - if(i == buf + 1) { - buf = i; - zone.ceiling = buf; - } else if(zone.isValid()) { - processZone(output, mc, mantle, zone, rx, rz, rx + (x << 4), rz + (z << 4)); - zone = new CaveZone(); - zone.setFloor(i); - buf = i; - } - } - - if(zone.isValid()) { - processZone(output, mc, mantle, zone, rx, rz, rx + (x << 4), rz + (z << 4)); - } - }); - - getEngine().getMetrics().getDeposit().put(p.getMilliseconds()); - } - - private void processZone(Hunk output, MantleChunk mc, Mantle mantle, CaveZone zone, int rx, int rz, int xx, int zz) { - boolean decFloor = B.isSolid(output.getClosest(rx, zone.floor - 1, rz)); - boolean decCeiling = B.isSolid(output.getClosest(rx, zone.ceiling + 1, rz)); - int center = (zone.floor + zone.ceiling) / 2; - int thickness = zone.airThickness(); - String customBiome = ""; - - if(B.isDecorant(output.getClosest(rx, zone.ceiling + 1, rz))) { - output.set(rx, zone.ceiling + 1, rz, AIR); - } - - if(B.isDecorant(output.get(rx, zone.ceiling, rz))) { - output.set(rx, zone.ceiling, rz, AIR); - } - - if(M.r(1D / 16D)) { - mantle.set(xx, zone.ceiling, zz, MarkerMatter.CAVE_CEILING); - } - - if(M.r(1D / 16D)) { - mantle.set(xx, zone.floor, zz, MarkerMatter.CAVE_FLOOR); - } - - for(int i = zone.floor; i <= zone.ceiling; i++) { - MatterCavern cavernData = (MatterCavern) mc.getOrCreate(i >> 4).slice(MatterCavern.class) - .get(rx, i & 15, rz); - - if(cavernData != null && !cavernData.getCustomBiome().isEmpty()) { - customBiome = cavernData.getCustomBiome(); - break; - } - } - - IrisBiome biome = customBiome.isEmpty() - ? getEngine().getCaveBiome(xx, zz) - : getEngine().getData().getBiomeLoader().load(customBiome); - - if(biome == null) { - return; - } - - biome.setInferredType(InferredType.CAVE); - - for(IrisDecorator i : biome.getDecorators()) { - if(i.getPartOf().equals(IrisDecorationPart.NONE) && B.isSolid(output.get(rx, zone.getFloor() - 1, rz))) { - decorant.getSurfaceDecorator().decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, biome, zone.getFloor() - 1, zone.airThickness()); - } else if(i.getPartOf().equals(IrisDecorationPart.CEILING) && B.isSolid(output.get(rx, zone.getCeiling() + 1, rz))) { - decorant.getCeilingDecorator().decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, biome, zone.getCeiling(), zone.airThickness()); - } - } - - KList blocks = biome.generateLayers(getDimension(), xx, zz, rng, 3, zone.floor, getData(), getComplex()); - - for(int i = 0; i < zone.floor - 1; i++) { - if(!blocks.hasIndex(i)) { - break; - } - - if(!B.isSolid(output.get(rx, zone.floor - i - 1, rz))) { - continue; - } - - if(B.isOre(output.get(rx, zone.floor - i - 1, rz))) { - continue; - } - - output.set(rx, zone.floor - i - 1, rz, blocks.get(i)); - } - - blocks = biome.generateCeilingLayers(getDimension(), xx, zz, rng, 3, zone.ceiling, getData(), getComplex()); - - if(zone.ceiling + 1 < mantle.getWorldHeight()) { - for(int i = 0; i < zone.ceiling + 1; i++) { - if(!blocks.hasIndex(i)) { - break; - } - - BlockData b = blocks.get(i); - BlockData up = output.get(rx, zone.ceiling + i + 1, rz); - - if(!B.isSolid(up)) { - continue; - } - - if(B.isOre(up)) { - output.set(rx, zone.ceiling + i + 1, rz, B.toDeepSlateOre(up, b)); - continue; - } - - output.set(rx, zone.ceiling + i + 1, rz, b); - } - } - } - - @Data - public static class CaveZone { - private int ceiling = -1; - private int floor = -1; - - public int airThickness() { - return (ceiling - floor) - 1; - } - - public boolean isValid() { - return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= IrisContext.get().getEngine().getHeight() && airThickness() > 0; - } - - public String toString() { - return floor + "-" + ceiling; - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/modifier/IrisDepositModifier.java b/src/main/java/com/volmit/iris/engine/modifier/IrisDepositModifier.java deleted file mode 100644 index 6512b9c18..000000000 --- a/src/main/java/com/volmit/iris/engine/modifier/IrisDepositModifier.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.modifier; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedModifier; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDepositGenerator; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.data.HeightMap; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import org.bukkit.block.data.BlockData; -import org.bukkit.util.BlockVector; - -public class IrisDepositModifier extends EngineAssignedModifier { - private final RNG rng; - - public IrisDepositModifier(Engine engine) { - super(engine, "Deposit"); - rng = new RNG(getEngine().getSeedManager().getDeposit()); - } - - @Override - public void onModify(int x, int z, Hunk output, boolean multicore) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - generateDeposits(rng, output, Math.floorDiv(x, 16), Math.floorDiv(z, 16), multicore); - getEngine().getMetrics().getDeposit().put(p.getMilliseconds()); - } - - public void generateDeposits(RNG rx, Hunk terrain, int x, int z, boolean multicore) { - RNG ro = rx.nextParallelRNG(x * x).nextParallelRNG(z * z); - IrisRegion region = getComplex().getRegionStream().get((x * 16) + 7, (z * 16) + 7); - IrisBiome biome = getComplex().getTrueBiomeStream().get((x * 16) + 7, (z * 16) + 7); - BurstExecutor burst = burst().burst(multicore); - - for(IrisDepositGenerator k : getDimension().getDeposits()) { - burst.queue(() -> generate(k, terrain, ro, x, z, false)); - } - - for(IrisDepositGenerator k : region.getDeposits()) { - for(int l = 0; l < ro.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) { - burst.queue(() -> generate(k, terrain, ro, x, z, false)); - } - } - - for(IrisDepositGenerator k : biome.getDeposits()) { - for(int l = 0; l < ro.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) { - burst.queue(() -> generate(k, terrain, ro, x, z, false)); - } - } - burst.complete(); - } - - public void generate(IrisDepositGenerator k, Hunk data, RNG rng, int cx, int cz, boolean safe) { - generate(k, data, rng, cx, cz, safe, null); - } - - public void generate(IrisDepositGenerator k, Hunk data, RNG rng, int cx, int cz, boolean safe, HeightMap he) { - for(int l = 0; l < rng.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) { - IrisObject clump = k.getClump(rng, getData()); - - int af = (int) Math.floor(clump.getW() / 2D); - int bf = (int) Math.floor(16D - (clump.getW() / 2D)); - - if(af > bf || af < 0 || bf > 15 || af > 15 || bf < 0) { - af = 6; - bf = 9; - } - - af = Math.max(af - 1, 0); - int x = rng.i(af, bf); - int z = rng.i(af, bf); - int height = (he != null ? he.getHeight((cx << 4) + x, (cz << 4) + z) : (int) (Math.round( - getComplex().getHeightStream().get((cx << 4) + x, (cz << 4) + z) - ))) - 7; - - if(height <= 0) { - return; - } - - int i = Math.max(0, k.getMinHeight()); - // TODO: WARNING HEIGHT - int a = Math.min(height, Math.min(getEngine().getHeight(), k.getMaxHeight())); - - if(i >= a) { - return; - } - - int h = rng.i(i, a); - - if(h > k.getMaxHeight() || h < k.getMinHeight() || h > height - 2) { - return; - } - - for(BlockVector j : clump.getBlocks().keySet()) { - int nx = j.getBlockX() + x; - int ny = j.getBlockY() + h; - int nz = j.getBlockZ() + z; - - if(ny > height || nx > 15 || nx < 0 || ny > getEngine().getHeight() || ny < 0 || nz < 0 || nz > 15) { - continue; - } - - if(!getEngine().getMantle().isCarved((cx << 4) + nx, ny, (cz << 4) + nz)) { - data.set(nx, ny, nz, B.toDeepSlateOre(data.get(nx, ny, nz), clump.getBlocks().get(j))); - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/modifier/IrisPerfectionModifier.java b/src/main/java/com/volmit/iris/engine/modifier/IrisPerfectionModifier.java deleted file mode 100644 index 700512b94..000000000 --- a/src/main/java/com/volmit/iris/engine/modifier/IrisPerfectionModifier.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.modifier; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedModifier; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.BlockData; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -public class IrisPerfectionModifier extends EngineAssignedModifier { - private static final BlockData AIR = B.get("AIR"); - private static final BlockData WATER = B.get("WATER"); - - public IrisPerfectionModifier(Engine engine) { - super(engine, "Perfection"); - } - - @Override - public void onModify(int x, int z, Hunk output, boolean multicore) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - AtomicBoolean changed = new AtomicBoolean(true); - int passes = 0; - AtomicInteger changes = new AtomicInteger(); - List surfaces = new ArrayList<>(); - List ceilings = new ArrayList<>(); - BurstExecutor burst = burst().burst(multicore); - while(changed.get()) { - passes++; - changed.set(false); - for(int i = 0; i < 16; i++) { - int finalI = i; - burst.queue(() -> { - for(int j = 0; j < 16; j++) { - surfaces.clear(); - ceilings.clear(); - int top = getHeight(output, finalI, j); - boolean inside = true; - surfaces.add(top); - - for(int k = top; k >= 0; k--) { - BlockData b = output.get(finalI, k, j); - boolean now = b != null && !(B.isAir(b) || B.isFluid(b)); - - if(now != inside) { - inside = now; - - if(inside) { - surfaces.add(k); - } else { - ceilings.add(k + 1); - } - } - } - - for(int k : surfaces) { - BlockData tip = output.get(finalI, k, j); - - if(tip == null) { - continue; - } - - boolean remove = false; - boolean remove2 = false; - - if(B.isDecorant(tip)) { - BlockData bel = output.get(finalI, k - 1, j); - - if(bel == null) { - remove = true; - } else if(!B.canPlaceOnto(tip.getMaterial(), bel.getMaterial())) { - remove = true; - } else if(bel instanceof Bisected) { - BlockData bb = output.get(finalI, k - 2, j); - if(bb == null || !B.canPlaceOnto(bel.getMaterial(), bb.getMaterial())) { - remove = true; - remove2 = true; - } - } - - if(remove) { - changed.set(true); - changes.getAndIncrement(); - output.set(finalI, k, j, AIR); - - if(remove2) { - changes.getAndIncrement(); - output.set(finalI, k - 1, j, AIR); - } - } - } - } - } - }); - } - } - - getEngine().getMetrics().getPerfection().put(p.getMilliseconds()); - } - - private int getHeight(Hunk output, int x, int z) { - for(int i = output.getHeight() - 1; i >= 0; i--) { - BlockData b = output.get(x, i, z); - - if(b != null && !B.isAir(b) && !B.isFluid(b)) { - return i; - } - } - - return 0; - } -} diff --git a/src/main/java/com/volmit/iris/engine/modifier/IrisPostModifier.java b/src/main/java/com/volmit/iris/engine/modifier/IrisPostModifier.java deleted file mode 100644 index 0fdc2e232..000000000 --- a/src/main/java/com/volmit/iris/engine/modifier/IrisPostModifier.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.modifier; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineAssignedModifier; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Levelled; -import org.bukkit.block.data.Waterlogged; -import org.bukkit.block.data.type.Slab; - -import java.util.concurrent.atomic.AtomicInteger; - -public class IrisPostModifier extends EngineAssignedModifier { - private static final BlockData AIR = B.get("AIR"); - private static final BlockData WATER = B.get("WATER"); - private final RNG rng; - - public IrisPostModifier(Engine engine) { - super(engine, "Post"); - rng = new RNG(getEngine().getSeedManager().getPost()); - } - - @Override - public void onModify(int x, int z, Hunk output, boolean multicore) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - AtomicInteger i = new AtomicInteger(); - AtomicInteger j = new AtomicInteger(); - Hunk sync = output.synchronize(); - for(i.set(0); i.get() < output.getWidth(); i.getAndIncrement()) { - for(j.set(0); j.get() < output.getDepth(); j.getAndIncrement()) { - int ii = i.get(); - int jj = j.get(); - post(ii, jj, sync, ii + x, jj + z); - } - } - - getEngine().getMetrics().getPost().put(p.getMilliseconds()); - } - - private void post(int currentPostX, int currentPostZ, Hunk currentData, int x, int z) { - int h = getEngine().getMantle().trueHeight(x, z); - int ha = getEngine().getMantle().trueHeight(x + 1, z); - int hb = getEngine().getMantle().trueHeight(x, z + 1); - int hc = getEngine().getMantle().trueHeight(x - 1, z); - int hd = getEngine().getMantle().trueHeight(x, z - 1); - - // Floating Nibs - int g = 0; - - if(h < 1) { - return; - } - - g += ha < h - 1 ? 1 : 0; - g += hb < h - 1 ? 1 : 0; - g += hc < h - 1 ? 1 : 0; - g += hd < h - 1 ? 1 : 0; - - if(g == 4 && isAir(x, h - 1, z, currentPostX, currentPostZ, currentData)) { - setPostBlock(x, h, z, AIR, currentPostX, currentPostZ, currentData); - - for(int i = h - 1; i > 0; i--) { - if(!isAir(x, i, z, currentPostX, currentPostZ, currentData)) { - h = i; - break; - } - } - } - - // Nibs - g = 0; - g += ha == h - 1 ? 1 : 0; - g += hb == h - 1 ? 1 : 0; - g += hc == h - 1 ? 1 : 0; - g += hd == h - 1 ? 1 : 0; - - if(g >= 4) { - BlockData bc = getPostBlock(x, h, z, currentPostX, currentPostZ, currentData); - BlockData b = getPostBlock(x, h + 1, z, currentPostX, currentPostZ, currentData); - Material m = bc.getMaterial(); - - if((b.getMaterial().isOccluding() && b.getMaterial().isSolid())) { - if(m.isSolid()) { - setPostBlock(x, h, z, b, currentPostX, currentPostZ, currentData); - h--; - } - } - } else { - // Potholes - g = 0; - g += ha == h + 1 ? 1 : 0; - g += hb == h + 1 ? 1 : 0; - g += hc == h + 1 ? 1 : 0; - g += hd == h + 1 ? 1 : 0; - - if(g >= 4) { - BlockData ba = getPostBlock(x, ha, z, currentPostX, currentPostZ, currentData); - BlockData bb = getPostBlock(x, hb, z, currentPostX, currentPostZ, currentData); - BlockData bc = getPostBlock(x, hc, z, currentPostX, currentPostZ, currentData); - BlockData bd = getPostBlock(x, hd, z, currentPostX, currentPostZ, currentData); - g = 0; - g = B.isSolid(ba) ? g + 1 : g; - g = B.isSolid(bb) ? g + 1 : g; - g = B.isSolid(bc) ? g + 1 : g; - g = B.isSolid(bd) ? g + 1 : g; - - if(g >= 3) { - setPostBlock(x, h + 1, z, getPostBlock(x, h, z, currentPostX, currentPostZ, currentData), currentPostX, currentPostZ, currentData); - h++; - } - } - } - - // Wall Patcher - IrisBiome biome = getComplex().getTrueBiomeStream().get(x, z); - - if(getDimension().isPostProcessingWalls()) { - if(!biome.getWall().getPalette().isEmpty()) { - if(ha < h - 2 || hb < h - 2 || hc < h - 2 || hd < h - 2) { - boolean brokeGround = false; - int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd)))); - - for(int i = h; i > h - max; i--) { - BlockData d = biome.getWall().get(rng, x + i, i + h, z + i, getData()); - - if(d != null) { - if(isAirOrWater(x, i, z, currentPostX, currentPostZ, currentData)) { - if(brokeGround) { - break; - } - - continue; - } - - setPostBlock(x, i, z, d, currentPostX, currentPostZ, currentData); - brokeGround = true; - } - } - } - } - } - - // Slab - if(getDimension().isPostProcessingSlabs()) { - //@builder - if((ha == h + 1 && isSolidNonSlab(x + 1, ha, z, currentPostX, currentPostZ, currentData)) - || (hb == h + 1 && isSolidNonSlab(x, hb, z + 1, currentPostX, currentPostZ, currentData)) - || (hc == h + 1 && isSolidNonSlab(x - 1, hc, z, currentPostX, currentPostZ, currentData)) - || (hd == h + 1 && isSolidNonSlab(x, hd, z - 1, currentPostX, currentPostZ, currentData))) - //@done - { - BlockData d = biome.getSlab().get(rng, x, h, z, getData()); - - if(d != null) { - boolean cancel = B.isAir(d); - - if(d.getMaterial().equals(Material.SNOW) && h + 1 <= getDimension().getFluidHeight()) { - cancel = true; - } - - if(isSnowLayer(x, h, z, currentPostX, currentPostZ, currentData)) { - cancel = true; - } - - if(!cancel && isAirOrWater(x, h + 1, z, currentPostX, currentPostZ, currentData)) { - setPostBlock(x, h + 1, z, d, currentPostX, currentPostZ, currentData); - h++; - } - } - } - } - - // Waterlogging - BlockData b = getPostBlock(x, h, z, currentPostX, currentPostZ, currentData); - - if(b instanceof Waterlogged) { - Waterlogged ww = (Waterlogged) b.clone(); - boolean w = false; - - if(h <= getDimension().getFluidHeight() + 1) { - if(isWaterOrWaterlogged(x, h + 1, z, currentPostX, currentPostZ, currentData)) { - w = true; - } else if((isWaterOrWaterlogged(x + 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, currentPostX, currentPostZ, currentData))) { - w = true; - } - } - - if(w != ww.isWaterlogged()) { - ww.setWaterlogged(w); - setPostBlock(x, h, z, ww, currentPostX, currentPostZ, currentData); - } - } else if(b.getMaterial().equals(Material.AIR) && h <= getDimension().getFluidHeight()) { - if((isWaterOrWaterlogged(x + 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, currentPostX, currentPostZ, currentData))) { - setPostBlock(x, h, z, WATER, currentPostX, currentPostZ, currentData); - } - } - - // Foliage - b = getPostBlock(x, h + 1, z, currentPostX, currentPostZ, currentData); - - if(B.isFoliage(b) || b.getMaterial().equals(Material.DEAD_BUSH)) { - Material onto = getPostBlock(x, h, z, currentPostX, currentPostZ, currentData).getMaterial(); - - if(!B.canPlaceOnto(b.getMaterial(), onto)) { - setPostBlock(x, h + 1, z, AIR, currentPostX, currentPostZ, currentData); - } - } - } - - public boolean isAir(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d.getMaterial().equals(Material.AIR) || d.getMaterial().equals(Material.CAVE_AIR); - } - - public boolean hasGravity(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d.getMaterial().equals(Material.SAND) || d.getMaterial().equals(Material.RED_SAND) || d.getMaterial().equals(Material.BLACK_CONCRETE_POWDER) || d.getMaterial().equals(Material.BLUE_CONCRETE_POWDER) || d.getMaterial().equals(Material.BROWN_CONCRETE_POWDER) || d.getMaterial().equals(Material.CYAN_CONCRETE_POWDER) || d.getMaterial().equals(Material.GRAY_CONCRETE_POWDER) || d.getMaterial().equals(Material.GREEN_CONCRETE_POWDER) || d.getMaterial().equals(Material.LIGHT_BLUE_CONCRETE_POWDER) || d.getMaterial().equals(Material.LIGHT_GRAY_CONCRETE_POWDER) || d.getMaterial().equals(Material.LIME_CONCRETE_POWDER) || d.getMaterial().equals(Material.MAGENTA_CONCRETE_POWDER) || d.getMaterial().equals(Material.ORANGE_CONCRETE_POWDER) || d.getMaterial().equals(Material.PINK_CONCRETE_POWDER) || d.getMaterial().equals(Material.PURPLE_CONCRETE_POWDER) || d.getMaterial().equals(Material.RED_CONCRETE_POWDER) || d.getMaterial().equals(Material.WHITE_CONCRETE_POWDER) || d.getMaterial().equals(Material.YELLOW_CONCRETE_POWDER); - } - - public boolean isSolid(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d.getMaterial().isSolid(); - } - - public boolean isSolidNonSlab(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d.getMaterial().isSolid() && !(d instanceof Slab); - } - - public boolean isAirOrWater(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d.getMaterial().equals(Material.WATER) || d.getMaterial().equals(Material.AIR) || d.getMaterial().equals(Material.CAVE_AIR); - } - - public boolean isSlab(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d instanceof Slab; - } - - public boolean isSnowLayer(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d.getMaterial().equals(Material.SNOW); - } - - public boolean isWater(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d.getMaterial().equals(Material.WATER); - } - - public boolean isWaterOrWaterlogged(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d.getMaterial().equals(Material.WATER) || (d instanceof Waterlogged && ((Waterlogged) d).isWaterlogged()); - } - - public boolean isLiquid(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { - BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); - return d instanceof Levelled; - } - - public void setPostBlock(int x, int y, int z, BlockData d, int currentPostX, int currentPostZ, Hunk currentData) { - if(y < currentData.getHeight()) { - currentData.set(x & 15, y, z & 15, d); - } - } - - public BlockData getPostBlock(int x, int y, int z, int cpx, int cpz, Hunk h) { - BlockData b = h.getClosest(x & 15, y, z & 15); - - return b == null ? AIR : b; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/CarveResult.java b/src/main/java/com/volmit/iris/engine/object/CarveResult.java deleted file mode 100644 index 06dff5b90..000000000 --- a/src/main/java/com/volmit/iris/engine/object/CarveResult.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import lombok.Value; - -@SuppressWarnings("ClassCanBeRecord") -@Value -public class CarveResult { - @SuppressWarnings("RedundantModifiersValueLombok") - private final int surface; - @SuppressWarnings("RedundantModifiersValueLombok") - private final int ceiling; - - public int getHeight() { - return ceiling - surface; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/CarvingMode.java b/src/main/java/com/volmit/iris/engine/object/CarvingMode.java deleted file mode 100644 index 77f48277c..000000000 --- a/src/main/java/com/volmit/iris/engine/object/CarvingMode.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Defines if an object is allowed to place in carvings, surfaces or both.") -public enum CarvingMode { - @Desc("Only place this object on surfaces (NOT under carvings)") - SURFACE_ONLY, - - @Desc("Only place this object under carvings (NOT on the surface)") - CARVING_ONLY, - - @Desc("This object can place anywhere") - ANYWHERE; - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean supportsCarving() { - return this.equals(ANYWHERE) || this.equals(CARVING_ONLY); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean supportsSurface() { - return this.equals(ANYWHERE) || this.equals(SURFACE_ONLY); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/CaveResult.java b/src/main/java/com/volmit/iris/engine/object/CaveResult.java deleted file mode 100644 index 19a099d6b..000000000 --- a/src/main/java/com/volmit/iris/engine/object/CaveResult.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import lombok.Data; - -@Data -public class CaveResult { - private int floor; - private int ceiling; - - public CaveResult(int floor, int ceiling) { - this.floor = floor; - this.ceiling = ceiling; - } - - public boolean isWithin(int v) { - return v > floor || v < ceiling; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IObjectPlacer.java b/src/main/java/com/volmit/iris/engine/object/IObjectPlacer.java deleted file mode 100644 index d14f1e2f6..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IObjectPlacer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.Engine; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; - -public interface IObjectPlacer { - int getHighest(int x, int z, IrisData data); - - int getHighest(int x, int z, IrisData data, boolean ignoreFluid); - - void set(int x, int y, int z, BlockData d); - - BlockData get(int x, int y, int z); - - boolean isPreventingDecay(); - - boolean isCarved(int x, int y, int z); - - boolean isSolid(int x, int y, int z); - - boolean isUnderwater(int x, int z); - - int getFluidHeight(); - - boolean isDebugSmartBore(); - - void setTile(int xx, int yy, int zz, TileData tile); - - Engine getEngine(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/IPostBlockAccess.java b/src/main/java/com/volmit/iris/engine/object/IPostBlockAccess.java deleted file mode 100644 index db1c74271..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IPostBlockAccess.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.util.collection.KList; -import org.bukkit.block.data.BlockData; -import org.bukkit.generator.ChunkGenerator.ChunkData; - -public interface IPostBlockAccess { - BlockData getPostBlock(int x, int y, int z, int currentPostX, int currentPostZ, ChunkData currentData); - - void setPostBlock(int x, int y, int z, BlockData d, int currentPostX, int currentPostZ, ChunkData currentData); - - int highestTerrainOrFluidBlock(int x, int z); - - int highestTerrainBlock(int x, int z); - - void updateHeight(int x, int z, int h); - - KList caveFloors(int x, int z); -} diff --git a/src/main/java/com/volmit/iris/engine/object/IRare.java b/src/main/java/com/volmit/iris/engine/object/IRare.java deleted file mode 100644 index c11a9c3f1..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IRare.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.stream.interpolation.Interpolated; - -import java.util.List; - -public interface IRare { - static ProceduralStream stream(ProceduralStream noise, List possibilities) { - return ProceduralStream.of((x, z) -> pick(possibilities, noise.get(x, z)), - (x, y, z) -> pick(possibilities, noise.get(x, y, z)), - new Interpolated() { - @Override - public double toDouble(T t) { - return 0; - } - - @Override - public T fromDouble(double d) { - return null; - } - }); - } - - - static T pickSlowly(List possibilities, double noiseValue) { - if(possibilities.isEmpty()) { - return null; - } - - if(possibilities.size() == 1) { - return possibilities.get(0); - } - - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for(T i : possibilities) { - totalRarity += IRare.get(i); - } - - for(T i : possibilities) { - rarityTypes.addMultiple(i, totalRarity / IRare.get(i)); - } - - return rarityTypes.get((int) (noiseValue * rarityTypes.last())); - } - - static T pick(List possibilities, double noiseValue) { - if(possibilities.isEmpty()) { - return null; - } - - if(possibilities.size() == 1) { - return possibilities.get(0); - } - int totalWeight = 0; // This is he baseline - int buffer = 0; - for(T i : possibilities) { // Im adding all of the rarity together - totalWeight += i.getRarity(); - } - double threshold = totalWeight * (possibilities.size() - 1) * noiseValue; - for(T i : possibilities) { - buffer += totalWeight - i.getRarity(); - - if(buffer >= threshold) { - return i; - } - } - return possibilities.get(possibilities.size() - 1); - } - - - static T pickOld(List possibilities, double noiseValue) { - if(possibilities.isEmpty()) { - return null; - } - - if(possibilities.size() == 1) { - return possibilities.get(0); - } - - double completeWeight = 0.0; - double highestWeight = 0.0; - - for(T item : possibilities) { - double weight = Math.max(item.getRarity(), 1); - highestWeight = Math.max(highestWeight, weight); - completeWeight += weight; - } - - double r = noiseValue * completeWeight; - double countWeight = 0.0; - - for(T item : possibilities) { - double weight = Math.max(highestWeight - Math.max(item.getRarity(), 1), 1); - countWeight += weight; - if(countWeight >= r) { - return item; - } - } - - return possibilities.get(possibilities.size() - 1); - } - - static int get(Object v) { - return v instanceof IRare ? Math.max(1, ((IRare) v).getRarity()) : 1; - } - - int getRarity(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/InferredType.java b/src/main/java/com/volmit/iris/engine/object/InferredType.java deleted file mode 100644 index e4a8a6139..000000000 --- a/src/main/java/com/volmit/iris/engine/object/InferredType.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Represents a biome type") -public enum InferredType { - @Desc("Represents any shore biome type") - SHORE, - - @Desc("Represents any land biome type") - LAND, - - @Desc("Represents any sea biome type") - SEA, - - @Desc("Represents any cave biome type") - CAVE, - - @Desc("Defers the type to whatever another biome type that already exists is.") - DEFER -} diff --git a/src/main/java/com/volmit/iris/engine/object/InventorySlotType.java b/src/main/java/com/volmit/iris/engine/object/InventorySlotType.java deleted file mode 100644 index 2110fdba3..000000000 --- a/src/main/java/com/volmit/iris/engine/object/InventorySlotType.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("An inventory slot type is used to represent a type of slot for items to fit into in any given inventory.") -public enum InventorySlotType { - @Desc("Typically the one you want to go with. Storage represnents most slots in inventories.") - STORAGE, - - @Desc("Used for the fuel slot in Furnaces, Blast furnaces, smokers etc.") - FUEL, - - @Desc("Used for the cook slot in furnaces") - FURNACE, - @Desc("Used for the cook slot in blast furnaces") - BLAST_FURNACE, - - @Desc("Used for the cook slot in smokers") - SMOKER, -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisAttributeModifier.java b/src/main/java/com/volmit/iris/engine/object/IrisAttributeModifier.java deleted file mode 100644 index b2705e8fa..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisAttributeModifier.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.attribute.Attributable; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.attribute.AttributeModifier.Operation; -import org.bukkit.inventory.meta.ItemMeta; - -@Snippet("attribute-modifier") -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Represents an attribute modifier for an item or an entity. This allows you to create modifications to basic game attributes such as MAX_HEALTH or ARMOR_VALUE.") -@Data -public class IrisAttributeModifier { - @Required - @Desc("The Attribute type. This type is pulled from the game attributes. Zombie & Horse attributes will not work on non-zombie/horse entities.\nUsing an attribute on an item will have affects when held, or worn. There is no way to specify further granularity as the game picks this depending on the item type.") - private Attribute attribute = null; - - @MinNumber(2) - @Required - @Desc("The Attribute Name is used internally only for the game. This value should be unique to all other attributes applied to this item/entity. It is not shown in game.") - private String name = ""; - - @Desc("The application operation (add number is default). Add Number adds to the default value. \nAdd scalar_1 will multiply by 1 for example if the health is 20 and you multiply_scalar_1 by 0.5, the health will result in 30, not 10. Use negative values to achieve that.") - private Operation operation = Operation.ADD_NUMBER; - - @Desc("Minimum amount for this modifier. Iris randomly chooses an amount, this is the minimum it can choose randomly for this attribute.") - private double minAmount = 1; - - @Desc("Maximum amount for this modifier Iris randomly chooses an amount, this is the maximum it can choose randomly for this attribute.") - private double maxAmount = 1; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance that this attribute is applied (0 to 1). If the chance is 0.5 (50%), then Iris will only apply this attribute 50% of the time.") - private double chance = 1; - - public void apply(RNG rng, ItemMeta meta) { - if(rng.nextDouble() < getChance()) { - meta.addAttributeModifier(getAttribute(), new AttributeModifier(getName(), getAmount(rng), getOperation())); - } - } - - public void apply(RNG rng, Attributable meta) { - if(rng.nextDouble() < getChance()) { - meta.getAttribute(getAttribute()).addModifier(new AttributeModifier(getName(), getAmount(rng), getOperation())); - } - } - - public double getAmount(RNG rng) { - return rng.d(getMinAmount(), getMaxAmount()); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisAxisRotationClamp.java b/src/main/java/com/volmit/iris/engine/object/IrisAxisRotationClamp.java deleted file mode 100644 index b65a95f38..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisAxisRotationClamp.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.M; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("axis-rotation") -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Represents a rotation axis with intervals and maxes. The x and z axis values are defaulted to disabled. The Y axis defaults to on, rotating by 90 degree increments.") -@Data -public class IrisAxisRotationClamp { - @Desc("Should this axis be rotated at all?") - private boolean enabled = false; - - private transient boolean forceLock = false; - - @Required - @DependsOn({"max"}) - @MinNumber(-360) - @MaxNumber(360) - @Desc("The minimum angle (from) or set this and max to zero for any angle degrees. Set both to the same non-zero value to force it to that angle only") - private double min = 0; - - @Required - @DependsOn({"min"}) - @MinNumber(-360) - @MaxNumber(360) - @Desc("The maximum angle (to) or set this and min to zero for any angle degrees. Set both to the same non-zero value to force it to that angle only") - private double max = 0; - - @Required - @DependsOn({"min", "max"}) - @MinNumber(0) - @MaxNumber(360) - @Desc("Iris spins the axis but not freely. For example an interval of 90 would mean 4 possible angles (right angles) degrees. \nSetting this to 0 means totally free rotation.\n\nNote that a lot of structures can have issues with non 90 degree intervals because the minecraft block resolution is so low.") - private double interval = 0; - - public void minMax(double fd) { - min = fd; - max = fd; - forceLock = true; - } - - public boolean isUnlimited() { - return min == max && min == 0; - } - - public boolean isLocked() { - return min == max && !isUnlimited(); - } - - public double getRadians(int rng) { - if(forceLock) { - return Math.toRadians(Math.ceil(Math.abs((max % 360D)))); - } - - if(isUnlimited()) { - if(interval < 1) { - interval = 1; - } - - return Math.toRadians((interval * (Math.ceil(Math.abs((rng % 360D) / interval)))) % 360D); - } - - if(min == max && min != 0) { - return Math.toRadians(max); - } - - return Math.toRadians(M.clip((interval * (Math.ceil(Math.abs((rng % 360D) / interval)))) % 360D, Math.min(min, max), Math.max(min, max))); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiome.java b/src/main/java/com/volmit/iris/engine/object/IrisBiome.java deleted file mode 100644 index 933cb543f..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiome.java +++ /dev/null @@ -1,726 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.gui.components.RenderType; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.data.DataProvider; -import com.volmit.iris.util.data.VanillaBiomeMap; -import com.volmit.iris.util.inventorygui.RandomColor; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Material; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -import java.awt.Color; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a biome in iris. Biomes are placed inside of regions and hold objects.\nA biome consists of layers (block palletes), decorations, objects & generators.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisBiome extends IrisRegistrant implements IRare { - private static final BlockData BARRIER = Material.BARRIER.createBlockData(); - private final transient AtomicCache> genCache = new AtomicCache<>(); - private final transient AtomicCache> genCacheMax = new AtomicCache<>(); - private final transient AtomicCache> genCacheMin = new AtomicCache<>(); - private final transient AtomicCache> surfaceObjectsCache = new AtomicCache<>(); - private final transient AtomicCache> carveObjectsCache = new AtomicCache<>(); - private final transient AtomicCache cacheColor = new AtomicCache<>(); - private final transient AtomicCache cacheColorObjectDensity = new AtomicCache<>(); - private final transient AtomicCache cacheColorDecoratorLoad = new AtomicCache<>(); - private final transient AtomicCache cacheColorLayerLoad = new AtomicCache<>(); - private final transient AtomicCache cacheColorDepositLoad = new AtomicCache<>(); - private final transient AtomicCache childrenCell = new AtomicCache<>(); - private final transient AtomicCache biomeGenerator = new AtomicCache<>(); - private final transient AtomicCache maxHeight = new AtomicCache<>(); - private final transient AtomicCache maxWithObjectHeight = new AtomicCache<>(); - private final transient AtomicCache realCarveBiome = new AtomicCache<>(); - private final transient AtomicCache> realChildren = new AtomicCache<>(); - private final transient AtomicCache> layerHeightGenerators = new AtomicCache<>(); - private final transient AtomicCache> layerSeaHeightGenerators = new AtomicCache<>(); - @MinNumber(2) - @Required - @Desc("This is the human readable name for this biome. This can and should be different than the file name. This is not used for loading biomes in other objects.") - private String name = "A Biome"; - @ArrayType(min = 1, type = IrisBiomeCustom.class) - @Desc("If the biome type custom is defined, specify this") - private KList customDerivitives; - @Desc("Spawn Entities in this area over time. Iris will continually replenish these mobs just like vanilla does.") - @ArrayType(min = 1, type = String.class) - @RegistryListResource(IrisSpawner.class) - private KList entitySpawners = new KList<>(); - @ArrayType(min = 1, type = IrisEffect.class) - @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play around the player even if where the effect was played is no longer in the biome the player is in.") - private KList effects = new KList<>(); - @DependsOn({"biomeStyle", "biomeZoom", "biomeScatter"}) - @Desc("This changes the dispersion of the biome colors if multiple derivatives are chosen.") - private IrisGeneratorStyle biomeStyle = NoiseStyle.SIMPLEX.style(); - @ArrayType(min = 1, type = IrisBlockDrops.class) - @Desc("Define custom block drops for this biome") - private KList blockDrops = new KList<>(); - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); - @Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") - private boolean lockLayers = false; - @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") - private int lockLayersMax = 7; - @Desc("Carving configuration for the dimension") - private IrisCarving carving = new IrisCarving(); - @Desc("Configuration of fluid bodies such as rivers & lakes") - private IrisFluidBodies fluidBodies = new IrisFluidBodies(); - @MinNumber(1) - @MaxNumber(512) - @Desc("The rarity of this biome (integer)") - private int rarity = 1; - @Desc("A color for visualizing this biome with a color. I.e. #F13AF5. This will show up on the map.") - private String color = null; - @Required - @Desc("The raw derivative of this biome. This is required or the terrain will not properly generate. Use any vanilla biome type. Look in examples/biome-list.txt") - private Biome derivative = Biome.THE_VOID; - @Required - @Desc("Override the derivative when vanilla places structures to this derivative. This is useful for example if you have an ocean biome, but you have set the derivative to desert to get a brown-ish color. To prevent desert structures from spawning on top of your ocean, you can set your vanillaDerivative to ocean, to allow for vanilla structures. Not defining this value will simply select the derivative.") - private Biome vanillaDerivative = null; - @ArrayType(min = 1, type = Biome.class) - @Desc("You can instead specify multiple biome derivatives to randomly scatter colors in this biome") - private KList biomeScatter = new KList<>(); - @ArrayType(min = 1, type = Biome.class) - @Desc("Since 1.13 supports 3D biomes, you can add different derivative colors for anything above the terrain. (Think swampy tree leaves with a desert looking grass surface)") - private KList biomeSkyScatter = new KList<>(); - @DependsOn({"children"}) - @Desc("If this biome has children biomes, and the gen layer chooses one of this biomes children, how much smaller will it be (inside of this biome). Higher values means a smaller biome relative to this biome's size. Set higher than 1.0 and below 3.0 for best results.") - private double childShrinkFactor = 1.5; - @DependsOn({"children"}) - @Desc("If this biome has children biomes, and the gen layer chooses one of this biomes children, How will it be shaped?") - private IrisGeneratorStyle childStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @RegistryListResource(IrisBiome.class) - @ArrayType(min = 1, type = String.class) - @Desc("List any biome names (file names without.json) here as children. Portions of this biome can sometimes morph into their children. Iris supports cyclic relationships such as A > B > A > B. Iris will stop checking 9 biomes down the tree.") - private KList children = new KList<>(); - @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) - @Desc("Jigsaw structures") - private KList jigsawStructures = new KList<>(); - @RegistryListResource(IrisBiome.class) - @Desc("The carving biome. If specified the biome will be used when under a carving instead of this current biome.") - private String carvingBiome = ""; - @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") - private IrisBiomePaletteLayer slab = new IrisBiomePaletteLayer().zero(); - @Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") - private IrisBiomePaletteLayer wall = new IrisBiomePaletteLayer().zero(); - @Required - @ArrayType(min = 1, type = IrisBiomePaletteLayer.class) - @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") - private KList layers = new KList().qadd(new IrisBiomePaletteLayer()); - @Required - @ArrayType(min = 1, type = IrisBiomePaletteLayer.class) - @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") - private KList caveCeilingLayers = new KList().qadd(new IrisBiomePaletteLayer()); - @ArrayType(min = 1, type = IrisBiomePaletteLayer.class) - @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") - private KList seaLayers = new KList<>(); - @ArrayType(min = 1, type = IrisDecorator.class) - @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") - private KList decorators = new KList<>(); - @ArrayType(min = 1, type = IrisObjectPlacement.class) - @Desc("Objects define what schematics (iob files) iris will place in this biome") - private KList objects = new KList<>(); - @Required - @ArrayType(min = 1, type = IrisBiomeGeneratorLink.class) - @Desc("Generators for this biome. Multiple generators with different interpolation sizes will mix with other biomes how you would expect. This defines your biome height relative to the fluid height. Use negative for oceans.") - private KList generators = new KList().qadd(new IrisBiomeGeneratorLink()); - @ArrayType(min = 1, type = IrisDepositGenerator.class) - @Desc("Define biome deposit generators that add onto the existing regional and global deposit generators") - private KList deposits = new KList<>(); - private transient InferredType inferredType; - @Desc("Collection of ores to be generated") - @ArrayType(type = IrisOreGenerator.class, min = 1) - private KList ores = new KList<>(); - - public BlockData generateOres(int x, int y, int z, RNG rng, IrisData data) { - if(ores.isEmpty()) { - return null; - } - BlockData b = null; - for(IrisOreGenerator i : ores) { - - b = i.generate(x, y, z, rng, data); - if(b != null) { - return b; - } - } - return null; - } - - public Biome getVanillaDerivative() { - return vanillaDerivative == null ? derivative : vanillaDerivative; - } - - public boolean isCustom() { - return getCustomDerivitives() != null && getCustomDerivitives().isNotEmpty(); - } - - public double getGenLinkMax(String loadKey) { - Integer v = genCacheMax.aquire(() -> - { - KMap l = new KMap<>(); - - for(IrisBiomeGeneratorLink i : getGenerators()) { - l.put(i.getGenerator(), i.getMax()); - } - - return l; - }).get(loadKey); - - return v == null ? 0 : v; - } - - public double getGenLinkMin(String loadKey) { - Integer v = genCacheMin.aquire(() -> - { - KMap l = new KMap<>(); - - for(IrisBiomeGeneratorLink i : getGenerators()) { - l.put(i.getGenerator(), i.getMin()); - } - - return l; - }).get(loadKey); - - return v == null ? 0 : v; - } - - public IrisBiomeGeneratorLink getGenLink(String loadKey) { - return genCache.aquire(() -> - { - KMap l = new KMap<>(); - - for(IrisBiomeGeneratorLink i : getGenerators()) { - l.put(i.getGenerator(), i); - } - - return l; - }).get(loadKey); - } - - public IrisBiome getRealCarvingBiome(IrisData data) { - return realCarveBiome.aquire(() -> - { - IrisBiome biome = data.getBiomeLoader().load(getCarvingBiome()); - - if(biome == null) { - biome = this; - } - - return biome; - }); - } - - public KList getSurfaceObjects() { - return getSurfaceObjectsCache().aquire(() -> - { - KList o = getObjects().copy(); - - for(IrisObjectPlacement i : o.copy()) { - if(!i.getCarvingSupport().supportsSurface()) { - o.remove(i); - } - } - - return o; - }); - } - - public KList getCarvingObjects() { - return getCarveObjectsCache().aquire(() -> - { - KList o = getObjects().copy(); - - for(IrisObjectPlacement i : o.copy()) { - if(!i.getCarvingSupport().supportsCarving()) { - o.remove(i); - } - } - - return o; - }); - } - - public double getHeight(Engine xg, double x, double z, long seed) { - double height = 0; - - for(IrisBiomeGeneratorLink i : generators) { - height += i.getHeight(xg, x, z, seed); - } - - return Math.max(0, Math.min(height, xg.getHeight())); - } - - public CNG getBiomeGenerator(RNG random) { - return biomeGenerator.aquire(() -> - biomeStyle.create(random.nextParallelRNG(213949 + 228888 + getRarity() + getName().length()), getLoader())); - } - - public CNG getChildrenGenerator(RNG random, int sig, double scale) { - return childrenCell.aquire(() -> getChildStyle().create(random.nextParallelRNG(sig * 2137), getLoader()).bake().scale(scale).bake()); - } - - public KList generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - if(isLockLayers()) { - return generateLockedLayers(wx, wz, random, maxDepth, height, rdata, complex); - } - - KList data = new KList<>(); - - if(maxDepth <= 0) { - return data; - } - - for(int i = 0; i < layers.size(); i++) { - CNG hgen = getLayerHeightGenerators(random, rdata).get(i); - double d = hgen.fit(layers.get(i).getMinHeight(), layers.get(i).getMaxHeight(), wx / layers.get(i).getZoom(), wz / layers.get(i).getZoom()); - - IrisSlopeClip sc = getLayers().get(i).getSlopeCondition(); - - if(!sc.isDefault()) { - if(!sc.isValid(complex.getSlopeStream().get(wx, wz))) { - d = 0; - } - } - - if(d <= 0) { - continue; - } - - for(int j = 0; j < d; j++) { - if(data.size() >= maxDepth) { - break; - } - - try { - data.add(getLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / layers.get(i).getZoom(), j, (wz - j) / layers.get(i).getZoom(), rdata)); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - if(data.size() >= maxDepth) { - break; - } - - if(dim.isExplodeBiomePalettes()) { - for(int j = 0; j < dim.getExplodeBiomePaletteSize(); j++) { - data.add(BARRIER); - - if(data.size() >= maxDepth) { - break; - } - } - } - } - - return data; - } - - public KList generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - KList data = new KList<>(); - - if(maxDepth <= 0) { - return data; - } - - for(int i = 0; i < caveCeilingLayers.size(); i++) { - CNG hgen = getLayerHeightGenerators(random, rdata).get(i); - double d = hgen.fit(caveCeilingLayers.get(i).getMinHeight(), caveCeilingLayers.get(i).getMaxHeight(), wx / caveCeilingLayers.get(i).getZoom(), wz / caveCeilingLayers.get(i).getZoom()); - - if(d <= 0) { - continue; - } - - for(int j = 0; j < d; j++) { - if(data.size() >= maxDepth) { - break; - } - - try { - data.add(getCaveCeilingLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / caveCeilingLayers.get(i).getZoom(), j, (wz - j) / caveCeilingLayers.get(i).getZoom(), rdata)); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - if(data.size() >= maxDepth) { - break; - } - - if(dim.isExplodeBiomePalettes()) { - for(int j = 0; j < dim.getExplodeBiomePaletteSize(); j++) { - data.add(BARRIER); - - if(data.size() >= maxDepth) { - break; - } - } - } - } - - return data; - } - - public KList generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) { - KList data = new KList<>(); - KList real = new KList<>(); - int maxDepth = Math.min(maxDepthf, getLockLayersMax()); - if(maxDepth <= 0) { - return data; - } - - for(int i = 0; i < layers.size(); i++) { - CNG hgen = getLayerHeightGenerators(random, rdata).get(i); - double d = hgen.fit(layers.get(i).getMinHeight(), layers.get(i).getMaxHeight(), wx / layers.get(i).getZoom(), wz / layers.get(i).getZoom()); - - IrisSlopeClip sc = getLayers().get(i).getSlopeCondition(); - - if(!sc.isDefault()) { - if(!sc.isValid(complex.getSlopeStream().get(wx, wz))) { - d = 0; - } - } - - if(d <= 0) { - continue; - } - - for(int j = 0; j < d; j++) { - try { - data.add(getLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / layers.get(i).getZoom(), j, (wz - j) / layers.get(i).getZoom(), rdata)); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - } - - if(data.isEmpty()) { - return real; - } - - for(int i = 0; i < maxDepth; i++) { - int offset = (512 - height) - i; - int index = offset % data.size(); - real.add(data.get(Math.max(index, 0))); - } - - return real; - } - - public int getMaxHeight() { - return maxHeight.aquire(() -> - { - int maxHeight = 0; - - for(IrisBiomeGeneratorLink i : getGenerators()) { - maxHeight += i.getMax(); - } - - return maxHeight; - }); - } - - public int getMaxWithObjectHeight(IrisData data) { - return maxWithObjectHeight.aquire(() -> - { - int maxHeight = 0; - - for(IrisBiomeGeneratorLink i : getGenerators()) { - maxHeight += i.getMax(); - } - - int gg = 0; - - for(IrisObjectPlacement i : getObjects()) { - for(IrisObject j : data.getObjectLoader().loadAll(i.getPlace())) { - gg = Math.max(gg, j.getH()); - } - } - - return maxHeight + gg + 3; - }); - } - - public IrisBiome infer(InferredType t, InferredType type) { - setInferredType(t.equals(InferredType.DEFER) ? type : t); - return this; - } - - public KList generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisData rdata) { - KList data = new KList<>(); - - for(int i = 0; i < seaLayers.size(); i++) { - CNG hgen = getLayerSeaHeightGenerators(random, rdata).get(i); - int d = hgen.fit(seaLayers.get(i).getMinHeight(), seaLayers.get(i).getMaxHeight(), wx / seaLayers.get(i).getZoom(), wz / seaLayers.get(i).getZoom()); - - if(d < 0) { - continue; - } - - for(int j = 0; j < d; j++) { - if(data.size() >= maxDepth) { - break; - } - - try { - data.add(getSeaLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / seaLayers.get(i).getZoom(), j, (wz - j) / seaLayers.get(i).getZoom(), rdata)); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - if(data.size() >= maxDepth) { - break; - } - } - - return data; - } - - public KList getLayerHeightGenerators(RNG rng, IrisData rdata) { - return layerHeightGenerators.aquire(() -> - { - KList layerHeightGenerators = new KList<>(); - - int m = 7235; - - for(IrisBiomePaletteLayer i : getLayers()) { - layerHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), rdata)); - } - - return layerHeightGenerators; - }); - } - - public KList getLayerSeaHeightGenerators(RNG rng, IrisData data) { - return layerSeaHeightGenerators.aquire(() -> - { - KList layerSeaHeightGenerators = new KList<>(); - - int m = 7735; - - for(IrisBiomePaletteLayer i : getSeaLayers()) { - layerSeaHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), data)); - } - - return layerSeaHeightGenerators; - }); - } - - public boolean isLand() { - if(inferredType == null) { - return true; - } - - return inferredType.equals(InferredType.LAND); - } - - public boolean isSea() { - if(inferredType == null) { - return false; - } - return inferredType.equals(InferredType.SEA); - } - - public boolean isAquatic() { - return isSea(); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isShore() { - if(inferredType == null) { - return false; - } - return inferredType.equals(InferredType.SHORE); - } - - public Biome getSkyBiome(RNG rng, double x, double y, double z) { - if(biomeSkyScatter.size() == 1) { - return biomeSkyScatter.get(0); - } - - if(biomeSkyScatter.isEmpty()) { - return getGroundBiome(rng, x, y, z); - } - - return biomeSkyScatter.get(getBiomeGenerator(rng).fit(0, biomeSkyScatter.size() - 1, x, y, z)); - } - - public IrisBiomeCustom getCustomBiome(RNG rng, double x, double y, double z) { - if(customDerivitives.size() == 1) { - return customDerivitives.get(0); - } - - return customDerivitives.get(getBiomeGenerator(rng).fit(0, customDerivitives.size() - 1, x, y, z)); - } - - public KList getRealChildren(DataProvider g) { - return realChildren.aquire(() -> - { - KList realChildren = new KList<>(); - - for(String i : getChildren()) { - realChildren.add(g.getData().getBiomeLoader().load(i)); - } - - return realChildren; - }); - } - - public KList getAllChildren(DataProvider g, int limit) { - KSet m = new KSet<>(); - m.addAll(getChildren()); - limit--; - - if(limit > 0) { - for(String i : getChildren()) { - IrisBiome b = g.getData().getBiomeLoader().load(i); - m.addAll(b.getAllChildren(g, limit)); - } - } - - return new KList<>(m); - } - - //TODO: Test - public Biome getGroundBiome(RNG rng, double x, double y, double z) { - if(biomeScatter.isEmpty()) { - return getDerivative(); - } - - if(biomeScatter.size() == 1) { - return biomeScatter.get(0); - } - - return getBiomeGenerator(rng).fit(biomeScatter, x, y, z); - } - - public BlockData getSurfaceBlock(int x, int z, RNG rng, IrisData idm) { - if(getLayers().isEmpty()) { - return B.get("AIR"); - } - - return getLayers().get(0).get(rng, x, 0, z, idm); - } - - public Color getColor(Engine engine, RenderType type) { - switch(type) { - case BIOME, HEIGHT, CAVE_LAND, REGION, BIOME_SEA, BIOME_LAND -> { - return this.cacheColor.aquire(() -> { - if(this.color == null) { - RandomColor randomColor = new RandomColor(getName().hashCode()); - if(this.getVanillaDerivative() == null) { - Iris.warn("No vanilla biome found for " + getName()); - return new Color(randomColor.randomColor()); - } - RandomColor.Color col = VanillaBiomeMap.getColorType(this.getVanillaDerivative()); - RandomColor.Luminosity lum = VanillaBiomeMap.getColorLuminosity(this.getVanillaDerivative()); - RandomColor.SaturationType sat = VanillaBiomeMap.getColorSaturatiom(this.getVanillaDerivative()); - int newColorI = randomColor.randomColor(col, col == RandomColor.Color.MONOCHROME ? RandomColor.SaturationType.MONOCHROME : sat, lum); - - return new Color(newColorI); - } - - try { - return Color.decode(this.color); - } catch(NumberFormatException e) { - Iris.warn("Could not parse color \"" + this.color + "\" for biome " + getName()); - return new Color(new RandomColor(getName().hashCode()).randomColor()); - } - }); - } - case OBJECT_LOAD -> { - return cacheColorObjectDensity.aquire(() -> { - double density = 0; - - for(IrisObjectPlacement i : getObjects()) { - density += i.getDensity() * i.getChance(); - } - - return Color.getHSBColor(0.225f, (float) (density / engine.getMaxBiomeObjectDensity()), 1f); - }); - } - case DECORATOR_LOAD -> { - return cacheColorDecoratorLoad.aquire(() -> { - double density = 0; - - for(IrisDecorator i : getDecorators()) { - density += i.getChance() * Math.min(1, i.getStackMax()) * 256; - } - - return Color.getHSBColor(0.41f, (float) (density / engine.getMaxBiomeDecoratorDensity()), 1f); - }); - } - case LAYER_LOAD -> { - return cacheColorLayerLoad.aquire(() -> Color.getHSBColor(0.625f, (float) (getLayers().size() / engine.getMaxBiomeLayerDensity()), 1f)); - } - } - - return Color.black; - } - - @Override - public String getFolderName() { - return "biomes"; - } - - @Override - public String getTypeName() { - return "Biome"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustom.java b/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustom.java deleted file mode 100644 index 3bd9a2b68..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustom.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.json.JSONArray; -import com.volmit.iris.util.json.JSONObject; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.awt.Color; -import java.util.Locale; - -@Snippet("custom-biome") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A custom biome, generated through a datapack") -@Data -public class IrisBiomeCustom { - @Required - @Desc("The resource key of this biome. Just a simple id such as 'plains' or something.") - private String id = ""; - - @MinNumber(-3) - @MaxNumber(3) - @Desc("The biome's temperature") - private double temperature = 0.8; - - @MinNumber(-3) - @MaxNumber(3) - @Desc("The biome's downfall amount (snow / rain), see preci") - private double humidity = 0.4; - - @DependsOn("spawnRarity") - @ArrayType(min = 1, type = IrisBiomeCustomSpawn.class) - @Desc("The biome's mob spawns") - private KList spawns = new KList<>(); - - @Desc("The biome's downfall type") - private IrisBiomeCustomPrecipType downfallType = IrisBiomeCustomPrecipType.rain; - - @Desc("Define an ambient particle to be rendered clientside (no server cost!)") - private IrisBiomeCustomParticle ambientParticle = null; - - @Required - @Desc("The biome's category type") - private IrisBiomeCustomCategory category = IrisBiomeCustomCategory.plains; - - @Desc("The spawn rarity of any defined spawners") - private int spawnRarity = -1; - - @Desc("The color of the sky, top half of sky. (hex format)") - private String skyColor = "#79a8e1"; - - @Desc("The color of the fog, bottom half of sky. (hex format)") - private String fogColor = "#c0d8e1"; - - @Desc("The color of the water (hex format). Leave blank / don't define to not change") - private String waterColor = "#3f76e4"; - - @Desc("The color of water fog (hex format). Leave blank / don't define to not change") - private String waterFogColor = "#050533"; - - @Desc("The color of the grass (hex format). Leave blank / don't define to not change") - private String grassColor = ""; - - @Desc("The color of foliage (hex format). Leave blank / don't define to not change") - private String foliageColor = ""; - - public String generateJson() { - JSONObject effects = new JSONObject(); - effects.put("sky_color", parseColor(getSkyColor())); - effects.put("fog_color", parseColor(getFogColor())); - effects.put("water_color", parseColor(getWaterColor())); - effects.put("water_fog_color", parseColor(getWaterFogColor())); - - if(ambientParticle != null) { - JSONObject particle = new JSONObject(); - JSONObject po = new JSONObject(); - po.put("type", ambientParticle.getParticle().name().toLowerCase()); - particle.put("options", po); - particle.put("probability", ambientParticle.getRarity()); - effects.put("particle", particle); - } - - if(!getGrassColor().isEmpty()) { - effects.put("grass_color", parseColor(getGrassColor())); - } - - if(!getFoliageColor().isEmpty()) { - effects.put("foliage_color", parseColor(getFoliageColor())); - } - - JSONObject j = new JSONObject(); - j.put("surface_builder", "minecraft:grass"); - j.put("depth", 0.125); - j.put("scale", 0.05); - j.put("temperature", getTemperature()); - j.put("downfall", getHumidity()); - j.put("creature_spawn_probability", getSpawnRarity()); - j.put("precipitation", getDownfallType().toString().toLowerCase()); - j.put("category", getCategory().toString().toLowerCase()); - j.put("effects", effects); - j.put("starts", new JSONArray()); - j.put("spawners", new JSONObject()); - j.put("spawn_costs", new JSONObject()); - j.put("carvers", new JSONObject()); - j.put("features", new JSONArray()); - - if(spawnRarity > 0) { - j.put("creature_spawn_probability", spawnRarity); - } - - if(getSpawns() != null && getSpawns().isNotEmpty()) { - JSONObject spawners = new JSONObject(); - KMap groups = new KMap<>(); - - for(IrisBiomeCustomSpawn i : getSpawns()) { - JSONArray g = groups.computeIfAbsent(i.getGroup(), (k) -> new JSONArray()); - JSONObject o = new JSONObject(); - o.put("type", "minecraft:" + i.getType().name().toLowerCase()); - o.put("weight", i.getWeight()); - o.put("minCount", i.getMinCount()); - o.put("maxCount", i.getMaxCount()); - g.put(o); - } - - for(IrisBiomeCustomSpawnType i : groups.k()) { - spawners.put(i.name().toLowerCase(Locale.ROOT), groups.get(i)); - } - - j.put("spawners", spawners); - } - - return j.toString(4); - } - - private int parseColor(String c) { - String v = (c.startsWith("#") ? c : "#" + c).trim(); - try { - return Color.decode(v).getRGB(); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Error Parsing '''color''', (" + c + ")"); - } - - return 0; - } - - public String getId() { - return id.toLowerCase(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomCategory.java b/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomCategory.java deleted file mode 100644 index 0d638e1cc..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomCategory.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("The custom biome category. Vanilla asks for this, basically what represents your biome closest?") -public enum IrisBiomeCustomCategory { - beach, - desert, - extreme_hills, - forest, - icy, - jungle, - mesa, - mushroom, - nether, - none, - ocean, - plains, - river, - savanna, - swamp, - taiga, - the_end -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomParticle.java b/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomParticle.java deleted file mode 100644 index 5af8fdb08..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomParticle.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Particle; - -@Snippet("custom-biome-particle") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A custom biome ambient particle") -@Data -public class IrisBiomeCustomParticle { - @Required - @Desc("The biome's particle type") - private Particle particle = Particle.FLASH; - - @MinNumber(1) - @MaxNumber(10000) - @Desc("The rarity") - private int rarity = 35; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomPrecipType.java b/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomPrecipType.java deleted file mode 100644 index c6e242bed..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomPrecipType.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Snow, rain, or nothing") -public enum IrisBiomeCustomPrecipType { - @Desc("No downfall") - none, - - @Desc("Rain downfall") - rain, - - @Desc("Snow downfall") - snow -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomSpawn.java b/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomSpawn.java deleted file mode 100644 index 9fd78d1b9..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomSpawn.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.entity.EntityType; - -@Snippet("custom-biome-spawn") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A custom biome spawn") -@Data -public class IrisBiomeCustomSpawn { - @Required - @Desc("The biome's entity type") - private EntityType type = EntityType.COW; - - @MinNumber(1) - @MaxNumber(20) - @Desc("The min to spawn") - private int minCount = 2; - - @MinNumber(1) - @MaxNumber(20) - @Desc("The max to spawn") - private int maxCount = 5; - - @MinNumber(1) - @MaxNumber(1000) - @Desc("The weight in this group. Higher weight, the more common this type is spawned") - private int weight = 1; - - @Desc("The rarity") - private IrisBiomeCustomSpawnType group = IrisBiomeCustomSpawnType.MISC; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomSpawnType.java b/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomSpawnType.java deleted file mode 100644 index 1c393e42d..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiomeCustomSpawnType.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("The mob spawn group") -public enum IrisBiomeCustomSpawnType { - @Desc("Typical monsters that spawn at night, like zombies and skeletons") - MONSTER, - - @Desc("Typical creatures like sheep, pigs, cows") - CREATURE, - - @Desc("Eg bats") - AMBIENT, - - @Desc("Odd spawn group but ok") - UNDERGROUND_WATER_CREATURE, - - @Desc("Water mobs like squid, dolphins") - WATER_CREATURE, - - @Desc("Fish") - WATER_AMBIENT, - - @Desc("Unknown") - MISC -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiomeGeneratorLink.java b/src/main/java/com/volmit/iris/engine/object/IrisBiomeGeneratorLink.java deleted file mode 100644 index eeb967a07..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiomeGeneratorLink.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.data.DataProvider; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("generator-layer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("This represents a link to a generator for a biome") -@Data -public class IrisBiomeGeneratorLink { - - private final transient AtomicCache gen = new AtomicCache<>(); - @RegistryListResource(IrisGenerator.class) - @Desc("The generator id") - private String generator = "default"; - @DependsOn({"min", "max"}) - @Required - @MinNumber(-2032) // TODO: WARNING HEIGHT - @MaxNumber(2032) // TODO: WARNING HEIGHT - @Desc("The min block value (value + fluidHeight)") - private int min = 0; - @DependsOn({"min", "max"}) - @Required - @MinNumber(-2032) // TODO: WARNING HEIGHT - @MaxNumber(2032) // TODO: WARNING HEIGHT - @Desc("The max block value (value + fluidHeight)") - private int max = 0; - - public IrisGenerator getCachedGenerator(DataProvider g) { - return gen.aquire(() -> - { - IrisGenerator gen = g.getData().getGeneratorLoader().load(getGenerator()); - - if(gen == null) { - gen = new IrisGenerator(); - } - - return gen; - }); - } - - public double getHeight(DataProvider xg, double x, double z, long seed) { - double g = getCachedGenerator(xg).getHeight(x, z, seed); - g = g < 0 ? 0 : g; - g = g > 1 ? 1 : g; - - return IrisInterpolation.lerp(min, max, g); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBiomePaletteLayer.java b/src/main/java/com/volmit/iris/engine/object/IrisBiomePaletteLayer.java deleted file mode 100644 index dd3a8beae..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBiomePaletteLayer.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -@Snippet("biome-palette") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A layer of surface / subsurface material in biomes") -@Data -public class IrisBiomePaletteLayer { - private final transient AtomicCache> blockData = new AtomicCache<>(); - private final transient AtomicCache layerGenerator = new AtomicCache<>(); - private final transient AtomicCache heightGenerator = new AtomicCache<>(); - @Desc("The style of noise") - private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); - @DependsOn({"minHeight", "maxHeight"}) - @MinNumber(0) - @MaxNumber(2032) // TODO: WARNING HEIGHT - - @Desc("The min thickness of this layer") - private int minHeight = 1; - @DependsOn({"minHeight", "maxHeight"}) - @MinNumber(1) - @MaxNumber(2032) // TODO: WARNING HEIGHT - - @Desc("The max thickness of this layer") - private int maxHeight = 1; - @Desc("If set, this layer will change size depending on the slope. If in bounds, the layer will get larger (taller) the closer to the center of this slope clip it is. If outside of the slipe's bounds, this layer will not show.") - private IrisSlopeClip slopeCondition = new IrisSlopeClip(); - @MinNumber(0.0001) - @Desc("The terrain zoom mostly for zooming in on a wispy palette") - private double zoom = 5; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks to be used in this layer") - private KList palette = new KList().qadd(new IrisBlockData("GRASS_BLOCK")); - - public CNG getHeightGenerator(RNG rng, IrisData data) { - return heightGenerator.aquire(() -> CNG.signature(rng.nextParallelRNG(minHeight * maxHeight + getBlockData(data).size()))); - } - - public BlockData get(RNG rng, double x, double y, double z, IrisData data) { - if(getBlockData(data).isEmpty()) { - return null; - } - - if(getBlockData(data).size() == 1) { - return getBlockData(data).get(0); - } - - return getLayerGenerator(rng, data).fit(getBlockData(data), x / zoom, y / zoom, z / zoom); - } - - public CNG getLayerGenerator(RNG rng, IrisData data) { - return layerGenerator.aquire(() -> - { - RNG rngx = rng.nextParallelRNG(minHeight + maxHeight + getBlockData(data).size()); - return style.create(rngx, data); - }); - } - - public KList add(String b) { - palette.add(new IrisBlockData(b)); - - return palette; - } - - public KList getBlockData(IrisData data) { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for(IrisBlockData ix : palette) { - BlockData bx = ix.getBlockData(data); - if(bx != null) { - for(int i = 0; i < ix.getWeight(); i++) { - blockData.add(bx); - } - } - } - - return blockData; - }); - } - - public IrisBiomePaletteLayer zero() { - palette.clear(); - return this; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBlockData.java b/src/main/java/com/volmit/iris/engine/object/IrisBlockData.java deleted file mode 100644 index 384337348..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBlockData.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListBlockType; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.EntityType; - -import java.util.Map; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents Block Data") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisBlockData extends IrisRegistrant { - private final transient AtomicCache blockdata = new AtomicCache<>(); - private final transient AtomicCache realProperties = new AtomicCache<>(); - @RegistryListBlockType - @Required - @Desc("The block to use") - private String block = "air"; - @Desc("Debug this block by printing it to the console when it's used. Must have debug turned on in settings.") - private boolean debug = false; - @MinNumber(1) - @MaxNumber(1000) - @Desc("The weight is used when this block data is inside of a list of blockdata. A weight of two is just as if you placed two of the same block data values in the same list making it more common when randomly picked.") - private int weight = 1; - @Desc("If the block cannot be created on this version, Iris will attempt to use this backup block data instead.") - private IrisBlockData backup = null; - @Desc("Optional properties for this block data such as 'waterlogged': true") - private KMap data = new KMap<>(); - - public IrisBlockData(String b) { - this.block = b; - } - - public static IrisBlockData from(String j) { - IrisBlockData b = new IrisBlockData(); - String v = j.toLowerCase().trim(); - - if(v.contains("[")) { - KList props = new KList<>(); - String rp = v.split("\\Q[\\E")[1].replaceAll("\\Q]\\E", ""); - b.setBlock(v.split("\\Q[\\E")[0]); - - if(rp.contains(",")) { - props.add(rp.split("\\Q,\\E")); - } else { - props.add(rp); - } - - for(String i : props) { - Object kg = filter(i.split("\\Q=\\E")[1]); - b.data.put(i.split("\\Q=\\E")[0], kg); - } - } else { - b.setBlock(v); - } - - return b; - } - - private static Object filter(String string) { - if(string.equals("true")) { - return true; - } - - if(string.equals("false")) { - return false; - } - - try { - return Integer.parseInt(string); - } catch(Throwable ignored) { - // Checks - } - - try { - return Double.valueOf(string).intValue(); - } catch(Throwable ignored) { - // Checks - } - - return string; - } - - public String computeProperties(KMap data) { - if(data.isEmpty()) { - return ""; - } - - KList r = new KList<>(); - - for(Map.Entry entry : data.entrySet()) { - r.add(entry.getKey() + "=" + filter(entry.getValue().toString())); - } - - return "[" + r.toString(",") + "]"; - } - - public String computeProperties() { - return computeProperties(getData()); - } - - public BlockData getBlockData(IrisData data) { - return blockdata.aquire(() -> - { - BlockData b = null; - - IrisBlockData customData = data.getBlockLoader().load(getBlock(), false); - - if(customData != null) { - b = customData.getBlockData(data); - - if(b != null) { - b = b.clone(); - - String st = b.getAsString(true); - - if(st.contains("[")) { - st = st.split("\\Q[\\E")[0]; - } - - KMap cdata = customData.getData().copy(); - - for(String i : getData().keySet()) { - cdata.put(i, getData().get(i)); - } - - String sx = keyify(st) + computeProperties(cdata); - - if(debug) { - Iris.debug("Block Data used " + sx + " (CUSTOM)"); - } - - BlockData bx = B.get(sx); - - if(bx != null) { - return bx; - } - - if(b != null) { - return b; - } - } - } - - String ss = keyify(getBlock()) + computeProperties(); - b = B.get(ss); - - if(debug) { - Iris.debug("Block Data used " + ss); - } - - if(b != null) { - return b; - } - - if(backup != null) { - return backup.getBlockData(data); - } - - return B.get("AIR"); - }); - } - - public TileData tryGetTile() { - //TODO Do like a registry thing with the tile data registry. Also update the parsing of data to include **block** entities. - if(data.containsKey("entitySpawn")) { - TileSpawner spawner = new TileSpawner(); - String name = (String)data.get("entitySpawn"); - if(name.contains(":")) - name = name.split(":")[1]; - spawner.setEntityType(EntityType.fromName(name)); - return spawner; - } - return null; - } - - private String keyify(String dat) { - if(dat.contains(":")) { - return dat; - } - - return "minecraft:" + dat; - } - - @Override - public String getFolderName() { - return "blocks"; - } - - @Override - public String getTypeName() { - return "Block"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisBlockDrops.java b/src/main/java/com/volmit/iris/engine/object/IrisBlockDrops.java deleted file mode 100644 index 9ef567271..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisBlockDrops.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; - -@Snippet("block-drops") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a block drop list") -@Data -public class IrisBlockDrops { - private final transient AtomicCache> data = new AtomicCache<>(); - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The blocks that drop loot") - private KList blocks = new KList<>(); - @Desc("If exact blocks is set to true, minecraft:barrel[axis=x] will only drop for that axis. When exact is false (default) any barrel will drop the defined drops.") - private boolean exactBlocks = false; - @Desc("Add in specific items to drop") - @ArrayType(min = 1, type = IrisLoot.class) - private KList drops = new KList<>(); - @Desc("If this is in a biome, setting skipParents to true will ignore the drops in the region and dimension for this block type. The default (false) will allow all three nodes to fire and add to a list of drops.") - private boolean skipParents = false; - @Desc("Removes the default vanilla block drops and only drops the given items & any parent loot tables specified for this block type.") - private boolean replaceVanillaDrops = false; - - public boolean shouldDropFor(BlockData data, IrisData rdata) { - KList list = this.data.aquire(() -> - { - KList b = new KList<>(); - - for(IrisBlockData i : getBlocks()) { - BlockData dd = i.getBlockData(rdata); - - if(dd != null) { - b.add(dd); - } - } - - return b.removeDuplicates(); - }); - - for(BlockData i : list) { - if(exactBlocks ? i.equals(data) : i.getMaterial().equals(data.getMaterial())) { - return true; - } - } - - return false; - } - - public void fillDrops(boolean debug, KList d) { - for(IrisLoot i : getDrops()) { - if(RNG.r.i(1, i.getRarity()) == i.getRarity()) { - d.add(i.get(debug, RNG.r)); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisCarving.java b/src/main/java/com/volmit/iris/engine/object/IrisCarving.java deleted file mode 100644 index 6ee2055b5..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisCarving.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("carving") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a carving configuration") -@Data -public class IrisCarving { - @ArrayType(type = IrisCavePlacer.class, min = 1) - @Desc("Define cave placers") - private KList caves = new KList<>(); - - @ArrayType(type = IrisRavinePlacer.class, min = 1) - @Desc("Define ravine placers") - private KList ravines = new KList<>(); - - @ArrayType(type = IrisElipsoid.class, min = 1) - @Desc("Define elipsoids") - private KList elipsoids = new KList<>(); - - @ArrayType(type = IrisSphere.class, min = 1) - @Desc("Define spheres") - private KList spheres = new KList<>(); - - @ArrayType(type = IrisPyramid.class, min = 1) - @Desc("Define pyramids") - private KList pyramids = new KList<>(); - - - @BlockCoordinates - public void doCarving(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z) { - doCarving(writer, rng, engine, x, y, z, -1); - } - - @BlockCoordinates - public void doCarving(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z, int waterHint) { - if(caves.isNotEmpty()) { - for(IrisCavePlacer i : caves) { - i.generateCave(writer, rng, engine, x, y, z, waterHint); - } - } - - if(ravines.isNotEmpty()) { - for(IrisRavinePlacer i : ravines) { - i.generateRavine(writer, rng, engine, x, y, z, waterHint); - } - } - - if(spheres.isNotEmpty()) { - for(IrisSphere i : spheres) { - if(rng.nextInt(i.getRarity()) == 0) { - i.generate(rng, engine, writer, x, y, z); - } - } - } - - if(elipsoids.isNotEmpty()) { - for(IrisElipsoid i : elipsoids) { - if(rng.nextInt(i.getRarity()) == 0) { - i.generate(rng, engine, writer, x, y, z); - } - } - } - - if(pyramids.isNotEmpty()) { - for(IrisPyramid i : pyramids) { - if(rng.nextInt(i.getRarity()) == 0) { - i.generate(rng, engine, writer, x, y, z); - } - } - } - } - - public int getMaxRange(IrisData data) { - int max = 0; - - for(IrisCavePlacer i : caves) { - max = Math.max(max, i.getSize(data)); - } - - for(IrisRavinePlacer i : ravines) { - max = Math.max(max, i.getSize(data)); - } - - if(elipsoids.isNotEmpty()) { - max = (int) Math.max(elipsoids.stream().mapToDouble(IrisElipsoid::maxSize).max().getAsDouble(), max); - } - - if(spheres.isNotEmpty()) { - max = (int) Math.max(spheres.stream().mapToDouble(IrisSphere::maxSize).max().getAsDouble(), max); - } - - if(pyramids.isNotEmpty()) { - max = (int) Math.max(pyramids.stream().mapToDouble(IrisPyramid::maxSize).max().getAsDouble(), max); - } - - return max; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisCave.java b/src/main/java/com/volmit/iris/engine/object/IrisCave.java deleted file mode 100644 index ce0f918a6..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisCave.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@EqualsAndHashCode(callSuper = true) -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Translate objects") -@Data -public class IrisCave extends IrisRegistrant { - @Desc("Define the shape of this cave") - private IrisWorm worm = new IrisWorm(); - - @Desc("Define potential forking features") - private IrisCarving fork = new IrisCarving(); - - @RegistryListResource(IrisBiome.class) - @Desc("Force this cave to only generate the specified custom biome") - private String customBiome = ""; - - @Desc("Limit the worm from ever getting higher or lower than this range") - private IrisRange verticalRange = new IrisRange(3, 255); - - @Override - public String getFolderName() { - return "caves"; - } - - @Override - public String getTypeName() { - return "Cave"; - } - - public void generate(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z) { - generate(writer, rng, engine, x, y, z, -1); - } - - public void generate(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z, int waterHint) { - - double girth = getWorm().getGirth().get(rng, x, z, engine.getData()); - KList points = getWorm().generate(rng, engine.getData(), writer, verticalRange, x, y, z, (at) -> { - }); - int highestWater = Math.max(waterHint, -1); - - if(highestWater == -1) { - for(IrisPosition i : points) { - double yy = i.getY() + girth; - int th = engine.getHeight(x, z, true); - - if(yy > th && th < engine.getDimension().getFluidHeight()) { - highestWater = Math.max(highestWater, (int) yy); - break; - } - } - } - - - int h = Math.min(Math.max(highestWater, waterHint), engine.getDimension().getFluidHeight()); - - for(IrisPosition i : points) { - fork.doCarving(writer, rng, engine, i.getX(), i.getY(), i.getZ(), h); - } - - MatterCavern c = new MatterCavern(true, customBiome, (byte) 0); - MatterCavern w = new MatterCavern(true, customBiome, (byte) 1); - - writer.setLineConsumer(points, - girth, true, - (xf, yf, zf) -> yf <= h ? w : c); - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } - - public int getMaxSize(IrisData data) { - return getWorm().getMaxDistance() + fork.getMaxRange(data); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisCavePlacer.java b/src/main/java/com/volmit/iris/engine/object/IrisCavePlacer.java deleted file mode 100644 index 9ff719397..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisCavePlacer.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.concurrent.atomic.AtomicBoolean; - -@Snippet("cave-placer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Translate objects") -@Data -public class IrisCavePlacer implements IRare { - private transient final AtomicCache caveCache = new AtomicCache<>(); - private transient final AtomicBoolean fail = new AtomicBoolean(false); - @Required - @Desc("Typically a 1 in RARITY on a per chunk/fork basis") - @MinNumber(1) - private int rarity = 15; - @MinNumber(1) - @Required - @Desc("The cave to place") - @RegistryListResource(IrisCave.class) - private String cave; - @Desc("If set to true, this cave is allowed to break the surface") - private boolean breakSurface = true; - @Desc("The height range this cave can spawn at. If breakSurface is false, the output of this range will be clamped by the current world height to prevent surface breaking.") - private IrisStyledRange caveStartHeight = new IrisStyledRange(13, 120, new IrisGeneratorStyle(NoiseStyle.STATIC)); - - public IrisCave getRealCave(IrisData data) { - return caveCache.aquire(() -> data.getCaveLoader().load(getCave())); - } - - public void generateCave(MantleWriter mantle, RNG rng, Engine engine, int x, int y, int z) { - generateCave(mantle, rng, engine, x, y, z, -1); - } - - public void generateCave(MantleWriter mantle, RNG rng, Engine engine, int x, int y, int z, int waterHint) { - if(fail.get()) { - return; - } - - if(rng.nextInt(rarity) != 0) { - return; - } - - IrisData data = engine.getData(); - IrisCave cave = getRealCave(data); - - if(cave == null) { - Iris.warn("Unable to locate cave for generation!"); - fail.set(true); - return; - } - - if(y == -1) { - int h = (int) caveStartHeight.get(rng, x, z, data); - int ma = breakSurface ? h : (int) (engine.getComplex().getHeightStream().get(x, z) - 9); - y = Math.min(h, ma); - } - - try { - cave.generate(mantle, rng, engine, x + rng.nextInt(15), y, z + rng.nextInt(15), waterHint); - } catch(Throwable e) { - e.printStackTrace(); - fail.set(true); - } - } - - public int getSize(IrisData data) { - IrisCave cave = getRealCave(data); - - if(cave != null) { - return cave.getMaxSize(data); - } - - return 32; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisColor.java b/src/main/java/com/volmit/iris/engine/object/IrisColor.java deleted file mode 100644 index 82912c407..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisColor.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.awt.Color; - -@Snippet("color") -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents a color") -@Data -public class IrisColor { - private final transient AtomicCache color = new AtomicCache<>(); - @MaxNumber(7) - @MinNumber(6) - @Desc("Pass in a 6 digit hexadecimal color to fill R G and B values. You can also include the # symbol, but it's not required.") - private String hex = null; - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the red channel. Only define this if you are not defining the hex value.") - private int red = 0; - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the green channel. Only define this if you are not defining the hex value.") - private int green = 0; - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the blue channel. Only define this if you are not defining the hex value.") - private int blue = 0; - - public static Color blend(Color... c) { - if(c == null || c.length <= 0) { - return null; - } - float ratio = 1f / ((float) c.length); - - int a = 0; - int r = 0; - int g = 0; - int b = 0; - - for(Color value : c) { - int rgb = value.getRGB(); - int a1 = (rgb >> 24 & 0xff); - int r1 = ((rgb & 0xff0000) >> 16); - int g1 = ((rgb & 0xff00) >> 8); - int b1 = (rgb & 0xff); - a += (a1 * ratio); - r += (r1 * ratio); - g += (g1 * ratio); - b += (b1 * ratio); - } - - return new Color(a << 24 | r << 16 | g << 8 | b); - } - - public Color getColor() { - return color.aquire(() -> { - if(hex != null) { - String v = (hex.startsWith("#") ? hex : "#" + hex).trim(); - try { - return Color.decode(v); - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - return new Color(red, green, blue); - }); - } - - public org.bukkit.Color getBukkitColor() { - return org.bukkit.Color.fromRGB(getColor().getRGB()); - } - - public int getAsRGB() { - if(hex != null) { - try { - if(hex.startsWith("#")) hex = hex.substring(1); - return Integer.parseInt(hex, 16); - } catch(NumberFormatException e) { - return 0; - } - } - - return red << 16 | green << 8 | blue; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisCommand.java b/src/main/java/com/volmit/iris/engine/object/IrisCommand.java deleted file mode 100644 index b0bbb7698..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisCommand.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; - -@Snippet("command") -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents a set of Iris commands") -@Data -public class IrisCommand { - - @ArrayType(min = 1, type = String.class) - @Desc("List of commands. Iris replaces {x} {y} and {z} with the location of the entity spawn") - private KList commands = new KList<>(); - - @Desc("The delay for running the command. Instant by default") - private long delay = 0; - - @Desc("If this should be repeated (indefinitely, cannot be cancelled). This does not persist with server-restarts, so it only repeats when the chunk is generated.") - private boolean repeat = false; - - @Desc("The delay between repeats, in server ticks (by default 100, so 5 seconds)") - private long repeatDelay = 100; - - @Desc("The block of 24 hour time in which the command should execute.") - private IrisTimeBlock timeBlock = new IrisTimeBlock(); - - @Desc("The weather that is required for the command to execute.") - private IrisWeather weather = IrisWeather.ANY; - - public boolean isValid(World world) { - return timeBlock.isWithin(world) && weather.is(world); - } - - public void run(Location at) { - if(!isValid(at.getWorld())) { - return; - } - - for(String command : commands) { - command = (command.startsWith("/") ? command.replaceFirst("/", "") : command) - .replaceAll("\\Q{x}\\E", String.valueOf(at.getBlockX())) - .replaceAll("\\Q{y}\\E", String.valueOf(at.getBlockY())) - .replaceAll("\\Q{z}\\E", String.valueOf(at.getBlockZ())); - final String finalCommand = command; - if(repeat) { - Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, () -> Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), finalCommand), delay, repeatDelay); - } else { - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), finalCommand), delay); - } - } - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/engine/object/IrisCommandRegistry.java b/src/main/java/com/volmit/iris/engine/object/IrisCommandRegistry.java deleted file mode 100644 index 20a424869..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisCommandRegistry.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -@Snippet("command-registry") -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents a casting location for a command") -@Data -public class IrisCommandRegistry { - @ArrayType(min = 1, type = IrisCommand.class) - @Desc("Run commands, at the exact location of the player") - private KList rawCommands = new KList<>(); - @DependsOn({"rawCommands"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") - private double commandOffsetX = 0; - @DependsOn({"rawCommands"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") - private double commandOffsetY = 0; - @DependsOn({"rawCommands"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") - private double commandOffsetZ = 0; - @DependsOn({"rawCommands"}) - @Desc("Randomize the altX from -altX to altX") - private boolean commandRandomAltX = true; - @DependsOn({"rawCommands"}) - @Desc("Randomize the altY from -altY to altY") - private boolean commandRandomAltY = false; - @DependsOn({"rawCommands"}) - @Desc("Randomize the altZ from -altZ to altZ") - private boolean commandRandomAltZ = true; - @DependsOn({"rawCommands"}) - @Desc("Randomize location for all separate commands (true), or run all on the same location (false)") - private boolean commandAllRandomLocations = true; - - public void run(Player p) { - if(rawCommands.isNotEmpty()) { - Location part = p.getLocation().clone().add( - commandRandomAltX ? RNG.r.d(-commandOffsetX, commandOffsetX) : commandOffsetX, - commandRandomAltY ? RNG.r.d(-commandOffsetY, commandOffsetY) : commandOffsetY, - commandRandomAltZ ? RNG.r.d(-commandOffsetZ, commandOffsetZ) : commandOffsetZ); - for(IrisCommand rawCommand : rawCommands) { - rawCommand.run(part); - if(commandAllRandomLocations) { - part = p.getLocation().clone().add( - commandRandomAltX ? RNG.r.d(-commandOffsetX, commandOffsetX) : commandOffsetX, - commandRandomAltY ? RNG.r.d(-commandOffsetY, commandOffsetY) : commandOffsetY, - commandRandomAltZ ? RNG.r.d(-commandOffsetZ, commandOffsetZ) : commandOffsetZ); - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisCompat.java b/src/main/java/com/volmit/iris/engine/object/IrisCompat.java deleted file mode 100644 index 726d191ae..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisCompat.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.google.gson.Gson; -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.scheduling.J; -import lombok.Data; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; - -import java.io.File; -import java.io.IOException; - -@Data -public class IrisCompat { - private KList blockFilters; - private KList itemFilters; - - public IrisCompat() { - blockFilters = getDefaultBlockCompatabilityFilters(); - itemFilters = getDefaultItemCompatabilityFilters(); - } - - public static IrisCompat configured(File f) { - IrisCompat def = new IrisCompat(); - String defa = new JSONObject(new Gson().toJson(def)).toString(4); - J.attemptAsync(() -> IO.writeAll(new File(f.getParentFile(), "compat.default.json"), defa)); - - - if(!f.exists()) { - J.a(() -> { - try { - IO.writeAll(f, defa); - } catch(IOException e) { - Iris.error("Failed to writeNodeData to compat file"); - Iris.reportError(e); - } - }); - } else { - // If the file doesn't exist, no additional mappings are present outside default - // so we shouldn't try getting them - try { - IrisCompat rea = new Gson().fromJson(IO.readAll(f), IrisCompat.class); - - for(IrisCompatabilityBlockFilter i : rea.getBlockFilters()) { - def.getBlockFilters().add(i); - } - - for(IrisCompatabilityItemFilter i : rea.getItemFilters()) { - def.getItemFilters().add(i); - } - } catch(Throwable e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - - return def; - } - - private static KList getDefaultItemCompatabilityFilters() { - KList filters = new KList<>(); - - // Below 1.16 - filters.add(new IrisCompatabilityItemFilter("NETHERITE_HELMET", "DIAMOND_HELMET")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_CHESTPLATE", "DIAMOND_CHESTPLATE")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_BOOTS", "DIAMOND_BOOTS")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_LEGGINGS", "DIAMOND_LEGGINGS")); - filters.add(new IrisCompatabilityItemFilter("MUSIC_DISC_PIGSTEP", "MUSIC_DISC_FAR")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_SWORD", "DIAMOND_SWORD")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_AXE", "DIAMOND_AXE")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_PICKAXE", "DIAMOND_PICKAXE")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_HOE", "DIAMOND_HOE")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_SHOVEL", "DIAMOND_SHOVEL")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_INGOT", "DIAMOND")); - filters.add(new IrisCompatabilityItemFilter("PIGLIN_BANNER_PATTERN", "PORKCHOP")); - filters.add(new IrisCompatabilityItemFilter("NETHERITE_SCRAP", "GOLD_INGOT")); - filters.add(new IrisCompatabilityItemFilter("WARPED_FUNGUS_ON_A_STICK", "CARROT_ON_A_STICK")); - - // Below 1.15 - filters.add(new IrisCompatabilityItemFilter("HONEY_BOTTLE", "GLASS_BOTTLE")); - filters.add(new IrisCompatabilityItemFilter("HONEYCOMB", "GLASS")); - - // Below 1.14 - filters.add(new IrisCompatabilityItemFilter("SWEET_BERRIES", "APPLE")); - filters.add(new IrisCompatabilityItemFilter("SUSPICIOUS_STEW", "MUSHROOM_STEW")); - filters.add(new IrisCompatabilityItemFilter("BLACK_DYE", "INK_SAC")); - filters.add(new IrisCompatabilityItemFilter("WHITE_DYE", "BONE_MEAL")); - filters.add(new IrisCompatabilityItemFilter("BROWN_DYE", "COCOA_BEANS")); - filters.add(new IrisCompatabilityItemFilter("BLUE_DYE", "LAPIS_LAZULI")); - filters.add(new IrisCompatabilityItemFilter("CROSSBOW", "BOW")); - filters.add(new IrisCompatabilityItemFilter("FLOWER_BANNER_PATTERN", "CORNFLOWER")); - filters.add(new IrisCompatabilityItemFilter("SKULL_BANNER_PATTERN", "BONE")); - filters.add(new IrisCompatabilityItemFilter("GLOBE_BANNER_PATTERN", "WHEAT_SEEDS")); - filters.add(new IrisCompatabilityItemFilter("MOJANG_BANNER_PATTERN", "DIRT")); - filters.add(new IrisCompatabilityItemFilter("CREEPER_BANNER_PATTERN", "CREEPER_HEAD")); - - return filters; - } - - private static KList getDefaultBlockCompatabilityFilters() { - KList filters = new KList<>(); - - // Below 1.16 - filters.add(new IrisCompatabilityBlockFilter("WEEPING_VINES", "NETHER_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("WEEPING_VINES_PLANT", "NETHER_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_WART_BLOCK", "NETHER_WART_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("TWISTING_VINES", "BAMBOO")); - filters.add(new IrisCompatabilityBlockFilter("TWISTING_VINES_PLANT", "BAMBOO")); - filters.add(new IrisCompatabilityBlockFilter("TARGET", "COBBLESTONE")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_SOIL", "SOULSAND")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_TORCH", "TORCH")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_LANTERN", "LANTERN")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_FIRE", "FIRE")); - filters.add(new IrisCompatabilityBlockFilter("SOUL_CAMPFIRE", "CAMPFIRE")); - filters.add(new IrisCompatabilityBlockFilter("SHROOMLIGHT", "GLOWSTONE")); - filters.add(new IrisCompatabilityBlockFilter("RESPAWN_ANCHOR", "OBSIDIAN")); - filters.add(new IrisCompatabilityBlockFilter("NETHER_SPROUTS", "RED_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("NETHER_GOLD_ORE", "GOLD_ORE")); - filters.add(new IrisCompatabilityBlockFilter("LODESTONE", "STONE")); - filters.add(new IrisCompatabilityBlockFilter("STRIPPED_WARPED_HYPHAE", "BROWN_MUSHROOM_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("STRIPPED_CRIMSON_HYPHAE", "RED_MUSHROOM_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_HYPHAE", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_HYPHAE", "RED_MUSHROOM_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("GILDED_BLACKSTONE", "COBBLESTONE")); - filters.add(new IrisCompatabilityBlockFilter("CRYING_OBSIDIAN", "OBSIDIAN")); - filters.add(new IrisCompatabilityBlockFilter("STRIPPED_WARPED_STEM", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("STRIPPED_CRIMSON_STEM", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_STEM", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_STEM", "MUSHROOM_STEM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_ROOTS", "RED_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_ROOTS", "BROWN_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_PLANKS", "OAK_PLANKS")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_PLANKS", "OAK_PLANKS")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_NYLIUM", "MYCELIUM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_NYLIUM", "MYCELIUM")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_FUNGUS", "BROWN_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_FUNGUS", "RED_MUSHROOM")); - filters.add(new IrisCompatabilityBlockFilter("CRACKED_NETHER_BRICKS", "NETHER_BRICKS")); - filters.add(new IrisCompatabilityBlockFilter("CHISELED_NETHER_BRICKS", "NETHER_BRICKS")); - filters.add(new IrisCompatabilityBlockFilter("NETHER_FENCE", "LEGACY_NETHER_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("CHAIN", "IRON_BARS")); - filters.add(new IrisCompatabilityBlockFilter("NETHERITE_BLOCK", "QUARTZ_BLOCK")); - filters.add(new IrisCompatabilityBlockFilter("BLACKSTONE", "COBBLESTONE")); - filters.add(new IrisCompatabilityBlockFilter("BASALT", "STONE")); - filters.add(new IrisCompatabilityBlockFilter("ANCIENT_DEBRIS", "NETHERRACK")); - filters.add(new IrisCompatabilityBlockFilter("NETHERRACK", "LEGACY_NETHERRACK")); - - // Below 1.15 - filters.add(new IrisCompatabilityBlockFilter("HONEY_BLOCK", "OAK_LEAVES")); - filters.add(new IrisCompatabilityBlockFilter("BEEHIVE", "OAK_LEAVES")); - filters.add(new IrisCompatabilityBlockFilter("BEE_NEST", "OAK_LEAVES")); - - // Below 1.14 - filters.add(new IrisCompatabilityBlockFilter("GRANITE_WALL", "COBBLESTONE_WALL")); - filters.add(new IrisCompatabilityBlockFilter("BLUE_ICE", "PACKED_ICE")); - filters.add(new IrisCompatabilityBlockFilter("DIORITE_WALL", "COBBLESTONE_WALL")); - filters.add(new IrisCompatabilityBlockFilter("ANDESITE_WALL", "COBBLESTONE_WALL")); - filters.add(new IrisCompatabilityBlockFilter("SWEET_BERRY_BUSH", "GRASS")); - filters.add(new IrisCompatabilityBlockFilter("STONECUTTER", "CRAFTING_TABLE")); - filters.add(new IrisCompatabilityBlockFilter("SANDSTONE_STAIRS", "LEGACY_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_SANDSTONE_STAIRS", "LEGACY_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("MOSSY_COBBLESTONE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("MOSSY_STONE_BRICK_STAIRS", "STONE_BRICK_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_GRANITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("GRANITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_DIORITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("DIORITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_ANDESITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("ANDESITE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("STONE_STAIRS", "COBBLESTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("END_STONE_BRICK_STAIRS", "LEGACY_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("NETHER_BRICK_STAIRS", "LEGACY_NETHER_BRICK_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("RED_NETHER_BRICK_STAIRS", "NETHER_BRICK_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_QUARTZ_STAIRS", "LEGACY_QUARTZ_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("QUARTZ_STAIRS", "LEGACY_QUARTZ_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("RED_SANDSTONE_STAIRS", "LEGACY_RED_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_RED_SANDSTONE_STAIRS", "LEGACY_RED_SANDSTONE_STAIRS")); - filters.add(new IrisCompatabilityBlockFilter("STONE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("SMOKER", "FURNACE")); - filters.add(new IrisCompatabilityBlockFilter("SMITHING_TABLE", "CRAFTING_TABLE")); - filters.add(new IrisCompatabilityBlockFilter("END_STONE_BRICK_SLAB", "SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("RED_NETHER_BRICK_SLAB", "NETHER_BRICK_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_QUARTZ_SLAB", "QUARTZ_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("CUT_SANDSTONE_SLAB", "SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("CUT_RED_SANDSTONE_SLAB", "RED_SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_RED_SANDSTONE_SLAB", "RED_SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("SMOOTH_SANDSTONE_SLAB", "SANDSTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("MOSSY_COBBLESTONE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("MOSSY_STONE_BRICK_SLAB", "STONE_BRICK_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("STONE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("ANDESITE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("ANDESITE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("DIORITE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("GRANITE_SLAB", "COBBLESTONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_ANDESITE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_DIORITE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("POLISHED_GRANITE_SLAB", "SMOOTH_STONE_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("WARPED_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("SPRUCE_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("SPRUCE_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("OAK_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("OAK_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("JUNGLE_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("JUNGLE_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("DARK_OAK_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("DARK_OAK_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("CRIMSON_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("BIRCH_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("BIRCH_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("ACACIA_WALL_SIGN", "LEGACY_WALL_SIGN")); - filters.add(new IrisCompatabilityBlockFilter("ACACIA_SIGN", "LEGACY_SIGN_POST")); - filters.add(new IrisCompatabilityBlockFilter("SCAFFOLDING", "BIRCH_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("LOOM", "LOOM")); - filters.add(new IrisCompatabilityBlockFilter("LECTERN", "BOOKSHELF")); - filters.add(new IrisCompatabilityBlockFilter("LANTERN", "REDSTONE_LAMP")); - filters.add(new IrisCompatabilityBlockFilter("JIGSAW", "AIR")); - filters.add(new IrisCompatabilityBlockFilter("GRINDSTONE", "COBBLESTONE")); - filters.add(new IrisCompatabilityBlockFilter("FLETCHING_TABLE", "CRAFTING_TABLE")); - filters.add(new IrisCompatabilityBlockFilter("COMPOSTER", "CHEST")); - filters.add(new IrisCompatabilityBlockFilter("CARTOGRAPHY_TABLE", "CRAFTING_TABLE")); - filters.add(new IrisCompatabilityBlockFilter("CAMPFIRE", "DARK_OAK_SLAB")); - filters.add(new IrisCompatabilityBlockFilter("BLAST_FURNACE", "FURNACE")); - filters.add(new IrisCompatabilityBlockFilter("BELL", "REDSTONE_LAMP")); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=south]", "minecraft:hay_bale[axis=z]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=north]", "minecraft:hay_bale[axis=z]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=east]", "minecraft:hay_bale[axis=x]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=west]", "minecraft:hay_bale[axis=x]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=up]", "minecraft:hay_bale[axis=y]", true)); - filters.add(new IrisCompatabilityBlockFilter("minecraft:barrel[facing=down]", "minecraft:hay_bale[axis=y]", true)); - filters.add(new IrisCompatabilityBlockFilter("BAMBOO", "BIRCH_FENCE")); - filters.add(new IrisCompatabilityBlockFilter("BAMBOO_SAPLING", "BIRCH_SAPLING")); - filters.add(new IrisCompatabilityBlockFilter("POTTED_BAMBOO", "POTTED_BIRCH_SAPLING")); - - return filters; - } - - public BlockData getBlock(String n) { - String buf = n; - int err = 16; - - BlockData tx = B.getOrNull(buf); - - if(tx != null) { - return tx; - } - - searching: - while(true) { - if(err-- <= 0) { - return B.get("STONE"); - } - - for(IrisCompatabilityBlockFilter i : blockFilters) { - if(i.getWhen().equalsIgnoreCase(buf)) { - BlockData b = i.getReplace(); - - if(b != null) { - return b; - } - - buf = i.getSupplement(); - continue searching; - } - } - - return B.get("STONE"); - } - } - - public Material getItem(String n) { - String buf = n; - int err = 16; - Material txf = B.getMaterialOrNull(buf); - - if(txf != null) { - return txf; - } - - int nomore = 64; - - searching: - while(true) { - if(nomore < 0) { - return B.getMaterial("STONE"); - } - - nomore--; - if(err-- <= 0) { - break; - } - - for(IrisCompatabilityItemFilter i : itemFilters) { - if(i.getWhen().equalsIgnoreCase(buf)) { - Material b = i.getReplace(); - - if(b != null) { - return b; - } - - buf = i.getSupplement(); - continue searching; - } - } - - break; - } - - buf = n; - BlockData tx = B.getOrNull(buf); - - if(tx != null) { - return tx.getMaterial(); - } - nomore = 64; - - searching: - while(true) { - if(nomore < 0) { - return B.getMaterial("STONE"); - } - - nomore--; - - if(err-- <= 0) { - return B.getMaterial("STONE"); - } - - for(IrisCompatabilityBlockFilter i : blockFilters) { - if(i.getWhen().equalsIgnoreCase(buf)) { - BlockData b = i.getReplace(); - - if(b != null) { - return b.getMaterial(); - } - - buf = i.getSupplement(); - continue searching; - } - } - - return B.getMaterial("STONE"); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisCompatabilityBlockFilter.java b/src/main/java/com/volmit/iris/engine/object/IrisCompatabilityBlockFilter.java deleted file mode 100644 index 227b9b473..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisCompatabilityBlockFilter.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.data.B; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Find and replace object materials for compatability") -@Data -public class IrisCompatabilityBlockFilter { - private final transient AtomicCache findData = new AtomicCache<>(true); - private final transient AtomicCache replaceData = new AtomicCache<>(true); - @Required - @Desc("When iris sees this block, and it's not reconized") - private String when = ""; - @Required - @Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.") - private String supplement = ""; - @Desc("If exact is true, it compares block data for example minecraft:some_log[axis=x]") - private boolean exact = false; - - public IrisCompatabilityBlockFilter(String when, String supplement) { - this(when, supplement, false); - } - - public BlockData getFind() { - return findData.aquire(() -> B.get(when)); - } - - public BlockData getReplace() { - return replaceData.aquire(() -> - { - BlockData b = B.getOrNull(supplement); - - if(b == null) { - return null; - } - - Iris.warn("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'"); - - return b; - }); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisCompatabilityItemFilter.java b/src/main/java/com/volmit/iris/engine/object/IrisCompatabilityItemFilter.java deleted file mode 100644 index 39fcb9ccf..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisCompatabilityItemFilter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.data.B; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Material; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Find and replace object items for compatability") -@Data -public class IrisCompatabilityItemFilter { - private final transient AtomicCache findData = new AtomicCache<>(true); - private final transient AtomicCache replaceData = new AtomicCache<>(true); - @Required - @Desc("When iris sees this block, and it's not reconized") - private String when = ""; - @Required - @Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.") - private String supplement = ""; - - public IrisCompatabilityItemFilter(String when, String supplement) { - this.when = when; - this.supplement = supplement; - } - - public Material getFind() { - return findData.aquire(() -> B.getMaterial(when)); - } - - public Material getReplace() { - return replaceData.aquire(() -> - { - Material b = B.getMaterialOrNull(supplement); - - if(b == null) { - return null; - } - - Iris.verbose("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'"); - - return b; - }); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisDecorationPart.java b/src/main/java/com/volmit/iris/engine/object/IrisDecorationPart.java deleted file mode 100644 index 104d8af76..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisDecorationPart.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Represents a location where decorations should go") -public enum IrisDecorationPart { - @Desc("The default, decorate anywhere") - NONE, - - @Desc("Targets shore lines (typically for sugar cane)") - SHORE_LINE, - - @Desc("Target sea surfaces (typically for lilypads)") - SEA_SURFACE, - - @Desc("Targets the sea floor (entire placement must be bellow sea level)") - SEA_FLOOR, - - @Desc("Decorates on cave & carving ceilings or underside of overhangs") - CEILING, -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisDecorator.java b/src/main/java/com/volmit/iris/engine/object/IrisDecorator.java deleted file mode 100644 index f8e9917aa..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisDecorator.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -@Snippet("decorator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A biome decorator is used for placing flowers, grass, cacti and so on") -@Data -public class IrisDecorator { - private final transient AtomicCache layerGenerator = new AtomicCache<>(); - private final transient AtomicCache varianceGenerator = new AtomicCache<>(); - private final transient AtomicCache heightGenerator = new AtomicCache<>(); - private final transient AtomicCache> blockData = new AtomicCache<>(); - private final transient AtomicCache> blockDataTops = new AtomicCache<>(); - @Desc("The varience dispersion is used when multiple blocks are put in the palette. Scatter scrambles them, Wispy shows streak-looking varience") - private IrisGeneratorStyle variance = NoiseStyle.STATIC.style(); - @Desc("Forcefully place this decorant anywhere it is supposed to go even if it should not go on a specific surface block. For example, you could force tallgrass to place on top of stone by using this.") - private boolean forcePlace = false; - @DependsOn({"scaleStack", "stackMin", "stackMax"}) - @Desc("If stackMax is set to true, use this to limit its max height for large caverns") - private int absoluteMaxStack = 30; - @Desc("Dispersion is used to pick places to spawn. Scatter randomly places them (vanilla) or Wispy for a streak like patch system.") - private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); - @DependsOn({"stackMin", "stackMax"}) - @Desc("If this decorator has a height more than 1 this changes how it picks the height between your maxes. Scatter = random, Wispy = wavy heights") - private IrisGeneratorStyle heightVariance = NoiseStyle.STATIC.style(); - @Desc("Tells iris where this decoration is a part of. I.e. SHORE_LINE or SEA_SURFACE") - private IrisDecorationPart partOf = IrisDecorationPart.NONE; - @DependsOn({"stackMin", "stackMax"}) - @MinNumber(1) - @MaxNumber(2032) // TODO: WARNING HEIGHT - @Desc("The minimum repeat stack height (setting to 3 would stack 3 of on top of each other") - private int stackMin = 1; - @DependsOn({"stackMin", "stackMax"}) - @MinNumber(1) - @MaxNumber(2032) // TODO: WARNING HEIGHT - @Desc("The maximum repeat stack height") - private int stackMax = 1; - @DependsOn({"stackMin", "stackMax"}) - @Desc(""" - Changes stackMin and stackMin from being absolute block heights and instead uses them as a percentage to scale the stack based on the cave height - - Within a cave, setting them stackMin/max to 50 would make the stack 50% of the cave height""") - private boolean scaleStack = false; - @Required - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance for this decorator to decorate at a given X,Y coordinate. This is hit 256 times per chunk (per surface block)") - // TODO: WARNING HEIGHT - private double chance = 0.1; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks to pick from when this decorator needs to place.") - private KList palette = new KList().qadd(new IrisBlockData("grass")); - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks used at the very top of a 'stackMax' of higher than 1. For example, bamboo tops.") - private KList topPalette = new KList<>(); - @DependsOn("topPalette") - @MinNumber(0.01) - @MaxNumber(1.0) - @Desc("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.") - private double topThreshold = 1.0; - - public int getHeight(RNG rng, double x, double z, IrisData data) { - if(stackMin == stackMax) { - return stackMin; - } - - return getHeightGenerator(rng, data) - .fit(stackMin, stackMax, - x / heightVariance.getZoom(), - z / heightVariance.getZoom()) + 1; - } - - public CNG getHeightGenerator(RNG rng, IrisData data) { - return heightGenerator.aquire(() -> - heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), data)); - } - - public CNG getGenerator(RNG rng, IrisData data) { - return layerGenerator.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), data)); - } - - public CNG getVarianceGenerator(RNG rng, IrisData data) { - return varianceGenerator.aquire(() -> - variance.create( - rng.nextParallelRNG(getBlockData(data).size()), data) - .scale(1D / variance.getZoom())); - } - - public KList add(String b) { - palette.add(new IrisBlockData(b)); - return palette; - } - - public BlockData getBlockData(IrisBiome b, RNG rng, double x, double z, IrisData data) { - if(getBlockData(data).isEmpty()) { - Iris.warn("Empty Block Data for " + b.getName()); - return null; - } - - double xx = x / style.getZoom(); - double zz = z / style.getZoom(); - - if(getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { - if(getBlockData(data).size() == 1) { - return getBlockData(data).get(0); - } - - return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x); //X and Z must be switched - } - - return null; - } - - public BlockData getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) { - if(getBlockData(data).isEmpty()) { - Iris.warn("Empty Block Data for " + b.getName()); - return null; - } - - double xx = x; - double yy = y; - double zz = z; - - if(!getVarianceGenerator(rng, data).isStatic()) { - xx = x / style.getZoom(); - yy = y / style.getZoom(); - zz = z / style.getZoom(); - } - - if(getBlockData(data).size() == 1) { - return getBlockData(data).get(0); - } - - return getVarianceGenerator(rng, data).fit(getBlockData(data), z, y, x).clone(); //X and Z must be switched - } - - public BlockData getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) { - if(getBlockDataTops(data).isEmpty()) { - return getBlockData100(b, rng, x, y, z, data); - } - - double xx = x / style.getZoom(); - double zz = z / style.getZoom(); - - if(getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here - if(getBlockData(data).size() == 1) { - return getBlockDataTops(data).get(0); - } - - return getVarianceGenerator(rng, data).fit(getBlockDataTops(data), z, y, x); //X and Z must be switched - } - - return null; - } - - public KList getBlockData(IrisData data) { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for(IrisBlockData i : palette) { - BlockData bx = i.getBlockData(data); - if(bx != null) { - for(int n = 0; n < i.getWeight(); n++) { - blockData.add(bx); - } - } - } - - return blockData; - }); - } - - public KList getBlockDataTops(IrisData data) { - return blockDataTops.aquire(() -> - { - KList blockDataTops = new KList<>(); - for(IrisBlockData i : topPalette) { - BlockData bx = i.getBlockData(data); - if(bx != null) { - for(int n = 0; n < i.getWeight(); n++) { - blockDataTops.add(bx); - } - } - } - - return blockDataTops; - }); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isStacking() { - return getStackMax() > 1; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisDepositGenerator.java b/src/main/java/com/volmit/iris/engine/object/IrisDepositGenerator.java deleted file mode 100644 index 6a7ea1b29..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisDepositGenerator.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; -import org.bukkit.util.BlockVector; - -@Snippet("deposit") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Creates ore & other block deposits underground") -@Data -public class IrisDepositGenerator { - private final transient AtomicCache> objects = new AtomicCache<>(); - private final transient AtomicCache> blockData = new AtomicCache<>(); - @Required - @MinNumber(0) - @MaxNumber(2032) // TODO: WARNING HEIGHT - @Desc("The minimum height this deposit can generate at") - private int minHeight = 7; - @Required - @MinNumber(0) - @MaxNumber(2032) // TODO: WARNING HEIGHT - @Desc("The maximum height this deposit can generate at") - private int maxHeight = 55; - @Required - @MinNumber(1) - @MaxNumber(8192) - @Desc("The minimum amount of deposit blocks per clump") - private int minSize = 3; - @Required - @MinNumber(1) - @MaxNumber(8192) - @Desc("The maximum amount of deposit blocks per clump") - private int maxSize = 64; - @Required - @MinNumber(1) - @MaxNumber(128) - @Desc("The maximum amount of clumps per chunk") - private int maxPerChunk = 3; - @Required - @MinNumber(0) - @MaxNumber(128) - @Desc("The minimum amount of clumps per chunk") - private int minPerChunk = 1; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks to be used in this deposit generator") - private KList palette = new KList<>(); - @MinNumber(1) - @MaxNumber(64) - @Desc("Ore varience is how many different objects clumps iris will create") - private int varience = 3; - - public IrisObject getClump(RNG rng, IrisData rdata) { - KList objects = this.objects.aquire(() -> - { - RNG rngv = rng.nextParallelRNG(3957778); - KList objectsf = new KList<>(); - - for(int i = 0; i < varience; i++) { - objectsf.add(generateClumpObject(rngv.nextParallelRNG(2349 * i + 3598), rdata)); - } - - return objectsf; - }); - return objects.get(rng.i(0, objects.size() - 1)); - } - - public int getMaxDimension() { - return Math.min(11, (int) Math.round(Math.pow(maxSize, 1D / 3D))); - } - - private IrisObject generateClumpObject(RNG rngv, IrisData rdata) { - int s = rngv.i(minSize, maxSize); - int dim = Math.min(11, (int) Math.round(Math.pow(maxSize, 1D / 3D))); - int w = dim / 2; - IrisObject o = new IrisObject(dim, dim, dim); - - if(s == 1) { - o.getBlocks().put(o.getCenter(), nextBlock(rngv, rdata)); - } else { - while(s > 0) { - s--; - BlockVector ang = new BlockVector(rngv.i(-w, w), rngv.i(-w, w), rngv.i(-w, w)); - BlockVector pos = o.getCenter().clone().add(ang).toBlockVector(); - o.getBlocks().put(pos, nextBlock(rngv, rdata)); - } - } - - return o; - } - - private BlockData nextBlock(RNG rngv, IrisData rdata) { - return getBlockData(rdata).get(rngv.i(0, getBlockData(rdata).size() - 1)); - } - - public KList getBlockData(IrisData rdata) { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - - for(IrisBlockData ix : palette) { - BlockData bx = ix.getBlockData(rdata); - - if(bx != null) { - blockData.add(bx); - } - } - - return blockData; - }); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisDimension.java b/src/main/java/com/volmit/iris/engine/object/IrisDimension.java deleted file mode 100644 index c41a1bf17..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisDimension.java +++ /dev/null @@ -1,487 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.data.DataProvider; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Material; -import org.bukkit.World.Environment; -import org.bukkit.block.data.BlockData; - -import java.io.File; -import java.io.IOException; - -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Represents a dimension") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisDimension extends IrisRegistrant { - public static final BlockData STONE = Material.STONE.createBlockData(); - public static final BlockData WATER = Material.WATER.createBlockData(); - private final transient AtomicCache parallaxSize = new AtomicCache<>(); - private final transient AtomicCache rockLayerGenerator = new AtomicCache<>(); - private final transient AtomicCache fluidLayerGenerator = new AtomicCache<>(); - private final transient AtomicCache coordFracture = new AtomicCache<>(); - private final transient AtomicCache sinr = new AtomicCache<>(); - private final transient AtomicCache cosr = new AtomicCache<>(); - private final transient AtomicCache rad = new AtomicCache<>(); - private final transient AtomicCache featuresUsed = new AtomicCache<>(); - private final transient AtomicCache> strongholdsCache = new AtomicCache<>(); - @MinNumber(2) - @Required - @Desc("The human readable name of this dimension") - private String name = "A Dimension"; - @MinNumber(1) - @MaxNumber(2032) - @Desc("Maximum height at which players can be teleported to through gameplay.") - private int logicalHeight = 256; - - @RegistryListResource(IrisJigsawStructure.class) - @Desc("If defined, Iris will place the given jigsaw structure where minecraft should place the overworld stronghold.") - private String stronghold; - @Desc("If set to true, Iris will remove chunks to allow visualizing cross sections of chunks easily") - private boolean debugChunkCrossSections = false; - @Desc("Vertically split up the biome palettes with 3 air blocks in between to visualize them") - private boolean explodeBiomePalettes = false; - @Desc("Studio Mode for testing different parts of the world") - private StudioMode studioMode = StudioMode.NORMAL; - @MinNumber(1) - @MaxNumber(16) - @Desc("Customize the palette height explosion") - private int explodeBiomePaletteSize = 3; - @MinNumber(2) - @MaxNumber(16) - @Desc("Every X/Z % debugCrossSectionsMod == 0 cuts the chunk") - private int debugCrossSectionsMod = 3; - @Desc("The average distance between strongholds") - private int strongholdJumpDistance = 1280; - @Desc("Define the maximum strongholds to place") - private int maxStrongholds = 14; - @Desc("Improves the biome grid variation by shuffling the cell grid more depending on the seed. This makes biomes across multiple seeds look far different than before.") - private boolean aggressiveBiomeReshuffle = false; - @Desc("Tree growth override settings") - private IrisTreeSettings treeSettings = new IrisTreeSettings(); - @Desc("Upon joining this world, Iris will send a resource pack request to the client. If they have previously selected yes, it will auto-switch depending on which dimension they go to.") - private String resourcePack = ""; - @Desc("Spawn Entities in this dimension over time. Iris will continually replenish these mobs just like vanilla does.") - @ArrayType(min = 1, type = String.class) - @RegistryListResource(IrisSpawner.class) - private KList entitySpawners = new KList<>(); - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); - @MinNumber(0) - @Desc("The version of this dimension. Changing this will stop users from accidentally upgrading (and breaking their worlds).") - private int version = 1; - @ArrayType(min = 1, type = IrisBlockDrops.class) - @Desc("Define custom block drops for this dimension") - private KList blockDrops = new KList<>(); - @Desc("Should bedrock be generated or not.") - private boolean bedrock = true; - @MinNumber(0) - @MaxNumber(1) - @Desc("The land chance. Up to 1.0 for total land or 0.0 for total sea") - private double landChance = 0.625; - @Desc("The placement style of regions") - private IrisGeneratorStyle regionStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The placement style of land/sea") - private IrisGeneratorStyle continentalStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The placement style of biomes") - private IrisGeneratorStyle landBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The placement style of biomes") - private IrisGeneratorStyle shoreBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The placement style of biomes") - private IrisGeneratorStyle seaBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("The placement style of biomes") - private IrisGeneratorStyle caveBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - @Desc("Instead of filling objects with air, fills them with cobweb so you can see them") - private boolean debugSmartBore = false; - @Desc("Generate decorations or not") - private boolean decorate = true; - @Desc("Use post processing or not") - private boolean postProcessing = true; - @Desc("Add slabs in post processing") - private boolean postProcessingSlabs = true; - @Desc("Add painted walls in post processing") - private boolean postProcessingWalls = true; - @Desc("Carving configuration for the dimension") - private IrisCarving carving = new IrisCarving(); - @Desc("Configuration of fluid bodies such as rivers & lakes") - private IrisFluidBodies fluidBodies = new IrisFluidBodies(); - @Desc("The world environment") - private Environment environment = Environment.NORMAL; - @RegistryListResource(IrisRegion.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("Define all of the regions to include in this dimension. Dimensions -> Regions -> Biomes -> Objects etc") - private KList regions = new KList<>(); - @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) - @Desc("Jigsaw structures") - private KList jigsawStructures = new KList<>(); - @Required - @MinNumber(0) - @MaxNumber(1024) - @Desc("The fluid height for this dimension") - private int fluidHeight = 63; - @Desc("Define the min and max Y bounds of this dimension. Please keep in mind that Iris internally generates from 0 to (max - min). \n\nFor example at -64 to 320, Iris is internally generating to 0 to 384, then on outputting chunks, it shifts it down by the min height (64 blocks). The default is -64 to 320. \n\nThe fluid height is placed at (fluid height + min height). So a fluid height of 63 would actually show up in the world at 1.") - private IrisRange dimensionHeight = new IrisRange(-64, 320); - @RegistryListResource(IrisBiome.class) - @Desc("Keep this either undefined or empty. Setting any biome name into this will force iris to only generate the specified biome. Great for testing.") - private String focus = ""; - @RegistryListResource(IrisRegion.class) - @Desc("Keep this either undefined or empty. Setting any region name into this will force iris to only generate the specified region. Great for testing.") - private String focusRegion = ""; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("Zoom in or out the biome size. Higher = bigger biomes") - private double biomeZoom = 5D; - @MinNumber(0) - @MaxNumber(360) - @Desc("You can rotate the input coordinates by an angle. This can make terrain appear more natural (less sharp corners and lines). This literally rotates the entire dimension by an angle. Hint: Try 12 degrees or something not on a 90 or 45 degree angle.") - private double dimensionAngleDeg = 0; - @Required - @Desc("Define the mode of this dimension (required!)") - private IrisDimensionMode mode = new IrisDimensionMode(); - @MinNumber(0) - @MaxNumber(8192) - @Desc("Coordinate fracturing applies noise to the input coordinates. This creates the 'iris swirls' and wavy features. The distance pushes these waves further into places they shouldnt be. This is a block value multiplier.") - private double coordFractureDistance = 20; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("Coordinate fracturing zoom. Higher = less frequent warping, Lower = more frequent and rapid warping / swirls.") - private double coordFractureZoom = 8; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("This zooms in the land space") - private double landZoom = 1; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("This zooms oceanic biomes") - private double seaZoom = 1; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("Zoom in continents") - private double continentZoom = 1; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("Change the size of regions") - private double regionZoom = 1; - @Desc("Disable this to stop placing objects, entities, features & updates") - private boolean useMantle = true; - @Desc("Prevent Leaf decay as if placed in creative mode") - private boolean preventLeafDecay = false; - @ArrayType(min = 1, type = IrisDepositGenerator.class) - @Desc("Define global deposit generators") - private KList deposits = new KList<>(); - @ArrayType(min = 1, type = IrisShapedGeneratorStyle.class) - @Desc("Overlay additional noise on top of the interoplated terrain.") - private KList overlayNoise = new KList<>(); - @Desc("If true, the spawner system has infinite energy. This is NOT recommended because it would allow for mobs to keep spawning over and over without a rate limit") - private boolean infiniteEnergy = false; - @MinNumber(0) - @MaxNumber(10000) - @Desc("This is the maximum energy you can have in a dimension") - private double maximumEnergy = 1000; - @MinNumber(0.0001) - @MaxNumber(512) - @Desc("The rock zoom mostly for zooming in on a wispy palette") - private double rockZoom = 5; - @Desc("The palette of blocks for 'stone'") - private IrisMaterialPalette rockPalette = new IrisMaterialPalette().qclear().qadd("stone"); - @Desc("The palette of blocks for 'water'") - private IrisMaterialPalette fluidPalette = new IrisMaterialPalette().qclear().qadd("water"); - @Desc("Remove cartographers so they do not crash the server (Iris worlds only)") - private boolean removeCartographersDueToCrash = true; - @Desc("Notify players of cancelled cartographer villager in this radius in blocks (set to -1 to disable, -2 for everyone)") - private int notifyPlayersOfCartographerCancelledRadius = 30; - @Desc("Collection of ores to be generated") - @ArrayType(type = IrisOreGenerator.class, min = 1) - private KList ores = new KList<>(); - @MinNumber(0) - @MaxNumber(318) - @Desc("The Subterrain Fluid Layer Height") - private int caveLavaHeight = 8; - - public int getMaxHeight() { - return (int) getDimensionHeight().getMax(); - } - - public int getMinHeight() { - return (int) getDimensionHeight().getMin(); - } - - public BlockData generateOres(int x, int y, int z, RNG rng, IrisData data) { - if(ores.isEmpty()) { - return null; - } - BlockData b = null; - for(IrisOreGenerator i : ores) { - - b = i.generate(x, y, z, rng, data); - if(b != null) { - return b; - } - } - return null; - } - - public KList getStrongholds(long seed) { - return strongholdsCache.aquire(() -> { - KList pos = new KList<>(); - int jump = strongholdJumpDistance; - RNG rng = new RNG((seed * 223) + 12945); - - for(int i = 0; i < maxStrongholds + 1; i++) { - int m = i + 1; - pos.add(new Position2( - (int) ((rng.i(jump * i) + (jump * i)) * (rng.b() ? -1D : 1D)), - (int) ((rng.i(jump * i) + (jump * i)) * (rng.b() ? -1D : 1D)) - )); - } - - pos.remove(0); - - return pos; - }); - } - - public int getFluidHeight() { - return fluidHeight - (int)dimensionHeight.getMin(); - } - - public CNG getCoordFracture(RNG rng, int signature) { - return coordFracture.aquire(() -> - { - CNG coordFracture = CNG.signature(rng.nextParallelRNG(signature)); - coordFracture.scale(0.012 / coordFractureZoom); - return coordFracture; - }); - } - - public double getDimensionAngle() { - return rad.aquire(() -> Math.toRadians(dimensionAngleDeg)); - } - - public Environment getEnvironment() { - return environment; - } - - public boolean hasFocusRegion() { - return !focusRegion.equals(""); - } - - public String getFocusRegion() { - return focusRegion; - } - - public double sinRotate() { - return sinr.aquire(() -> Math.sin(getDimensionAngle())); - } - - public double cosRotate() { - return cosr.aquire(() -> Math.cos(getDimensionAngle())); - } - - public KList getAllRegions(DataProvider g) { - KList r = new KList<>(); - - for(String i : getRegions()) { - r.add(g.getData().getRegionLoader().load(i)); - } - - return r; - } - - public KList getAllAnyRegions() { - KList r = new KList<>(); - - for(String i : getRegions()) { - r.add(IrisData.loadAnyRegion(i)); - } - - return r; - } - - public KList getAllBiomes(DataProvider g) { - return g.getData().getBiomeLoader().loadAll(g.getData().getBiomeLoader().getPossibleKeys()); - } - - public KList getAllAnyBiomes() { - KList r = new KList<>(); - - for(IrisRegion i : getAllAnyRegions()) { - if(i == null) { - continue; - } - - r.addAll(i.getAllAnyBiomes()); - } - - return r; - } - - public IrisGeneratorStyle getBiomeStyle(InferredType type) { - switch(type) { - case CAVE: - return caveBiomeStyle; - case LAND: - return landBiomeStyle; - case SEA: - return seaBiomeStyle; - case SHORE: - return shoreBiomeStyle; - default: - break; - } - - return landBiomeStyle; - } - - public boolean installDataPack(DataProvider data, File datapacks) { - boolean write = false; - boolean changed = false; - - IO.delete(new File(datapacks, "iris/data/" + getLoadKey().toLowerCase())); - - for(IrisBiome i : getAllBiomes(data)) { - if(i.isCustom()) { - write = true; - - for(IrisBiomeCustom j : i.getCustomDerivitives()) { - File output = new File(datapacks, "iris/data/" + getLoadKey().toLowerCase() + "/worldgen/biome/" + j.getId() + ".json"); - - if(!output.exists()) { - changed = true; - } - - Iris.verbose(" Installing Data Pack Biome: " + output.getPath()); - output.getParentFile().mkdirs(); - try { - IO.writeAll(output, j.generateJson()); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - } - } - - if(!dimensionHeight.equals(new IrisRange(-64, 320)) && this.name.equalsIgnoreCase("overworld")) { - Iris.verbose(" Installing Data Pack Dimension Type: \"minecraft:overworld\""); - changed = writeDimensionType(changed, datapacks); - } - - if(write) { - File mcm = new File(datapacks, "iris/pack.mcmeta"); - try { - IO.writeAll(mcm, """ - { - "pack": { - "description": "Iris Data Pack. This pack contains all installed Iris Packs' resources.", - "pack_format": 10 - } - } - """); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - Iris.verbose(" Installing Data Pack MCMeta: " + mcm.getPath()); - } - - return changed; - } - - @Override - public String getFolderName() { - return "dimensions"; - } - - @Override - public String getTypeName() { - return "Dimension"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } - - public boolean writeDimensionType(boolean changed, File datapacks) { - File dimType = new File(datapacks, "iris/data/minecraft/dimension_type/overworld.json"); - if(!dimType.exists()) - changed = true; - dimType.getParentFile().mkdirs(); - try { - IO.writeAll(dimType, generateDatapackJson()); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - return changed; - } - - private String generateDatapackJson() { - JSONObject obj = new JSONObject(DP_OVERWORLD_DEFAULT); - obj.put("min_y", dimensionHeight.getMin()); - obj.put("height", dimensionHeight.getMax() - dimensionHeight.getMin()); - obj.put("logical_height", logicalHeight); - return obj.toString(4); - } - - private static final String DP_OVERWORLD_DEFAULT = """ - { - "ultrawarm": false, - "natural": true, - "coordinate_scale": 1.0, - "has_skylight": true, - "has_ceiling": false, - "ambient_light": 0, - "piglin_safe": false, - "bed_works": true, - "respawn_anchor_works": false, - "has_raids": true, - "monster_spawn_block_light_limit": 7, - "monster_spawn_light_level": 1, - "infiniburn": "#minecraft:infiniburn_overworld", - "effects": "minecraft:overworld" - }"""; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisDimensionMode.java b/src/main/java/com/volmit/iris/engine/object/IrisDimensionMode.java deleted file mode 100644 index ccf3c49b1..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisDimensionMode.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("dimension-mode") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a dimensional mode") -@Data -public class IrisDimensionMode { - @Desc("The dimension type") - private IrisDimensionModeType type = IrisDimensionModeType.OVERWORLD; - -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisDimensionModeType.java b/src/main/java/com/volmit/iris/engine/object/IrisDimensionModeType.java deleted file mode 100644 index d971bcbe6..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisDimensionModeType.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineMode; -import com.volmit.iris.engine.mode.ModeEnclosure; -import com.volmit.iris.engine.mode.ModeIslands; -import com.volmit.iris.engine.mode.ModeOverworld; -import com.volmit.iris.engine.mode.ModeSuperFlat; -import com.volmit.iris.engine.object.annotations.Desc; - -import java.util.function.Function; - -@Desc("The type of dimension this is") -public enum IrisDimensionModeType { - @Desc("Typical dimensions. Has a fluid height, and all features of a biome based world") - OVERWORLD(ModeOverworld::new), - - @Desc("Ultra fast, but very limited in features. Only supports terrain & biomes. No decorations, mobs, objects, or anything of the sort!") - SUPERFLAT(ModeSuperFlat::new), - - @Desc("Like the nether, a ceiling & floor carved out") - ENCLOSURE(ModeEnclosure::new), - - @Desc("Floating islands of terrain") - ISLANDS(ModeIslands::new), - ; - private final Function factory; - - IrisDimensionModeType(Function factory) { - this.factory = factory; - } - - public EngineMode create(Engine e) { - return factory.apply(e); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisDirection.java b/src/main/java/com/volmit/iris/engine/object/IrisDirection.java deleted file mode 100644 index d0f56086f..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisDirection.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.util.collection.GBiset; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.Cuboid.CuboidDirection; -import com.volmit.iris.util.math.DOP; -import com.volmit.iris.util.math.VectorMath; -import org.bukkit.Axis; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.type.Jigsaw; -import org.bukkit.util.Vector; - -import java.util.Map; - -/** - * Directions - * - * @author cyberpwn - */ -@Desc("A direction object") -public enum IrisDirection { - @Desc("0, 1, 0") - UP_POSITIVE_Y(0, 1, 0, CuboidDirection.Up), - @Desc("0, -1, 0") - DOWN_NEGATIVE_Y(0, -1, 0, CuboidDirection.Down), - @Desc("0, 0, -1") - NORTH_NEGATIVE_Z(0, 0, -1, CuboidDirection.North), - @Desc("0, 0, 1") - SOUTH_POSITIVE_Z(0, 0, 1, CuboidDirection.South), - @Desc("1, 0, 0") - EAST_POSITIVE_X(1, 0, 0, CuboidDirection.East), - @Desc("-1, 0, 0") - WEST_NEGATIVE_X(-1, 0, 0, CuboidDirection.West); - - private static KMap, DOP> permute = null; - - private final int x; - private final int y; - private final int z; - private final CuboidDirection f; - - IrisDirection(int x, int y, int z, CuboidDirection f) { - this.x = x; - this.y = y; - this.z = z; - this.f = f; - } - - public static IrisDirection getDirection(BlockFace f) { - return switch(f) { - case DOWN -> DOWN_NEGATIVE_Y; - case EAST, EAST_NORTH_EAST, EAST_SOUTH_EAST -> EAST_POSITIVE_X; - case NORTH, NORTH_NORTH_WEST, NORTH_EAST, NORTH_NORTH_EAST, NORTH_WEST -> NORTH_NEGATIVE_Z; - case SELF, UP -> UP_POSITIVE_Y; - case SOUTH, SOUTH_EAST, SOUTH_SOUTH_EAST, SOUTH_SOUTH_WEST, SOUTH_WEST -> SOUTH_POSITIVE_Z; - case WEST, WEST_NORTH_WEST, WEST_SOUTH_WEST -> WEST_NEGATIVE_X; - }; - - } - - public static IrisDirection fromJigsawBlock(String direction) { - for(IrisDirection i : IrisDirection.values()) { - if(i.name().toLowerCase().split("\\Q_\\E")[0] - .equals(direction.split("\\Q_\\E")[0])) { - return i; - } - } - - return null; - } - - public static IrisDirection getDirection(Jigsaw.Orientation orientation) { - return switch(orientation) { - case DOWN_EAST, UP_EAST, EAST_UP -> EAST_POSITIVE_X; - case DOWN_NORTH, UP_NORTH, NORTH_UP -> NORTH_NEGATIVE_Z; - case DOWN_SOUTH, UP_SOUTH, SOUTH_UP -> SOUTH_POSITIVE_Z; - case DOWN_WEST, UP_WEST, WEST_UP -> WEST_NEGATIVE_X; - }; - - } - - public static IrisDirection closest(Vector v) { - double m = Double.MAX_VALUE; - IrisDirection s = null; - - for(IrisDirection i : values()) { - Vector x = i.toVector(); - double g = x.distance(v); - - if(g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static IrisDirection closest(Vector v, IrisDirection... d) { - double m = Double.MAX_VALUE; - IrisDirection s = null; - - for(IrisDirection i : d) { - Vector x = i.toVector(); - double g = x.distance(v); - - if(g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static IrisDirection closest(Vector v, KList d) { - double m = Double.MAX_VALUE; - IrisDirection s = null; - - for(IrisDirection i : d) { - Vector x = i.toVector(); - double g = x.distance(v); - - if(g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static KList news() { - return new KList().add(NORTH_NEGATIVE_Z, EAST_POSITIVE_X, WEST_NEGATIVE_X, SOUTH_POSITIVE_Z); - } - - public static IrisDirection getDirection(Vector v) { - Vector k = VectorMath.triNormalize(v.clone().normalize()); - - for(IrisDirection i : udnews()) { - if(i.x == k.getBlockX() && i.y == k.getBlockY() && i.z == k.getBlockZ()) { - return i; - } - } - - return IrisDirection.NORTH_NEGATIVE_Z; - } - - public static KList udnews() { - return new KList().add(UP_POSITIVE_Y, DOWN_NEGATIVE_Y, NORTH_NEGATIVE_Z, EAST_POSITIVE_X, WEST_NEGATIVE_X, SOUTH_POSITIVE_Z); - } - - /** - * Get the directional value from the given byte from common directional blocks - * (MUST BE BETWEEN 0 and 5 INCLUSIVE) - * - * @param b - * the byte - * @return the direction or null if the byte is outside of the inclusive range - * 0-5 - */ - public static IrisDirection fromByte(byte b) { - if(b > 5 || b < 0) { - return null; - } - - if(b == 0) { - return DOWN_NEGATIVE_Y; - } else if(b == 1) { - return UP_POSITIVE_Y; - } else if(b == 2) { - return NORTH_NEGATIVE_Z; - } else if(b == 3) { - return SOUTH_POSITIVE_Z; - } else if(b == 4) { - return WEST_NEGATIVE_X; - } else { - return EAST_POSITIVE_X; - } - } - - public static void calculatePermutations() { - if(permute != null) { - return; - } - - permute = new KMap<>(); - - for(IrisDirection i : udnews()) { - for(IrisDirection j : udnews()) { - GBiset b = new GBiset<>(i, j); - - if(i.equals(j)) { - permute.put(b, new DOP("DIRECT") { - @Override - public Vector op(Vector v) { - return v; - } - }); - } else if(i.reverse().equals(j)) { - if(i.isVertical()) { - permute.put(b, new DOP("R180CCZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCZ(VectorMath.rotate90CCZ(v)); - } - }); - } else { - permute.put(b, new DOP("R180CCY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCY(VectorMath.rotate90CCY(v)); - } - }); - } - } else if(getDirection(VectorMath.rotate90CX(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CX") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CX(v); - } - }); - } else if(getDirection(VectorMath.rotate90CCX(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCX") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCX(v); - } - }); - } else if(getDirection(VectorMath.rotate90CY(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CY(v); - } - }); - } else if(getDirection(VectorMath.rotate90CCY(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCY(v); - } - }); - } else if(getDirection(VectorMath.rotate90CZ(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CZ(v); - } - }); - } else if(getDirection(VectorMath.rotate90CCZ(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCZ(v); - } - }); - } else { - permute.put(b, new DOP("FAIL") { - @Override - public Vector op(Vector v) { - return v; - } - }); - } - } - } - } - - @Override - public String toString() { - return switch(this) { - case DOWN_NEGATIVE_Y -> "Down"; - case EAST_POSITIVE_X -> "East"; - case NORTH_NEGATIVE_Z -> "North"; - case SOUTH_POSITIVE_Z -> "South"; - case UP_POSITIVE_Y -> "Up"; - case WEST_NEGATIVE_X -> "West"; - }; - - } - - public boolean isVertical() { - return equals(DOWN_NEGATIVE_Y) || equals(UP_POSITIVE_Y); - } - - public Vector toVector() { - return new Vector(x, y, z); - } - - public boolean isCrooked(IrisDirection to) { - if(equals(to.reverse())) { - return false; - } - - return !equals(to); - } - - public Vector angle(Vector initial, IrisDirection d) { - calculatePermutations(); - - for(Map.Entry, DOP> entry : permute.entrySet()) { - GBiset i = entry.getKey(); - if(i.getA().equals(this) && i.getB().equals(d)) { - return entry.getValue().op(initial); - } - } - - return initial; - } - - public IrisDirection reverse() { - switch(this) { - case DOWN_NEGATIVE_Y: - return UP_POSITIVE_Y; - case EAST_POSITIVE_X: - return WEST_NEGATIVE_X; - case NORTH_NEGATIVE_Z: - return SOUTH_POSITIVE_Z; - case SOUTH_POSITIVE_Z: - return NORTH_NEGATIVE_Z; - case UP_POSITIVE_Y: - return DOWN_NEGATIVE_Y; - case WEST_NEGATIVE_X: - return EAST_POSITIVE_X; - default: - break; - } - - return EAST_POSITIVE_X; - } - - public int x() { - return x; - } - - public int y() { - return y; - } - - public int z() { - return z; - } - - public CuboidDirection f() { - return f; - } - - /** - * Get the byte value represented in some directional blocks - * - * @return the byte value - */ - public byte byteValue() { - switch(this) { - case DOWN_NEGATIVE_Y: - return 0; - case EAST_POSITIVE_X: - return 5; - case NORTH_NEGATIVE_Z: - return 2; - case SOUTH_POSITIVE_Z: - return 3; - case UP_POSITIVE_Y: - return 1; - case WEST_NEGATIVE_X: - return 4; - default: - break; - } - - return -1; - } - - public BlockFace getFace() { - return switch(this) { - case DOWN_NEGATIVE_Y -> BlockFace.DOWN; - case EAST_POSITIVE_X -> BlockFace.EAST; - case NORTH_NEGATIVE_Z -> BlockFace.NORTH; - case SOUTH_POSITIVE_Z -> BlockFace.SOUTH; - case UP_POSITIVE_Y -> BlockFace.UP; - case WEST_NEGATIVE_X -> BlockFace.WEST; - }; - - } - - public Axis getAxis() { - return switch(this) { - case DOWN_NEGATIVE_Y, UP_POSITIVE_Y -> Axis.Y; - case EAST_POSITIVE_X, WEST_NEGATIVE_X -> Axis.X; - case NORTH_NEGATIVE_Z, SOUTH_POSITIVE_Z -> Axis.Z; - }; - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisDuration.java b/src/main/java/com/volmit/iris/engine/object/IrisDuration.java deleted file mode 100644 index f8f6659ea..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisDuration.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.format.Form; -import lombok.Data; - -import java.util.concurrent.TimeUnit; - -@Snippet("duration") -@Data -@Desc("Represents a combined duration. Fill each property to add time into a single duration") -public class IrisDuration { - @Desc("Milliseconds (1000ms = 1 second)") - private int milliseconds = 0; - - @Desc("Minecraft Ticks (20 minecraft ticks = 1 second") - private int minecraftTicks = 0; - - @Desc("Seconds (60 seconds = 1 minute)") - private int seconds = 0; - - @Desc("Minutes (60 minutes = 1 hour)") - private int minutes = 0; - - @Desc("Minecraft Hours (about 50 real seconds)") - private int minecraftHours = 0; - - @Desc("Hours (24 hours = 1 day)") - private int hours = 0; - - @Desc("Minecraft Days (1 minecraft day = 20 real minutes)") - private int minecraftDays = 0; - - @Desc("Minecraft Weeks (1 minecraft week = 2 real hours and 18 real minutes)") - private int minecraftWeeks = 0; - - @Desc("Minecraft Lunar Cycles (1 minecraft lunar cycle = 2 real hours and 36 real minutes)") - private int minecraftLunarCycles = 0; - - @Desc("REAL (not minecraft) Days") - private int days = 0; - - public String toString() { - return Form.duration((double) toMilliseconds(), 2); - } - - public long toMilliseconds() { - return getMilliseconds() - + TimeUnit.SECONDS.toMillis(getSeconds()) - + TimeUnit.MINUTES.toMillis(getMinutes()) - + TimeUnit.HOURS.toMillis(getHours()) - + TimeUnit.DAYS.toMillis(getDays()) - + (getMinecraftTicks() * 50L) - + (getMinecraftHours() * 50000L) - + (getMinecraftWeeks() * 50000L) - + (getMinecraftDays() * 24000L) - + (getMinecraftWeeks() * 168000L) - + (getMinecraftLunarCycles() * 192000L); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEffect.java b/src/main/java/com/volmit/iris/engine/object/IrisEffect.java deleted file mode 100644 index 6a426b8fe..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEffect.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.Sound; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.util.Vector; - -@Snippet("effect") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("An iris effect") -@Data -public class IrisEffect { - private final transient AtomicCache pt = new AtomicCache<>(); - private final transient AtomicCache latch = new AtomicCache<>(); - @Desc("The potion effect to apply in this area") - private String potionEffect = ""; - @Desc("The particle effect to apply in the area") - private Particle particleEffect = null; - @DependsOn({"particleEffect"}) - @MinNumber(-32) - @MaxNumber(32) - @Desc("Randomly offset from the surface to this surface+value") - private int particleOffset = 0; - @DependsOn({"particleEffect"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") - private double particleAltX = 0; - @DependsOn({"particleEffect"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") - private double particleAltY = 0; - @DependsOn({"particleEffect"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") - private double particleAltZ = 0; - @DependsOn({"particleEffect"}) - @Desc("Randomize the altX by -altX to altX") - private boolean randomAltX = true; - @DependsOn({"particleEffect"}) - @Desc("Randomize the altY by -altY to altY") - private boolean randomAltY = false; - @DependsOn({"particleEffect"}) - @Desc("Randomize the altZ by -altZ to altZ") - private boolean randomAltZ = true; - @Desc("The sound to play") - private Sound sound = null; - @DependsOn({"sound"}) - @MinNumber(0) - @MaxNumber(512) - @Desc("The max distance from the player the sound will play") - private int soundDistance = 12; - @DependsOn({"sound", "maxPitch"}) - @MinNumber(0.01) - @MaxNumber(1.99) - @Desc("The minimum sound pitch") - private double minPitch = 0.5D; - @DependsOn({"sound", "minVolume"}) - @MinNumber(0.01) - @MaxNumber(1.99) - @Desc("The max sound pitch") - private double maxPitch = 1.5D; - @DependsOn({"sound"}) - @MinNumber(0.001) - @MaxNumber(512) - @Desc("The sound volume.") - private double volume = 1.5D; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(512) - @Desc("The particle count. Try setting to zero for using the alt xyz to a motion value instead of an offset") - private int particleCount = 0; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(64) - @Desc("How far away from the player particles can play") - private int particleDistance = 20; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(128) - @Desc("How wide the particles can play (player's view left and right) RADIUS") - private int particleDistanceWidth = 24; - @DependsOn({"particleEffect"}) - @Desc("An extra value for some particles... Which bukkit doesn't even document.") - private double extra = 0; - @DependsOn({"potionEffect"}) - @MinNumber(-1) - @MaxNumber(1024) - @Desc("The Potion Strength or -1 to disable") - private int potionStrength = -1; - @DependsOn({"potionEffect", "potionTicksMin"}) - @MinNumber(1) - @Desc("The max time the potion will last for") - private int potionTicksMax = 155; - @DependsOn({"potionEffect", "potionTicksMax"}) - @MinNumber(1) - @Desc("The min time the potion will last for") - private int potionTicksMin = 75; - @Required - @MinNumber(0) - @Desc("The effect interval in milliseconds") - private int interval = 150; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(16) - @Desc("The effect distance start away") - private int particleAway = 5; - @Required - @MinNumber(1) - @Desc("The chance is 1 in CHANCE per interval") - private int chance = 50; - @ArrayType(min = 1, type = IrisCommandRegistry.class) - @Desc("Run commands, with configurable location parameters") - private IrisCommandRegistry commandRegistry = null; - - - public boolean canTick() { - return latch.aquire(() -> new ChronoLatch(interval)).flip(); - } - - public PotionEffectType getRealType() { - return pt.aquire(() -> - { - PotionEffectType t = PotionEffectType.LUCK; - - if(getPotionEffect().isEmpty()) { - return t; - } - - try { - for(PotionEffectType i : PotionEffectType.values()) { - if(i.getName().toUpperCase().replaceAll("\\Q \\E", "_").equals(getPotionEffect())) { - t = i; - - return t; - } - } - } catch(Throwable e) { - Iris.reportError(e); - - } - - Iris.warn("Unknown Potion Effect Type: " + getPotionEffect()); - - return t; - }); - } - - public void apply(Player p, Engine g) { - if(!canTick()) { - return; - } - - if(RNG.r.nextInt(chance) != 0) { - return; - } - - if(sound != null) { - Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); - - J.s(() -> p.playSound(part, getSound(), (float) volume, (float) RNG.r.d(minPitch, maxPitch))); - } - - if(particleEffect != null) { - Location part = p.getLocation().clone().add(p.getLocation().getDirection().clone().multiply(RNG.r.i(particleDistance) + particleAway)).clone().add(p.getLocation().getDirection().clone().rotateAroundY(Math.toRadians(90)).multiply(RNG.r.d(-particleDistanceWidth, particleDistanceWidth))); - - part.setY(Math.round(g.getHeight(part.getBlockX(), part.getBlockZ())) + 1); - part.add(RNG.r.d(), 0, RNG.r.d()); - int offset = p.getWorld().getMinHeight(); - if(extra != 0) { - J.s(() -> p.spawnParticle(particleEffect, part.getX(), part.getY() + offset + RNG.r.i(particleOffset), - part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ, - extra)); - } else { - J.s(() -> p.spawnParticle(particleEffect, part.getX(), part.getY() + offset + RNG.r.i(particleOffset), part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ)); - } - } - - if(commandRegistry != null) { - commandRegistry.run(p); - } - - if(potionStrength > -1) { - if(p.hasPotionEffect(getRealType())) { - PotionEffect e = p.getPotionEffect(getRealType()); - if(e.getAmplifier() > getPotionStrength()) { - return; - } - - J.s(() -> p.removePotionEffect(getRealType())); - } - - J.s(() -> p.addPotionEffect(new PotionEffect(getRealType(), - RNG.r.i(Math.min(potionTicksMax, potionTicksMin), - Math.max(potionTicksMax, potionTicksMin)), - getPotionStrength(), - true, false, false))); - } - } - - public void apply(Entity p) { - if(!canTick()) { - return; - } - - if(RNG.r.nextInt(chance) != 0) { - return; - } - - if(sound != null) { - Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); - - J.s(() -> p.getWorld().playSound(part, getSound(), (float) volume, (float) RNG.r.d(minPitch, maxPitch))); - } - - if(particleEffect != null) { - Location part = p.getLocation().clone().add(0, 0.25, 0).add(new Vector(1, 1, 1).multiply(RNG.r.d())).subtract(new Vector(1, 1, 1).multiply(RNG.r.d())); - part.add(RNG.r.d(), 0, RNG.r.d()); - int offset = p.getWorld().getMinHeight(); - if(extra != 0) { - J.s(() -> p.getWorld().spawnParticle(particleEffect, part.getX(), part.getY() + offset + RNG.r.i(particleOffset), - part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ, - extra)); - } else { - J.s(() -> p.getWorld().spawnParticle(particleEffect, part.getX(), part.getY() + offset + RNG.r.i(particleOffset), part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ)); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisElipsoid.java b/src/main/java/com/volmit/iris/engine/object/IrisElipsoid.java deleted file mode 100644 index d031fd9b1..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisElipsoid.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.matter.slices.CavernMatter; -import lombok.Data; - -@Snippet("carving-elipsoid") -@Desc("Represents an procedural eliptical shape") -@Data -public class IrisElipsoid implements IRare { - private transient final AtomicCache matterNodeCache = new AtomicCache<>(); - @Required - @Desc("Typically a 1 in RARITY on a per fork basis") - @MinNumber(1) - private int rarity = 1; - @RegistryListResource(IrisBiome.class) - @Desc("Force this cave to only generate the specified custom biome") - private String customBiome = ""; - @Desc("The styled random radius for x") - private IrisStyledRange xRadius = new IrisStyledRange(1, 5, new IrisGeneratorStyle(NoiseStyle.STATIC)); - @Desc("The styled random radius for y") - private IrisStyledRange yRadius = new IrisStyledRange(1, 5, new IrisGeneratorStyle(NoiseStyle.STATIC)); - @Desc("The styled random radius for z") - private IrisStyledRange zRadius = new IrisStyledRange(1, 5, new IrisGeneratorStyle(NoiseStyle.STATIC)); - - @SuppressWarnings("SuspiciousNameCombination") - public void generate(RNG rng, Engine engine, MantleWriter writer, int x, int y, int z) { - writer.setElipsoid(x, y, z, - xRadius.get(rng, z, y, engine.getData()), - yRadius.get(rng, x, z, engine.getData()), - zRadius.get(rng, y, x, engine.getData()), true, matterNodeCache.aquire(() -> CavernMatter.get(getCustomBiome(), 0))); - } - - public double maxSize() { - return Math.max(xRadius.getMax(), Math.max(yRadius.getMax(), zRadius.getMax())); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEnchantment.java b/src/main/java/com/volmit/iris/engine/object/IrisEnchantment.java deleted file mode 100644 index d97663d02..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEnchantment.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.bukkit.inventory.meta.ItemMeta; - -import java.lang.reflect.Field; - -@Snippet("enchantment") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an enchantment & level") -@Data -public class IrisEnchantment { - @Required - @Desc("The enchantment") - private String enchantment = ""; - - @MinNumber(1) - @Desc("Minimum amount of this loot") - private int minLevel = 1; - - @MinNumber(1) - @Desc("Maximum amount of this loot") - private int maxLevel = 1; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance that this enchantment is applied (0 to 1)") - private double chance = 1; - - public void apply(RNG rng, ItemMeta meta) { - try { - if(rng.nextDouble() < chance) { - if(meta instanceof EnchantmentStorageMeta) { - ((EnchantmentStorageMeta) meta).addStoredEnchant(getEnchant(), getLevel(rng), true); - return; - } - meta.addEnchant(getEnchant(), getLevel(rng), true); - } - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - public Enchantment getEnchant() { - for(Field i : Enchantment.class.getDeclaredFields()) { - if(i.getType().equals(Enchantment.class) && i.getName().equals(getEnchantment())) { - try { - return (Enchantment) i.get(null); - } catch(IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - } - - return null; - } - - public int getLevel(RNG rng) { - return rng.i(getMinLevel(), getMaxLevel()); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEngineChunkData.java b/src/main/java/com/volmit/iris/engine/object/IrisEngineChunkData.java deleted file mode 100644 index 4b579e240..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEngineChunkData.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.util.collection.KList; -import lombok.Data; - -@Data -public class IrisEngineChunkData { - private long chunk; - private KList cooldowns = new KList<>(); - - public void cleanup(Engine engine) { - for(IrisEngineSpawnerCooldown i : getCooldowns().copy()) { - IrisSpawner sp = engine.getData().getSpawnerLoader().load(i.getSpawner()); - - if(sp == null || i.canSpawn(sp.getMaximumRate())) { - getCooldowns().remove(i); - } - } - } - - public boolean isEmpty() { - return cooldowns.isEmpty(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEngineData.java b/src/main/java/com/volmit/iris/engine/object/IrisEngineData.java deleted file mode 100644 index 0166d8ee1..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEngineData.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.util.collection.KList; -import lombok.Data; - -@Data -public class IrisEngineData { - private IrisEngineStatistics statistics = new IrisEngineStatistics(); - private KList spawnerCooldowns = new KList<>(); - private KList chunks = new KList<>(); - private Long seed = null; - - public void removeChunk(int x, int z) { - long k = Cache.key(x, z); - chunks.removeWhere((i) -> i.getChunk() == k); - } - - public IrisEngineChunkData getChunk(int x, int z) { - long k = Cache.key(x, z); - - for(IrisEngineChunkData i : chunks) { - if(i.getChunk() == k) { - return i; - } - } - - IrisEngineChunkData c = new IrisEngineChunkData(); - c.setChunk(k); - chunks.add(c); - return c; - } - - public void cleanup(Engine engine) { - for(IrisEngineSpawnerCooldown i : getSpawnerCooldowns().copy()) { - IrisSpawner sp = engine.getData().getSpawnerLoader().load(i.getSpawner()); - - if(sp == null || i.canSpawn(sp.getMaximumRate())) { - getSpawnerCooldowns().remove(i); - } - } - - for(IrisEngineChunkData i : chunks.copy()) { - i.cleanup(engine); - - if(i.isEmpty()) { - getChunks().remove(i); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEngineSpawnerCooldown.java b/src/main/java/com/volmit/iris/engine/object/IrisEngineSpawnerCooldown.java deleted file mode 100644 index ecc319935..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEngineSpawnerCooldown.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.util.math.M; -import lombok.Data; - -@Data -public class IrisEngineSpawnerCooldown { - private long lastSpawn = 0; - private String spawner; - - public void spawn(Engine engine) { - lastSpawn = M.ms(); - } - - public boolean canSpawn(IrisRate s) { - return M.ms() - lastSpawn > s.getInterval(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEngineStatistics.java b/src/main/java/com/volmit/iris/engine/object/IrisEngineStatistics.java deleted file mode 100644 index f6a723cd5..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEngineStatistics.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import lombok.Data; - -@Data -public class IrisEngineStatistics { - private int totalHotloads = 0; - private int chunksGenerated = 0; - - public void generatedChunk() { - chunksGenerated++; - } - - public void hotloaded() { - totalHotloads++; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEngineStreamType.java b/src/main/java/com/volmit/iris/engine/object/IrisEngineStreamType.java deleted file mode 100644 index 3b122c785..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEngineStreamType.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.util.stream.ProceduralStream; - -import java.util.function.Function; - -@Desc("Represents a stream from the engine") -public enum IrisEngineStreamType { - @Desc("Represents the given slope at the x, z coordinates") - SLOPE((f) -> f.getComplex().getSlopeStream()), - - @Desc("Represents the base generator height at the given position. This includes only the biome generators / interpolation and noise features but does not include carving, caves.") - HEIGHT((f) -> f.getComplex().getHeightStream()), - - @Desc("Represents the base generator height at the given position. This includes only the biome generators / interpolation and noise features but does not include carving, caves. with Max(height, fluidHeight).") - HEIGHT_OR_FLUID((f) -> f.getComplex().getHeightFluidStream()), - - @Desc("Represents the overlay noise generators summed (dimension setting)") - OVERLAY_NOISE((f) -> f.getComplex().getOverlayStream()), - - @Desc("Represents the noise style of regions") - REGION_STYLE((f) -> f.getComplex().getRegionStyleStream()), - - @Desc("Represents the identity of regions. Each region has a unique number (very large numbers)") - REGION_IDENTITY((f) -> f.getComplex().getRegionIdentityStream()); - - private final Function> getter; - - IrisEngineStreamType(Function> getter) { - this.getter = getter; - } - - public ProceduralStream get(Engine engine) { - return getter.apply(engine); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEngineValueType.java b/src/main/java/com/volmit/iris/engine/object/IrisEngineValueType.java deleted file mode 100644 index 72c4620d6..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEngineValueType.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.annotations.Desc; - -import java.util.function.Function; - -@Desc("Represents a value from the engine") -public enum IrisEngineValueType { - @Desc("Represents actual height of the engine") - ENGINE_HEIGHT((f) -> Double.valueOf(f.getHeight())), - - @Desc("Represents virtual bottom of the engine in the compound. If this engine is on top of another engine, it's min height would be at the maxHeight of the previous engine + 1") - ENGINE_MIN_HEIGHT((f) -> Double.valueOf(f.getMinHeight())), - - @Desc("Represents virtual top of the engine in the compound. If this engine is below another engine, it's max height would be at the minHeight of the next engine - 1") - ENGINE_MAX_HEIGHT((f) -> Double.valueOf(f.getWorld().maxHeight())), - - @Desc("The fluid height defined in the dimension file") - FLUID_HEIGHT((f) -> Double.valueOf(f.getComplex().getFluidHeight())), - ; - - private final Function getter; - - IrisEngineValueType(Function getter) { - this.getter = getter; - } - - public Double get(Engine engine) { - return getter.apply(engine); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEntity.java b/src/main/java/com/volmit/iris/engine/object/IrisEntity.java deleted file mode 100644 index c2e16324b..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEntity.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.RegistryListSpecialEntity; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.plugin.Chunks; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.Particle; -import org.bukkit.Sound; -import org.bukkit.attribute.Attributable; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Mob; -import org.bukkit.entity.Panda; -import org.bukkit.entity.Panda.Gene; -import org.bukkit.entity.Villager; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.loot.LootContext; -import org.bukkit.loot.LootTable; -import org.bukkit.loot.Lootable; -import org.bukkit.util.Vector; - -import java.util.Collection; -import java.util.Random; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -@SuppressWarnings("ALL") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor - -@Desc("Represents an iris entity.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisEntity extends IrisRegistrant { - @Required - @Desc("The type of entity to spawn. To spawn a mythic mob, set this type to unknown and define mythic type.") - private EntityType type = EntityType.UNKNOWN; - - @Desc("The custom name of this entity") - private String customName = ""; - - @Desc("Should the name on this entity be visible even if you arent looking at it.") - private boolean customNameVisible = false; - - @Desc("If this entity type is a mob, should it be aware of it's surroundings & interact with the world.") - private boolean aware = true; - - @Desc("If this entity type is a creature, should it have ai goals.") - private boolean ai = true; - - @Desc("Should this entity be glowing") - private boolean glowing = false; - - @Desc("Should gravity apply to this entity") - private boolean gravity = true; - - @Desc("When an entity is invulnerable it can only be damaged by players increative mode.") - private boolean invulnerable = false; - - @Desc("When an entity is silent it will not produce any sound.") - private boolean silent = false; - - @Desc("Should this entity be allowed to pickup items") - private boolean pickupItems = false; - - @Desc("Should this entity be removed when far away") - private boolean removable = false; - - @Desc("Entity helmet equipment") - private IrisLoot helmet = null; - - @Desc("Entity chestplate equipment") - private IrisLoot chestplate = null; - - @Desc("Entity boots equipment") - private IrisLoot boots = null; - - @Desc("Entity leggings equipment") - private IrisLoot leggings = null; - - @Desc("Entity main hand equipment") - private IrisLoot mainHand = null; - - @Desc("Entity off hand equipment") - private IrisLoot offHand = null; - - @Desc("Make other entities ride this entity") - @ArrayType(min = 1, type = IrisEntity.class) - private KList passengers = new KList<>(); - - @Desc("Attribute modifiers for this entity") - @ArrayType(min = 1, type = IrisAttributeModifier.class) - private KList attributes = new KList<>(); - - @Desc("Loot tables for drops") - private IrisLootReference loot = new IrisLootReference(); - - @Desc("If specified, this entity will be leashed by this entity. I.e. THIS ENTITY Leashed by SPECIFIED. This has no effect on EnderDragons, Withers, Players, or Bats.Non-living entities excluding leashes will not persist as leashholders.") - private IrisEntity leashHolder = null; - - @Desc("If specified, this entity will spawn with an effect") - private IrisEffect spawnEffect = null; - - @Desc("Simply moves the entity from below the surface slowly out of the ground as a spawn-in effect") - private boolean spawnEffectRiseOutOfGround = false; - - @Desc("The main gene for a panda if the entity type is a panda") - private Gene pandaMainGene = Gene.NORMAL; - - @Desc("The hidden gene for a panda if the entity type is a panda") - private Gene pandaHiddenGene = Gene.NORMAL; - - @Desc("The this entity is ageable, set it's baby status") - private boolean baby = false; - - @Desc("If the entity should never be culled. Useful for Jigsaws") - private boolean keepEntity = false; - - @Desc("The surface type to spawn this mob on") - private IrisSurface surface = IrisSurface.LAND; - - @RegistryListSpecialEntity - @Desc("Create a mob from another plugin, such as Mythic Mobs. Should be in the format of a namespace of PluginName:MobName") - private String specialType = ""; - - @Desc("Set the entity type to UNKNOWN, then define a script here which ends with the entity variable (the result). You can use Iris.getLocation() to find the target location. You can spawn any entity this way.") - @RegistryListResource(IrisScript.class) - private String spawnerScript = ""; - - @ArrayType(min = 1, type = String.class) - @Desc("Set the entity type to UNKNOWN, then define a script here. You can use Iris.getLocation() to find the target location. You can spawn any entity this way.") - @RegistryListResource(IrisScript.class) - private KList postSpawnScripts = new KList<>(); - - @ArrayType(min = 1, type = IrisCommand.class) - @Desc("Run raw commands when this entity is spawned. Use {x}, {y}, and {z} for location. /summon pig {x} {y} {z}") - private KList rawCommands = new KList<>(); - - public Entity spawn(Engine gen, Location at) { - return spawn(gen, at, new RNG(at.hashCode())); - } - - public Entity spawn(Engine gen, Location at, RNG rng) { - if(!Chunks.isSafe(at)) { - return null; - } - if(isSpawnEffectRiseOutOfGround()) { - AtomicReference f = new AtomicReference<>(at); - try { - J.sfut(() -> { - if(Chunks.hasPlayersNearby(f.get())) { - Location b = f.get().clone(); - Location start = new Location(b.getWorld(), b.getX(), b.getY() - 5, b.getZ()); - f.set(start); - } - }).get(); - } catch(InterruptedException e) { - e.printStackTrace(); - } catch(ExecutionException e) { - e.printStackTrace(); - } - at = f.get(); - } - - Entity ee = doSpawn(at); - - if(ee == null && !Chunks.isSafe(at)) { - return null; - } - - if(!spawnerScript.isEmpty() && ee == null) { - synchronized(this) { - gen.getExecution().getAPI().setLocation(at); - try { - ee = (Entity) gen.getExecution().evaluate(spawnerScript); - } catch(Throwable ex) { - Iris.error("You must return an Entity in your scripts to use entity scripts!"); - ex.printStackTrace(); - } - } - } - - if(ee == null) { - return null; - } - - Entity e = ee; - e.setCustomName(getCustomName() != null ? C.translateAlternateColorCodes('&', getCustomName()) : null); - e.setCustomNameVisible(isCustomNameVisible()); - e.setGlowing(isGlowing()); - e.setGravity(isGravity()); - e.setInvulnerable(isInvulnerable()); - e.setSilent(isSilent()); - e.setPersistent(isKeepEntity() || IrisSettings.get().getWorld().isForcePersistEntities()); - - int gg = 0; - for(IrisEntity i : passengers) { - Entity passenger = i.spawn(gen, at, rng.nextParallelRNG(234858 + gg++)); - if(!Bukkit.isPrimaryThread()) { - J.s(() -> e.addPassenger(passenger)); - } - } - - if(e instanceof Attributable) { - Attributable a = (Attributable) e; - - for(IrisAttributeModifier i : getAttributes()) { - i.apply(rng, a); - } - } - - if(e instanceof Lootable) { - Lootable l = (Lootable) e; - - if(getLoot().getTables().isNotEmpty()) { - Location finalAt = at; - l.setLootTable(new LootTable() { - @Override - public NamespacedKey getKey() { - return new NamespacedKey(Iris.instance, "loot-" + IrisEntity.this.hashCode()); - } - - @Override - public Collection populateLoot(Random random, LootContext context) { - KList items = new KList<>(); - - for(String fi : getLoot().getTables()) { - IrisLootTable i = gen.getData().getLootLoader().load(fi); - items.addAll(i.getLoot(gen.isStudio(), false, rng.nextParallelRNG(345911), InventorySlotType.STORAGE, finalAt.getBlockX(), finalAt.getBlockY(), finalAt.getBlockZ(), 8, 4)); - } - - return items; - } - - @Override - public void fillInventory(Inventory inventory, Random random, LootContext context) { - for(ItemStack i : populateLoot(random, context)) { - inventory.addItem(i); - } - - gen.scramble(inventory, rng); - } - }); - } - } - - if(e instanceof LivingEntity) { - LivingEntity l = (LivingEntity) e; - l.setAI(isAi()); - l.setCanPickupItems(isPickupItems()); - - if(getLeashHolder() != null) { - l.setLeashHolder(getLeashHolder().spawn(gen, at, rng.nextParallelRNG(234548))); - } - - l.setRemoveWhenFarAway(isRemovable()); - - if(getHelmet() != null && rng.i(1, getHelmet().getRarity()) == 1) { - l.getEquipment().setHelmet(getHelmet().get(gen.isStudio(), rng)); - } - - if(getChestplate() != null && rng.i(1, getChestplate().getRarity()) == 1) { - l.getEquipment().setChestplate(getChestplate().get(gen.isStudio(), rng)); - } - - if(getLeggings() != null && rng.i(1, getLeggings().getRarity()) == 1) { - l.getEquipment().setLeggings(getLeggings().get(gen.isStudio(), rng)); - } - - if(getBoots() != null && rng.i(1, getBoots().getRarity()) == 1) { - l.getEquipment().setBoots(getBoots().get(gen.isStudio(), rng)); - } - - if(getMainHand() != null && rng.i(1, getMainHand().getRarity()) == 1) { - l.getEquipment().setItemInMainHand(getMainHand().get(gen.isStudio(), rng)); - } - - if(getOffHand() != null && rng.i(1, getOffHand().getRarity()) == 1) { - l.getEquipment().setItemInOffHand(getOffHand().get(gen.isStudio(), rng)); - } - } - - if(e instanceof Ageable && isBaby()) { - ((Ageable) e).setBaby(); - } - - if(e instanceof Panda) { - ((Panda) e).setMainGene(getPandaMainGene()); - ((Panda) e).setMainGene(getPandaHiddenGene()); - } - - if(e instanceof Villager) { - Villager villager = (Villager) e; - villager.setRemoveWhenFarAway(false); - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> { - villager.setPersistent(true); - }, 1); - } - - if(e instanceof Mob) { - Mob m = (Mob) e; - m.setAware(isAware()); - } - - if(spawnEffect != null) { - spawnEffect.apply(e); - } - - if(postSpawnScripts.isNotEmpty()) { - synchronized(this) { - gen.getExecution().getAPI().setLocation(at); - gen.getExecution().getAPI().setEntity(ee); - - for(String i : postSpawnScripts) { - gen.getExecution().execute(i); - } - } - } - - if(rawCommands.isNotEmpty()) { - final Location fat = at; - rawCommands.forEach(r -> r.run(fat)); - } - - Location finalAt1 = at; - - J.s(() -> { - if(isSpawnEffectRiseOutOfGround() && e instanceof LivingEntity && Chunks.hasPlayersNearby(finalAt1)) { - Location start = finalAt1.clone(); - e.setInvulnerable(true); - ((LivingEntity) e).setAI(false); - ((LivingEntity) e).setCollidable(false); - ((LivingEntity) e).setNoDamageTicks(100000); - AtomicInteger t = new AtomicInteger(0); - AtomicInteger v = new AtomicInteger(0); - v.set(J.sr(() -> { - if(t.get() > 100) { - J.csr(v.get()); - return; - } - - t.incrementAndGet(); - if(e.getLocation().getBlock().getType().isSolid() || ((LivingEntity) e).getEyeLocation().getBlock().getType().isSolid()) { - e.teleport(start.add(new Vector(0, 0.1, 0))); - ItemStack itemCrackData = new ItemStack(((LivingEntity) e).getEyeLocation().clone().subtract(0, 2, 0).getBlock().getBlockData().getMaterial()); - e.getWorld().spawnParticle(Particle.ITEM_CRACK, ((LivingEntity) e).getEyeLocation(), 6, 0.2, 0.4, 0.2, 0.06f, itemCrackData); - if(M.r(0.2)) { - e.getWorld().playSound(e.getLocation(), Sound.BLOCK_CHORUS_FLOWER_GROW, 0.8f, 0.1f); - } - } else { - J.csr(v.get()); - ((LivingEntity) e).setNoDamageTicks(0); - ((LivingEntity) e).setCollidable(true); - ((LivingEntity) e).setAI(true); - e.setInvulnerable(false); - } - }, 0)); - } - }); - - - return e; - } - - private int surfaceY(Location l) { - int m = l.getBlockY(); - - while(m-- > 0) { - Location ll = l.clone(); - ll.setY(m); - - if(ll.getBlock().getType().isSolid()) { - return m; - } - } - - return 0; - } - - private Entity doSpawn(Location at) { - if(!Chunks.isSafe(at)) { - return null; - } - - if(type.equals(EntityType.UNKNOWN)) { - return null; - } - - if(!Bukkit.isPrimaryThread()) { - // Someone called spawn (worldedit maybe?) on a non server thread - // Due to the structure of iris, we will call it sync and busy wait until it's done. - AtomicReference ae = new AtomicReference<>(); - - try { - J.s(() -> ae.set(doSpawn(at))); - } catch(Throwable e) { - return null; - } - PrecisionStopwatch p = PrecisionStopwatch.start(); - - while(ae.get() == null) { - J.sleep(25); - - if(p.getMilliseconds() > 500) { - return null; - } - } - - return ae.get(); - } - - if(isSpecialType()) { - if(specialType.toLowerCase().startsWith("mythicmobs:")) { - return Iris.linkMythicMobs.spawnMob(specialType.substring(11), at); - } else { - Iris.warn("Invalid mob type to spawn: '" + specialType + "'!"); - return null; - } - } - - - return at.getWorld().spawnEntity(at, getType()); - } - - public boolean isCitizens() { - return false; - - // TODO: return Iris.linkCitizens.supported() && someType is not empty; - } - - public boolean isSpecialType() { - return specialType != null && !specialType.equals(""); - } - - @Override - public String getFolderName() { - return "entities"; - } - - @Override - public String getTypeName() { - return "Entity"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisEntitySpawn.java b/src/main/java/com/volmit/iris/engine/object/IrisEntitySpawn.java deleted file mode 100644 index 6bb199431..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisEntitySpawn.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterMarker; -import com.volmit.iris.util.matter.slices.MarkerMatter; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Entity; - -@Snippet("entity-spawn") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an entity spawn during initial chunk generation") -@Data -public class IrisEntitySpawn implements IRare { - private final transient AtomicCache rng = new AtomicCache<>(); - private final transient AtomicCache ent = new AtomicCache<>(); - @RegistryListResource(IrisEntity.class) - @Required - @Desc("The entity") - private String entity = ""; - @Desc("The energy multiplier when calculating spawn energy usage") - private double energyMultiplier = 1; - @MinNumber(1) - @Desc("The 1 in RARITY chance for this entity to spawn") - private int rarity = 1; - @MinNumber(1) - @Desc("The minumum of this entity to spawn") - private int minSpawns = 1; - @MinNumber(1) - @Desc("The max of this entity to spawn") - private int maxSpawns = 1; - private transient IrisSpawner referenceSpawner; - private transient IrisMarker referenceMarker; - - public int spawn(Engine gen, Chunk c, RNG rng) { - int spawns = minSpawns == maxSpawns ? minSpawns : rng.i(Math.min(minSpawns, maxSpawns), Math.max(minSpawns, maxSpawns)); - int s = 0; - - if(spawns > 0) { - for(int id = 0; id < spawns; id++) { - int x = (c.getX() * 16) + rng.i(15); - int z = (c.getZ() * 16) + rng.i(15); - int h = gen.getHeight(x, z, true) + (gen.getWorld().tryGetRealWorld() ? gen.getWorld().realWorld().getMinHeight() : -64); - int hf = gen.getHeight(x, z, false) + (gen.getWorld().tryGetRealWorld() ? gen.getWorld().realWorld().getMinHeight() : -64); - Location l = switch(getReferenceSpawner().getGroup()) { - case NORMAL -> new Location(c.getWorld(), x, hf + 1, z); - case CAVE -> gen.getMantle().findMarkers(c.getX(), c.getZ(), MarkerMatter.CAVE_FLOOR) - .convert((i) -> i.toLocation(c.getWorld()).add(0, 1, 0)).getRandom(rng); - case UNDERWATER, BEACH -> new Location(c.getWorld(), x, rng.i(h + 1, hf), z); - }; - - if(l != null) { - if(referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) { - if(referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) { - if(spawn100(gen, l) != null) { - s++; - } - } - } else { - if(spawn100(gen, l) != null) { - s++; - } - } - } - } - } - - return s; - } - - public int spawn(Engine gen, IrisPosition c, RNG rng) { - int spawns = minSpawns == maxSpawns ? minSpawns : rng.i(Math.min(minSpawns, maxSpawns), Math.max(minSpawns, maxSpawns)); - int s = 0; - - if(!gen.getWorld().tryGetRealWorld()) { - return 0; - } - - World world = gen.getWorld().realWorld(); - if(spawns > 0) { - - if(referenceMarker != null) { - gen.getMantle().getMantle().remove(c.getX(), c.getY(), c.getZ(), MatterMarker.class); - } - - for(int id = 0; id < spawns; id++) { - Location l = c.toLocation(world).add(0, 1, 0); - - if(referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) { - if(referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) { - if(spawn100(gen, l, true) != null) { - s++; - } - } - } else { - if(spawn100(gen, l, true) != null) { - s++; - } - } - } - } - - return s; - } - - public IrisEntity getRealEntity(Engine g) { - return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); - } - - public Entity spawn(Engine g, Location at) { - if(getRealEntity(g) == null) { - return null; - } - - if(rng.aquire(() -> new RNG(g.getSeedManager().getEntity())).i(1, getRarity()) == 1) { - return spawn100(g, at); - } - - return null; - } - - private Entity spawn100(Engine g, Location at) { - return spawn100(g, at, false); - } - - private Entity spawn100(Engine g, Location at, boolean ignoreSurfaces) { - try { - IrisEntity irisEntity = getRealEntity(g); - if(irisEntity == null) { // No entity - Iris.debug(" You are trying to spawn an entity that does not exist!"); - return null; - } - - if(!ignoreSurfaces && !irisEntity.getSurface().matches(at.clone().subtract(0, 1, 0).getBlock())) { - return null; - } - - Entity e = irisEntity.spawn(g, at.add(0.5, 0, 0.5), rng.aquire(() -> new RNG(g.getSeedManager().getEntity()))); - if(e != null) { - Iris.debug("Spawned " + C.DARK_AQUA + "Entity<" + getEntity() + "> " + C.GREEN + e.getType() + C.LIGHT_PURPLE + " @ " + C.GRAY + e.getLocation().getX() + ", " + e.getLocation().getY() + ", " + e.getLocation().getZ()); - } - - - return e; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - Iris.error(" Failed to retrieve real entity @ " + at + " (entity: " + getEntity() + ")"); - return null; - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisExpression.java b/src/main/java/com/volmit/iris/engine/object/IrisExpression.java deleted file mode 100644 index 97fb58041..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisExpression.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.dfsek.paralithic.Expression; -import com.dfsek.paralithic.eval.parser.Parser; -import com.dfsek.paralithic.eval.parser.Scope; -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.stream.interpolation.Interpolated; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an Iris Expression") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisExpression extends IrisRegistrant { - private static final Parser parser = new Parser(); - - @ArrayType(type = IrisExpressionLoad.class, min = 1) - @Desc("Variables to use in this expression") - private KList variables = new KList<>(); - - @Required - @Desc("The expression. Inherited variables are x, y and z. Avoid using those variable names.") - private String expression; - - private transient AtomicCache expressionCache = new AtomicCache<>(); - private transient AtomicCache> streamCache = new AtomicCache<>(); - - private Expression expression() { - return expressionCache.aquire(() -> { - Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables. - - try { - for(IrisExpressionLoad i : variables) { - scope.addInvocationVariable(i.getName()); - } - - scope.addInvocationVariable("x"); - scope.addInvocationVariable("y"); - scope.addInvocationVariable("z"); - } catch(Throwable e) { - e.printStackTrace(); - Iris.error("Script Variable load error in " + getLoadFile().getPath()); - } - - try { - return parser.parse(getExpression(), scope); - } catch(Throwable e) { - e.printStackTrace(); - Iris.error("Script load error in " + getLoadFile().getPath()); - } - - return null; - }); - } - - public ProceduralStream stream(RNG rng) { - return streamCache.aquire(() -> ProceduralStream.of((x, z) -> evaluate(rng, x, z), - (x, y, z) -> evaluate(rng, x, y, z), Interpolated.DOUBLE)); - } - - public double evaluate(RNG rng, double x, double z) { - double[] g = new double[3 + getVariables().size()]; - int m = 0; - for(IrisExpressionLoad i : getVariables()) { - g[m++] = i.getValue(rng, getLoader(), x, z); - } - - g[m++] = x; - g[m++] = z; - g[m] = -1; - - return expression().evaluate(g); - } - - public double evaluate(RNG rng, double x, double y, double z) { - double[] g = new double[3 + getVariables().size()]; - int m = 0; - for(IrisExpressionLoad i : getVariables()) { - g[m++] = i.getValue(rng, getLoader(), x, y, z); - } - - g[m++] = x; - g[m++] = y; - g[m] = z; - - return expression().evaluate(g); - } - - @Override - public String getFolderName() { - return "expressions"; - } - - @Override - public String getTypeName() { - return "Expression"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisExpressionLoad.java b/src/main/java/com/volmit/iris/engine/object/IrisExpressionLoad.java deleted file mode 100644 index c0296c535..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisExpressionLoad.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.stream.ProceduralStream; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("expression-load") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a variable to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisExpressionLoad { - @Required - @Desc("The variable to assign this value to. Do not set the name to x, y, or z") - private String name = ""; - - @Desc("If the style value is not defined, this value will be used") - private double staticValue = -1; - - @Desc("If defined, this variable will use a generator style as it's value") - private IrisGeneratorStyle styleValue = null; - - @Desc("If defined, iris will use an internal stream from the engine as it's value") - private IrisEngineStreamType engineStreamValue = null; - - @Desc("If defined, iris will use an internal value from the engine as it's value") - private IrisEngineValueType engineValue = null; - - private transient AtomicCache> streamCache = new AtomicCache<>(); - private transient AtomicCache valueCache = new AtomicCache<>(); - - public double getValue(RNG rng, IrisData data, double x, double z) { - if(engineValue != null) { - return valueCache.aquire(() -> engineValue.get(data.getEngine())); - } - - if(engineStreamValue != null) { - return streamCache.aquire(() -> engineStreamValue.get(data.getEngine())).get(x, z); - } - - if(styleValue != null) { - return styleValue.create(rng, data).noise(x, z); - } - - return staticValue; - } - - public double getValue(RNG rng, IrisData data, double x, double y, double z) { - if(engineValue != null) { - return valueCache.aquire(() -> engineValue.get(data.getEngine())); - } - - if(engineStreamValue != null) { - return streamCache.aquire(() -> engineStreamValue.get(data.getEngine())).get(x, z); - } - - if(styleValue != null) { - return styleValue.create(rng, data).noise(x, y, z); - } - - return staticValue; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisFluidBodies.java b/src/main/java/com/volmit/iris/engine/object/IrisFluidBodies.java deleted file mode 100644 index 071e2ade6..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisFluidBodies.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("fluid-bodies") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a fluid body configuration") -@Data -public class IrisFluidBodies { - @ArrayType(type = IrisRiver.class, min = 1) - @Desc("Define rivers") - private KList rivers = new KList<>(); - - @ArrayType(type = IrisLake.class, min = 1) - @Desc("Define lakes") - private KList lakes = new KList<>(); - - @BlockCoordinates - public void generate(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z) { - if(rivers.isNotEmpty()) { - for(IrisRiver i : rivers) { - i.generate(writer, rng, engine, x, y, z); - } - } - - if(lakes.isNotEmpty()) { - for(IrisLake i : lakes) { - i.generate(writer, rng, engine, x, y, z); - } - } - } - - public int getMaxRange(IrisData data) { - int max = 0; - - for(IrisRiver i : rivers) { - max = Math.max(max, i.getSize(data)); - } - - for(IrisLake i : lakes) { - max = Math.max(max, i.getSize(data)); - } - - - return max; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisFontStyle.java b/src/main/java/com/volmit/iris/engine/object/IrisFontStyle.java deleted file mode 100644 index ebfe36389..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisFontStyle.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Represents a basic font style to apply to a font family") -public enum IrisFontStyle { - @Desc("Plain old text") - PLAIN, - - @Desc("Italicized Text") - ITALIC, - - @Desc("Bold Text") - BOLD, -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisGenerator.java b/src/main/java/com/volmit/iris/engine/object/IrisGenerator.java deleted file mode 100644 index 6b23b8a57..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisGenerator.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CellGenerator; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.List; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a composite generator of noise gens") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisGenerator extends IrisRegistrant { - private final transient AtomicCache cellGen = new AtomicCache<>(); - @MinNumber(0.001) - @Desc("The zoom or frequency.") - private double zoom = 1; - @MinNumber(0) - @Desc("The opacity, essentially a multiplier on the output.") - private double opacity = 1; - @Desc("Multiply the compsites instead of adding them") - private boolean multiplicitive = false; - @MinNumber(0.001) - @Desc("The size of the cell fractures") - private double cellFractureZoom = 1D; - @MinNumber(0) - @Desc("Cell Fracture Coordinate Shuffling") - private double cellFractureShuffle = 12D; - @Desc("The height of fracture cells. Set to 0 to disable") - private double cellFractureHeight = 0D; - @MinNumber(0) - @MaxNumber(1) - @Desc("How big are the cells (X,Z) relative to the veins that touch them. Between 0 and 1. 0.1 means thick veins, small cells.") - private double cellPercentSize = 0.75D; - @Desc("The offset to shift this noise x") - private double offsetX = 0; - @Desc("The offset to shift this noise z") - private double offsetZ = 0; - @Required - @Desc("The seed for this generator") - private long seed = 1; - @Required - @Desc("The interpolator to use when smoothing this generator into other regions & generators") - private IrisInterpolator interpolator = new IrisInterpolator(); - @MinNumber(0) - @MaxNumber(8192) - @Desc("Cliff Height Max. Disable with 0 for min and max") - private double cliffHeightMax = 0; - @MinNumber(0) - @MaxNumber(8192) - @Desc("Cliff Height Min. Disable with 0 for min and max") - private double cliffHeightMin = 0; - @ArrayType(min = 1, type = IrisNoiseGenerator.class) - @Desc("The list of noise gens this gen contains.") - private KList composite = new KList<>(); - @Desc("The noise gen for cliff height.") - private IrisNoiseGenerator cliffHeightGenerator = new IrisNoiseGenerator(); - - public double getMax() { - return opacity; - } - - public boolean hasCliffs() { - return cliffHeightMax > 0; - } - - public CellGenerator getCellGenerator(long seed) { - return cellGen.aquire(() -> new CellGenerator(new RNG(seed + 239466))); - } - - public T fitRarity(KList b, long superSeed, double rx, double rz) { - if(b.size() == 0) { - return null; - } - - if(b.size() == 1) { - return b.get(0); - } - - KList rarityMapped = new KList<>(); - boolean o = false; - int max = 1; - for(T i : b) { - if(i.getRarity() > max) { - max = i.getRarity(); - } - } - - max++; - - for(T i : b) { - for(int j = 0; j < max - i.getRarity(); j++) { - //noinspection AssignmentUsedAsCondition - if(o = !o) { - rarityMapped.add(i); - } else { - rarityMapped.add(0, i); - } - } - } - - if(rarityMapped.size() == 1) { - return rarityMapped.get(0); - } - - if(rarityMapped.isEmpty()) { - throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); - } - - return fit(rarityMapped, superSeed, rx, rz); - } - - public T fit(T[] v, long superSeed, double rx, double rz) { - if(v.length == 0) { - return null; - } - - if(v.length == 1) { - return v[0]; - } - - return v[fit(0, v.length - 1, superSeed, rx, rz)]; - } - - public T fit(List v, long superSeed, double rx, double rz) { - if(v.size() == 0) { - return null; - } - - if(v.size() == 1) { - return v.get(0); - } - - return v.get(fit(0, v.size() - 1, superSeed, rx, rz)); - } - - public int fit(int min, int max, long superSeed, double rx, double rz) { - if(min == max) { - return min; - } - - double noise = getHeight(rx, rz, superSeed); - - return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); - } - - public int fit(double min, double max, long superSeed, double rx, double rz) { - if(min == max) { - return (int) Math.round(min); - } - - double noise = getHeight(rx, rz, superSeed); - - return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); - } - - public double fitDouble(double min, double max, long superSeed, double rx, double rz) { - if(min == max) { - return min; - } - - double noise = getHeight(rx, rz, superSeed); - - return IrisInterpolation.lerp(min, max, noise); - } - - public double getHeight(double rx, double rz, long superSeed) { - return getHeight(rx, 0, rz, superSeed, true); - } - - - public double getHeight(double rx, double ry, double rz, long superSeed) { - return getHeight(rx, ry, rz, superSeed, false); - } - - public double getHeight(double rx, double ry, double rz, long superSeed, boolean no3d) { - if(composite.isEmpty()) { - return 0; - } - - int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * seed + offsetX + offsetZ); - double h = multiplicitive ? 1 : 0; - double tp = 0; - - if(composite.size() == 1) { - if(multiplicitive) { - h *= composite.get(0).getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom, getLoader()); - } else { - tp += composite.get(0).getOpacity(); - h += composite.get(0).getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom, getLoader()); - } - } else { - for(IrisNoiseGenerator i : composite) { - if(multiplicitive) { - h *= i.getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom, getLoader()); - } else { - tp += i.getOpacity(); - h += i.getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom, getLoader()); - } - } - } - - double v = multiplicitive ? h * opacity : (h / tp) * opacity; - - if(Double.isNaN(v)) { - v = 0; - } - - v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc) : v; - v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v; - - return v; - } - - public double cell(double rx, double rz, double v, double superSeed) { - getCellGenerator(seed + 46222).setShuffle(getCellFractureShuffle()); - return getCellGenerator(seed + 46222).getDistance(rx / getCellFractureZoom(), rz / getCellFractureZoom()) > getCellPercentSize() ? (v * getCellFractureHeight()) : v; - } - - private boolean hasCellCracks() { - return getCellFractureHeight() != 0; - } - - public double getCliffHeight(double rx, double rz, double superSeed) { - int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * seed + offsetX + offsetZ); - double h = cliffHeightGenerator.getNoise((long) (seed + superSeed + hc), (rx + offsetX) / zoom, (rz + offsetZ) / zoom, getLoader()); - return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h); - } - - public double cliff(double rx, double rz, double v, double superSeed) { - double cliffHeight = getCliffHeight(rx, rz, superSeed - 34857); - return (Math.round((v * 255D) / cliffHeight) * cliffHeight) / 255D; - } - - public IrisGenerator rescale(double scale) { - zoom /= scale; - return this; - } - - public KList getAllComposites() { - KList g = new KList<>(); - - for(IrisNoiseGenerator i : composite) { - g.addAll(i.getAllComposites()); - } - - return g; - } - - @Override - public String getFolderName() { - return "generators"; - } - - @Override - public String getTypeName() { - return "Generator"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisGeneratorStyle.java b/src/main/java/com/volmit/iris/engine/object/IrisGeneratorStyle.java deleted file mode 100644 index 123a1d247..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisGeneratorStyle.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.noise.ExpressionNoise; -import com.volmit.iris.util.noise.ImageNoise; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.Objects; - -@Snippet("style") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A gen style") -@Data -public class IrisGeneratorStyle { - private final transient AtomicCache cng = new AtomicCache<>(); - @Desc("The chance is 1 in CHANCE per interval") - private NoiseStyle style = NoiseStyle.FLAT; - - @Desc("If set above 0, this style will be cellularized") - private double cellularFrequency = 0; - - @Desc("Cell zooms") - private double cellularZoom = 1; - @MinNumber(0.00001) - @Desc("The zoom of this style") - private double zoom = 1; - @Desc("Instead of using the style property, use a custom expression to represent this style.") - @RegistryListResource(IrisExpression.class) - private String expression = null; - @Desc("Use an Image map instead of a generated value") - private IrisImageMap imageMap = null; - @MinNumber(0.00001) - @Desc("The Output multiplier. Only used if parent is fracture.") - private double multiplier = 1; - @Desc("If set to true, each dimension will be fractured with a different order of input coordinates. This is usually 2 or 3 times slower than normal.") - private boolean axialFracturing = false; - @Desc("Apply a generator to the coordinate field fed into this parent generator. I.e. Distort your generator with another generator.") - private IrisGeneratorStyle fracture = null; - @MinNumber(0.01562) - @MaxNumber(64) - @Desc("The exponent") - private double exponent = 1; - @MinNumber(0) - @MaxNumber(8192) - @Desc("If the cache size is set above 0, this generator will be cached") - private int cacheSize = 0; - - public IrisGeneratorStyle(NoiseStyle s) { - this.style = s; - } - - public IrisGeneratorStyle zoomed(double z) { - this.zoom = z; - return this; - } - - public CNG createNoCache(RNG rng, IrisData data) { - return createNoCache(rng, data, false); - } - - - private int hash() - { - return Objects.hash(expression, imageMap, multiplier, axialFracturing, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style); - } - - public CNG createNoCache(RNG rng, IrisData data, boolean actuallyCached) { - String cacheKey = hash() + ""; - - if(getExpression() != null) { - IrisExpression e = data.getExpressionLoader().load(getExpression()); - - if(e != null) { - CNG cng = new CNG(rng, new ExpressionNoise(rng, e), 1D, 1) - .bake().scale(1D / zoom).pow(exponent).bake(); - cng.setTrueFracturing(axialFracturing); - - if(fracture != null) { - cng.fractureWith(fracture.create(rng.nextParallelRNG(2934), data), fracture.getMultiplier()); - } - - if(cellularFrequency > 0) { - return cng.cellularize(rng.nextParallelRNG(884466), cellularFrequency).scale(1D / cellularZoom).bake(); - } - - return cng; - } - } else if(getImageMap() != null) { - CNG cng = new CNG(rng, new ImageNoise(data, getImageMap()), 1D, 1).bake().scale(1D / zoom).pow(exponent).bake(); - cng.setTrueFracturing(axialFracturing); - - if(fracture != null) { - cng.fractureWith(fracture.create(rng.nextParallelRNG(2934), data), fracture.getMultiplier()); - } - - if(cellularFrequency > 0) { - return cng.cellularize(rng.nextParallelRNG(884466), cellularFrequency).scale(1D / cellularZoom).bake(); - } - - return cng; - } - - CNG cng = style.create(rng).bake().scale(1D / zoom).pow(exponent).bake(); - cng.setTrueFracturing(axialFracturing); - - if(fracture != null) { - cng.fractureWith(fracture.create(rng.nextParallelRNG(2934), data), fracture.getMultiplier()); - } - - if(cellularFrequency > 0) { - return cng.cellularize(rng.nextParallelRNG(884466), cellularFrequency).scale(1D / cellularZoom).bake(); - } - - return cng; - } - - public double warp(RNG rng, IrisData data, double value, double... coords) - { - return create(rng, data).noise(coords) + value; - } - - public CNG create(RNG rng, IrisData data) { - return cng.aquire(() -> createNoCache(rng, data, true)); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isFlat() { - return style.equals(NoiseStyle.FLAT); - } - - public double getMaxFractureDistance() { - return multiplier; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisImage.java b/src/main/java/com/volmit/iris/engine/object/IrisImage.java deleted file mode 100644 index 973360f2f..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisImage.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; - -import javax.imageio.ImageIO; -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; - -public class IrisImage extends IrisRegistrant { - private final BufferedImage image; - - public int getWidth() { - return image.getWidth(); - } - - public int getHeight() { - return image.getHeight(); - } - - public int getRawValue(int x, int z) { - if(x >= getWidth() || z >= getHeight() || x < 0 || z < 0) { - return 0; - } - - return image.getRGB(x, z); - } - - public double getValue(IrisImageChannel channel, int x, int z) { - int color = getRawValue(x, z); - - switch(channel) { - case RED -> { - return ((color >> 16) & 0xFF) / 255D; - } - case GREEN -> { - return ((color >> 8) & 0xFF) / 255D; - } - case BLUE -> { - return ((color) & 0xFF) / 255D; - } - case SATURATION -> { - return Color.RGBtoHSB((color >> 16) & 0xFF, (color >> 8) & 0xFF, (color) & 0xFF, null)[1]; - } - case HUE -> { - return Color.RGBtoHSB((color >> 16) & 0xFF, (color >> 8) & 0xFF, (color) & 0xFF, null)[0]; - } - case BRIGHTNESS -> { - return Color.RGBtoHSB((color >> 16) & 0xFF, (color >> 8) & 0xFF, (color) & 0xFF, null)[2]; - } - case COMPOSITE_ADD_RGB -> { - return ((((color >> 16) & 0xFF) / 255D) + (((color >> 8) & 0xFF) / 255D) + (((color) & 0xFF) / 255D)) / 3D; - } - case COMPOSITE_MUL_RGB -> { - return (((color >> 16) & 0xFF) / 255D) * (((color >> 8) & 0xFF) / 255D) * (((color) & 0xFF) / 255D); - } - case COMPOSITE_MAX_RGB -> { - return Math.max(Math.max((((color >> 16) & 0xFF) / 255D), (((color >> 8) & 0xFF) / 255D)), (((color) & 0xFF) / 255D)); - } - case COMPOSITE_ADD_HSB -> { - float[] hsb = Color.RGBtoHSB((color >> 16) & 0xFF, (color >> 8) & 0xFF, (color) & 0xFF, null); - return (hsb[0] + hsb[1] + hsb[2]) / 3D; - } - case COMPOSITE_MUL_HSB -> { - float[] hsb = Color.RGBtoHSB((color >> 16) & 0xFF, (color >> 8) & 0xFF, (color) & 0xFF, null); - return hsb[0] * hsb[1] * hsb[2]; - } - case COMPOSITE_MAX_HSB -> { - float[] hsb = Color.RGBtoHSB((color >> 16) & 0xFF, (color >> 8) & 0xFF, (color) & 0xFF, null); - return Math.max(hsb[0], Math.max(hsb[1], hsb[2])); - } - case RAW -> { - return color; - } - } - - return color; - } - - public IrisImage() { - this(new BufferedImage(4, 4, BufferedImage.TYPE_INT_RGB)); - } - - public IrisImage(BufferedImage image) { - this.image = image; - } - - @Override - public String getFolderName() { - return "images"; - } - - @Override - public String getTypeName() { - return "Image"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } - - public void writeDebug(IrisImageChannel channel) { - - - try { - File at = new File(getLoadFile().getParentFile(), "debug-see-" + getLoadFile().getName()); - BufferedImage b = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); - for(int i = 0; i < getWidth(); i++) { - for(int j = 0; j < getHeight(); j++) { - b.setRGB(i, j, Color.getHSBColor(0, 0, (float) getValue(channel, i, j)).getRGB()); - } - } - ImageIO.write(b, "png", at); - Iris.warn("Debug image written to " + at.getPath() + " for channel " + channel.name()); - } catch(IOException e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisImageChannel.java b/src/main/java/com/volmit/iris/engine/object/IrisImageChannel.java deleted file mode 100644 index dd5405fa7..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisImageChannel.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Determines a derived channel of an image to read") -public enum IrisImageChannel { - @Desc("The red channel of the image") - RED, - @Desc("Thge green channel of the image") - GREEN, - @Desc("The blue channel of the image") - BLUE, - @Desc("The saturation as a channel of the image") - SATURATION, - @Desc("The hue as a channel of the image") - HUE, - @Desc("The brightness as a channel of the image") - BRIGHTNESS, - @Desc("The composite of RGB as a channel of the image. Takes the average channel value (adding)") - COMPOSITE_ADD_RGB, - @Desc("The composite of RGB as a channel of the image. Multiplies the channels") - COMPOSITE_MUL_RGB, - @Desc("The composite of RGB as a channel of the image. Picks the highest channel") - COMPOSITE_MAX_RGB, - @Desc("The composite of HSB as a channel of the image Takes the average channel value (adding)") - COMPOSITE_ADD_HSB, - @Desc("The composite of HSB as a channel of the image Multiplies the channels") - COMPOSITE_MUL_HSB, - @Desc("The composite of HSB as a channel of the image Picks the highest channel") - COMPOSITE_MAX_HSB, - @Desc("The raw value as a channel (probably doesnt look very good)") - RAW -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisImageMap.java b/src/main/java/com/volmit/iris/engine/object/IrisImageMap.java deleted file mode 100644 index 666f18275..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisImageMap.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("carving") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an image map") -@Data -public class IrisImageMap { - @RegistryListResource(IrisImage.class) - @Desc("Define the png image to read in this noise map") - private String image = ""; - - @MinNumber(1) - @Desc("The amount of distance a single pixel is when reading this map, reading x=13, would still read pixel 0 if the scale is 32. You can zoom this externally through noise styles for zooming out.") - private double coordinateScale = 32; - - @Desc("The interpolation method if the coordinateScale is greater than 1. This blends the image into noise. For nearest neighbor, use NONE.") - private InterpolationMethod interpolationMethod = InterpolationMethod.BILINEAR_STARCAST_6; - - @Desc("The channel of the image to read from. This basically converts image data into a number betwen 0 to 1 per pixel using a certain 'channel/filter'") - private IrisImageChannel channel = IrisImageChannel.COMPOSITE_ADD_HSB; - - @Desc("Invert the channel input") - private boolean inverted = false; - - @Desc("Tile the image coordinates") - private boolean tiled = false; - - @Desc("Center 0,0 to the center of the image instead of the top left.") - private boolean centered = true; - - private transient AtomicCache imageCache = new AtomicCache(); - - public double getNoise(IrisData data, int x, int z) { - IrisImage i = imageCache.aquire(() -> data.getImageLoader().load(image)); - if(i == null) { - Iris.error("NULL IMAGE FOR " + image); - } - - return IrisInterpolation.getNoise(interpolationMethod, x, z, coordinateScale, (xx, zz) -> rawNoise(i, xx, zz)); - } - - private double rawNoise(IrisImage i, double x, double z) { - x /= coordinateScale; - z /= coordinateScale; - x = isCentered() ? x + ((i.getWidth() / 2D) * coordinateScale) : x; - z = isCentered() ? z + ((i.getHeight() / 2D) * coordinateScale) : z; - x = isTiled() ? x % i.getWidth() : x; - z = isTiled() ? z % i.getHeight() : z; - double v = i.getValue(getChannel(), (int) x, (int) z); - return isInverted() ? 1D - v : v; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisInterpolator.java b/src/main/java/com/volmit/iris/engine/object/IrisInterpolator.java deleted file mode 100644 index 99c716978..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisInterpolator.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.function.NoiseProvider; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.Objects; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Configures rotation for iris") -@Data -public class IrisInterpolator { - public static final IrisInterpolator DEFAULT = new IrisInterpolator(); - - @Required - @Desc("The interpolation method when two biomes use different heights but this same generator") - private InterpolationMethod function = InterpolationMethod.BILINEAR_STARCAST_6; - - @Required - @MinNumber(1) - @MaxNumber(8192) - @Desc("The range checked horizontally. Smaller ranges yeild more detail but are not as smooth.") - private double horizontalScale = 7; - - @Override - public int hashCode() { - return Objects.hash(horizontalScale, function); - } - - @Override - public boolean equals(Object o) { - if(o instanceof IrisInterpolator i) { - return i.getFunction().equals(function) && i.getHorizontalScale() == horizontalScale; - } - - return false; - } - - public double interpolate(double x, double z, NoiseProvider provider) { - return interpolate((int) Math.round(x), (int) Math.round(z), provider); - } - - public double interpolate(int x, int z, NoiseProvider provider) { - return IrisInterpolation.getNoise(getFunction(), x, z, getHorizontalScale(), provider); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisInterpolator3D.java b/src/main/java/com/volmit/iris/engine/object/IrisInterpolator3D.java deleted file mode 100644 index 09ad75c8a..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisInterpolator3D.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.function.NoiseProvider3; -import com.volmit.iris.util.interpolation.InterpolationMethod3D; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("interpolator-3d") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Configures interpolatin in 3D") -@Data -public class IrisInterpolator3D { - @Required - @Desc("The interpolation method when two biomes use different heights but this same generator") - private InterpolationMethod3D function = InterpolationMethod3D.TRILINEAR; - - @Required - @MinNumber(1) - @MaxNumber(8192) - @Desc("The range checked in all dimensions. Smaller ranges yeild more detail but are not as smooth.") - private double scale = 4; - - public double interpolate(double x, double y, double z, NoiseProvider3 provider) { - return interpolate((int) Math.round(x), (int) Math.round(y), (int) Math.round(z), provider); - } - - public double interpolate(int x, int y, int z, NoiseProvider3 provider) { - return IrisInterpolation.getNoise3D(getFunction(), x, y, z, getScale(), provider); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisJigsawPiece.java b/src/main/java/com/volmit/iris/engine/object/IrisJigsawPiece.java deleted file mode 100644 index c862339f5..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisJigsawPiece.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.util.BlockVector; - -import java.io.IOException; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor - -@Desc("Represents a structure tile") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawPiece extends IrisRegistrant { - @RegistryListResource(IrisObject.class) - @Required - @Desc("The object this piece represents") - private String object = ""; - - @Required - @ArrayType(type = IrisJigsawPieceConnector.class, min = 1) - @Desc("The connectors this object contains") - private KList connectors = new KList<>(); - - @Desc("Configure everything about the object placement. Please don't define this unless you actually need it as using this option will slow down the jigsaw deign stage. Use this where you need it, just avoid using it everywhere to keep things fast.") - private IrisObjectPlacement placementOptions = new IrisObjectPlacement().setMode(ObjectPlaceMode.FAST_MAX_HEIGHT); - - private transient AtomicCache max2dDim = new AtomicCache<>(); - private transient AtomicCache max3dDim = new AtomicCache<>(); - - public int getMax2dDimension() { - return max2dDim.aquire(() -> { - try { - BlockVector v = IrisObject.sampleSize(getLoader().getObjectLoader().findFile(getObject())); - return Math.max(v.getBlockX(), v.getBlockZ()); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return 0; - }); - } - - public int getMax3dDimension() { - return max3dDim.aquire(() -> { - try { - BlockVector v = IrisObject.sampleSize(getLoader().getObjectLoader().findFile(getObject())); - return Math.max(Math.max(v.getBlockX(), v.getBlockZ()), v.getBlockY()); - } catch(IOException e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return -1; - }); - } - - - public IrisJigsawPieceConnector getConnector(IrisPosition relativePosition) { - for(IrisJigsawPieceConnector i : connectors) { - if(i.getPosition().equals(relativePosition)) { - return i; - } - } - - return null; - } - - public IrisJigsawPiece copy() { - IrisJigsawPiece p = new IrisJigsawPiece(); - p.setObject(getObject()); - p.setLoader(getLoader()); - p.setLoadKey(getLoadKey()); - p.setLoadFile(getLoadFile()); - p.setConnectors(new KList<>()); - p.setPlacementOptions(getPlacementOptions()); - - for(IrisJigsawPieceConnector i : getConnectors()) { - p.getConnectors().add(i.copy()); - } - - return p; - } - - public boolean isTerminal() { - return connectors.size() == 1; - } - - public ObjectPlaceMode getPlaceMode() { - return getPlacementOptions().getMode(); - } - - @Override - public String getFolderName() { - return "jigsaw-pieces"; - } - - @Override - public String getTypeName() { - return "Jigsaw Piece"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisJigsawPieceConnector.java b/src/main/java/com/volmit/iris/engine/object/IrisJigsawPieceConnector.java deleted file mode 100644 index 3e4f412d4..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisJigsawPieceConnector.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor - -@Snippet("connector") -@Desc("Represents a structure tile") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawPieceConnector { - @Required - @Desc("The name of this connector, such as entry, or table node. This is a name for organization. Other connectors can specifically use targetName to target a specific connector type. Multiple connectors can use the same name.") - private String name = ""; - - @Required - @Desc("Target a piece's connector with the specified name. For any piece's connector, define * or don't define it.") - private String targetName = "*"; - - @Desc("Rotates the placed piece on this connector. If rotation is enabled, this connector will effectivley rotate, if this connector is facing the Z direction, then the connected piece would rotate in the X,Y direction in 90 degree segments.") - private boolean rotateConnector = false; - - @Desc("If set to true, this connector is allowed to place pieces inside of it's own piece. For example if you are adding a light post, or house on top of a path piece, you would set this to true to allow the piece to collide with the path bounding box.") - private boolean innerConnector = false; - - @RegistryListResource(IrisJigsawPool.class) - @Desc("Pick piece pools to place onto this connector") - @ArrayType(type = String.class, min = 1) - @Required - private KList pools = new KList<>(); - - @RegistryListResource(IrisEntity.class) - @Desc("Pick an entity to spawn on this connector") - private String spawnEntity; - - @Desc("Stop the entity from despawning") - private boolean keepEntity; - - @MaxNumber(50) - @MinNumber(1) - @Desc("The amount of entities to spawn (must be a whole number)") - private int entityCount = 1; - - @Desc("The relative position this connector is located at for connecting to other pieces") - @Required - private IrisPosition position = new IrisPosition(0, 0, 0); - - @Desc("The relative position to this connector to place entities at") - @DependsOn({"spawnEntity"}) - private IrisPosition entityPosition = null; - - @Desc("The direction this connector is facing. If the direction is set to UP, then pieces will place ABOVE the connector.") - @Required - private IrisDirection direction = IrisDirection.UP_POSITIVE_Y; - - public String toString() { - return direction.getFace().name() + "@(" + position.getX() + "," + position.getY() + "," + position.getZ() + ")"; - } - - public IrisJigsawPieceConnector copy() { - IrisJigsawPieceConnector c = new IrisJigsawPieceConnector(); - c.setInnerConnector(isInnerConnector()); - c.setTargetName(getTargetName()); - c.setPosition(getPosition().copy()); - c.setDirection(getDirection()); - c.setRotateConnector(isRotateConnector()); - c.setName(getName()); - c.setSpawnEntity(getSpawnEntity()); - c.setPools(getPools().copy()); - return c; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisJigsawPlacement.java b/src/main/java/com/volmit/iris/engine/object/IrisJigsawPlacement.java deleted file mode 100644 index a60c18603..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisJigsawPlacement.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("jigsaw-placer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a jigsaw placement") -@Data -public class IrisJigsawPlacement { - @RegistryListResource(IrisJigsawStructure.class) - @Required - @Desc("The jigsaw structure to use") - private String structure = ""; - - @Required - @MinNumber(1) - @Desc("The rarity for this jigsaw structure to place on a per chunk basis") - private int rarity = 29; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisJigsawPool.java b/src/main/java/com/volmit/iris/engine/object/IrisJigsawPool.java deleted file mode 100644 index 91cd1ae18..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisJigsawPool.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor - -@Desc("Represents a structure piece pool") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawPool extends IrisRegistrant { - @RegistryListResource(IrisJigsawPiece.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("A list of structure piece pools") - private KList pieces = new KList<>(); - - @Override - public String getFolderName() { - return "jigsaw-pools"; - } - - @Override - public String getTypeName() { - return "Jigsaw Pool"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisJigsawStructure.java b/src/main/java/com/volmit/iris/engine/object/IrisJigsawStructure.java deleted file mode 100644 index 62a26ac81..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisJigsawStructure.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor - -@Desc("Represents a jigsaw structure") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawStructure extends IrisRegistrant { - @RegistryListResource(IrisJigsawPiece.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("The starting pieces. Randomly chooses a starting piece, then connects pieces using the pools define in the starting piece.") - private KList pieces = new KList<>(); - - @MaxNumber(32) - @MinNumber(1) - @Desc("The maximum pieces that can step out from the center piece") - private int maxDepth = 9; - - @Desc("Jigsaw grows the parallax layer which slows iris down a bit. Since there are so many pieces, Iris takes the avg piece size and calculates the parallax radius from that. Unless your structures are using only the biggest pieces, your structure should fit in the chosen size fine. If you are seeing cut-off parts of your structures or broken terrain, turn this option on. This option will pick the biggest piece dimensions and multiply it by your (maxDepth+1) * 2 as the size to grow the parallax layer by. But typically keep this off.") - private boolean useMaxPieceSizeForParallaxRadius = false; - - @Desc("If set to true, iris will look for any pieces with only one connector in valid pools for edge connectors and attach them to 'terminate' the paths/piece connectors. Essentially it caps off ends. For example in a village, Iris would add houses to the ends of roads where possible. For terminators to be selected, they can only have one connector or they wont be chosen.") - private boolean terminate = true; - - @Desc("Override the y range instead of placing on the height map") - private IrisStyledRange overrideYRange = null; - - @Desc("Force Y to a specific value") - private int lockY = -1; - - private transient AtomicCache maxDimension = new AtomicCache<>(); - - private void loadPool(String p, KList pools, KList pieces) { - if(p.isEmpty()) { - return; - } - - IrisJigsawPool pool = getLoader().getJigsawPoolLoader().load(p); - - if(pool == null) { - Iris.warn("Can't find jigsaw pool: " + p); - return; - } - - for(String i : pool.getPieces()) { - if(pieces.addIfMissing(i)) { - loadPiece(i, pools, pieces); - } - } - } - - private void loadPiece(String p, KList pools, KList pieces) { - IrisJigsawPiece piece = getLoader().getJigsawPieceLoader().load(p); - - if(piece == null) { - Iris.warn("Can't find jigsaw piece: " + p); - return; - } - - for(IrisJigsawPieceConnector i : piece.getConnectors()) { - for(String j : i.getPools()) { - if(pools.addIfMissing(j)) { - loadPool(j, pools, pieces); - } - } - } - } - - public int getMaxDimension() { - return maxDimension.aquire(() -> { - if(useMaxPieceSizeForParallaxRadius) { - int max = 0; - KList pools = new KList<>(); - KList pieces = new KList<>(); - - for(String i : getPieces()) { - loadPiece(i, pools, pieces); - } - - for(String i : pieces) { - max = Math.max(max, getLoader().getJigsawPieceLoader().load(i).getMax3dDimension()); - } - - return max * (((getMaxDepth() + 1) * 2) + 1); - } else { - KList pools = new KList<>(); - KList pieces = new KList<>(); - - for(String i : getPieces()) { - loadPiece(i, pools, pieces); - } - - int avg = 0; - - for(String i : pieces) { - avg += getLoader().getJigsawPieceLoader().load(i).getMax2dDimension(); - } - - return (avg / (pieces.size() > 0 ? pieces.size() : 1)) * (((getMaxDepth() + 1) * 2) + 1); - } - }); - } - - @Override - public String getFolderName() { - return "jigsaw-structures"; - } - - @Override - public String getTypeName() { - return "Jigsaw Structure"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisJigsawStructurePlacement.java b/src/main/java/com/volmit/iris/engine/object/IrisJigsawStructurePlacement.java deleted file mode 100644 index 609658e2d..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisJigsawStructurePlacement.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - - -@Snippet("jigsaw-structure-placement") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a jigsaw structure placer") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawStructurePlacement { - @RegistryListResource(IrisJigsawStructure.class) - @Required - @Desc("The structure to place") - private String structure; - - @Required - @Desc("The 1 in X chance rarity") - private int rarity = 100; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisLake.java b/src/main/java/com/volmit/iris/engine/object/IrisLake.java deleted file mode 100644 index ce321e563..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisLake.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("lake") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an Iris Lake") -@Data -public class IrisLake implements IRare { - @Required - @Desc("Typically a 1 in RARITY on a per chunk/fork basis") - @MinNumber(1) - private int rarity = 15; - - @Desc("The width style of this lake") - private IrisShapedGeneratorStyle widthStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN.style(), 5, 9); - - @Desc("The depth style of this lake") - private IrisShapedGeneratorStyle depthStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN.style(), 4, 7); - - @Desc("Define the shape of this lake") - private IrisWorm worm = new IrisWorm(); - - @RegistryListResource(IrisBiome.class) - @Desc("Force this lake to only generate the specified custom biome") - private String customBiome = ""; - - public int getSize(IrisData data) { - return worm.getMaxDistance(); - } - - public void generate(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisLoot.java b/src/main/java/com/volmit/iris/engine/object/IrisLoot.java deleted file mode 100644 index fecc68100..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisLoot.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.ExternalDataSVC; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListItemType; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.TagParser; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftItemStack; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.material.Colorable; - -import java.awt.Color; -import java.util.Optional; - -@Snippet("loot") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a loot entry") -@Data -public class IrisLoot { - private final transient AtomicCache chance = new AtomicCache<>(); - @Desc("The target inventory slot types to fill this loot with") - private InventorySlotType slotTypes = InventorySlotType.STORAGE; - @MinNumber(1) - @Desc("The sub rarity of this loot. Calculated after this loot table has been picked.") - private int rarity = 1; - @MinNumber(1) - @Desc("Minimum amount of this loot") - private int minAmount = 1; - @MinNumber(1) - @Desc("Maximum amount of this loot") - private int maxAmount = 1; - @MinNumber(1) - @Desc("The display name of this item") - private String displayName = null; - @MinNumber(0) - @MaxNumber(1) - @Desc("Minimum durability percent") - private double minDurability = 0; - @MinNumber(0) - @MaxNumber(1) - @Desc("Maximum durability percent") - private double maxDurability = 1; - @Desc("Define a custom model identifier 1.14+ only") - private Integer customModel = null; - @Desc("Set this to true to prevent it from being broken") - private boolean unbreakable = false; - @ArrayType(min = 1, type = ItemFlag.class) - @Desc("The item flags to add") - private KList itemFlags = new KList<>(); - @Desc("Apply enchantments to this item") - @ArrayType(min = 1, type = IrisEnchantment.class) - private KList enchantments = new KList<>(); - @Desc("Apply attribute modifiers to this item") - @ArrayType(min = 1, type = IrisAttributeModifier.class) - private KList attributes = new KList<>(); - @ArrayType(min = 1, type = String.class) - @Desc("Add lore to this item") - private KList lore = new KList<>(); - @RegistryListItemType - @Required - @Desc("This is the item or block type. Does not accept minecraft:*. Only materials such as DIAMOND_SWORD or DIRT.") - private String type = ""; - @Desc("The dye color") - private DyeColor dyeColor = null; - @Desc("The leather armor color") - private String leatherColor = null; - @Desc("Defines a custom NBT Tag for the item.") - private KMap customNbt; - - public Material getType() { - return B.getMaterial(type); - } - - public ItemStack get(boolean debug, RNG rng) { - try { - ItemStack is; - if(!type.startsWith("minecraft:") && type.contains(":")) { - Optional opt = Iris.service(ExternalDataSVC.class).getItemStack(NamespacedKey.fromString(type)); - if(opt.isEmpty()) { - //TODO Better third party provider - Iris.warn("Unknown Material: " + type); - return null; - } - is = opt.get(); - is.setAmount(Math.max(1, rng.i(getMinAmount(), getMaxAmount()))); - } else { - is = new ItemStack(getType(), Math.max(1, rng.i(getMinAmount(), getMaxAmount()))); - } - - ItemMeta m = is.getItemMeta(); - - if(is.getType().getMaxDurability() > 0 && m instanceof Damageable d) { - int max = is.getType().getMaxDurability(); - d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); - } - - for(IrisEnchantment i : getEnchantments()) { - i.apply(rng, m); - } - - for(IrisAttributeModifier i : getAttributes()) { - i.apply(rng, m); - } - - try { - m.setCustomModelData(getCustomModel()); - } catch(Throwable e) { - Iris.reportError(e); - } - m.setLocalizedName(C.translateAlternateColorCodes('&', displayName)); - m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); - m.setUnbreakable(isUnbreakable()); - - for(ItemFlag i : getItemFlags()) { - m.addItemFlags(i); - } - - KList lore = new KList<>(); - - getLore().forEach((i) -> - { - String mf = C.translateAlternateColorCodes('&', i); - - if(mf.length() > 24) { - for(String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) { - lore.add(g.trim()); - } - } else { - lore.add(mf); - } - }); - - if(debug) { - if(lore.isNotEmpty()) { - lore.add(C.GRAY + "--------------------"); - } - - lore.add(C.GRAY + "1 in " + (getRarity()) + " Chance (" + Form.pc(1D / (getRarity()), 5) + ")"); - } - - m.setLore(lore); - - if(getLeatherColor() != null && m instanceof LeatherArmorMeta) { - Color c = Color.decode(getLeatherColor()); - ((LeatherArmorMeta) m).setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue())); - } - - if(getDyeColor() != null && m instanceof Colorable) { - ((Colorable) m).setColor(getDyeColor()); - } - - is.setItemMeta(m); - return applyCustomNbt(is); - } catch(Throwable e) { - Iris.reportError(e); - } - - return new ItemStack(Material.AIR); - } - - public ItemStack get(boolean debug, boolean giveSomething, IrisLootTable table, RNG rng, int x, int y, int z) { - if(debug) { - chance.reset(); - } - - if(giveSomething || chance.aquire(() -> NoiseStyle.STATIC.create(rng)).fit(1, rarity * table.getRarity(), x, y, z) == 1) { - try { - ItemStack is; - if(!type.startsWith("minecraft:") && type.contains(":")) { - Optional opt = Iris.service(ExternalDataSVC.class).getItemStack(NamespacedKey.fromString(type)); - if(opt.isEmpty()) { - Iris.warn("Unknown Material: " + type); - return null; - } - is = opt.get(); - is.setAmount(Math.max(1, rng.i(getMinAmount(), getMaxAmount()))); - return is; - } else { - is = new ItemStack(getType(), Math.max(1, rng.i(getMinAmount(), getMaxAmount()))); - } - - ItemMeta m = is.getItemMeta(); - - if(is.getType().getMaxDurability() > 0 && m instanceof Damageable d) { - int max = is.getType().getMaxDurability(); - d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); - } - - for(IrisEnchantment i : getEnchantments()) { - i.apply(rng, m); - } - - for(IrisAttributeModifier i : getAttributes()) { - i.apply(rng, m); - } - - try { - m.setCustomModelData(getCustomModel()); - } catch(Throwable e) { - Iris.reportError(e); - } - - m.setLocalizedName(C.translateAlternateColorCodes('&', displayName)); - m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); - m.setUnbreakable(isUnbreakable()); - - for(ItemFlag i : getItemFlags()) { - m.addItemFlags(i); - } - - KList lore = new KList<>(); - - getLore().forEach((i) -> - { - String mf = C.translateAlternateColorCodes('&', i); - - if(mf.length() > 24) { - for(String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) { - lore.add(g.trim()); - } - } else { - lore.add(mf); - } - }); - - if(debug) { - if(lore.isNotEmpty()) { - lore.add(C.GRAY + "--------------------"); - } - - lore.add(C.GRAY + "From: " + table.getName() + " (" + Form.pc(1D / table.getRarity(), 5) + ")"); - lore.add(C.GRAY + "1 in " + (table.getRarity() * getRarity()) + " Chance (" + Form.pc(1D / (table.getRarity() * getRarity()), 5) + ")"); - } - - m.setLore(lore); - is.setItemMeta(m); - return applyCustomNbt(is); - } catch(Throwable e) { - //Iris.reportError(e); - e.printStackTrace(); - } - } - - return null; - } - - private ItemStack applyCustomNbt(ItemStack stack) throws CommandSyntaxException { - if(customNbt == null || customNbt.isEmpty()) - return stack; - net.minecraft.world.item.ItemStack s = CraftItemStack.asNMSCopy(stack); - CompoundTag tag = TagParser.parseTag(new JSONObject(customNbt).toString()); - tag.merge(s.getOrCreateTag()); - s.setTag(tag); - return CraftItemStack.asBukkitCopy(s); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisLootMode.java b/src/main/java/com/volmit/iris/engine/object/IrisLootMode.java deleted file mode 100644 index ae205e84e..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisLootMode.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("A loot mode is used to describe what to do with the existing loot layers before adding this loot. Using ADD will simply add this table to the building list of tables (i.e. add dimension tables, region tables then biome tables). By using clear or replace, you remove the parent tables before and add just your tables.") -public enum IrisLootMode { - @Desc("Add to the existing parent loot tables") - ADD, - @Desc("Clear all loot tables then add this table") - CLEAR, - @Desc("Replace all loot tables with this table (same as clear)") - REPLACE -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisLootReference.java b/src/main/java/com/volmit/iris/engine/object/IrisLootReference.java deleted file mode 100644 index 0063dd54c..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisLootReference.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.data.DataProvider; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("loot-registry") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a loot entry") -@Data -public class IrisLootReference { - private final transient AtomicCache> tt = new AtomicCache<>(); - @Desc("Add = add on top of parent tables, Replace = clear first then add these. Clear = Remove all and dont add loot from this or parent.") - private IrisLootMode mode = IrisLootMode.ADD; - @RegistryListResource(IrisLootTable.class) - @ArrayType(min = 1, type = String.class) - @Desc("Add loot table registries here") - private KList tables = new KList<>(); - @MinNumber(0) - @Desc("Increase the chance of loot in this area") - private double multiplier = 1D; - - public KList getLootTables(DataProvider g) { - return tt.aquire(() -> - { - KList t = new KList<>(); - - for(String i : tables) { - t.add(g.getData().getLootLoader().load(i)); - } - - return t; - }); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisLootTable.java b/src/main/java/com/volmit/iris/engine/object/IrisLootTable.java deleted file mode 100644 index 3e18957f8..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisLootTable.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a loot table. Biomes, Regions & Objects can add or replace the virtual table with these loot tables") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisLootTable extends IrisRegistrant { - @Required - @Desc("The name of this loot table") - @MinNumber(2) - private String name = ""; - - @MinNumber(1) - @Desc("The rarity as in 1 in X chance") - private int rarity = 1; - - @MinNumber(1) - @Desc("The maximum amount of loot that can be picked in this table at a time.") - private int maxPicked = 5; - - @MinNumber(0) - @Desc("The minimum amount of loot that can be picked in this table at a time.") - private int minPicked = 1; - - @Desc("The loot in this table") - @ArrayType(min = 1, type = IrisLoot.class) - private KList loot = new KList<>(); - - public KList getLoot(boolean debug, boolean doSomething, RNG rng, InventorySlotType slot, int x, int y, int z, int gg, int ffs) { - KList lootf = new KList<>(); - - int m = 0; - int mx = rng.i(getMinPicked(), getMaxPicked()); - - while(m < mx) { - int num = rng.i(loot.size()); - - IrisLoot l = loot.get(num); - - if(l.getSlotTypes() == slot) { - ItemStack item = l.get(debug, false, this, rng, x, y, z); - - if(item != null && item.getType() != Material.AIR) { - lootf.add(item); - m++; - } - } - } - - return lootf; - } - - @Override - public String getFolderName() { - return "loot"; - } - - @Override - public String getTypeName() { - return "Loot"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisMarker.java b/src/main/java/com/volmit/iris/engine/object/IrisMarker.java deleted file mode 100644 index fc0c7eef9..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisMarker.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Represents a marker") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisMarker extends IrisRegistrant { - @Desc("A list of spawners to add to anywhere this marker is.") - @RegistryListResource(IrisSpawner.class) - @ArrayType(type = String.class, min = 1) - private KList spawners = new KList<>(); - - @Desc("Remove this marker when the block it's assigned to is changed.") - private boolean removeOnChange = true; - - @Desc("If true, markers will only be placed here if there is 2 air blocks above it.") - private boolean emptyAbove = true; - - @Desc("If this marker is used, what is the chance it removes itself. For example 25% (0.25) would mean that on average 4 uses will remove a specific marker. Set this below 0 (-1) to never exhaust & set this to 1 or higher to always exhaust on first use.") - private double exhaustionChance = 0.33; - - public boolean shouldExhaust() { - return RNG.r.chance(exhaustionChance); - } - - @Override - public String getFolderName() { - return "markers"; - } - - @Override - public String getTypeName() { - return "Marker"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisMaterialPalette.java b/src/main/java/com/volmit/iris/engine/object/IrisMaterialPalette.java deleted file mode 100644 index 24dbf0419..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisMaterialPalette.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -import java.util.Optional; - -@Snippet("palette") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A palette of materials") -@Data -public class IrisMaterialPalette { - private final transient AtomicCache> blockData = new AtomicCache<>(); - private final transient AtomicCache layerGenerator = new AtomicCache<>(); - private final transient AtomicCache heightGenerator = new AtomicCache<>(); - @Desc("The style of noise") - private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); - @MinNumber(0.0001) - @Desc("The terrain zoom mostly for zooming in on a wispy palette") - private double zoom = 5; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks to be used in this layer") - private KList palette = new KList().qadd(new IrisBlockData("STONE")); - - public BlockData get(RNG rng, double x, double y, double z, IrisData rdata) { - if(getBlockData(rdata).isEmpty()) { - return null; - } - - if(getBlockData(rdata).size() == 1) { - return getBlockData(rdata).get(0); - } - - return getLayerGenerator(rng, rdata).fit(getBlockData(rdata), x / zoom, y / zoom, z / zoom); - } - - public Optional> getTile(RNG rng, double x, double y, double z, IrisData rdata) { - if(getBlockData(rdata).isEmpty()) - return Optional.empty(); - - TileData tile = getBlockData(rdata).size() == 1 ? palette.get(0).tryGetTile() : palette.getRandom(rng).tryGetTile(); - return tile != null ? Optional.of(tile) : Optional.empty(); - } - - public CNG getLayerGenerator(RNG rng, IrisData rdata) { - return layerGenerator.aquire(() -> - { - RNG rngx = rng.nextParallelRNG(-23498896 + getBlockData(rdata).size()); - return style.create(rngx, rdata); - }); - } - - public IrisMaterialPalette qclear() { - palette.clear(); - return this; - } - - public KList add(String b) { - palette.add(new IrisBlockData(b)); - - return palette; - } - - public IrisMaterialPalette qadd(String b) { - palette.add(new IrisBlockData(b)); - - return this; - } - - public KList getBlockData(IrisData rdata) { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for(IrisBlockData ix : palette) { - BlockData bx = ix.getBlockData(rdata); - if(bx != null) { - for(int i = 0; i < ix.getWeight(); i++) { - blockData.add(bx); - } - } - } - - return blockData; - }); - } - - public IrisMaterialPalette zero() { - palette.clear(); - return this; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisMod.java b/src/main/java/com/volmit/iris/engine/object/IrisMod.java deleted file mode 100644 index 53cff7298..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisMod.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Represents a dimension") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisMod extends IrisRegistrant { - @MinNumber(2) - @Required - @Desc("The human readable name of this dimension") - private String name = "A Dimension Mod"; - - @Desc("If this mod only works with a specific dimension, define it's load key here. Such as overworld, or flat. Otherwise iris will assume this mod works with anything.") - private String forDimension = ""; - - @MinNumber(-1) - @MaxNumber(512) - @Desc("Override the fluid height. Otherwise set it to -1") - private int overrideFluidHeight = -1; - - @Desc("A list of biomes to remove") - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class, min = 1) - private KList removeBiomes = new KList<>(); - - @Desc("A list of objects to remove") - @RegistryListResource(IrisObject.class) - @ArrayType(type = String.class, min = 1) - private KList removeObjects = new KList<>(); - - @Desc("A list of regions to remove") - @RegistryListResource(IrisRegion.class) - @ArrayType(type = String.class, min = 1) - private KList removeRegions = new KList<>(); - - @Desc("A list of regions to inject") - @RegistryListResource(IrisRegion.class) - @ArrayType(type = String.class, min = 1) - private KList injectRegions = new KList<>(); - - @ArrayType(min = 1, type = IrisModBiomeInjector.class) - @Desc("Inject biomes into existing regions") - private KList biomeInjectors = new KList<>(); - - @ArrayType(min = 1, type = IrisModBiomeReplacer.class) - @Desc("Replace biomes with other biomes") - private KList biomeReplacers = new KList<>(); - - @ArrayType(min = 1, type = IrisModObjectReplacer.class) - @Desc("Replace objects with other objects") - private KList objectReplacers = new KList<>(); - - @ArrayType(min = 1, type = IrisModObjectPlacementBiomeInjector.class) - @Desc("Inject placers into existing biomes") - private KList biomeObjectPlacementInjectors = new KList<>(); - - @ArrayType(min = 1, type = IrisModObjectPlacementRegionInjector.class) - @Desc("Inject placers into existing regions") - private KList regionObjectPlacementInjectors = new KList<>(); - - @ArrayType(min = 1, type = IrisModRegionReplacer.class) - @Desc("Replace biomes with other biomes") - private KList regionReplacers = new KList<>(); - - @ArrayType(min = 1, type = IrisObjectReplace.class) - @Desc("Replace blocks with other blocks") - private KList blockReplacers = new KList<>(); - - @ArrayType(min = 1, type = IrisModNoiseStyleReplacer.class) - @Desc("Replace noise styles with other styles") - private KList styleReplacers = new KList<>(); - - @Override - public String getFolderName() { - return "mods"; - } - - @Override - public String getTypeName() { - return "Mod"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisModBiomeInjector.java b/src/main/java/com/volmit/iris/engine/object/IrisModBiomeInjector.java deleted file mode 100644 index 7beb598f6..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisModBiomeInjector.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("biome-injector") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A biome injector") -@Data -public class IrisModBiomeInjector { - @Required - @Desc("The region to find") - @RegistryListResource(IrisRegion.class) - private String region = ""; - - @Required - @Desc("A biome to inject into the region") - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class, min = 1) - private KList inject = new KList<>(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisModBiomeReplacer.java b/src/main/java/com/volmit/iris/engine/object/IrisModBiomeReplacer.java deleted file mode 100644 index a0142ef68..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisModBiomeReplacer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("biome-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A biome replacer") -@Data -public class IrisModBiomeReplacer { - @Required - @Desc("A list of biomes to find") - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class, min = 1) - private KList find = new KList<>(); - - @Required - @Desc("A biome to replace it with") - @RegistryListResource(IrisBiome.class) - private String replace = ""; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisModNoiseStyleReplacer.java b/src/main/java/com/volmit/iris/engine/object/IrisModNoiseStyleReplacer.java deleted file mode 100644 index a873087ae..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisModNoiseStyleReplacer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("noise-style-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A noise style replacer") -@Data -public class IrisModNoiseStyleReplacer { - @Required - @Desc("A noise style to find") - @ArrayType(type = String.class, min = 1) - private NoiseStyle find = NoiseStyle.IRIS; - - @Required - @Desc("If replaceTypeOnly is set to true, Iris will keep the existing generator style and only replace the type itself. Otherwise it will use the replace tag for every style using the find type.") - private boolean replaceTypeOnly = false; - - @Required - @Desc("A noise style to replace it with") - @RegistryListResource(IrisBiome.class) - private IrisGeneratorStyle replace = new IrisGeneratorStyle(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisModObjectPlacementBiomeInjector.java b/src/main/java/com/volmit/iris/engine/object/IrisModObjectPlacementBiomeInjector.java deleted file mode 100644 index 19174e0ea..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisModObjectPlacementBiomeInjector.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-placement-biome-injector") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("An object placement injector") -@Data -public class IrisModObjectPlacementBiomeInjector { - @Required - @Desc("The biome to find") - @RegistryListResource(IrisBiome.class) - private String biome = ""; - - @Required - @Desc("A biome to inject into the region") - @ArrayType(type = IrisObjectPlacement.class, min = 1) - private KList place = new KList<>(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisModObjectPlacementRegionInjector.java b/src/main/java/com/volmit/iris/engine/object/IrisModObjectPlacementRegionInjector.java deleted file mode 100644 index b49f93a69..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisModObjectPlacementRegionInjector.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-placement-region-injector") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("An object placement injector") -@Data -public class IrisModObjectPlacementRegionInjector { - @Required - @Desc("The biome to find") - @RegistryListResource(IrisRegion.class) - private String biome = ""; - - @Required - @Desc("A biome to inject into the region") - @ArrayType(type = IrisObjectPlacement.class, min = 1) - private KList place = new KList<>(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisModObjectReplacer.java b/src/main/java/com/volmit/iris/engine/object/IrisModObjectReplacer.java deleted file mode 100644 index 11348a2e3..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisModObjectReplacer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A biome replacer") -@Data -public class IrisModObjectReplacer { - @Required - @Desc("A list of objects to find") - @RegistryListResource(IrisObject.class) - @ArrayType(type = String.class, min = 1) - private KList find = new KList<>(); - - @Required - @Desc("An object to replace it with") - @RegistryListResource(IrisBiome.class) - private String replace = ""; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisModRegionReplacer.java b/src/main/java/com/volmit/iris/engine/object/IrisModRegionReplacer.java deleted file mode 100644 index f8eb96261..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisModRegionReplacer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("region-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A region replacer") -@Data -public class IrisModRegionReplacer { - @Required - @Desc("A list of regions to find") - @RegistryListResource(IrisRegion.class) - @ArrayType(type = String.class, min = 1) - private KList find = new KList<>(); - - @Required - @Desc("A region to replace it with") - @RegistryListResource(IrisRegion.class) - private String replace = ""; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisNoiseGenerator.java b/src/main/java/com/volmit/iris/engine/object/IrisNoiseGenerator.java deleted file mode 100644 index db0f33f35..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisNoiseGenerator.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("generator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A noise generator") -@Data -public class IrisNoiseGenerator { - private final transient AtomicCache generator = new AtomicCache<>(); - @MinNumber(0.0001) - @Desc("The coordinate input zoom") - private double zoom = 1; - @Desc("Reverse the output. So that noise = -noise + opacity") - private boolean negative = false; - @MinNumber(0) - @MaxNumber(1) - @Desc("The output multiplier") - private double opacity = 1; - @Desc("Coordinate offset x") - private double offsetX = 0; - @Desc("Height output offset y. Avoid using with terrain generation.") - private double offsetY = 0; - @Desc("Coordinate offset z") - private double offsetZ = 0; - @Required - @Desc("The seed") - private long seed = 0; - @Desc("Apply a parametric curve on the output") - private boolean parametric = false; - @Desc("Apply a bezier curve on the output") - private boolean bezier = false; - @Desc("Apply a sin-center curve on the output (0, and 1 = 0 and 0.5 = 1.0 using a sinoid shape.)") - private boolean sinCentered = false; - @Desc("The exponent noise^EXPONENT") - private double exponent = 1; - @Desc("Enable / disable. Outputs offsetY if disabled") - private boolean enabled = true; - @Required - @Desc("The Noise Style") - private IrisGeneratorStyle style = NoiseStyle.IRIS.style(); - @MinNumber(1) - @Desc("Multiple octaves for multple generators of changing zooms added together") - private int octaves = 1; - @ArrayType(min = 1, type = IrisNoiseGenerator.class) - @Desc("Apply a child noise generator to fracture the input coordinates of this generator") - private KList fracture = new KList<>(); - - public IrisNoiseGenerator(boolean enabled) { - this(); - this.enabled = enabled; - } - - protected CNG getGenerator(long superSeed, IrisData data) { - return generator.aquire(() -> style.create(new RNG(superSeed + 33955677 - seed), data).oct(octaves)); - } - - public double getMax() { - return getOffsetY() + opacity; - } - - public double getNoise(long superSeed, double xv, double zv, IrisData data) { - if(!enabled) { - return offsetY; - } - - double x = xv; - double z = zv; - int g = 33; - - for(IrisNoiseGenerator i : fracture) { - if(i.isEnabled()) { - x += i.getNoise(superSeed + seed + g, xv, zv, data) - (opacity / 2D); - z -= i.getNoise(superSeed + seed + g, zv, xv, data) - (opacity / 2D); - } - g += 819; - } - - double n = getGenerator(superSeed, data).fitDouble(0, opacity, (x / zoom) + offsetX, (z / zoom) + offsetZ); - n = negative ? (-n + opacity) : n; - n = (exponent != 1 ? n < 0 ? -Math.pow(-n, exponent) : Math.pow(n, exponent) : n) + offsetY; - n = parametric ? IrisInterpolation.parametric(n, 1) : n; - n = bezier ? IrisInterpolation.bezier(n) : n; - n = sinCentered ? IrisInterpolation.sinCenter(n) : n; - - return n; - } - - public KList getAllComposites() { - KList g = new KList<>(); - - g.add(this); - - for(IrisNoiseGenerator i : getFracture()) { - g.addAll(i.getAllComposites()); - } - - return g; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObject.java b/src/main/java/com/volmit/iris/engine/object/IrisObject.java deleted file mode 100644 index 5a5c2c059..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObject.java +++ /dev/null @@ -1,1172 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.placer.HeightmapObjectPlacer; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.AxisAlignedBB; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterMarker; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.IrisLock; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import lombok.experimental.Accessors; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Waterlogged; -import org.bukkit.block.data.type.Leaves; -import org.bukkit.util.BlockVector; -import org.bukkit.util.Vector; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; - -@Accessors(chain = true) -@EqualsAndHashCode(callSuper = false) -public class IrisObject extends IrisRegistrant { - protected static final Vector HALF = new Vector(0.5, 0.5, 0.5); - protected static final BlockData AIR = B.get("CAVE_AIR"); - protected static final BlockData VAIR = B.get("VOID_AIR"); - protected static final BlockData VAIR_DEBUG = B.get("COBWEB"); - protected static final BlockData[] SNOW_LAYERS = new BlockData[] {B.get("minecraft:snow[layers=1]"), B.get("minecraft:snow[layers=2]"), B.get("minecraft:snow[layers=3]"), B.get("minecraft:snow[layers=4]"), B.get("minecraft:snow[layers=5]"), B.get("minecraft:snow[layers=6]"), B.get("minecraft:snow[layers=7]"), B.get("minecraft:snow[layers=8]")}; - protected transient final IrisLock readLock = new IrisLock("read-conclock"); - @Getter - @Setter - protected transient volatile boolean smartBored = false; - @Getter - @Setter - protected transient IrisLock lock = new IrisLock("Preloadcache"); - @Setter - protected transient AtomicCache aabb = new AtomicCache<>(); - private KMap blocks; - private KMap> states; - @Getter - @Setter - private int w; - @Getter - @Setter - private int d; - @Getter - @Setter - private int h; - @Getter - @Setter - private transient BlockVector center; - - public IrisObject(int w, int h, int d) { - blocks = new KMap<>(); - states = new KMap<>(); - this.w = w; - this.h = h; - this.d = d; - center = new BlockVector(w / 2, h / 2, d / 2); - } - - public IrisObject() { - this(0, 0, 0); - } - - public static BlockVector getCenterForSize(BlockVector size) { - return new BlockVector(size.getX() / 2, size.getY() / 2, size.getZ() / 2); - } - - public static AxisAlignedBB getAABBFor(BlockVector size) { - BlockVector center = new BlockVector(size.getX() / 2, size.getY() / 2, size.getZ() / 2); - return new AxisAlignedBB(new IrisPosition(new BlockVector(0, 0, 0).subtract(center).toBlockVector()), - new IrisPosition(new BlockVector(size.getX() - 1, size.getY() - 1, size.getZ() - 1).subtract(center).toBlockVector())); - } - - @SuppressWarnings({"resource", "RedundantSuppression"}) - public static BlockVector sampleSize(File file) throws IOException { - FileInputStream in = new FileInputStream(file); - DataInputStream din = new DataInputStream(in); - BlockVector bv = new BlockVector(din.readInt(), din.readInt(), din.readInt()); - Iris.later(din::close); - return bv; - } - - private static List blocksBetweenTwoPoints(Vector loc1, Vector loc2) { - List locations = new ArrayList<>(); - int topBlockX = Math.max(loc1.getBlockX(), loc2.getBlockX()); - int bottomBlockX = Math.min(loc1.getBlockX(), loc2.getBlockX()); - int topBlockY = Math.max(loc1.getBlockY(), loc2.getBlockY()); - int bottomBlockY = Math.min(loc1.getBlockY(), loc2.getBlockY()); - int topBlockZ = Math.max(loc1.getBlockZ(), loc2.getBlockZ()); - int bottomBlockZ = Math.min(loc1.getBlockZ(), loc2.getBlockZ()); - - for(int x = bottomBlockX; x <= topBlockX; x++) { - for(int z = bottomBlockZ; z <= topBlockZ; z++) { - for(int y = bottomBlockY; y <= topBlockY; y++) { - locations.add(new BlockVector(x, y, z)); - } - } - } - return locations; - } - - public AxisAlignedBB getAABB() { - return aabb.aquire(() -> getAABBFor(new BlockVector(w, h, d))); - } - - public void ensureSmartBored(boolean debug) { - if(smartBored) { - return; - } - - PrecisionStopwatch p = PrecisionStopwatch.start(); - BlockData vair = debug ? VAIR_DEBUG : VAIR; - lock.lock(); - AtomicInteger applied = new AtomicInteger(); - if(getBlocks().isEmpty()) { - lock.unlock(); - Iris.warn("Cannot Smart Bore " + getLoadKey() + " because it has 0 blocks in it."); - smartBored = true; - return; - } - - BlockVector max = new BlockVector(Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE); - BlockVector min = new BlockVector(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); - - for(BlockVector i : getBlocks().keySet()) { - max.setX(Math.max(i.getX(), max.getX())); - min.setX(Math.min(i.getX(), min.getX())); - max.setY(Math.max(i.getY(), max.getY())); - min.setY(Math.min(i.getY(), min.getY())); - max.setZ(Math.max(i.getZ(), max.getZ())); - min.setZ(Math.min(i.getZ(), min.getZ())); - } - - BurstExecutor burst = MultiBurst.burst.burst(); - - // Smash X - for(int rayY = min.getBlockY(); rayY <= max.getBlockY(); rayY++) { - int finalRayY = rayY; - burst.queue(() -> { - for(int rayZ = min.getBlockZ(); rayZ <= max.getBlockZ(); rayZ++) { - int start = Integer.MAX_VALUE; - int end = Integer.MIN_VALUE; - - for(int ray = min.getBlockX(); ray <= max.getBlockX(); ray++) { - if(getBlocks().containsKey(new BlockVector(ray, finalRayY, rayZ))) { - start = Math.min(ray, start); - end = Math.max(ray, end); - } - } - - if(start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) { - for(int i = start; i <= end; i++) { - BlockVector v = new BlockVector(i, finalRayY, rayZ); - - if(!B.isAir(getBlocks().get(v))) { - getBlocks().computeIfAbsent(v, (vv) -> vair); - applied.getAndIncrement(); - } - } - } - } - }); - } - - // Smash Y - for(int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) { - int finalRayX = rayX; - burst.queue(() -> { - for(int rayZ = min.getBlockZ(); rayZ <= max.getBlockZ(); rayZ++) { - int start = Integer.MAX_VALUE; - int end = Integer.MIN_VALUE; - - for(int ray = min.getBlockY(); ray <= max.getBlockY(); ray++) { - if(getBlocks().containsKey(new BlockVector(finalRayX, ray, rayZ))) { - start = Math.min(ray, start); - end = Math.max(ray, end); - } - } - - if(start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) { - for(int i = start; i <= end; i++) { - BlockVector v = new BlockVector(finalRayX, i, rayZ); - - if(!B.isAir(getBlocks().get(v))) { - getBlocks().computeIfAbsent(v, (vv) -> vair); - applied.getAndIncrement(); - } - } - } - } - }); - } - - // Smash Z - for(int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) { - int finalRayX = rayX; - burst.queue(() -> { - for(int rayY = min.getBlockY(); rayY <= max.getBlockY(); rayY++) { - int start = Integer.MAX_VALUE; - int end = Integer.MIN_VALUE; - - for(int ray = min.getBlockZ(); ray <= max.getBlockZ(); ray++) { - if(getBlocks().containsKey(new BlockVector(finalRayX, rayY, ray))) { - start = Math.min(ray, start); - end = Math.max(ray, end); - } - } - - if(start != Integer.MAX_VALUE && end != Integer.MIN_VALUE) { - for(int i = start; i <= end; i++) { - BlockVector v = new BlockVector(finalRayX, rayY, i); - - if(!B.isAir(getBlocks().get(v))) { - getBlocks().computeIfAbsent(v, (vv) -> vair); - applied.getAndIncrement(); - } - } - } - } - }); - } - - burst.complete(); - smartBored = true; - lock.unlock(); - Iris.debug("Smart Bore: " + getLoadKey() + " in " + Form.duration(p.getMilliseconds(), 2) + " (" + Form.f(applied.get()) + ")"); - } - - public synchronized IrisObject copy() { - IrisObject o = new IrisObject(w, h, d); - o.setLoadKey(o.getLoadKey()); - o.setCenter(getCenter().clone()); - - for(BlockVector i : getBlocks().keySet()) { - o.getBlocks().put(i.clone(), Objects.requireNonNull(getBlocks().get(i)).clone()); - } - - for(BlockVector i : getStates().keySet()) { - o.getStates().put(i.clone(), Objects.requireNonNull(getStates().get(i)).clone()); - } - - return o; - } - - public void readLegacy(InputStream in) throws IOException { - DataInputStream din = new DataInputStream(in); - this.w = din.readInt(); - this.h = din.readInt(); - this.d = din.readInt(); - center = new BlockVector(w / 2, h / 2, d / 2); - int s = din.readInt(); - - for(int i = 0; i < s; i++) { - getBlocks().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), B.get(din.readUTF())); - } - - try { - int size = din.readInt(); - - for(int i = 0; i < size; i++) { - getStates().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din)); - } - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - public void read(InputStream in) throws Throwable { - DataInputStream din = new DataInputStream(in); - this.w = din.readInt(); - this.h = din.readInt(); - this.d = din.readInt(); - if(!din.readUTF().equals("Iris V2 IOB;")) { - return; - } - center = new BlockVector(w / 2, h / 2, d / 2); - int s = din.readShort(); - int i; - KList palette = new KList<>(); - - for(i = 0; i < s; i++) { - palette.add(din.readUTF()); - } - - s = din.readInt(); - - for(i = 0; i < s; i++) { - getBlocks().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), B.get(palette.get(din.readShort()))); - } - - s = din.readInt(); - - for(i = 0; i < s; i++) { - getStates().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din)); - } - } - - public void write(OutputStream o) throws IOException { - DataOutputStream dos = new DataOutputStream(o); - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(d); - dos.writeUTF("Iris V2 IOB;"); - KList palette = new KList<>(); - - for(BlockData i : getBlocks().values()) { - palette.addIfMissing(i.getAsString()); - } - - dos.writeShort(palette.size()); - - for(String i : palette) { - dos.writeUTF(i); - } - - dos.writeInt(getBlocks().size()); - - for(BlockVector i : getBlocks().keySet()) { - dos.writeShort(i.getBlockX()); - dos.writeShort(i.getBlockY()); - dos.writeShort(i.getBlockZ()); - dos.writeShort(palette.indexOf(getBlocks().get(i).getAsString())); - } - - dos.writeInt(getStates().size()); - for(BlockVector i : getStates().keySet()) { - dos.writeShort(i.getBlockX()); - dos.writeShort(i.getBlockY()); - dos.writeShort(i.getBlockZ()); - getStates().get(i).toBinary(dos); - } - } - - public void read(File file) throws IOException { - FileInputStream fin = new FileInputStream(file); - try { - read(fin); - fin.close(); - } catch(Throwable e) { - Iris.reportError(e); - fin.close(); - fin = new FileInputStream(file); - readLegacy(fin); - fin.close(); - } - } - - public void write(File file) throws IOException { - if(file == null) { - return; - } - - FileOutputStream out = new FileOutputStream(file); - write(out); - out.close(); - } - - public void shrinkwrap() { - BlockVector min = new BlockVector(); - BlockVector max = new BlockVector(); - - for(BlockVector i : getBlocks().keySet()) { - min.setX(Math.min(min.getX(), i.getX())); - min.setY(Math.min(min.getY(), i.getY())); - min.setZ(Math.min(min.getZ(), i.getZ())); - max.setX(Math.max(max.getX(), i.getX())); - max.setY(Math.max(max.getY(), i.getY())); - max.setZ(Math.max(max.getZ(), i.getZ())); - } - - w = max.getBlockX() - min.getBlockX(); - h = max.getBlockY() - min.getBlockY(); - d = max.getBlockZ() - min.getBlockZ(); - } - - public void clean() { - KMap d = new KMap<>(); - - for(BlockVector i : getBlocks().keySet()) { - d.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getBlocks().get(i))); - } - - KMap> dx = new KMap<>(); - - for(BlockVector i : getBlocks().keySet()) { - d.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getBlocks().get(i))); - } - - for(BlockVector i : getStates().keySet()) { - dx.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getStates().get(i))); - } - - blocks = d; - states = dx; - } - - public BlockVector getSigned(int x, int y, int z) { - if(x >= w || y >= h || z >= d) { - throw new RuntimeException(x + " " + y + " " + z + " exceeds limit of " + w + " " + h + " " + d); - } - - return new BlockVector(x, y, z).subtract(center).toBlockVector(); - } - - public void setUnsigned(int x, int y, int z, BlockData block) { - BlockVector v = getSigned(x, y, z); - - if(block == null) { - getBlocks().remove(v); - getStates().remove(v); - } else { - getBlocks().put(v, block); - } - } - - public void setUnsigned(int x, int y, int z, Block block) { - BlockVector v = getSigned(x, y, z); - - if(block == null) { - getBlocks().remove(v); - getStates().remove(v); - } else { - BlockData data = block.getBlockData(); - getBlocks().put(v, data); - TileData state = TileData.getTileState(block); - if(state != null) { - Iris.info("Saved State " + v); - getStates().put(v, state); - } - } - } - - public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) { - return place(x, -1, z, placer, config, rng, rdata); - } - - public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, CarveResult c, IrisData rdata) { - return place(x, -1, z, placer, config, rng, null, c, rdata); - } - - public int place(int x, int yv, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) { - return place(x, yv, z, placer, config, rng, null, null, rdata); - } - - public int place(Location loc, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) { - return place(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), placer, config, rng, rdata); - } - - public int place(int x, int yv, int z, IObjectPlacer oplacer, IrisObjectPlacement config, RNG rng, Consumer listener, CarveResult c, IrisData rdata) { - IObjectPlacer placer = (config.getHeightmap() != null) ? new HeightmapObjectPlacer(oplacer.getEngine() == null ? IrisContext.get().getEngine() : oplacer.getEngine(), rng, x, yv, z, config, oplacer) : oplacer; - - if(config.isSmartBore()) { - ensureSmartBored(placer.isDebugSmartBore()); - } - - boolean warped = !config.getWarp().isFlat(); - boolean stilting = (config.getMode().equals(ObjectPlaceMode.STILT) || config.getMode().equals(ObjectPlaceMode.FAST_STILT) || - config.getMode() == ObjectPlaceMode.MIN_STILT || config.getMode() == ObjectPlaceMode.FAST_MIN_STILT || - config.getMode() == ObjectPlaceMode.CENTER_STILT); - KMap heightmap = config.getSnow() > 0 ? new KMap<>() : null; - int spinx = rng.imax() / 1000; - int spiny = rng.imax() / 1000; - int spinz = rng.imax() / 1000; - int rty = config.getRotation().rotate(new BlockVector(0, getCenter().getBlockY(), 0), spinx, spiny, spinz).getBlockY(); - int ty = config.getTranslate().translate(new BlockVector(0, getCenter().getBlockY(), 0), config.getRotation(), spinx, spiny, spinz).getBlockY(); - int y = -1; - int xx, zz; - int yrand = config.getTranslate().getYRandom(); - yrand = yrand > 0 ? rng.i(0, yrand) : yrand < 0 ? rng.i(yrand, 0) : yrand; - boolean bail = false; - - if(yv < 0) { - if(config.getMode().equals(ObjectPlaceMode.CENTER_HEIGHT) || config.getMode() == ObjectPlaceMode.CENTER_STILT) { - y = (c != null ? c.getSurface() : placer.getHighest(x, z, getLoader(), config.isUnderwater())) + rty; - if(placer.isCarved(x, y, z) || placer.isCarved(x, y - 1, z) || placer.isCarved(x, y - 2, z) || placer.isCarved(x, y - 3, z)) { - bail = true; - } - } else if(config.getMode().equals(ObjectPlaceMode.MAX_HEIGHT) || config.getMode().equals(ObjectPlaceMode.STILT)) { - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); - int xLength = (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); - int minX = Math.min(x - xLength, x + xLength); - int maxX = Math.max(x - xLength, x + xLength); - int zLength = (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); - int minZ = Math.min(z - zLength, z + zLength); - int maxZ = Math.max(z - zLength, z + zLength); - for(int i = minX; i <= maxX; i++) { - for(int ii = minZ; ii <= maxZ; ii++) { - int h = placer.getHighest(i, ii, getLoader(), config.isUnderwater()) + rty; - if(placer.isCarved(i, h, ii) || placer.isCarved(i, h - 1, ii) || placer.isCarved(i, h - 2, ii) || placer.isCarved(i, h - 3, ii)) { - bail = true; - break; - } - if(h > y) - y = h; - } - } - } else if(config.getMode().equals(ObjectPlaceMode.FAST_MAX_HEIGHT) || config.getMode().equals(ObjectPlaceMode.FAST_STILT)) { - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); - - int xRadius = (rotatedDimensions.getBlockX() / 2); - int xLength = xRadius + offset.getBlockX(); - int minX = Math.min(x - xLength, x + xLength); - int maxX = Math.max(x - xLength, x + xLength); - int zRadius = (rotatedDimensions.getBlockZ() / 2); - int zLength = zRadius + offset.getBlockZ(); - int minZ = Math.min(z - zLength, z + zLength); - int maxZ = Math.max(z - zLength, z + zLength); - - for(int i = minX; i <= maxX; i += Math.abs(xRadius) + 1) { - for(int ii = minZ; ii <= maxZ; ii += Math.abs(zRadius) + 1) { - int h = placer.getHighest(i, ii, getLoader(), config.isUnderwater()) + rty; - if(placer.isCarved(i, h, ii) || placer.isCarved(i, h - 1, ii) || placer.isCarved(i, h - 2, ii) || placer.isCarved(i, h - 3, ii)) { - bail = true; - break; - } - if(h > y) - y = h; - } - } - } else if(config.getMode().equals(ObjectPlaceMode.MIN_HEIGHT) || config.getMode() == ObjectPlaceMode.MIN_STILT) { - y = rdata.getEngine().getHeight() + 1; - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); - - int xLength = (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); - int minX = Math.min(x - xLength, x + xLength); - int maxX = Math.max(x - xLength, x + xLength); - int zLength = (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); - int minZ = Math.min(z - zLength, z + zLength); - int maxZ = Math.max(z - zLength, z + zLength); - for(int i = minX; i <= maxX; i++) { - for(int ii = minZ; ii <= maxZ; ii++) { - int h = placer.getHighest(i, ii, getLoader(), config.isUnderwater()) + rty; - if(placer.isCarved(i, h, ii) || placer.isCarved(i, h - 1, ii) || placer.isCarved(i, h - 2, ii) || placer.isCarved(i, h - 3, ii)) { - bail = true; - break; - } - if(h < y) { - y = h; - } - } - } - } else if(config.getMode().equals(ObjectPlaceMode.FAST_MIN_HEIGHT) || config.getMode() == ObjectPlaceMode.FAST_MIN_STILT) { - y = rdata.getEngine().getHeight() + 1; - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); - - int xRadius = (rotatedDimensions.getBlockX() / 2); - int xLength = xRadius + offset.getBlockX(); - int minX = Math.min(x - xLength, x + xLength); - int maxX = Math.max(x - xLength, x + xLength); - int zRadius = (rotatedDimensions.getBlockZ() / 2); - int zLength = zRadius + offset.getBlockZ(); - int minZ = Math.min(z - zLength, z + zLength); - int maxZ = Math.max(z - zLength, z + zLength); - - for(int i = minX; i <= maxX; i += Math.abs(xRadius) + 1) { - for(int ii = minZ; ii <= maxZ; ii += Math.abs(zRadius) + 1) { - int h = placer.getHighest(i, ii, getLoader(), config.isUnderwater()) + rty; - if(placer.isCarved(i, h, ii) || placer.isCarved(i, h - 1, ii) || placer.isCarved(i, h - 2, ii) || placer.isCarved(i, h - 3, ii)) { - bail = true; - break; - } - if(h < y) { - y = h; - } - } - } - } else if(config.getMode().equals(ObjectPlaceMode.PAINT)) { - y = placer.getHighest(x, z, getLoader(), config.isUnderwater()) + rty; - if(placer.isCarved(x, y, z) || placer.isCarved(x, y - 1, z) || placer.isCarved(x, y - 2, z) || placer.isCarved(x, y - 3, z)) { - bail = true; - } - } - } else { - y = yv; - if(placer.isCarved(x, y, z) || placer.isCarved(x, y - 1, z) || placer.isCarved(x, y - 2, z) || placer.isCarved(x, y - 3, z)) { - bail = true; - } - } - - if(yv >= 0 && config.isBottom()) { - y += Math.floorDiv(h, 2); - bail = placer.isCarved(x, y, z) || placer.isCarved(x, y - 1, z) || placer.isCarved(x, y - 2, z) || placer.isCarved(x, y - 3, z); - } - - if(bail) { - return -1; - } - - if(yv < 0) { - if(!config.isUnderwater() && !config.isOnwater() && placer.isUnderwater(x, z)) { - return -1; - } - } - - if(c != null && Math.max(0, h + yrand + ty) + 1 >= c.getHeight()) { - return -1; - } - - if(config.isUnderwater() && y + rty + ty >= placer.getFluidHeight()) { - return -1; - } - - if(!config.getClamp().canPlace(y + rty + ty, y - rty + ty)) { - return -1; - } - - if(config.isBore()) { - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - for(int i = x - Math.floorDiv(w, 2) + (int) offset.getX(); i <= x + Math.floorDiv(w, 2) - (w % 2 == 0 ? 1 : 0) + (int) offset.getX(); i++) { - for(int j = y - Math.floorDiv(h, 2) - config.getBoreExtendMinY() + (int) offset.getY(); j <= y + Math.floorDiv(h, 2) + config.getBoreExtendMaxY() - (h % 2 == 0 ? 1 : 0) + (int) offset.getY(); j++) { - for(int k = z - Math.floorDiv(d, 2) + (int) offset.getZ(); k <= z + Math.floorDiv(d, 2) - (d % 2 == 0 ? 1 : 0) + (int) offset.getX(); k++) { - placer.set(i, j, k, AIR); - } - } - } - } - - int lowest = Integer.MAX_VALUE; - y += yrand; - readLock.lock(); - - KMap markers = null; - - try { - if(config.getMarkers().isNotEmpty() && placer.getEngine() != null) { - markers = new KMap<>(); - for(IrisObjectMarker j : config.getMarkers()) { - IrisMarker marker = getLoader().getMarkerLoader().load(j.getMarker()); - - if(marker == null) { - continue; - } - - int max = j.getMaximumMarkers(); - - for(BlockVector i : getBlocks().k().shuffle()) { - if(max <= 0) { - break; - } - - BlockData data = getBlocks().get(i); - - for(BlockData k : j.getMark(rdata)) { - if(max <= 0) { - break; - } - - if(j.isExact() ? k.matches(data) : k.getMaterial().equals(data.getMaterial())) { - boolean a = !blocks.containsKey(new BlockVector(i.clone().add(new BlockVector(0, 1, 0)))); - boolean fff = !blocks.containsKey(new BlockVector(i.clone().add(new BlockVector(0, 2, 0)))); - - if(!marker.isEmptyAbove() || (a && fff)) { - markers.put(i, j.getMarker()); - max--; - } - } - } - } - } - } - - for(BlockVector g : getBlocks().keySet()) { - BlockData d; - TileData tile = null; - - try { - d = getBlocks().get(g); - tile = getStates().get(g); - } catch(Throwable e) { - Iris.reportError(e); - Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (cme)"); - d = AIR; - } - - if(d == null) { - Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (null)"); - d = AIR; - } - - BlockVector i = g.clone(); - BlockData data = d.clone(); - i = config.getRotation().rotate(i.clone(), spinx, spiny, spinz).clone(); - i = config.getTranslate().translate(i.clone(), config.getRotation(), spinx, spiny, spinz).clone(); - - if(stilting && i.getBlockY() < lowest && !B.isAir(data)) { - lowest = i.getBlockY(); - } - - if(placer.isPreventingDecay() && (data) instanceof Leaves && !((Leaves) (data)).isPersistent()) { - ((Leaves) data).setPersistent(true); - } - - for(IrisObjectReplace j : config.getEdit()) { - if(rng.chance(j.getChance())) { - for(BlockData k : j.getFind(rdata)) { - if(j.isExact() ? k.matches(data) : k.getMaterial().equals(data.getMaterial())) { - BlockData newData = j.getReplace(rng, i.getX() + x, i.getY() + y, i.getZ() + z, rdata).clone(); - - if(newData.getMaterial() == data.getMaterial()) - data = data.merge(newData); - else - data = newData; - - if(newData.getMaterial() == Material.SPAWNER) { - Optional> t = j.getReplace().getTile(rng, x, y, z, rdata); - if(t.isPresent()) { - tile = t.get(); - } - } - } - } - } - } - - data = config.getRotation().rotate(data, spinx, spiny, spinz); - xx = x + (int) Math.round(i.getX()); - - int yy = y + (int) Math.round(i.getY()); - zz = z + (int) Math.round(i.getZ()); - - if(warped) { - xx += config.warp(rng, i.getX() + x, i.getY() + y, i.getZ() + z, getLoader()); - zz += config.warp(rng, i.getZ() + z, i.getY() + y, i.getX() + x, getLoader()); - } - - if(yv < 0 && (config.getMode().equals(ObjectPlaceMode.PAINT))) { - yy = (int) Math.round(i.getY()) + Math.floorDiv(h, 2) + placer.getHighest(xx, zz, getLoader(), config.isUnderwater()); - } - - if(heightmap != null) { - Position2 pos = new Position2(xx, zz); - - if(!heightmap.containsKey(pos)) { - heightmap.put(pos, yy); - } - - if(heightmap.get(pos) < yy) { - heightmap.put(pos, yy); - } - } - - if(config.isMeld() && !placer.isSolid(xx, yy, zz)) { - continue; - } - - if(config.isWaterloggable() && yy <= placer.getFluidHeight() && data instanceof Waterlogged) { - ((Waterlogged) data).setWaterlogged(true); - } - - if(listener != null) { - listener.accept(new BlockPosition(xx, yy, zz)); - } - - if(markers != null && markers.containsKey(g)) { - placer.getEngine().getMantle().getMantle().set(xx, yy, zz, new MatterMarker(markers.get(g))); - } - - if(!data.getMaterial().equals(Material.AIR) && !data.getMaterial().equals(Material.CAVE_AIR)) { - placer.set(xx, yy, zz, data); - if(tile != null) { - placer.setTile(xx, yy, zz, tile); - } - } - } - } catch(Throwable e) { - Iris.reportError(e); - } - readLock.unlock(); - - if(stilting) { - readLock.lock(); - IrisStiltSettings settings = config.getStiltSettings(); - for(BlockVector g : getBlocks().keySet()) { - BlockData d; - - if(settings == null || settings.getPalette() == null) { - try { - d = getBlocks().get(g); - } catch(Throwable e) { - Iris.reportError(e); - Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (stilt cme)"); - d = AIR; - } - - if(d == null) { - Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (stilt null)"); - d = AIR; - } - } else - d = config.getStiltSettings().getPalette().get(rng, x, y, z, rdata); - - - BlockVector i = g.clone(); - i = config.getRotation().rotate(i.clone(), spinx, spiny, spinz).clone(); - i = config.getTranslate().translate(i.clone(), config.getRotation(), spinx, spiny, spinz).clone(); - - if(i.getBlockY() != lowest) - continue; - - for(IrisObjectReplace j : config.getEdit()) { - if(rng.chance(j.getChance())) { - for(BlockData k : j.getFind(rdata)) { - if(j.isExact() ? k.matches(d) : k.getMaterial().equals(d.getMaterial())) { - BlockData newData = j.getReplace(rng, i.getX() + x, i.getY() + y, i.getZ() + z, rdata).clone(); - - if(newData.getMaterial() == d.getMaterial()) { - d = d.merge(newData); - } else { - d = newData; - } - } - } - } - } - - if(d == null || B.isAir(d)) - continue; - - xx = x + (int) Math.round(i.getX()); - zz = z + (int) Math.round(i.getZ()); - - if(warped) { - xx += config.warp(rng, i.getX() + x, i.getY() + y, i.getZ() + z, getLoader()); - zz += config.warp(rng, i.getZ() + z, i.getY() + y, i.getX() + x, getLoader()); - } - - int highest = placer.getHighest(xx, zz, getLoader(), true); - - if(config.isWaterloggable() && highest <= placer.getFluidHeight() && d instanceof Waterlogged) - ((Waterlogged) d).setWaterlogged(true); - - if(yv >= 0 && config.isBottom()) - y += Math.floorDiv(h, 2); - - int lowerBound = highest - 1; - if(settings != null) { - lowerBound -= config.getStiltSettings().getOverStilt() - rng.i(0, config.getStiltSettings().getYRand()); - if(settings.getYMax() != 0) - lowerBound -= Math.min(config.getStiltSettings().getYMax() - (lowest + y - highest), 0); - } - for(int j = lowest + y; j > lowerBound; j--) - placer.set(xx, j, zz, d); - } - - readLock.unlock(); - } - - if(heightmap != null) { - RNG rngx = rng.nextParallelRNG(3468854); - - for(Position2 i : heightmap.k()) { - int vx = i.getX(); - int vy = heightmap.get(i); - int vz = i.getZ(); - - if(config.getSnow() > 0) { - int height = rngx.i(0, (int) (config.getSnow() * 7)); - placer.set(vx, vy + 1, vz, SNOW_LAYERS[Math.max(Math.min(height, 7), 0)]); - } - } - } - - return y; - } - - public IrisObject rotateCopy(IrisObjectRotation rt) { - IrisObject copy = copy(); - copy.rotate(rt, 0, 0, 0); - return copy; - } - - public void rotate(IrisObjectRotation r, int spinx, int spiny, int spinz) { - KMap d = new KMap<>(); - - for(BlockVector i : getBlocks().keySet()) { - d.put(r.rotate(i.clone(), spinx, spiny, spinz), r.rotate(getBlocks().get(i).clone(), - spinx, spiny, spinz)); - } - - KMap> dx = new KMap<>(); - - for(BlockVector i : getStates().keySet()) { - dx.put(r.rotate(i.clone(), spinx, spiny, spinz), getStates().get(i)); - } - - blocks = d; - states = dx; - } - - public void place(Location at) { - for(BlockVector i : getBlocks().keySet()) { - Block b = at.clone().add(0, getCenter().getY(), 0).add(i).getBlock(); - b.setBlockData(Objects.requireNonNull(getBlocks().get(i)), false); - - if(getStates().containsKey(i)) { - Iris.info(Objects.requireNonNull(states.get(i)).toString()); - BlockState st = b.getState(); - Objects.requireNonNull(getStates().get(i)).toBukkitTry(st); - st.update(); - } - } - } - - public void placeCenterY(Location at) { - for(BlockVector i : getBlocks().keySet()) { - Block b = at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i).getBlock(); - b.setBlockData(Objects.requireNonNull(getBlocks().get(i)), false); - - if(getStates().containsKey(i)) { - Objects.requireNonNull(getStates().get(i)).toBukkitTry(b.getState()); - } - } - } - - public synchronized KMap getBlocks() { - return blocks; - } - - public synchronized KMap> getStates() { - return states; - } - - public void unplaceCenterY(Location at) { - for(BlockVector i : getBlocks().keySet()) { - at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i).getBlock().setBlockData(AIR, false); - } - } - - public IrisObject scaled(double scale, IrisObjectPlacementScaleInterpolator interpolation) { - Vector sm1 = new Vector(scale - 1, scale - 1, scale - 1); - scale = Math.max(0.001, Math.min(50, scale)); - if(scale < 1) { - scale = scale - 0.0001; - } - - IrisPosition l1 = getAABB().max(); - IrisPosition l2 = getAABB().min(); - @SuppressWarnings({"unchecked", "rawtypes"}) HashMap placeBlock = new HashMap(); - - Vector center = getCenter(); - if(getH() == 2) { - center = center.setY(center.getBlockY() + 0.5); - } - if(getW() == 2) { - center = center.setX(center.getBlockX() + 0.5); - } - if(getD() == 2) { - center = center.setZ(center.getBlockZ() + 0.5); - } - - IrisObject oo = new IrisObject((int) Math.ceil((w * scale) + (scale * 2)), (int) Math.ceil((h * scale) + (scale * 2)), (int) Math.ceil((d * scale) + (scale * 2))); - - for(Map.Entry entry : blocks.entrySet()) { - BlockData bd = entry.getValue(); - placeBlock.put(entry.getKey().clone().add(HALF).subtract(center) - .multiply(scale).add(sm1).toBlockVector(), bd); - } - - for(Map.Entry entry : placeBlock.entrySet()) { - BlockVector v = entry.getKey(); - if(scale > 1) { - for(BlockVector vec : blocksBetweenTwoPoints(v.clone().add(center), v.clone().add(center).add(sm1))) { - oo.getBlocks().put(vec, entry.getValue()); - } - } else { - oo.setUnsigned(v.getBlockX(), v.getBlockY(), v.getBlockZ(), entry.getValue()); - } - } - - if(scale > 1) { - switch(interpolation) { - case TRILINEAR -> oo.trilinear((int) Math.round(scale)); - case TRICUBIC -> oo.tricubic((int) Math.round(scale)); - case TRIHERMITE -> oo.trihermite((int) Math.round(scale)); - } - } - - return oo; - } - - public void trilinear(int rad) { - KMap v = getBlocks().copy(); - KMap b = new KMap<>(); - BlockVector min = getAABB().minbv(); - BlockVector max = getAABB().maxbv(); - - for(int x = min.getBlockX(); x <= max.getBlockX(); x++) { - for(int y = min.getBlockY(); y <= max.getBlockY(); y++) { - for(int z = min.getBlockZ(); z <= max.getBlockZ(); z++) { - if(IrisInterpolation.getTrilinear(x, y, z, rad, (xx, yy, zz) -> { - BlockData data = v.get(new BlockVector((int) xx, (int) yy, (int) zz)); - - if(data == null || data.getMaterial().isAir()) { - return 0; - } - - return 1; - }) >= 0.5) { - b.put(new BlockVector(x, y, z), nearestBlockData(x, y, z)); - } else { - b.put(new BlockVector(x, y, z), AIR); - } - } - } - } - - blocks = b; - } - - public void tricubic(int rad) { - KMap v = getBlocks().copy(); - KMap b = new KMap<>(); - BlockVector min = getAABB().minbv(); - BlockVector max = getAABB().maxbv(); - - for(int x = min.getBlockX(); x <= max.getBlockX(); x++) { - for(int y = min.getBlockY(); y <= max.getBlockY(); y++) { - for(int z = min.getBlockZ(); z <= max.getBlockZ(); z++) { - if(IrisInterpolation.getTricubic(x, y, z, rad, (xx, yy, zz) -> { - BlockData data = v.get(new BlockVector((int) xx, (int) yy, (int) zz)); - - if(data == null || data.getMaterial().isAir()) { - return 0; - } - - return 1; - }) >= 0.5) { - b.put(new BlockVector(x, y, z), nearestBlockData(x, y, z)); - } else { - b.put(new BlockVector(x, y, z), AIR); - } - } - } - } - - blocks = b; - } - - public void trihermite(int rad) { - trihermite(rad, 0D, 0D); - } - - public void trihermite(int rad, double tension, double bias) { - KMap v = getBlocks().copy(); - KMap b = new KMap<>(); - BlockVector min = getAABB().minbv(); - BlockVector max = getAABB().maxbv(); - - for(int x = min.getBlockX(); x <= max.getBlockX(); x++) { - for(int y = min.getBlockY(); y <= max.getBlockY(); y++) { - for(int z = min.getBlockZ(); z <= max.getBlockZ(); z++) { - if(IrisInterpolation.getTrihermite(x, y, z, rad, (xx, yy, zz) -> { - BlockData data = v.get(new BlockVector((int) xx, (int) yy, (int) zz)); - - if(data == null || data.getMaterial().isAir()) { - return 0; - } - - return 1; - }, tension, bias) >= 0.5) { - b.put(new BlockVector(x, y, z), nearestBlockData(x, y, z)); - } else { - b.put(new BlockVector(x, y, z), AIR); - } - } - } - } - - blocks = b; - } - - private BlockData nearestBlockData(int x, int y, int z) { - BlockVector vv = new BlockVector(x, y, z); - BlockData r = getBlocks().get(vv); - - if(r != null && !r.getMaterial().isAir()) { - return r; - } - - double d = Double.MAX_VALUE; - - for(Map.Entry entry : blocks.entrySet()) { - BlockData dat = entry.getValue(); - - if(dat.getMaterial().isAir()) { - continue; - } - - double dx = entry.getKey().distanceSquared(vv); - - if(dx < d) { - d = dx; - r = dat; - } - } - - return r; - } - - public int volume() { - return blocks.size(); - } - - @Override - public String getFolderName() { - return "objects"; - } - - @Override - public String getTypeName() { - return "Object"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectLimit.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectLimit.java deleted file mode 100644 index 9fac8a1bb..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectLimit.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-limit") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Translate objects") -@Data -public class IrisObjectLimit { - @MinNumber(0) - @MaxNumber(1024) - @Desc("The minimum height for placement (bottom of object)") - private int minimumHeight = -2048; //TODO: WARNING HEIGHT - - @MinNumber(0) - @MaxNumber(1024) - @Desc("The maximum height for placement (top of object)") - private int maximumHeight = 2048; //TODO: WARNING HEIGHT - - public boolean canPlace(int h, int l) { - return h <= maximumHeight && l >= minimumHeight; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectLoot.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectLoot.java deleted file mode 100644 index cddc5edd5..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectLoot.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -@Snippet("object-loot") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents loot within this object or jigsaw piece") -@Data -public class IrisObjectLoot { - private final transient AtomicCache> filterCache = new AtomicCache<>(); - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The list of blocks this loot table should apply to") - private KList filter = new KList<>(); - @Desc("Exactly match the block data or not") - private boolean exact = false; - @Desc("The loot table name") - @Required - @RegistryListResource(IrisLootTable.class) - private String name; - @Desc("The weight of this loot table being chosen") - private int weight = 1; - - public KList getFilter(IrisData rdata) { - return filterCache.aquire(() -> - { - KList b = new KList<>(); - - for(IrisBlockData i : filter) { - BlockData bx = i.getBlockData(rdata); - - if(bx != null) { - b.add(bx); - } - } - - return b; - }); - } - - public boolean matchesFilter(IrisData manager, BlockData data) { - for(BlockData filterData : getFilter(manager)) { - if(filterData.matches(data)) return true; - } - return false; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectMarker.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectMarker.java deleted file mode 100644 index 83cebb084..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectMarker.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -@Snippet("object-marker") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Find blocks to mark") -@Data -public class IrisObjectMarker { - @ArrayType(min = 1, type = IrisBlockData.class) - @Required - @Desc("Find block types to mark") - private KList mark = new KList<>(); - - @MinNumber(1) - @MaxNumber(16) - @Desc("The maximum amount of markers to place. Use these sparingly!") - private int maximumMarkers = 8; - - @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") - private boolean exact = false; - - @Required - @RegistryListResource(IrisMarker.class) - @Desc("The marker to add") - private String marker; - - private final transient AtomicCache> findData = new AtomicCache<>(); - - public KList getMark(IrisData rdata) { - return findData.aquire(() -> - { - KList b = new KList<>(); - - for(IrisBlockData i : mark) { - BlockData bx = i.getBlockData(rdata); - - if(bx != null) { - b.add(bx); - } - } - - return b; - }); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectPlacement.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectPlacement.java deleted file mode 100644 index a60508096..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectPlacement.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.data.DataProvider; -import com.volmit.iris.util.data.WeightedRandom; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Material; -import org.bukkit.TreeType; -import org.bukkit.block.data.BlockData; - -@Snippet("object-placer") -@EqualsAndHashCode() -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an iris object placer. It places objects.") -@Data -public class IrisObjectPlacement { - private final transient AtomicCache surfaceWarp = new AtomicCache<>(); - @RegistryListResource(IrisObject.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("List of objects to place") - private KList place = new KList<>(); - @Desc("Rotate this objects placement") - private IrisObjectRotation rotation = new IrisObjectRotation(); - @Desc("Limit the max height or min height of placement.") - private IrisObjectLimit clamp = new IrisObjectLimit(); - @MinNumber(0) - @MaxNumber(1) - @Desc("The maximum layer level of a snow filter overtop of this placement. Set to 0 to disable. Max of 1.") - private double snow = 0; - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance for this to place in a chunk. If you need multiple per chunk, set this to 1 and use density.") - private double chance = 1; - @MinNumber(1) - @Desc("If the chance check passes, place this many in a single chunk") - private int density = 1; - @Desc("If the chance check passes, and you specify this, it picks a number in the range based on noise, and 'density' is ignored.") - private IrisStyledRange densityStyle = null; - @Desc("When stilting is enabled, this object will define various properties related to it.") - private IrisStiltSettings stiltSettings; - @MaxNumber(64) - @MinNumber(0) - @Desc("When bore is enabled, expand max-y of the cuboid it removes") - private int boreExtendMaxY = 0; - @ArrayType(min = 1, type = IrisObjectMarker.class) - @Desc("Add markers to blocks in this object") - private KList markers = new KList<>(); - @MaxNumber(64) - @MinNumber(-1) - @Desc("When bore is enabled, lower min-y of the cuboid it removes") - private int boreExtendMinY = 0; - @Desc("If set to true, objects will place on the terrain height, ignoring the water surface.") - private boolean underwater = false; - @Desc("If set to true, objects will place in carvings (such as underground) or under an overhang.") - private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; - @Desc("If this is defined, this object wont place on the terrain heightmap, but instead on this virtual heightmap") - private IrisNoiseGenerator heightmap; - @Desc("If set to true, Iris will try to fill the insides of 'rooms' and 'pockets' where air should fit based off of raytrace checks. This prevents a village house placing in an area where a tree already exists, and instead replaces the parts of the tree where the interior of the structure is. \n\nThis operation does not affect warmed-up generation speed however it does slow down loading objects.") - private boolean smartBore = false; - @Desc("If set to true, Blocks placed underwater that could be waterlogged are waterlogged.") - private boolean waterloggable = false; - @Desc("If set to true, objects will place on the fluid height level Such as boats.") - private boolean onwater = false; - @Desc("If set to true, this object will only place parts of itself where blocks already exist. Warning: Melding is very performance intensive!") - private boolean meld = false; - @Desc("If set to true, this object will place from the ground up instead of height checks when not y locked to the surface. This is not compatable with X and Z axis rotations (it may look off)") - private boolean bottom = false; - @Desc("If set to true, air will be placed before the schematic places.") - private boolean bore = false; - @Desc("Use a generator to warp the field of coordinates. Using simplex for example would make a square placement warp like a flag") - private IrisGeneratorStyle warp = new IrisGeneratorStyle(NoiseStyle.FLAT); - @Desc("If the place mode is set to CENTER_HEIGHT_RIGID and you have an X/Z translation, Turning on translate center will also translate the center height check.") - private boolean translateCenter = false; - @Desc("The placement mode") - private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - @ArrayType(min = 1, type = IrisObjectReplace.class) - @Desc("Find and replace blocks") - private KList edit = new KList<>(); - @Desc("Translate this object's placement") - private IrisObjectTranslate translate = new IrisObjectTranslate(); - @Desc("Scale Objects") - private IrisObjectScale scale = new IrisObjectScale(); - @ArrayType(min = 1, type = IrisObjectLoot.class) - @Desc("The loot tables to apply to these objects") - private KList loot = new KList<>(); - @Desc("This object / these objects override the following trees when they grow...") - @ArrayType(min = 1, type = IrisTree.class) - private KList trees = new KList<>(); - private transient AtomicCache cache = new AtomicCache<>(); - - public IrisObjectPlacement toPlacement(String... place) { - IrisObjectPlacement p = new IrisObjectPlacement(); - p.setPlace(new KList<>(place)); - p.setTranslateCenter(translateCenter); - p.setMode(mode); - p.setEdit(edit); - p.setTranslate(translate); - p.setWarp(warp); - p.setBore(bore); - p.setMeld(meld); - p.setWaterloggable(waterloggable); - p.setOnwater(onwater); - p.setSmartBore(smartBore); - p.setCarvingSupport(carvingSupport); - p.setUnderwater(underwater); - p.setBoreExtendMaxY(boreExtendMaxY); - p.setBoreExtendMinY(boreExtendMinY); - p.setStiltSettings(stiltSettings); - p.setDensity(density); - p.setChance(chance); - p.setSnow(snow); - p.setClamp(clamp); - p.setRotation(rotation); - p.setLoot(loot); - return p; - } - - public CNG getSurfaceWarp(RNG rng, IrisData data) { - return surfaceWarp.aquire(() -> - getWarp().create(rng, data)); - } - - public double warp(RNG rng, double x, double y, double z, IrisData data) { - return getSurfaceWarp(rng, data).fitDouble(-(getWarp().getMultiplier() / 2D), (getWarp().getMultiplier() / 2D), x, y, z); - } - - public IrisObject getObject(DataProvider g, RNG random) { - if(place.isEmpty()) { - return null; - } - - return g.getData().getObjectLoader().load(place.get(random.nextInt(place.size()))); - } - - public boolean matches(IrisTreeSize size, TreeType type) { - for(IrisTree i : getTrees()) { - if(i.matches(size, type)) { - return true; - } - } - - return false; - } - - public int getDensity() { - if(densityStyle == null) { - return density; - } - return densityStyle.getMid(); - } - - public int getDensity(RNG rng, double x, double z, IrisData data) { - if(densityStyle == null) { - return density; - } - - return (int) Math.round(densityStyle.get(rng, x, z, data)); - } - - private TableCache getCache(IrisData manager) { - return cache.aquire(() -> { - TableCache tc = new TableCache(); - - for(IrisObjectLoot loot : getLoot()) { - IrisLootTable table = manager.getLootLoader().load(loot.getName()); - if(table == null) { - Iris.warn("Couldn't find loot table " + loot.getName()); - continue; - } - - if(loot.getFilter().isEmpty()) //Table applies to all containers - { - tc.global.put(table, loot.getWeight()); - } else if(!loot.isExact()) //Table is meant to be by type - { - for(BlockData filterData : loot.getFilter(manager)) { - if(!tc.basic.containsKey(filterData.getMaterial())) { - tc.basic.put(filterData.getMaterial(), new WeightedRandom<>()); - } - - tc.basic.get(filterData.getMaterial()).put(table, loot.getWeight()); - } - } else //Filter is exact - { - for(BlockData filterData : loot.getFilter(manager)) { - if(!tc.exact.containsKey(filterData.getMaterial())) { - tc.exact.put(filterData.getMaterial(), new KMap<>()); - } - - if(!tc.exact.get(filterData.getMaterial()).containsKey(filterData)) { - tc.exact.get(filterData.getMaterial()).put(filterData, new WeightedRandom<>()); - } - - tc.exact.get(filterData.getMaterial()).get(filterData).put(table, loot.getWeight()); - } - } - } - return tc; - }); - } - - /** - * Gets the loot table that should be used for the block - * - * @param data - * The block data of the block - * @param dataManager - * Iris Data Manager - * @return The loot table it should use. - */ - public IrisLootTable getTable(BlockData data, IrisData dataManager) { - TableCache cache = getCache(dataManager); - - if(B.isStorageChest(data)) { - IrisLootTable picked = null; - if(cache.exact.containsKey(data.getMaterial()) && cache.exact.containsKey(data)) { - picked = cache.exact.get(data.getMaterial()).get(data).pullRandom(); - } else if(cache.basic.containsKey(data.getMaterial())) { - picked = cache.basic.get(data.getMaterial()).pullRandom(); - } else if(cache.global.getSize() > 0) { - picked = cache.global.pullRandom(); - } - - return picked; - } - - return null; - } - - private static class TableCache { - final transient WeightedRandom global = new WeightedRandom<>(); - final transient KMap> basic = new KMap<>(); - final transient KMap>> exact = new KMap<>(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectPlacementScaleInterpolator.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectPlacementScaleInterpolator.java deleted file mode 100644 index da8cafc31..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectPlacementScaleInterpolator.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Use 3D Interpolation on scaled objects if they are larger than the origin.") -public enum IrisObjectPlacementScaleInterpolator { - @Desc("Don't interpolate, big cubes") - NONE, - @Desc("Uses linear interpolation in 3 dimensions, generally pretty good, but slow") - TRILINEAR, - @Desc("Uses cubic spline interpolation in 3 dimensions, even better, but extreme slowdowns") - TRICUBIC, - @Desc("Uses hermite spline interpolation in 3 dimensions, even better, but extreme slowdowns") - TRIHERMITE -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectReplace.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectReplace.java deleted file mode 100644 index e09ac75e4..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectReplace.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -@Snippet("object-block-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Find and replace object materials") -@Data -public class IrisObjectReplace { - private final transient AtomicCache replaceGen = new AtomicCache<>(); - private final transient AtomicCache> findData = new AtomicCache<>(); - private final transient AtomicCache> replaceData = new AtomicCache<>(); - @ArrayType(min = 1, type = IrisBlockData.class) - @Required - @Desc("Find this block") - private KList find = new KList<>(); - @Required - @Desc("Replace it with this block palette") - private IrisMaterialPalette replace = new IrisMaterialPalette(); - @Desc("Exactly match the block data or not") - private boolean exact = false; - @MinNumber(0) - @MaxNumber(1) - @Desc("Modifies the chance the block is replaced") - private float chance = 1; - - public KList getFind(IrisData rdata) { - return findData.aquire(() -> - { - KList b = new KList<>(); - - for(IrisBlockData i : find) { - BlockData bx = i.getBlockData(rdata); - - if(bx != null) { - b.add(bx); - } - } - - return b; - }); - } - - public BlockData getReplace(RNG seed, double x, double y, double z, IrisData rdata) { - return getReplace().get(seed, x, y, z, rdata); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectRotation.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectRotation.java deleted file mode 100644 index 7a6521050..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectRotation.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Axis; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.MultipleFacing; -import org.bukkit.block.data.Orientable; -import org.bukkit.block.data.Rotatable; -import org.bukkit.util.BlockVector; - -import java.util.List; - -@Snippet("object-rotator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Configures rotation for iris") -@Data -public class IrisObjectRotation { - @Desc("If this rotator is enabled or not") - private boolean enabled = true; - - @Desc("The x axis rotation") - private IrisAxisRotationClamp xAxis = new IrisAxisRotationClamp(); - - @Desc("The y axis rotation") - private IrisAxisRotationClamp yAxis = new IrisAxisRotationClamp(true, false, 0, 0, 90); - - @Desc("The z axis rotation") - private IrisAxisRotationClamp zAxis = new IrisAxisRotationClamp(); - - public static IrisObjectRotation of(double x, double y, double z) { - IrisObjectRotation rt = new IrisObjectRotation(); - IrisAxisRotationClamp rtx = new IrisAxisRotationClamp(); - IrisAxisRotationClamp rty = new IrisAxisRotationClamp(); - IrisAxisRotationClamp rtz = new IrisAxisRotationClamp(); - rt.setEnabled(x != 0 || y != 0 || z != 0); - rt.setXAxis(rtx); - rt.setYAxis(rty); - rt.setZAxis(rtz); - rtx.setEnabled(x != 0); - rty.setEnabled(y != 0); - rtz.setEnabled(z != 0); - rtx.setInterval(90); - rty.setInterval(90); - rtz.setInterval(90); - rtx.minMax(x); - rty.minMax(y); - rtz.minMax(z); - - return rt; - } - - public double getYRotation(int spin) { - return getRotation(spin, yAxis); - } - - public double getXRotation(int spin) { - return getRotation(spin, xAxis); - } - - public double getZRotation(int spin) { - return getRotation(spin, zAxis); - } - - public IrisObject rotateCopy(IrisObject e) { - if(e == null) { - return null; - } - - return e.rotateCopy(this); - } - - public IrisJigsawPiece rotateCopy(IrisJigsawPiece v) { - IrisJigsawPiece piece = v.copy(); - for(IrisJigsawPieceConnector i : piece.getConnectors()) { - i.setPosition(rotate(i.getPosition())); - i.setDirection(rotate(i.getDirection())); - } - - return piece; - } - - public BlockVector rotate(BlockVector direction) { - return rotate(direction, 0, 0, 0); - } - - public IrisDirection rotate(IrisDirection direction) { - BlockVector v = rotate(direction.toVector().toBlockVector()); - return IrisDirection.closest(v); - } - - public double getRotation(int spin, IrisAxisRotationClamp clamp) { - if(!enabled) { - return 0; - } - - if(!clamp.isEnabled()) { - return 0; - } - - return clamp.getRadians(spin); - } - - public BlockFace getFace(BlockVector v) { - int x = (int) Math.round(v.getX()); - int y = (int) Math.round(v.getY()); - int z = (int) Math.round(v.getZ()); - - if(x == 0 && z == -1) { - return BlockFace.NORTH; - } - - if(x == 0 && z == 1) { - return BlockFace.SOUTH; - } - - if(x == 1 && z == 0) { - return BlockFace.EAST; - } - - if(x == -1 && z == 0) { - return BlockFace.WEST; - } - - if(y > 0) { - return BlockFace.UP; - } - - if(y < 0) { - return BlockFace.DOWN; - } - - return BlockFace.SOUTH; - } - - public BlockFace getHexFace(BlockVector v) { - int x = v.getBlockX(); - int y = v.getBlockY(); - int z = v.getBlockZ(); - - if(x == 0 && z == -1) return BlockFace.NORTH; - if(x == 1 && z == -2) return BlockFace.NORTH_NORTH_EAST; - if(x == 1 && z == -1) return BlockFace.NORTH_EAST; - if(x == 2 && z == -1) return BlockFace.EAST_NORTH_EAST; - if(x == 1 && z == 0) return BlockFace.EAST; - if(x == 2 && z == 1) return BlockFace.EAST_SOUTH_EAST; - if(x == 1 && z == 1) return BlockFace.SOUTH_EAST; - if(x == 1 && z == 2) return BlockFace.SOUTH_SOUTH_EAST; - if(x == 0 && z == 1) return BlockFace.SOUTH; - if(x == -1 && z == 2) return BlockFace.SOUTH_SOUTH_WEST; - if(x == -1 && z == 1) return BlockFace.SOUTH_WEST; - if(x == -2 && z == 1) return BlockFace.WEST_SOUTH_WEST; - if(x == -1 && z == 0) return BlockFace.WEST; - if(x == -2 && z == -1) return BlockFace.WEST_NORTH_WEST; - if(x == -1 && z == -1) return BlockFace.NORTH_WEST; - if(x == -1 && z == -2) return BlockFace.NORTH_NORTH_WEST; - - if(y > 0) { - return BlockFace.UP; - } - - if(y < 0) { - return BlockFace.DOWN; - } - - return BlockFace.SOUTH; - } - - public BlockFace faceForAxis(Axis axis) { - return switch(axis) { - case X -> BlockFace.EAST; - case Y -> BlockFace.UP; - case Z -> BlockFace.NORTH; - }; - - } - - public Axis axisFor(BlockFace f) { - return switch(f) { - case NORTH, SOUTH -> Axis.Z; - case EAST, WEST -> Axis.X; - default -> Axis.Y; - }; - - } - - public Axis axisFor2D(BlockFace f) { - return switch(f) { - case EAST, WEST, UP, DOWN -> Axis.X; - default -> Axis.Z; - }; - - } - - public BlockData rotate(BlockData dd, int spinxx, int spinyy, int spinzz) { - BlockData d = dd; - try { - int spinx = (int) (90D * (Math.ceil(Math.abs((spinxx % 360D) / 90D)))); - int spiny = (int) (90D * (Math.ceil(Math.abs((spinyy % 360D) / 90D)))); - int spinz = (int) (90D * (Math.ceil(Math.abs((spinzz % 360D) / 90D)))); - - if(!canRotate()) { - return d; - } - - if(d instanceof Directional g) { - BlockFace f = g.getFacing(); - BlockVector bv = new BlockVector(f.getModX(), f.getModY(), f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace t = getFace(bv); - - if(g.getFaces().contains(t)) { - g.setFacing(t); - } else if(!g.getMaterial().isSolid()) { - d = null; - } - } else if(d instanceof Rotatable g) { - BlockFace f = g.getRotation(); - - BlockVector bv = new BlockVector(f.getModX(), 0, f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace face = getHexFace(bv); - - g.setRotation(face); - - } else if(d instanceof Orientable) { - BlockFace f = getFace(((Orientable) d).getAxis()); - BlockVector bv = new BlockVector(f.getModX(), f.getModY(), f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - Axis a = getAxis(bv); - - if(!a.equals(((Orientable) d).getAxis()) && ((Orientable) d).getAxes().contains(a)) { - ((Orientable) d).setAxis(a); - } - } else if(d instanceof MultipleFacing g) { - List faces = new KList<>(); - - for(BlockFace i : g.getFaces()) { - BlockVector bv = new BlockVector(i.getModX(), i.getModY(), i.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace r = getFace(bv); - - if(g.getAllowedFaces().contains(r)) { - faces.add(r); - } - } - - for(BlockFace i : g.getFaces()) { - g.setFace(i, false); - } - - for(BlockFace i : faces) { - g.setFace(i, true); - } - } else if(d.getMaterial().equals(Material.NETHER_PORTAL) && d instanceof Orientable g) { - //TODO: Fucks up logs - BlockFace f = faceForAxis(g.getAxis()); - BlockVector bv = new BlockVector(f.getModX(), f.getModY(), f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace t = getFace(bv); - Axis a = !g.getAxes().contains(Axis.Y) ? axisFor(t) : axisFor2D(t); - ((Orientable) d).setAxis(a); - } - } catch(Throwable e) { - Iris.reportError(e); - - } - - return d; - } - - public Axis getAxis(BlockVector v) { - if(Math.abs(v.getBlockX()) > Math.max(Math.abs(v.getBlockY()), Math.abs(v.getBlockZ()))) { - return Axis.X; - } - - if(Math.abs(v.getBlockY()) > Math.max(Math.abs(v.getBlockX()), Math.abs(v.getBlockZ()))) { - return Axis.Y; - } - - if(Math.abs(v.getBlockZ()) > Math.max(Math.abs(v.getBlockX()), Math.abs(v.getBlockY()))) { - return Axis.Z; - } - - return Axis.Y; - } - - private BlockFace getFace(Axis axis) { - return switch(axis) { - case X -> BlockFace.EAST; - case Y -> BlockFace.UP; - case Z -> BlockFace.SOUTH; - }; - } - - public IrisPosition rotate(IrisPosition b) { - return rotate(b, 0, 0, 0); - } - - public IrisPosition rotate(IrisPosition b, int spinx, int spiny, int spinz) { - return new IrisPosition(rotate(new BlockVector(b.getX(), b.getY(), b.getZ()), spinx, spiny, spinz)); - } - - public BlockVector rotate(BlockVector b, int spinx, int spiny, int spinz) { - if(!canRotate()) { - return b; - } - - BlockVector v = b.clone(); - - if(canRotateX()) { - if(getXAxis().isLocked()) { - if(Math.abs(getXAxis().getMax()) % 360D == 180D) { - v.setZ(-v.getZ()); - v.setY(-v.getY()); - } else if(getXAxis().getMax() % 360D == 90D || getXAxis().getMax() % 360D == -270D) { - double z = v.getZ(); - v.setZ(v.getY()); - v.setY(-z); - } else if(getXAxis().getMax() == -90D || getXAxis().getMax() % 360D == 270D) { - double z = v.getZ(); - v.setZ(-v.getY()); - v.setY(z); - } else { - v.rotateAroundX(getXRotation(spinx)); - } - } else { - v.rotateAroundX(getXRotation(spinx)); - } - } - - if(canRotateZ()) { - if(getZAxis().isLocked()) { - if(Math.abs(getZAxis().getMax()) % 360D == 180D) { - v.setY(-v.getY()); - v.setX(-v.getX()); - } else if(getZAxis().getMax() % 360D == 90D || getZAxis().getMax() % 360D == -270D) { - double y = v.getY(); - v.setY(v.getX()); - v.setX(-y); - } else if(getZAxis().getMax() == -90D || getZAxis().getMax() % 360D == 270D) { - double y = v.getY(); - v.setY(-v.getX()); - v.setX(y); - } else { - v.rotateAroundZ(getZRotation(spinz)); - } - } else { - v.rotateAroundY(getZRotation(spinz)); - } - } - - if(canRotateY()) { - if(getYAxis().isLocked()) { - if(Math.abs(getYAxis().getMax()) % 360D == 180D) { - v.setX(-v.getX()); - v.setZ(-v.getZ()); - } else if(getYAxis().getMax() % 360D == 90D || getYAxis().getMax() % 360D == -270D) { - double x = v.getX(); - v.setX(v.getZ()); - v.setZ(-x); - } else if(getYAxis().getMax() == -90D || getYAxis().getMax() % 360D == 270D) { - double x = v.getX(); - v.setX(-v.getZ()); - v.setZ(x); - } else { - v.rotateAroundY(getYRotation(spiny)); - } - } else { - v.rotateAroundY(getYRotation(spiny)); - } - } - - return v; - } - - public boolean canRotateX() { - return enabled && xAxis.isEnabled(); - } - - public boolean canRotateY() { - return enabled && yAxis.isEnabled(); - } - - public boolean canRotateZ() { - return enabled && zAxis.isEnabled(); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean canRotate() { - return canRotateX() || canRotateY() || canRotateZ(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectScale.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectScale.java deleted file mode 100644 index 8ec414b5d..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectScale.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("object-scale") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Scale objects") -@Data -public class IrisObjectScale { - private static transient ConcurrentLinkedHashMap> cache - = new ConcurrentLinkedHashMap.Builder>() - .initialCapacity(64) - .maximumWeightedCapacity(1024) - .concurrencyLevel(32) - .build(); - @MinNumber(1) - @MaxNumber(32) - @Desc("Iris Objects are scaled and cached to speed up placements. Because of this extra memory is used, so we evenly distribute variations across the defined scale range, then pick one randomly. If the differences is small, use a lower number. For more possibilities on the scale spectrum, increase this at the cost of memory.") - private int variations = 7; - @MinNumber(0.01) - @MaxNumber(50) - @Desc("The minimum scale") - private double minimumScale = 1; - @MinNumber(0.01) - @MaxNumber(50) - @Desc("The maximum height for placement (top of object)") - private double maximumScale = 1; - @Desc("If this object is scaled up beyond its origin size, specify a 3D interpolator") - private IrisObjectPlacementScaleInterpolator interpolation = IrisObjectPlacementScaleInterpolator.NONE; - - public boolean shouldScale() { - return ((minimumScale == maximumScale) && maximumScale == 1) || variations <= 0; - } - - public int getMaxSizeFor(int indim) { - return (int) (getMaxScale() * indim); - } - - public double getMaxScale() { - double mx = 0; - - for(double i = minimumScale; i < maximumScale; i += (maximumScale - minimumScale) / (double) (Math.min(variations, 32))) { - mx = i; - } - - return mx; - } - - public IrisObject get(RNG rng, IrisObject origin) { - if(shouldScale()) { - return origin; - } - - return cache.computeIfAbsent(origin, (k) -> { - KList c = new KList<>(); - for(double i = minimumScale; i < maximumScale; i += (maximumScale - minimumScale) / (double) (Math.min(variations, 32))) { - c.add(origin.scaled(i, getInterpolation())); - } - - return c; - }).getRandom(rng); - } - - public boolean canScaleBeyond() { - return shouldScale() && maximumScale > 1; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisObjectTranslate.java b/src/main/java/com/volmit/iris/engine/object/IrisObjectTranslate.java deleted file mode 100644 index 53a3392e8..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisObjectTranslate.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.util.BlockVector; - -@Snippet("object-translator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Translate objects") -@Data -public class IrisObjectTranslate { - @MinNumber(-128) // TODO: WARNING HEIGHT - @MaxNumber(128) // TODO: WARNING HEIGHT - @Desc("The x shift in blocks") - private int x = 0; - - @Required - @MinNumber(-128) // TODO: WARNING HEIGHT - @MaxNumber(128) // TODO: WARNING HEIGHT - @Desc("The y shift in blocks") - private int y = 0; - - @MinNumber(-128) // TODO: WARNING HEIGHT - @MaxNumber(128) // TODO: WARNING HEIGHT - @Desc("Adds an additional amount of height randomly (translateY + rand(0 - yRandom))") - private int yRandom = 0; - - @MinNumber(-128) // TODO: WARNING HEIGHT - @MaxNumber(128) // TODO: WARNING HEIGHT - @Desc("The z shift in blocks") - private int z = 0; - - public boolean canTranslate() { - return x != 0 || y != 0 || z != 0; - } - - public BlockVector translate(BlockVector i) { - if(canTranslate()) { - return (BlockVector) i.clone().add(new BlockVector(x, y, z)); - } - - return i; - } - - public BlockVector translate(BlockVector clone, IrisObjectRotation rotation, int sx, int sy, int sz) { - if(canTranslate()) { - return (BlockVector) clone.clone().add(rotation.rotate(new BlockVector(x, y, z), sx, sy, sz)); - } - - return clone; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisOreGenerator.java b/src/main/java/com/volmit/iris/engine/object/IrisOreGenerator.java deleted file mode 100644 index 25809d482..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisOreGenerator.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Ore Layer") -@Data -public class IrisOreGenerator { - @Desc("The palette of 'ore' generated") - private IrisMaterialPalette palette = new IrisMaterialPalette().qclear(); - @Desc("The generator style for the 'ore'") - private IrisGeneratorStyle chanceStyle = new IrisGeneratorStyle(NoiseStyle.STATIC); - @Desc("Will ores generate on the surface of the terrain layer") - private boolean generateSurface = false; - @Desc("Threshold for rate of generation") - private double threshold = 0.5; - @Desc("Height limit (min, max)") - private IrisRange range = new IrisRange(30, 80); - - private transient AtomicCache chanceCache = new AtomicCache<>(); - - public BlockData generate(int x, int y, int z, RNG rng, IrisData data) { - if(palette.getPalette().isEmpty()) { - return null; - } - - if(!range.contains(y)) { - return null; - } - - CNG chance = chanceCache.aquire(() -> chanceStyle.create(rng, data)); - - if(chance.noise(x, y, z) > threshold) { - return null; - } - - return palette.get(rng, x, y, z, data); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisPosition.java b/src/main/java/com/volmit/iris/engine/object/IrisPosition.java deleted file mode 100644 index 1f3f6bf28..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisPosition.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.util.BlockVector; -import org.bukkit.util.Vector; - -@Snippet("position-3d") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a position") -@Data -public class IrisPosition { - @Desc("The x position") - private int x = 0; - - @Desc("The y position") - private int y = 0; - - @Desc("The z position") - private int z = 0; - - public IrisPosition(BlockVector bv) { - this(bv.getBlockX(), bv.getBlockY(), bv.getBlockZ()); - } - - public IrisPosition(Location l) { - this(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - } - - public IrisPosition(Vector v) { - this(v.getBlockX(), v.getBlockY(), v.getBlockZ()); - } - - public IrisPosition(double x, double y, double z) { - this((int) x, (int) y, (int) z); - } - - - public IrisPosition add(IrisPosition relativePosition) { - return new IrisPosition(relativePosition.x + x, relativePosition.y + y, relativePosition.z + z); - } - - public IrisPosition sub(IrisPosition relativePosition) { - return new IrisPosition(x - relativePosition.x, y - relativePosition.y, z - relativePosition.z); - } - - public Location toLocation(World world) { - return new Location(world, x, y, z); - } - - public IrisPosition copy() { - return new IrisPosition(x, y, z); - } - - @Override - public String toString() { - return "[" + getX() + "," + getY() + "," + getZ() + "]"; - } - - public boolean isLongerThan(IrisPosition s, int maxLength) { - return Math.abs(Math.pow(s.x - x, 2) + Math.pow(s.y - y, 2) + Math.pow(s.z - z, 2)) > maxLength * maxLength; - } - - public Vector toVector() { - return new Vector(x, y, z); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisPosition2D.java b/src/main/java/com/volmit/iris/engine/object/IrisPosition2D.java deleted file mode 100644 index e56aee810..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisPosition2D.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("position-2d") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a position") -@Data -public class IrisPosition2D { - @Desc("The x position") - private int x = 0; - - @Desc("The z position") - private int z = 0; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisPotionEffect.java b/src/main/java/com/volmit/iris/engine/object/IrisPotionEffect.java deleted file mode 100644 index a185310d4..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisPotionEffect.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor - -@Snippet("potion-effect") -@Desc("An iris potion effect") -@Data -public class IrisPotionEffect { - private final transient AtomicCache pt = new AtomicCache<>(); - @Required - @Desc("The potion effect to apply in this area") - private String potionEffect = ""; - @Required - @MinNumber(-1) - @MaxNumber(1024) - @Desc("The Potion Strength or -1 to disable") - private int strength = -1; - @Required - @MinNumber(1) - @Desc("The time the potion will last for") - private int ticks = 200; - @Desc("Is the effect ambient") - private boolean ambient = false; - @Desc("Is the effect showing particles") - private boolean particles = true; - - public PotionEffectType getRealType() { - return pt.aquire(() -> - { - PotionEffectType t = PotionEffectType.LUCK; - - if(getPotionEffect().isEmpty()) { - return t; - } - - try { - for(PotionEffectType i : PotionEffectType.values()) { - if(i.getName().toUpperCase().replaceAll("\\Q \\E", "_").equals(getPotionEffect())) { - t = i; - - return t; - } - } - } catch(Throwable e) { - Iris.reportError(e); - - } - - Iris.warn("Unknown Potion Effect Type: " + getPotionEffect()); - - return t; - }); - } - - public void apply(LivingEntity p) { - if(strength > -1) { - if(p.hasPotionEffect(getRealType())) { - PotionEffect e = p.getPotionEffect(getRealType()); - if(e.getAmplifier() > strength) { - return; - } - - p.removePotionEffect(getRealType()); - } - - p.addPotionEffect(new PotionEffect(getRealType(), ticks, strength, ambient, particles, false)); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisPyramid.java b/src/main/java/com/volmit/iris/engine/object/IrisPyramid.java deleted file mode 100644 index a05071df9..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisPyramid.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.matter.slices.CavernMatter; -import lombok.Data; - -@Snippet("carving-pyramid") -@Desc("Represents an procedural eliptical shape") -@Data -public class IrisPyramid implements IRare { - private transient final AtomicCache matterNodeCache = new AtomicCache<>(); - @Required - @Desc("Typically a 1 in RARITY on a per fork basis") - @MinNumber(1) - private int rarity = 1; - @RegistryListResource(IrisBiome.class) - @Desc("Force this cave to only generate the specified custom biome") - private String customBiome = ""; - @Desc("The styled random radius for x") - private IrisStyledRange baseWidth = new IrisStyledRange(1, 5, new IrisGeneratorStyle(NoiseStyle.STATIC)); - - public void generate(RNG rng, Engine engine, MantleWriter writer, int x, int y, int z) { - writer.setPyramid(x, y, z, matterNodeCache.aquire(() -> CavernMatter.get(getCustomBiome(), 0)), - (int) baseWidth.get(rng, z, y, engine.getData()), true); - } - - public double maxSize() { - return baseWidth.getMax(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisRange.java b/src/main/java/com/volmit/iris/engine/object/IrisRange.java deleted file mode 100644 index 4c7732515..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisRange.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("range") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a range") -@Data -public class IrisRange { - @Desc("The minimum value") - private double min = 16; - - @Desc("The maximum value") - private double max = 32; - - public double get(RNG rng) { - if(min == max) { - return min; - } - - return rng.d(min, max); - } - - public boolean contains(int v) { - return v >= min && v <= max; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisRareObject.java b/src/main/java/com/volmit/iris/engine/object/IrisRareObject.java deleted file mode 100644 index 86946cf42..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisRareObject.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("rare-object") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a structure tile") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisRareObject { - @Required - @MinNumber(1) - @Desc("The rarity is 1 in X") - private int rarity = 1; - - @RegistryListResource(IrisObject.class) - @Required - @Desc("The object to place if rarity check passed") - private String object = ""; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisRate.java b/src/main/java/com/volmit/iris/engine/object/IrisRate.java deleted file mode 100644 index a365fe544..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisRate.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.scheduling.ChronoLatch; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Snippet("rate") -@NoArgsConstructor -@AllArgsConstructor -@Data -@Desc("Represents a count of something per time duration") -public class IrisRate { - @Desc("The amount of things. Leave 0 for infinite (meaning always spawn whenever)") - private int amount = 0; - - @Desc("The time interval. Leave blank for infinite 0 (meaning always spawn all the time)") - private IrisDuration per = new IrisDuration(); - - public String toString() { - return Form.f(amount) + "/" + per; - } - - public long getInterval() { - long t = per.getMilliseconds() / (amount == 0 ? 1 : amount); - return Math.abs(t <= 0 ? 1 : t); - } - - public ChronoLatch toChronoLatch() { - return new ChronoLatch(getInterval()); - } - - public boolean isInfinite() { - return per.toMilliseconds() == 0; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisRavine.java b/src/main/java/com/volmit/iris/engine/object/IrisRavine.java deleted file mode 100644 index cb935920a..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisRavine.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@EqualsAndHashCode(callSuper = true) -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Translate objects") -@Data -public class IrisRavine extends IrisRegistrant { - @Desc("Define the shape of this ravine (2d, ignores Y)") - private IrisWorm worm = new IrisWorm(); - - @RegistryListResource(IrisBiome.class) - @Desc("Force this cave to only generate the specified custom biome") - private String customBiome = ""; - - @Desc("Define potential forking features") - private IrisCarving fork = new IrisCarving(); - - @Desc("The style used to determine the curvature of this worm's y") - private IrisShapedGeneratorStyle depthStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN, 5, 18); - - @Desc("The style used to determine the curvature of this worm's y") - private IrisShapedGeneratorStyle baseWidthStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN, 3, 6); - - @MinNumber(1) - @MaxNumber(100) - @Desc("The angle at which the ravine widens as it gets closer to the surface") - private double angle = 18; - - @MinNumber(1) - @MaxNumber(100) - @Desc("The angle at which the ravine widens as it gets closer to the surface") - private double topAngle = 38; - - @Desc("To fill this cave with lava, set the lava level to a height from the bottom most point of the cave.") - private int lavaLevel = -1; - - @Desc("How many worm nodes must be placed to actually generate a ravine? Higher reduces the chances but also reduces ravine 'holes'") - private int nodeThreshold = 5; - - @MinNumber(1) - @MaxNumber(8) - @Desc("The thickness of the ravine ribs") - private double ribThickness = 3; - - @Override - public String getFolderName() { - return "ravines"; - } - - @Override - public String getTypeName() { - return "Ravine"; - } - - public void generate(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z) { - generate(writer, rng, engine, x, y, z, -1); - } - - public void generate(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z, int waterHint) { - KList pos = getWorm().generate(rng, engine.getData(), writer, null, x, y, z, (at) -> { - }); - CNG dg = depthStyle.getGenerator().createNoCache(rng, engine.getData()); - CNG bw = baseWidthStyle.getGenerator().createNoCache(rng, engine.getData()); - int highestWater = Math.max(waterHint, -1); - boolean water = false; - - if(highestWater == -1) { - for(IrisPosition i : pos) { - int rsurface = y == -1 ? engine.getComplex().getHeightStream().get(x, z).intValue() : y; - int depth = (int) Math.round(dg.fitDouble(depthStyle.getMin(), depthStyle.getMax(), i.getX(), i.getZ())); - int surface = (int) Math.round(rsurface - depth * 0.45); - int yy = surface + depth; - int th = engine.getHeight(x, z, true); - - if(yy > th && th < engine.getDimension().getFluidHeight()) { - highestWater = Math.max(highestWater, yy); - water = true; - break; - } - } - } else { - water = true; - } - - MatterCavern c = new MatterCavern(true, customBiome, (byte) (water ? 1 : 0)); - MatterCavern l = new MatterCavern(true, customBiome, (byte) 2); - - if(pos.size() < nodeThreshold) { - return; - } - - for(IrisPosition p : pos) { - int rsurface = y == -1 ? engine.getComplex().getHeightStream().get(x, z).intValue() : y; - int depth = (int) Math.round(dg.fitDouble(depthStyle.getMin(), depthStyle.getMax(), p.getX(), p.getZ())); - int width = (int) Math.round(bw.fitDouble(baseWidthStyle.getMin(), baseWidthStyle.getMax(), p.getX(), p.getZ())); - int surface = (int) Math.round(rsurface - depth * 0.45); - - fork.doCarving(writer, rng, engine, p.getX(), rng.i(surface - depth, surface), p.getZ(), Math.max(highestWater, waterHint)); - - for(int i = surface + depth; i >= surface; i--) { - if(i % ribThickness == 0) { - double v = width + ((((surface + depth) - i) * (angle / 360D))); - - if(v <= 0.25) { - break; - } - - if(i <= ribThickness + 2) { - break; - } - - if(lavaLevel >= 0 && i <= lavaLevel + (surface - depthStyle.getMid())) { - writer.setElipsoid(p.getX(), i, p.getZ(), v, ribThickness, v, true, l); - } else { - writer.setElipsoid(p.getX(), i, p.getZ(), v, ribThickness, v, true, c); - } - } - } - - for(int i = surface - depth; i <= surface; i++) { - if(i % ribThickness == 0) { - double v = width - ((((surface - depth) - i) * (angle / 360D))); - - if(v <= 0.25) { - break; - } - - if(i <= ribThickness + 2) { - break; - } - - if(lavaLevel >= 0 && i <= lavaLevel + (surface - depthStyle.getMid())) { - writer.setElipsoid(p.getX(), i, p.getZ(), v, ribThickness, v, true, l); - } else { - writer.setElipsoid(p.getX(), i, p.getZ(), v, ribThickness, v, true, c); - } - } - } - } - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } - - public int getMaxSize(IrisData data) { - return getWorm().getMaxDistance() + fork.getMaxRange(data); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisRavinePlacer.java b/src/main/java/com/volmit/iris/engine/object/IrisRavinePlacer.java deleted file mode 100644 index ee885957a..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisRavinePlacer.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.concurrent.atomic.AtomicBoolean; - -@Snippet("ravine-placer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Translate objects") -@Data -public class IrisRavinePlacer implements IRare { - private transient final AtomicCache ravineCache = new AtomicCache<>(); - private transient final AtomicBoolean fail = new AtomicBoolean(false); - @Required - @Desc("Typically a 1 in RARITY on a per chunk/fork basis") - @MinNumber(1) - private int rarity = 15; - @MinNumber(1) - @Required - @Desc("The ravine to place") - @RegistryListResource(IrisRavine.class) - private String ravine; - - public IrisRavine getRealRavine(IrisData data) { - return ravineCache.aquire(() -> data.getRavineLoader().load(getRavine())); - } - - public void generateRavine(MantleWriter mantle, RNG rng, Engine engine, int x, int y, int z) { - generateRavine(mantle, rng, engine, x, y, z, -1); - } - - public void generateRavine(MantleWriter mantle, RNG rng, Engine engine, int x, int y, int z, int waterHint) { - if(fail.get()) { - return; - } - - if(rng.nextInt(rarity) != 0) { - return; - } - - IrisData data = engine.getData(); - IrisRavine ravine = getRealRavine(data); - - if(ravine == null) { - Iris.warn("Unable to locate ravine for generation!"); - fail.set(true); - return; - } - - try { - int xx = x + rng.nextInt(15); - int zz = z + rng.nextInt(15); - ravine.generate(mantle, rng, engine, xx, y, zz, waterHint); - } catch(Throwable e) { - e.printStackTrace(); - fail.set(true); - } - } - - public int getSize(IrisData data) { - return getRealRavine(data).getMaxSize(data); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisRegion.java b/src/main/java/com/volmit/iris/engine/object/IrisRegion.java deleted file mode 100644 index 8322bdbc0..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisRegion.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.gui.components.RenderType; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.data.DataProvider; -import com.volmit.iris.util.data.VanillaBiomeMap; -import com.volmit.iris.util.inventorygui.RandomColor; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; - -import java.awt.Color; -import java.util.Random; - - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an iris region") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisRegion extends IrisRegistrant implements IRare { - private final transient AtomicCache> surfaceObjectsCache = new AtomicCache<>(); - private final transient AtomicCache> carveObjectsCache = new AtomicCache<>(); - private final transient AtomicCache> cacheRidge = new AtomicCache<>(); - private final transient AtomicCache> cacheSpot = new AtomicCache<>(); - private final transient AtomicCache shoreHeightGenerator = new AtomicCache<>(); - private final transient AtomicCache> realLandBiomes = new AtomicCache<>(); - private final transient AtomicCache> realLakeBiomes = new AtomicCache<>(); - private final transient AtomicCache> realRiverBiomes = new AtomicCache<>(); - private final transient AtomicCache> realSeaBiomes = new AtomicCache<>(); - private final transient AtomicCache> realShoreBiomes = new AtomicCache<>(); - private final transient AtomicCache> realCaveBiomes = new AtomicCache<>(); - private final transient AtomicCache lakeGen = new AtomicCache<>(); - private final transient AtomicCache riverGen = new AtomicCache<>(); - private final transient AtomicCache riverChanceGen = new AtomicCache<>(); - private final transient AtomicCache cacheColor = new AtomicCache<>(); - @MinNumber(2) - @Required - @Desc("The name of the region") - private String name = "A Region"; - @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) - @Desc("Jigsaw structures") - private KList jigsawStructures = new KList<>(); - @ArrayType(min = 1, type = IrisEffect.class) - @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play arround the player even if where the effect was played is no longer in the biome the player is in.") - private KList effects = new KList<>(); - @Desc("Spawn Entities in this region over time. Iris will continually replenish these mobs just like vanilla does.") - @ArrayType(min = 1, type = String.class) - @RegistryListResource(IrisSpawner.class) - private KList entitySpawners = new KList<>(); - @MinNumber(1) - @MaxNumber(128) - @Desc("The rarity of the region") - private int rarity = 1; - @ArrayType(min = 1, type = IrisBlockDrops.class) - @Desc("Define custom block drops for this region") - private KList blockDrops = new KList<>(); - @RegistryListResource(IrisSpawner.class) - @ArrayType(min = 1, type = IrisObjectPlacement.class) - @Desc("Objects define what schematics (iob files) iris will place in this region") - private KList objects = new KList<>(); - @MinNumber(0) - @Desc("The min shore height") - private double shoreHeightMin = 1.2; - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); - @MinNumber(0) - @Desc("The the max shore height") - private double shoreHeightMax = 3.2; - @MinNumber(0.0001) - @Desc("The varience of the shore height") - private double shoreHeightZoom = 3.14; - @MinNumber(0.0001) - @Desc("How large land biomes are in this region") - private double landBiomeZoom = 1; - @MinNumber(0.0001) - @Desc("How large shore biomes are in this region") - private double shoreBiomeZoom = 1; - @MinNumber(0.0001) - @Desc("How large sea biomes are in this region") - private double seaBiomeZoom = 1; - @MinNumber(0.0001) - @Desc("How large cave biomes are in this region") - private double caveBiomeZoom = 1; - @Desc("Carving configuration for the dimension") - private IrisCarving carving = new IrisCarving(); - @Desc("Configuration of fluid bodies such as rivers & lakes") - private IrisFluidBodies fluidBodies = new IrisFluidBodies(); - @RegistryListResource(IrisBiome.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("A list of root-level biomes in this region. Don't specify child biomes of other biomes here. Just the root parents.") - private KList landBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("A list of root-level biomes in this region. Don't specify child biomes of other biomes here. Just the root parents.") - private KList seaBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("A list of root-level biomes in this region. Don't specify child biomes of other biomes here. Just the root parents.") - private KList shoreBiomes = new KList<>(); - @RegistryListResource(IrisBiome.class) - @ArrayType(min = 1, type = String.class) - @Desc("A list of root-level biomes in this region. Don't specify child biomes of other biomes here. Just the root parents.") - private KList caveBiomes = new KList<>(); - @ArrayType(min = 1, type = IrisDepositGenerator.class) - @Desc("Define regional deposit generators that add onto the global deposit generators") - private KList deposits = new KList<>(); - @Desc("The style of rivers") - private IrisGeneratorStyle riverStyle = NoiseStyle.VASCULAR_THIN.style().zoomed(7.77); - @Desc("The style of lakes") - private IrisGeneratorStyle lakeStyle = NoiseStyle.CELLULAR_IRIS_THICK.style(); - @Desc("A color for visualizing this region with a color. I.e. #F13AF5. This will show up on the map.") - private String color = null; - @Desc("Collection of ores to be generated") - @ArrayType(type = IrisOreGenerator.class, min = 1) - private KList ores = new KList<>(); - - public BlockData generateOres(int x, int y, int z, RNG rng, IrisData data) { - if(ores.isEmpty()) { - return null; - } - BlockData b = null; - for(IrisOreGenerator i : ores) { - - b = i.generate(x, y, z, rng, data); - if(b != null) { - return b; - } - } - return null; - } - - public String getName() { - return name; - } - - public KList getSurfaceObjects() { - return getSurfaceObjectsCache().aquire(() -> - { - KList o = getObjects().copy(); - - for(IrisObjectPlacement i : o.copy()) { - if(!i.getCarvingSupport().supportsSurface()) { - o.remove(i); - } - } - - return o; - }); - } - - public KList getCarvingObjects() { - return getCarveObjectsCache().aquire(() -> - { - KList o = getObjects().copy(); - - for(IrisObjectPlacement i : o.copy()) { - if(!i.getCarvingSupport().supportsCarving()) { - o.remove(i); - } - } - - return o; - }); - } - - public double getBiomeZoom(InferredType t) { - switch(t) { - case CAVE: - return caveBiomeZoom; - case LAND: - return landBiomeZoom; - case SEA: - return seaBiomeZoom; - case SHORE: - return shoreBiomeZoom; - default: - break; - } - - return 1; - } - - public CNG getShoreHeightGenerator() { - return shoreHeightGenerator.aquire(() -> - CNG.signature(new RNG((long) (getName().length() + getLandBiomeZoom() + getLandBiomes().size() + 3458612)))); - } - - public double getShoreHeight(double x, double z) { - return getShoreHeightGenerator().fitDouble(shoreHeightMin, shoreHeightMax, x / shoreHeightZoom, z / shoreHeightZoom); - } - - public KSet getAllBiomeIds() { - KSet names = new KSet<>(); - names.addAll(landBiomes); - names.addAll(caveBiomes); - names.addAll(seaBiomes); - names.addAll(shoreBiomes); - - return names; - } - - public KList getAllBiomes(DataProvider g) { - KMap b = new KMap<>(); - KSet names = getAllBiomeIds(); - - while(!names.isEmpty()) { - for(String i : new KList<>(names)) { - if(b.containsKey(i)) { - names.remove(i); - continue; - } - - IrisBiome biome = g.getData().getBiomeLoader().load(i); - - names.remove(i); - if(biome == null) { - continue; - } - - names.add(biome.getCarvingBiome()); - b.put(biome.getLoadKey(), biome); - names.addAll(biome.getChildren()); - } - } - - return b.v(); - } - - public KList getBiomes(DataProvider g, InferredType type) { - if(type.equals(InferredType.LAND)) { - return getRealLandBiomes(g); - } else if(type.equals(InferredType.SEA)) { - return getRealSeaBiomes(g); - } else if(type.equals(InferredType.SHORE)) { - return getRealShoreBiomes(g); - } else if(type.equals(InferredType.CAVE)) { - return getRealCaveBiomes(g); - } - - return new KList<>(); - } - - public KList getRealCaveBiomes(DataProvider g) { - return realCaveBiomes.aquire(() -> - { - KList realCaveBiomes = new KList<>(); - - for(String i : getCaveBiomes()) { - realCaveBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realCaveBiomes; - }); - } - - public KList getRealShoreBiomes(DataProvider g) { - return realShoreBiomes.aquire(() -> - { - KList realShoreBiomes = new KList<>(); - - for(String i : getShoreBiomes()) { - realShoreBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realShoreBiomes; - }); - } - - public KList getRealSeaBiomes(DataProvider g) { - return realSeaBiomes.aquire(() -> - { - KList realSeaBiomes = new KList<>(); - - for(String i : getSeaBiomes()) { - realSeaBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realSeaBiomes; - }); - } - - public KList getRealLandBiomes(DataProvider g) { - return realLandBiomes.aquire(() -> - { - KList realLandBiomes = new KList<>(); - - for(String i : getLandBiomes()) { - realLandBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realLandBiomes; - }); - } - - public KList getAllAnyBiomes() { - KMap b = new KMap<>(); - KSet names = new KSet<>(); - names.addAll(landBiomes); - names.addAll(caveBiomes); - names.addAll(seaBiomes); - names.addAll(shoreBiomes); - - while(!names.isEmpty()) { - for(String i : new KList<>(names)) { - if(b.containsKey(i)) { - names.remove(i); - continue; - } - - IrisBiome biome = IrisData.loadAnyBiome(i); - - names.remove(i); - if(biome == null) { - continue; - } - - names.add(biome.getCarvingBiome()); - b.put(biome.getLoadKey(), biome); - names.addAll(biome.getChildren()); - } - } - - return b.v(); - } - - public Color getColor(DataProvider dataProvider, RenderType type) { - return this.cacheColor.aquire(() -> { - if(this.color == null) { - Random rand = new Random(getName().hashCode() + getAllBiomeIds().hashCode()); - RandomColor randomColor = new RandomColor(rand); - - KList biomes = getRealLandBiomes(dataProvider); - - while(biomes.size() > 0) { - int index = rand.nextInt(biomes.size()); - IrisBiome biome = biomes.get(index); - - if(biome.getVanillaDerivative() != null) { - RandomColor.Color col = VanillaBiomeMap.getColorType(biome.getVanillaDerivative()); - RandomColor.Luminosity lum = VanillaBiomeMap.getColorLuminosity(biome.getVanillaDerivative()); - RandomColor.SaturationType sat = VanillaBiomeMap.getColorSaturatiom(biome.getVanillaDerivative()); - int newColorI = randomColor.randomColor(col, col == RandomColor.Color.MONOCHROME ? RandomColor.SaturationType.MONOCHROME : sat, lum); - return new Color(newColorI); - } - - biomes.remove(index); - } - - Iris.warn("Couldn't find a suitable color for region " + getName()); - return new Color(new RandomColor(rand).randomColor()); - } - - try { - return Color.decode(this.color); - } catch(NumberFormatException e) { - Iris.warn("Could not parse color \"" + this.color + "\" for region " + getName()); - return Color.WHITE; - } - }); - } - - public void pickRandomColor(DataProvider data) { - - } - - @Override - public String getFolderName() { - return "regions"; - } - - @Override - public String getTypeName() { - return "Region"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisRiver.java b/src/main/java/com/volmit/iris/engine/object/IrisRiver.java deleted file mode 100644 index 10fb8155b..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisRiver.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("river") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an Iris river") -@Data -public class IrisRiver implements IRare { - @Required - @Desc("Typically a 1 in RARITY on a per chunk/fork basis") - @MinNumber(1) - private int rarity = 15; - - @Desc("The width style of this river") - private IrisStyledRange width = new IrisStyledRange(3, 6, NoiseStyle.PERLIN.style()); - - @Desc("Define the shape of this river") - private IrisWorm worm = new IrisWorm(); - - @RegistryListResource(IrisBiome.class) - @Desc("Force this river to only generate the specified custom biome") - private String customBiome = ""; - - @Desc("The width style of this lake") - private IrisShapedGeneratorStyle widthStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN.style(), 5, 9); - - @Desc("The depth style of this lake") - private IrisShapedGeneratorStyle depthStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN.style(), 4, 7); - - public int getSize(IrisData data) { - return worm.getMaxDistance(); - } - - public void generate(MantleWriter writer, RNG rng, Engine engine, int x, int y, int z) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisScript.java b/src/main/java/com/volmit/iris/engine/object/IrisScript.java deleted file mode 100644 index 7c28be980..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisScript.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.Data; -import lombok.EqualsAndHashCode; - -@EqualsAndHashCode(callSuper = true) -@Data -public class IrisScript extends IrisRegistrant { - private final String source; - - public IrisScript() { - this(""); - } - - public IrisScript(String source) { - this.source = source; - } - - @Override - public String getFolderName() { - return "scripts"; - } - - @Override - public String getTypeName() { - return "Script"; - } - - public String toString() { - return source; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisSeed.java b/src/main/java/com/volmit/iris/engine/object/IrisSeed.java deleted file mode 100644 index 370ddac3e..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisSeed.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("color") -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents a color") -@Data -public class IrisSeed { - @Desc("The seed to use") - private long seed = 1337; - - @Desc("To calculate a seed Iris passes in it's natural seed for the current feature, then mixes it with your seed. Setting this to true ignores the parent seed and always uses your exact seed ignoring the input of Iris feature seeds. You can use this to match seeds on other generators.") - private boolean ignoreNaturalSeedInput = false; - - public long getSeed(long seed) { - return (seed * 47) + getSeed() + 29334667L; - } - - public RNG rng(long inseed) { - return new RNG(getSeed(inseed)); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisShapedGeneratorStyle.java b/src/main/java/com/volmit/iris/engine/object/IrisShapedGeneratorStyle.java deleted file mode 100644 index 8aa25febd..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisShapedGeneratorStyle.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("shaped-style") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("This represents a generator with a min and max height") -@Data -public class IrisShapedGeneratorStyle { - @Required - @Desc("The generator id") - private IrisGeneratorStyle generator = new IrisGeneratorStyle(NoiseStyle.IRIS); - - @Required - @MinNumber(-2032) // TODO: WARNING HEIGHT - @MaxNumber(2032) // TODO: WARNING HEIGHT - @Desc("The min block value") - private int min = 0; - - @Required - @MinNumber(-2032) // TODO: WARNING HEIGHT - @MaxNumber(2032) // TODO: WARNING HEIGHT - @Desc("The max block value") - private int max = 0; - - public IrisShapedGeneratorStyle(NoiseStyle style, int min, int max) { - this(style); - this.min = min; - this.max = max; - } - - public IrisShapedGeneratorStyle(NoiseStyle style) { - this.generator = new IrisGeneratorStyle(style); - } - - public double get(RNG rng, IrisData data, double... dim) { - return generator.create(rng, data).fitDouble(min, max, dim); - } - - public boolean isFlat() { - return min == max || getGenerator().isFlat(); - } - - public int getMid() { - return (getMax() + getMin()) / 2; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisSlopeClip.java b/src/main/java/com/volmit/iris/engine/object/IrisSlopeClip.java deleted file mode 100644 index 521d493d1..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisSlopeClip.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("slope-clip") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Translate objects") -@Data -public class IrisSlopeClip { - @MinNumber(0) - @MaxNumber(1024) - @Desc("The minimum slope for placement") - private double minimumSlope = 0; - - @MinNumber(0) - @MaxNumber(1024) - @Desc("The maximum slope for placement") - private double maximumSlope = 10; - - public boolean isDefault() { - return minimumSlope <= 0 && maximumSlope >= 10; - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isValid(double slope) { - if(isDefault()) { - return true; - } - - return !(minimumSlope > slope) && !(maximumSlope < slope); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisSpawnGroup.java b/src/main/java/com/volmit/iris/engine/object/IrisSpawnGroup.java deleted file mode 100644 index 2b0ff8b69..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisSpawnGroup.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Terrain modes are used to decide the generator type currently used") -public enum IrisSpawnGroup { - @Desc("Spawns on the terrain surface") - NORMAL, - - @Desc("Spawns in cave-air and low light level areas") - CAVE, - - @Desc("Spawns underwater") - UNDERWATER, - - @Desc("Spawns in beaches") - BEACH -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisSpawner.java b/src/main/java/com/volmit/iris/engine/object/IrisSpawner.java deleted file mode 100644 index 212905404..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisSpawner.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.World; - -@EqualsAndHashCode(callSuper = true) -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an entity spawn during initial chunk generation") -@Data -public class IrisSpawner extends IrisRegistrant { - - private transient IrisMarker referenceMarker; - - @ArrayType(min = 1, type = IrisEntitySpawn.class) - @Desc("The entity spawns to add") - private KList spawns = new KList<>(); - - @ArrayType(min = 1, type = IrisEntitySpawn.class) - @Desc("The entity spawns to add initially. EXECUTES PER CHUNK!") - private KList initialSpawns = new KList<>(); - - @Desc("The energy multiplier when calculating spawn energy usage") - private double energyMultiplier = 1; - - @Desc("This spawner will not spawn in a given chunk if that chunk has more than the defined amount of living entities.") - private int maxEntitiesPerChunk = 1; - - @Desc("The block of 24 hour time to contain this spawn in.") - private IrisTimeBlock timeBlock = new IrisTimeBlock(); - - @Desc("The block of 24 hour time to contain this spawn in.") - private IrisWeather weather = IrisWeather.ANY; - - @Desc("The maximum rate this spawner can fire") - private IrisRate maximumRate = new IrisRate(); - - @Desc("The maximum rate this spawner can fire on a specific chunk") - private IrisRate maximumRatePerChunk = new IrisRate(); - - @Desc("The light levels this spawn is allowed to run in (0-15 inclusive)") - private IrisRange allowedLightLevels = new IrisRange(0, 15); - - @Desc("Where should these spawns be placed") - private IrisSpawnGroup group = IrisSpawnGroup.NORMAL; - - public boolean isValid(IrisBiome biome) { - return switch(group) { - case NORMAL -> switch(biome.getInferredType()) { - case SHORE, SEA, CAVE, DEFER -> false; - case LAND -> true; - }; - case CAVE -> true; - case UNDERWATER -> switch(biome.getInferredType()) { - case SHORE, LAND, CAVE, DEFER -> false; - case SEA -> true; - }; - case BEACH -> switch(biome.getInferredType()) { - case SHORE -> true; - case LAND, CAVE, SEA, DEFER -> false; - }; - }; - } - - public boolean isValid(World world) { - return timeBlock.isWithin(world) && weather.is(world); - } - - @Override - public String getFolderName() { - return "spawners"; - } - - @Override - public String getTypeName() { - return "Spawner"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisSphere.java b/src/main/java/com/volmit/iris/engine/object/IrisSphere.java deleted file mode 100644 index 06fd43f21..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisSphere.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListResource; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.matter.slices.CavernMatter; -import lombok.Data; - -@Snippet("carving-sphere") -@Desc("Represents an procedural eliptical shape") -@Data -public class IrisSphere implements IRare { - private transient final AtomicCache matterNodeCache = new AtomicCache<>(); - @Required - @Desc("Typically a 1 in RARITY on a per fork basis") - @MinNumber(1) - private int rarity = 1; - @RegistryListResource(IrisBiome.class) - @Desc("Force this cave to only generate the specified custom biome") - private String customBiome = ""; - @Desc("The styled random radius for x") - private IrisStyledRange radius = new IrisStyledRange(1, 5, new IrisGeneratorStyle(NoiseStyle.STATIC)); - - public void generate(RNG rng, Engine engine, MantleWriter writer, int x, int y, int z) { - writer.setSphere(x, y, z, radius.get(rng, z, y, engine.getData()), true, matterNodeCache.aquire(() -> CavernMatter.get(getCustomBiome(), 0))); - } - - public double maxSize() { - return radius.getMax(); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisStiltSettings.java b/src/main/java/com/volmit/iris/engine/object/IrisStiltSettings.java deleted file mode 100644 index ca4bd55a6..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisStiltSettings.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("stilt-settings") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Defines stilting behaviour.") -@Data -public class IrisStiltSettings { - @MinNumber(0) - @MaxNumber(64) - @Desc("Defines the maximum amount of blocks the object stilts verticially before overstilting and randomRange.") - private int yMax; - @MinNumber(0) - @MaxNumber(64) - @Desc("Defines the upper boundary for additional blocks after overstilting and/or maxStiltRange.") - private int yRand; - @MaxNumber(64) - @MinNumber(0) - @Desc("If the place mode is set to stilt, you can over-stilt it even further into the ground. Especially useful when using fast stilt due to inaccuracies.") - private int overStilt; - @Desc("If defined, stilting will be done using this block palette rather than the last layer of the object.") - private IrisMaterialPalette palette; - -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisStyledRange.java b/src/main/java/com/volmit/iris/engine/object/IrisStyledRange.java deleted file mode 100644 index 410ffbdec..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisStyledRange.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.stream.interpolation.Interpolated; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("style-range") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a range styled with a custom generator") -@Data -public class IrisStyledRange { - @Desc("The minimum value") - private double min = 16; - - @Desc("The maximum value") - private double max = 32; - - @Desc("The style to pick the range") - private IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.STATIC); - - public double get(RNG rng, double x, double z, IrisData data) { - if(min == max) { - return min; - } - - if(style.isFlat()) { - return M.lerp(min, max, 0.5); - } - - return style.create(rng, data).fitDouble(min, max, x, z); - } - - public ProceduralStream stream(RNG rng, IrisData data) { - return ProceduralStream.of((x, z) -> get(rng, x, z, data), Interpolated.DOUBLE); - } - - public boolean isFlat() { - return getMax() == getMin() || style.isFlat(); - } - - public int getMid() { - return (int) ((getMax() + getMin()) / 2); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisSurface.java b/src/main/java/com/volmit/iris/engine/object/IrisSurface.java deleted file mode 100644 index bbf3ae064..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisSurface.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.Waterlogged; - -@Desc("The type of surface entities should spawn on") -public enum IrisSurface { - - @Desc("Land surfaces") - LAND, - - @Desc("Any surfaces animals can spawn on, such as dirt, grass and podzol") - ANIMAL, - - @Desc("Within the water") - WATER, - - @Desc("On land or on water") - OVERWORLD, - - @Desc("Within lava") - LAVA; - - /** - * Check if this Iris surface matches the blockstate provided - * - * @param state - * The blockstate - * @return True if it matches - */ - public boolean matches(Block state) { - Material type = state.getType(); - if(type.isSolid()) { - return this == LAND || this == OVERWORLD || (this == ANIMAL - && (type == Material.GRASS_BLOCK || type == Material.DIRT - || type == Material.DIRT_PATH || type == Material.COARSE_DIRT - || type == Material.ROOTED_DIRT || type == Material.PODZOL - || type == Material.MYCELIUM || type == Material.SNOW_BLOCK)); - } - if(type == Material.LAVA) return this == LAVA; - if(type == Material.WATER || type == Material.SEAGRASS - || type == Material.TALL_SEAGRASS || type == Material.KELP_PLANT - || type == Material.KELP || - (state instanceof Waterlogged && ((Waterlogged) state).isWaterlogged())) - return this == WATER || this == OVERWORLD; - - return false; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisTimeBlock.java b/src/main/java/com/volmit/iris/engine/object/IrisTimeBlock.java deleted file mode 100644 index bee1fdc6a..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisTimeBlock.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.Data; -import org.bukkit.World; - -@Snippet("time-block") -@Data -@Desc("Represents a time of day (24h time, not 12h am/pm). Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") -public class IrisTimeBlock { - @Desc("The beginning hour. Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") - private double startHour = 0; - - @Desc("The ending hour. Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") - private double endHour = 0; - - public boolean isWithin(World world) { - return isWithin(((world.getTime() / 1000D) + 6) % 24); - } - - public boolean isWithin(double hour) { - if(startHour == endHour) { - return endHour != -1; - } - - if(startHour > endHour) { - return hour >= startHour || hour <= endHour; - } - - return hour >= startHour && hour <= endHour; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisTree.java b/src/main/java/com/volmit/iris/engine/object/IrisTree.java deleted file mode 100644 index 15adaad67..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisTree.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.TreeType; - -@Snippet("tree") -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Tree replace options for this object placer") -@Data -public class IrisTree { - @Required - @Desc("The types of trees overwritten by this object") - @ArrayType(min = 1, type = TreeType.class) - private KList treeTypes; - - @Desc("If enabled, overrides any TreeType") - private boolean anyTree = false; - - @Required - @Desc("The size of the square of saplings this applies to (2 means a 2 * 2 sapling area)") - @ArrayType(min = 1, type = IrisTreeSize.class) - private KList sizes = new KList<>(); - - @Desc("If enabled, overrides trees of any size") - private boolean anySize; - - public boolean matches(IrisTreeSize size, TreeType type) { - if(!matchesSize(size)) { - return false; - } - - return matchesType(type); - } - - private boolean matchesSize(IrisTreeSize size) { - for(IrisTreeSize i : getSizes()) { - if((i.getDepth() == size.getDepth() && i.getWidth() == size.getWidth()) || (i.getDepth() == size.getWidth() && i.getWidth() == size.getDepth())) { - return true; - } - } - - return false; - } - - private boolean matchesType(TreeType type) { - return getTreeTypes().contains(type); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/engine/object/IrisTreeModes.java b/src/main/java/com/volmit/iris/engine/object/IrisTreeModes.java deleted file mode 100644 index adc5d03c6..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisTreeModes.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Sapling override object picking options") -public enum IrisTreeModes { - @Desc("Check biome, then region, then dimension, pick the first one that has options") - FIRST, - - @Desc("Check biome, regions, and dimensions, and pick any option from the total list") - ALL -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/engine/object/IrisTreeSettings.java b/src/main/java/com/volmit/iris/engine/object/IrisTreeSettings.java deleted file mode 100644 index b3afde29c..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisTreeSettings.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("tree-settings") -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Tree growth override settings") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisTreeSettings { - - @Required - @Desc("Turn replacing on and off") - boolean enabled = false; - - @Desc("Object picking modes") - IrisTreeModes mode = IrisTreeModes.FIRST; -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisTreeSize.java b/src/main/java/com/volmit/iris/engine/object/IrisTreeSize.java deleted file mode 100644 index dd3445f82..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisTreeSize.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("tree-size") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Sapling override object picking options") -@Data -public class IrisTreeSize { - - @Required - @Desc("The width of the sapling area") - int width = 1; - - @Required - @Desc("The depth of the sapling area") - int depth = 1; - - /** - * Does the size match - * - * @param size - * the size to check match - * @return true if it matches (fits within width and depth) - */ - public boolean doesMatch(IrisTreeSize size) { - return (width == size.getWidth() && depth == size.getDepth()) || (depth == size.getWidth() && width == size.getDepth()); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisVillagerOverride.java b/src/main/java/com/volmit/iris/engine/object/IrisVillagerOverride.java deleted file mode 100644 index 69c5edd38..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisVillagerOverride.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.ArrayType; -import com.volmit.iris.engine.object.annotations.DependsOn; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -@Snippet("villager-override") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Override cartographer map trades with others or disable the trade altogether") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisVillagerOverride { - @Desc(""" - Disable the trade altogether. - If a cartographer villager gets a new explorer map trade: - If this is enabled -> the trade is removed - If this is disabled -> the trade is replaced with the "override" setting below - Default is true, so if you omit this, trades will be removed.""") - private boolean disableTrade = true; - - @DependsOn("disableTrade") - @Required - @Desc(""" - The items to override the cartographer trade with. - By default, this is: - 3 emeralds + 3 glass blocks -> 1 spyglass. - Can trade 3 to 5 times""") - @ArrayType(min = 1, type = IrisVillagerTrade.class) - private KList items = new KList<>(new IrisVillagerTrade() - .setIngredient1(new ItemStack(Material.EMERALD, 3)) - .setIngredient2(new ItemStack(Material.GLASS, 3)) - .setResult(new ItemStack(Material.SPYGLASS)) - .setMinTrades(3) - .setMaxTrades(5)); - - public KList getValidItems() { - KList valid = new KList<>(); - getItems().stream().filter(IrisVillagerTrade::isValidItems).forEach(valid::add); - return valid.size() == 0 ? null : valid; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisVillagerTrade.java b/src/main/java/com/volmit/iris/engine/object/IrisVillagerTrade.java deleted file mode 100644 index f59e1a977..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisVillagerTrade.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.MaxNumber; -import com.volmit.iris.engine.object.annotations.MinNumber; -import com.volmit.iris.engine.object.annotations.RegistryListItemType; -import com.volmit.iris.engine.object.annotations.Required; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.MerchantRecipe; - -import java.util.List; - - -@Snippet("villager-trade") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@SuppressWarnings("BooleanMethodIsAlwaysInverted") -@Desc("Represents a villager trade.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisVillagerTrade { - - @Required - @RegistryListItemType - @Desc("The first, required, ingredient for the trade.\nNote: this MUST be an item, and may not be a non-obtainable block!") - private ItemStack ingredient1; - - @RegistryListItemType - @Desc("The second, optional, ingredient for the trade.\nNote: this MUST be an item, and may not be a non-obtainable block!") - private ItemStack ingredient2 = null; - - @Required - @RegistryListItemType - @Desc("The result of the trade.\nNote: this MUST be an item, and may not be a non-obtainable block!") - private ItemStack result; - - @Desc("The min amount of times this trade can be done. Default 3") - @MinNumber(1) - @MaxNumber(64) - private int minTrades = 3; - - @Desc("The max amount of times this trade can be done. Default 5") - @MinNumber(1) - @MaxNumber(64) - private int maxTrades = 5; - - /** - * @return true if:
- * ingredient 1 & result are non-null,
- * mintrades > 0, maxtrades > 0, maxtrades > mintrades, and
- * ingredient 1, (if defined ingredient 2) and the result are valid items - */ - public boolean isValidItems() { - KList warnings = new KList<>(); - if(ingredient1 == null) { - warnings.add("Ingredient 1 is null"); - } - - if(result == null) { - warnings.add("Result is null"); - } - - if(minTrades <= 0) { - warnings.add("Negative minimal trades"); - } - - if(maxTrades <= 0) { - warnings.add("Negative maximal trades"); - } - - if(minTrades > maxTrades) { - warnings.add("More minimal than maximal trades"); - } - - if(ingredient1 != null && !ingredient1.getType().isItem()) { - warnings.add("Ingredient 1 is not an item"); - } - - if(ingredient2 != null && !ingredient2.getType().isItem()) { - warnings.add("Ingredient 2 is not an item"); - } - - if(result != null && !result.getType().isItem()) { - warnings.add("Result is not an item"); - } - - if(warnings.isEmpty()) { - return true; - } else { - Iris.warn("Faulty item in cartographer item overrides: " + this); - warnings.forEach(w -> Iris.warn(" " + w)); - return false; - } - } - - /** - * Get the ingredients - * - * @return The list of 1 or 2 ingredients (depending on if ing2 is null) - */ - public List getIngredients() { - if(!isValidItems()) { - return null; - } - return ingredient2 == null ? new KList<>(ingredient1) : new KList<>(ingredient1, ingredient2); - } - - /** - * @return the amount of trades (RNG.r.i(min, max)) - */ - public int getAmount() { - return RNG.r.i(minTrades, maxTrades); - } - - /** - * @return the trade as a merchant recipe - */ - public MerchantRecipe convert() { - MerchantRecipe recipe = new MerchantRecipe(getResult(), getAmount()); - recipe.setIngredients(getIngredients()); - return recipe; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisWeather.java b/src/main/java/com/volmit/iris/engine/object/IrisWeather.java deleted file mode 100644 index e1fb45ff9..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisWeather.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import org.bukkit.World; - -@Desc("Represents a weather type") -public enum IrisWeather { - @Desc("Represents when weather is not causing downfall") - NONE, - - @Desc("Represents rain or snow") - DOWNFALL, - - @Desc("Represents rain or snow with thunder") - DOWNFALL_WITH_THUNDER, - - @Desc("Any weather") - ANY; - - public boolean is(World world) { - return switch(this) { - case NONE -> world.isClearWeather(); - case DOWNFALL -> world.hasStorm(); - case DOWNFALL_WITH_THUNDER -> world.hasStorm() && world.isThundering(); - case ANY -> true; - }; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisWorld.java b/src/main/java/com/volmit/iris/engine/object/IrisWorld.java deleted file mode 100644 index 0589521d8..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisWorld.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.util.collection.KList; -import lombok.AccessLevel; -import lombok.Builder; -import lombok.Data; -import lombok.Getter; -import lombok.Setter; -import lombok.experimental.Accessors; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import java.io.File; -import java.util.Collection; -import java.util.List; - -@Builder -@Data -@Accessors(chain = true, fluent = true) -public class IrisWorld { - private static final KList NO_PLAYERS = new KList<>(); - private static final KList NO_ENTITIES = new KList<>(); - private String name; - private File worldFolder; - - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private long seed; - private World.Environment environment; - private World realWorld; - private int minHeight; - private int maxHeight; - - public static IrisWorld fromWorld(World world) { - return bindWorld(IrisWorld.builder().build(), world); - } - - private static IrisWorld bindWorld(IrisWorld iw, World world) { - return iw.name(world.getName()) - .worldFolder(world.getWorldFolder()) - .minHeight(world.getMinHeight()) - .maxHeight(world.getMaxHeight()) - .realWorld(world) - .environment(world.getEnvironment()); - } - - public long getRawWorldSeed() { - return seed; - } - - public void setRawWorldSeed(long seed) { - this.seed = seed; - } - - public boolean tryGetRealWorld() { - if(hasRealWorld()) { - return true; - } - - World w = Bukkit.getWorld(name); - - if(w != null) { - realWorld = w; - return true; - } - - return false; - } - - public boolean hasRealWorld() { - return realWorld != null; - } - - public List getPlayers() { - - if(hasRealWorld()) { - return realWorld().getPlayers(); - } - - return NO_PLAYERS; - } - - public void evacuate() { - if(hasRealWorld()) { - IrisToolbelt.evacuate(realWorld()); - } - } - - public void bind(World world) { - if(hasRealWorld()) { - return; - } - - bindWorld(this, world); - } - - public Location spawnLocation() { - if(hasRealWorld()) { - return realWorld().getSpawnLocation(); - } - - Iris.error("This world is not real yet, cannot get spawn location! HEADLESS!"); - return null; - } - - public Collection getEntitiesByClass(Class t) { - if(hasRealWorld()) { - return realWorld().getEntitiesByClass(t); - } - - return (KList) NO_ENTITIES; - } - - public int getHeight() { - return maxHeight - minHeight; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/IrisWorm.java b/src/main/java/com/volmit/iris/engine/object/IrisWorm.java deleted file mode 100644 index 7a29a0ea8..000000000 --- a/src/main/java/com/volmit/iris/engine/object/IrisWorm.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.object.annotations.Snippet; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.function.Consumer; - -@Snippet("worm") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Generate worms") -@Data -public class IrisWorm { - @Desc("The style used to determine the curvature of this worm's x") - private IrisShapedGeneratorStyle xStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN, -2, 2); - - @Desc("The style used to determine the curvature of this worm's y") - private IrisShapedGeneratorStyle yStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN, -2, 2); - - @Desc("The style used to determine the curvature of this worm's z") - private IrisShapedGeneratorStyle zStyle = new IrisShapedGeneratorStyle(NoiseStyle.PERLIN, -2, 2); - - @Desc("The max block distance this worm can travel from its start. This can have performance implications at ranges over 1,000 blocks but it's not too serious, test.") - private int maxDistance = 128; - - @Desc("The iterations this worm can make") - private int maxIterations = 512; - - @Desc("By default if a worm loops back into itself, it stops at that point and does not continue. This is an optimization, to prevent this turn this option on.") - private boolean allowLoops = false; - - @Desc("The thickness of the worms. Each individual worm has the same thickness while traveling however, each spawned worm will vary in thickness.") - private IrisStyledRange girth = new IrisStyledRange().setMin(3).setMax(5) - .setStyle(new IrisGeneratorStyle(NoiseStyle.PERLIN)); - - public KList generate(RNG rng, IrisData data, MantleWriter writer, IrisRange verticalRange, int x, int y, int z, Consumer fork) { - int itr = maxIterations; - double jx, jy, jz; - double cx = x; - double cy = y; - double cz = z; - IrisPosition start = new IrisPosition(x, y, z); - KList pos = new KList<>(); - KSet check = allowLoops ? null : new KSet<>(); - CNG gx = xStyle.getGenerator().createNoCache(new RNG(rng.lmax()), data); - CNG gy = xStyle.getGenerator().createNoCache(new RNG(rng.lmax()), data); - CNG gz = xStyle.getGenerator().createNoCache(new RNG(rng.lmax()), data); - - while(itr-- > 0) { - IrisPosition current = new IrisPosition(Math.round(cx), Math.round(cy), Math.round(cz)); - fork.accept(current); - pos.add(current); - - if(check != null) { - check.add(current); - } - - jx = gx.fitDouble(xStyle.getMin(), xStyle.getMax(), cx, cy, cz); - jy = gy.fitDouble(yStyle.getMin(), yStyle.getMax(), cx, cy, cz); - jz = gz.fitDouble(zStyle.getMin(), zStyle.getMax(), cx, cy, cz); - cx += jx; - cy += jy; - cz += jz; - IrisPosition next = new IrisPosition(Math.round(cx), Math.round(cy), Math.round(cz)); - - if(verticalRange != null && !verticalRange.contains(next.getY())) { - break; - } - - if(!writer.isWithin((int) Math.round(cx), verticalRange != null ? (int) Math.round(cy) : 5, (int) Math.round(cz))) { - break; - } - - if(next.isLongerThan(start, maxDistance)) { - break; - } - - if(check != null && check.contains(next)) { - break; - } - } - - return pos; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/NoiseStyle.java b/src/main/java/com/volmit/iris/engine/object/NoiseStyle.java deleted file mode 100644 index 324268874..000000000 --- a/src/main/java/com/volmit/iris/engine/object/NoiseStyle.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.noise.CNGFactory; -import com.volmit.iris.util.noise.NoiseType; -import com.volmit.iris.util.stream.ProceduralStream; - -@Desc("Styles of noise") -public enum NoiseStyle { - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - STATIC(rng -> new CNG(rng, NoiseType.WHITE, 1D, 1)), - - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - STATIC_BILINEAR(rng -> new CNG(rng, NoiseType.WHITE_BILINEAR, 1D, 1)), - - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - STATIC_BICUBIC(rng -> new CNG(rng, NoiseType.WHITE_BICUBIC, 1D, 1)), - - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - STATIC_HERMITE(rng -> new CNG(rng, NoiseType.WHITE_HERMITE, 1D, 1)), - - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - IRIS(rng -> CNG.signature(rng).scale(1)), - - @Desc("Clover Noise") - CLOVER(rng -> new CNG(rng, NoiseType.CLOVER, 1D, 1).scale(0.06).bake()), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_3, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_6, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_9, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_STARCAST_12, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_3, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_6, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_9, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR_STARCAST_12, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE_STARCAST_3(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_3, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE_STARCAST_6(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_6, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE_STARCAST_9(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_9, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE_STARCAST_12(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE_STARCAST_12, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BILINEAR(rng -> new CNG(rng, NoiseType.CLOVER_BILINEAR, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_BICUBIC(rng -> new CNG(rng, NoiseType.CLOVER_BICUBIC, 1D, 1)), - - @Desc("CLOVER noise creates the same noise level for cells, changes noise level on cell borders.") - CLOVER_HERMITE(rng -> new CNG(rng, NoiseType.CLOVER_HERMITE, 1D, 1)), - - @Desc("Vascular noise gets higher as the position nears a cell border.") - VASCULAR(rng -> new CNG(rng, NoiseType.VASCULAR, 1D, 1)), - - @Desc("It always returns 0.5") - FLAT(rng -> new CNG(rng, NoiseType.FLAT, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR(rng -> new CNG(rng, NoiseType.CELLULAR, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_3, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_6, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_9, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_STARCAST_12, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_3, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_6, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_9, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR_STARCAST_12, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE_STARCAST_3(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_3, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE_STARCAST_6(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_6, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE_STARCAST_9(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_9, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE_STARCAST_12(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE_STARCAST_12, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BILINEAR(rng -> new CNG(rng, NoiseType.CELLULAR_BILINEAR, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_BICUBIC(rng -> new CNG(rng, NoiseType.CELLULAR_BICUBIC, 1D, 1)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - CELLULAR_HERMITE(rng -> new CNG(rng, NoiseType.CELLULAR_HERMITE, 1D, 1)), - - @Desc("Classic German Engineering") - NOWHERE(rng -> CNG.signaturePerlin(rng).scale(0.776).bake()), - - @Desc("Classic German Engineering") - NOWHERE_CELLULAR(rng -> CNG.signaturePerlin(rng, NoiseType.CELLULAR).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_CLOVER(rng -> CNG.signaturePerlin(rng, NoiseType.CLOVER).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_SIMPLEX(rng -> CNG.signaturePerlin(rng, NoiseType.SIMPLEX).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_GLOB(rng -> CNG.signaturePerlin(rng, NoiseType.GLOB).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_VASCULAR(rng -> CNG.signaturePerlin(rng, NoiseType.VASCULAR).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_CUBIC(rng -> CNG.signaturePerlin(rng, NoiseType.CUBIC).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_SUPERFRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX).scale(1).bake()), - - @Desc("Classic German Engineering") - NOWHERE_FRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_BILLOW_PERLIN).scale(1).bake()), - - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - IRIS_DOUBLE(rng -> CNG.signatureDouble(rng).scale(1)), - - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - IRIS_THICK(rng -> CNG.signatureThick(rng).scale(1)), - - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - IRIS_HALF(rng -> CNG.signatureHalf(rng).scale(1)), - - @Desc("Basic, Smooth & Fast Simplex noise.") - SIMPLEX(rng -> new CNG(rng, 1D, 1).scale(1)), - - @Desc("Very Detailed smoke using simplex fractured with fractal billow simplex at high octaves.") - FRACTAL_SMOKE(rng -> new CNG(rng, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(1), NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 8).scale(0.2), 1000).scale(0.34)), - - @Desc("Thinner Veins.") - VASCULAR_THIN(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.VASCULAR, 1D, 1).scale(1).pow(0.65)), - - @Desc("Cells of simplex noise") - SIMPLEX_CELLS(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.SIMPLEX, 1D, 1).scale(1).fractureWith(new CNG(rng.nextParallelRNG(8), NoiseType.CELLULAR, 1D, 1).scale(1), 200)), - - @Desc("Veins of simplex noise") - SIMPLEX_VASCULAR(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.SIMPLEX, 1D, 1).scale(1).fractureWith(new CNG(rng.nextParallelRNG(8), NoiseType.VASCULAR, 1D, 1).scale(1), 200)), - - @Desc("Very Detailed fluid using simplex fractured with fractal billow simplex at high octaves.") - FRACTAL_WATER(rng -> new CNG(rng, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(1), NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 9).scale(0.03), 9900).scale(1.14)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN(rng -> new CNG(rng, NoiseType.PERLIN, 1D, 1).scale(1.15)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN_IRIS(rng -> CNG.signature(rng, NoiseType.PERLIN).scale(1.47)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.PERLIN).scale(1.47)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.PERLIN).scale(1.47)), - - @Desc("Perlin. Like simplex but more natural") - PERLIN_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.PERLIN).scale(1.47)), - - @Desc("Billow Fractal Perlin Noise.") - FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 1).scale(1.47)), - - @Desc("Billow Fractal Perlin Noise. 2 Octaves") - BIOCTAVE_FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 2).scale(1.17)), - - @Desc("Billow Fractal Simplex Noise. Single octave.") - FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 1)), - - @Desc("FBM Fractal Simplex Noise. Single octave.") - FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 1)), - - @Desc("Billow Fractal Iris Noise. Single octave.") - FRACTAL_BILLOW_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - - @Desc("FBM Fractal Iris Noise. Single octave.") - FRACTAL_FBM_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - - @Desc("Billow Fractal Iris Noise. Single octave.") - FRACTAL_BILLOW_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - - @Desc("FBM Fractal Iris Noise. Single octave.") - FRACTAL_FBM_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - - @Desc("Billow Fractal Iris Noise. Single octave.") - FRACTAL_BILLOW_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - - @Desc("FBM Fractal Iris Noise. Single octave.") - FRACTAL_FBM_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - - @Desc("Rigid Multi Fractal Simplex Noise. Single octave.") - FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 1)), - - @Desc("Billow Fractal Simplex Noise. 2 octaves.") - BIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 2)), - - @Desc("FBM Fractal Simplex Noise. 2 octaves.") - BIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 2)), - - @Desc("Rigid Multi Fractal Simplex Noise. 2 octaves.") - BIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 2)), - - @Desc("Rigid Multi Fractal Simplex Noise. 3 octaves.") - TRIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 3)), - - @Desc("Billow Fractal Simplex Noise. 3 octaves.") - TRIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 3)), - - @Desc("FBM Fractal Simplex Noise. 3 octaves.") - TRIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 3)), - - @Desc("Rigid Multi Fractal Simplex Noise. 4 octaves.") - QUADOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 4)), - - @Desc("Billow Fractal Simplex Noise. 4 octaves.") - QUADOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 4)), - - @Desc("FBM Fractal Simplex Noise. 4 octaves.") - QUADOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 4)), - - @Desc("Rigid Multi Fractal Simplex Noise. 5 octaves.") - QUINTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 5)), - - @Desc("Billow Fractal Simplex Noise. 5 octaves.") - QUINTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 5)), - - @Desc("FBM Fractal Simplex Noise. 5 octaves.") - QUINTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 5)), - - @Desc("Rigid Multi Fractal Simplex Noise. 6 octaves.") - SEXOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 6)), - - @Desc("Billow Fractal Simplex Noise. 6 octaves.") - SEXOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 6)), - - @Desc("FBM Fractal Simplex Noise. 6 octaves.") - SEXOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 6)), - - @Desc("Rigid Multi Fractal Simplex Noise. 7 octaves.") - SEPTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 7)), - - @Desc("Billow Fractal Simplex Noise. 7 octaves.") - SEPTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 7)), - - @Desc("FBM Fractal Simplex Noise. 7 octaves.") - SEPTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 7)), - - @Desc("Rigid Multi Fractal Simplex Noise. 8 octaves.") - OCTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 8)), - - @Desc("Billow Fractal Simplex Noise. 8 octaves.") - OCTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 8)), - - @Desc("FBM Fractal Simplex Noise. 8 octaves.") - OCTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 8)), - - @Desc("Rigid Multi Fractal Simplex Noise. 9 octaves.") - NONOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 9)), - - @Desc("Billow Fractal Simplex Noise. 9 octaves.") - NONOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 9)), - - @Desc("FBM Fractal Simplex Noise. 9 octaves.") - NONOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 9)), - - @Desc("Rigid Multi Fractal Simplex Noise. 10 octaves.") - VIGOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 10)), - - @Desc("Billow Fractal Simplex Noise. 10 octaves.") - VIGOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 10)), - - @Desc("FBM Fractal Simplex Noise. 10 octaves.") - VIGOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 10)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 2 octaves") - BIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 2).scale(1D / 2D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 3 octaves") - TRIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 3).scale(1D / 3D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 4 octaves") - QUADOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 4).scale(1D / 4D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 5 octaves") - QUINTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 5).scale(1D / 5D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 6 octaves") - SEXOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 6).scale(1D / 6D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 7 octaves") - SEPTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 7).scale(1D / 12D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 8 octaves") - OCTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 8).scale(1D / 25D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 9 octaves") - NONOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 9).scale(1D / 50D)), - - @Desc("Basic, Smooth & Fast Simplex noise. Uses 10 octaves") - VIGOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 10).scale(1D / 100D)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB(rng -> new CNG(rng, NoiseType.GLOB, 1D, 1)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB_IRIS(rng -> CNG.signature(rng, NoiseType.GLOB)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.GLOB)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.GLOB)), - - @Desc("Glob noise is like cellular, but with globs...") - GLOB_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.GLOB)), - - @Desc("Cubic Noise") - CUBIC(rng -> new CNG(rng, NoiseType.CUBIC, 1D, 1).scale(256)), - - @Desc("Fractal Cubic Noise") - FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 1).scale(2)), - - @Desc("Fractal Cubic Noise With Iris Swirls") - FRACTAL_CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - - @Desc("Fractal Cubic Noise With Iris Swirls") - FRACTAL_CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - - @Desc("Fractal Cubic Noise With Iris Swirls") - FRACTAL_CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - - @Desc("Fractal Cubic Noise With Iris Swirls") - FRACTAL_CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - - @Desc("Fractal Cubic Noise, 2 Octaves") - BIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 2).scale(2)), - - @Desc("Fractal Cubic Noise, 3 Octaves") - TRIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 3).scale(1.5)), - - @Desc("Fractal Cubic Noise, 4 Octaves") - QUADOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 4).scale(1)), - - @Desc("Cubic Noise") - CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.CUBIC).scale(256)), - - @Desc("Cubic Noise") - CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CUBIC).scale(256)), - - @Desc("Cubic Noise") - CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CUBIC).scale(256)), - - @Desc("Cubic Noise") - CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CUBIC).scale(256)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.") - CELLULAR_IRIS(rng -> CNG.signature(rng, NoiseType.CELLULAR)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.") - CELLULAR_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CELLULAR)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.") - CELLULAR_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CELLULAR)), - - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders. Cells are distorted using Iris styled wispy noise.") - CELLULAR_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CELLULAR)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell") - CELLULAR_HEIGHT(rng -> new CNG(rng, NoiseType.CELLULAR_HEIGHT, 1D, 1)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.") - CELLULAR_HEIGHT_IRIS(rng -> CNG.signature(rng, NoiseType.CELLULAR_HEIGHT)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.") - CELLULAR_HEIGHT_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CELLULAR_HEIGHT)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.") - CELLULAR_HEIGHT_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CELLULAR_HEIGHT)), - - @Desc("Inverse of vascular, height gets to 1.0 as it approaches the center of a cell, using the iris style.") - CELLULAR_HEIGHT_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CELLULAR_HEIGHT)), - - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - VASCULAR_IRIS(rng -> CNG.signature(rng, NoiseType.VASCULAR)), - - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - VASCULAR_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.VASCULAR)), - - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - VASCULAR_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.VASCULAR)), - - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - VASCULAR_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.VASCULAR)), - ; - - private final CNGFactory f; - - NoiseStyle(CNGFactory f) { - this.f = f; - } - - public ProceduralStream stream(RNG seed) { - return create(seed).stream(); - } - - public ProceduralStream stream(long seed) { - return create(new RNG(seed)).stream(); - } - - public CNG create(RNG seed) { - CNG cng = f.create(seed).bake(); - cng.setLeakStyle(this); - return cng; - } - - public IrisGeneratorStyle style() { - return new IrisGeneratorStyle(this); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/ObjectPlaceMode.java b/src/main/java/com/volmit/iris/engine/object/ObjectPlaceMode.java deleted file mode 100644 index b632406e1..000000000 --- a/src/main/java/com/volmit/iris/engine/object/ObjectPlaceMode.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("Object Place modes are useful for positioning objects just right. The default value is CENTER_HEIGHT.") -public enum ObjectPlaceMode { - @Desc("The default place mode. This mode picks a center point (where the center of the object will be) and takes the height. That height is used for the whole object.") - - CENTER_HEIGHT, - - @Desc("Samples a lot of points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.") - - MAX_HEIGHT, - - @Desc("Samples only 4 points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.\"") - - FAST_MAX_HEIGHT, - - @Desc("Samples a lot of points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") - - MIN_HEIGHT, - - @Desc("Samples only 4 points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") - - FAST_MIN_HEIGHT, - - @Desc("Stilting is MAX_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - - STILT, - - @Desc("Just like stilting but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") - - FAST_STILT, - - @Desc("Stilting is MIN_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - - MIN_STILT, - - @Desc("Just like MIN_STILT but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") - - FAST_MIN_STILT, - - @Desc("Stilting is CENTER_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - - CENTER_STILT, - - @Desc("Samples the height of the terrain at every x,z position of your object and pushes it down to the surface. It's pretty much like a melt function over the terrain.") - - PAINT -} diff --git a/src/main/java/com/volmit/iris/engine/object/StudioMode.java b/src/main/java/com/volmit/iris/engine/object/StudioMode.java deleted file mode 100644 index 40d931308..000000000 --- a/src/main/java/com/volmit/iris/engine/object/StudioMode.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.engine.platform.BukkitChunkGenerator; -import com.volmit.iris.engine.platform.studio.generators.BiomeBuffetGenerator; - -import java.util.function.Consumer; - -@Desc("Represents a studio mode") -public enum StudioMode { - NORMAL(i -> i.setStudioGenerator(null)), - BIOME_BUFFET_1x1(i -> i.setStudioGenerator(new BiomeBuffetGenerator(i.getEngine(), 1))), - BIOME_BUFFET_3x3(i -> i.setStudioGenerator(new BiomeBuffetGenerator(i.getEngine(), 3))), - BIOME_BUFFET_5x5(i -> i.setStudioGenerator(new BiomeBuffetGenerator(i.getEngine(), 5))), - BIOME_BUFFET_9x9(i -> i.setStudioGenerator(new BiomeBuffetGenerator(i.getEngine(), 9))), - BIOME_BUFFET_18x18(i -> i.setStudioGenerator(new BiomeBuffetGenerator(i.getEngine(), 18))), - BIOME_BUFFET_36x36(i -> i.setStudioGenerator(new BiomeBuffetGenerator(i.getEngine(), 36))), - REGION_BUFFET(i -> i.setStudioGenerator(null)), - OBJECT_BUFFET(i -> i.setStudioGenerator(null)), - - ; - - private final Consumer injector; - - StudioMode(Consumer injector) { - this.injector = injector; - } - - public void inject(BukkitChunkGenerator c) { - injector.accept(c); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/TileBanner.java b/src/main/java/com/volmit/iris/engine/object/TileBanner.java deleted file mode 100644 index efcc2d557..000000000 --- a/src/main/java/com/volmit/iris/engine/object/TileBanner.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.ListTag; -import lombok.Data; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.block.Banner; -import org.bukkit.block.banner.Pattern; -import org.bukkit.block.banner.PatternType; -import org.bukkit.block.data.BlockData; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -@Data -public class TileBanner implements TileData { - public static final int id = 2; - - private List patterns = new ArrayList<>(); - private DyeColor baseColor; - - @Override - public String getTileId() { - return "minecraft:banner"; - } - - @Override - public boolean isApplicable(BlockData data) { - return isBanner(data.getMaterial()); - } - - @Override - public void toBukkit(Banner banner) { - banner.setPatterns(patterns); - banner.setBaseColor(baseColor); - } - - @Override - public void fromBukkit(Banner banner) { - this.patterns = banner.getPatterns(); - this.baseColor = banner.getBaseColor(); - } - - @SuppressWarnings("MethodDoesntCallSuperMethod") - @Override - public TileBanner clone() { - TileBanner ts = new TileBanner(); - ts.setBaseColor(getBaseColor()); - ts.setPatterns(getPatterns()); - return ts; - } - - @Override - public void toBinary(DataOutputStream out) throws IOException { - out.writeShort(id); - out.writeByte(baseColor.ordinal()); - out.writeByte(patterns.size()); - for(Pattern p : patterns) { - out.writeByte(p.getColor().ordinal()); - out.writeByte(p.getPattern().ordinal()); - } - } - - @Override - public void fromBinary(DataInputStream in) throws IOException { - baseColor = DyeColor.values()[in.readByte()]; - int listSize = in.readByte(); - patterns = new ArrayList<>(); - - for(int i = 0; i < listSize; i++) { - DyeColor color = DyeColor.values()[in.readByte()]; - PatternType type = PatternType.values()[in.readByte()]; - patterns.add(new Pattern(color, type)); - } - } - - @SuppressWarnings("deprecation") - @Override - public CompoundTag toNBT(CompoundTag tag) { - @SuppressWarnings("unchecked") ListTag listTag = (ListTag) ListTag.createUnchecked(CompoundTag.class); - for(Pattern p : patterns) { - CompoundTag pattern = new CompoundTag(); - pattern.putString("Pattern", p.getPattern().getIdentifier()); - pattern.putByte("Color", p.getColor().getDyeData()); - listTag.add(pattern); - } - tag.put("Patterns", listTag); - return tag; - } - - public boolean isBanner(Material material) { - return switch(material) { - case RED_BANNER, RED_WALL_BANNER, ORANGE_BANNER, ORANGE_WALL_BANNER, YELLOW_BANNER, YELLOW_WALL_BANNER, LIME_BANNER, LIME_WALL_BANNER, GREEN_BANNER, GREEN_WALL_BANNER, CYAN_BANNER, CYAN_WALL_BANNER, LIGHT_BLUE_BANNER, LIGHT_BLUE_WALL_BANNER, BLUE_BANNER, BLUE_WALL_BANNER, PURPLE_BANNER, PURPLE_WALL_BANNER, MAGENTA_BANNER, MAGENTA_WALL_BANNER, PINK_BANNER, PINK_WALL_BANNER, WHITE_BANNER, WHITE_WALL_BANNER, LIGHT_GRAY_BANNER, LIGHT_GRAY_WALL_BANNER, GRAY_BANNER, GRAY_WALL_BANNER, BLACK_BANNER, BLACK_WALL_BANNER, BROWN_BANNER, BROWN_WALL_BANNER -> true; - default -> false; - }; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/TileData.java b/src/main/java/com/volmit/iris/engine/object/TileData.java deleted file mode 100644 index b4198e330..000000000 --- a/src/main/java/com/volmit/iris/engine/object/TileData.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.TileState; -import org.bukkit.block.data.BlockData; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; - -@SuppressWarnings("ALL") -public interface TileData extends Cloneable { - - static final KList> registry = setup(); - - static KList> setup() { - KList> registry = new KList<>(); - - registry.add(new TileSign()); - registry.add(new TileSpawner()); - registry.add(new TileBanner()); - - return registry; - } - - static TileData read(DataInputStream s) throws IOException { - try { - int id = s.readShort(); - @SuppressWarnings("unchecked") TileData d = registry.get(id).getClass().getConstructor().newInstance(); - d.fromBinary(s); - return d; - } catch(InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) { - throw new IOException("Failed to create TileData instance due to missing type registrar!"); - } - } - - static boolean setTileState(Block block, TileData data) { - if(block.getState() instanceof TileState && data.isApplicable(block.getBlockData())) - return data.toBukkitTry(block.getState()); - return false; - } - - static TileData getTileState(Block block) { - for(TileData i : registry) { - BlockData data = block.getBlockData(); - - if(i.isApplicable(data)) { - try { - @SuppressWarnings("unchecked") TileData s = i.getClass().getConstructor().newInstance(); - s.fromBukkitTry(block.getState()); - return s; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - } - - return null; - } - - String getTileId(); - - boolean isApplicable(BlockData data); - - void toBukkit(T t); - - void fromBukkit(T t); - - default boolean toBukkitTry(BlockState t) { - try { - //noinspection unchecked - toBukkit((T) t); - t.update(); - return true; - } catch(Throwable e) { - Iris.reportError(e); - - } - - return false; - } - - default boolean fromBukkitTry(BlockState t) { - try { - //noinspection unchecked - fromBukkit((T) t); - return true; - } catch(Throwable e) { - Iris.reportError(e); - - } - - return false; - } - - CompoundTag toNBT(CompoundTag parent); - - void toBinary(DataOutputStream out) throws IOException; - - void fromBinary(DataInputStream in) throws IOException; - - TileData clone(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/TileSign.java b/src/main/java/com/volmit/iris/engine/object/TileSign.java deleted file mode 100644 index 119ec3378..000000000 --- a/src/main/java/com/volmit/iris/engine/object/TileSign.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.util.nbt.tag.CompoundTag; -import lombok.Data; -import org.bukkit.DyeColor; -import org.bukkit.block.Sign; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.WallSign; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Data -public class TileSign implements TileData { - public static final int id = 0; - private String line1; - private String line2; - private String line3; - private String line4; - private DyeColor dyeColor; - - @Override - public String getTileId() { - return "minecraft:sign"; - } - - @Override - public boolean isApplicable(BlockData data) { - return data instanceof org.bukkit.block.data.type.Sign || data instanceof WallSign; - } - - @Override - public void toBukkit(Sign t) { - t.setLine(0, line1); - t.setLine(1, line2); - t.setLine(2, line3); - t.setLine(3, line4); - t.setColor(dyeColor); - } - - @Override - public void fromBukkit(Sign sign) { - line1 = sign.getLine(0); - line2 = sign.getLine(1); - line3 = sign.getLine(2); - line4 = sign.getLine(3); - dyeColor = sign.getColor(); - } - - @SuppressWarnings("MethodDoesntCallSuperMethod") - @Override - public TileSign clone() { - TileSign ts = new TileSign(); - ts.setDyeColor(getDyeColor()); - ts.setLine1(getLine1()); - ts.setLine2(getLine2()); - ts.setLine3(getLine3()); - ts.setLine4(getLine4()); - return ts; - } - - @Override - public void toBinary(DataOutputStream out) throws IOException { - out.writeShort(id); - out.writeUTF(line1); - out.writeUTF(line2); - out.writeUTF(line3); - out.writeUTF(line4); - out.writeByte(dyeColor.ordinal()); - } - - @Override - public void fromBinary(DataInputStream in) throws IOException { - line1 = in.readUTF(); - line2 = in.readUTF(); - line3 = in.readUTF(); - line4 = in.readUTF(); - dyeColor = DyeColor.values()[in.readByte()]; - } - - @Override - public CompoundTag toNBT(CompoundTag tag) { - tag.putString("Text1", line1); - tag.putString("Text2", line2); - tag.putString("Text3", line3); - tag.putString("Text4", line4); - tag.putString("Color", dyeColor.name().toLowerCase()); - return tag; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/TileSpawner.java b/src/main/java/com/volmit/iris/engine/object/TileSpawner.java deleted file mode 100644 index e410973b1..000000000 --- a/src/main/java/com/volmit/iris/engine/object/TileSpawner.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object; - -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.ListTag; -import lombok.Data; -import org.bukkit.Material; -import org.bukkit.block.CreatureSpawner; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.EntityType; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Data -public class TileSpawner implements TileData { - - public static final int id = 1; - - private EntityType entityType; - @Override - public String getTileId() { - return "minecraft:mob_spawner"; - } - - @Override - public boolean isApplicable(BlockData data) { - return data.getMaterial() == Material.SPAWNER; - } - - @Override - public void toBukkit(CreatureSpawner t) { - t.setSpawnedType(entityType); - } - - @Override - public void fromBukkit(CreatureSpawner sign) { - entityType = sign.getSpawnedType(); - } - - @SuppressWarnings("MethodDoesntCallSuperMethod") - @Override - public TileSpawner clone() { - TileSpawner ts = new TileSpawner(); - ts.setEntityType(getEntityType()); - return ts; - } - - @Override - public void toBinary(DataOutputStream out) throws IOException { - out.writeShort(id); - out.writeShort(entityType.ordinal()); - } - - @Override - public void fromBinary(DataInputStream in) throws IOException { - entityType = EntityType.values()[in.readShort()]; - } - - @Override - public CompoundTag toNBT(CompoundTag parent) { - @SuppressWarnings("unchecked") ListTag potentials = (ListTag) ListTag.createUnchecked(CompoundTag.class); - CompoundTag t = new CompoundTag(); - CompoundTag ent = new CompoundTag(); - ent.putString("id", entityType.getKey().toString()); - t.put("Entity", ent); - t.putInt("Weight", 1); - potentials.add(t); - parent.put("SpawnPotentials", potentials); - return parent; - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/ArrayType.java b/src/main/java/com/volmit/iris/engine/object/annotations/ArrayType.java deleted file mode 100644 index 226012cdb..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/ArrayType.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface ArrayType { - Class type(); - - int min() default 0; -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/DependsOn.java b/src/main/java/com/volmit/iris/engine/object/annotations/DependsOn.java deleted file mode 100644 index c33a2f236..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/DependsOn.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({FIELD}) -public @interface DependsOn { - String[] value(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/Desc.java b/src/main/java/com/volmit/iris/engine/object/annotations/Desc.java deleted file mode 100644 index 48509c137..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/Desc.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface Desc { - String value(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/MaxNumber.java b/src/main/java/com/volmit/iris/engine/object/annotations/MaxNumber.java deleted file mode 100644 index d5928e49d..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/MaxNumber.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({FIELD}) -public @interface MaxNumber { - double value(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/MinNumber.java b/src/main/java/com/volmit/iris/engine/object/annotations/MinNumber.java deleted file mode 100644 index 54dab8fac..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/MinNumber.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({FIELD}) -public @interface MinNumber { - double value(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListBiomeDownfallType.java b/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListBiomeDownfallType.java deleted file mode 100644 index 50711e581..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListBiomeDownfallType.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListBiomeDownfallType { - -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListBlockType.java b/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListBlockType.java deleted file mode 100644 index 8170fb9d8..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListBlockType.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListBlockType { - -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListFont.java b/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListFont.java deleted file mode 100644 index 2a2964e9f..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListFont.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListFont { - -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListItemType.java b/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListItemType.java deleted file mode 100644 index aea5013bb..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListItemType.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListItemType { - -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListResource.java b/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListResource.java deleted file mode 100644 index 9475b7a69..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListResource.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import com.volmit.iris.core.loader.IrisRegistrant; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListResource { - Class value(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListSpecialEntity.java b/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListSpecialEntity.java deleted file mode 100644 index 34a292a3c..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/RegistryListSpecialEntity.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListSpecialEntity { - -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/Required.java b/src/main/java/com/volmit/iris/engine/object/annotations/Required.java deleted file mode 100644 index dcb6828b0..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/Required.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface Required { - -} diff --git a/src/main/java/com/volmit/iris/engine/object/annotations/Snippet.java b/src/main/java/com/volmit/iris/engine/object/annotations/Snippet.java deleted file mode 100644 index b0dbae401..000000000 --- a/src/main/java/com/volmit/iris/engine/object/annotations/Snippet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target({TYPE}) -public @interface Snippet { - String value(); -} diff --git a/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterObject.java b/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterObject.java deleted file mode 100644 index 227f55a29..000000000 --- a/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterObject.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.volmit.iris.engine.object.matter; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.matter.IrisMatter; -import com.volmit.iris.util.matter.Matter; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.io.File; -import java.io.IOException; - -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisMatterObject extends IrisRegistrant { - private final Matter matter; - - public IrisMatterObject() - { - this(1,1,1); - } - - public IrisMatterObject(int w, int h, int d) - { - this(new IrisMatter(w,h,d)); - } - - public IrisMatterObject(Matter matter) - { - this.matter = matter; - } - - public static IrisMatterObject from(IrisObject object) - { - return new IrisMatterObject(Matter.from(object)); - } - - public static IrisMatterObject from(File j) throws IOException, ClassNotFoundException { - return new IrisMatterObject(Matter.read(j)); - } - - @Override - public String getFolderName() { - return "matter"; - } - - @Override - public String getTypeName() { - return "Matter"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterPlacement.java b/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterPlacement.java deleted file mode 100644 index e85f102d9..000000000 --- a/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterPlacement.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.object.matter; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.IrisEngine; -import com.volmit.iris.engine.object.IRare; -import com.volmit.iris.engine.object.IrisStyledRange; -import com.volmit.iris.engine.object.annotations.*; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.mantle.Mantle; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.matter.MatterSlice; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("matter-placer") -@EqualsAndHashCode() -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents an iris object placer. It places matter objects.") -@Data -public class IrisMatterPlacement implements IRare { - @RegistryListResource(IrisMatterObject.class) - @Required - @ArrayType(min = 1, type = String.class) - @Desc("List of objects to place") - private KList place = new KList<>(); - - @MinNumber(0) - @Desc("The rarity of this object placing") - private int rarity = 0; - - @MinNumber(0) - @Desc("The styled density of this object") - private IrisStyledRange densityRange; - - @Desc("The absolute density for this object") - private double density = 1; - - @Desc("Translate this matter object before placement") - private IrisMatterTranslate translate; - - @Desc("Place this object on the surface height, bedrock or the sky, then use translate if need be.") - private IrisMatterPlacementLocation location = IrisMatterPlacementLocation.SURFACE; - - public void place(IrisEngine engine, IrisData data, RNG rng, int ax, int az) - { - IrisMatterObject object = data.getMatterLoader().load(place.getRandom(rng)); - int x = ax; - int z = az; - int yoff = 0; - - if(translate != null) - { - x += translate.xOffset(data, rng, x, z); - yoff += translate.yOffset(data, rng, x, z); - z += translate.zOffset(data, rng, x, z); - } - - int y = yoff + location.at(engine, x, z); - Mantle mantle = engine.getMantle().getMantle(); - - int xx = x; - int yy = y; - int zz = z; - - for(MatterSlice slice : object.getMatter().getSliceMap().values()) - { - slice.iterate((mx, my, mz, v) -> { - mantle.set(xx + mx, yy + my, zz + mz, v); - }); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterPlacementLocation.java b/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterPlacementLocation.java deleted file mode 100644 index 20f175cb4..000000000 --- a/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterPlacementLocation.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.volmit.iris.engine.object.matter; - -import com.volmit.iris.engine.IrisEngine; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.util.function.Function3; - -import java.util.function.Function; -@Desc("WHERE THINGS PLACE") -public enum IrisMatterPlacementLocation { - SURFACE((e, x, z) -> e.getHeight(x, z, true)), - SURFACE_ON_FLUID((e, x, z) -> e.getHeight(x, z, false)), - BEDROCK((e, x, z) -> 0), - SKY((e, x, z) -> e.getHeight()); - - private final Function3 computer; - - private IrisMatterPlacementLocation(Function3 computer) - { - this.computer = computer; - } - - public int at(IrisEngine engine, int x, int z) { - return computer.apply(engine, x, z); - } -} diff --git a/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterTranslate.java b/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterTranslate.java deleted file mode 100644 index 7b7e599c9..000000000 --- a/src/main/java/com/volmit/iris/engine/object/matter/IrisMatterTranslate.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.volmit.iris.engine.object.matter; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.IrisEngine; -import com.volmit.iris.engine.object.IrisStyledRange; -import com.volmit.iris.engine.object.annotations.Desc; -import com.volmit.iris.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Data -@NoArgsConstructor -@AllArgsConstructor -@EqualsAndHashCode() -@Accessors(chain = true) -@Desc("Represents a matter translator") -public class IrisMatterTranslate { - @Desc("For varied coordinate shifts use ranges not the literal coordinate") - private IrisStyledRange rangeX = null; - @Desc("For varied coordinate shifts use ranges not the literal coordinate") - private IrisStyledRange rangeY = null; - @Desc("For varied coordinate shifts use ranges not the literal coordinate") - private IrisStyledRange rangeZ = null; - @Desc("Define an absolute shift instead of varied.") - private int x = 0; - @Desc("Define an absolute shift instead of varied.") - private int y = 0; - @Desc("Define an absolute shift instead of varied.") - private int z = 0; - - public int xOffset(IrisData data, RNG rng, int rx, int rz) - { - if(rangeX != null) - { - return (int) Math.round(rangeX.get(rng, rx, rz, data)); - } - - return x; - } - - public int yOffset(IrisData data, RNG rng, int rx, int rz) - { - if(rangeY != null) - { - return (int) Math.round(rangeY.get(rng, rx, rz, data)); - } - - return y; - } - - public int zOffset(IrisData data, RNG rng, int rx, int rz) - { - if(rangeZ != null) - { - return (int) Math.round(rangeZ.get(rng, rx, rz, data)); - } - - return z; - } -} diff --git a/src/main/java/com/volmit/iris/engine/platform/BukkitChunkGenerator.java b/src/main/java/com/volmit/iris/engine/platform/BukkitChunkGenerator.java deleted file mode 100644 index d12028f25..000000000 --- a/src/main/java/com/volmit/iris/engine/platform/BukkitChunkGenerator.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.platform; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.service.StudioSVC; -import com.volmit.iris.engine.IrisEngine; -import com.volmit.iris.engine.data.chunk.TerrainChunk; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineTarget; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisWorld; -import com.volmit.iris.engine.object.StudioMode; -import com.volmit.iris.engine.platform.studio.StudioGenerator; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.data.IrisBiomeStorage; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.hunk.view.BiomeGridHunkHolder; -import com.volmit.iris.util.hunk.view.ChunkDataHunkHolder; -import com.volmit.iris.util.io.ReactiveFolder; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.Looper; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.Setter; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.generator.BiomeProvider; -import org.bukkit.generator.BlockPopulator; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.generator.WorldInfo; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.util.List; -import java.util.Random; -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; - -@EqualsAndHashCode(callSuper = true) -@Data -public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChunkGenerator { - private static final int LOAD_LOCKS = Runtime.getRuntime().availableProcessors() * 4; - private final Semaphore loadLock; - private final IrisWorld world; - private final File dataLocation; - private final String dimensionKey; - private final ReactiveFolder folder; - private final KList populators; - private final ChronoLatch hotloadChecker; - private final AtomicBoolean setup; - private final boolean studio; - private Engine engine; - private Looper hotloader; - private StudioMode lastMode; - @Setter - private StudioGenerator studioGenerator; - - public BukkitChunkGenerator(IrisWorld world, boolean studio, File dataLocation, String dimensionKey) { - setup = new AtomicBoolean(false); - studioGenerator = null; - populators = new KList<>(); - loadLock = new Semaphore(LOAD_LOCKS); - this.world = world; - this.hotloadChecker = new ChronoLatch(1000, false); - this.studio = studio; - this.dataLocation = dataLocation; - this.dimensionKey = dimensionKey; - this.folder = new ReactiveFolder(dataLocation, (_a, _b, _c) -> hotload()); - } - - private void setupEngine() { - IrisData data = IrisData.get(dataLocation); - IrisDimension dimension = data.getDimensionLoader().load(dimensionKey); - - if(dimension == null) { - Iris.error("Oh No! There's no pack in " + data.getDataFolder().getPath() + " or... there's no dimension for the key " + dimensionKey); - IrisDimension test = IrisData.loadAnyDimension(dimensionKey); - - if(test != null) { - Iris.warn("Looks like " + dimensionKey + " exists in " + test.getLoadFile().getPath() + " "); - Iris.service(StudioSVC.class).installIntoWorld(Iris.getSender(), dimensionKey, dataLocation.getParentFile().getParentFile()); - Iris.warn("Attempted to install into " + data.getDataFolder().getPath()); - data.dump(); - data.clearLists(); - test = data.getDimensionLoader().load(dimensionKey); - - if(test != null) { - Iris.success("Woo! Patched the Engine!"); - dimension = test; - } else { - Iris.error("Failed to patch dimension!"); - throw new RuntimeException("Missing Dimension: " + dimensionKey); - } - } else { - Iris.error("Nope, you don't have an installation containing " + dimensionKey + " try downloading it?"); - throw new RuntimeException("Missing Dimension: " + dimensionKey); - } - } - - lastMode = StudioMode.NORMAL; - engine = new IrisEngine(new EngineTarget(world, dimension, data), studio); - populators.clear(); - } - - @Override - public void injectChunkReplacement(World world, int x, int z, Consumer jobs) { - try { - loadLock.acquire(); - IrisBiomeStorage st = new IrisBiomeStorage(); - TerrainChunk tc = TerrainChunk.createUnsafe(world, st); - Hunk blocks = Hunk.view(tc); - Hunk biomes = Hunk.view(tc, tc.getMinHeight(), tc.getMaxHeight()); - this.world.bind(world); - getEngine().generate(x << 4, z << 4, blocks, biomes, true); - Iris.debug("Regenerated " + x + " " + z); - int t = 0; - for(int i = getEngine().getHeight() >> 4; i >= 0; i--) { - if(!world.isChunkLoaded(x, z)) { - continue; - } - - Chunk c = world.getChunkAt(x, z); - for(Entity ee : c.getEntities()) { - if(ee instanceof Player) { - continue; - } - - J.s(ee::remove); - } - - J.s(() -> engine.getWorldManager().onChunkLoad(c, false)); - - int finalI = i; - jobs.accept(() -> { - - for(int xx = 0; xx < 16; xx++) { - for(int yy = 0; yy < 16; yy++) { - for(int zz = 0; zz < 16; zz++) { - if(yy + (finalI << 4) >= engine.getHeight() || yy + (finalI << 4) < 0) { - continue; - } - c.getBlock(xx, yy + (finalI << 4) + world.getMinHeight(), zz) - .setBlockData(tc.getBlockData(xx, yy + (finalI << 4) + world.getMinHeight(), zz), false); - } - } - } - }); - } - - loadLock.release(); - } catch(Throwable e) { - loadLock.release(); - Iris.error("======================================"); - e.printStackTrace(); - Iris.reportErrorChunk(x, z, e, "CHUNK"); - Iris.error("======================================"); - - ChunkData d = Bukkit.createChunkData(world); - - for(int i = 0; i < 16; i++) { - for(int j = 0; j < 16; j++) { - d.setBlock(i, 0, j, Material.RED_GLAZED_TERRACOTTA.createBlockData()); - } - } - } - } - - private Engine getEngine(World world) { - if(setup.get()) { - return getEngine(); - } - - synchronized(this) { - getWorld().setRawWorldSeed(world.getSeed()); - setupEngine(); - this.hotloader = studio ? new Looper() { - @Override - protected long loop() { - if(hotloadChecker.flip()) { - folder.check(); - } - - return 250; - } - } : null; - - if(studio) { - hotloader.setPriority(Thread.MIN_PRIORITY); - hotloader.start(); - hotloader.setName(getTarget().getWorld().name() + " Hotloader"); - } - - setup.set(true); - } - - return engine; - } - - @Override - public void close() { - withExclusiveControl(() -> { - if(isStudio()) { - hotloader.interrupt(); - } - - getEngine().close(); - folder.clear(); - populators.clear(); - - }); - } - - @Override - public boolean isStudio() { - return studio; - } - - @Override - public void hotload() { - if(!isStudio()) { - return; - } - - withExclusiveControl(() -> getEngine().hotload()); - } - - public void withExclusiveControl(Runnable r) { - J.a(() -> { - try { - loadLock.acquire(LOAD_LOCKS); - r.run(); - loadLock.release(LOAD_LOCKS); - } catch(Throwable e) { - Iris.reportError(e); - } - }); - } - - @Override - public void touch(World world) { - getEngine(world); - } - - @Override - public @NotNull ChunkData generateChunkData(@NotNull World world, @NotNull Random ignored, int x, int z, @NotNull BiomeGrid biome) { - try { - getEngine(world); - loadLock.acquire(); - computeStudioGenerator(); - TerrainChunk tc = TerrainChunk.create(world, biome); - this.world.bind(world); - - if(studioGenerator != null) { - studioGenerator.generateChunk(getEngine(), tc, x, z); - } else { - ChunkDataHunkHolder blocks = new ChunkDataHunkHolder(tc); - BiomeGridHunkHolder biomes = new BiomeGridHunkHolder(tc, tc.getMinHeight(), tc.getMaxHeight()); - getEngine().generate(x << 4, z << 4, blocks, biomes, true); - blocks.apply(); - biomes.apply(); - } - - ChunkData c = tc.getRaw(); - Iris.debug("Generated " + x + " " + z); - loadLock.release(); - return c; - } catch(Throwable e) { - loadLock.release(); - Iris.error("======================================"); - e.printStackTrace(); - Iris.reportErrorChunk(x, z, e, "CHUNK"); - Iris.error("======================================"); - - ChunkData d = Bukkit.createChunkData(world); - - for(int i = 0; i < 16; i++) { - for(int j = 0; j < 16; j++) { - d.setBlock(i, 0, j, Material.RED_GLAZED_TERRACOTTA.createBlockData()); - } - } - - return d; - } - } - - private void computeStudioGenerator() { - if(!getEngine().getDimension().getStudioMode().equals(lastMode)) { - lastMode = getEngine().getDimension().getStudioMode(); - getEngine().getDimension().getStudioMode().inject(this); - } - } - - @NotNull - @Override - public List getDefaultPopulators(@NotNull World world) { - return populators; - } - - @Override - public boolean isParallelCapable() { - return true; - } - - @Override - public boolean shouldGenerateCaves() { - return false; - } - - @Override - public boolean shouldGenerateDecorations() { - return false; - } - - @Override - public boolean shouldGenerateMobs() { - return false; - } - - @Override - public boolean shouldGenerateStructures() { - return false; - } - - @Override - public boolean shouldGenerateNoise() { - return false; - } - - @Override - public boolean shouldGenerateSurface() { - return false; - } - - @Override - public boolean shouldGenerateBedrock() { - return false; - } - - @Nullable - @Override - public BiomeProvider getDefaultBiomeProvider(@NotNull WorldInfo worldInfo) { - return null; - } -} diff --git a/src/main/java/com/volmit/iris/engine/platform/DummyChunkGenerator.java b/src/main/java/com/volmit/iris/engine/platform/DummyChunkGenerator.java deleted file mode 100644 index b78340ba4..000000000 --- a/src/main/java/com/volmit/iris/engine/platform/DummyChunkGenerator.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.platform; - -import org.bukkit.generator.ChunkGenerator; - -public class DummyChunkGenerator extends ChunkGenerator { - -} diff --git a/src/main/java/com/volmit/iris/engine/platform/PlatformChunkGenerator.java b/src/main/java/com/volmit/iris/engine/platform/PlatformChunkGenerator.java deleted file mode 100644 index fcedc1a3d..000000000 --- a/src/main/java/com/volmit/iris/engine/platform/PlatformChunkGenerator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.platform; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.EngineTarget; -import com.volmit.iris.engine.framework.Hotloadable; -import com.volmit.iris.util.data.DataProvider; -import org.bukkit.World; - -import java.util.function.Consumer; - -public interface PlatformChunkGenerator extends Hotloadable, DataProvider { - Engine getEngine(); - - @Override - default IrisData getData() { - return getEngine().getData(); - } - - default EngineTarget getTarget() { - return getEngine().getTarget(); - } - - void injectChunkReplacement(World world, int x, int z, Consumer jobs); - - void close(); - - boolean isStudio(); - - void touch(World world); -} diff --git a/src/main/java/com/volmit/iris/engine/platform/studio/EnginedStudioGenerator.java b/src/main/java/com/volmit/iris/engine/platform/studio/EnginedStudioGenerator.java deleted file mode 100644 index cd966c158..000000000 --- a/src/main/java/com/volmit/iris/engine/platform/studio/EnginedStudioGenerator.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.platform.studio; - -import com.volmit.iris.engine.data.chunk.TerrainChunk; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.WrongEngineBroException; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -public abstract class EnginedStudioGenerator implements StudioGenerator { - private final Engine engine; - - @Override - public abstract void generateChunk(Engine engine, TerrainChunk tc, int x, int z) throws WrongEngineBroException; -} diff --git a/src/main/java/com/volmit/iris/engine/platform/studio/StudioGenerator.java b/src/main/java/com/volmit/iris/engine/platform/studio/StudioGenerator.java deleted file mode 100644 index 51d37d0a2..000000000 --- a/src/main/java/com/volmit/iris/engine/platform/studio/StudioGenerator.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.platform.studio; - -import com.volmit.iris.engine.data.chunk.TerrainChunk; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.WrongEngineBroException; - -public interface StudioGenerator { - void generateChunk(Engine engine, TerrainChunk tc, int x, int z) throws WrongEngineBroException; -} diff --git a/src/main/java/com/volmit/iris/engine/platform/studio/generators/BiomeBuffetGenerator.java b/src/main/java/com/volmit/iris/engine/platform/studio/generators/BiomeBuffetGenerator.java deleted file mode 100644 index 1fb2a8c97..000000000 --- a/src/main/java/com/volmit/iris/engine/platform/studio/generators/BiomeBuffetGenerator.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.platform.studio.generators; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.data.chunk.TerrainChunk; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.WrongEngineBroException; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.platform.studio.EnginedStudioGenerator; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; - -import java.util.Objects; - -public class BiomeBuffetGenerator extends EnginedStudioGenerator { - private static final BlockData FLOOR = Material.BARRIER.createBlockData(); - private final IrisBiome[] biomes; - private final int width; - private final int biomeSize; - - public BiomeBuffetGenerator(Engine engine, int biomeSize) { - super(engine); - this.biomeSize = biomeSize; - biomes = engine.getDimension().getAllBiomes(engine).toArray(new IrisBiome[0]); - width = Math.max((int) Math.sqrt(biomes.length), 1); - } - - @Override - public void generateChunk(Engine engine, TerrainChunk tc, int x, int z) throws WrongEngineBroException { - int id = Cache.to1D(x / biomeSize, 0, z / biomeSize, width, 1); - - if(id >= 0 && id < biomes.length) { - IrisBiome biome = biomes[id]; - String foc = engine.getDimension().getFocus(); - - if(!Objects.equals(foc, biome.getLoadKey())) { - engine.getDimension().setFocus(biome.getLoadKey()); - engine.hotloadComplex(); - } - - engine.generate(x << 4, z << 4, tc, true); - } else { - tc.setRegion(0, 0, 0, 16, 1, 16, FLOOR); - } - } -} diff --git a/src/main/java/com/volmit/iris/engine/scripting/EngineExecutionEnvironment.java b/src/main/java/com/volmit/iris/engine/scripting/EngineExecutionEnvironment.java deleted file mode 100644 index 464feb77a..000000000 --- a/src/main/java/com/volmit/iris/engine/scripting/EngineExecutionEnvironment.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.scripting; - -import com.volmit.iris.engine.framework.Engine; -import org.apache.bsf.BSFManager; - -public interface EngineExecutionEnvironment { - Engine getEngine(); - - IrisScriptingAPI getAPI(); - - BSFManager getManager(); - - void execute(String script); - - Object evaluate(String script); - - default void close() { - - } -} diff --git a/src/main/java/com/volmit/iris/engine/scripting/IrisScriptingAPI.java b/src/main/java/com/volmit/iris/engine/scripting/IrisScriptingAPI.java deleted file mode 100644 index c0a3e35d9..000000000 --- a/src/main/java/com/volmit/iris/engine/scripting/IrisScriptingAPI.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.engine.scripting; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.engine.object.IrisExpression; -import lombok.Data; -import org.bukkit.Location; -import org.bukkit.entity.Entity; - -@Data -public class IrisScriptingAPI { - private final Engine engine; - private IrisRegistrant preprocessorObject; - private double x = 0; - private double y = 0; - private double z = 0; - private Location location; - private Entity entity; - - public IrisScriptingAPI(Engine engine) { - this.engine = engine; - } - - public IrisData getData() { - return getEngine().getData(); - } - - public IrisComplex getComplex() { - return getEngine().getComplex(); - } - - public long getSeed() { - return getEngine().getSeedManager().getScript(); - } - - public double expression(String expressionName, double x, double y, double z) { - IrisExpression expression = getData().getExpressionLoader().load(expressionName); - return expression.evaluate(getComplex().getRng(), x, y, z); - } - - public double expression(String expressionName, double x, double z) { - IrisExpression expression = getData().getExpressionLoader().load(expressionName); - return expression.evaluate(getComplex().getRng(), x, z); - } - - public IrisBiome getBiomeAt(int x, int z) { - return getEngine().getSurfaceBiome(x, z); - } - - public IrisDimension getDimension() { - return getEngine().getDimension(); - } - - public void info(String log) { - Iris.info(log); - } - - public void debug(String log) { - Iris.debug(log); - } - - public void warn(String log) { - Iris.warn(log); - } - - public void error(String log) { - Iris.error(log); - } -} diff --git a/src/main/java/com/volmit/iris/util/api/APIAwareBlock.java b/src/main/java/com/volmit/iris/util/api/APIAwareBlock.java deleted file mode 100644 index 4e0881db5..000000000 --- a/src/main/java/com/volmit/iris/util/api/APIAwareBlock.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.api; - -import org.bukkit.block.data.BlockData; - -@FunctionalInterface -public interface APIAwareBlock { - void onPlaced(BlockData block, String namespace, String key, int x, int y, int z); -} diff --git a/src/main/java/com/volmit/iris/util/api/APIWorldBlock.java b/src/main/java/com/volmit/iris/util/api/APIWorldBlock.java deleted file mode 100644 index 8eec1385a..000000000 --- a/src/main/java/com/volmit/iris/util/api/APIWorldBlock.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.api; - -import org.bukkit.block.Block; - -@FunctionalInterface -public interface APIWorldBlock { - void onWorldPlaced(Block block, String namespace, String key); -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/atomics/AtomicAverage.java b/src/main/java/com/volmit/iris/util/atomics/AtomicAverage.java deleted file mode 100644 index 2800f5ba2..000000000 --- a/src/main/java/com/volmit/iris/util/atomics/AtomicAverage.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.atomics; - -import com.google.common.util.concurrent.AtomicDoubleArray; -import com.volmit.iris.Iris; -import com.volmit.iris.util.data.DoubleArrayUtils; - -/** - * Provides an incredibly fast averaging object. It swaps values from a sum - * using an array. Averages do not use any form of looping. An average of 10,000 - * entries is the same speed as an average with 5 entries. - * - * @author cyberpwn - */ -public class AtomicAverage { - protected final AtomicDoubleArray values; - protected int cursor; - private double average; - private double lastSum; - private boolean dirty; - private boolean brandNew; - - /** - * Create an average holder - * - * @param size - * the size of entries to keep - */ - public AtomicAverage(int size) { - values = new AtomicDoubleArray(size); - DoubleArrayUtils.fill(values, 0); - brandNew = true; - average = 0; - cursor = 0; - lastSum = 0; - dirty = false; - } - - /** - * Put a value into the average (rolls over if full) - * - * @param i - * the value - */ - public void put(double i) { - - try { - dirty = true; - - if(brandNew) { - DoubleArrayUtils.fill(values, i); - lastSum = size() * i; - brandNew = false; - return; - } - - double current = values.get(cursor); - lastSum = (lastSum - current) + i; - values.set(cursor, i); - cursor = cursor + 1 < size() ? cursor + 1 : 0; - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - /** - * Get the current average - * - * @return the average - */ - public double getAverage() { - if(dirty) { - calculateAverage(); - return getAverage(); - } - - return average; - } - - private void calculateAverage() { - average = lastSum / (double) size(); - dirty = false; - } - - public int size() { - return values.length(); - } - - public boolean isDirty() { - return dirty; - } -} diff --git a/src/main/java/com/volmit/iris/util/atomics/AtomicRollingSequence.java b/src/main/java/com/volmit/iris/util/atomics/AtomicRollingSequence.java deleted file mode 100644 index b05850c2d..000000000 --- a/src/main/java/com/volmit/iris/util/atomics/AtomicRollingSequence.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.atomics; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.M; - -public class AtomicRollingSequence extends AtomicAverage { - private double median; - private double max; - private double min; - private boolean dirtyMedian; - private int dirtyExtremes; - private boolean precision; - - public AtomicRollingSequence(int size) { - super(size); - median = 0; - min = 0; - max = 0; - setPrecision(false); - } - - public double addLast(int amt) { - double f = 0; - - for(int i = 0; i < Math.min(values.length(), amt); i++) { - f += values.get(i); - } - - return f; - } - - public boolean isPrecision() { - return precision; - } - - public void setPrecision(boolean p) { - this.precision = p; - } - - public double getMin() { - if(dirtyExtremes > (isPrecision() ? 0 : values.length())) { - resetExtremes(); - } - - return min; - } - - public double getMax() { - if(dirtyExtremes > (isPrecision() ? 0 : values.length())) { - resetExtremes(); - } - - return max; - } - - public double getMedian() { - if(dirtyMedian) { - recalculateMedian(); - } - - return median; - } - - private void recalculateMedian() { - median = new KList().forceAdd(values).sort().middleValue(); - dirtyMedian = false; - } - - public void resetExtremes() { - max = Integer.MIN_VALUE; - min = Integer.MAX_VALUE; - - for(int i = 0; i < values.length(); i++) { - double v = values.get(i); - max = M.max(max, v); - min = M.min(min, v); - } - - dirtyExtremes = 0; - } - - public void put(double i) { - super.put(i); - dirtyMedian = true; - dirtyExtremes++; - max = M.max(max, i); - min = M.min(min, i); - } -} diff --git a/src/main/java/com/volmit/iris/util/board/Board.java b/src/main/java/com/volmit/iris/util/board/Board.java deleted file mode 100644 index daf535658..000000000 --- a/src/main/java/com/volmit/iris/util/board/Board.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.board; - -import com.volmit.iris.util.format.C; -import lombok.NonNull; -import lombok.Setter; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.Team; - -import java.util.Collections; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -/** - * @author Missionary (missionarymc@gmail.com) - * @since 3/23/2018 - */ -public class Board { - - private static final String[] CACHED_ENTRIES = new String[C.values().length]; - - private static final Function APPLY_COLOR_TRANSLATION = s -> C.translateAlternateColorCodes('&', s); - - static { - IntStream.range(0, 15).forEach(i -> CACHED_ENTRIES[i] = C.values()[i].toString() + C.RESET); - } - - private final Player player; - private final Objective objective; - @Setter - private BoardSettings boardSettings; - private boolean ready; - - @SuppressWarnings("deprecation") - public Board(@NonNull final Player player, final BoardSettings boardSettings) { - this.player = player; - this.boardSettings = boardSettings; - this.objective = this.getScoreboard().getObjective("board") == null ? this.getScoreboard().registerNewObjective("board", "dummy") : this.getScoreboard().getObjective("board"); - this.objective.setDisplaySlot(DisplaySlot.SIDEBAR); - Team team = this.getScoreboard().getTeam("board") == null ? this.getScoreboard().registerNewTeam("board") : this.getScoreboard().getTeam("board"); - team.setAllowFriendlyFire(true); - team.setCanSeeFriendlyInvisibles(false); - team.setPrefix(""); - team.setSuffix(""); - this.ready = true; - } - - public Scoreboard getScoreboard() { - return (player != null) ? player.getScoreboard() : null; - } - - public void remove() { - this.resetScoreboard(); - } - - public void update() { - // Checking if we are ready to start updating the Scoreboard. - if(!ready) { - return; - } - - // Making sure the player is connected. - if(!player.isOnline()) { - remove(); - return; - } - - // Making sure the Scoreboard Provider is set. - if(boardSettings == null) { - return; - } - - // Getting their Scoreboard display from the Scoreboard Provider. - final List entries = boardSettings.getBoardProvider().getLines(player).stream().map(APPLY_COLOR_TRANSLATION).collect(Collectors.toList()); - - if(boardSettings.getScoreDirection() == ScoreDirection.UP) { - Collections.reverse(entries); - } - - // Setting the Scoreboard title - String title = boardSettings.getBoardProvider().getTitle(player); - if(title.length() > 32) { - Bukkit.getLogger().warning("The title " + title + " is over 32 characters in length, substringing to prevent errors."); - title = title.substring(0, 32); - } - objective.setDisplayName(C.translateAlternateColorCodes('&', title)); - - // Clearing previous Scoreboard values if entry sizes don't match. - if(this.getScoreboard().getEntries().size() != entries.size()) - this.getScoreboard().getEntries().forEach(this::removeEntry); - - // Setting Scoreboard lines. - for(int i = 0; i < entries.size(); i++) { - String str = entries.get(i); - BoardEntry entry = BoardEntry.translateToEntry(str); - Team team = getScoreboard().getTeam(CACHED_ENTRIES[i]); - - if(team == null) { - team = this.getScoreboard().registerNewTeam(CACHED_ENTRIES[i]); - team.addEntry(team.getName()); - } - - team.setPrefix(entry.getPrefix()); - team.setSuffix(entry.getSuffix()); - - switch(boardSettings.getScoreDirection()) { - case UP -> objective.getScore(team.getName()).setScore(1 + i); - case DOWN -> objective.getScore(team.getName()).setScore(15 - i); - } - } - } - - public void removeEntry(String id) { - this.getScoreboard().resetScores(id); - } - - public void resetScoreboard() { - ready = false; - player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard()); - } -} diff --git a/src/main/java/com/volmit/iris/util/board/BoardEntry.java b/src/main/java/com/volmit/iris/util/board/BoardEntry.java deleted file mode 100644 index cd252b3bd..000000000 --- a/src/main/java/com/volmit/iris/util/board/BoardEntry.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.board; - -import com.volmit.iris.util.format.C; -import lombok.Getter; -import org.apache.commons.lang.StringUtils; - -/** - * @author Missionary (missionarymc@gmail.com) - * @since 3/29/2018 - */ -@SuppressWarnings("ClassCanBeRecord") -public class BoardEntry { - - @Getter - private final String prefix, suffix; - - private BoardEntry(final String prefix, final String suffix) { - this.prefix = prefix; - this.suffix = suffix; - } - - public static BoardEntry translateToEntry(String input) { - if(input.isEmpty()) { - return new BoardEntry("", ""); - } - if(input.length() <= 16) { - return new BoardEntry(input, ""); - } else { - String prefix = input.substring(0, 16); - String suffix = ""; - - if(prefix.endsWith("\u00a7")) { - prefix = prefix.substring(0, prefix.length() - 1); - suffix = "\u00a7" + suffix; - } - - suffix = StringUtils.left(C.getLastColors(prefix) + suffix + input.substring(16), 16); - return new BoardEntry(prefix, suffix); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/board/BoardManager.java b/src/main/java/com/volmit/iris/util/board/BoardManager.java deleted file mode 100644 index c9989cf67..000000000 --- a/src/main/java/com/volmit/iris/util/board/BoardManager.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.board; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitTask; - -import java.util.Collections; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - - -public class BoardManager { - - private final JavaPlugin plugin; - private final Map scoreboards; - private final BukkitTask updateTask; - private BoardSettings boardSettings; - - - public BoardManager(JavaPlugin plugin, BoardSettings boardSettings) { - this.plugin = plugin; - this.boardSettings = boardSettings; - this.scoreboards = new ConcurrentHashMap<>(); - this.updateTask = new BoardUpdateTask(this).runTaskTimer(plugin, 2L, 20L); - plugin.getServer().getOnlinePlayers().forEach(this::setup); - } - - - public void setBoardSettings(BoardSettings boardSettings) { - this.boardSettings = boardSettings; - scoreboards.values().forEach(board -> board.setBoardSettings(boardSettings)); - } - - - public boolean hasBoard(Player player) { - return scoreboards.containsKey(player.getUniqueId()); - } - - - public Optional getBoard(Player player) { - return Optional.ofNullable(scoreboards.get(player.getUniqueId())); - } - - - public void setup(Player player) { - Optional.ofNullable(scoreboards.remove(player.getUniqueId())).ifPresent(Board::resetScoreboard); - if(player.getScoreboard().equals(Bukkit.getScoreboardManager().getMainScoreboard())) { - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - scoreboards.put(player.getUniqueId(), new Board(player, boardSettings)); - } - - - public void remove(Player player) { - Optional.ofNullable(scoreboards.remove(player.getUniqueId())).ifPresent(Board::remove); - } - - - public Map getScoreboards() { - return Collections.unmodifiableMap(scoreboards); - } - - - public void onDisable() { - updateTask.cancel(); - plugin.getServer().getOnlinePlayers().forEach(this::remove); - scoreboards.clear(); - } -} diff --git a/src/main/java/com/volmit/iris/util/board/BoardProvider.java b/src/main/java/com/volmit/iris/util/board/BoardProvider.java deleted file mode 100644 index 5b13bbc86..000000000 --- a/src/main/java/com/volmit/iris/util/board/BoardProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.board; - -import org.bukkit.entity.Player; - -import java.util.List; - - -public interface BoardProvider { - - String getTitle(Player player); - - - List getLines(Player player); -} diff --git a/src/main/java/com/volmit/iris/util/board/BoardSettings.java b/src/main/java/com/volmit/iris/util/board/BoardSettings.java deleted file mode 100644 index 8ca30503c..000000000 --- a/src/main/java/com/volmit/iris/util/board/BoardSettings.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.board; - -import lombok.Builder; -import lombok.Getter; - - -@SuppressWarnings("ClassCanBeRecord") -@Getter -@Builder -public class BoardSettings { - - private final BoardProvider boardProvider; - - - private final ScoreDirection scoreDirection; -} diff --git a/src/main/java/com/volmit/iris/util/board/BoardUpdateTask.java b/src/main/java/com/volmit/iris/util/board/BoardUpdateTask.java deleted file mode 100644 index ce7ded229..000000000 --- a/src/main/java/com/volmit/iris/util/board/BoardUpdateTask.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.board; - -import lombok.RequiredArgsConstructor; -import org.bukkit.Bukkit; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.UUID; -import java.util.function.Predicate; - -/** - * @author Missionary (missionarymc@gmail.com) - * @since 5/31/2018 - */ -@RequiredArgsConstructor -public class BoardUpdateTask extends BukkitRunnable { - - private static final Predicate PLAYER_IS_ONLINE = uuid -> Bukkit.getPlayer(uuid) != null; - - private final BoardManager boardManager; - - @Override - public void run() { - boardManager.getScoreboards().entrySet().stream().filter(entrySet -> PLAYER_IS_ONLINE.test(entrySet.getKey())).forEach(entrySet -> entrySet.getValue().update()); - } -} diff --git a/src/main/java/com/volmit/iris/util/board/ScoreDirection.java b/src/main/java/com/volmit/iris/util/board/ScoreDirection.java deleted file mode 100644 index ab8610b93..000000000 --- a/src/main/java/com/volmit/iris/util/board/ScoreDirection.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.board; - -/** - * @author Missionary (missionarymc@gmail.com) - * @since 5/31/2018 - */ - -public enum ScoreDirection { - - UP, - - - DOWN -} diff --git a/src/main/java/com/volmit/iris/util/cache/ArrayCache.java b/src/main/java/com/volmit/iris/util/cache/ArrayCache.java deleted file mode 100644 index 8b578898e..000000000 --- a/src/main/java/com/volmit/iris/util/cache/ArrayCache.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.util.hunk.bits.Writable; - -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public interface ArrayCache extends Writable { - T get(int i); - - void set(int i, T t); - - void iset(int i, int v); - - int getWidth(); - - int getHeight(); - - void writeCache(DataOutputStream dos) throws IOException; - - static int zigZag(int coord, int size) - { - if(coord < 0) - { - coord = Math.abs(coord); - } - - if(coord % (size * 2) >= size) - { - return (size) - (coord % size) - 1; - } - - else { - return coord % size; - } - } - - default void set(int x, int y, T v) - { - set((zigZag(y, getHeight()) * getWidth()) + zigZag(x, getWidth()), v); - } - - default T get(int x, int y) - { - try - { - return get((zigZag(y, getHeight()) * getWidth()) + zigZag(x, getWidth())); - } - - catch(Throwable e) - { - e.printStackTrace(); - throw e; - } - } - - default void iset(int x, int y, int v) - { - iset((zigZag(y, getHeight()) * getWidth()) + zigZag(x, getWidth()), v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/ByteBitCache.java b/src/main/java/com/volmit/iris/util/cache/ByteBitCache.java deleted file mode 100644 index eb701973f..000000000 --- a/src/main/java/com/volmit/iris/util/cache/ByteBitCache.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class ByteBitCache extends DataBitCache { - public ByteBitCache(int width, int height) { - super(width, height); - } - - @Override - public Integer readNodeData(DataInputStream din) throws IOException { - return (int) din.readByte(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Integer integer) throws IOException { - dos.writeByte(integer); - } - - @Override - public void iset(int i, int v) { - set(i, v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/ByteCache.java b/src/main/java/com/volmit/iris/util/cache/ByteCache.java deleted file mode 100644 index 7c9421b3a..000000000 --- a/src/main/java/com/volmit/iris/util/cache/ByteCache.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import lombok.Getter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class ByteCache implements ArrayCache { - @Getter - private final int width; - @Getter - private final int height; - private final byte[] cache; - - public ByteCache(int width, int height) - { - this.width = width; - this.height = height; - cache = new byte[width * height]; - } - - public void set(int i, Integer v) - { - cache[i] = v.byteValue(); - } - - public Integer get(int i) - { - return (int)cache[i]; - } - - @Override - public void writeCache(DataOutputStream dos) throws IOException { - dos.writeInt(width); - dos.writeInt(height); - - for(int i = 0; i < width * height; i++) - { - dos.writeByte(get(i)); - } - } - - @Override - public Integer readNodeData(DataInputStream din) throws IOException { - return (int) din.readByte(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Integer integer) throws IOException { - dos.writeByte(integer); - } - - @Override - public void iset(int i, int v) { - set(i, v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/DataBitCache.java b/src/main/java/com/volmit/iris/util/cache/DataBitCache.java deleted file mode 100644 index ba8ff7ebf..000000000 --- a/src/main/java/com/volmit/iris/util/cache/DataBitCache.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import com.volmit.iris.util.hunk.bits.DataContainer; -import lombok.Getter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public abstract class DataBitCache implements ArrayCache { - @Getter - private final int width; - @Getter - private final int height; - private final DataContainer cache; - - public DataBitCache(int width, int height) - { - this.width = width; - this.height = height; - cache = new DataContainer<>(this, width * height); - } - - public void set(int i, T v) - { - cache.set(i, v); - } - - public T get(int i) - { - return cache.get(i); - } - - @Override - public void writeCache(DataOutputStream dos) throws IOException { - dos.writeInt(width); - dos.writeInt(height); - cache.writeDos(dos); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/FloatBitCache.java b/src/main/java/com/volmit/iris/util/cache/FloatBitCache.java deleted file mode 100644 index 4d0473dfc..000000000 --- a/src/main/java/com/volmit/iris/util/cache/FloatBitCache.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class FloatBitCache extends DataBitCache { - public FloatBitCache(int width, int height) { - super(width, height); - } - - @Override - public Float readNodeData(DataInputStream din) throws IOException { - return din.readFloat(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Float integer) throws IOException { - dos.writeFloat(integer); - } - - @Override - public void iset(int i, int v) { - set(i, (float)v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/FloatCache.java b/src/main/java/com/volmit/iris/util/cache/FloatCache.java deleted file mode 100644 index 334922a52..000000000 --- a/src/main/java/com/volmit/iris/util/cache/FloatCache.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import lombok.Getter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - -public class FloatCache implements ArrayCache { - @Getter - private final int width; - @Getter - private final int height; - private final float[] cache; - - - public FloatCache(File file) throws IOException { - this(new DataInputStream(new FileInputStream(file))); - } - - public FloatCache(DataInputStream din) throws IOException { - this(din.readInt(), din.readInt()); - for(int i = 0; i < width * height; i++) - { - cache[i] = din.readFloat(); - } - din.close(); - } - - public FloatCache(int width, int height) - { - this.width = width; - this.height = height; - cache = new float[width * height]; - } - - public void set(int i, Float v) - { - cache[i] = v; - } - - public Float get(int i) - { - return cache[i]; - } - - @Override - public void writeCache(DataOutputStream dos) throws IOException { - dos.writeInt(width); - dos.writeInt(height); - - for(int i = 0; i < width * height; i++) - { - dos.writeFloat(get(i)); - } - } - - @Override - public Float readNodeData(DataInputStream din) throws IOException { - return din.readFloat(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Float integer) throws IOException { - dos.writeFloat(integer); - } - - @Override - public void iset(int i, int v) { - set(i, (float) v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/IntBitCache.java b/src/main/java/com/volmit/iris/util/cache/IntBitCache.java deleted file mode 100644 index c06e62682..000000000 --- a/src/main/java/com/volmit/iris/util/cache/IntBitCache.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class IntBitCache extends DataBitCache { - public IntBitCache(int width, int height) { - super(width, height); - } - - @Override - public Integer readNodeData(DataInputStream din) throws IOException { - return din.readInt(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Integer integer) throws IOException { - dos.writeInt(integer); - } - - @Override - public void iset(int i, int v) { - set(i, v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/IntCache.java b/src/main/java/com/volmit/iris/util/cache/IntCache.java deleted file mode 100644 index 63509466e..000000000 --- a/src/main/java/com/volmit/iris/util/cache/IntCache.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import com.volmit.iris.util.hunk.bits.DataContainer; -import com.volmit.iris.util.hunk.bits.Writable; -import lombok.Getter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class IntCache implements ArrayCache { - @Getter - private final int width; - @Getter - private final int height; - private final int[] cache; - - public IntCache(int width, int height) - { - this.width = width; - this.height = height; - cache = new int[width * height]; - } - - public void set(int i, Integer v) - { - cache[i] = v; - } - - public Integer get(int i) - { - return cache[i]; - } - - @Override - public void writeCache(DataOutputStream dos) throws IOException { - dos.writeInt(width); - dos.writeInt(height); - - for(int i = 0; i < width * height; i++) - { - dos.writeInt(get(i)); - } - } - - @Override - public Integer readNodeData(DataInputStream din) throws IOException { - return din.readInt(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Integer integer) throws IOException { - dos.writeInt(integer); - } - - @Override - public void iset(int i, int v) { - set(i, v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/ShortBitCache.java b/src/main/java/com/volmit/iris/util/cache/ShortBitCache.java deleted file mode 100644 index 4bb01d053..000000000 --- a/src/main/java/com/volmit/iris/util/cache/ShortBitCache.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class ShortBitCache extends DataBitCache { - public ShortBitCache(int width, int height) { - super(width, height); - } - - @Override - public Short readNodeData(DataInputStream din) throws IOException { - return din.readShort(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Short integer) throws IOException { - dos.writeShort(integer); - } - - @Override - public void iset(int i, int v) { - set(i, (short) v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/ShortCache.java b/src/main/java/com/volmit/iris/util/cache/ShortCache.java deleted file mode 100644 index b25f3981d..000000000 --- a/src/main/java/com/volmit/iris/util/cache/ShortCache.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -import lombok.Getter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class ShortCache implements ArrayCache { - @Getter - private final int width; - @Getter - private final int height; - private final short[] cache; - - public ShortCache(int width, int height) - { - this.width = width; - this.height = height; - cache = new short[width * height]; - } - - public void set(int i, Short v) - { - cache[i] = v; - } - - public Short get(int i) - { - return cache[i]; - } - - @Override - public void writeCache(DataOutputStream dos) throws IOException { - dos.writeInt(width); - dos.writeInt(height); - - for(int i = 0; i < width * height; i++) - { - dos.writeShort(get(i)); - } - } - - @Override - public Short readNodeData(DataInputStream din) throws IOException { - return din.readShort(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Short integer) throws IOException { - dos.writeShort(integer); - } - - @Override - public void iset(int i, int v) { - set(i, (short) v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/UByteBitCache.java b/src/main/java/com/volmit/iris/util/cache/UByteBitCache.java deleted file mode 100644 index 4a1309f7b..000000000 --- a/src/main/java/com/volmit/iris/util/cache/UByteBitCache.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -public class UByteBitCache extends ByteBitCache { - public UByteBitCache(int width, int height) { - super(width, height); - } - - @Override - public void set(int i, Integer v) { - super.set(i, v + Byte.MIN_VALUE); - } - - @Override - public Integer get(int i) { - return super.get(i) - Byte.MIN_VALUE; - } - - @Override - public void iset(int i, int v) { - set(i, v); - } -} diff --git a/src/main/java/com/volmit/iris/util/cache/UByteCache.java b/src/main/java/com/volmit/iris/util/cache/UByteCache.java deleted file mode 100644 index 81f5c23cc..000000000 --- a/src/main/java/com/volmit/iris/util/cache/UByteCache.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.cache; - -public class UByteCache extends ByteCache { - public UByteCache(int width, int height) { - super(width, height); - } - - @Override - public void set(int i, Integer v) { - super.set(i, v + Byte.MIN_VALUE); - } - - @Override - public Integer get(int i) { - return super.get(i) - Byte.MIN_VALUE; - } - - @Override - public void iset(int i, int v) { - set(i, v); - } -} diff --git a/src/main/java/com/volmit/iris/util/collection/GBiset.java b/src/main/java/com/volmit/iris/util/collection/GBiset.java deleted file mode 100644 index 19beaaded..000000000 --- a/src/main/java/com/volmit/iris/util/collection/GBiset.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.collection; - - -import java.io.Serializable; - -/** - * A Biset - * - * @param
- * the first object type - * @param - * the second object type - * @author cyberpwn - */ -@SuppressWarnings("hiding") -public class GBiset implements Serializable { - private static final long serialVersionUID = 1L; - private A a; - private B b; - - /** - * Create a new Biset - * - * @param a - * the first object - * @param b - * the second object - */ - public GBiset(A a, B b) { - this.a = a; - this.b = b; - } - - /** - * Get the object of the type A - * - * @return the first object - */ - public A getA() { - return a; - } - - /** - * Set the first object - * - * @param a - * the first object A - */ - public void setA(A a) { - this.a = a; - } - - /** - * Get the second object - * - * @return the second object - */ - public B getB() { - return b; - } - - /** - * Set the second object - */ - public void setB(B b) { - this.b = b; - } -} diff --git a/src/main/java/com/volmit/iris/util/collection/GListAdapter.java b/src/main/java/com/volmit/iris/util/collection/GListAdapter.java deleted file mode 100644 index 2ca4ddbc6..000000000 --- a/src/main/java/com/volmit/iris/util/collection/GListAdapter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.collection; - - -import java.util.List; - -/** - * Adapts a list of objects into a list of other objects - * - * @param - * the from object in lists (the item INSIDE the list) - * @param - * the to object in lists (the item INSIDE the list) - * @author cyberpwn - */ -public abstract class GListAdapter { - /** - * Adapts a list of FROM to a list of TO - * - * @param from - * the from list - * @return the to list - */ - public List adapt(List from) { - List adapted = new KList<>(); - - for(FROM i : from) { - TO t = onAdapt(i); - - if(t != null) { - adapted.add(onAdapt(i)); - } - } - - return adapted; - } - - /** - * Adapts a list object FROM to TO for use with the adapt method - * - * @param from - * the from object - * @return the to object - */ - public abstract TO onAdapt(FROM from); -} diff --git a/src/main/java/com/volmit/iris/util/collection/KList.java b/src/main/java/com/volmit/iris/util/collection/KList.java deleted file mode 100644 index 2da64a039..000000000 --- a/src/main/java/com/volmit/iris/util/collection/KList.java +++ /dev/null @@ -1,723 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.collection; - -import com.google.common.util.concurrent.AtomicDoubleArray; -import com.volmit.iris.util.json.JSONArray; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Random; -import java.util.function.Function; -import java.util.function.Predicate; - -@SuppressWarnings("ALL") -public class KList extends ArrayList implements List { - private static final long serialVersionUID = -2892550695744823337L; - - @SafeVarargs - public KList(T... ts) { - super(); - add(ts); - } - - public KList() { - super(); - } - - public KList(int cap) { - super(cap); - } - - public KList(Collection values) { - super(); - add(values); - } - - public KList(Enumeration e) { - super(); - add(e); - } - - public static KList fromJSONAny(JSONArray oo) { - KList s = new KList(); - - for(int i = 0; i < oo.length(); i++) { - s.add(oo.get(i).toString()); - } - - return s; - } - - public static KList asStringList(List oo) { - KList s = new KList(); - - for(Object i : oo) { - s.add(i.toString()); - } - - return s; - } - - public int indexOfAddIfNeeded(T v) { - addIfMissing(v); - return indexOf(v); - } - - /** - * Remove the last element - */ - public KList removeLast() { - remove(last()); - - return this; - } - - public void addMultiple(T t, int c) { - for(int i = 0; i < c; i++) { - add(t); - } - } - - private KList add(Enumeration e) { - while(e.hasMoreElements()) { - add(e.nextElement()); - } - - return this; - } - - public KList add(Collection values) { - addAll(values); - return this; - } - - /** - * Create a Map out of this list where this list becomes the values of the - * returned map. You must specify each key for each value in this list. In the - * function, returning null will not add the keyval pair. - * - * @param - * the inferred key type - * @param f - * the function - * @return the new map - */ - public KMap asValues(Function f) { - KMap m = new KMap(); - forEach((i) -> m.putNonNull(f.apply(i), i)); - return m; - } - - /** - * Create a Map out of this list where this list becomes the keys of the - * returned map. You must specify each value for each key in this list. In the - * function, returning null will not add the keyval pair. - * - * @param - * the inferred value type - * @param f - * the function - * @return the new map - */ - public KMap asKeys(Function f) { - KMap m = new KMap(); - forEach((i) -> m.putNonNull(i, f.apply(i))); - return m; - } - - /** - * Cut this list into targetCount sublists - * - * @param targetCount - * the target count of sublists - * @return the list of sublists - */ - public KList> divide(int targetCount) { - return split(size() / targetCount); - } - - /** - * Split this list into a list of sublists with roughly targetSize elements of T - * per sublist - * - * @param targetSize - * the target size - * @return the list of sublists - */ - public KList> split(int targetSize) { - targetSize = targetSize < 1 ? 1 : targetSize; - KList> gg = new KList<>(); - KList b = new KList<>(); - - for(T i : this) { - if(b.size() >= targetSize) { - gg.add(b.copy()); - b.clear(); - } - - b.add(i); - } - - if(!b.isEmpty()) { - gg.add(b); - } - - return gg; - } - - /** - * Rewrite this list by checking each value and changing the value (or not). - * Return null to remove the element in the function - * - * @param t - * the function - * @return the same list (not a copy) - */ - public KList rewrite(Function t) { - KList m = copy(); - clear(); - - for(T i : m) { - addNonNull(t.apply(i)); - } - - return this; - } - - /** - * To array - * - * @return the array - */ - @SuppressWarnings("unchecked") - public T[] array() { - return (T[]) toArray(); - } - - /** - * Return a copy of this list - * - * @return the copy - */ - public KList copy() { - return new KList().add(this); - } - - /** - * Shuffle the list - * - * @return the same list - */ - public KList shuffle() { - Collections.shuffle(this); - return this; - } - - public KList shuffle(Random rng) { - Collections.shuffle(this, rng); - return this; - } - - /** - * Sort the list (based on toString comparison) - * - * @return the same list - */ - public KList sort() { - Collections.sort(this, (a, b) -> a.toString().compareTo(b.toString())); - return this; - } - - /** - * Reverse this list - * - * @return the same list - */ - public KList reverse() { - Collections.reverse(this); - return this; - } - - @Override - public String toString() { - return "[" + toString(", ") + "]"; - } - - /** - * Tostring with a seperator for each item in the list - * - * @param split - * the seperator - * @return the string representing this object - */ - public String toString(String split) { - if(isEmpty()) { - return ""; - } - - if(size() == 1) { - return get(0) + ""; - } - - StringBuilder b = new StringBuilder(); - - for(String i : toStringList()) { - b.append(split).append(i == null ? "null" : i); - } - - return b.substring(split.length()); - } - - /** - * Invoke tostring on each value in the list into a string list - * - * @return the string list - */ - public KList toStringList() { - return convert((t) -> t + ""); - } - - /** - * Add the contents of the given list (v) into this list using a converter - * - * @param - * the type of the forign list - * @param v - * the forign (given) list - * @param converter - * the converter that converts the forign type into this list type - * @return this list (builder) - */ - public KList addFrom(List v, Function converter) { - v.forEach((g) -> add(converter.apply(g))); - return this; - } - - /** - * Convert this list into another list type. Such as GList to - * GList. list.convert((i) -> "" + i); - */ - public KList convert(Function converter) { - KList v = new KList(); - forEach((t) -> v.addNonNull(converter.apply(t))); - return v; - } - - public KList removeWhere(Predicate t) { - for(T i : copy()) { - if(t.test(i)) { - remove(i); - } - } - - return this; - } - - /** - * Adds T to the list, ignores if null - * - * @param t - * the value to add - * @return the same list - */ - public KList addNonNull(T t) { - if(t != null) { - super.add(t); - } - - return this; - } - - /** - * Swaps the values of index a and b. For example "hello", "world", "!" swap(1, - * 2) would change the list to "hello", "!", "world" - * - * @param a - * the first index - * @param b - * the second index - * @return the same list (builder), not a copy - */ - public KList swapIndexes(int a, int b) { - T aa = remove(a); - T bb = get(b); - add(a, bb); - remove(b); - add(b, aa); - - return this; - } - - /** - * Remove a number of elements from the list - * - * @param t - * the elements - * @return this list - */ - @SuppressWarnings("unchecked") - public KList remove(T... t) { - for(T i : t) { - super.remove(i); - } - - return this; - } - - /** - * Add another glist's contents to this one (addall builder) - * - * @param t - * the list - * @return the same list - */ - public KList add(KList t) { - super.addAll(t); - return this; - } - - /** - * Add a number of values to this list - * - * @param t - * the list - * @return this list - */ - @SuppressWarnings("unchecked") - public KList add(T... t) { - for(T i : t) { - super.add(i); - } - - return this; - } - - /** - * Check if this list has an index at the given index - * - * @param index - * the given index - * @return true if size > index - */ - public boolean hasIndex(int index) { - return size() > index && index >= 0; - } - - /** - * Get the last index of this list (size - 1) - * - * @return the last index of this list - */ - public int last() { - return size() - 1; - } - - /** - * Deduplicate this list by converting to linked hash set and back - * - * @return the deduplicated list - */ - public KList dedupe() { - LinkedHashSet lhs = new LinkedHashSet(this); - return qclear().add(lhs); - } - - /** - * Clear this list (and return it) - * - * @return the same list - */ - public KList qclear() { - super.clear(); - return this; - } - - /** - * Simply !isEmpty() - * - * @return true if this list has 1 or more element(s) - */ - public boolean hasElements() { - return !isEmpty(); - } - - /** - * Simply !isEmpty() - * - * @return true if this list has 1 or more element(s) - */ - public boolean isNotEmpty() { - return !isEmpty(); - } - - /** - * Pop the first item off this list and return it - * - * @return the popped off item or null if the list is empty - */ - public T pop() { - if(isEmpty()) { - return null; - } - - return remove(0); - } - - /** - * Pop the last item off this list and return it - * - * @return the popped off item or null if the list is empty - */ - public T popLast() { - if(isEmpty()) { - return null; - } - - return remove(last()); - } - - public T popRandom() { - if(isEmpty()) { - return null; - } - - if(size() == 1) { - return pop(); - } - - return remove(M.irand(0, last())); - } - - public T popRandom(RNG rng) { - if(isEmpty()) { - return null; - } - - if(size() == 1) { - return pop(); - } - - return remove(rng.i(0, last())); - } - - public KList sub(int f, int t) { - KList g = new KList<>(); - - for(int i = f; i < M.min(size(), t); i++) { - g.add(get(i)); - } - - return g; - } - - public JSONArray toJSONStringArray() { - JSONArray j = new JSONArray(); - - for(Object i : this) { - j.put(i.toString()); - } - - return j; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(Object[] values) { - for(Object i : values) { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(int[] values) { - for(Object i : values) { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(double[] values) { - for(Object i : values) { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(AtomicDoubleArray values) { - for(int i = 0; i < values.length(); i++) { - add((T) ((Object) values.get(i))); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(float[] values) { - for(Object i : values) { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(byte[] values) { - for(Object i : values) { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(short[] values) { - for(Object i : values) { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(long[] values) { - for(Object i : values) { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(boolean[] values) { - for(Object i : values) { - add((T) i); - } - - return this; - } - - public T middleValue() { - return get(middleIndex()); - } - - private int middleIndex() { - return size() % 2 == 0 ? (size() / 2) : ((size() / 2) + 1); - } - - public T getRandom() { - if(isEmpty()) { - return null; - } - - if(size() == 1) { - return get(0); - } - - return get(M.irand(0, last())); - } - - public KList popRandom(RNG rng, int c) { - KList m = new KList<>(); - - for(int i = 0; i < c; i++) { - if(isEmpty()) { - break; - } - - m.add(popRandom()); - } - - return m; - } - - public T getRandom(RNG rng) { - if(isEmpty()) { - return null; - } - - if(size() == 1) { - return get(0); - } - - return get(rng.i(0, last())); - } - - public KList qdel(T t) { - remove(t); - return this; - } - - public KList qadd(T t) { - add(t); - return this; - } - - public KList qaddIfMissing(T t) { - addIfMissing(t); - return this; - } - - public KList removeDuplicates() { - KSet v = new KSet<>(); - v.addAll(this); - KList m = new KList<>(); - m.addAll(v); - return m; - } - - public boolean addIfMissing(T t) { - if(!contains(t)) { - add(t); - return true; - } - - return false; - } - - public void addAllIfMissing(KList t) { - for(T i : t) { - if(!contains(i)) { - add(i); - } - } - } - - public KList shuffleCopy(Random rng) { - KList t = copy(); - t.shuffle(rng); - return t; - } - - public KList qdrop() { - pop(); - return this; - } -} diff --git a/src/main/java/com/volmit/iris/util/collection/KMap.java b/src/main/java/com/volmit/iris/util/collection/KMap.java deleted file mode 100644 index 443cc0cb7..000000000 --- a/src/main/java/com/volmit/iris/util/collection/KMap.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.collection; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.function.Consumer2; -import com.volmit.iris.util.function.Consumer3; -import com.volmit.iris.util.scheduling.Queue; - -import java.util.Collections; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -@SuppressWarnings("ALL") -public class KMap extends ConcurrentHashMap { - private static final long serialVersionUID = 7288942695300448163L; - - public KMap() { - super(); - } - - public KMap(Map gMap) { - this(); - put(gMap); - } - - public K getKey(V value) { - for(KeyPair i : keypair()) { - if(i.getV().equals(value)) { - return i.getK(); - } - } - - return null; - } - - /** - * Puts a value into a map-value-list based on the key such that if GMap> where V is GList - * - * @param - * the list type in the value type - * @param k - * the key to look for - * @param vs - * the values to put into the list of the given key - * @return the same list (builder) - */ - @SuppressWarnings("unchecked") - public KMap putValueList(K k, S... vs) { - try { - KMap> s = (KMap>) this; - - if(!s.containsKey(k)) { - s.put(k, new KList()); - } - - s.get(k).add(vs); - } catch(Throwable e) { - Iris.reportError(e); - - } - - return this; - } - - /** - * Returns a sorted list of keys from this map, based on the sorting order of - * the values. - * - * @return the value-sorted key list - */ - public KList sortK() { - KList k = new KList(); - KList v = v(); - - Collections.sort(v, new Comparator() { - @Override - public int compare(V v, V t1) { - return v.toString().compareTo(t1.toString()); - } - }); - - for(V i : v) { - for(K j : k()) { - if(get(j).equals(i)) { - k.add(j); - } - } - } - - k.dedupe(); - return k; - } - - /** - * Returns a sorted list of keys from this map, based on the sorting order of - * the values. Sorting is based on numerical values - * - * @return the value-sorted key list - */ - public KList sortKNumber() { - KList k = new KList(); - KList v = v(); - - Collections.sort(v, new Comparator() { - @Override - public int compare(V v, V t1) { - Number n1 = (Number) v; - Number n2 = (Number) t1; - - return (int) ((n1.doubleValue() - n2.doubleValue()) * 1000); - } - }); - - for(V i : v) { - for(K j : k()) { - if(get(j).equals(i)) { - k.add(j); - } - } - } - - k.dedupe(); - return k; - } - - /** - * Put another map's values into this map - * - * @param m - * the map to insert - * @return this map (builder) - */ - public KMap put(Map m) { - putAll(m); - return this; - } - - /** - * Return a copy of this map - * - * @return the copied map - */ - public KMap copy() { - return new KMap(this); - } - - /** - * Loop through each keyvalue set (copy of it) with the map parameter - * - * @param f - * the function - * @return the same gmap - */ - public KMap rewrite(Consumer3> f) { - KMap m = copy(); - - for(K i : m.k()) { - f.accept(i, get(i), this); - } - - return this; - } - - /** - * Loop through each keyvalue set (copy of it) - * - * @param f - * the function - * @return the same gmap - */ - public KMap each(Consumer2 f) { - for(K i : k()) { - f.accept(i, get(i)); - } - - return this; - } - - /** - * Flip the hashmap and flatten the value list even if there are multiple keys - * - * @return the flipped and flattened hashmap - */ - public KMap flipFlatten() { - KMap> f = flip(); - KMap m = new KMap<>(); - - for(V i : f.k()) { - m.putNonNull(i, m.isEmpty() ? null : m.get(0)); - } - - return m; - } - - /** - * Flip the hashmap so keys are now list-keys in the value position - * - * @return the flipped hashmap - */ - public KMap> flip() { - KMap> flipped = new KMap>(); - - for(K i : keySet()) { - if(i == null) { - continue; - } - - if(!flipped.containsKey(get(i))) { - flipped.put(get(i), new KList()); - } - - flipped.get(get(i)).add(i); - } - - return flipped; - } - - /** - * Sort values based on the keys sorting order - * - * @return the values (sorted) - */ - public KList sortV() { - KList v = new KList(); - KList k = k(); - - Collections.sort(k, new Comparator() { - @Override - public int compare(K v, K t1) { - return v.toString().compareTo(t1.toString()); - } - }); - - for(K i : k) { - for(V j : v()) { - if(get(i).equals(j)) { - v.add(j); - } - } - } - - v.dedupe(); - return v; - } - - public KList sortVNoDedupe() { - KList v = new KList(); - KList k = k(); - - Collections.sort(k, new Comparator() { - @Override - public int compare(K v, K t1) { - return v.toString().compareTo(t1.toString()); - } - }); - - for(K i : k) { - for(V j : v()) { - if(get(i).equals(j)) { - v.add(j); - } - } - } - - return v; - } - - /** - * Get a copy of this maps keys - * - * @return the keys - */ - public KList k() { - KList k = new KList(); - Enumeration kk = keys(); - - while(kk.hasMoreElements()) { - K kkk = kk.nextElement(); - k.add(kkk); - } - - return k; - } - - /** - * Get a copy of this maps values - * - * @return the values - */ - public KList v() { - return new KList(values()); - } - - /** - * Still works as it normally should except it returns itself (builder) - * - * @param key - * the key - * @param value - * the value (single only supported) - */ - public KMap qput(K key, V value) { - super.put(key, value); - return this; - } - - /** - * Works just like put, except it wont put anything unless the key and value are - * nonnull - * - * @param key - * the nonnull key - * @param value - * the nonnull value - * @return the same map - */ - public KMap putNonNull(K key, V value) { - if(key != null || value != null) { - put(key, value); - } - - return this; - } - - public V putThen(K key, V valueIfKeyNotPresent) { - if(!containsKey(key)) { - put(key, valueIfKeyNotPresent); - } - - return get(key); - } - - /** - * Clear this map and return it - * - * @return the cleared map - */ - public KMap qclear() { - super.clear(); - return this; - } - - /** - * Convert this map to keypairs - * - * @return the keypair list - */ - public KList> keypair() { - KList> g = new KList<>(); - each((k, v) -> g.add(new KeyPair(k, v))); - return g; - } - - /** - * Create a keypair queue - * - * @return the queue - */ - public Queue> enqueue() { - return Queue.create(keypair()); - } - - /** - * Create a key queue - * - * @return the queue - */ - public Queue enqueueKeys() { - return Queue.create(k()); - } - - /** - * Create a value queue - * - * @return the queue - */ - public Queue enqueueValues() { - return Queue.create(v()); - } -} diff --git a/src/main/java/com/volmit/iris/util/collection/KSet.java b/src/main/java/com/volmit/iris/util/collection/KSet.java deleted file mode 100644 index ad96f7085..000000000 --- a/src/main/java/com/volmit/iris/util/collection/KSet.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.collection; - -import java.util.Collection; -import java.util.HashSet; - -public class KSet extends HashSet { - private static final long serialVersionUID = 1L; - - public KSet() { - super(); - } - - public KSet(Collection c) { - super(c); - } - - public KSet(int initialCapacity, float loadFactor) { - super(initialCapacity, loadFactor); - } - - public KSet(int initialCapacity) { - super(initialCapacity); - } - - public KSet copy() { - return new KSet(this); - } -} diff --git a/src/main/java/com/volmit/iris/util/collection/KeyPair.java b/src/main/java/com/volmit/iris/util/collection/KeyPair.java deleted file mode 100644 index 536de9518..000000000 --- a/src/main/java/com/volmit/iris/util/collection/KeyPair.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.collection; - -/** - * Represents a keypair - * - * @param - * the key type - * @param - * the value type - * @author cyberpwn - */ -@SuppressWarnings("hiding") -public class KeyPair { - private K k; - private V v; - - /** - * Create a keypair - * - * @param k - * the key - * @param v - * the value - */ - public KeyPair(K k, V v) { - this.k = k; - this.v = v; - } - - public K getK() { - return k; - } - - public void setK(K k) { - this.k = k; - } - - public V getV() { - return v; - } - - public void setV(V v) { - this.v = v; - } -} diff --git a/src/main/java/com/volmit/iris/util/collection/StateList.java b/src/main/java/com/volmit/iris/util/collection/StateList.java deleted file mode 100644 index 67346951b..000000000 --- a/src/main/java/com/volmit/iris/util/collection/StateList.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.collection; - -public class StateList { - private final KList states; - - public StateList(String... states) { - this.states = new KList(states); - - if(getBits() > 64) { - throw new RuntimeException("StateLists cannot exceed 64 bits! You are trying to use " + getBits() + " bits!"); - } - } - - public StateList(Enum... states) { - this.states = new KList>().convert(Enum::name); - - if(getBits() > 64) { - throw new RuntimeException("StateLists cannot exceed 64 bits! You are trying to use " + getBits() + " bits!"); - } - } - - public long max() { - return (long) (Math.pow(2, getBits()) - 1); - } - - public KList getEnabled(long list) { - KList f = new KList<>(); - - for(String i : states) { - if(is(list, i)) { - f.add(i); - } - } - - return f; - } - - public long of(String... enabledStates) { - long b = 0; - - for(String i : enabledStates) { - b |= getBit(i); - } - - return b; - } - - public long set(long list, String state, boolean enabled) { - long bit = getBit(state); - boolean is = is(list, state); - - if(enabled && !is) { - return list | bit; - } else if(!enabled && is) { - return list ^ bit; - } - - return list; - } - - public boolean is(long list, String state) { - long bit = getBit(state); - - return bit > 0 && (list & bit) == bit; - } - - public boolean hasBit(String state) { - return getBit(state) > 0; - } - - public long getBit(String state) { - return getBit(states.indexOf(state)); - } - - public long getBit(int index) { - return (long) (index < 0 ? -1 : Math.pow(2, index)); - } - - public int getBytes() { - return getBits() == 0 ? 0 : ((getBits() >> 2) + 1); - } - - public int getBits() { - return states.size(); - } -} diff --git a/src/main/java/com/volmit/iris/util/context/IrisContext.java b/src/main/java/com/volmit/iris/util/context/IrisContext.java deleted file mode 100644 index 9173a60b7..000000000 --- a/src/main/java/com/volmit/iris/util/context/IrisContext.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.context; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.IrisComplex; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.scheduling.ChronoLatch; -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class IrisContext { - private static final KMap context = new KMap<>(); - private static ChronoLatch cl = new ChronoLatch(60000); - private final Engine engine; - - public static IrisContext get() { - return context.get(Thread.currentThread()); - } - - public static void touch(IrisContext c) { - synchronized(context) { - context.put(Thread.currentThread(), c); - - if(cl.flip()) { - dereference(); - } - } - } - - public static void dereference() { - synchronized(context) { - for(Thread i : context.k()) { - if(!i.isAlive() || context.get(i).engine.isClosed()) { - if(context.get(i).engine.isClosed()) { - Iris.debug("Dereferenced Context " + i.getName() + " " + i.getId()); - } - - context.remove(i); - } - } - } - } - - public void touch() { - IrisContext.touch(this); - } - - public IrisData getData() { - return engine.getData(); - } - - public IrisComplex getComplex() { - return engine.getComplex(); - } -} diff --git a/src/main/java/com/volmit/iris/util/data/B.java b/src/main/java/com/volmit/iris/util/data/B.java deleted file mode 100644 index 5b7ba27a7..000000000 --- a/src/main/java/com/volmit/iris/util/data/B.java +++ /dev/null @@ -1,675 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.service.ExternalDataSVC; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.scheduling.ChronoLatch; -import it.unimi.dsi.fastutil.ints.Int2IntMap; -import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; -import it.unimi.dsi.fastutil.ints.IntOpenHashSet; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.ints.IntSets; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Waterlogged; -import org.bukkit.block.data.type.Leaves; -import org.bukkit.block.data.type.PointedDripstone; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.bukkit.Material.*; - -public class B { - private static final KMap custom = new KMap<>(); - - private static final Material AIR_MATERIAL = Material.AIR; - private static final BlockData AIR = AIR_MATERIAL.createBlockData(); - private static final IntSet foliageCache = buildFoliageCache(); - private static final IntSet deepslateCache = buildDeepslateCache(); - private static final Int2IntMap normal2DeepslateCache = buildNormal2DeepslateCache(); - private static final Int2IntMap deepslate2NormalCache = buildDeepslate2NormalCache(); - private static final IntSet decorantCache = buildDecorantCache(); - private static final IntSet storageCache = buildStorageCache(); - private static final IntSet storageChestCache = buildStorageChestCache(); - private static final IntSet litCache = buildLitCache(); - private static final ChronoLatch clw = new ChronoLatch(1000); - - private static IntSet buildFoliageCache() { - IntSet b = new IntOpenHashSet(); - Arrays.stream(new Material[] { - POPPY, - DANDELION, - CORNFLOWER, - SWEET_BERRY_BUSH, - CRIMSON_ROOTS, - WARPED_ROOTS, - NETHER_SPROUTS, - ALLIUM, - AZURE_BLUET, - BLUE_ORCHID, - OXEYE_DAISY, - LILY_OF_THE_VALLEY, - WITHER_ROSE, - DARK_OAK_SAPLING, - ACACIA_SAPLING, - JUNGLE_SAPLING, - BIRCH_SAPLING, - SPRUCE_SAPLING, - OAK_SAPLING, - ORANGE_TULIP, - PINK_TULIP, - RED_TULIP, - WHITE_TULIP, - FERN, - LARGE_FERN, - GRASS, - TALL_GRASS - }).forEach((i) -> b.add(i.ordinal())); - - return IntSets.unmodifiable(b); - } - - private static IntSet buildDeepslateCache() { - IntSet b = new IntOpenHashSet(); - Arrays.stream(new Material[] { - DEEPSLATE, - DEEPSLATE_BRICKS, - DEEPSLATE_BRICK_SLAB, - DEEPSLATE_BRICK_STAIRS, - DEEPSLATE_BRICK_WALL, - DEEPSLATE_TILE_SLAB, - DEEPSLATE_TILES, - DEEPSLATE_TILE_STAIRS, - DEEPSLATE_TILE_WALL, - CRACKED_DEEPSLATE_TILES - }).forEach((i) -> b.add(i.ordinal())); - - return IntSets.unmodifiable(b); - } - - private static Int2IntMap buildNormal2DeepslateCache() { - Int2IntMap b = new Int2IntOpenHashMap(); - - b.put(COAL_ORE.ordinal(), DEEPSLATE_COAL_ORE.ordinal()); - b.put(EMERALD_ORE.ordinal(), DEEPSLATE_EMERALD_ORE.ordinal()); - b.put(DIAMOND_ORE.ordinal(), DEEPSLATE_DIAMOND_ORE.ordinal()); - b.put(COPPER_ORE.ordinal(), DEEPSLATE_COPPER_ORE.ordinal()); - b.put(GOLD_ORE.ordinal(), DEEPSLATE_GOLD_ORE.ordinal()); - b.put(IRON_ORE.ordinal(), DEEPSLATE_IRON_ORE.ordinal()); - b.put(LAPIS_ORE.ordinal(), DEEPSLATE_LAPIS_ORE.ordinal()); - b.put(REDSTONE_ORE.ordinal(), DEEPSLATE_REDSTONE_ORE.ordinal()); - - return b; - } - - private static Int2IntMap buildDeepslate2NormalCache() { - Int2IntMap b = new Int2IntOpenHashMap(); - - b.put(DEEPSLATE_COAL_ORE.ordinal(), COAL_ORE.ordinal()); - b.put(DEEPSLATE_EMERALD_ORE.ordinal(), EMERALD_ORE.ordinal()); - b.put(DEEPSLATE_DIAMOND_ORE.ordinal(), DIAMOND_ORE.ordinal()); - b.put(DEEPSLATE_COPPER_ORE.ordinal(), COPPER_ORE.ordinal()); - b.put(DEEPSLATE_GOLD_ORE.ordinal(), GOLD_ORE.ordinal()); - b.put(DEEPSLATE_IRON_ORE.ordinal(), IRON_ORE.ordinal()); - b.put(DEEPSLATE_LAPIS_ORE.ordinal(), LAPIS_ORE.ordinal()); - b.put(DEEPSLATE_REDSTONE_ORE.ordinal(), REDSTONE_ORE.ordinal()); - - return b; - } - - private static IntSet buildDecorantCache() { - IntSet b = new IntOpenHashSet(); - Arrays.stream(new Material[] { - GRASS, - TALL_GRASS, - FERN, - LARGE_FERN, - CORNFLOWER, - SUNFLOWER, - CHORUS_FLOWER, - POPPY, - DANDELION, - OXEYE_DAISY, - ORANGE_TULIP, - PINK_TULIP, - RED_TULIP, - WHITE_TULIP, - LILAC, - DEAD_BUSH, - SWEET_BERRY_BUSH, - ROSE_BUSH, - WITHER_ROSE, - ALLIUM, - BLUE_ORCHID, - LILY_OF_THE_VALLEY, - CRIMSON_FUNGUS, - WARPED_FUNGUS, - RED_MUSHROOM, - BROWN_MUSHROOM, - CRIMSON_ROOTS, - AZURE_BLUET, - WEEPING_VINES, - WEEPING_VINES_PLANT, - WARPED_ROOTS, - NETHER_SPROUTS, - TWISTING_VINES, - TWISTING_VINES_PLANT, - SUGAR_CANE, - WHEAT, - POTATOES, - CARROTS, - BEETROOTS, - NETHER_WART, - SEA_PICKLE, - SEAGRASS, - ACACIA_BUTTON, - BIRCH_BUTTON, - CRIMSON_BUTTON, - DARK_OAK_BUTTON, - JUNGLE_BUTTON, - OAK_BUTTON, - POLISHED_BLACKSTONE_BUTTON, - SPRUCE_BUTTON, - STONE_BUTTON, - WARPED_BUTTON, - TORCH, - SOUL_TORCH - }).forEach((i) -> b.add(i.ordinal())); - b.addAll(foliageCache); - - return IntSets.unmodifiable(b); - } - - private static IntSet buildLitCache() { - IntSet b = new IntOpenHashSet(); - Arrays.stream(new Material[] { - GLOWSTONE, - AMETHYST_CLUSTER, - SMALL_AMETHYST_BUD, - MEDIUM_AMETHYST_BUD, - LARGE_AMETHYST_BUD, - END_ROD, - SOUL_SAND, - TORCH, - REDSTONE_TORCH, - SOUL_TORCH, - REDSTONE_WALL_TORCH, - WALL_TORCH, - SOUL_WALL_TORCH, - LANTERN, - CANDLE, - JACK_O_LANTERN, - REDSTONE_LAMP, - MAGMA_BLOCK, - LIGHT, - SHROOMLIGHT, - SEA_LANTERN, - SOUL_LANTERN, - FIRE, - SOUL_FIRE, - SEA_PICKLE, - BREWING_STAND, - REDSTONE_ORE, - }).forEach((i) -> b.add(i.ordinal())); - - return IntSets.unmodifiable(b); - } - - private static IntSet buildStorageCache() { - IntSet b = new IntOpenHashSet(); - Arrays.stream(new Material[] { - CHEST, - SMOKER, - TRAPPED_CHEST, - SHULKER_BOX, - WHITE_SHULKER_BOX, - ORANGE_SHULKER_BOX, - MAGENTA_SHULKER_BOX, - LIGHT_BLUE_SHULKER_BOX, - YELLOW_SHULKER_BOX, - LIME_SHULKER_BOX, - PINK_SHULKER_BOX, - GRAY_SHULKER_BOX, - LIGHT_GRAY_SHULKER_BOX, - CYAN_SHULKER_BOX, - PURPLE_SHULKER_BOX, - BLUE_SHULKER_BOX, - BROWN_SHULKER_BOX, - GREEN_SHULKER_BOX, - RED_SHULKER_BOX, - BLACK_SHULKER_BOX, - BARREL, - DISPENSER, - DROPPER, - HOPPER, - FURNACE, - BLAST_FURNACE - }).forEach((i) -> b.add(i.ordinal())); - - return IntSets.unmodifiable(b); - } - - public static BlockData toDeepSlateOre(BlockData block, BlockData ore) { - int key = ore.getMaterial().ordinal(); - - if(isDeepSlate(block)) { - if(normal2DeepslateCache.containsKey(key)) { - return Material.values()[normal2DeepslateCache.get(key)].createBlockData(); - } - } else { - if(deepslate2NormalCache.containsKey(key)) { - return Material.values()[deepslate2NormalCache.get(key)].createBlockData(); - } - } - - return ore; - } - - public static boolean isDeepSlate(BlockData blockData) { - return deepslateCache.contains(blockData.getMaterial().ordinal()); - } - - public static boolean isOre(BlockData blockData) { - return blockData.getMaterial().name().endsWith("_ORE"); - } - - private static IntSet buildStorageChestCache() { - IntSet b = new IntOpenHashSet(storageCache); - b.remove(SMOKER.ordinal()); - b.remove(FURNACE.ordinal()); - b.remove(BLAST_FURNACE.ordinal()); - - return IntSets.unmodifiable(b); - } - - public static boolean canPlaceOnto(Material mat, Material onto) { - if((onto.equals(CRIMSON_NYLIUM) || onto.equals(WARPED_NYLIUM)) && - (mat.equals(CRIMSON_FUNGUS) || mat.equals(CRIMSON_ROOTS) || mat.equals(WARPED_FUNGUS) || mat.equals(WARPED_ROOTS))) { - return true; - } - - if(isFoliage(mat)) { - if(!isFoliagePlantable(onto)) { - return false; - } - } - - if(onto.equals(Material.AIR) || - onto.equals(B.getMaterial("CAVE_AIR")) - || onto.equals(B.getMaterial("VOID_AIR"))) { - return false; - } - - if(onto.equals(Material.GRASS_BLOCK) && mat.equals(Material.DEAD_BUSH)) { - return false; - } - - if(onto.equals(Material.DIRT_PATH)) { - if(!mat.isSolid()) { - return false; - } - } - - if(onto.equals(Material.ACACIA_LEAVES) - || onto.equals(Material.BIRCH_LEAVES) - || onto.equals(Material.DARK_OAK_LEAVES) - || onto.equals(Material.JUNGLE_LEAVES) - || onto.equals(Material.OAK_LEAVES) - || onto.equals(Material.SPRUCE_LEAVES)) { - return mat.isSolid(); - } - - return true; - } - - public static boolean isFoliagePlantable(BlockData d) { - return d.getMaterial().equals(Material.GRASS_BLOCK) - || d.getMaterial().equals(Material.ROOTED_DIRT) - || d.getMaterial().equals(Material.DIRT) - || d.getMaterial().equals(Material.COARSE_DIRT) - || d.getMaterial().equals(Material.PODZOL); - } - - public static boolean isFoliagePlantable(Material d) { - return d.equals(Material.GRASS_BLOCK) - || d.equals(Material.DIRT) - || d.equals(TALL_GRASS) - || d.equals(TALL_SEAGRASS) - || d.equals(LARGE_FERN) - || d.equals(SUNFLOWER) - || d.equals(PEONY) - || d.equals(LILAC) - || d.equals(ROSE_BUSH) - || d.equals(Material.ROOTED_DIRT) - || d.equals(Material.COARSE_DIRT) - || d.equals(Material.PODZOL); - } - - public static boolean isWater(BlockData b) { - return b.getMaterial().equals(Material.WATER); - } - - public static BlockData getAir() { - return AIR; - } - - public static Material getMaterialOrNull(String bdx) { - try { - return Material.valueOf(bdx.trim().toUpperCase()); - } catch(Throwable e) { - Iris.reportError(e); - if(clw.flip()) { - Iris.warn("Unknown Material: " + bdx); - } - return null; - } - } - - public static Material getMaterial(String bdx) { - Material m = getMaterialOrNull(bdx); - - if(m == null) { - return AIR_MATERIAL; - } - - return m; - } - - public static boolean isSolid(BlockData mat) { - return mat.getMaterial().isSolid(); - } - - public static BlockData getOrNull(String bdxf) { - try { - String bd = bdxf.trim(); - - if(!custom.isEmpty() && custom.containsKey(bd)) - { - return custom.get(bd); - } - - if(bd.startsWith("minecraft:cauldron[level=")) { - bd = bd.replaceAll("\\Q:cauldron[\\E", ":water_cauldron["); - } - - if(bd.equals("minecraft:grass_path")) { - return DIRT_PATH.createBlockData(); - } - - BlockData bdx = parseBlockData(bd); - - if(bdx == null) { - if(clw.flip()) { - Iris.warn("Unknown Block Data '" + bd + "'"); - } - return AIR; - } - - return bdx; - } catch(Throwable e) { - Iris.reportError(e); - - if(clw.flip()) { - Iris.warn("Unknown Block Data '" + bdxf + "'"); - } - } - - return null; - } - - public static BlockData get(String bdxf) { - BlockData bd = getOrNull(bdxf); - - if(bd != null) { - return bd; - } - - return AIR; - } - - private static synchronized BlockData createBlockData(String s) { - try { - return Bukkit.createBlockData(s); - } catch(IllegalArgumentException e) { - if(s.contains("[")) { - return createBlockData(s.split("\\Q[\\E")[0]); - } - } - - Iris.error("Can't find block data for " + s); - return null; - } - - private static BlockData parseBlockData(String ix) { - try { - BlockData bx = null; - - if(!ix.startsWith("minecraft:") && ix.contains(":")) { - NamespacedKey key = NamespacedKey.fromString(ix); - Optional bd = Iris.service(ExternalDataSVC.class).getBlockData(key); - if(bd.isPresent()) - bx = bd.get(); - } - - if(bx == null) { - try { - bx = createBlockData(ix.toLowerCase()); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - if(bx == null) { - try { - bx = createBlockData("minecraft:" + ix.toLowerCase()); - } catch(Throwable e) { - - } - } - - if(bx == null) { - try { - bx = Material.valueOf(ix.toUpperCase()).createBlockData(); - } catch(Throwable e) { - - } - } - - if(bx == null) { - return null; - } - - if(bx instanceof Leaves && IrisSettings.get().getGenerator().isPreventLeafDecay()) { - ((Leaves) bx).setPersistent(true); - } else if(bx instanceof Leaves) { - ((Leaves) bx).setPersistent(false); - } - - return bx; - } catch(Throwable e) { - if(clw.flip()) { - Iris.warn("Unknown Block Data: " + ix); - } - - String block = ix.contains(":") ? ix.split(":")[1].toLowerCase() : ix.toLowerCase(); - String state = block.contains("[") ? block.split("\\Q[\\E")[1].split("\\Q]\\E")[0] : ""; - Map stateMap = new HashMap<>(); - if(!state.equals("")) { - Arrays.stream(state.split(",")).forEach(s -> stateMap.put(s.split("=")[0], s.split("=")[1])); - } - block = block.split("\\Q[\\E")[0]; - - switch(block) { - case "cauldron" -> block = "water_cauldron"; - case "grass_path" -> block = "dirt_path"; - case "concrete" -> block = "white_concrete"; - case "wool" -> block = "white_wool"; - case "beetroots" -> { - if(stateMap.containsKey("age")) { - String updated = stateMap.get("age"); - switch(updated) { - case "7" -> updated = "3"; - case "3", "4", "5" -> updated = "2"; - case "1", "2" -> updated = "1"; - } - stateMap.put("age", updated); - } - } - } - - Map newStates = new HashMap<>(); - for(String key : stateMap.keySet()) { //Iterate through every state and check if its valid - try { - String newState = block + "[" + key + "=" + stateMap.get(key) + "]"; - createBlockData(newState); - newStates.put(key, stateMap.get(key)); - - } catch(IllegalArgumentException ignored) { - } - } - - //Combine all the "good" states again - state = newStates.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining(",")); - if(!state.equals("")) state = "[" + state + "]"; - String newBlock = block + state; - Iris.debug("Converting " + ix + " to " + newBlock); - - try { - return createBlockData(newBlock); - } catch(Throwable e1) { - Iris.reportError(e1); - } - - return null; - } - } - - public static boolean isStorage(BlockData mat) { - return storageCache.contains(mat.getMaterial().ordinal()); - } - - public static boolean isStorageChest(BlockData mat) { - return storageChestCache.contains(mat.getMaterial().ordinal()); - } - - public static boolean isLit(BlockData mat) { - return litCache.contains(mat.getMaterial().ordinal()); - } - - public static boolean isUpdatable(BlockData mat) { - return isLit(mat) - || isStorage(mat) - || (mat instanceof PointedDripstone - && ((PointedDripstone) mat).getThickness().equals(PointedDripstone.Thickness.TIP)); - } - - public static boolean isFoliage(Material d) { - return foliageCache.contains(d.ordinal()); - } - - public static boolean isFoliage(BlockData d) { - return isFoliage(d.getMaterial()); - } - - public static boolean isDecorant(BlockData m) { - return decorantCache.contains(m.getMaterial().ordinal()); - } - - public static KList get(KList find) { - KList b = new KList<>(); - - for(String i : find) { - BlockData bd = get(i); - - if(bd != null) { - b.add(bd); - } - } - - return b; - } - - public static boolean isFluid(BlockData d) { - return d.getMaterial().equals(Material.WATER) || d.getMaterial().equals(Material.LAVA); - } - - public static boolean isAirOrFluid(BlockData d) { - return isAir(d) || isFluid(d); - } - - public static boolean isAir(BlockData d) { - if(d == null) { - return true; - } - - return d.getMaterial().equals(Material.AIR) || d.getMaterial().equals(Material.CAVE_AIR) || d.getMaterial().equals(Material.VOID_AIR); - } - - - public synchronized static String[] getBlockTypes() { - KList bt = new KList<>(); - - for(Material i : Material.values()) { - if(i.isBlock()) { - String v = i.createBlockData().getAsString(true); - - if(v.contains("[")) { - v = v.split("\\Q[\\E")[0]; - } - - bt.add(v); - } - } - - for(NamespacedKey id : Iris.service(ExternalDataSVC.class).getAllIdentifiers()) - bt.add(id.toString()); - bt.addAll(custom.k()); - - return bt.toArray(new String[0]); - } - - public static String[] getItemTypes() { - KList bt = new KList<>(); - - for(Material i : Material.values()) { - String v = i.name().toLowerCase().trim(); - bt.add(v); - } - - return bt.toArray(new String[0]); - } - - public static boolean isWaterLogged(BlockData b) { - return (b instanceof Waterlogged) && ((Waterlogged) b).isWaterlogged(); - } - - public static void registerCustomBlockData(String namespace, String key, BlockData blockData) { - custom.put(namespace + ":" + key, blockData); - } -} diff --git a/src/main/java/com/volmit/iris/util/data/BiomeMap.java b/src/main/java/com/volmit/iris/util/data/BiomeMap.java deleted file mode 100644 index 1e39447fe..000000000 --- a/src/main/java/com/volmit/iris/util/data/BiomeMap.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.engine.object.IrisBiome; - -public class BiomeMap { - private final IrisBiome[] height; - - public BiomeMap() { - height = new IrisBiome[256]; - } - - public void setBiome(int x, int z, IrisBiome h) { - height[x * 16 + z] = h; - } - - public IrisBiome getBiome(int x, int z) { - return height[x * 16 + z]; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/ChunkCache.java b/src/main/java/com/volmit/iris/util/data/ChunkCache.java deleted file mode 100644 index 0ce831cc8..000000000 --- a/src/main/java/com/volmit/iris/util/data/ChunkCache.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.util.function.Function2; - -import java.util.concurrent.atomic.AtomicReferenceArray; - -public class ChunkCache { - private final AtomicReferenceArray cache; - - public ChunkCache() { - cache = new AtomicReferenceArray<>(256); - } - - public T compute(int x, int z, Function2 function) { - T t = get(x & 15, z & 15); - - if(t == null) { - t = function.apply(x, z); - set(x & 15, z & 15, t); - } - - return t; - } - - private void set(int x, int z, T t) { - cache.set(x * 16 + z, t); - } - - private T get(int x, int z) { - return cache.get(x * 16 + z); - } -} diff --git a/src/main/java/com/volmit/iris/util/data/ComplexCache.java b/src/main/java/com/volmit/iris/util/data/ComplexCache.java deleted file mode 100644 index 8478db011..000000000 --- a/src/main/java/com/volmit/iris/util/data/ComplexCache.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.util.collection.KMap; - -public class ComplexCache { - private final KMap> chunks; - - public ComplexCache() { - chunks = new KMap<>(); - } - - public boolean has(int x, int z) { - return chunks.containsKey(Cache.key(x, z)); - } - - public void invalidate(int x, int z) { - chunks.remove(Cache.key(x, z)); - } - - public ChunkCache chunk(int x, int z) { - return chunks.computeIfAbsent(Cache.key(x, z), (f) -> new ChunkCache<>()); - } -} diff --git a/src/main/java/com/volmit/iris/util/data/Cuboid.java b/src/main/java/com/volmit/iris/util/data/Cuboid.java deleted file mode 100644 index a2ade169c..000000000 --- a/src/main/java/com/volmit/iris/util/data/Cuboid.java +++ /dev/null @@ -1,801 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.Direction; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.entity.Entity; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * Cuboids - * - * @author cyberpwn - */ -public class Cuboid implements Iterable, Cloneable, ConfigurationSerializable { - protected final String worldName; - protected int x1, y1, z1; - protected int x2, y2, z2; - - /** - * Construct a Cuboid given two Location objects which represent any two corners - * of the Cuboid. - * - * @param l1 - * one of the corners - * @param l2 - * the other corner - */ - public Cuboid(Location l1, Location l2) { - if(!l1.getWorld().equals(l2.getWorld())) { - throw new IllegalArgumentException("locations must be on the same world"); - } - - worldName = l1.getWorld().getName(); - x1 = Math.min(l1.getBlockX(), l2.getBlockX()); - y1 = Math.min(l1.getBlockY(), l2.getBlockY()); - z1 = Math.min(l1.getBlockZ(), l2.getBlockZ()); - x2 = Math.max(l1.getBlockX(), l2.getBlockX()); - y2 = Math.max(l1.getBlockY(), l2.getBlockY()); - z2 = Math.max(l1.getBlockZ(), l2.getBlockZ()); - } - - /** - * Construct a one-block Cuboid at the given Location of the Cuboid. - * - * @param l1 - * location of the Cuboid - */ - public Cuboid(Location l1) { - this(l1, l1); - } - - /** - * Copy constructor. - * - * @param other - * the Cuboid to copy - */ - public Cuboid(Cuboid other) { - this(other.getWorld().getName(), other.x1, other.y1, other.z1, other.x2, other.y2, other.z2); - } - - /** - * Construct a Cuboid in the given World and xyz co-ordinates - * - * @param world - * the Cuboid's world - * @param x1 - * X co-ordinate of corner 1 - * @param y1 - * Y co-ordinate of corner 1 - * @param z1 - * Z co-ordinate of corner 1 - * @param x2 - * X co-ordinate of corner 2 - * @param y2 - * Y co-ordinate of corner 2 - * @param z2 - * Z co-ordinate of corner 2 - */ - public Cuboid(World world, int x1, int y1, int z1, int x2, int y2, int z2) { - this.worldName = world.getName(); - this.x1 = Math.min(x1, x2); - this.x2 = Math.max(x1, x2); - this.y1 = Math.min(y1, y2); - this.y2 = Math.max(y1, y2); - this.z1 = Math.min(z1, z2); - this.z2 = Math.max(z1, z2); - } - - /** - * Construct a Cuboid in the given world name and xyz co-ordinates. - * - * @param worldName - * the Cuboid's world name - * @param x1 - * X co-ordinate of corner 1 - * @param y1 - * Y co-ordinate of corner 1 - * @param z1 - * Z co-ordinate of corner 1 - * @param x2 - * X co-ordinate of corner 2 - * @param y2 - * Y co-ordinate of corner 2 - * @param z2 - * Z co-ordinate of corner 2 - */ - private Cuboid(String worldName, int x1, int y1, int z1, int x2, int y2, int z2) { - this.worldName = worldName; - this.x1 = Math.min(x1, x2); - this.x2 = Math.max(x1, x2); - this.y1 = Math.min(y1, y2); - this.y2 = Math.max(y1, y2); - this.z1 = Math.min(z1, z2); - this.z2 = Math.max(z1, z2); - } - - public Cuboid(Map map) { - worldName = (String) map.get("worldName"); - x1 = (Integer) map.get("x1"); - x2 = (Integer) map.get("x2"); - y1 = (Integer) map.get("y1"); - y2 = (Integer) map.get("y2"); - z1 = (Integer) map.get("z1"); - z2 = (Integer) map.get("z2"); - } - - public KList getEntities() { - KList en = new KList<>(); - - for(Chunk i : getChunks()) { - for(Entity j : i.getEntities()) { - if(contains(j.getLocation())) { - en.add(j); - } - } - } - - return en; - } - - /** - * Set the locations - * - * @param l1 - * a - * @param l2 - * b - */ - public void set(Location l1, Location l2) { - x1 = Math.min(l1.getBlockX(), l2.getBlockX()); - y1 = Math.min(l1.getBlockY(), l2.getBlockY()); - z1 = Math.min(l1.getBlockZ(), l2.getBlockZ()); - x2 = Math.max(l1.getBlockX(), l2.getBlockX()); - y2 = Math.max(l1.getBlockY(), l2.getBlockY()); - z2 = Math.max(l1.getBlockZ(), l2.getBlockZ()); - } - - @Override - public Map serialize() { - Map map = new HashMap<>(); - map.put("worldName", worldName); - map.put("x1", x1); - map.put("y1", y1); - map.put("z1", z1); - map.put("x2", x2); - map.put("y2", y2); - map.put("z2", z2); - return map; - } - - public Cuboid flatten(int level) { - return new Cuboid(getWorld(), x1, level, z1, x2, level, z2); - } - - /** - * Get the Location of the lower northeast corner of the Cuboid (minimum XYZ - * co-ordinates). - * - * @return Location of the lower northeast corner - */ - public Location getLowerNE() { - return new Location(getWorld(), x1, y1, z1); - } - - /** - * Get the Location of the upper southwest corner of the Cuboid (maximum XYZ - * co-ordinates). - * - * @return Location of the upper southwest corner - */ - public Location getUpperSW() { - return new Location(getWorld(), x2, y2, z2); - } - - /** - * Get the the centre of the Cuboid - * - * @return Location at the centre of the Cuboid - */ - public Location getCenter() { - int x1 = getUpperX() + 1; - int y1 = getUpperY() + 1; - int z1 = getUpperZ() + 1; - return new Location(getWorld(), getLowerX() + (x1 - getLowerX()) / 2.0, getLowerY() + (y1 - getLowerY()) / 2.0, getLowerZ() + (z1 - getLowerZ()) / 2.0); - } - - /** - * Get the Cuboid's world. - * - * @return the World object representing this Cuboid's world - * @throws IllegalStateException - * if the world is not loaded - */ - public World getWorld() { - World world = Bukkit.getWorld(worldName); - if(world == null) { - throw new IllegalStateException("world '" + worldName + "' is not loaded"); - } - return world; - } - - /** - * Get the size of this Cuboid along the X axis - * - * @return Size of Cuboid along the X axis - */ - public int getSizeX() { - return (x2 - x1) + 1; - } - - /** - * Get the size of this Cuboid along the Y axis - * - * @return Size of Cuboid along the Y axis - */ - public int getSizeY() { - return (y2 - y1) + 1; - } - - /** - * Get the size of this Cuboid along the Z axis - * - * @return Size of Cuboid along the Z axis - */ - public int getSizeZ() { - return (z2 - z1) + 1; - } - - /** - * Get the cuboid dimensions - * - * @return the dimensions - */ - public Dimension getDimension() { - return new Dimension(getSizeX(), getSizeY(), getSizeZ()); - } - - /** - * Get the minimum X co-ordinate of this Cuboid - * - * @return the minimum X co-ordinate - */ - public int getLowerX() { - return x1; - } - - /** - * Get the minimum Y co-ordinate of this Cuboid - * - * @return the minimum Y co-ordinate - */ - public int getLowerY() { - return y1; - } - - /** - * Get the minimum Z co-ordinate of this Cuboid - * - * @return the minimum Z co-ordinate - */ - public int getLowerZ() { - return z1; - } - - /** - * Get the maximum X co-ordinate of this Cuboid - * - * @return the maximum X co-ordinate - */ - public int getUpperX() { - return x2; - } - - /** - * Get the maximum Y co-ordinate of this Cuboid - * - * @return the maximum Y co-ordinate - */ - public int getUpperY() { - return y2; - } - - /** - * Get the maximum Z co-ordinate of this Cuboid - * - * @return the maximum Z co-ordinate - */ - public int getUpperZ() { - return z2; - } - - /** - * Get the Blocks at the eight corners of the Cuboid. - * - * @return array of Block objects representing the Cuboid corners - */ - public Block[] corners() { - Block[] res = new Block[8]; - World w = getWorld(); - res[0] = w.getBlockAt(x1, y1, z1); - res[1] = w.getBlockAt(x1, y1, z2); - res[2] = w.getBlockAt(x1, y2, z1); - res[3] = w.getBlockAt(x1, y2, z2); - res[4] = w.getBlockAt(x2, y1, z1); - res[5] = w.getBlockAt(x2, y1, z2); - res[6] = w.getBlockAt(x2, y2, z1); - res[7] = w.getBlockAt(x2, y2, z2); - return res; - } - - /** - * Expand the Cuboid in the given direction by the given amount. Negative - * amounts will shrink the Cuboid in the given direction. Shrinking a cuboid's - * face past the opposite face is not an error and will return a valid Cuboid. - * - * @param dir - * the direction in which to expand - * @param amount - * the number of blocks by which to expand - * @return a new Cuboid expanded by the given direction and amount - */ - public Cuboid expand(CuboidDirection dir, int amount) { - return switch(dir) { - case North -> new Cuboid(worldName, x1 - amount, y1, z1, x2, y2, z2); - case South -> new Cuboid(worldName, x1, y1, z1, x2 + amount, y2, z2); - case East -> new Cuboid(worldName, x1, y1, z1 - amount, x2, y2, z2); - case West -> new Cuboid(worldName, x1, y1, z1, x2, y2, z2 + amount); - case Down -> new Cuboid(worldName, x1, y1 - amount, z1, x2, y2, z2); - case Up -> new Cuboid(worldName, x1, y1, z1, x2, y2 + amount, z2); - default -> throw new IllegalArgumentException("invalid direction " + dir); - }; - } - - public Cuboid expand(Direction dir, int amount) { - int ax = dir.toVector().getBlockX() == 1 ? amount : 0; - int sx = dir.toVector().getBlockX() == -1 ? -amount : 0; - int ay = dir.toVector().getBlockY() == 1 ? amount : 0; - int sy = dir.toVector().getBlockY() == -1 ? -amount : 0; - int az = dir.toVector().getBlockZ() == 1 ? amount : 0; - int sz = dir.toVector().getBlockZ() == -1 ? -amount : 0; - return new Cuboid(worldName, x1 + sx, y1 + sy, z1 + sz, x2 + ax, y2 + ay, z2 + az); - } - - /** - * Shift the Cuboid in the given direction by the given amount. - * - * @param dir - * the direction in which to shift - * @param amount - * the number of blocks by which to shift - * @return a new Cuboid shifted by the given direction and amount - */ - public Cuboid shift(CuboidDirection dir, int amount) { - return expand(dir, amount).expand(dir.opposite(), -amount); - } - - /** - * Outset (grow) the Cuboid in the given direction by the given amount. - * - * @param dir - * the direction in which to outset (must be Horizontal, Vertical, or - * Both) - * @param amount - * the number of blocks by which to outset - * @return a new Cuboid outset by the given direction and amount - */ - public Cuboid outset(CuboidDirection dir, int amount) { - Cuboid c = switch(dir) { - case Horizontal -> expand(CuboidDirection.North, amount).expand(CuboidDirection.South, amount).expand(CuboidDirection.East, amount).expand(CuboidDirection.West, amount); - case Vertical -> expand(CuboidDirection.Down, amount).expand(CuboidDirection.Up, amount); - case Both -> outset(CuboidDirection.Horizontal, amount).outset(CuboidDirection.Vertical, amount); - default -> throw new IllegalArgumentException("invalid direction " + dir); - }; - return c; - } - - /** - * Inset (shrink) the Cuboid in the given direction by the given amount. - * Equivalent to calling outset() with a negative amount. - * - * @param dir - * the direction in which to inset (must be Horizontal, Vertical, or - * Both) - * @param amount - * the number of blocks by which to inset - * @return a new Cuboid inset by the given direction and amount - */ - public Cuboid inset(CuboidDirection dir, int amount) { - return outset(dir, -amount); - } - - /** - * Return true if the point at (x,y,z) is contained within this Cuboid. - * - * @param x - * the X co-ordinate - * @param y - * the Y co-ordinate - * @param z - * the Z co-ordinate - * @return true if the given point is within this Cuboid, false otherwise - */ - public boolean contains(int x, int y, int z) { - return x >= x1 && x <= x2 && y >= y1 && y <= y2 && z >= z1 && z <= z2; - } - - /** - * Check if the given Block is contained within this Cuboid. - * - * @param b - * the Block to check for - * @return true if the Block is within this Cuboid, false otherwise - */ - public boolean contains(Block b) { - return contains(b.getLocation()); - } - - /** - * Check if the given Location is contained within this Cuboid. - * - * @param l - * the Location to check for - * @return true if the Location is within this Cuboid, false otherwise - */ - public boolean contains(Location l) { - return worldName.equals(l.getWorld().getName()) && contains(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - } - - /** - * Get the volume of this Cuboid. - * - * @return the Cuboid volume, in blocks - */ - public int volume() { - return getSizeX() * getSizeY() * getSizeZ(); - } - - /** - * Get the average light level of all empty (air) blocks in the Cuboid. Returns - * 0 if there are no empty blocks. - * - * @return the average light level of this Cuboid - */ - public byte averageLightLevel() { - long total = 0; - int n = 0; - for(Block b : this) { - if(b.isEmpty()) { - total += b.getLightLevel(); - ++n; - } - } - return n > 0 ? (byte) (total / n) : 0; - } - - /** - * Contract the Cuboid, returning a Cuboid with any air around the edges - * removed, just large enough to include all non-air blocks. - * - * @return a new Cuboid with no external air blocks - */ - public Cuboid contract() { - return this.contract(CuboidDirection.Down).contract(CuboidDirection.South).contract(CuboidDirection.East).contract(CuboidDirection.Up).contract(CuboidDirection.North).contract(CuboidDirection.West); - } - - /** - * Contract the Cuboid in the given direction, returning a new Cuboid which has - * no exterior empty space. E.g. a direction of Down will push the top face - * downwards as much as possible. - * - * @param dir - * the direction in which to contract - * @return a new Cuboid contracted in the given direction - */ - public Cuboid contract(CuboidDirection dir) { - Cuboid face = getFace(dir.opposite()); - switch(dir) { - case Down -> { - while(face.containsOnly(Material.AIR) && face.getLowerY() > this.getLowerY()) { - face = face.shift(CuboidDirection.Down, 1); - } - return new Cuboid(worldName, x1, y1, z1, x2, face.getUpperY(), z2); - } - case Up -> { - while(face.containsOnly(Material.AIR) && face.getUpperY() < this.getUpperY()) { - face = face.shift(CuboidDirection.Up, 1); - } - return new Cuboid(worldName, x1, face.getLowerY(), z1, x2, y2, z2); - } - case North -> { - while(face.containsOnly(Material.AIR) && face.getLowerX() > this.getLowerX()) { - face = face.shift(CuboidDirection.North, 1); - } - return new Cuboid(worldName, x1, y1, z1, face.getUpperX(), y2, z2); - } - case South -> { - while(face.containsOnly(Material.AIR) && face.getUpperX() < this.getUpperX()) { - face = face.shift(CuboidDirection.South, 1); - } - return new Cuboid(worldName, face.getLowerX(), y1, z1, x2, y2, z2); - } - case East -> { - while(face.containsOnly(Material.AIR) && face.getLowerZ() > this.getLowerZ()) { - face = face.shift(CuboidDirection.East, 1); - } - return new Cuboid(worldName, x1, y1, z1, x2, y2, face.getUpperZ()); - } - case West -> { - while(face.containsOnly(Material.AIR) && face.getUpperZ() < this.getUpperZ()) { - face = face.shift(CuboidDirection.West, 1); - } - return new Cuboid(worldName, x1, y1, face.getLowerZ(), x2, y2, z2); - } - default -> throw new IllegalArgumentException("Invalid direction " + dir); - } - } - - /** - * Get the Cuboid representing the face of this Cuboid. The resulting Cuboid - * will be one block thick in the axis perpendicular to the requested face. - * - * @param dir - * which face of the Cuboid to get - * @return the Cuboid representing this Cuboid's requested face - */ - public Cuboid getFace(CuboidDirection dir) { - return switch(dir) { - case Down -> new Cuboid(worldName, x1, y1, z1, x2, y1, z2); - case Up -> new Cuboid(worldName, x1, y2, z1, x2, y2, z2); - case North -> new Cuboid(worldName, x1, y1, z1, x1, y2, z2); - case South -> new Cuboid(worldName, x2, y1, z1, x2, y2, z2); - case East -> new Cuboid(worldName, x1, y1, z1, x2, y2, z1); - case West -> new Cuboid(worldName, x1, y1, z2, x2, y2, z2); - default -> throw new IllegalArgumentException("Invalid direction " + dir); - }; - } - - /** - * Check if the Cuboid contains only blocks of the given type - * - * @param material - * the material to check for - * @return true if this Cuboid contains only blocks of the given type - */ - public boolean containsOnly(Material material) { - for(Block b : this) { - if(b.getType() != material) { - return false; - } - } - return true; - } - - /** - * Get the Cuboid big enough to hold both this Cuboid and the given one. - * - * @param other - * the other Cuboid to include - * @return a new Cuboid large enough to hold this Cuboid and the given Cuboid - */ - public Cuboid getBoundingCuboid(Cuboid other) { - if(other == null) { - return this; - } - - int xMin = Math.min(getLowerX(), other.getLowerX()); - int yMin = Math.min(getLowerY(), other.getLowerY()); - int zMin = Math.min(getLowerZ(), other.getLowerZ()); - int xMax = Math.max(getUpperX(), other.getUpperX()); - int yMax = Math.max(getUpperY(), other.getUpperY()); - int zMax = Math.max(getUpperZ(), other.getUpperZ()); - - return new Cuboid(worldName, xMin, yMin, zMin, xMax, yMax, zMax); - } - - /** - * Get a block relative to the lower NE point of the Cuboid. - * - * @param x - * the X co-ordinate - * @param y - * the Y co-ordinate - * @param z - * the Z co-ordinate - * @return the block at the given position - */ - public Block getRelativeBlock(int x, int y, int z) { - return getWorld().getBlockAt(x1 + x, y1 + y, z1 + z); - } - - /** - * Get a block relative to the lower NE point of the Cuboid in the given World. - * This version of getRelativeBlock() should be used if being called many times, - * to avoid excessive calls to getWorld(). - * - * @param w - * the World - * @param x - * the X co-ordinate - * @param y - * the Y co-ordinate - * @param z - * the Z co-ordinate - * @return the block at the given position - */ - public Block getRelativeBlock(World w, int x, int y, int z) { - return w.getBlockAt(x1 + x, y1 + y, z1 + z); - } - - /** - * Get a list of the chunks which are fully or partially contained in this - * cuboid. - * - * @return a list of Chunk objects - */ - public List getChunks() { - List res = new ArrayList<>(); - - World w = getWorld(); - int x1 = getLowerX() & ~0xf; - int x2 = getUpperX() & ~0xf; - int z1 = getLowerZ() & ~0xf; - int z2 = getUpperZ() & ~0xf; - for(int x = x1; x <= x2; x += 16) { - for(int z = z1; z <= z2; z += 16) { - res.add(w.getChunkAt(x >> 4, z >> 4)); - } - } - return res; - } - - /* - Set all the blocks within the Cuboid to the given MaterialData, using a - MassBlockUpdate object for fast updates. - - @param mat - * the MaterialData to set - * @param mbu - * the MassBlockUpdate object - */ - - /** - * Reset the light level of all blocks within this Cuboid. - */ - - /* - * (non-Javadoc) - * - * @see java.lang.Iterable#iterator() - */ - @Override - public Iterator iterator() { - return new CuboidIterator(getWorld(), x1, y1, z1, x2, y2, z2); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#clone() - */ - @SuppressWarnings("MethodDoesntCallSuperMethod") - @Override - public Cuboid clone() { - return new Cuboid(this); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Cuboid: " + worldName + "," + x1 + "," + y1 + "," + z1 + "=>" + x2 + "," + y2 + "," + z2; - } - - public enum CuboidDirection { - - North, - East, - South, - West, - Up, - Down, - Horizontal, - Vertical, - Both, - Unknown; - - public CuboidDirection opposite() { - return switch(this) { - case North -> South; - case East -> West; - case South -> North; - case West -> East; - case Horizontal -> Vertical; - case Vertical -> Horizontal; - case Up -> Down; - case Down -> Up; - case Both -> Both; - default -> Unknown; - }; - } - } - - public static class CuboidIterator implements Iterator { - private final World w; - private final int baseX; - private final int baseY; - private final int baseZ; - private final int sizeX; - private final int sizeY; - private final int sizeZ; - private int x, y, z; - - public CuboidIterator(World w, int x1, int y1, int z1, int x2, int y2, int z2) { - this.w = w; - baseX = x1; - baseY = y1; - baseZ = z1; - sizeX = Math.abs(x2 - x1) + 1; - sizeY = Math.abs(y2 - y1) + 1; - sizeZ = Math.abs(z2 - z1) + 1; - x = y = z = 0; - } - - @Override - public boolean hasNext() { - return x < sizeX && y < sizeY && z < sizeZ; - } - - @Override - public Block next() { - Block b = w.getBlockAt(baseX + x, baseY + y, baseZ + z); - if(++x >= sizeX) { - x = 0; - if(++y >= sizeY) { - y = 0; - ++z; - } - } - return b; - } - - @Override - public void remove() { - // nop - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/CuboidException.java b/src/main/java/com/volmit/iris/util/data/CuboidException.java deleted file mode 100644 index 990cefd45..000000000 --- a/src/main/java/com/volmit/iris/util/data/CuboidException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -/** - * Represents a cuboid exception - * - * @author cyberpwn - */ -public class CuboidException extends Exception { - private static final long serialVersionUID = 1L; - - public CuboidException(String string) { - super(string); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/DUTF.java b/src/main/java/com/volmit/iris/util/data/DUTF.java deleted file mode 100644 index b48bb7e7e..000000000 --- a/src/main/java/com/volmit/iris/util/data/DUTF.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -/** - *

Encodes signed and unsigned values using a common variable-length - * scheme, found for example in - * - * Google's Protocol Buffers. It uses fewer bytes to encode smaller values, - * but will use slightly more bytes to encode large values.

- *

- *

Signed values are further encoded using so-called zig-zag encoding - * in order to make them "compatible" with variable-length encoding.

- */ -public final class DUTF { - - private DUTF() { - } - - public static void write(String s, DataOutputStream dos) throws IOException { - byte[] b = s.getBytes(StandardCharsets.UTF_8); - dos.writeShort(b.length); - dos.write(b); - } - - public static String read(DataInputStream din) throws IOException { - byte[] d = new byte[din.readShort()]; - din.read(d); - return new String(d, StandardCharsets.UTF_8); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/DataPalette.java b/src/main/java/com/volmit/iris/util/data/DataPalette.java deleted file mode 100644 index 669674f88..000000000 --- a/src/main/java/com/volmit/iris/util/data/DataPalette.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.util.collection.KList; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class DataPalette { - private final KList palette; - - public DataPalette() { - this(new KList<>(16)); - } - - public DataPalette(KList palette) { - this.palette = palette; - } - - public static DataPalette getPalette(IOAdapter adapter, DataInputStream din) throws IOException { - KList palette = new KList<>(); - int s = din.readShort() - Short.MIN_VALUE; - - for(int i = 0; i < s; i++) { - palette.add(adapter.read(din)); - } - - return new DataPalette<>(palette); - } - - public KList getPalette() { - return palette; - } - - public T get(int index) { - synchronized(palette) { - if(!palette.hasIndex(index)) { - return null; - } - - return palette.get(index); - } - } - - public int getIndex(T t) { - int v = 0; - - synchronized(palette) { - v = palette.indexOf(t); - - if(v == -1) { - v = palette.size(); - palette.add(t); - } - } - - return v; - } - - public void write(IOAdapter adapter, DataOutputStream dos) throws IOException { - synchronized(palette) { - dos.writeShort(getPalette().size() + Short.MIN_VALUE); - - for(T t : palette) { - adapter.write(t, dos); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/data/DataProvider.java b/src/main/java/com/volmit/iris/util/data/DataProvider.java deleted file mode 100644 index cf1146e51..000000000 --- a/src/main/java/com/volmit/iris/util/data/DataProvider.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.core.loader.IrisData; - -public interface DataProvider { - IrisData getData(); -} diff --git a/src/main/java/com/volmit/iris/util/data/Dimension.java b/src/main/java/com/volmit/iris/util/data/Dimension.java deleted file mode 100644 index dd4626793..000000000 --- a/src/main/java/com/volmit/iris/util/data/Dimension.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -/** - * Dimensions - * - * @author cyberpwn - */ -public class Dimension { - private final int width; - private final int height; - private final int depth; - - /** - * Make a dimension - * - * @param width - * width of this (X) - * @param height - * the height (Y) - * @param depth - * the depth (Z) - */ - public Dimension(int width, int height, int depth) { - this.width = width; - this.height = height; - this.depth = depth; - } - - /** - * Make a dimension - * - * @param width - * width of this (X) - * @param height - * the height (Y) - */ - public Dimension(int width, int height) { - this.width = width; - this.height = height; - this.depth = 0; - } - - /** - * Get the direction of the flat part of this dimension (null if no thin - * face) - * - * @return the direction of the flat pane or null - */ - public DimensionFace getPane() { - if(width == 1) { - return DimensionFace.X; - } - - if(height == 1) { - return DimensionFace.Y; - } - - if(depth == 1) { - return DimensionFace.Z; - } - - return null; - } - - public int getWidth() { - return width; - } - - public int getHeight() { - return height; - } - - public int getDepth() { - return depth; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/DimensionFace.java b/src/main/java/com/volmit/iris/util/data/DimensionFace.java deleted file mode 100644 index 500c76526..000000000 --- a/src/main/java/com/volmit/iris/util/data/DimensionFace.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -/** - * Represents a dimension (coordinates not worlds) - * - * @author cyberpwn - */ -public enum DimensionFace { - /** - * The X dimension (width) - */ - X, - - /** - * The Y dimension (height) - */ - Y, - - /** - * The Z dimension (depth) - */ - Z -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/DoubleArrayUtils.java b/src/main/java/com/volmit/iris/util/data/DoubleArrayUtils.java deleted file mode 100644 index e947ecc41..000000000 --- a/src/main/java/com/volmit/iris/util/data/DoubleArrayUtils.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - - -import com.google.common.util.concurrent.AtomicDoubleArray; - -import java.util.Arrays; - -public class DoubleArrayUtils { - public static void shiftRight(double[] values, double push) { - if(values.length - 2 + 1 >= 0) System.arraycopy(values, 0, values, 1, values.length - 2 + 1); - - values[0] = push; - } - - public static void wrapRight(double[] values) { - double last = values[values.length - 1]; - shiftRight(values, last); - } - - public static void fill(double[] values, double value) { - Arrays.fill(values, value); - } - - public static void fill(AtomicDoubleArray values, double value) { - for(int i = 0; i < values.length(); i++) { - values.set(i, value); - } - } - -} diff --git a/src/main/java/com/volmit/iris/util/data/Heafty.java b/src/main/java/com/volmit/iris/util/data/Heafty.java deleted file mode 100644 index 4e0cce01e..000000000 --- a/src/main/java/com/volmit/iris/util/data/Heafty.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -@FunctionalInterface -public interface Heafty { - int getHeaft(); -} diff --git a/src/main/java/com/volmit/iris/util/data/HeightMap.java b/src/main/java/com/volmit/iris/util/data/HeightMap.java deleted file mode 100644 index 5b0a78f08..000000000 --- a/src/main/java/com/volmit/iris/util/data/HeightMap.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import java.util.Arrays; - -public class HeightMap { - private final int[] height; - - public HeightMap() { - height = new int[256]; - Arrays.fill(height, 0); - } - - public void setHeight(int x, int z, int h) { - height[x * 16 + z] = (h); - } - - public int getHeight(int x, int z) { - return height[x * 16 + z]; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/IOAdapter.java b/src/main/java/com/volmit/iris/util/data/IOAdapter.java deleted file mode 100644 index 6d9903ff8..000000000 --- a/src/main/java/com/volmit/iris/util/data/IOAdapter.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public interface IOAdapter { - void write(T t, DataOutputStream dos) throws IOException; - - T read(DataInputStream din) throws IOException; -} diff --git a/src/main/java/com/volmit/iris/util/data/InvertedBiomeGrid.java b/src/main/java/com/volmit/iris/util/data/InvertedBiomeGrid.java deleted file mode 100644 index 27e5d110b..000000000 --- a/src/main/java/com/volmit/iris/util/data/InvertedBiomeGrid.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import org.bukkit.block.Biome; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; - -public class InvertedBiomeGrid implements BiomeGrid { - private final BiomeGrid grid; - - public InvertedBiomeGrid(BiomeGrid real) { - this.grid = real; - } - - - @SuppressWarnings("deprecation") - @Override - public Biome getBiome(int arg0, int arg1) { - return grid.getBiome(arg0, arg1); - } - - - @Override - public Biome getBiome(int arg0, int arg1, int arg2) { - return grid.getBiome(arg0, 255 - arg1, arg2); - } - - @SuppressWarnings("deprecation") - @Override - public void setBiome(int arg0, int arg1, Biome arg2) { - grid.setBiome(arg0, arg1, arg2); - } - - @Override - public void setBiome(int arg0, int arg1, int arg2, Biome arg3) { - grid.setBiome(arg0, 255 - arg1, arg2, arg3); - } -} diff --git a/src/main/java/com/volmit/iris/util/data/IrisBiomeStorage.java b/src/main/java/com/volmit/iris/util/data/IrisBiomeStorage.java deleted file mode 100644 index 7de7820b8..000000000 --- a/src/main/java/com/volmit/iris/util/data/IrisBiomeStorage.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.util.math.IrisMathHelper; -import org.bukkit.block.Biome; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; -import org.jetbrains.annotations.NotNull; - -public class IrisBiomeStorage implements BiomeGrid { - public static final int a; - public static final int b; - public static final int c; - private static final int e; - private static final int f; - - static { - e = (int) Math.round(Math.log(16.0) / Math.log(2.0)) - 2; - f = (int) Math.round(Math.log(256.0) / Math.log(2.0)) - 2; // TODO: WARNING HEIGHT - a = 1 << IrisBiomeStorage.e + IrisBiomeStorage.e + IrisBiomeStorage.f; - b = (1 << IrisBiomeStorage.e) - 1; - c = (1 << IrisBiomeStorage.f) - 1; - } - - private final Biome[] g; - - public IrisBiomeStorage(final Biome[] aBiome) { - this.g = aBiome; - } - - public IrisBiomeStorage() { - this(new Biome[IrisBiomeStorage.a]); - } - - public IrisBiomeStorage b() { - return new IrisBiomeStorage(this.g.clone()); - } - - public void inject(BiomeGrid grid) { - // TODO: WARNING HEIGHT - for(int i = 0; i < 256; i++) { - for(int j = 0; j < 16; j++) { - for(int k = 0; k < 16; k++) { - Biome b = getBiome(j, i, k); - - if(b == null || b.equals(Biome.THE_VOID)) { - continue; - } - - grid.setBiome(j, i, k, b); - } - } - } - } - - @NotNull - @Override - public Biome getBiome(int x, int z) { - return null; - } - - public Biome getBiome(final int x, final int y, final int z) { - final int l = x & IrisBiomeStorage.b; - final int i2 = IrisMathHelper.clamp(y, 0, IrisBiomeStorage.c); - final int j2 = z & IrisBiomeStorage.b; - return this.g[i2 << IrisBiomeStorage.e + IrisBiomeStorage.e | j2 << IrisBiomeStorage.e | l]; - } - - @Override - public void setBiome(int x, int z, @NotNull Biome bio) { - - } - - public void setBiome(final int x, final int y, final int z, final Biome biome) { - final int l = x & IrisBiomeStorage.b; - final int i2 = IrisMathHelper.clamp(y, 0, IrisBiomeStorage.c); - final int j2 = z & IrisBiomeStorage.b; - this.g[i2 << IrisBiomeStorage.e + IrisBiomeStorage.e | j2 << IrisBiomeStorage.e | l] = biome; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/KCache.java b/src/main/java/com/volmit/iris/util/data/KCache.java deleted file mode 100644 index eaa504571..000000000 --- a/src/main/java/com/volmit/iris/util/data/KCache.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.github.benmanes.caffeine.cache.CacheLoader; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.github.benmanes.caffeine.cache.LoadingCache; -import com.volmit.iris.engine.framework.MeteredCache; -import com.volmit.iris.util.math.RollingSequence; - -public class KCache implements MeteredCache { - private final long max; - private CacheLoader loader; - private final LoadingCache cache; - private final boolean fastDump; - private final RollingSequence msu = new RollingSequence(100); - - public KCache(CacheLoader loader, long max) { - this(loader, max, false); - } - - public KCache(CacheLoader loader, long max, boolean fastDump) { - this.max = max; - this.fastDump = fastDump; - this.loader = loader; - this.cache = create(loader); - } - - private LoadingCache create(CacheLoader loader) { - return Caffeine - .newBuilder() - .maximumSize(max) - .softValues() - .initialCapacity((int) (max)) - .build((k) -> loader == null ? null : loader.load(k)); - } - - - public void setLoader(CacheLoader loader) { - this.loader = loader; - } - - public void invalidate(K k) { - cache.invalidate(k); - } - - public void invalidate() { - cache.invalidateAll(); - } - - public V get(K k) { - return cache.get(k); - } - - @Override - public long getSize() { - return cache.estimatedSize(); - } - - @Override - public KCache getRawCache() { - return this; - } - - @Override - public long getMaxSize() { - return max; - } - - @Override - public boolean isClosed() { - return false; - } - - public boolean contains(K next) { - return cache.getIfPresent(next) != null; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/MaterialBlock.java b/src/main/java/com/volmit/iris/util/data/MaterialBlock.java deleted file mode 100644 index 7762d8270..000000000 --- a/src/main/java/com/volmit/iris/util/data/MaterialBlock.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; - -/** - * Material blocks - * - * @author cyberpwn - */ -@SuppressWarnings("deprecation") -public class MaterialBlock { - private Material material; - private Byte data; - - /** - * Create a materialblock - * - * @param material - * the material - * @param data - * the data - */ - public MaterialBlock(Material material, Byte data) { - this.material = material; - this.data = data; - } - - public MaterialBlock(Material material) { - this.material = material; - data = 0; - } - - public MaterialBlock(Location location) { - this(location.getBlock()); - } - - public MaterialBlock(BlockState state) { - material = state.getType(); - data = state.getData().getData(); - } - - public MaterialBlock(Block block) { - material = block.getType(); - data = block.getData(); - } - - public MaterialBlock() { - material = Material.AIR; - data = 0; - } - - public Material getMaterial() { - return material; - } - - public void setMaterial(Material material) { - this.material = material; - } - - public Byte getData() { - return data; - } - - public void setData(Byte data) { - this.data = data; - } - - @Override - public String toString() { - if(getData() == 0) { - return getMaterial().toString(); - } - - return getMaterial().toString() + ":" + getData(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result + ((material == null) ? 0 : material.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if(this == obj) { - return true; - } - if(obj == null) { - return false; - } - if(getClass() != obj.getClass()) { - return false; - } - MaterialBlock other = (MaterialBlock) obj; - if(data == null) { - if(other.data != null) { - return false; - } - } else if(!data.equals(other.data)) { - return false; - } - return material == other.material; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/NibbleArray.java b/src/main/java/com/volmit/iris/util/data/NibbleArray.java deleted file mode 100644 index 2a493dc8f..000000000 --- a/src/main/java/com/volmit/iris/util/data/NibbleArray.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.nio.ByteOrder; -import java.util.Arrays; -import java.util.StringJoiner; - -public class NibbleArray implements Writable { - private static final int[] MASKS = new int[8]; - - static { - for(int i = 0; i < MASKS.length; i++) { - MASKS[i] = maskFor(i); - } - } - - private final int size; - private final Object lock = new Object(); - private byte[] data; - private int depth; - private byte mask; - private transient int bitIndex, byteIndex, bitInByte; - - public NibbleArray(int capacity, DataInputStream in) throws IOException { - size = capacity; - read(in); - } - - public NibbleArray(int nibbleDepth, int capacity) { - if(nibbleDepth > 8 || nibbleDepth < 1) { - throw new IllegalArgumentException(); - } - - int neededBits = nibbleDepth * capacity; - - size = capacity; - depth = nibbleDepth; - data = new byte[(neededBits + neededBits % 8) / 8]; - mask = (byte) maskFor(nibbleDepth); - } - - public NibbleArray(int nibbleDepth, int capacity, NibbleArray existing) { - if(nibbleDepth > 8 || nibbleDepth < 1) { - throw new IllegalArgumentException(); - } - - int neededBits = nibbleDepth * capacity; - size = capacity; - depth = nibbleDepth; - data = new byte[(neededBits + neededBits % 8) / 8]; - mask = (byte) maskFor(nibbleDepth); - - for(int i = 0; i < Math.min(size, existing.size()); i++) { - set(i, existing.get(i)); - } - } - - public static int maskFor(int amountOfBits) { - return powerOfTwo(amountOfBits) - 1; - } - - public static int powerOfTwo(int power) { - int result = 1; - - for(int i = 0; i < power; i++) { - result *= 2; - } - - return result; - } - - public static String binaryString(byte b, ByteOrder byteOrder) { - String str = String.format("%8s", Integer.toBinaryString(b & 0xff)).replace(' ', '0'); - - return byteOrder.equals(ByteOrder.BIG_ENDIAN) ? str : reverse(str); - } - - public static String reverse(String str) { - return new StringBuilder(str).reverse().toString(); - } - - @Override - public void write(DataOutputStream o) throws IOException { - o.writeByte(depth + Byte.MIN_VALUE); - o.write(data); - } - - @Override - public void read(DataInputStream i) throws IOException { - depth = i.readByte() - Byte.MIN_VALUE; - int neededBits = depth * size; - data = new byte[(neededBits + neededBits % 8) / 8]; - mask = (byte) maskFor(depth); - i.read(data); - } - - public int size() { - return size; - } - - public byte get(int index) { - synchronized(lock) { - bitIndex = index * depth; - byteIndex = bitIndex >> 3; - bitInByte = bitIndex & 7; - int value = data[byteIndex] >> bitInByte; - - if(bitInByte + depth > 8) { - value |= data[byteIndex + 1] << bitInByte; - } - - return (byte) (value & mask); - } - } - - public byte get(int x, int y, int z) { - return get(index(x, y, z)); - } - - public int index(int x, int y, int z) { - return y << 8 | z << 4 | x; - } - - public void set(int x, int y, int z, int nibble) { - set(index(x, y, z), nibble); - } - - public void set(int index, int nibble) { - set(index, (byte) nibble); - } - - public void set(int index, byte nybble) { - synchronized(lock) { - bitIndex = index * depth; - byteIndex = bitIndex >> 3; - bitInByte = bitIndex & 7; - data[byteIndex] = (byte) (((~(data[byteIndex] & (mask << bitInByte)) & data[byteIndex]) | ((nybble & mask) << bitInByte)) & 0xff); - - if(bitInByte + depth > 8) { - data[byteIndex + 1] = (byte) (((~(data[byteIndex + 1] & MASKS[bitInByte + depth - 8]) & data[byteIndex + 1]) | ((nybble & mask) >> (8 - bitInByte))) & 0xff); - } - } - } - - public String toBitsString() { - return toBitsString(ByteOrder.BIG_ENDIAN); - } - - public String toBitsString(ByteOrder byteOrder) { - StringJoiner joiner = new StringJoiner(" "); - - for(byte datum : data) { - joiner.add(binaryString(datum, byteOrder)); - } - - return joiner.toString(); - } - - public void clear() { - Arrays.fill(data, (byte) 0); - } - - public void setAll(byte nibble) { - for(int i = 0; i < size; i++) { - set(i, nibble); - } - } - - public void setAll(int nibble) { - for(int i = 0; i < size; i++) { - set(i, (byte) nibble); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/NibbleDataPalette.java b/src/main/java/com/volmit/iris/util/data/NibbleDataPalette.java deleted file mode 100644 index f2a19644c..000000000 --- a/src/main/java/com/volmit/iris/util/data/NibbleDataPalette.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.util.collection.KList; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public abstract class NibbleDataPalette implements Writable { - private static final int DEFAULT_BITS_PER_BLOCK = 4; - private static final int CAPACITY = 4096; - private int bpb; - private NibbleArray data; - private KList palette; - - public NibbleDataPalette(T defaultValue) { - palette = new KList<>(); - bpb = DEFAULT_BITS_PER_BLOCK; - data = new NibbleArray(bpb, CAPACITY); - data.setAll(Byte.MIN_VALUE); - getPaletteId(defaultValue); - } - - public abstract T readType(DataInputStream i) throws IOException; - - public abstract void writeType(T t, DataOutputStream o) throws IOException; - - @Override - public void write(DataOutputStream o) throws IOException { - o.writeByte(bpb + Byte.MIN_VALUE); - o.writeByte(palette.size() + Byte.MIN_VALUE); - - for(T i : palette) { - writeType(i, o); - } - - data.write(o); - } - - @Override - public void read(DataInputStream i) throws IOException { - bpb = i.readByte() - Byte.MIN_VALUE; - palette = new KList<>(); - int v = i.readByte() - Byte.MIN_VALUE; - - for(int j = 0; j < v; j++) { - palette.add(readType(i)); - } - - data = new NibbleArray(CAPACITY, i); - } - - private void expand() { - if(bpb < 8) { - changeBitsPerBlock(bpb + 1); - } else { - throw new IndexOutOfBoundsException("The Data Palette can only handle at most 256 block types per 16x16x16 region. We cannot use more than 8 bits per block!"); - } - } - - public final void optimize() { - int targetBits = bpb; - int needed = palette.size(); - - for(int i = 1; i < bpb; i++) { - if(Math.pow(2, i) > needed) { - targetBits = i; - break; - } - } - - changeBitsPerBlock(targetBits); - } - - private void changeBitsPerBlock(int bits) { - bpb = bits; - data = new NibbleArray(bpb, CAPACITY, data); - } - - public final void set(int x, int y, int z, T d) { - data.set(getCoordinateIndex(x, y, z), getPaletteId(d)); - } - - public final T get(int x, int y, int z) { - return palette.get(data.get(getCoordinateIndex(x, y, z))); - } - - private int getPaletteId(T d) { - int index = palette.indexOf(d); - - if(index == -1) { - index = palette.size(); - palette.add(d); - - if(palette.size() > Math.pow(2, bpb)) { - expand(); - } - } - - return index + Byte.MIN_VALUE; - } - - private int getCoordinateIndex(int x, int y, int z) { - return y << 8 | z << 4 | x; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/Recycler.java b/src/main/java/com/volmit/iris/util/data/Recycler.java deleted file mode 100644 index ac4218b08..000000000 --- a/src/main/java/com/volmit/iris/util/data/Recycler.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.volmit.iris.util.data; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Supplier; - -public class Recycler { - private final List> pool; - private final Supplier factory; - - public Recycler(Supplier factory) - { - pool = new CopyOnWriteArrayList<>(); - this.factory = factory; - } - - public int getFreeObjects() - { - int m = 0; - RecycledObject o; - for (RecycledObject tRecycledObject : pool) { - o = tRecycledObject; - - if (!o.isUsed()) { - m++; - } - } - - return m; - } - - public int getUsedOjects() - { - int m = 0; - RecycledObject o; - for (RecycledObject tRecycledObject : pool) { - o = tRecycledObject; - - if (o.isUsed()) { - m++; - } - } - - return m; - } - - public void dealloc(T t) - { - RecycledObject o; - - for (RecycledObject tRecycledObject : pool) { - o = tRecycledObject; - if (o.isUsed() && System.identityHashCode(t) == System.identityHashCode(o.getObject())) { - o.dealloc(); - return; - } - } - } - - public T alloc() - { - RecycledObject o; - - for (RecycledObject tRecycledObject : pool) { - o = tRecycledObject; - if (o.alloc()) { - return o.getObject(); - } - } - - expand(); - - return alloc(); - } - - public boolean contract() - { - return contract(Math.max(getFreeObjects() / 2, Runtime.getRuntime().availableProcessors())); - } - - public boolean contract(int maxFree) - { - int remove = getFreeObjects() - maxFree; - - if(remove > 0) - { - RecycledObject o; - - for(int i = pool.size()-1; i > 0; i--) - { - o = pool.get(i); - if(!o.isUsed()) - { - pool.remove(i); - remove--; - - if(remove <= 0) - { - return true; - } - } - } - } - - return false; - } - - public void expand() - { - if(pool.isEmpty()) - { - expand(Runtime.getRuntime().availableProcessors()); - return; - } - - expand(getUsedOjects() + Runtime.getRuntime().availableProcessors()); - } - - public void expand(int by) - { - for(int i = 0; i < by; i++) - { - pool.add(new RecycledObject<>(factory.get())); - } - } - - public int size() - { - return pool.size(); - } - - public void deallocAll() - { - pool.clear(); - } - - public static class RecycledObject - { - private final T object; - private final AtomicBoolean used; - - public RecycledObject(T object) - { - this.object = object; - used = new AtomicBoolean(false); - } - - public T getObject() - { - return object; - } - - public boolean isUsed() - { - return used.get(); - } - - public void dealloc() - { - used.set(false); - } - - public boolean alloc() - { - if(used.get()) - { - return false; - } - - used.set(true); - return true; - } - } -} diff --git a/src/main/java/com/volmit/iris/util/data/Shrinkwrap.java b/src/main/java/com/volmit/iris/util/data/Shrinkwrap.java deleted file mode 100644 index 32d247767..000000000 --- a/src/main/java/com/volmit/iris/util/data/Shrinkwrap.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -public class Shrinkwrap { - private T t; - - public Shrinkwrap(T t) { - set(t); - } - - public Shrinkwrap() { - this(null); - } - - public T get() { - return t; - } - - public void set(T t) { - this.t = t; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/VanillaBiomeMap.java b/src/main/java/com/volmit/iris/util/data/VanillaBiomeMap.java deleted file mode 100644 index 43be48b37..000000000 --- a/src/main/java/com/volmit/iris/util/data/VanillaBiomeMap.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.inventorygui.RandomColor.Color; -import com.volmit.iris.util.inventorygui.RandomColor.Luminosity; -import com.volmit.iris.util.inventorygui.RandomColor.SaturationType; -import org.bukkit.block.Biome; - -public class VanillaBiomeMap { - - private static final KMap BIOME_HEX = new KMap<>(); - private static final KMap BIOME_COLOR = new KMap<>(); - private static final KMap BIOME_LUMINOSITY = new KMap<>(); - private static final KMap BIOME_SATURATION = new KMap<>(); - private static final KMap BIOME_IDs = new KMap<>(); - - static { - add(Biome.OCEAN, 0x000070, Color.BLUE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.PLAINS, 0x8DB360, Color.GREEN, Luminosity.LIGHT, SaturationType.MEDIUM); - add(Biome.DESERT, 0xFA9418, Color.YELLOW, Luminosity.LIGHT, SaturationType.MEDIUM); - add(Biome.WINDSWEPT_HILLS, 0x606060, Color.MONOCHROME, Luminosity.BRIGHT, null); - add(Biome.FOREST, 0x056621, Color.GREEN, Luminosity.BRIGHT, null); - add(Biome.TAIGA, 0x0B6659, Color.GREEN, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.SWAMP, 0x07F9B2, Color.ORANGE, Luminosity.DARK, SaturationType.MEDIUM); - add(Biome.RIVER, 0x0000FF, Color.BLUE, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.NETHER_WASTES, 0xBF3B3B, Color.RED, Luminosity.LIGHT, SaturationType.MEDIUM); - add(Biome.THE_END, 0x8080FF, Color.PURPLE, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.FROZEN_OCEAN, 0x7070D6, Color.BLUE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.FROZEN_RIVER, 0xA0A0FF, Color.BLUE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.SNOWY_PLAINS, 0xFFFFFF, Color.MONOCHROME, Luminosity.LIGHT, null); - add(Biome.MUSHROOM_FIELDS, 0xFF00FF, Color.PURPLE, Luminosity.BRIGHT, null); - add(Biome.BEACH, 0xFADE55, Color.YELLOW, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.JUNGLE, 0x537B09, Color.GREEN, Luminosity.BRIGHT, SaturationType.HIGH); - add(Biome.SPARSE_JUNGLE, 0x628B17, Color.GREEN, Luminosity.BRIGHT, SaturationType.HIGH); - add(Biome.DEEP_OCEAN, 0x000030, Color.BLUE, Luminosity.DARK, null); - add(Biome.STONY_SHORE, 0xA2A284, Color.GREEN, Luminosity.DARK, null); - add(Biome.SNOWY_BEACH, 0xFAF0C0, Color.YELLOW, Luminosity.LIGHT, null); - add(Biome.BIRCH_FOREST, 0x307444, Color.GREEN, Luminosity.LIGHT, null); - add(Biome.DARK_FOREST, 0x40511A, Color.GREEN, Luminosity.DARK, null); - add(Biome.SNOWY_TAIGA, 0x31554A, Color.BLUE, Luminosity.LIGHT, null); - add(Biome.OLD_GROWTH_PINE_TAIGA, 0x596651, Color.ORANGE, Luminosity.LIGHT, null); - add(Biome.WINDSWEPT_FOREST, 0x507050, Color.MONOCHROME, Luminosity.BRIGHT, null); - add(Biome.SAVANNA, 0xBDB25F, Color.GREEN, Luminosity.LIGHT, null); - add(Biome.SAVANNA_PLATEAU, 0xA79D64, Color.GREEN, Luminosity.LIGHT, null); - add(Biome.BADLANDS, 0xD94515, Color.ORANGE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.WOODED_BADLANDS, 0xB09765, Color.ORANGE, Luminosity.BRIGHT, SaturationType.HIGH); - add(Biome.SMALL_END_ISLANDS, 0xff1a8c, Color.PURPLE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.END_MIDLANDS, 0x8080FF, Color.YELLOW, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.END_HIGHLANDS, 0x8080FF, Color.PURPLE, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.END_BARRENS, 0x8080FF, Color.PURPLE, Luminosity.LIGHT, SaturationType.MEDIUM); - add(Biome.WARM_OCEAN, 0x0000AC, Color.BLUE, Luminosity.BRIGHT, SaturationType.LOW); - add(Biome.LUKEWARM_OCEAN, 0x000090, Color.BLUE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.COLD_OCEAN, 0x202070, Color.BLUE, Luminosity.BRIGHT, SaturationType.HIGH); - add(Biome.DEEP_LUKEWARM_OCEAN, 0x000040, Color.BLUE, Luminosity.DARK, SaturationType.MEDIUM); - add(Biome.DEEP_COLD_OCEAN, 0x202038, Color.BLUE, Luminosity.DARK, SaturationType.HIGH); - add(Biome.DEEP_FROZEN_OCEAN, 0x404090, Color.BLUE, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.THE_VOID, 0x000000, Color.MONOCHROME, Luminosity.DARK, null); - add(Biome.SUNFLOWER_PLAINS, 0xB5DB88, Color.GREEN, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.WINDSWEPT_GRAVELLY_HILLS, 0x789878, Color.MONOCHROME, Luminosity.LIGHT, null); - add(Biome.FLOWER_FOREST, 0x2D8E49, Color.RED, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.ICE_SPIKES, 0xB4DCDC, Color.BLUE, Luminosity.LIGHT, SaturationType.LOW); - add(Biome.OLD_GROWTH_BIRCH_FOREST, 0x589C6C, Color.GREEN, Luminosity.LIGHT, null); - add(Biome.OLD_GROWTH_SPRUCE_TAIGA, 0x818E79, Color.ORANGE, Luminosity.DARK, SaturationType.HIGH); - add(Biome.WINDSWEPT_SAVANNA, 0xE5DA87, Color.ORANGE, Luminosity.LIGHT, SaturationType.HIGH); - add(Biome.ERODED_BADLANDS, 0xFF6D3D, Color.ORANGE, Luminosity.LIGHT, SaturationType.HIGH); - add(Biome.BAMBOO_JUNGLE, 0x768E14, Color.GREEN, Luminosity.BRIGHT, SaturationType.HIGH); - add(Biome.SOUL_SAND_VALLEY, 0x5E3830, Color.BLUE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.CRIMSON_FOREST, 0xDD0808, Color.RED, Luminosity.DARK, SaturationType.HIGH); - add(Biome.WARPED_FOREST, 0x49907B, Color.BLUE, Luminosity.BRIGHT, null); - add(Biome.BASALT_DELTAS, 0x403636, Color.MONOCHROME, Luminosity.DARK, null); - add(Biome.DRIPSTONE_CAVES, 0xcc6600, Color.ORANGE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.LUSH_CAVES, 0x003300, Color.GREEN, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.MEADOW, 0xff00ff, Color.BLUE, Luminosity.BRIGHT, SaturationType.LOW); - add(Biome.GROVE, 0x80ff80, Color.GREEN, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.SNOWY_SLOPES, 0x00ffff, Color.BLUE, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.FROZEN_PEAKS, 0xA0A0A0, Color.MONOCHROME, Luminosity.LIGHT, null); - add(Biome.JAGGED_PEAKS, 0x3d7bc2, Color.MONOCHROME, Luminosity.BRIGHT, SaturationType.MEDIUM); - add(Biome.STONY_PEAKS, 0x888888, Color.MONOCHROME, Luminosity.LIGHT, null); - add(Biome.CUSTOM, 0xffffff, Color.MONOCHROME, Luminosity.DARK, SaturationType.MONOCHROME); - - } - - - private static void add(Biome biome, int color, Color randomColor, Luminosity luminosity, SaturationType saturation) { - BIOME_HEX.put(biome, color); - BIOME_COLOR.put(biome, randomColor); - if(luminosity != null) BIOME_LUMINOSITY.put(biome, luminosity); - if(saturation != null) BIOME_SATURATION.put(biome, saturation); - BIOME_IDs.put(biome, (short) biome.ordinal()); - } - - private static void add(Biome biome, int color, Color randomColor, Luminosity luminosity) { - add(biome, color, randomColor, luminosity, null); - } - - public static int getColor(Biome biome) { - return BIOME_HEX.get(biome); - } - - public static Color getColorType(Biome biome) { - return BIOME_COLOR.get(biome); - } - - public static Luminosity getColorLuminosity(Biome biome) { - return BIOME_LUMINOSITY.get(biome); - } - - public static SaturationType getColorSaturatiom(Biome biome) { - return BIOME_SATURATION.get(biome); - } - - public static short getId(Biome biome) { - return BIOME_IDs.get(biome); - } -} diff --git a/src/main/java/com/volmit/iris/util/data/Varint.java b/src/main/java/com/volmit/iris/util/data/Varint.java deleted file mode 100644 index 93eb31812..000000000 --- a/src/main/java/com/volmit/iris/util/data/Varint.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -/** - *

Encodes signed and unsigned values using a common variable-length - * scheme, found for example in - * - * Google's Protocol Buffers. It uses fewer bytes to encode smaller values, - * but will use slightly more bytes to encode large values.

- *

- *

Signed values are further encoded using so-called zig-zag encoding - * in order to make them "compatible" with variable-length encoding.

- */ -public final class Varint { - - private Varint() { - } - - /** - * Encodes a value using the variable-length encoding from - * - * Google Protocol Buffers. It uses zig-zag encoding to efficiently - * encode signed values. If values are known to be nonnegative, - * {@link #writeUnsignedVarLong(long, DataOutput)} should be used. - * - * @param value - * value to encode - * @param out - * to writeNodeData bytes to - * @throws IOException - * if {@link DataOutput} throws {@link IOException} - */ - public static void writeSignedVarLong(long value, DataOutput out) throws IOException { - // Great trick from http://code.google.com/apis/protocolbuffers/docs/encoding.html#types - writeUnsignedVarLong((value << 1) ^ (value >> 63), out); - } - - /** - * Encodes a value using the variable-length encoding from - * - * Google Protocol Buffers. Zig-zag is not used, so input must not be negative. - * If values can be negative, use {@link #writeSignedVarLong(long, DataOutput)} - * instead. This method treats negative input as like a large unsigned value. - * - * @param value - * value to encode - * @param out - * to writeNodeData bytes to - * @throws IOException - * if {@link DataOutput} throws {@link IOException} - */ - public static void writeUnsignedVarLong(long value, DataOutput out) throws IOException { - while((value & 0xFFFFFFFFFFFFFF80L) != 0L) { - out.writeByte(((int) value & 0x7F) | 0x80); - value >>>= 7; - } - out.writeByte((int) value & 0x7F); - } - - /** - * @see #writeSignedVarLong(long, DataOutput) - */ - public static void writeSignedVarInt(int value, DataOutput out) throws IOException { - // Great trick from http://code.google.com/apis/protocolbuffers/docs/encoding.html#types - writeUnsignedVarInt((value << 1) ^ (value >> 31), out); - } - - /** - * @see #writeUnsignedVarLong(long, DataOutput) - */ - public static void writeUnsignedVarInt(int value, DataOutput out) throws IOException { - while((value & 0xFFFFFF80) != 0L) { - out.writeByte((value & 0x7F) | 0x80); - value >>>= 7; - } - out.writeByte(value & 0x7F); - } - - public static byte[] writeSignedVarInt(int value) { - // Great trick from http://code.google.com/apis/protocolbuffers/docs/encoding.html#types - return writeUnsignedVarInt((value << 1) ^ (value >> 31)); - } - - /** - * @see #writeUnsignedVarLong(long, DataOutput) - *

- * This one does not use streams and is much faster. - * Makes a single object each time, and that object is a primitive array. - */ - public static byte[] writeUnsignedVarInt(int value) { - byte[] byteArrayList = new byte[10]; - int i = 0; - while((value & 0xFFFFFF80) != 0L) { - byteArrayList[i++] = ((byte) ((value & 0x7F) | 0x80)); - value >>>= 7; - } - byteArrayList[i] = ((byte) (value & 0x7F)); - byte[] out = new byte[i + 1]; - for(; i >= 0; i--) { - out[i] = byteArrayList[i]; - } - return out; - } - - /** - * @param in - * to read bytes from - * @return decode value - * @throws IOException - * if {@link DataInput} throws {@link IOException} - * @throws IllegalArgumentException - * if variable-length value does not terminate - * after 9 bytes have been read - * @see #writeSignedVarLong(long, DataOutput) - */ - public static long readSignedVarLong(DataInput in) throws IOException { - long raw = readUnsignedVarLong(in); - // This undoes the trick in writeSignedVarLong() - long temp = (((raw << 63) >> 63) ^ raw) >> 1; - // This extra step lets us deal with the largest signed values by treating - // negative results from read unsigned methods as like unsigned values - // Must re-flip the top bit if the original read value had it set. - return temp ^ (raw & (1L << 63)); - } - - /** - * @param in - * to read bytes from - * @return decode value - * @throws IOException - * if {@link DataInput} throws {@link IOException} - * @throws IllegalArgumentException - * if variable-length value does not terminate - * after 9 bytes have been read - * @see #writeUnsignedVarLong(long, DataOutput) - */ - public static long readUnsignedVarLong(DataInput in) throws IOException { - long value = 0L; - int i = 0; - long b; - while(((b = in.readByte()) & 0x80L) != 0) { - value |= (b & 0x7F) << i; - i += 7; - if(i > 63) { - throw new IllegalArgumentException("Variable length quantity is too long"); - } - } - return value | (b << i); - } - - /** - * @throws IllegalArgumentException - * if variable-length value does not terminate - * after 5 bytes have been read - * @throws IOException - * if {@link DataInput} throws {@link IOException} - * @see #readSignedVarLong(DataInput) - */ - public static int readSignedVarInt(DataInput in) throws IOException { - int raw = readUnsignedVarInt(in); - // This undoes the trick in writeSignedVarInt() - int temp = (((raw << 31) >> 31) ^ raw) >> 1; - // This extra step lets us deal with the largest signed values by treating - // negative results from read unsigned methods as like unsigned values. - // Must re-flip the top bit if the original read value had it set. - return temp ^ (raw & (1 << 31)); - } - - /** - * @throws IllegalArgumentException - * if variable-length value does not terminate - * after 5 bytes have been read - * @throws IOException - * if {@link DataInput} throws {@link IOException} - * @see #readUnsignedVarLong(DataInput) - */ - public static int readUnsignedVarInt(DataInput in) throws IOException { - int value = 0; - int i = 0; - int b; - while(((b = in.readByte()) & 0x80) != 0) { - value |= (b & 0x7F) << i; - i += 7; - if(i > 35) { - throw new IllegalArgumentException("Variable length quantity is too long"); - } - } - return value | (b << i); - } - - public static int readSignedVarInt(byte[] bytes) { - int raw = readUnsignedVarInt(bytes); - // This undoes the trick in writeSignedVarInt() - int temp = (((raw << 31) >> 31) ^ raw) >> 1; - // This extra step lets us deal with the largest signed values by treating - // negative results from read unsigned methods as like unsigned values. - // Must re-flip the top bit if the original read value had it set. - return temp ^ (raw & (1 << 31)); - } - - public static int readUnsignedVarInt(byte[] bytes) { - int value = 0; - int i = 0; - byte rb = Byte.MIN_VALUE; - for(byte b : bytes) { - rb = b; - if((b & 0x80) == 0) { - break; - } - value |= (b & 0x7f) << i; - i += 7; - if(i > 35) { - throw new IllegalArgumentException("Variable length quantity is too long"); - } - } - return value | (rb << i); - } - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/WeightMap.java b/src/main/java/com/volmit/iris/util/data/WeightMap.java deleted file mode 100644 index c2d643ee3..000000000 --- a/src/main/java/com/volmit/iris/util/data/WeightMap.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.util.collection.KMap; - -public class WeightMap extends KMap { - private static final long serialVersionUID = 87558033900969389L; - private boolean modified = false; - private double lastWeight = 0; - - public double getPercentChance(T t) { - if(totalWeight() <= 0) { - return 0; - } - - return getWeight(t) / totalWeight(); - } - - public void clear() { - modified = true; - } - - public WeightMap setWeight(T t, double weight) { - modified = true; - put(t, weight); - - return this; - } - - public double getWeight(T t) { - return get(t); - } - - public double totalWeight() { - if(!modified) { - return lastWeight; - } - - modified = false; - Shrinkwrap s = new Shrinkwrap<>(0D); - forEachKey(Integer.MAX_VALUE, (d) -> s.set(s.get() + 1)); - lastWeight = s.get(); - - return lastWeight; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/WeightedRandom.java b/src/main/java/com/volmit/iris/util/data/WeightedRandom.java deleted file mode 100644 index c2fdb0fd1..000000000 --- a/src/main/java/com/volmit/iris/util/data/WeightedRandom.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KeyPair; - -import java.util.Random; - -public class WeightedRandom { - - private final KList> weightedObjects = new KList<>(); - private final Random random; - private int totalWeight = 0; - - public WeightedRandom(Random random) { - this.random = random; - } - - public WeightedRandom() { - this.random = new Random(); - } - - public void put(T object, int weight) { - weightedObjects.add(new KeyPair<>(object, weight)); - totalWeight += weight; - } - - public T pullRandom() { - int pull = random.nextInt(totalWeight); - int index = 0; - while(pull > 0) { - pull -= weightedObjects.get(index).getV(); - index++; - } - return weightedObjects.get(index).getK(); - } - - public int getSize() { - return weightedObjects.size(); - } - - public void shuffle() { - weightedObjects.shuffle(random); - } -} diff --git a/src/main/java/com/volmit/iris/util/data/Writable.java b/src/main/java/com/volmit/iris/util/data/Writable.java deleted file mode 100644 index 9386e0fac..000000000 --- a/src/main/java/com/volmit/iris/util/data/Writable.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public interface Writable { - void write(DataOutputStream o) throws IOException; - - void read(DataInputStream i) throws IOException; -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/BitStorage.java b/src/main/java/com/volmit/iris/util/data/palette/BitStorage.java deleted file mode 100644 index 714fd2761..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/BitStorage.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import org.apache.commons.lang3.Validate; - -import java.util.concurrent.atomic.AtomicLongArray; -import java.util.function.IntConsumer; - -public class BitStorage { - private static final int[] MAGIC = new int[] { - -1, -1, 0, Integer.MIN_VALUE, 0, 0, 1431655765, 1431655765, 0, Integer.MIN_VALUE, - 0, 1, 858993459, 858993459, 0, 715827882, 715827882, 0, 613566756, 613566756, - 0, Integer.MIN_VALUE, 0, 2, 477218588, 477218588, 0, 429496729, 429496729, 0, - 390451572, 390451572, 0, 357913941, 357913941, 0, 330382099, 330382099, 0, 306783378, - 306783378, 0, 286331153, 286331153, 0, Integer.MIN_VALUE, 0, 3, 252645135, 252645135, - 0, 238609294, 238609294, 0, 226050910, 226050910, 0, 214748364, 214748364, 0, - 204522252, 204522252, 0, 195225786, 195225786, 0, 186737708, 186737708, 0, 178956970, - 178956970, 0, 171798691, 171798691, 0, 165191049, 165191049, 0, 159072862, 159072862, - 0, 153391689, 153391689, 0, 148102320, 148102320, 0, 143165576, 143165576, 0, - 138547332, 138547332, 0, Integer.MIN_VALUE, 0, 4, 130150524, 130150524, 0, 126322567, - 126322567, 0, 122713351, 122713351, 0, 119304647, 119304647, 0, 116080197, 116080197, - 0, 113025455, 113025455, 0, 110127366, 110127366, 0, 107374182, 107374182, 0, - 104755299, 104755299, 0, 102261126, 102261126, 0, 99882960, 99882960, 0, 97612893, - 97612893, 0, 95443717, 95443717, 0, 93368854, 93368854, 0, 91382282, 91382282, - 0, 89478485, 89478485, 0, 87652393, 87652393, 0, 85899345, 85899345, 0, - 84215045, 84215045, 0, 82595524, 82595524, 0, 81037118, 81037118, 0, 79536431, - 79536431, 0, 78090314, 78090314, 0, 76695844, 76695844, 0, 75350303, 75350303, - 0, 74051160, 74051160, 0, 72796055, 72796055, 0, 71582788, 71582788, 0, - 70409299, 70409299, 0, 69273666, 69273666, 0, 68174084, 68174084, 0, Integer.MIN_VALUE, - 0, 5}; - - private final AtomicLongArray data; - private final int bits; - private final long mask; - private final int size; - private final int valuesPerLong; - private final int divideMul; - private final int divideAdd; - private final int divideShift; - - public BitStorage(int bits, int length) { - this(bits, length, (AtomicLongArray) null); - } - - private static AtomicLongArray atomic(long[] data) { - if(data == null) { - return null; - } - - AtomicLongArray d = new AtomicLongArray(data.length); - for(int i = 0; i < data.length; i++) { - d.set(i, data[i]); - } - - return d; - } - - private static long[] atomic(AtomicLongArray data) { - if(data == null) { - return null; - } - - long[] d = new long[data.length()]; - for(int i = 0; i < data.length(); i++) { - d[i] = data.get(i); - } - - return d; - } - - public BitStorage(int bits, int length, long[] data) { - this(bits, length, atomic(data)); - } - - public BitStorage(int bits, int length, AtomicLongArray data) { - Validate.inclusiveBetween(1L, 32L, bits); - this.size = length; - this.bits = bits; - this.mask = (1L << bits) - 1L; - this.valuesPerLong = (char) (64 / bits); - int var3 = 3 * (this.valuesPerLong - 1); - this.divideMul = MAGIC[var3]; - this.divideAdd = MAGIC[var3 + 1]; - this.divideShift = MAGIC[var3 + 2]; - int var4 = (length + this.valuesPerLong - 1) / this.valuesPerLong; - if(data != null) { - if(data.length() != var4) { - throw new RuntimeException("NO!"); - } - this.data = data; - } else { - this.data = new AtomicLongArray(var4); - } - } - - private int cellIndex(int var0) { - long var1 = Integer.toUnsignedLong(this.divideMul); - long var3 = Integer.toUnsignedLong(this.divideAdd); - return (int) (var0 * var1 + var3 >> 32L >> this.divideShift); - } - - public int getAndSet(int var0, int var1) { - Validate.inclusiveBetween(0L, (this.size - 1), var0); - Validate.inclusiveBetween(0L, this.mask, var1); - int var2 = cellIndex(var0); - long var3 = this.data.get(var2); - int var5 = (var0 - var2 * this.valuesPerLong) * this.bits; - int var6 = (int) (var3 >> var5 & this.mask); - this.data.set(var2, var3 & (this.mask << var5 ^ 0xFFFFFFFFFFFFFFFFL) | (var1 & this.mask) << var5); - return var6; - } - - public void set(int var0, int var1) { - Validate.inclusiveBetween(0L, (this.size - 1), var0); - Validate.inclusiveBetween(0L, this.mask, var1); - int var2 = cellIndex(var0); - long var3 = this.data.get(var2); - int var5 = (var0 - var2 * this.valuesPerLong) * this.bits; - - this.data.set(var2, var3 & (this.mask << var5 ^ 0xFFFFFFFFFFFFFFFFL) | (var1 & this.mask) << var5); - } - - public int get(int var0) { - Validate.inclusiveBetween(0L, (this.size - 1), var0); - int var1 = cellIndex(var0); - long var2 = this.data.get(var1); - int var4 = (var0 - var1 * this.valuesPerLong) * this.bits; - return (int) (var2 >> var4 & this.mask); - } - - public long[] getRaw() { - return atomic(data); - } - - public int getSize() { - return this.size; - } - - public int getBits() { - return this.bits; - } - - public void getAll(IntConsumer var0) { - int var1 = 0; - for(int i = 0; i < data.length(); i++) { - long var5 = data.get(i); - for(int var7 = 0; var7 < this.valuesPerLong; var7++) { - var0.accept((int) (var5 & this.mask)); - var5 >>= this.bits; - if(++var1 >= this.size) - return; - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/CountConsumer.java b/src/main/java/com/volmit/iris/util/data/palette/CountConsumer.java deleted file mode 100644 index 785997ed9..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/CountConsumer.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -@FunctionalInterface -public interface CountConsumer { - void accept(T paramT, int paramInt); -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/CrudeIncrementalIntIdentityHashBiMap.java b/src/main/java/com/volmit/iris/util/data/palette/CrudeIncrementalIntIdentityHashBiMap.java deleted file mode 100644 index 1f8476db1..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/CrudeIncrementalIntIdentityHashBiMap.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import com.google.common.collect.Iterators; - -import java.util.Iterator; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicIntegerArray; -import java.util.concurrent.atomic.AtomicReferenceArray; - -public class CrudeIncrementalIntIdentityHashBiMap implements IdMap { - public static final int NOT_FOUND = -1; - private static final Object EMPTY_SLOT = null; - private static final float LOADFACTOR = 0.8F; - private AtomicReferenceArray keys; - private AtomicIntegerArray values; - private AtomicReferenceArray byId; - private int nextId; - private int size; - - public CrudeIncrementalIntIdentityHashBiMap(int var0) { - var0 = (int) (var0 / 0.8F); - this.keys = new AtomicReferenceArray<>(var0); - this.values = new AtomicIntegerArray(var0); - this.byId = new AtomicReferenceArray<>(var0); - } - - public int getId(K var0) { - return getValue(indexOf(var0, hash(var0))); - } - - - public K byId(int var0) { - if(var0 < 0 || var0 >= this.byId.length()) { - return null; - } - return this.byId.get(var0); - } - - private int getValue(int var0) { - if(var0 == -1) { - return -1; - } - return this.values.get(var0); - } - - public boolean contains(K var0) { - return (getId(var0) != -1); - } - - public boolean contains(int var0) { - return (byId(var0) != null); - } - - public int add(K var0) { - int var1 = nextId(); - addMapping(var0, var1); - return var1; - } - - private int nextId() { - while(nextId < byId.length() && byId.get(nextId) != null) { - nextId++; - } - return nextId; - } - - private void grow(int var0) { - AtomicReferenceArray var1 = this.keys; - AtomicIntegerArray var2 = this.values; - this.keys = new AtomicReferenceArray<>(var0); - this.values = new AtomicIntegerArray(var0); - this.byId = new AtomicReferenceArray<>(var0); - this.nextId = 0; - this.size = 0; - for(int var3 = 0; var3 < var1.length(); var3++) { - if(var1.get(var3) != null) { - addMapping(var1.get(var3), var2.get(var3)); - } - } - } - - public void addMapping(K var0, int var1) { - int var2 = Math.max(var1, this.size + 1); - if(var2 >= this.keys.length() * 0.8F) { - int i = this.keys.length() << 1; - while(i < var1) - i <<= 1; - grow(i); - } - int var3 = findEmpty(hash(var0)); - this.keys.set(var3, var0); - this.values.set(var3, var1); - this.byId.set(var1, var0); - this.size++; - if(var1 == this.nextId) - this.nextId++; - } - - private int hash(K var0) { - return (Mth.murmurHash3Mixer(System.identityHashCode(var0)) & Integer.MAX_VALUE) % this.keys.length(); - } - - private int indexOf(K var0, int var1) { - int var2; - for(var2 = var1; var2 < this.keys.length(); var2++) { - if(this.keys.get(var2) == null) { - return 0; - } - if(this.keys.get(var2).equals(var0)) - return var2; - if(this.keys.get(var2) == EMPTY_SLOT) - return -1; - } - for(var2 = 0; var2 < var1; var2++) { - if(this.keys.get(var2).equals(var0)) - return var2; - if(this.keys.get(var2) == EMPTY_SLOT) - return -1; - } - return -1; - } - - private int findEmpty(int var0) { - int var1; - for(var1 = var0; var1 < this.keys.length(); var1++) { - if(this.keys.get(var1) == EMPTY_SLOT) - return var1; - } - for(var1 = 0; var1 < var0; var1++) { - if(this.keys.get(var1) == EMPTY_SLOT) - return var1; - } - throw new RuntimeException("Overflowed :("); - } - - public Iterator iterator() { - return Iterators.filter(new Iterator() { - int i = 0; - - @Override - public boolean hasNext() { - return i < byId.length() - 1; - } - - @Override - public K next() { - return byId.get(i++); - } - }, Objects::nonNull); - } - - public void clear() { - - for(int i = 0; i < Math.max(keys.length(), byId.length()); i++) { - if(i < keys.length() - 1) { - keys.set(i, null); - } - - if(i < byId.length() - 1) { - byId.set(i, null); - } - } - - this.nextId = 0; - this.size = 0; - } - - public int size() { - return this.size; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/GlobalPalette.java b/src/main/java/com/volmit/iris/util/data/palette/GlobalPalette.java deleted file mode 100644 index 6dc98299f..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/GlobalPalette.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import java.util.List; -import java.util.function.Predicate; - -public class GlobalPalette implements Palette { - private final IdMapper registry; - - private final T defaultValue; - - public GlobalPalette(T... f) { - IdMapper mapper = new IdMapper<>(); - for(T i : f) { - mapper.add(i); - } - registry = mapper; - defaultValue = f[0]; - } - - public GlobalPalette(IdMapper var0, T var1) { - this.registry = var0; - this.defaultValue = var1; - } - - public int idFor(T var0) { - int var1 = this.registry.getId(var0); - return (var1 == -1) ? 0 : var1; - } - - public boolean maybeHas(Predicate var0) { - return true; - } - - public T valueFor(int var0) { - T var1 = this.registry.byId(var0); - return (var1 == null) ? this.defaultValue : var1; - } - - public int getSize() { - return this.registry.size(); - } - - @Override - public void read(List fromList) { - - } - - @Override - public void write(List toList) { - - } -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/HashMapPalette.java b/src/main/java/com/volmit/iris/util/data/palette/HashMapPalette.java deleted file mode 100644 index bdfb39cee..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/HashMapPalette.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KMap; - -import java.util.List; - -public class HashMapPalette implements Palette { - private final KMap values; - private final PaletteResize resizeHandler; - private final int bits; - private int id; - - public HashMapPalette(int var1, PaletteResize var2) { - this.bits = var1; - this.resizeHandler = var2; - this.values = new KMap<>(); - id = 1; - } - - public int idFor(T var0) { - if(var0 == null) { - return 0; - } - - return this.values.computeIfAbsent(var0, (k) -> { - int newId = id++; - - if(newId >= 1 << this.bits) { - Iris.info(newId + " to..."); - newId = this.resizeHandler.onResize(this.bits + 1, var0); - Iris.info(newId + ".."); - } - - return newId; - }); - } - - public T valueFor(int var0) { - return this.values.getKey(var0); - } - - public int getSize() { - return this.values.size(); - } - - @Override - public void read(List data) { - data.forEach(this::idFor); - } - - @Override - public void write(List toList) { - toList.addAll(values.keySet()); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/palette/IdMap.java b/src/main/java/com/volmit/iris/util/data/palette/IdMap.java deleted file mode 100644 index 4c74d39c5..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/IdMap.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -public interface IdMap extends Iterable { - int getId(T paramT); - - T byId(int paramInt); -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/IdMapper.java b/src/main/java/com/volmit/iris/util/data/palette/IdMapper.java deleted file mode 100644 index 74d27eeb1..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/IdMapper.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import com.google.common.base.Predicates; -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; - -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.List; - -public class IdMapper implements IdMap { - public static final int DEFAULT = -1; - private final IdentityHashMap tToId; - private final List idToT; - private int nextId; - - public IdMapper(IdentityHashMap tToId, List idToT, int nextId) { - this.tToId = tToId; - this.idToT = idToT; - this.nextId = nextId; - } - - public IdMapper() { - this(512); - } - - public IdMapper(int var0) { - this.idToT = Lists.newArrayListWithExpectedSize(var0); - this.tToId = new IdentityHashMap<>(var0); - } - - public void addMapping(T var0, int var1) { - this.tToId.put(var0, Integer.valueOf(var1)); - while(this.idToT.size() <= var1) { - this.idToT.add(null); - } - this.idToT.set(var1, var0); - if(this.nextId <= var1) - this.nextId = var1 + 1; - } - - public void add(T var0) { - addMapping(var0, this.nextId); - } - - public int getId(T var0) { - Integer var1 = this.tToId.get(var0); - return (var1 == null) ? -1 : var1.intValue(); - } - - public final T byId(int var0) { - if(var0 >= 0 && var0 < this.idToT.size()) { - return this.idToT.get(var0); - } - return null; - } - - public Iterator iterator() { - return Iterators.filter(this.idToT.iterator(), Predicates.notNull()); - } - - public boolean contains(int var0) { - return (byId(var0) != null); - } - - public int size() { - return this.tToId.size(); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/palette/LinearPalette.java b/src/main/java/com/volmit/iris/util/data/palette/LinearPalette.java deleted file mode 100644 index 0e17042ce..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/LinearPalette.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import java.util.List; -import java.util.concurrent.atomic.AtomicReferenceArray; - -public class LinearPalette implements Palette { - private final AtomicReferenceArray values; - private final PaletteResize resizeHandler; - private final int bits; - private int size; - - public LinearPalette(int var1, PaletteResize var2) { - this.values = new AtomicReferenceArray<>(1 << var1); - this.bits = var1; - this.resizeHandler = var2; - } - - public int idFor(T var0) { - int var1; - for(var1 = 0; var1 < size; var1++) { - if(values.get(var1) == null && var0 == null) { - return var1; - } - - if(values.get(var1) != null && values.get(var1).equals(var0)) { - return var1; - } - } - var1 = size; - if(var1 < values.length()) { - values.set(var1, var0); - size++; - return var1; - } - return resizeHandler.onResize(bits + 1, var0); - } - - public T valueFor(int var0) { - if(var0 >= 0 && var0 < size) { - return this.values.get(var0); - } - return null; - } - - public int getSize() { - return size; - } - - @Override - public void read(List fromList) { - for(int i = 0; i < fromList.size(); i++) { - values.set(i, fromList.get(i)); - } - - size = fromList.size(); - } - - @Override - public void write(List toList) { - for(int i = 0; i < size; i++) { - T v = values.get(i); - toList.add(v); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/Mth.java b/src/main/java/com/volmit/iris/util/data/palette/Mth.java deleted file mode 100644 index a4aa6f132..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/Mth.java +++ /dev/null @@ -1,712 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import java.util.Random; -import java.util.UUID; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class Mth { - public static final float PI = 3.1415927F; - public static final float HALF_PI = 1.5707964F; - public static final float TWO_PI = 6.2831855F; - public static final float DEG_TO_RAD = 0.017453292F; - public static final float RAD_TO_DEG = 57.295776F; - public static final float EPSILON = 1.0E-5F; - public static final float SQRT_OF_TWO = sqrt(2.0F); - private static final int BIG_ENOUGH_INT = 1024; - private static final float BIG_ENOUGH_FLOAT = 1024.0F; - private static final long UUID_VERSION = 61440L; - private static final long UUID_VERSION_TYPE_4 = 16384L; - private static final long UUID_VARIANT = -4611686018427387904L; - private static final long UUID_VARIANT_2 = -9223372036854775808L; - private static final float SIN_SCALE = 10430.378F; - - private static final float[] SIN; - private static final Random RANDOM = new Random(); - private static final int[] MULTIPLY_DE_BRUIJN_BIT_POSITION = new int[] { - 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, - 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, - 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, - 10, 9}; - private static final double ONE_SIXTH = 0.16666666666666666D; - private static final int FRAC_EXP = 8; - private static final int LUT_SIZE = 257; - private static final double FRAC_BIAS = Double.longBitsToDouble(4805340802404319232L); - private static final double[] ASIN_TAB = new double[257]; - private static final double[] COS_TAB = new double[257]; - - static { - SIN = make(new float[65536], var0 -> { - for(int var1 = 0; var1 < var0.length; var1++) - var0[var1] = (float) Math.sin(var1 * Math.PI * 2.0D / 65536.0D); - }); - } - - static { - for(int var0 = 0; var0 < 257; var0++) { - double var1 = var0 / 256.0D; - double var3 = Math.asin(var1); - COS_TAB[var0] = Math.cos(var3); - ASIN_TAB[var0] = var3; - } - } - - public static T make(Supplier var0) { - return var0.get(); - } - - public static T make(T var0, Consumer var1) { - var1.accept(var0); - return var0; - } - - public static float sin(float var0) { - return SIN[(int) (var0 * 10430.378F) & 0xFFFF]; - } - - public static float cos(float var0) { - return SIN[(int) (var0 * 10430.378F + 16384.0F) & 0xFFFF]; - } - - public static float sqrt(float var0) { - return (float) Math.sqrt(var0); - } - - public static int floor(float var0) { - int var1 = (int) var0; - return (var0 < var1) ? (var1 - 1) : var1; - } - - public static int fastFloor(double var0) { - return (int) (var0 + 1024.0D) - 1024; - } - - public static int floor(double var0) { - int var2 = (int) var0; - return (var0 < var2) ? (var2 - 1) : var2; - } - - public static long lfloor(double var0) { - long var2 = (long) var0; - return (var0 < var2) ? (var2 - 1L) : var2; - } - - public static int absFloor(double var0) { - return (int) ((var0 >= 0.0D) ? var0 : (-var0 + 1.0D)); - } - - public static float abs(float var0) { - return Math.abs(var0); - } - - public static int abs(int var0) { - return Math.abs(var0); - } - - public static int ceil(float var0) { - int var1 = (int) var0; - return (var0 > var1) ? (var1 + 1) : var1; - } - - public static int ceil(double var0) { - int var2 = (int) var0; - return (var0 > var2) ? (var2 + 1) : var2; - } - - public static byte clamp(byte var0, byte var1, byte var2) { - if(var0 < var1) - return var1; - if(var0 > var2) - return var2; - return var0; - } - - public static int clamp(int var0, int var1, int var2) { - if(var0 < var1) - return var1; - if(var0 > var2) - return var2; - return var0; - } - - public static long clamp(long var0, long var2, long var4) { - if(var0 < var2) - return var2; - if(var0 > var4) - return var4; - return var0; - } - - public static float clamp(float var0, float var1, float var2) { - if(var0 < var1) - return var1; - if(var0 > var2) - return var2; - return var0; - } - - public static double clamp(double var0, double var2, double var4) { - if(var0 < var2) - return var2; - if(var0 > var4) - return var4; - return var0; - } - - public static double clampedLerp(double var0, double var2, double var4) { - if(var4 < 0.0D) - return var0; - if(var4 > 1.0D) - return var2; - return lerp(var4, var0, var2); - } - - public static float clampedLerp(float var0, float var1, float var2) { - if(var2 < 0.0F) - return var0; - if(var2 > 1.0F) - return var1; - return lerp(var2, var0, var1); - } - - public static double absMax(double var0, double var2) { - if(var0 < 0.0D) - var0 = -var0; - if(var2 < 0.0D) - var2 = -var2; - return (var0 > var2) ? var0 : var2; - } - - public static int intFloorDiv(int var0, int var1) { - return Math.floorDiv(var0, var1); - } - - public static int nextInt(Random var0, int var1, int var2) { - if(var1 >= var2) - return var1; - return var0.nextInt(var2 - var1 + 1) + var1; - } - - public static float nextFloat(Random var0, float var1, float var2) { - if(var1 >= var2) - return var1; - return var0.nextFloat() * (var2 - var1) + var1; - } - - public static double nextDouble(Random var0, double var1, double var3) { - if(var1 >= var3) - return var1; - return var0.nextDouble() * (var3 - var1) + var1; - } - - public static double average(long[] var0) { - long var1 = 0L; - for(long var6 : var0) - var1 += var6; - return var1 / var0.length; - } - - public static boolean equal(float var0, float var1) { - return (Math.abs(var1 - var0) < 1.0E-5F); - } - - public static boolean equal(double var0, double var2) { - return (Math.abs(var2 - var0) < 9.999999747378752E-6D); - } - - public static int positiveModulo(int var0, int var1) { - return Math.floorMod(var0, var1); - } - - public static float positiveModulo(float var0, float var1) { - return (var0 % var1 + var1) % var1; - } - - public static double positiveModulo(double var0, double var2) { - return (var0 % var2 + var2) % var2; - } - - public static int wrapDegrees(int var0) { - int var1 = var0 % 360; - if(var1 >= 180) - var1 -= 360; - if(var1 < -180) - var1 += 360; - return var1; - } - - public static float wrapDegrees(float var0) { - float var1 = var0 % 360.0F; - if(var1 >= 180.0F) - var1 -= 360.0F; - if(var1 < -180.0F) - var1 += 360.0F; - return var1; - } - - public static double wrapDegrees(double var0) { - double var2 = var0 % 360.0D; - if(var2 >= 180.0D) - var2 -= 360.0D; - if(var2 < -180.0D) - var2 += 360.0D; - return var2; - } - - public static float degreesDifference(float var0, float var1) { - return wrapDegrees(var1 - var0); - } - - public static float degreesDifferenceAbs(float var0, float var1) { - return abs(degreesDifference(var0, var1)); - } - - public static float rotateIfNecessary(float var0, float var1, float var2) { - float var3 = degreesDifference(var0, var1); - float var4 = clamp(var3, -var2, var2); - return var1 - var4; - } - - public static float approach(float var0, float var1, float var2) { - var2 = abs(var2); - if(var0 < var1) - return clamp(var0 + var2, var0, var1); - return clamp(var0 - var2, var1, var0); - } - - public static float approachDegrees(float var0, float var1, float var2) { - float var3 = degreesDifference(var0, var1); - return approach(var0, var0 + var3, var2); - } - - public static int getInt(String var0, int var1) { - return Integer.valueOf(var0, var1); - } - - public static int getInt(String var0, int var1, int var2) { - return Math.max(var2, getInt(var0, var1)); - } - - public static double getDouble(String var0, double var1) { - try { - return Double.parseDouble(var0); - } catch(Throwable var3) { - return var1; - } - } - - public static double getDouble(String var0, double var1, double var3) { - return Math.max(var3, getDouble(var0, var1)); - } - - public static int smallestEncompassingPowerOfTwo(int var0) { - int var1 = var0 - 1; - var1 |= var1 >> 1; - var1 |= var1 >> 2; - var1 |= var1 >> 4; - var1 |= var1 >> 8; - var1 |= var1 >> 16; - return var1 + 1; - } - - public static boolean isPowerOfTwo(int var0) { - return (var0 != 0 && (var0 & var0 - 1) == 0); - } - - public static int ceillog2(int var0) { - var0 = isPowerOfTwo(var0) ? var0 : smallestEncompassingPowerOfTwo(var0); - return MULTIPLY_DE_BRUIJN_BIT_POSITION[(int) (var0 * 125613361L >> 27L) & 0x1F]; - } - - public static int log2(int var0) { - return ceillog2(var0) - (isPowerOfTwo(var0) ? 0 : 1); - } - - public static int color(float var0, float var1, float var2) { - return color(floor(var0 * 255.0F), floor(var1 * 255.0F), floor(var2 * 255.0F)); - } - - public static int color(int var0, int var1, int var2) { - int var3 = var0; - var3 = (var3 << 8) + var1; - var3 = (var3 << 8) + var2; - return var3; - } - - public static int colorMultiply(int var0, int var1) { - int var2 = (var0 & 0xFF0000) >> 16; - int var3 = (var1 & 0xFF0000) >> 16; - int var4 = (var0 & 0xFF00) >> 8; - int var5 = (var1 & 0xFF00) >> 8; - int var6 = (var0 & 0xFF); - int var7 = (var1 & 0xFF); - int var8 = (int) (var2 * var3 / 255.0F); - int var9 = (int) (var4 * var5 / 255.0F); - int var10 = (int) (var6 * var7 / 255.0F); - return var0 & 0xFF000000 | var8 << 16 | var9 << 8 | var10; - } - - public static int colorMultiply(int var0, float var1, float var2, float var3) { - int var4 = (var0 & 0xFF0000) >> 16; - int var5 = (var0 & 0xFF00) >> 8; - int var6 = (var0 & 0xFF); - int var7 = (int) (var4 * var1); - int var8 = (int) (var5 * var2); - int var9 = (int) (var6 * var3); - return var0 & 0xFF000000 | var7 << 16 | var8 << 8 | var9; - } - - public static float frac(float var0) { - return var0 - floor(var0); - } - - public static double frac(double var0) { - return var0 - lfloor(var0); - } - - public static long getSeed(int var0, int var1, int var2) { - long var3 = (var0 * 3129871) ^ var2 * 116129781L ^ var1; - var3 = var3 * var3 * 42317861L + var3 * 11L; - return var3 >> 16L; - } - - public static UUID createInsecureUUID(Random var0) { - long var1 = var0.nextLong() & 0xFFFFFFFFFFFF0FFFL | 0x4000L; - long var3 = var0.nextLong() & 0x3FFFFFFFFFFFFFFFL | Long.MIN_VALUE; - return new UUID(var1, var3); - } - - public static UUID createInsecureUUID() { - return createInsecureUUID(RANDOM); - } - - public static double inverseLerp(double var0, double var2, double var4) { - return (var0 - var2) / (var4 - var2); - } - - public static double atan2(double var0, double var2) { - double var4 = var2 * var2 + var0 * var0; - if(Double.isNaN(var4)) - return Double.NaN; - boolean var6 = (var0 < 0.0D); - if(var6) - var0 = -var0; - boolean var7 = (var2 < 0.0D); - if(var7) - var2 = -var2; - boolean var8 = (var0 > var2); - if(var8) { - double d = var2; - var2 = var0; - var0 = d; - } - double var9 = fastInvSqrt(var4); - var2 *= var9; - var0 *= var9; - double var11 = FRAC_BIAS + var0; - int var13 = (int) Double.doubleToRawLongBits(var11); - double var14 = ASIN_TAB[var13]; - double var16 = COS_TAB[var13]; - double var18 = var11 - FRAC_BIAS; - double var20 = var0 * var16 - var2 * var18; - double var22 = (6.0D + var20 * var20) * var20 * 0.16666666666666666D; - double var24 = var14 + var22; - if(var8) - var24 = 1.5707963267948966D - var24; - if(var7) - var24 = Math.PI - var24; - if(var6) - var24 = -var24; - return var24; - } - - public static float fastInvSqrt(float var0) { - float var1 = 0.5F * var0; - int var2 = Float.floatToIntBits(var0); - var2 = 1597463007 - (var2 >> 1); - var0 = Float.intBitsToFloat(var2); - var0 *= 1.5F - var1 * var0 * var0; - return var0; - } - - public static double fastInvSqrt(double var0) { - double var2 = 0.5D * var0; - long var4 = Double.doubleToRawLongBits(var0); - var4 = 6910469410427058090L - (var4 >> 1L); - var0 = Double.longBitsToDouble(var4); - var0 *= 1.5D - var2 * var0 * var0; - return var0; - } - - public static float fastInvCubeRoot(float var0) { - int var1 = Float.floatToIntBits(var0); - var1 = 1419967116 - var1 / 3; - float var2 = Float.intBitsToFloat(var1); - var2 = 0.6666667F * var2 + 1.0F / 3.0F * var2 * var2 * var0; - var2 = 0.6666667F * var2 + 1.0F / 3.0F * var2 * var2 * var0; - return var2; - } - - public static int hsvToRgb(float var0, float var1, float var2) { - float var8, var9, var10; - int var11, var12, var13, var3 = (int) (var0 * 6.0F) % 6; - float var4 = var0 * 6.0F - var3; - float var5 = var2 * (1.0F - var1); - float var6 = var2 * (1.0F - var4 * var1); - float var7 = var2 * (1.0F - (1.0F - var4) * var1); - switch(var3) { - case 0: - var8 = var2; - var9 = var7; - var10 = var5; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 1: - var8 = var6; - var9 = var2; - var10 = var5; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 2: - var8 = var5; - var9 = var2; - var10 = var7; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 3: - var8 = var5; - var9 = var6; - var10 = var2; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 4: - var8 = var7; - var9 = var5; - var10 = var2; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 5: - var8 = var2; - var9 = var5; - var10 = var6; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - } - throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + var0 + ", " + var1 + ", " + var2); - } - - public static int murmurHash3Mixer(int var0) { - var0 ^= var0 >>> 16; - var0 *= -2048144789; - var0 ^= var0 >>> 13; - var0 *= -1028477387; - var0 ^= var0 >>> 16; - return var0; - } - - public static long murmurHash3Mixer(long var0) { - var0 ^= var0 >>> 33L; - var0 *= -49064778989728563L; - var0 ^= var0 >>> 33L; - var0 *= -4265267296055464877L; - var0 ^= var0 >>> 33L; - return var0; - } - - public static double[] cumulativeSum(double... var0) { - float var1 = 0.0F; - for(double var5 : var0) - var1 = (float) (var1 + var5); - int var2; - for(var2 = 0; var2 < var0.length; var2++) - var0[var2] = var0[var2] / var1; - for(var2 = 0; var2 < var0.length; var2++) - var0[var2] = ((var2 == 0) ? 0.0D : var0[var2 - 1]) + var0[var2]; - return var0; - } - - public static int getRandomForDistributionIntegral(Random var0, double[] var1) { - double var2 = var0.nextDouble(); - for(int var4 = 0; var4 < var1.length; var4++) { - if(var2 < var1[var4]) - return var4; - } - return var1.length; - } - - public static double[] binNormalDistribution(double var0, double var2, double var4, int var6, int var7) { - double[] var8 = new double[var7 - var6 + 1]; - int var9 = 0; - for(int var10 = var6; var10 <= var7; var10++) { - var8[var9] = Math.max(0.0D, var0 * - - StrictMath.exp(-(var10 - var4) * (var10 - var4) / 2.0D * var2 * var2)); - var9++; - } - return var8; - } - - public static double[] binBiModalNormalDistribution(double var0, double var2, double var4, double var6, double var8, double var10, int var12, int var13) { - double[] var14 = new double[var13 - var12 + 1]; - int var15 = 0; - for(int var16 = var12; var16 <= var13; var16++) { - var14[var15] = Math.max(0.0D, var0 * - - StrictMath.exp(-(var16 - var4) * (var16 - var4) / 2.0D * var2 * var2) + var6 * - StrictMath.exp(-(var16 - var10) * (var16 - var10) / 2.0D * var8 * var8)); - var15++; - } - return var14; - } - - public static double[] binLogDistribution(double var0, double var2, int var4, int var5) { - double[] var6 = new double[var5 - var4 + 1]; - int var7 = 0; - for(int var8 = var4; var8 <= var5; var8++) { - var6[var7] = Math.max(var0 * StrictMath.log(var8) + var2, 0.0D); - var7++; - } - return var6; - } - - public static float lerp(float var0, float var1, float var2) { - return var1 + var0 * (var2 - var1); - } - - public static double lerp(double var0, double var2, double var4) { - return var2 + var0 * (var4 - var2); - } - - public static double lerp2(double var0, double var2, double var4, double var6, double var8, double var10) { - return lerp(var2, - - lerp(var0, var4, var6), - lerp(var0, var8, var10)); - } - - public static double lerp3(double var0, double var2, double var4, double var6, double var8, double var10, double var12, double var14, double var16, double var18, double var20) { - return lerp(var4, - - lerp2(var0, var2, var6, var8, var10, var12), - lerp2(var0, var2, var14, var16, var18, var20)); - } - - public static double smoothstep(double var0) { - return var0 * var0 * var0 * (var0 * (var0 * 6.0D - 15.0D) + 10.0D); - } - - public static double smoothstepDerivative(double var0) { - return 30.0D * var0 * var0 * (var0 - 1.0D) * (var0 - 1.0D); - } - - public static int sign(double var0) { - if(var0 == 0.0D) - return 0; - return (var0 > 0.0D) ? 1 : -1; - } - - public static float rotLerp(float var0, float var1, float var2) { - return var1 + var0 * wrapDegrees(var2 - var1); - } - - public static float diffuseLight(float var0, float var1, float var2) { - return Math.min(var0 * var0 * 0.6F + var1 * var1 * (3.0F + var1) / 4.0F + var2 * var2 * 0.8F, 1.0F); - } - - @Deprecated - public static float rotlerp(float var0, float var1, float var2) { - float var3 = var1 - var0; - while(var3 < -180.0F) - var3 += 360.0F; - while(var3 >= 180.0F) - var3 -= 360.0F; - return var0 + var2 * var3; - } - - @Deprecated - public static float rotWrap(double var0) { - while(var0 >= 180.0D) - var0 -= 360.0D; - while(var0 < -180.0D) - var0 += 360.0D; - return (float) var0; - } - - public static float triangleWave(float var0, float var1) { - return (Math.abs(var0 % var1 - var1 * 0.5F) - var1 * 0.25F) / var1 * 0.25F; - } - - public static float square(float var0) { - return var0 * var0; - } - - public static double square(double var0) { - return var0 * var0; - } - - public static int square(int var0) { - return var0 * var0; - } - - public static double clampedMap(double var0, double var2, double var4, double var6, double var8) { - return clampedLerp(var6, var8, inverseLerp(var0, var2, var4)); - } - - public static double map(double var0, double var2, double var4, double var6, double var8) { - return lerp(inverseLerp(var0, var2, var4), var6, var8); - } - - public static double wobble(double var0) { - return var0 + (2.0D * (new Random(floor(var0 * 3000.0D))).nextDouble() - 1.0D) * 1.0E-7D / 2.0D; - } - - public static int roundToward(int var0, int var1) { - return (var0 + var1 - 1) / var1 * var1; - } - - public static int randomBetweenInclusive(Random var0, int var1, int var2) { - return var0.nextInt(var2 - var1 + 1) + var1; - } - - public static float randomBetween(Random var0, float var1, float var2) { - return var0.nextFloat() * (var2 - var1) + var1; - } - - public static float normal(Random var0, float var1, float var2) { - return var1 + (float) var0.nextGaussian() * var2; - } - - public static double length(int var0, double var1, int var3) { - return Math.sqrt((var0 * var0) + var1 * var1 + (var3 * var3)); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/palette/Palette.java b/src/main/java/com/volmit/iris/util/data/palette/Palette.java deleted file mode 100644 index 27c8d4407..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/Palette.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import java.util.List; - -public interface Palette { - int idFor(T paramT); - - T valueFor(int paramInt); - - int getSize(); - - void read(List fromList); - - void write(List toList); -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/PaletteAccess.java b/src/main/java/com/volmit/iris/util/data/palette/PaletteAccess.java deleted file mode 100644 index b860edb21..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/PaletteAccess.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import com.volmit.iris.util.nbt.tag.CompoundTag; - -public interface PaletteAccess { - void setBlock(int x, int y, int z, CompoundTag data); - - CompoundTag getBlock(int x, int y, int z); - - void writeToSection(CompoundTag tag); - - void readFromSection(CompoundTag tag); -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/PaletteResize.java b/src/main/java/com/volmit/iris/util/data/palette/PaletteResize.java deleted file mode 100644 index b4fcade1b..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/PaletteResize.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -interface PaletteResize { - int onResize(int paramInt, T paramT); -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/PaletteType.java b/src/main/java/com/volmit/iris/util/data/palette/PaletteType.java deleted file mode 100644 index d228f49b0..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/PaletteType.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import com.volmit.iris.util.data.Varint; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -public interface PaletteType { - void writePaletteNode(DataOutputStream dos, T t) throws IOException; - - T readPaletteNode(DataInputStream din) throws IOException; - - default void writeList(DataOutputStream dos, List list) throws IOException { - Varint.writeUnsignedVarInt(list.size(), dos); - for(T i : list) { - writePaletteNode(dos, i); - } - } - - default List readList(DataInputStream din) throws IOException { - int v = Varint.readUnsignedVarInt(din); - List t = new ArrayList<>(); - - for(int i = 0; i < v; i++) { - t.add(readPaletteNode(din)); - } - - return t; - } -} diff --git a/src/main/java/com/volmit/iris/util/data/palette/PalettedContainer.java b/src/main/java/com/volmit/iris/util/data/palette/PalettedContainer.java deleted file mode 100644 index c44dd35ff..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/PalettedContainer.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.math.M; -import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; - -import java.util.List; - -public class PalettedContainer implements PaletteResize { - public static final int GLOBAL_PALETTE_BITS = 9; - public static final int MIN_PALETTE_SIZE = 4; - private static final int SIZE = 4096; - private final PaletteResize dummyPaletteResize = (var0, var1) -> 0; - protected BitStorage storage; - private Palette palette; - private int bits; - - public PalettedContainer() { - setBits(4); - } - - private static int getIndex(int var0, int var1, int var2) { - return var1 << 8 | var2 << 4 | var0; - } - - private void setBits(int var0) { - if(var0 == this.bits) { - return; - } - this.bits = var0; - if(this.bits <= 4) { - this.bits = 4; - this.palette = new LinearPalette<>(this.bits, this); - } else { - this.palette = new HashMapPalette<>(this.bits, this); - } - - this.palette.idFor(null); - this.storage = new BitStorage(this.bits, 4096); - } - - public int onResize(int var0, T var1) { - BitStorage var2 = this.storage; - Palette var3 = this.palette; - setBits(var0); - for(int var4 = 0; var4 < var2.getSize(); var4++) { - T var5 = var3.valueFor(var2.get(var4)); - if(var5 != null) { - set(var4, var5); - } - } - - return this.palette.idFor(var1); - } - - public T getAndSet(int var0, int var1, int var2, T var3) { - return getAndSet(getIndex(var0, var1, var2), var3); - } - - public T getAndSetUnchecked(int var0, int var1, int var2, T var3) { - return getAndSet(getIndex(var0, var1, var2), var3); - } - - private T getAndSet(int var0, T var1) { - int var2 = this.palette.idFor(var1); - int var3 = this.storage.getAndSet(var0, var2); - return this.palette.valueFor(var3); - } - - public void set(int var0, int var1, int var2, T var3) { - set(getIndex(var0, var1, var2), var3); - } - - private void set(int var0, T var1) { - int var2 = this.palette.idFor(var1); - - if(M.r(0.003)) { - Iris.info("ID for " + var1 + " is " + var2 + " Palette: " + palette.getSize()); - } - - this.storage.set(var0, var2); - } - - public T get(int var0, int var1, int var2) { - return get(getIndex(var0, var1, var2)); - } - - protected T get(int var0) { - return this.palette.valueFor(this.storage.get(var0)); - } - - public void read(List palette, long[] data) { - int var2 = Math.max(4, Mth.ceillog2(palette.size())); - if(var2 != this.bits) { - setBits(var2); - } - - this.palette.read(palette); - int var3 = data.length * 64 / 4096; - if(var3 == this.bits) { - System.arraycopy(data, 0, this.storage.getRaw(), 0, data.length); - } else { - BitStorage var4 = new BitStorage(var3, 4096, data); - for(int var5 = 0; var5 < 4096; var5++) { - this.storage.set(var5, var4.get(var5)); - } - } - } - - public long[] write(List toList) { - HashMapPalette var3 = new HashMapPalette<>(this.bits, this.dummyPaletteResize); - T var4 = null; - int var5 = 0; - int[] var6 = new int[4096]; - for(int i = 0; i < 4096; i++) { - T t = get(i); - if(t != var4) { - var4 = t; - var5 = var3.idFor(t); - } - var6[i] = var5; - } - - var3.write(toList); - int var8 = Math.max(4, Mth.ceillog2(toList.size())); - BitStorage var9 = new BitStorage(var8, 4096); - for(int var10 = 0; var10 < var6.length; var10++) { - var9.set(var10, var6[var10]); - } - return var9.getRaw(); - } - - public void count(CountConsumer var0) { - Int2IntOpenHashMap int2IntOpenHashMap = new Int2IntOpenHashMap(); - this.storage.getAll(var1 -> int2IntOpenHashMap.put(var1, int2IntOpenHashMap.get(var1) + 1)); - int2IntOpenHashMap.int2IntEntrySet().forEach(var1 -> var0.accept(this.palette.valueFor(var1.getIntKey()), var1.getIntValue())); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/data/palette/QuartPos.java b/src/main/java/com/volmit/iris/util/data/palette/QuartPos.java deleted file mode 100644 index ca5cb8e45..000000000 --- a/src/main/java/com/volmit/iris/util/data/palette/QuartPos.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.data.palette; - -public final class QuartPos { - public static final int BITS = 2; - - public static final int SIZE = 4; - - private static final int SECTION_TO_QUARTS_BITS = 2; - - public static int fromBlock(int var0) { - return var0 >> 2; - } - - public static int toBlock(int var0) { - return var0 << 2; - } - - public static int fromSection(int var0) { - return var0 << 2; - } - - public static int toSection(int var0) { - return var0 >> 2; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/DecreeContext.java b/src/main/java/com/volmit/iris/util/decree/DecreeContext.java deleted file mode 100644 index 4a1ad0cfc..000000000 --- a/src/main/java/com/volmit/iris/util/decree/DecreeContext.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree; - -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.ChronoLatch; - -public class DecreeContext { - private static final ChronoLatch cl = new ChronoLatch(60000); - private static final KMap context = new KMap<>(); - - public static VolmitSender get() { - return context.get(Thread.currentThread()); - } - - public static void touch(VolmitSender c) { - synchronized(context) { - context.put(Thread.currentThread(), c); - - if(cl.flip()) { - for(Thread i : context.k()) { - if(!i.isAlive()) { - context.remove(i); - } - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/DecreeContextHandler.java b/src/main/java/com/volmit/iris/util/decree/DecreeContextHandler.java deleted file mode 100644 index db2074aab..000000000 --- a/src/main/java/com/volmit/iris/util/decree/DecreeContextHandler.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.plugin.VolmitSender; - -public interface DecreeContextHandler { - KMap, DecreeContextHandler> contextHandlers = buildContextHandlers(); - - static KMap, DecreeContextHandler> buildContextHandlers() { - KMap, DecreeContextHandler> contextHandlers = new KMap<>(); - - try { - Iris.initialize("com.volmit.iris.util.decree.context").forEach((i) - -> contextHandlers.put(((DecreeContextHandler) i).getType(), (DecreeContextHandler) i)); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return contextHandlers; - } - - Class getType(); - - T handle(VolmitSender sender); -} diff --git a/src/main/java/com/volmit/iris/util/decree/DecreeExecutor.java b/src/main/java/com/volmit/iris/util/decree/DecreeExecutor.java deleted file mode 100644 index 71f196396..000000000 --- a/src/main/java/com/volmit/iris/util/decree/DecreeExecutor.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree; - -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.platform.PlatformChunkGenerator; -import com.volmit.iris.util.plugin.VolmitSender; -import org.bukkit.World; -import org.bukkit.entity.Player; - -public interface DecreeExecutor { - default VolmitSender sender() { - return DecreeContext.get(); - } - - default Player player() { - return sender().player(); - } - - default Engine engine() { - if(sender().isPlayer() && IrisToolbelt.access(sender().player().getWorld()) != null) { - PlatformChunkGenerator gen = IrisToolbelt.access(sender().player().getWorld()); - if(gen != null) { - return gen.getEngine(); - } - } - - return null; - } - - default PlatformChunkGenerator access() { - if(sender().isPlayer()) { - return IrisToolbelt.access(world()); - } - return null; - } - - default World world() { - if(sender().isPlayer()) { - return sender().player().getWorld(); - } - return null; - } - - default T get(T v, T ifUndefined) { - return v == null ? ifUndefined : v; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/DecreeNode.java b/src/main/java/com/volmit/iris/util/decree/DecreeNode.java deleted file mode 100644 index d647b0cd2..000000000 --- a/src/main/java/com/volmit/iris/util/decree/DecreeNode.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.annotations.Param; -import lombok.Data; - -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -@Data -public class DecreeNode { - private final Method method; - private final Object instance; - private final Decree decree; - - public DecreeNode(Object instance, Method method) { - this.instance = instance; - this.method = method; - this.decree = method.getDeclaredAnnotation(Decree.class); - if(decree == null) { - throw new RuntimeException("Cannot instantiate DecreeNode on method " + method.getName() + " in " + method.getDeclaringClass().getCanonicalName() + " not annotated by @Decree"); - } - } - - /** - * Get the parameters of this decree node - * - * @return The list of parameters if ALL are annotated by @{@link Param}, else null - */ - public KList getParameters() { - KList required = new KList<>(); - KList optional = new KList<>(); - - for(Parameter i : method.getParameters()) { - DecreeParameter p = new DecreeParameter(i); - if(p.isRequired()) { - required.add(p); - } else { - optional.add(p); - } - } - - required.addAll(optional); - - return required; - } - - public String getName() { - return decree.name().isEmpty() ? method.getName() : decree.name(); - } - - public DecreeOrigin getOrigin() { - return decree.origin(); - } - - public String getDescription() { - return decree.description().isEmpty() ? Decree.DEFAULT_DESCRIPTION : decree.description(); - } - - public KList getNames() { - KList d = new KList<>(); - d.add(getName()); - - for(String i : decree.aliases()) { - if(i.isEmpty()) { - continue; - } - - d.add(i); - } - - - d.removeDuplicates(); - return d; - } - - public boolean isSync() { - return decree.sync(); - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/DecreeOrigin.java b/src/main/java/com/volmit/iris/util/decree/DecreeOrigin.java deleted file mode 100644 index 970414f4e..000000000 --- a/src/main/java/com/volmit/iris/util/decree/DecreeOrigin.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree; - -import com.volmit.iris.util.plugin.VolmitSender; - -public enum DecreeOrigin { - PLAYER, - CONSOLE, - /** - * Both the player and the console - */ - BOTH; - - /** - * Check if the origin is valid for a sender - * - * @param sender - * The sender to check - * @return True if valid for origin - */ - public boolean validFor(VolmitSender sender) { - if(sender.isPlayer()) { - return this.equals(PLAYER) || this.equals(BOTH); - } else { - return this.equals(CONSOLE) || this.equals(BOTH); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/DecreeParameter.java b/src/main/java/com/volmit/iris/util/decree/DecreeParameter.java deleted file mode 100644 index d35215490..000000000 --- a/src/main/java/com/volmit/iris/util/decree/DecreeParameter.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree; - -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.annotations.Param; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.decree.specialhandlers.DummyHandler; -import lombok.Data; - -import java.lang.reflect.Parameter; - -@Data -public class DecreeParameter { - private final Parameter parameter; - private final Param param; - private transient final AtomicCache> handlerCache = new AtomicCache<>(); - - public DecreeParameter(Parameter parameter) { - this.parameter = parameter; - this.param = parameter.getDeclaredAnnotation(Param.class); - if(param == null) { - throw new RuntimeException("Cannot instantiate DecreeParameter on " + parameter.getName() + " in method " + parameter.getDeclaringExecutable().getName() + "(...) in class " + parameter.getDeclaringExecutable().getDeclaringClass().getCanonicalName() + " not annotated by @Param"); - } - } - - public DecreeParameterHandler getHandler() { - return handlerCache.aquire(() -> { - try { - if(param.customHandler().equals(DummyHandler.class)) { - return DecreeSystem.getHandler(getType()); - } - - return param.customHandler().getConstructor().newInstance(); - } catch(Throwable e) { - e.printStackTrace(); - } - - return null; - }); - } - - public Class getType() { - return parameter.getType(); - } - - public String getName() { - return param.name().isEmpty() ? parameter.getName() : param.name(); - } - - public String getDescription() { - return param.description().isEmpty() ? Param.DEFAULT_DESCRIPTION : param.description(); - } - - public boolean isRequired() { - return !hasDefault(); - } - - public KList getNames() { - KList d = new KList<>(); - - for(String i : param.aliases()) { - if(i.isEmpty()) { - continue; - } - - d.add(i); - } - - d.add(getName()); - d.removeDuplicates(); - - return d; - } - - public Object getDefaultValue() throws DecreeParsingException { - return param.defaultValue().trim().isEmpty() ? null : getHandler().parse(param.defaultValue().trim(), true); - } - - public boolean hasDefault() { - return !param.defaultValue().trim().isEmpty(); - } - - public String example() { - KList ff = getHandler().getPossibilities(); - ff = ff != null ? ff : new KList<>(); - KList f = ff.convert((i) -> getHandler().toStringForce(i)); - if(f.isEmpty()) { - f = new KList<>(); - f.add(getHandler().getRandomDefault()); - } - - return f.getRandom(); - } - - public boolean isContextual() { - return param.contextual(); - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/DecreeParameterHandler.java b/src/main/java/com/volmit/iris/util/decree/DecreeParameterHandler.java deleted file mode 100644 index efe11b38d..000000000 --- a/src/main/java/com/volmit/iris/util/decree/DecreeParameterHandler.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.util.concurrent.atomic.AtomicReference; - -public interface DecreeParameterHandler { - /** - * Should return the possible values for this type - * - * @return Possibilities for this type. - */ - KList getPossibilities(); - - default boolean isDummy() { - return false; - } - - /** - * Converting the type back to a string (inverse of the {@link #parse(String) parse} method) - * - * @param t - * The input of the designated type to convert to a String - * @return The resulting string - */ - String toString(T t); - - /** - * Forces conversion to the designated type before converting to a string using {@link #toString(T t)} - * - * @param t - * The object to convert to string (that should be of this type) - * @return The resulting string. - */ - default String toStringForce(Object t) { - return toString((T) t); - } - - /** - * Should parse a String into the designated type - * - * @param in - * The string to parse - * @return The value extracted from the string, of the designated type - * @throws DecreeParsingException - * Thrown when the parsing fails (ex: "oop" translated to an integer throws this) - */ - default T parse(String in) throws DecreeParsingException { - return parse(in, false); - } - - /** - * Should parse a String into the designated type. You can force it to not throw a whichexception - * - * @param in - * The string to parse - * @param force - * force an option instead of throwing decreewhich - * @return The value extracted from the string, of the designated type - * @throws DecreeParsingException - * Thrown when the parsing fails (ex: "oop" translated to an integer throws this) - */ - T parse(String in, boolean force) throws DecreeParsingException; - - /** - * Returns whether a certain type is supported by this handler
- * - * @param type - * The type to check - * @return True if supported, false if not - */ - boolean supports(Class type); - - /** - * The possible entries for the inputted string (support for autocomplete on partial entries) - * - * @param input - * The inputted string to check against - * @return A {@link KList} of possibilities - */ - default KList getPossibilities(String input) { - if(input.trim().isEmpty()) { - KList f = getPossibilities(); - return f == null ? new KList<>() : f; - } - - input = input.trim(); - KList possible = getPossibilities(); - KList matches = new KList<>(); - - if(possible == null || possible.isEmpty()) { - return matches; - } - - if(input.isEmpty()) { - return getPossibilities(); - } - - KList converted = possible.convert(v -> toString(v).trim()); - - for(int i = 0; i < converted.size(); i++) { - String g = converted.get(i); - // if - // G == I or - // I in G or - // G in I - if(g.equalsIgnoreCase(input) || g.toLowerCase().contains(input.toLowerCase()) || input.toLowerCase().contains(g.toLowerCase())) { - matches.add(possible.get(i)); - } - } - - return matches; - } - - default String getRandomDefault() { - return "NOEXAMPLE"; - } - - default double getMultiplier(AtomicReference g) { - double multiplier = 1; - String in = g.get(); - boolean valid = true; - while(valid) { - boolean trim = false; - if(in.toLowerCase().endsWith("k")) { - multiplier *= 1000; - trim = true; - } else if(in.toLowerCase().endsWith("m")) { - multiplier *= 1000000; - trim = true; - } else if(in.toLowerCase().endsWith("h")) { - multiplier *= 100; - trim = true; - } else if(in.toLowerCase().endsWith("c")) { - multiplier *= 16; - trim = true; - } else if(in.toLowerCase().endsWith("r")) { - multiplier *= (16 * 32); - trim = true; - } else { - valid = false; - } - - if(trim) { - in = in.substring(0, in.length() - 1); - } - } - - g.set(in); - return multiplier; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/DecreeSystem.java b/src/main/java/com/volmit/iris/util/decree/DecreeSystem.java deleted file mode 100644 index fd869c46d..000000000 --- a/src/main/java/com/volmit/iris/util/decree/DecreeSystem.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.virtual.VirtualDecreeCommand; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Sound; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -public interface DecreeSystem extends CommandExecutor, TabCompleter { - KList> handlers = Iris.initialize("com.volmit.iris.util.decree.handlers", null).convert((i) -> (DecreeParameterHandler) i); - - static KList enhanceArgs(String[] args) { - return enhanceArgs(args, true); - } - - static KList enhanceArgs(String[] args, boolean trim) { - KList a = new KList<>(); - - if(args.length == 0) { - return a; - } - - StringBuilder flat = new StringBuilder(); - for(String i : args) { - if(trim) { - if(i.trim().isEmpty()) { - continue; - } - - flat.append(" ").append(i.trim()); - } else { - if(i.endsWith(" ")) { - flat.append(" ").append(i.trim()).append(" "); - } - } - } - - flat = new StringBuilder(flat.length() > 0 ? trim ? flat.toString().trim().length() > 0 ? flat.substring(1).trim() : flat.toString().trim() : flat.substring(1) : flat); - StringBuilder arg = new StringBuilder(); - boolean quoting = false; - - for(int x = 0; x < flat.length(); x++) { - char i = flat.charAt(x); - char j = x < flat.length() - 1 ? flat.charAt(x + 1) : i; - boolean hasNext = x < flat.length(); - - if(i == ' ' && !quoting) { - if(!arg.toString().trim().isEmpty() && trim) { - a.add(arg.toString().trim()); - arg = new StringBuilder(); - } - } else if(i == '"') { - if(!quoting && (arg.length() == 0)) { - quoting = true; - } else if(quoting) { - quoting = false; - - if(hasNext && j == ' ') { - if(!arg.toString().trim().isEmpty() && trim) { - a.add(arg.toString().trim()); - arg = new StringBuilder(); - } - } else if(!hasNext) { - if(!arg.toString().trim().isEmpty() && trim) { - a.add(arg.toString().trim()); - arg = new StringBuilder(); - } - } - } - } else { - arg.append(i); - } - } - - if(!arg.toString().trim().isEmpty() && trim) { - a.add(arg.toString().trim()); - } - - return a; - } - - /** - * Get the handler for the specified type - * - * @param type - * The type to handle - * @return The corresponding {@link DecreeParameterHandler}, or null - */ - static DecreeParameterHandler getHandler(Class type) { - for(DecreeParameterHandler i : handlers) { - if(i.supports(type)) { - return i; - } - } - Iris.error("Unhandled type in Decree Parameter: " + type.getName() + ". This is bad!"); - return null; - } - - /** - * The root class to start command searching from - */ - VirtualDecreeCommand getRoot(); - - default boolean call(VolmitSender sender, String[] args) { - DecreeContext.touch(sender); - return getRoot().invoke(sender, enhanceArgs(args)); - } - - @Nullable - @Override - default List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - KList enhanced = new KList<>(args); - KList v = getRoot().tabComplete(enhanced, enhanced.toString(" ")); - v.removeDuplicates(); - - if(sender instanceof Player) { - if(IrisSettings.get().getGeneral().isCommandSounds()) { - ((Player) sender).playSound(((Player) sender).getLocation(), Sound.BLOCK_AMETHYST_BLOCK_CHIME, 0.25f, RNG.r.f(0.125f, 1.95f)); - } - } - - return v; - } - - @Override - default boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if(!sender.hasPermission("iris.all")) { - sender.sendMessage("You lack the Permission 'iris.all'"); - return true; - } - - J.aBukkit(() -> { - if(!call(new VolmitSender(sender), args)) { - - if(IrisSettings.get().getGeneral().isCommandSounds()) { - if(sender instanceof Player) { - ((Player) sender).playSound(((Player) sender).getLocation(), Sound.BLOCK_AMETHYST_CLUSTER_BREAK, 0.77f, 0.25f); - ((Player) sender).playSound(((Player) sender).getLocation(), Sound.BLOCK_BEACON_DEACTIVATE, 0.2f, 0.45f); - } - } - - sender.sendMessage(C.RED + "Unknown Iris Command"); - } else { - if(IrisSettings.get().getGeneral().isCommandSounds()) { - if(sender instanceof Player) { - ((Player) sender).playSound(((Player) sender).getLocation(), Sound.BLOCK_AMETHYST_CLUSTER_BREAK, 0.77f, 1.65f); - ((Player) sender).playSound(((Player) sender).getLocation(), Sound.BLOCK_RESPAWN_ANCHOR_CHARGE, 0.125f, 2.99f); - } - } - } - }); - return true; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/annotations/Decree.java b/src/main/java/com/volmit/iris/util/decree/annotations/Decree.java deleted file mode 100644 index 37b6324ef..000000000 --- a/src/main/java/com/volmit/iris/util/decree/annotations/Decree.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.annotations; - -import com.volmit.iris.util.decree.DecreeOrigin; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -public @interface Decree { - - String DEFAULT_DESCRIPTION = "No Description Provided"; - - /** - * The name of this command, which is the Method's name by default - */ - String name() default ""; - - /** - * Only allow if studio mode is enabled - * - * @return defaults to false - */ - boolean studio() default false; - - /** - * If the node's functions MUST be run in sync, set this to true.
- * Defaults to false - */ - boolean sync() default false; - - /** - * The description of this command.
- * Is {@link #DEFAULT_DESCRIPTION} by default - */ - String description() default DEFAULT_DESCRIPTION; - - /** - * The origin this command must come from.
- * Must be elements of the {@link DecreeOrigin} enum
- * By default, is {@link DecreeOrigin#BOTH}, meaning both console & player can send the command - */ - DecreeOrigin origin() default DecreeOrigin.BOTH; - - /** - * The aliases of this parameter (instead of just the {@link #name() name} (if specified) or Method Name (name of - * method))
- * Can be initialized as just a string (ex. "alias") or as an array (ex. {"alias1", "alias2"})
- * If someone uses /plugin foo and you specify alias="f" here, /plugin f will do the exact same. - */ - String[] aliases() default ""; -} diff --git a/src/main/java/com/volmit/iris/util/decree/annotations/Param.java b/src/main/java/com/volmit/iris/util/decree/annotations/Param.java deleted file mode 100644 index 382cc42f3..000000000 --- a/src/main/java/com/volmit/iris/util/decree/annotations/Param.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.annotations; - -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.specialhandlers.DummyHandler; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.PARAMETER) -public @interface Param { - String DEFAULT_DESCRIPTION = "No Description Provided"; - - /** - * The main name of this command.
- * Required parameter.
- * This is what is used in game, alongside any (if specified) {@link #aliases() aliases} - */ - String name() default ""; - - /** - * The description of this parameter, used in help-popups in game.
- * The default value is {@link #DEFAULT_DESCRIPTION} - */ - String description() default DEFAULT_DESCRIPTION; - - /** - * The default value for this argument.
- * The entered string is parsed to the value similarly to how commandline-text would be.
- * Which indicates the variable MUST be defined by the person running the command.
- * If you define this, the variable automatically becomes non-required, but can still be set. - */ - String defaultValue() default ""; - - /** - * The aliases of this parameter (instead of just the {@link #name() name} (if specified) or Method Name (name of - * method))
- * Can be initialized as just a string (ex. "alias") or as an array (ex. {"alias1", "alias2"})
- * If someone uses /plugin foo bar=baz and you specify alias="b" here, /plugin foo b=baz will do the exact same. - */ - String[] aliases() default ""; - - /** - * Attempts to dynamically pull context from the player, default data or something else for supported types - */ - boolean contextual() default false; - - Class> customHandler() default DummyHandler.class; -} diff --git a/src/main/java/com/volmit/iris/util/decree/context/BiomeContextHandler.java b/src/main/java/com/volmit/iris/util/decree/context/BiomeContextHandler.java deleted file mode 100644 index d99502a9f..000000000 --- a/src/main/java/com/volmit/iris/util/decree/context/BiomeContextHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.context; - -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.util.decree.DecreeContextHandler; -import com.volmit.iris.util.plugin.VolmitSender; - -public class BiomeContextHandler implements DecreeContextHandler { - public Class getType() { - return IrisBiome.class; - } - - public IrisBiome handle(VolmitSender sender) { - if(sender.isPlayer() - && IrisToolbelt.isIrisWorld(sender.player().getWorld()) - && IrisToolbelt.access(sender.player().getWorld()).getEngine() != null) { - return IrisToolbelt.access(sender.player().getWorld()).getEngine().getBiomeOrMantle(sender.player().getLocation()); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/context/DimensionContextHandler.java b/src/main/java/com/volmit/iris/util/decree/context/DimensionContextHandler.java deleted file mode 100644 index efd52c31f..000000000 --- a/src/main/java/com/volmit/iris/util/decree/context/DimensionContextHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.context; - -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.util.decree.DecreeContextHandler; -import com.volmit.iris.util.plugin.VolmitSender; - -public class DimensionContextHandler implements DecreeContextHandler { - public Class getType() { - return IrisDimension.class; - } - - public IrisDimension handle(VolmitSender sender) { - if(sender.isPlayer() - && IrisToolbelt.isIrisWorld(sender.player().getWorld()) - && IrisToolbelt.access(sender.player().getWorld()).getEngine() != null) { - return IrisToolbelt.access(sender.player().getWorld()).getEngine().getDimension(); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/context/GeneratorContextHandler.java b/src/main/java/com/volmit/iris/util/decree/context/GeneratorContextHandler.java deleted file mode 100644 index fd09da671..000000000 --- a/src/main/java/com/volmit/iris/util/decree/context/GeneratorContextHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.context; - -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IrisGenerator; -import com.volmit.iris.util.decree.DecreeContextHandler; -import com.volmit.iris.util.plugin.VolmitSender; - -public class GeneratorContextHandler implements DecreeContextHandler { - @Override - public Class getType() { - return IrisGenerator.class; - } - - @Override - public IrisGenerator handle(VolmitSender sender) { - if(sender.isPlayer() - && IrisToolbelt.isIrisWorld(sender.player().getWorld()) - && IrisToolbelt.access(sender.player().getWorld()).getEngine() != null) { - Engine engine = IrisToolbelt.access(sender.player().getWorld()).getEngine(); - return engine.getData().getGeneratorLoader().load(engine.getBiome(sender.player().getLocation()).getGenerators().getRandom().getGenerator()); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/context/RegionContextHandler.java b/src/main/java/com/volmit/iris/util/decree/context/RegionContextHandler.java deleted file mode 100644 index 5ca3b7f97..000000000 --- a/src/main/java/com/volmit/iris/util/decree/context/RegionContextHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.context; - -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.decree.DecreeContextHandler; -import com.volmit.iris.util.plugin.VolmitSender; - -public class RegionContextHandler implements DecreeContextHandler { - public Class getType() { - return IrisRegion.class; - } - - public IrisRegion handle(VolmitSender sender) { - if(sender.isPlayer() - && IrisToolbelt.isIrisWorld(sender.player().getWorld()) - && IrisToolbelt.access(sender.player().getWorld()).getEngine() != null) { - return IrisToolbelt.access(sender.player().getWorld()).getEngine().getRegion(sender.player().getLocation()); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/context/WorldContextHandler.java b/src/main/java/com/volmit/iris/util/decree/context/WorldContextHandler.java deleted file mode 100644 index f340b716d..000000000 --- a/src/main/java/com/volmit/iris/util/decree/context/WorldContextHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.context; - -import com.volmit.iris.util.decree.DecreeContextHandler; -import com.volmit.iris.util.plugin.VolmitSender; -import org.bukkit.World; - -public class WorldContextHandler implements DecreeContextHandler { - public Class getType() { - return World.class; - } - - public World handle(VolmitSender sender) { - return sender.isPlayer() ? sender.player().getWorld() : null; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/exceptions/DecreeParsingException.java b/src/main/java/com/volmit/iris/util/decree/exceptions/DecreeParsingException.java deleted file mode 100644 index 01c02c231..000000000 --- a/src/main/java/com/volmit/iris/util/decree/exceptions/DecreeParsingException.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.exceptions; - -/** - * Thrown when a decree parameter is parsed, but parsing fails - */ -public class DecreeParsingException extends Exception { - public DecreeParsingException(String message) { - super(message); - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/BiomeHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/BiomeHandler.java deleted file mode 100644 index 64d7635cd..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/BiomeHandler.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisBiome; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class BiomeHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisBiome j : data.getBiomeLoader().loadAll(data.getBiomeLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisBiome dim) { - return dim.getLoadKey(); - } - - @Override - public IrisBiome parse(String in, boolean force) throws DecreeParsingException { - if(in.equals("null")) { - return null; - } - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Biome \"" + in + "\""); - } - - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisBiome.class); - } - - @Override - public String getRandomDefault() { - return "biome"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/BlockVectorHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/BlockVectorHandler.java deleted file mode 100644 index f456161e9..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/BlockVectorHandler.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeContext; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.DecreeSystem; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.plugin.VolmitSender; -import org.bukkit.FluidCollisionMode; -import org.bukkit.entity.Player; -import org.bukkit.util.BlockVector; - -public class BlockVectorHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KList vx = new KList<>(); - VolmitSender s = DecreeContext.get(); - - if(s.isPlayer()) { - vx.add(s.player().getLocation().toVector().toBlockVector()); - } - - return vx; - } - - @Override - public String toString(BlockVector v) { - if(v.getY() == 0) { - return Form.f(v.getBlockX(), 2) + "," + Form.f(v.getBlockZ(), 2); - } - - return Form.f(v.getBlockX(), 2) + "," + Form.f(v.getBlockY(), 2) + "," + Form.f(v.getBlockZ(), 2); - } - - @Override - public BlockVector parse(String in, boolean force) throws DecreeParsingException { - try { - if(in.contains(",")) { - String[] comp = in.split("\\Q,\\E"); - - if(comp.length == 2) { - return new BlockVector(Integer.parseInt(comp[0].trim()), 0, Integer.parseInt(comp[1].trim())); - } else if(comp.length == 3) { - return new BlockVector(Integer.parseInt(comp[0].trim()), - Integer.parseInt(comp[1].trim()), - Integer.parseInt(comp[2].trim())); - } else { - throw new DecreeParsingException("Could not parse components for vector. You have " + comp.length + " components. Expected 2 or 3."); - } - } else if(in.equalsIgnoreCase("here") || in.equalsIgnoreCase("me") || in.equalsIgnoreCase("self")) { - if(!DecreeContext.get().isPlayer()) { - throw new DecreeParsingException("You cannot specify me,self,here as a console."); - } - - return DecreeContext.get().player().getLocation().toVector().toBlockVector(); - } else if(in.equalsIgnoreCase("look") || in.equalsIgnoreCase("cursor") || in.equalsIgnoreCase("crosshair")) { - if(!DecreeContext.get().isPlayer()) { - throw new DecreeParsingException("You cannot specify look,cursor,crosshair as a console."); - } - - return DecreeContext.get().player().getTargetBlockExact(256, FluidCollisionMode.NEVER).getLocation().toVector().toBlockVector(); - } else if(in.trim().toLowerCase().startsWith("player:")) { - String v = in.trim().split("\\Q:\\E")[1]; - - - KList px = DecreeSystem.getHandler(Player.class).getPossibilities(v); - - if(px != null && px.isNotEmpty()) { - return ((Player) px.get(0)).getLocation().toVector().toBlockVector(); - } else if(px == null || px.isEmpty()) { - throw new DecreeParsingException("Cannot find player: " + v); - } - } - } catch(Throwable e) { - throw new DecreeParsingException("Unable to get Vector for \"" + in + "\" because of an uncaught exception: " + e); - } - - return null; - } - - @Override - public boolean supports(Class type) { - return type.equals(BlockVector.class); - } - - @Override - public String getRandomDefault() { - return M.r(0.5) ? "0,0" : "0,0,0"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/BooleanHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/BooleanHandler.java deleted file mode 100644 index 9a6355b17..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/BooleanHandler.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.math.M; - -public class BooleanHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - @Override - public String toString(Boolean aByte) { - return aByte.toString(); - } - - @Override - public Boolean parse(String in, boolean force) throws DecreeParsingException { - try { - if(in.equals("null") || in.equals("other") || in.equals("flip")) { - return null; - } - return Boolean.parseBoolean(in); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to parse boolean \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(Boolean.class) || type.equals(boolean.class); - } - - @Override - public String getRandomDefault() { - return M.r(0.5) + ""; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/ByteHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/ByteHandler.java deleted file mode 100644 index 41f9ce831..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/ByteHandler.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.math.RNG; - -public class ByteHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - @Override - public String toString(Byte aByte) { - return aByte.toString(); - } - - @Override - public Byte parse(String in, boolean force) throws DecreeParsingException { - try { - return Byte.parseByte(in); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to parse byte \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(Byte.class) || type.equals(byte.class); - } - - @Override - public String getRandomDefault() { - return RNG.r.i(0, Byte.MAX_VALUE) + ""; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/CaveHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/CaveHandler.java deleted file mode 100644 index 62a02be1c..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/CaveHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisCave; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class CaveHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisCave j : data.getCaveLoader().loadAll(data.getCaveLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisCave dim) { - return dim.getLoadKey(); - } - - @Override - public IrisCave parse(String in, boolean force) throws DecreeParsingException { - if(in.equals("null")) { - return null; - } - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Cave \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Cave\"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisCave.class); - } - - @Override - public String getRandomDefault() { - return "cave"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/DimensionHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/DimensionHandler.java deleted file mode 100644 index 3b073a51f..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/DimensionHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisDimension; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class DimensionHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisDimension j : data.getDimensionLoader().loadAll(data.getDimensionLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisDimension dim) { - return dim.getLoadKey(); - } - - @Override - public IrisDimension parse(String in, boolean force) throws DecreeParsingException { - - if(in.equalsIgnoreCase("default")) { - return parse(IrisSettings.get().getGenerator().getDefaultWorldType()); - } - - KList options = getPossibilities(in); - - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Dimension \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).toList().get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisDimension.class); - } - - @Override - public String getRandomDefault() { - return "dimension"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/DoubleHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/DoubleHandler.java deleted file mode 100644 index 85974e35d..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/DoubleHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.RNG; - -import java.util.concurrent.atomic.AtomicReference; - -public class DoubleHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - @Override - public Double parse(String in, boolean force) throws DecreeParsingException { - try { - AtomicReference r = new AtomicReference<>(in); - double m = getMultiplier(r); - return Double.parseDouble(r.get()) * m; - } catch(Throwable e) { - throw new DecreeParsingException("Unable to parse double \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(Double.class) || type.equals(double.class); - } - - @Override - public String toString(Double f) { - return f.toString(); - } - - @Override - public String getRandomDefault() { - return Form.f(RNG.r.d(0, 99.99), 1) + ""; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/EntityHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/EntityHandler.java deleted file mode 100644 index e1ba7bd65..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/EntityHandler.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisEntity; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class EntityHandler implements DecreeParameterHandler { - - /** - * Should return the possible values for this type - * - * @return Possibilities for this type. - */ - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisEntity j : data.getEntityLoader().loadAll(data.getEntityLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - /** - * Converting the type back to a string (inverse of the {@link #parse(String) parse} method) - * - * @param entity - * The input of the designated type to convert to a String - * @return The resulting string - */ - @Override - public String toString(IrisEntity entity) { - return entity.getLoadKey(); - } - - /** - * Should parse a String into the designated type - * - * @param in - * The string to parse - * @return The value extracted from the string, of the designated type - * @throws DecreeParsingException - * Thrown when the parsing fails (ex: "oop" translated to an integer throws this) - */ - @Override - public IrisEntity parse(String in, boolean force) throws DecreeParsingException { - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Entity \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - /** - * Returns whether a certain type is supported by this handler
- * - * @param type - * The type to check - * @return True if supported, false if not - */ - @Override - public boolean supports(Class type) { - return type.equals(IrisEntity.class); - } - - @Override - public String getRandomDefault() { - return "entity"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/FloatHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/FloatHandler.java deleted file mode 100644 index f64771ad2..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/FloatHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.RNG; - -import java.util.concurrent.atomic.AtomicReference; - -public class FloatHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - @Override - public Float parse(String in, boolean force) throws DecreeParsingException { - try { - AtomicReference r = new AtomicReference<>(in); - double m = getMultiplier(r); - return (float) (Float.parseFloat(r.get()) * m); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to parse float \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(Float.class) || type.equals(float.class); - } - - @Override - public String toString(Float f) { - return f.toString(); - } - - @Override - public String getRandomDefault() { - return Form.f(RNG.r.d(0, 99.99), 1) + ""; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/GeneratorHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/GeneratorHandler.java deleted file mode 100644 index 56590128e..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/GeneratorHandler.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisGenerator; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class GeneratorHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisGenerator j : data.getGeneratorLoader().loadAll(data.getGeneratorLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisGenerator gen) { - return gen.getLoadKey(); - } - - @Override - public IrisGenerator parse(String in, boolean force) throws DecreeParsingException { - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Generator \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisGenerator.class); - } - - @Override - public String getRandomDefault() { - return "generator"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/IntegerHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/IntegerHandler.java deleted file mode 100644 index 477242ad9..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/IntegerHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.math.RNG; - -import java.util.concurrent.atomic.AtomicReference; - -public class IntegerHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - @Override - public Integer parse(String in, boolean force) throws DecreeParsingException { - try { - AtomicReference r = new AtomicReference<>(in); - double m = getMultiplier(r); - return (int) (Integer.valueOf(r.get()).doubleValue() * m); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to parse integer \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(Integer.class) || type.equals(int.class); - } - - @Override - public String toString(Integer f) { - return f.toString(); - } - - @Override - public String getRandomDefault() { - return RNG.r.i(0, 99) + ""; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/JigsawPieceHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/JigsawPieceHandler.java deleted file mode 100644 index 06f84f920..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/JigsawPieceHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisJigsawPiece; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class JigsawPieceHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisJigsawPiece j : data.getJigsawPieceLoader().loadAll(data.getJigsawPieceLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisJigsawPiece dim) { - return dim.getLoadKey(); - } - - @Override - public IrisJigsawPiece parse(String in, boolean force) throws DecreeParsingException { - if(in.equals("null")) { - return null; - } - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Jigsaw Piece \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Jigsaw Piece \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisJigsawPiece.class); - } - - @Override - public String getRandomDefault() { - return "jigsaw-piece"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/JigsawPoolHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/JigsawPoolHandler.java deleted file mode 100644 index 3200b22c7..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/JigsawPoolHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisJigsawPool; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class JigsawPoolHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisJigsawPool j : data.getJigsawPoolLoader().loadAll(data.getJigsawPoolLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisJigsawPool dim) { - return dim.getLoadKey(); - } - - @Override - public IrisJigsawPool parse(String in, boolean force) throws DecreeParsingException { - if(in.equals("null")) { - return null; - } - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Jigsaw Pool \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Jigsaw Pool \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisJigsawPool.class); - } - - @Override - public String getRandomDefault() { - return "jigsaw-pool"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/JigsawStructureHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/JigsawStructureHandler.java deleted file mode 100644 index 35fd9215a..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/JigsawStructureHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisJigsawStructure; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class JigsawStructureHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisJigsawStructure j : data.getJigsawStructureLoader().loadAll(data.getJigsawStructureLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisJigsawStructure dim) { - return dim.getLoadKey(); - } - - @Override - public IrisJigsawStructure parse(String in, boolean force) throws DecreeParsingException { - if(in.equals("null")) { - return null; - } - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Jigsaw Structure \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Jigsaw Structure \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisJigsawStructure.class); - } - - @Override - public String getRandomDefault() { - return "jigsaw-structure"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/LongHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/LongHandler.java deleted file mode 100644 index 97e5ce60b..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/LongHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.math.RNG; - -import java.util.concurrent.atomic.AtomicReference; - -public class LongHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - @Override - public Long parse(String in, boolean force) throws DecreeParsingException { - try { - AtomicReference r = new AtomicReference<>(in); - double m = getMultiplier(r); - return (long) (Long.valueOf(r.get()).doubleValue() * m); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to parse long \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(Long.class) || type.equals(long.class); - } - - @Override - public String toString(Long f) { - return f.toString(); - } - - @Override - public String getRandomDefault() { - return RNG.r.i(0, 99) + ""; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/PlayerHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/PlayerHandler.java deleted file mode 100644 index 9cf8fade2..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/PlayerHandler.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.stream.Collectors; - -public class PlayerHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>(new ArrayList<>(Bukkit.getOnlinePlayers())); - } - - @Override - public String toString(Player player) { - return player.getName(); - } - - @Override - public Player parse(String in, boolean force) throws DecreeParsingException { - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Player \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(Player.class); - } - - @Override - public String getRandomDefault() { - return "playername"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/RegionHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/RegionHandler.java deleted file mode 100644 index f5b7e95b3..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/RegionHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisRegion; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class RegionHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisRegion j : data.getRegionLoader().loadAll(data.getRegionLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisRegion dim) { - return dim.getLoadKey(); - } - - @Override - public IrisRegion parse(String in, boolean force) throws DecreeParsingException { - if(in.equals("null")) { - return null; - } - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Region \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisRegion.class); - } - - @Override - public String getRandomDefault() { - return "region"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/ScriptHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/ScriptHandler.java deleted file mode 100644 index 52112a889..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/ScriptHandler.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisScript; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class ScriptHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KMap p = new KMap<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - for(IrisScript j : data.getScriptLoader().loadAll(data.getScriptLoader().getPossibleKeys())) { - p.putIfAbsent(j.getLoadKey(), j); - } - - data.close(); - } - } - - return p.v(); - } - - @Override - public String toString(IrisScript script) { - return script.getLoadKey(); - } - - @Override - public IrisScript parse(String in, boolean force) throws DecreeParsingException { - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Script \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(IrisScript.class); - } - - @Override - public String getRandomDefault() { - return "script"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/ShortHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/ShortHandler.java deleted file mode 100644 index 8b72fe9c2..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/ShortHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.math.RNG; - -import java.util.concurrent.atomic.AtomicReference; - -public class ShortHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - @Override - public Short parse(String in, boolean force) throws DecreeParsingException { - try { - AtomicReference r = new AtomicReference<>(in); - double m = getMultiplier(r); - return (short) (Short.valueOf(r.get()).doubleValue() * m); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to parse short \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(Short.class) || type.equals(short.class); - } - - @Override - public String toString(Short f) { - return f.toString(); - } - - @Override - public String getRandomDefault() { - return RNG.r.i(0, 99) + ""; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/StringHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/StringHandler.java deleted file mode 100644 index 26557bd74..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/StringHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -/** - * Abstraction can sometimes breed stupidity - */ -public class StringHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - @Override - public String toString(String s) { - return s; - } - - @Override - public String parse(String in, boolean force) throws DecreeParsingException { - return in; - } - - @Override - public boolean supports(Class type) { - return type.equals(String.class); - } - - @Override - public String getRandomDefault() { - return new KList().qadd("text").qadd("string") - .qadd("blah").qadd("derp").qadd("yolo").getRandom(); - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/VectorHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/VectorHandler.java deleted file mode 100644 index 611706b62..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/VectorHandler.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeContext; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.DecreeSystem; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.format.Form; -import org.bukkit.FluidCollisionMode; -import org.bukkit.entity.Player; -import org.bukkit.util.BlockVector; -import org.bukkit.util.Vector; - -public class VectorHandler implements DecreeParameterHandler { - - private static final KList randoms = new KList<>( - "here", - "0,0,0", - "0,0", - "look", - "player:" - ); - - @Override - public KList getPossibilities() { - return null; - } - - @Override - public String toString(Vector v) { - if(v.getY() == 0) { - return Form.f(v.getX(), 2) + "," + Form.f(v.getZ(), 2); - } - - return Form.f(v.getX(), 2) + "," + Form.f(v.getY(), 2) + "," + Form.f(v.getZ(), 2); - } - - @Override - public Vector parse(String in, boolean force) throws DecreeParsingException { - try { - if(in.contains(",")) { - String[] comp = in.split("\\Q,\\E"); - - if(comp.length == 2) { - return new BlockVector(Double.parseDouble(comp[0].trim()), 0, Double.parseDouble(comp[1].trim())); - } else if(comp.length == 3) { - return new BlockVector(Double.parseDouble(comp[0].trim()), - Double.parseDouble(comp[1].trim()), - Double.parseDouble(comp[2].trim())); - } else { - throw new DecreeParsingException("Could not parse components for vector. You have " + comp.length + " components. Expected 2 or 3."); - } - } else if(in.equalsIgnoreCase("here") || in.equalsIgnoreCase("me") || in.equalsIgnoreCase("self")) { - if(!DecreeContext.get().isPlayer()) { - throw new DecreeParsingException("You cannot specify me,self,here as a console."); - } - - return DecreeContext.get().player().getLocation().toVector(); - } else if(in.equalsIgnoreCase("look") || in.equalsIgnoreCase("cursor") || in.equalsIgnoreCase("crosshair")) { - if(!DecreeContext.get().isPlayer()) { - throw new DecreeParsingException("You cannot specify look,cursor,crosshair as a console."); - } - - return DecreeContext.get().player().getTargetBlockExact(256, FluidCollisionMode.NEVER).getLocation().toVector(); - } else if(in.trim().toLowerCase().startsWith("player:")) { - String v = in.trim().split("\\Q:\\E")[1]; - - - KList px = DecreeSystem.getHandler(Player.class).getPossibilities(v); - - if(px != null && px.isNotEmpty()) { - return ((Player) px.get(0)).getLocation().toVector(); - } else if(px == null || px.isEmpty()) { - throw new DecreeParsingException("Cannot find player: " + v); - } - } - } catch(Throwable e) { - throw new DecreeParsingException("Unable to get Vector for \"" + in + "\" because of an uncaught exception: " + e); - } - - return null; - } - - @Override - public boolean supports(Class type) { - return type.equals(Vector.class); - } - - @Override - public String getRandomDefault() { - return randoms.getRandom(); - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/handlers/WorldHandler.java b/src/main/java/com/volmit/iris/util/decree/handlers/WorldHandler.java deleted file mode 100644 index 16debe629..000000000 --- a/src/main/java/com/volmit/iris/util/decree/handlers/WorldHandler.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.handlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import org.bukkit.Bukkit; -import org.bukkit.World; - -import java.util.stream.Collectors; - -public class WorldHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KList options = new KList<>(); - for(World world : Bukkit.getWorlds()) { - if(!world.getName().toLowerCase().startsWith("iris/")) { - options.add(world); - } - } - return options; - } - - @Override - public String toString(World world) { - return world.getName(); - } - - @Override - public World parse(String in, boolean force) throws DecreeParsingException { - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find World \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(World.class); - } - - @Override - public String getRandomDefault() { - return "world"; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/specialhandlers/DummyHandler.java b/src/main/java/com/volmit/iris/util/decree/specialhandlers/DummyHandler.java deleted file mode 100644 index 9491f7588..000000000 --- a/src/main/java/com/volmit/iris/util/decree/specialhandlers/DummyHandler.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.specialhandlers; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -public class DummyHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - return null; - } - - public boolean isDummy() { - return true; - } - - @Override - public String toString(Object o) { - return null; - } - - @Override - public Object parse(String in, boolean force) throws DecreeParsingException { - return null; - } - - @Override - public boolean supports(Class type) { - return false; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/specialhandlers/ObjectHandler.java b/src/main/java/com/volmit/iris/util/decree/specialhandlers/ObjectHandler.java deleted file mode 100644 index 47bb5a5a8..000000000 --- a/src/main/java/com/volmit/iris/util/decree/specialhandlers/ObjectHandler.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.specialhandlers; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.decree.DecreeParameterHandler; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; - -import java.io.File; -import java.util.stream.Collectors; - -public class ObjectHandler implements DecreeParameterHandler { - @Override - public KList getPossibilities() { - KList p = new KList<>(); - - //noinspection ConstantConditions - for(File i : Iris.instance.getDataFolder("packs").listFiles()) { - if(i.isDirectory()) { - IrisData data = IrisData.get(i); - p.add(data.getObjectLoader().getPossibleKeys()); - } - } - - return p; - } - - @Override - public String toString(String irisObject) { - return irisObject; - } - - @Override - public String parse(String in, boolean force) throws DecreeParsingException { - KList options = getPossibilities(in); - - if(options.isEmpty()) { - throw new DecreeParsingException("Unable to find Object \"" + in + "\""); - } - try { - return options.stream().filter((i) -> toString(i).equalsIgnoreCase(in)).collect(Collectors.toList()).get(0); - } catch(Throwable e) { - throw new DecreeParsingException("Unable to filter which Biome \"" + in + "\""); - } - } - - @Override - public boolean supports(Class type) { - return type.equals(String.class); - } - - @Override - public String getRandomDefault() { - String f = getPossibilities().getRandom(); - - return f == null ? "object" : f; - } -} diff --git a/src/main/java/com/volmit/iris/util/decree/virtual/VirtualDecreeCommand.java b/src/main/java/com/volmit/iris/util/decree/virtual/VirtualDecreeCommand.java deleted file mode 100644 index 9e97c205d..000000000 --- a/src/main/java/com/volmit/iris/util/decree/virtual/VirtualDecreeCommand.java +++ /dev/null @@ -1,588 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.decree.virtual; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.decree.DecreeContext; -import com.volmit.iris.util.decree.DecreeContextHandler; -import com.volmit.iris.util.decree.DecreeNode; -import com.volmit.iris.util.decree.DecreeParameter; -import com.volmit.iris.util.decree.annotations.Decree; -import com.volmit.iris.util.decree.exceptions.DecreeParsingException; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.plugin.CommandDummy; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import lombok.Data; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Objects; -import java.util.stream.Collectors; - -@Data -public class VirtualDecreeCommand { - private final Class type; - private final VirtualDecreeCommand parent; - private final KList nodes; - private final DecreeNode node; - String[] gradients = new String[] { - "", - "", - "", - "", - "", - "" - }; - private ChronoLatch cl = new ChronoLatch(1000); - - private VirtualDecreeCommand(Class type, VirtualDecreeCommand parent, KList nodes, DecreeNode node) { - this.parent = parent; - this.type = type; - this.nodes = nodes; - this.node = node; - } - - public static VirtualDecreeCommand createRoot(Object v) throws Throwable { - return createRoot(null, v); - } - - public static VirtualDecreeCommand createRoot(VirtualDecreeCommand parent, Object v) throws Throwable { - VirtualDecreeCommand c = new VirtualDecreeCommand(v.getClass(), parent, new KList<>(), null); - - for(Field i : v.getClass().getDeclaredFields()) { - if(Modifier.isStatic(i.getModifiers()) || Modifier.isFinal(i.getModifiers()) || Modifier.isTransient(i.getModifiers()) || Modifier.isVolatile(i.getModifiers())) { - continue; - } - - if(!i.getType().isAnnotationPresent(Decree.class)) { - continue; - } - - i.setAccessible(true); - Object childRoot = i.get(v); - - if(childRoot == null) { - childRoot = i.getType().getConstructor().newInstance(); - i.set(v, childRoot); - } - - c.getNodes().add(createRoot(c, childRoot)); - } - - for(Method i : v.getClass().getDeclaredMethods()) { - if(Modifier.isStatic(i.getModifiers()) || Modifier.isFinal(i.getModifiers()) || Modifier.isPrivate(i.getModifiers())) { - continue; - } - - if(!i.isAnnotationPresent(Decree.class)) { - continue; - } - - c.getNodes().add(new VirtualDecreeCommand(v.getClass(), c, new KList<>(), new DecreeNode(v, i))); - } - - return c; - } - - public void cacheAll() { - VolmitSender sender = new VolmitSender(new CommandDummy()); - - if(isNode()) { - sender.sendDecreeHelpNode(this); - } - - for(VirtualDecreeCommand j : nodes) { - j.cacheAll(); - } - } - - public String getPath() { - KList n = new KList<>(); - VirtualDecreeCommand cursor = this; - - while(cursor.getParent() != null) { - cursor = cursor.getParent(); - n.add(cursor.getName()); - } - - return "/" + n.reverse().qadd(getName()).toString(" "); - } - - public String getParentPath() { - return getParent().getPath(); - } - - public String getName() { - return isNode() ? getNode().getName() : getType().getDeclaredAnnotation(Decree.class).name(); - } - - private boolean isStudio() { - return isNode() ? getNode().getDecree().studio() : getType().getDeclaredAnnotation(Decree.class).studio(); - } - - public String getDescription() { - return isNode() ? getNode().getDescription() : getType().getDeclaredAnnotation(Decree.class).description(); - } - - public KList getNames() { - if(isNode()) { - return getNode().getNames(); - } - - Decree dc = getType().getDeclaredAnnotation(Decree.class); - KList d = new KList<>(); - d.add(dc.name()); - for(String i : dc.aliases()) { - if(i.isEmpty()) { - continue; - } - - d.add(i); - } - - d.removeDuplicates(); - - return d; - } - - public boolean isNode() { - return node != null; - } - - public KList tabComplete(KList args, String raw) { - KList skip = new KList<>(); - KList tabs = new KList<>(); - invokeTabComplete(args, skip, tabs, raw); - return tabs; - } - - private boolean invokeTabComplete(KList args, KList skip, KList tabs, String raw) { - if(isStudio() && !IrisSettings.get().getStudio().isStudio()) { - return false; - } - - if(isNode()) { - tab(args, tabs); - skip.add(hashCode()); - return false; - } - - if(args.isEmpty()) { - tab(args, tabs); - return true; - } - - String head = args.get(0); - - if(args.size() > 1 || head.endsWith(" ")) { - VirtualDecreeCommand match = matchNode(head, skip); - - if(match != null) { - args.pop(); - return match.invokeTabComplete(args, skip, tabs, raw); - } - - skip.add(hashCode()); - } else { - tab(args, tabs); - } - - return false; - } - - private void tab(KList args, KList tabs) { - String last = null; - KList ignore = new KList<>(); - Runnable la = () -> { - - }; - for(String a : args) { - la.run(); - last = a; - la = () -> { - if(isNode()) { - String sea = a.contains("=") ? a.split("\\Q=\\E")[0] : a; - sea = sea.trim(); - - searching: - for(DecreeParameter i : getNode().getParameters()) { - for(String m : i.getNames()) { - if(m.equalsIgnoreCase(sea) || m.toLowerCase().contains(sea.toLowerCase()) || sea.toLowerCase().contains(m.toLowerCase())) { - ignore.add(i); - continue searching; - } - } - } - } - }; - } - - if(last != null) { - if(isNode()) { - for(DecreeParameter i : getNode().getParameters()) { - if(ignore.contains(i)) { - continue; - } - - int g = 0; - - if(last.contains("=")) { - String[] vv = last.trim().split("\\Q=\\E"); - String vx = vv.length == 2 ? vv[1] : ""; - for(String f : i.getHandler().getPossibilities(vx).convert((v) -> i.getHandler().toStringForce(v))) { - g++; - tabs.add(i.getName() + "=" + f); - } - } else { - for(String f : i.getHandler().getPossibilities("").convert((v) -> i.getHandler().toStringForce(v))) { - g++; - tabs.add(i.getName() + "=" + f); - } - } - - if(g == 0) { - tabs.add(i.getName() + "="); - } - } - } else { - for(VirtualDecreeCommand i : getNodes()) { - String m = i.getName(); - if(m.equalsIgnoreCase(last) || m.toLowerCase().contains(last.toLowerCase()) || last.toLowerCase().contains(m.toLowerCase())) { - tabs.addAll(i.getNames()); - } - } - } - } - } - - /** - * Maps the input a player typed to the parameters of this command - * - * @param sender - * The sender - * @param in - * The input - * @return A map of all the parameter names and their values - */ - private KMap map(VolmitSender sender, KList in) { - KMap data = new KMap<>(); - KSet nowhich = new KSet<>(); - - KList unknownInputs = new KList<>(in.stream().filter(s -> !s.contains("=")).collect(Collectors.toList())); - KList knownInputs = new KList<>(in.stream().filter(s -> s.contains("=")).collect(Collectors.toList())); - - //Loop known inputs - for(int x = 0; x < knownInputs.size(); x++) { - String stringParam = knownInputs.get(x); - int original = in.indexOf(stringParam); - - String[] v = stringParam.split("\\Q=\\E"); - String key = v[0]; - String value = v[1]; - DecreeParameter param = null; - - //Find decree parameter from string param - for(DecreeParameter j : getNode().getParameters()) { - for(String k : j.getNames()) { - if(k.equalsIgnoreCase(key)) { - param = j; - break; - } - } - } - - //If it failed, see if we can find it by checking if the names contain the param - if(param == null) { - for(DecreeParameter j : getNode().getParameters()) { - for(String k : j.getNames()) { - if(k.toLowerCase().contains(key.toLowerCase()) || key.toLowerCase().contains(k.toLowerCase())) { - param = j; - break; - } - } - } - } - - //Still failed to find, error them - if(param == null) { - Iris.debug("Can't find parameter key for " + key + "=" + value + " in " + getPath()); - sender.sendMessage(C.YELLOW + "Unknown Parameter: " + key); - unknownInputs.add(value); //Add the value to the unknowns and see if we can assume it later - continue; - } - - key = param.getName(); - - try { - data.put(key, param.getHandler().parse(value, nowhich.contains(original))); //Parse and put - } catch(DecreeParsingException e) { - Iris.debug("Can't parse parameter value for " + key + "=" + value + " in " + getPath() + " using handler " + param.getHandler().getClass().getSimpleName()); - sender.sendMessage(C.RED + "Cannot convert \"" + value + "\" into a " + param.getType().getSimpleName()); - e.printStackTrace(); - return null; - } - } - - //Make a list of decree params that haven't been identified - KList decreeParameters = new KList<>(getNode().getParameters().stream().filter(param -> !data.contains(param.getName())).collect(Collectors.toList())); - - //Loop Unknown inputs - for(int x = 0; x < unknownInputs.size(); x++) { - String stringParam = unknownInputs.get(x); - int original = in.indexOf(stringParam); - try { - DecreeParameter par = decreeParameters.get(x); - - try { - data.put(par.getName(), par.getHandler().parse(stringParam, nowhich.contains(original))); - } catch(DecreeParsingException e) { - Iris.debug("Can't parse parameter value for " + par.getName() + "=" + stringParam + " in " + getPath() + " using handler " + par.getHandler().getClass().getSimpleName()); - sender.sendMessage(C.RED + "Cannot convert \"" + stringParam + "\" into a " + par.getType().getSimpleName()); - e.printStackTrace(); - return null; - } - } catch(IndexOutOfBoundsException e) { - sender.sendMessage(C.YELLOW + "Unknown Parameter: " + stringParam + " (" + Form.getNumberSuffixThStRd(x + 1) + " argument)"); - } - } - - return data; - } - - public boolean invoke(VolmitSender sender, KList realArgs) { - return invoke(sender, realArgs, new KList<>()); - } - - public boolean invoke(VolmitSender sender, KList args, KList skip) { - if(isStudio() && !IrisSettings.get().getStudio().isStudio()) { - sender.sendMessage(C.RED + "To use Iris Studio Commands, please enable studio in Iris/settings.json (settings auto-reload)"); - return false; - } - - Iris.debug("@ " + getPath() + " with " + args.toString(", ")); - if(isNode()) { - Iris.debug("Invoke " + getPath() + "(" + args.toString(",") + ") at "); - if(invokeNode(sender, map(sender, args))) { - return true; - } - - skip.add(hashCode()); - return false; - } - - if(args.isEmpty()) { - sender.sendDecreeHelp(this); - - return true; - } else if(args.size() == 1) { - for(String i : args) { - if(i.startsWith("help=")) { - sender.sendDecreeHelp(this, Integer.parseInt(i.split("\\Q=\\E")[1]) - 1); - return true; - } - } - } - - String head = args.get(0); - VirtualDecreeCommand match = matchNode(head, skip); - - if(match != null) { - args.pop(); - return match.invoke(sender, args, skip); - } - - skip.add(hashCode()); - - return false; - } - - private boolean invokeNode(VolmitSender sender, KMap map) { - if(map == null) { - return false; - } - - Object[] params = new Object[getNode().getMethod().getParameterCount()]; - int vm = 0; - for(DecreeParameter i : getNode().getParameters()) { - Object value = map.get(i.getName()); - - try { - if(value == null && i.hasDefault()) { - value = i.getDefaultValue(); - } - } catch(DecreeParsingException e) { - Iris.debug("Can't parse parameter value for " + i.getName() + "=" + i.getParam().defaultValue() + " in " + getPath() + " using handler " + i.getHandler().getClass().getSimpleName()); - sender.sendMessage(C.RED + "Cannot convert \"" + i.getParam().defaultValue() + "\" into a " + i.getType().getSimpleName()); - return false; - } - - if(sender.isPlayer() && i.isContextual() && value == null) { - Iris.debug("Contextual!"); - DecreeContextHandler ch = DecreeContextHandler.contextHandlers.get(i.getType()); - - if(ch != null) { - value = ch.handle(sender); - - if(value != null) { - Iris.debug("Parameter \"" + i.getName() + "\" derived a value of \"" + i.getHandler().toStringForce(value) + "\" from " + ch.getClass().getSimpleName()); - } else { - Iris.debug("Parameter \"" + i.getName() + "\" could not derive a value from \"" + ch.getClass().getSimpleName()); - } - } else { - Iris.debug("Parameter \"" + i.getName() + "\" is contextual but has no context handler for \"" + i.getType().getCanonicalName() + "\""); - } - } - - if(i.hasDefault() && value == null) { - try { - Iris.debug("Parameter \"" + i.getName() + "\" is using default value \"" + i.getParam().defaultValue() + "\""); - value = i.getDefaultValue(); - } catch(Throwable e) { - e.printStackTrace(); - } - } - - if(i.isRequired() && value == null) { - sender.sendMessage(C.RED + "Missing argument \"" + i.getName() + "\" (" + i.getType().getSimpleName() + ") as the " + Form.getNumberSuffixThStRd(vm + 1) + " argument."); - sender.sendDecreeHelpNode(this); - return false; - } - - params[vm] = value; - vm++; - } - - DecreeContext.touch(sender); - Runnable rx = () -> { - try { - DecreeContext.touch(sender); - getNode().getMethod().setAccessible(true); - getNode().getMethod().invoke(getNode().getInstance(), params); - } catch(Throwable e) { - e.printStackTrace(); - throw new RuntimeException("Failed to execute "); // TODO: - } - }; - - if(getNode().isSync()) { - J.s(rx); - } else { - rx.run(); - } - - return true; - } - - public KList matchAllNodes(String in) { - KList g = new KList<>(); - - if(in.trim().isEmpty()) { - g.addAll(nodes); - return g; - } - - for(VirtualDecreeCommand i : nodes) { - if(i.matches(in)) { - g.add(i); - } - } - - for(VirtualDecreeCommand i : nodes) { - if(i.deepMatches(in)) { - g.add(i); - } - } - - g.removeDuplicates(); - return g; - } - - public VirtualDecreeCommand matchNode(String in, KList skip) { - if(in.trim().isEmpty()) { - return null; - } - - for(VirtualDecreeCommand i : nodes) { - if(skip.contains(i.hashCode())) { - continue; - } - - if(i.matches(in)) { - return i; - } - } - - for(VirtualDecreeCommand i : nodes) { - if(skip.contains(i.hashCode())) { - continue; - } - - if(i.deepMatches(in)) { - return i; - } - } - - return null; - } - - public boolean deepMatches(String in) { - KList a = getNames(); - - for(String i : a) { - if(i.toLowerCase().contains(in.toLowerCase()) || in.toLowerCase().contains(i.toLowerCase())) { - return true; - } - } - - return false; - } - - @Override - public int hashCode() { - return Objects.hash(getName(), getDescription(), getType(), getPath()); - } - - @Override - public boolean equals(Object obj) { - if(!(obj instanceof VirtualDecreeCommand)) { - return false; - } - return this.hashCode() == obj.hashCode(); - } - - public boolean matches(String in) { - KList a = getNames(); - - for(String i : a) { - if(i.equalsIgnoreCase(in)) { - return true; - } - } - - return false; - } -} diff --git a/src/main/java/com/volmit/iris/util/documentation/BlockCoordinates.java b/src/main/java/com/volmit/iris/util/documentation/BlockCoordinates.java deleted file mode 100644 index e0e6b66e6..000000000 --- a/src/main/java/com/volmit/iris/util/documentation/BlockCoordinates.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.documentation; - -/** - * This method expects coords in block - */ -public @interface BlockCoordinates { - -} diff --git a/src/main/java/com/volmit/iris/util/documentation/ChunkCoordinates.java b/src/main/java/com/volmit/iris/util/documentation/ChunkCoordinates.java deleted file mode 100644 index 64a1a38b4..000000000 --- a/src/main/java/com/volmit/iris/util/documentation/ChunkCoordinates.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.documentation; - -/** - * This method expects blocks in chunk coordinates - */ -public @interface ChunkCoordinates { - -} diff --git a/src/main/java/com/volmit/iris/util/documentation/ChunkRelativeBlockCoordinates.java b/src/main/java/com/volmit/iris/util/documentation/ChunkRelativeBlockCoordinates.java deleted file mode 100644 index e5d86a9f9..000000000 --- a/src/main/java/com/volmit/iris/util/documentation/ChunkRelativeBlockCoordinates.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.documentation; - -/** - * This method expects coords in block - */ -public @interface ChunkRelativeBlockCoordinates { - -} diff --git a/src/main/java/com/volmit/iris/util/documentation/RegionCoordinates.java b/src/main/java/com/volmit/iris/util/documentation/RegionCoordinates.java deleted file mode 100644 index 9d07a39e1..000000000 --- a/src/main/java/com/volmit/iris/util/documentation/RegionCoordinates.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.documentation; - -/** - * This method expects coordinates in region coords - */ -public @interface RegionCoordinates { - -} diff --git a/src/main/java/com/volmit/iris/util/exceptions/IrisException.java b/src/main/java/com/volmit/iris/util/exceptions/IrisException.java deleted file mode 100644 index 187bcc3d0..000000000 --- a/src/main/java/com/volmit/iris/util/exceptions/IrisException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.exceptions; - -public class IrisException extends Exception { - public IrisException() { - super(); - } - - public IrisException(String message) { - super(message); - } - - public IrisException(Throwable message) { - super(message); - } - - public IrisException(String message, Throwable e) { - super(message, e); - } -} diff --git a/src/main/java/com/volmit/iris/util/exceptions/MissingDimensionException.java b/src/main/java/com/volmit/iris/util/exceptions/MissingDimensionException.java deleted file mode 100644 index 368d2d09d..000000000 --- a/src/main/java/com/volmit/iris/util/exceptions/MissingDimensionException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.exceptions; - -public class MissingDimensionException extends IrisException { - public MissingDimensionException() { - super(); - } - - public MissingDimensionException(String message) { - super(message); - } -} diff --git a/src/main/java/com/volmit/iris/util/format/C.java b/src/main/java/com/volmit/iris/util/format/C.java deleted file mode 100644 index 8876bc922..000000000 --- a/src/main/java/com/volmit/iris/util/format/C.java +++ /dev/null @@ -1,747 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.format; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.plugin.VolmitSender; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import org.apache.commons.lang.Validate; -import org.bukkit.ChatColor; -import org.bukkit.Color; -import org.bukkit.DyeColor; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Colors - * - * @author cyberpwn - */ -public enum C { - /** - * Represents black - */ - BLACK('0', 0x00) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.BLACK; - } - }, - /** - * Represents dark blue - */ - DARK_BLUE('1', 0x1) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.DARK_BLUE; - } - }, - /** - * Represents dark green - */ - DARK_GREEN('2', 0x2) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.DARK_GREEN; - } - }, - /** - * Represents dark blue (aqua) - */ - DARK_AQUA('3', 0x3) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.DARK_AQUA; - } - }, - /** - * Represents dark red - */ - DARK_RED('4', 0x4) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.DARK_RED; - } - }, - /** - * Represents dark purple - */ - DARK_PURPLE('5', 0x5) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.DARK_PURPLE; - } - }, - /** - * Represents gold - */ - GOLD('6', 0x6) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.GOLD; - } - }, - /** - * Represents gray - */ - GRAY('7', 0x7) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.GRAY; - } - }, - /** - * Represents dark gray - */ - DARK_GRAY('8', 0x8) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.DARK_GRAY; - } - }, - /** - * Represents blue - */ - BLUE('9', 0x9) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.BLUE; - } - }, - /** - * Represents green - */ - GREEN('a', 0xA) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.GREEN; - } - }, - - IRIS("<#1bb19e>", 'a', 0xA) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.GREEN; - } - }, - - /** - * Represents aqua - */ - AQUA('b', 0xB) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.AQUA; - } - }, - /** - * Represents red - */ - RED('c', 0xC) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.RED; - } - }, - /** - * Represents light purple - */ - LIGHT_PURPLE('d', 0xD) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.LIGHT_PURPLE; - } - }, - /** - * Represents yellow - */ - YELLOW('e', 0xE) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.YELLOW; - } - }, - /** - * Represents white - */ - WHITE('f', 0xF) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.WHITE; - } - }, - /** - * Represents magical characters that change around randomly - */ - MAGIC("", 'k', 0x10, true) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.MAGIC; - } - }, - /** - * Makes the text bold. - */ - BOLD('l', 0x11, true) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.BOLD; - } - }, - /** - * Makes a line appear through the text. - */ - STRIKETHROUGH('m', 0x12, true) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.STRIKETHROUGH; - } - }, - /** - * Makes the text appear underlined. - */ - UNDERLINE("", 'n', 0x13, true) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.UNDERLINE; - } - }, - /** - * Makes the text italic. - */ - ITALIC('o', 0x14, true) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.ITALIC; - } - }, - - /** - * Resets all previous chat colors or formats. - */ - RESET('r', 0x15) { - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.RESET; - } - }, - - - ; - /** - * The special character which prefixes all chat colour codes. Use this if you - * need to dynamically convert colour codes from your custom format. - */ - public static final char COLOR_CHAR = '\u00A7'; - public final static C[] COLORCYCLE = new C[] {C.GOLD, C.YELLOW, C.GREEN, C.AQUA, C.LIGHT_PURPLE, C.AQUA, C.GREEN, C.YELLOW, C.GOLD, C.RED}; - private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + COLOR_CHAR + "[0-9A-FK-OR]"); - private final static C[] COLORS = new C[] {C.BLACK, C.DARK_BLUE, C.DARK_GREEN, C.DARK_AQUA, C.DARK_RED, C.DARK_PURPLE, C.GOLD, C.GRAY, C.DARK_GRAY, C.BLUE, C.GREEN, C.AQUA, C.RED, C.LIGHT_PURPLE, C.YELLOW, C.WHITE}; - @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - private final static Map BY_ID = new HashMap<>(); - private final static Map BY_CHAR = new HashMap<>(); - private final static Map dyeChatMap = new HashMap<>(); - private final static Map chatHexMap = new HashMap<>(); - private final static Map dyeHexMap = new HashMap<>(); - - static { - chatHexMap.put(C.BLACK, "#000000"); - chatHexMap.put(C.DARK_BLUE, "#0000AA"); - chatHexMap.put(C.IRIS, "#1bb19e"); - chatHexMap.put(C.DARK_GREEN, "#00AA00"); - chatHexMap.put(C.DARK_AQUA, "#00AAAA"); - chatHexMap.put(C.DARK_RED, "#AA0000"); - chatHexMap.put(C.DARK_PURPLE, "#AA00AA"); - chatHexMap.put(C.GOLD, "#FFAA00"); - chatHexMap.put(C.GRAY, "#AAAAAA"); - chatHexMap.put(C.DARK_GRAY, "#555555"); - chatHexMap.put(C.BLUE, "#5555FF"); - chatHexMap.put(C.GREEN, "#55FF55"); - chatHexMap.put(C.AQUA, "#55FFFF"); - chatHexMap.put(C.RED, "#FF5555"); - chatHexMap.put(C.LIGHT_PURPLE, "#FF55FF"); - chatHexMap.put(C.YELLOW, "#FFFF55"); - chatHexMap.put(C.WHITE, "#FFFFFF"); - dyeChatMap.put(DyeColor.BLACK, C.DARK_GRAY); - dyeChatMap.put(DyeColor.BLUE, C.DARK_BLUE); - dyeChatMap.put(DyeColor.BROWN, C.GOLD); - dyeChatMap.put(DyeColor.CYAN, C.AQUA); - dyeChatMap.put(DyeColor.GRAY, C.GRAY); - dyeChatMap.put(DyeColor.GREEN, C.DARK_GREEN); - dyeChatMap.put(DyeColor.LIGHT_BLUE, C.BLUE); - dyeChatMap.put(DyeColor.LIME, C.GREEN); - dyeChatMap.put(DyeColor.MAGENTA, C.LIGHT_PURPLE); - dyeChatMap.put(DyeColor.ORANGE, C.GOLD); - dyeChatMap.put(DyeColor.PINK, C.LIGHT_PURPLE); - dyeChatMap.put(DyeColor.PURPLE, C.DARK_PURPLE); - dyeChatMap.put(DyeColor.RED, C.RED); - dyeChatMap.put(DyeColor.LIGHT_GRAY, C.GRAY); - dyeChatMap.put(DyeColor.WHITE, C.WHITE); - dyeChatMap.put(DyeColor.YELLOW, C.YELLOW); - dyeHexMap.put(DyeColor.BLACK, "#181414"); - dyeHexMap.put(DyeColor.BLUE, "#253193"); - dyeHexMap.put(DyeColor.BROWN, "#56331c"); - dyeHexMap.put(DyeColor.CYAN, "#267191"); - dyeHexMap.put(DyeColor.GRAY, "#414141"); - dyeHexMap.put(DyeColor.GREEN, "#364b18"); - dyeHexMap.put(DyeColor.LIGHT_BLUE, "#6387d2"); - dyeHexMap.put(DyeColor.LIME, "#39ba2e"); - dyeHexMap.put(DyeColor.MAGENTA, "#be49c9"); - dyeHexMap.put(DyeColor.ORANGE, "#ea7e35"); - dyeHexMap.put(DyeColor.PINK, "#d98199"); - dyeHexMap.put(DyeColor.PURPLE, "#7e34bf"); - dyeHexMap.put(DyeColor.RED, "#9e2b27"); - dyeHexMap.put(DyeColor.LIGHT_GRAY, "#a0a7a7"); - dyeHexMap.put(DyeColor.WHITE, "#a4a4a4"); - dyeHexMap.put(DyeColor.YELLOW, "#c2b51c"); - } - - static { - for(C color : values()) { - BY_ID.put(color.intCode, color); - BY_CHAR.put(color.code, color); - } - } - - private final int intCode; - private final char code; - private final String token; - private final boolean isFormat; - private final String toString; - - C(char code, int intCode) { - this("^", code, intCode, false); - } - - C(String token, char code, int intCode) { - this(token, code, intCode, false); - } - - C(char code, int intCode, boolean isFormat) { - this("^", code, intCode, false); - } - - C(String token, char code, int intCode, boolean isFormat) { - this.code = code; - this.token = token.equalsIgnoreCase("^") ? "<" + name().toLowerCase(Locale.ROOT) + ">" : token; - this.intCode = intCode; - this.isFormat = isFormat; - this.toString = new String(new char[] {COLOR_CHAR, code}); - } - - public static float[] spin(float[] c, int shift) { - return new float[] {spin(c[0], shift), spinc(c[1], shift), spinc(c[2], shift)}; - } - - public static float[] spin(float[] c, int a, int b, int d) { - return new float[] {spin(c[0], a), spinc(c[1], b), spinc(c[2], d)}; - } - - public static float spin(float c, int shift) { - float g = ((((int) Math.floor(c * 360)) + shift) % 360) / 360F; - return g < 0 ? 1f - g : g; - } - - public static float spinc(float c, int shift) { - float g = ((((int) Math.floor(c * 255)) + shift)) / 255F; - return Math.max(0f, Math.min(g, 1f)); - } - - public static java.awt.Color spin(java.awt.Color c, int h, int s, int b) { - float[] hsb = java.awt.Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null); - hsb = spin(hsb, h, s, b); - return java.awt.Color.getHSBColor(hsb[0], hsb[1], hsb[2]); - } - - public static String spinToHex(C color, int h, int s, int b) { - return "#" + Integer.toHexString(spin(color.awtColor(), h, s, b).getRGB()).substring(2); - } - - public static String aura(String s, int hrad, int srad, int vrad) { - return aura(s, hrad, srad, vrad, 0.3D); - } - - public static String aura(String s, int hrad, int srad, int vrad, double pulse) { - String msg = compress(s); - StringBuilder b = new StringBuilder(); - boolean c = false; - - for(char i : msg.toCharArray()) { - if(c) { - c = false; - - C o = C.getByChar(i); - - if(hrad != 0 || srad != 0 || vrad != 0) { - if(pulse > 0) { - b.append(VolmitSender.pulse(spinToHex(o, hrad, srad, vrad), spinToHex(o, -hrad, -srad, -vrad), pulse)); - } else { - b.append(""); - } - } else { - b.append(C.getByChar(i).token); - } - - continue; - } - - if(i == C.COLOR_CHAR) { - c = true; - continue; - } - - b.append(i); - } - - return b.toString(); - } - - public static String compress(String c) { - return BaseComponent.toLegacyText(TextComponent.fromLegacyText(c)); - } - - /** - * Gets the color represented by the specified color code - * - * @param code - * Code to check - * @return Associative {@link org.bukkit.ChatColor} with the given code, or null - * if it doesn't exist - */ - public static C getByChar(char code) { - try { - C c = BY_CHAR.get(code); - return c == null ? C.WHITE : c; - } catch(Exception e) { - Iris.reportError(e); - return C.WHITE; - } - } - - /** - * Gets the color represented by the specified color code - * - * @param code - * Code to check - * @return Associative {@link org.bukkit.ChatColor} with the given code, or null - * if it doesn't exist - */ - public static C getByChar(String code) { - try { - Validate.notNull(code, "Code cannot be null"); - Validate.isTrue(code.length() > 0, "Code must have at least one char"); - - return BY_CHAR.get(code.charAt(0)); - } catch(Exception e) { - Iris.reportError(e); - return C.WHITE; - } - } - - /** - * Strips the given message of all color codes - * - * @param input - * String to strip of color - * @return A copy of the input string, without any coloring - */ - public static String stripColor(final String input) { - if(input == null) { - return null; - } - - return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); - } - - /** - * DyeColor to ChatColor - * - * @param dclr - * the dye color - * @return the color - */ - public static C dyeToChat(DyeColor dclr) { - if(dyeChatMap.containsKey(dclr)) { - return dyeChatMap.get(dclr); - } - - return C.MAGIC; - } - - public static DyeColor chatToDye(ChatColor color) { - for(Map.Entry entry : dyeChatMap.entrySet()) { - if(entry.getValue().toString().equals(color.toString())) { - return entry.getKey(); - } - } - - return DyeColor.BLACK; - } - - @SuppressWarnings("unlikely-arg-type") - public static String chatToHex(C clr) { - if(chatHexMap.containsKey(clr)) { - return chatHexMap.get(clr); - } - - return "#000000"; - } - - public static String dyeToHex(DyeColor clr) { - if(dyeHexMap.containsKey(clr)) { - return dyeHexMap.get(clr); - } - - return "#000000"; - } - - public static Color hexToColor(String hex) { - if(hex.startsWith("#")) { - hex = hex.substring(1); - } - - if(hex.contains("x")) { - hex = hex.substring(hex.indexOf("x")); - } - - if(hex.length() != 6 && hex.length() != 3) { - return null; - } - int sz = hex.length() / 3, mult = 1 << ((2 - sz) * 4), x = 0; - - for(int i = 0, z = 0; z < hex.length(); ++i, z += sz) { - x |= (mult * Integer.parseInt(hex.substring(z, z + sz), 16)) << (i * 8); - } - - return Color.fromBGR(x & 0xffffff); - } - - public static Color rgbToColor(String rgb) { - String[] parts = rgb.split("[^0-9]+"); - if(parts.length < 3) { - return null; - } - - int x = 0, i; - - for(i = 0; i < 3; ++i) { - x |= Integer.parseInt(parts[i]) << (i * 8); - } - - return Color.fromBGR(x & 0xffffff); - } - - public static String generateColorTable() { - StringBuilder str = new StringBuilder(); - - str.append(""); - - for(Map.Entry e : chatHexMap.entrySet()) { - str.append(String.format("" + "", e.getKey().name(), e.getValue())); - } - - str.append("
Chat ColorColor
%1$sTest String
"); - str.append(""); - for(Map.Entry e : dyeHexMap.entrySet()) { - str.append(String.format("" + "", e.getKey().name(), e.getValue())); - } - - str.append("
Dye ColorColor
%1$sTest String
"); - - return str.toString(); - } - - /** - * Translates a string using an alternate color code character into a string - * that uses the internal ChatColor.COLOR_CODE color code character. The - * alternate color code character will only be replaced if it is immediately - * followed by 0-9, A-F, a-f, K-O, k-o, R or r. - * - * @param altColorChar - * The alternate color code character to replace. Ex: {@literal &} - * @param textToTranslate - * Text containing the alternate color code character. - * @return Text containing the ChatColor.COLOR_CODE color code character. - */ - public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { - if(textToTranslate == null) { - return null; - } - - char[] b = textToTranslate.toCharArray(); - for(int i = 0; i < b.length - 1; i++) { - if(b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { - b[i] = C.COLOR_CHAR; - b[i + 1] = Character.toLowerCase(b[i + 1]); - } - } - return new String(b); - } - - public static C fromItemMeta(byte c) { - for(C i : C.values()) { - if(i.getItemMeta() == c) { - return i; - } - } - - return null; - } - - public static C randomColor() { - return COLORS[(int) (Math.random() * (COLORS.length - 1))]; - } - - /** - * Gets the ChatColors used at the end of the given input string. - * - * @param input - * Input string to retrieve the colors from. - * @return Any remaining ChatColors to pass onto the next line. - */ - public static String getLastColors(String input) { - StringBuilder result = new StringBuilder(); - int length = input.length(); - - // Search backwards from the end as it is faster - for(int index = length - 1; index > -1; index--) { - char section = input.charAt(index); - if(section == COLOR_CHAR && index < length - 1) { - char c = input.charAt(index + 1); - C color = getByChar(c); - - if(color != null) { - result.insert(0, color); - - // Once we find a color or reset we can stop searching - if(color.isColor() || color.equals(RESET)) { - break; - } - } - } - } - - return result.toString(); - } - - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.RESET; - } - - /** - * Gets the char value associated with this color - * - * @return A char value of this color code - */ - public char getChar() { - return code; - } - - @Override - public String toString() { - return intCode == -1 ? token : toString; - } - - /** - * get the dye color for the chatcolor - */ - public DyeColor dye() { - return chatToDye(chatColor()); - } - - public String hex() { - return chatToHex(this); - } - - public java.awt.Color awtColor() { - return java.awt.Color.decode(hex()); - } - - /** - * Checks if this code is a format code as opposed to a color code. - * - * @return whether this ChatColor is a format code - */ - public boolean isFormat() { - return isFormat; - } - - /** - * Checks if this code is a color code as opposed to a format code. - * - * @return whether this ChatColor is a color code - */ - public boolean isColor() { - return !isFormat && this != RESET; - } - - /** - * Get the ChatColor enum instance instead of C - */ - public ChatColor chatColor() { - return ChatColor.getByChar(code); - } - - public byte getMeta() { - return switch(this) { - case AQUA -> (byte) 11; - case BLACK -> (byte) 0; - case BLUE, DARK_AQUA -> (byte) 9; - case BOLD, UNDERLINE, STRIKETHROUGH, RESET, MAGIC, ITALIC -> (byte) -1; - case DARK_BLUE -> (byte) 1; - case DARK_GRAY -> (byte) 8; - case DARK_GREEN -> (byte) 2; - case DARK_PURPLE -> (byte) 5; - case DARK_RED -> (byte) 4; - case GOLD -> (byte) 6; - case GRAY -> (byte) 7; - case GREEN -> (byte) 10; - case LIGHT_PURPLE -> (byte) 13; - case RED -> (byte) 12; - case YELLOW -> (byte) 14; - default -> (byte) 15; - }; - } - - public byte getItemMeta() { - return switch(this) { - case AQUA, DARK_AQUA -> (byte) 9; - case BLUE -> (byte) 3; - case BOLD, UNDERLINE, RESET, STRIKETHROUGH, MAGIC, ITALIC -> (byte) -1; - case DARK_BLUE -> (byte) 11; - case DARK_GRAY -> (byte) 7; - case DARK_GREEN -> (byte) 13; - case DARK_PURPLE -> (byte) 10; - case DARK_RED, RED -> (byte) 14; - case GOLD, YELLOW -> (byte) 4; - case GRAY -> (byte) 8; - case GREEN -> (byte) 5; - case LIGHT_PURPLE -> (byte) 2; - case WHITE -> (byte) 0; - default -> (byte) 15; - }; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/format/Form.java b/src/main/java/com/volmit/iris/util/format/Form.java deleted file mode 100644 index 5b5d27c64..000000000 --- a/src/main/java/com/volmit/iris/util/format/Form.java +++ /dev/null @@ -1,1323 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.format; - -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RollingSequence; - -import java.math.BigInteger; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.TreeMap; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class Form { - private static final String[] NAMES = new String[] {"Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion", "Undecillion", "Duodecillion", "Tredecillion", "Quattuordecillion", "Quindecillion", "Sexdecillion", "Septendecillion", "Octodecillion", "Novemdecillion", "Vigintillion",}; - private static final BigInteger THOUSAND = BigInteger.valueOf(1000); - private static final NavigableMap MAP; - private static NumberFormat NF; - private static DecimalFormat DF; - - static { - MAP = new TreeMap<>(); - for(int i = 0; i < NAMES.length; i++) { - MAP.put(THOUSAND.pow(i + 1), NAMES[i]); - } - } - - public static String getNumberSuffixThStRd(int day) { - if(day >= 11 && day <= 13) { - return Form.f(day) + "th"; - } - return switch(day % 10) { - case 1 -> Form.f(day) + "st"; - case 2 -> Form.f(day) + "nd"; - case 3 -> Form.f(day) + "rd"; - default -> Form.f(day) + "th"; - }; - } - - private static void instantiate() { - if(NF == null) { - NF = NumberFormat.getInstance(Locale.US); - } - } - - /** - * Scroll text - * - * @param smx - * the text - * @param viewport - * the viewport length - * @param time - * the timeline value - */ - public static String scroll(String smx, int viewport, long time) { - String src = Form.repeat(" ", viewport) + smx + Form.repeat(" ", viewport); - int len = src.length(); - int walk = (int) (time % (len - viewport)); - String base = src.substring(walk, M.min(walk + viewport, len - 1)); - base = base.length() < viewport ? base + Form.repeat(" ", (viewport - base.length()) - 3) : base; - - return base; - } - - /** - * Capitalize the first letter - * - * @param s - * the string - * @return the capitalized string - */ - public static String capitalize(String s) { - StringBuilder roll = new StringBuilder(); - boolean f = true; - - for(Character i : s.trim().toCharArray()) { - if(f) { - roll.append(Character.toUpperCase(i)); - f = false; - } else { - roll.append(i); - } - } - - return roll.toString(); - } - - /** - * Capitalize all words in the string - * - * @param s - * the string - * @return the capitalized string - */ - public static String capitalizeWords(String s) { - StringBuilder rollx = new StringBuilder(); - - for(String i : s.trim().split(" ")) { - rollx.append(" ").append(capitalize(i.trim())); - } - - return rollx.substring(1); - } - - /** - * Hard word wrap - * - * @param s - * the words - * @param len - * the length per line - * @return the wrapped string - */ - public static String wrap(String s, int len) { - return wrap(s, len, null, false); - } - - /** - * Soft Word wrap - * - * @param s - * the string - * @param len - * the length to wrap - * @return the wrapped string - */ - public static String wrapWords(String s, int len) { - return wrap(s, len, null, true); - } - - /** - * Wrap words - * - * @param s - * the string - * @param len - * the wrap length - * @param newLineSep - * the new line seperator - * @param soft - * should it be soft wrapped or hard wrapped? - * @return the wrapped words - */ - public static String wrap(String s, int len, String newLineSep, boolean soft) { - return wrap(s, len, newLineSep, soft, " "); - } - - public static String hardWrap(String s, int len) { - StringBuilder ss = new StringBuilder(); - - for(int i = 0; i < s.length(); i += len) { - if(i + len > s.length()) { - ss.append(s, i, s.length()); - break; - } - - ss.append(s, i, i + len).append("\n"); - } - - return ss.toString(); - } - - public static List hardWrapList(String s, int len) { - List l = new ArrayList<>(); - for(int i = 0; i < s.length(); i += len) { - if(i + len > s.length()) { - l.add(s.substring(i)); - break; - } - - l.add(s.substring(i, i + len)); - } - - return l; - } - - - /** - * Wrap words - * - * @param s - * the string - * @param len - * the length - * @param newLineSep - * the new line seperator - * @param soft - * soft or hard wrapping - * @param regex - * the regex - * @return the wrapped string - */ - public static String wrap(String s, int len, String newLineSep, boolean soft, String regex) { - if(s == null) { - return null; - } else { - if(newLineSep == null) { - newLineSep = "\n"; - } - - if(len < 1) { - len = 1; - } - - if(regex.trim().equals("")) { - regex = " "; - } - - Pattern arg4 = Pattern.compile(regex); - int arg5 = s.length(); - int arg6 = 0; - StringBuilder arg7 = new StringBuilder(arg5 + 32); - - while(arg6 < arg5) { - int arg8 = -1; - Matcher arg9 = arg4.matcher(s.substring(arg6, Math.min(arg6 + len + 1, arg5))); - if(arg9.find()) { - if(arg9.start() == 0) { - arg6 += arg9.end(); - continue; - } - - arg8 = arg9.start(); - } - - if(arg5 - arg6 <= len) { - break; - } - - while(arg9.find()) { - arg8 = arg9.start() + arg6; - } - - if(arg8 >= arg6) { - arg7.append(s, arg6, arg8); - arg7.append(newLineSep); - arg6 = arg8 + 1; - } else if(soft) { - arg7.append(s, arg6, len + arg6); - arg7.append(newLineSep); - arg6 += len; - } else { - arg9 = arg4.matcher(s.substring(arg6 + len)); - if(arg9.find()) { - arg8 = arg9.start() + arg6 + len; - } - - if(arg8 >= 0) { - arg7.append(s, arg6, arg8); - arg7.append(newLineSep); - arg6 = arg8 + 1; - } else { - arg7.append(s.substring(arg6)); - arg6 = arg5; - } - } - } - - arg7.append(s.substring(arg6)); - return arg7.toString(); - } - } - - /** - * Returns a fancy duration up to Years - * - * @param duration - * the duration in ms - * @return the fancy duration - */ - public static String duration(RollingSequence rollingSequence, long duration) { - String suffix = "Millisecond"; - double phantom = duration; - int div = 1000; - - if(phantom > div) { - phantom /= div; - suffix = "Second"; - div = 60; - - if(phantom > div) { - phantom /= div; - suffix = "Minute"; - - if(phantom > div) { - phantom /= div; - suffix = "Hour"; - div = 24; - - if(phantom > 24) { - phantom /= div; - suffix = "Day"; - div = 7; - - if(phantom > div) { - phantom /= div; - suffix = "Week"; - div = 4; - - if(phantom > div) { - phantom /= div; - suffix = "Month"; - div = 12; - - //noinspection IfStatementWithIdenticalBranches - if(phantom > div) { - phantom /= div; - suffix = "Year"; - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } else { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } else { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } else { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } else { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } else { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } else { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } else { - return "Under a Second"; - } - } - - /** - * Fixes the minute issue with formatting - * - * @param c - * the calendar - * @return the minute string - */ - public static String fmin(Calendar c) { - String s = c.get(Calendar.MINUTE) + ""; - if(s.length() == 1) { - return "0" + s; - } - - return s; - } - - /** - * Get a fancy time stamp - * - * @param time - * the stamp in time (ago) - * @return the fancy stamp in time (ago) - */ - public static String ago(long time) { - long current = M.ms(); - - if(time > current - TimeUnit.SECONDS.toMillis(30) && time < current) { - return "Just Now"; - } else if(time > current - TimeUnit.SECONDS.toMillis(60) && time < current) { - return "Seconds Ago"; - } else if(time > current - TimeUnit.MINUTES.toMillis(10) && time < current) { - return "Minutes Ago"; - } else { - Calendar now = Calendar.getInstance(); - Calendar c = Calendar.getInstance(); - c.setTimeInMillis(time); - boolean sameYear = now.get(Calendar.YEAR) == c.get(Calendar.YEAR); - boolean sameDay = now.get(Calendar.DAY_OF_YEAR) == c.get(Calendar.DAY_OF_YEAR); - - if(sameDay) { - int h = c.get(Calendar.HOUR); - h = h == 0 ? 12 : h; - - return "Today at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); - } else if(sameYear) { - boolean yesterday = now.get(Calendar.DAY_OF_YEAR) - 1 == c.get(Calendar.DAY_OF_YEAR); - - if(yesterday) { - int h = c.get(Calendar.HOUR); - h = h == 0 ? 12 : h; - - return "Yesterday at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); - } else { - int h = c.get(Calendar.HOUR); - h = h == 0 ? 12 : h; - String dow = switch(c.get(Calendar.DAY_OF_WEEK)) { - case Calendar.SUNDAY -> "Sunday"; - case Calendar.MONDAY -> "Monday"; - case Calendar.TUESDAY -> "Tuesday"; - case Calendar.WEDNESDAY -> "Wednesday"; - case Calendar.THURSDAY -> "Thursday"; - case Calendar.FRIDAY -> "Friday"; - case Calendar.SATURDAY -> "Saturday"; - default -> "Error Day"; - }; - - String monthName = "Error Month"; - int month = c.get(Calendar.MONTH); - - switch(month) { - case Calendar.JANUARY -> monthName = "Jan"; - case Calendar.FEBRUARY -> monthName = "Feb"; - case Calendar.MARCH -> monthName = "Mar"; - case Calendar.APRIL -> monthName = "Apr"; - case Calendar.MAY -> monthName = "May"; - case Calendar.JUNE -> monthName = "Jun"; - case Calendar.JULY -> monthName = "Jul"; - case Calendar.AUGUST -> monthName = "Aug"; - case Calendar.SEPTEMBER -> monthName = "Sep"; - case Calendar.OCTOBER -> monthName = "Oct"; - case Calendar.NOVEMBER -> monthName = "Nov"; - case Calendar.DECEMBER -> monthName = "Dec"; - } - - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - String suffix = numberSuffix(dayOfMonth); - - return dow + ", " + monthName + " " + suffix + " at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); - } - } else { - int h = c.get(Calendar.HOUR); - h = h == 0 ? 12 : h; - String dow = switch(c.get(Calendar.DAY_OF_WEEK)) { - case Calendar.SUNDAY -> "Sunday"; - case Calendar.MONDAY -> "Monday"; - case Calendar.TUESDAY -> "Tuesday"; - case Calendar.WEDNESDAY -> "Wednesday"; - case Calendar.THURSDAY -> "Thursday"; - case Calendar.FRIDAY -> "Friday"; - case Calendar.SATURDAY -> "Saturday"; - default -> "Error Day"; - }; - - String monthName = "Error Month"; - int month = c.get(Calendar.MONTH); - - switch(month) { - case Calendar.JANUARY -> monthName = "Jan"; - case Calendar.FEBRUARY -> monthName = "Feb"; - case Calendar.MARCH -> monthName = "Mar"; - case Calendar.APRIL -> monthName = "Apr"; - case Calendar.MAY -> monthName = "May"; - case Calendar.JUNE -> monthName = "Jun"; - case Calendar.JULY -> monthName = "Jul"; - case Calendar.AUGUST -> monthName = "Aug"; - case Calendar.SEPTEMBER -> monthName = "Sep"; - case Calendar.OCTOBER -> monthName = "Oct"; - case Calendar.NOVEMBER -> monthName = "Nov"; - case Calendar.DECEMBER -> monthName = "Dec"; - } - - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - String suffix = numberSuffix(dayOfMonth); - int year = c.get(Calendar.YEAR); - - return year + ", " + dow + ", " + monthName + " " + suffix + " at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); - } - } - } - - /** - * Get the suffix for a number i.e. 1st 2nd 3rd - * - * @param i - * the number - * @return the suffix - */ - public static String numberSuffix(int i) { - String[] sufixes = new String[] {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}; - return switch(i % 100) { - case 11, 12, 13 -> i + "th"; - default -> i + sufixes[i % 10]; - }; - } - - /** - * Get a high accuracy but limited range duration (accurate up to a couple - * minutes) - * - * @param ms - * the milliseconds (double) - * @param prec - * the precision (decimal format) - * @return the formatted string - */ - public static String duration(double ms, int prec) { - if(ms < 1000.0) { - return Form.f(ms, prec) + "ms"; - } - - if(ms / 1000.0 < 60.0) { - return Form.f(ms / 1000.0, prec) + "s"; - } - - if(ms / 1000.0 / 60.0 < 60.0) { - return Form.f(ms / 1000.0 / 60.0, prec) + "m"; - } - - if(ms / 1000.0 / 60.0 / 60.0 < 24.0) { - return Form.f(ms / 1000.0 / 60.0 / 60.0, prec) + " hours"; - } - - if(ms / 1000.0 / 60.0 / 60.0 / 24.0 < 7) { - return Form.f(ms / 1000.0 / 60.0 / 24.0, prec) + " days"; - } - - return Form.f(ms, prec) + "ms"; - } - - public static String duration(long ms) { - return duration(ms, 0); - } - - /** - * Get a duration from milliseconds up to days - * - * @param ms - * the ms - * @param prec - * the precision (decimal format) - * @return the formatted string - */ - public static String duration(long ms, int prec) { - if(ms < 1000.0) { - return Form.f(ms, prec) + "ms"; - } - - if(ms / 1000.0 < 60.0) { - return Form.f(ms / 1000.0, prec) + " seconds"; - } - - if(ms / 1000.0 / 60.0 < 60.0) { - return Form.f(ms / 1000.0 / 60.0, prec) + " minutes"; - } - - if(ms / 1000.0 / 60.0 / 60.0 < 24.0) { - return Form.f(ms / 1000.0 / 60.0 / 60.0, prec) + " hours"; - } - - if(ms / 1000.0 / 60.0 / 60.0 / 24.0 < 7) { - return Form.f(ms / 1000.0 / 60.0 / 24.0, prec) + " days"; - } - - return Form.f(ms, prec) + "ms"; - } - - /** - * Format a big value - * - * @param i - * the number - * @return the full value in string - */ - public static String b(int i) { - return b(new BigInteger(String.valueOf(i))); - } - - /** - * Format a big value - * - * @param i - * the number - * @return the full value in string - */ - public static String b(long i) { - return b(new BigInteger(String.valueOf(i))); - } - - /** - * Format a big value - * - * @param i - * the number - * @return the full value in string - */ - public static String b(double i) { - return b(new BigInteger(String.valueOf((long) i))); - } - - /** - * Format a big number - * - * @param number - * the big number - * @return the value in string - */ - public static String b(BigInteger number) { - Entry entry = MAP.floorEntry(number); - if(entry == null) { - return "Nearly nothing"; - } - - BigInteger key = entry.getKey(); - BigInteger d = key.divide(THOUSAND); - BigInteger m = number.divide(d); - float f = m.floatValue() / 1000.0f; - float rounded = ((int) (f * 100.0)) / 100.0f; - - if(rounded % 1 == 0) { - return ((int) rounded) + " " + entry.getValue(); - } - - return rounded + " " + entry.getValue(); - } - - /** - * Calculate a fancy string representation of a file size. Adds a suffix of B, - * KB, MB, GB, or TB - * - * @param s - * the size (in bytes) - * @return the string - */ - public static String fileSize(long s) { - return ofSize(s, 1000); - } - - /** - * ":", "a", "b", "c" -> a:b:c - * - * @param splitter - * the splitter that goes in between - * @param strings - * the strings - * @return the result - */ - public static String split(String splitter, String... strings) { - StringBuilder b = new StringBuilder(); - - for(String i : strings) { - b.append(splitter); - b.append(i); - } - - return b.substring(splitter.length()); - } - - /** - * Calculate a fancy string representation of a file size. Adds a suffix of B, - * KB, MB, GB, or TB - * - * @param s - * the size (in bytes) - * @return the string - */ - public static String memSize(long s) { - return ofSize(s, 1024); - } - - public static String memSize(long s, int dec) { - return ofSize(s, 1024, dec); - } - - /** - * Get the timestamp of the time t (ms since 1970) - * - * @param t - * the time - * @return the stamp - */ - @SuppressWarnings("deprecation") - public static String stamp(long t) { - Date d = new Date(t); - return d.getMonth() + "-" + d.getDate() + "-" + (d.getYear() + 1900) + " " + d.getHours() + "h " + d.getMinutes() + "m " + d.getSeconds() + "s "; - } - - @SuppressWarnings("deprecation") - public static String stampTime(long t) { - Date d = new Date(t); - - return Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + forceDoubleDigit(d.getMinutes()) + ":" + forceDoubleDigit(d.getSeconds()); - } - - public static String forceDoubleDigit(int dig) { - if(dig < 10) { - return "0" + dig; - } - - return dig + ""; - } - - @SuppressWarnings("deprecation") - public static String stampDay(long t) { - Date d = new Date(t); - return d.getMonth() + "-" + d.getDate() + "-" + (d.getYear() + 1900); - } - - /** - * Calculate a fancy string representation of a size in B, KB, MB, GB, or TB - * with a special divisor. The divisor decides how much goes up in the suffix - * chain. - * - * @param s - * the size (in bytes) - * @param div - * the divisor - * @return the string - */ - public static String ofSize(long s, int div) { - double d = (double) s; - String sub = "Bytes"; - - if(d > div - 1) { - d /= div; - sub = "KB"; - - if(d > div - 1) { - d /= div; - sub = "MB"; - - if(d > div - 1) { - d /= div; - sub = "GB"; - - if(d > div - 1) { - d /= div; - sub = "TB"; - } - } - } - } - - if(sub.equals("GB") || sub.equals("TB")) { - return Form.f(d, 1) + sub; - } else { - return Form.f(d, 0) + sub; - } - } - - /** - * Calculate a fancy string representation of a size in B, KB, MB, GB, or TB - * with a special divisor. The divisor decides how much goes up in the suffix - * chain. - * - * @param s - * the size (in bytes) - * @param div - * the divisor - * @param dec - * the decimal places - * @return the string - */ - public static String ofSize(long s, int div, int dec) { - double d = (double) s; - String sub = "Bytes"; - - if(d > div - 1) { - d /= div; - sub = "KB"; - - if(d > div - 1) { - d /= div; - sub = "MB"; - - if(d > div - 1) { - d /= div; - sub = "GB"; - - if(d > div - 1) { - d /= div; - sub = "TB"; - } - } - } - } - - return Form.f(d, dec) + " " + sub; - } - - /** - * Calculate a fancy string representation of a size in Grams, KG, MG, GG, TG - * with a special divisor. The divisor decides how much goes up in the suffix - * chain. - * - * @param s - * the size (in bytes) - * @param div - * the divisor - * @param dec - * the decimal places - * @return the string - */ - public static String ofSizeMetricWeight(long s, int div, int dec) { - boolean neg = s < 0; - if(neg) { - s = -s; - } - double d = (double) s; - String sub = "Grams"; - - if(d > div - 1) { - d /= div; - sub = "KG"; - - if(d > div - 1) { - d /= div; - sub = "MG"; - - if(d > div - 1) { - d /= div; - sub = "GG"; - - if(d > div - 1) { - d /= div; - sub = "TG"; - } - } - } - } - - return (neg ? "-" : "") + Form.f(d, dec) + " " + sub; - } - - /** - * Trim a string to a length, then append ... at the end if it extends the limit - * - * @param s - * the string - * @param l - * the limit - * @return the modified string - */ - public static String trim(String s, int l) { - if(s.length() <= l) { - return s; - } - - return s.substring(0, l) + "..."; - } - - /** - * Get a class name into a configuration/filename key For example, - * PhantomController.class is converted to phantom-controller - * - * @param clazz - * the class - * @return the string representation - */ - public static String cname(String clazz) { - StringBuilder codeName = new StringBuilder(); - - for(Character i : clazz.toCharArray()) { - if(Character.isUpperCase(i)) { - codeName.append("-").append(Character.toLowerCase(i)); - } else { - codeName.append(i); - } - } - - if(codeName.toString().startsWith("-")) { - codeName = new StringBuilder(codeName.substring(1)); - } - - return codeName.toString(); - } - - /** - * Get a formatted representation of the memory given in megabytes - * - * @param mb - * the megabytes - * @return the string representation with suffixes - */ - public static String mem(long mb) { - if(mb < 1024) { - return f(mb) + " MB"; - } else { - return f(((double) mb / (double) 1024), 1) + " GB"; - } - } - - /** - * Get a formatted representation of the memory given in kilobytes - * - * @return the string representation with suffixes - */ - public static String memx(long kb) { - if(kb < 1024) { - return fd(kb, 2) + " KB"; - } else { - double mb = (double) kb / 1024.0; - - if(mb < 1024) { - return fd(mb, 2) + " MB"; - } else { - double gb = mb / 1024.0; - - return fd(gb, 2) + " GB"; - } - } - } - - /** - * Format a long. Changes -10334 into -10,334 - * - * @param i - * the number - * @return the string representation of the number - */ - public static String f(long i) { - instantiate(); - return NF.format(i); - } - - /** - * Format a number. Changes -10334 into -10,334 - * - * @param i - * the number - * @return the string representation of the number - */ - public static String f(int i) { - instantiate(); - return NF.format(i); - } - - /** - * Formats a double's decimals to a limit - * - * @param i - * the double - * @param p - * the number of decimal places to use - * @return the formated string - */ - public static String f(double i, int p) { - String form = "#"; - - if(p > 0) { - form = form + "." + repeat("#", p); - } - - DF = new DecimalFormat(form); - - return DF.format(i).replaceAll("\\Q,\\E", "."); - } - - /** - * Formats a double's decimals to a limit, however, this will add zeros to the - * decimal places that dont need to be placed down. 2.4343 formatted with 6 - * decimals gets returned as 2.434300 - * - * @param i - * the double - * @param p - * the number of decimal places to use - * @return the formated string - */ - public static String fd(double i, int p) { - String form = "0"; - - if(p > 0) { - form = form + "." + repeat("0", p); - } - - DF = new DecimalFormat(form); - - return DF.format(i); - } - - /** - * Formats a float's decimals to a limit - * - * @param i - * the float - * @param p - * the number of decimal places to use - * @return the formated string - */ - public static String f(float i, int p) { - String form = "#"; - - if(p > 0) { - form = form + "." + repeat("#", p); - } - - DF = new DecimalFormat(form); - - return DF.format(i); - } - - /** - * Formats a double's decimals (one decimal point) - * - * @param i - * the double - */ - public static String f(double i) { - return f(i, 1); - } - - /** - * Formats a float's decimals (one decimal point) - * - * @param i - * the float - */ - public static String f(float i) { - return f(i, 1); - } - - /** - * Get a percent representation of a double and decimal places (0.53) would - * return 53% - * - * @param i - * the double - * @param p - * the number of decimal points - * @return a string - */ - public static String pc(double i, int p) { - return f(i * 100.0, p) + "%"; - } - - /** - * Get a percent representation of a float and decimal places (0.53) would - * return 53% - * - * @param i - * the float - * @param p - * the number of decimal points - * @return a string - */ - public static String pc(float i, int p) { - return f(i * 100, p) + "%"; - } - - /** - * Get a percent representation of a double and zero decimal places (0.53) would - * return 53% - * - * @param i - * the double - * @return a string - */ - public static String pc(double i) { - return f(i * 100, 0) + "%"; - } - - /** - * Get a percent representation of a float and zero decimal places (0.53) would - * return 53% - * - * @param i - * the double - * @return a string - */ - public static String pc(float i) { - return f(i * 100, 0) + "%"; - } - - /** - * Get a percent as the percent of i out of "of" with custom decimal places - * - * @param i - * the percent out of - * @param of - * of of - * @param p - * the decimal places - * @return the string - */ - public static String pc(int i, int of, int p) { - return f(100.0 * (((double) i) / ((double) of)), p) + "%"; - } - - /** - * Get a percent as the percent of i out of "of" - * - * @param i - * the percent out of - * @param of - * of of - * @return the string - */ - public static String pc(int i, int of) { - return pc(i, of, 0); - } - - /** - * Get a percent as the percent of i out of "of" with custom decimal places - * - * @param i - * the percent out of - * @param of - * of of - * @param p - * the decimal places - * @return the string - */ - public static String pc(long i, long of, int p) { - return f(100.0 * (((double) i) / ((double) of)), p) + "%"; - } - - /** - * Get a percent as the percent of i out of "of" - * - * @param i - * the percent out of - * @param of - * of of - * @return the string - */ - public static String pc(long i, long of) { - return pc(i, of, 0); - } - - /** - * Milliseconds to seconds (double) - * - * @param ms - * the milliseconds - * @return a formatted string to milliseconds - */ - public static String msSeconds(long ms) { - return f((double) ms / 1000.0); - } - - /** - * Milliseconds to seconds (double) custom decimals - * - * @param ms - * the milliseconds - * @param p - * number of decimal points - * @return a formatted string to milliseconds - */ - public static String msSeconds(long ms, int p) { - return f((double) ms / 1000.0, p); - } - - /** - * nanoseconds to seconds (double) - * - * @return a formatted string to nanoseconds - */ - public static String nsMs(long ns) { - return f((double) ns / 1000000.0); - } - - /** - * nanoseconds to seconds (double) custom decimals - * - * @param p - * number of decimal points - * @return a formatted string to nanoseconds - */ - public static String nsMs(long ns, int p) { - return f((double) ns / 1000000.0, p); - } - - /** - * nanoseconds to seconds (double) custom decimals - * - * @param p - * number of decimal points - * @return a formatted string to nanoseconds - */ - public static String nsMsd(long ns, int p) { - return fd((double) ns / 1000000.0, p); - } - - /** - * Get roman numeral representation of the int - * - * @param num - * the int - * @return the numerals - */ - public static String toRoman(int num) { - LinkedHashMap roman_numerals = new LinkedHashMap<>(); - - roman_numerals.put("M", 1000); - roman_numerals.put("CM", 900); - roman_numerals.put("D", 500); - roman_numerals.put("CD", 400); - roman_numerals.put("C", 100); - roman_numerals.put("XC", 90); - roman_numerals.put("L", 50); - roman_numerals.put("XL", 40); - roman_numerals.put("X", 10); - roman_numerals.put("IX", 9); - roman_numerals.put("V", 5); - roman_numerals.put("IV", 4); - roman_numerals.put("I", 1); - - StringBuilder res = new StringBuilder(); - - for(Map.Entry entry : roman_numerals.entrySet()) { - int matches = num / entry.getValue(); - - res.append(repeat(entry.getKey(), matches)); - num = num % entry.getValue(); - } - - return res.toString(); - } - - /** - * Get the number representation from roman numerals. - * - * @param number - * the roman number - * @return the int representation - */ - public static int fromRoman(String number) { - if(number.isEmpty()) { - return 0; - } - - number = number.toUpperCase(); - - if(number.startsWith("M")) { - return 1000 + fromRoman(number.substring(1)); - } - - if(number.startsWith("CM")) { - return 900 + fromRoman(number.substring(2)); - } - - if(number.startsWith("D")) { - return 500 + fromRoman(number.substring(1)); - } - - if(number.startsWith("CD")) { - return 400 + fromRoman(number.substring(2)); - } - - if(number.startsWith("C")) { - return 100 + fromRoman(number.substring(1)); - } - - if(number.startsWith("XC")) { - return 90 + fromRoman(number.substring(2)); - } - - if(number.startsWith("L")) { - return 50 + fromRoman(number.substring(1)); - } - - if(number.startsWith("XL")) { - return 40 + fromRoman(number.substring(2)); - } - - if(number.startsWith("X")) { - return 10 + fromRoman(number.substring(1)); - } - - if(number.startsWith("IX")) { - return 9 + fromRoman(number.substring(2)); - } - - if(number.startsWith("V")) { - return 5 + fromRoman(number.substring(1)); - } - - if(number.startsWith("IV")) { - return 4 + fromRoman(number.substring(2)); - } - - if(number.startsWith("I")) { - return 1 + fromRoman(number.substring(1)); - } - - return 0; - } - - /** - * Repeat a string - * - * @param s - * the string - * @param n - * the amount of times to repeat - * @return the repeated string - */ - @SuppressWarnings("StringRepeatCanBeUsed") - public static String repeat(String s, int n) { - if(s == null) { - return null; - } - - final StringBuilder sb = new StringBuilder(); - - for(int i = 0; i < n; i++) { - sb.append(s); - } - - return sb.toString(); - } -} diff --git a/src/main/java/com/volmit/iris/util/format/MemoryMonitor.java b/src/main/java/com/volmit/iris/util/format/MemoryMonitor.java deleted file mode 100644 index 16e7993b5..000000000 --- a/src/main/java/com/volmit/iris/util/format/MemoryMonitor.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.format; - -import com.volmit.iris.util.math.RollingSequence; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.Looper; - -public class MemoryMonitor { - private Looper looper; - private long usedMemory; - private long garbageMemory; - private long garbageLast; - private long garbageBin; - private long pressure; - private final ChronoLatch cl; - private final RollingSequence pressureAvg; - private final Runtime runtime; - - public MemoryMonitor(int sampleDelay) { - this.runtime = Runtime.getRuntime(); - usedMemory = -1; - pressureAvg = new RollingSequence(Math.max(Math.min(100, 1000 / sampleDelay), 3)); - garbageBin = 0; - garbageMemory = -1; - cl = new ChronoLatch(1000); - garbageLast = 0; - pressure = 0; - - looper = new Looper() { - @Override - protected long loop() { - sample(); - return sampleDelay; - } - }; - looper.setPriority(Thread.MIN_PRIORITY); - looper.setName("Memory Monitor"); - looper.start(); - } - - public long getGarbageBytes() { - return garbageMemory; - } - - public long getUsedBytes() { - return usedMemory; - } - - public long getMaxBytes() { - return runtime.maxMemory(); - } - - public long getPressure() { - return (long) pressureAvg.getAverage(); - } - - public double getUsagePercent() { - return usedMemory / (double) getMaxBytes(); - } - - @SuppressWarnings("IfStatementWithIdenticalBranches") - private void sample() { - long used = getVMUse(); - if(usedMemory == -1) { - usedMemory = used; - garbageMemory = 0; - return; - } - - if(used < usedMemory) { - usedMemory = used; - } else { - garbageMemory = used - usedMemory; - } - - long g = garbageMemory - garbageLast; - - if(g >= 0) { - garbageBin += g; - garbageLast = garbageMemory; - } else { - garbageMemory = 0; - garbageLast = 0; - } - - if(cl.flip()) { - if(garbageMemory > 0) { - pressure = garbageBin; - garbageBin = 0; - } else { - pressure = 0; - garbageBin = 0; - } - } - - pressureAvg.put(pressure); - } - - private long getVMUse() { - return runtime.totalMemory() - runtime.freeMemory(); - } - - public void close() { - if(looper != null) { - looper.interrupt(); - looper = null; - } - } -} diff --git a/src/main/java/com/volmit/iris/util/function/Consumer2.java b/src/main/java/com/volmit/iris/util/function/Consumer2.java deleted file mode 100644 index c068da44a..000000000 --- a/src/main/java/com/volmit/iris/util/function/Consumer2.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@SuppressWarnings({"hiding", "RedundantSuppression"}) -@FunctionalInterface -public interface Consumer2 { - void accept(A a, B b); -} diff --git a/src/main/java/com/volmit/iris/util/function/Consumer2IO.java b/src/main/java/com/volmit/iris/util/function/Consumer2IO.java deleted file mode 100644 index 1ce4f7590..000000000 --- a/src/main/java/com/volmit/iris/util/function/Consumer2IO.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -import java.io.IOException; - -@SuppressWarnings({"hiding", "RedundantSuppression"}) -@FunctionalInterface -public interface Consumer2IO { - void accept(A a, B b) throws IOException; -} diff --git a/src/main/java/com/volmit/iris/util/function/Consumer3.java b/src/main/java/com/volmit/iris/util/function/Consumer3.java deleted file mode 100644 index a6748afd6..000000000 --- a/src/main/java/com/volmit/iris/util/function/Consumer3.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@SuppressWarnings("ALL") -@FunctionalInterface -public interface Consumer3 { - void accept(A a, B b, C c); -} diff --git a/src/main/java/com/volmit/iris/util/function/Consumer4.java b/src/main/java/com/volmit/iris/util/function/Consumer4.java deleted file mode 100644 index 3a96b10b1..000000000 --- a/src/main/java/com/volmit/iris/util/function/Consumer4.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface Consumer4 { - void accept(A a, B b, C c, D d); -} diff --git a/src/main/java/com/volmit/iris/util/function/Consumer4IO.java b/src/main/java/com/volmit/iris/util/function/Consumer4IO.java deleted file mode 100644 index 4a3246e1c..000000000 --- a/src/main/java/com/volmit/iris/util/function/Consumer4IO.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -import java.io.IOException; - -@FunctionalInterface -public interface Consumer4IO { - void accept(A a, B b, C c, D d) throws IOException; -} diff --git a/src/main/java/com/volmit/iris/util/function/Consumer5.java b/src/main/java/com/volmit/iris/util/function/Consumer5.java deleted file mode 100644 index 2101f8f0d..000000000 --- a/src/main/java/com/volmit/iris/util/function/Consumer5.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface Consumer5 { - void accept(A a, B b, C c, D d, E e); -} diff --git a/src/main/java/com/volmit/iris/util/function/Consumer6.java b/src/main/java/com/volmit/iris/util/function/Consumer6.java deleted file mode 100644 index b852bd97e..000000000 --- a/src/main/java/com/volmit/iris/util/function/Consumer6.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface Consumer6 { - void accept(A a, B b, C c, D d, E e, F f); -} diff --git a/src/main/java/com/volmit/iris/util/function/Consumer8.java b/src/main/java/com/volmit/iris/util/function/Consumer8.java deleted file mode 100644 index 996031e04..000000000 --- a/src/main/java/com/volmit/iris/util/function/Consumer8.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface Consumer8 { - void accept(A a, B b, C c, D d, E e, F f, G g, H h); -} diff --git a/src/main/java/com/volmit/iris/util/function/Function2.java b/src/main/java/com/volmit/iris/util/function/Function2.java deleted file mode 100644 index 94c0215ad..000000000 --- a/src/main/java/com/volmit/iris/util/function/Function2.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface Function2 { - R apply(A a, B b); -} diff --git a/src/main/java/com/volmit/iris/util/function/Function3.java b/src/main/java/com/volmit/iris/util/function/Function3.java deleted file mode 100644 index 9801bc068..000000000 --- a/src/main/java/com/volmit/iris/util/function/Function3.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface Function3 { - R apply(A a, B b, C c); -} diff --git a/src/main/java/com/volmit/iris/util/function/Function4.java b/src/main/java/com/volmit/iris/util/function/Function4.java deleted file mode 100644 index 5e0351b31..000000000 --- a/src/main/java/com/volmit/iris/util/function/Function4.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface Function4 { - R apply(A a, B b, C c, D d); -} diff --git a/src/main/java/com/volmit/iris/util/function/NastyFunction.java b/src/main/java/com/volmit/iris/util/function/NastyFunction.java deleted file mode 100644 index f490848a2..000000000 --- a/src/main/java/com/volmit/iris/util/function/NastyFunction.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -public interface NastyFunction { - R run(T t); -} diff --git a/src/main/java/com/volmit/iris/util/function/NastyFuture.java b/src/main/java/com/volmit/iris/util/function/NastyFuture.java deleted file mode 100644 index 51db74ba1..000000000 --- a/src/main/java/com/volmit/iris/util/function/NastyFuture.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -public interface NastyFuture { - R run(); -} diff --git a/src/main/java/com/volmit/iris/util/function/NastyRunnable.java b/src/main/java/com/volmit/iris/util/function/NastyRunnable.java deleted file mode 100644 index 816080153..000000000 --- a/src/main/java/com/volmit/iris/util/function/NastyRunnable.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -public interface NastyRunnable { - void run() throws Throwable; -} diff --git a/src/main/java/com/volmit/iris/util/function/NastySupplier.java b/src/main/java/com/volmit/iris/util/function/NastySupplier.java deleted file mode 100644 index a8b753d33..000000000 --- a/src/main/java/com/volmit/iris/util/function/NastySupplier.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -public interface NastySupplier { - T get() throws Throwable; -} diff --git a/src/main/java/com/volmit/iris/util/function/NoiseInjector.java b/src/main/java/com/volmit/iris/util/function/NoiseInjector.java deleted file mode 100644 index 6a0135929..000000000 --- a/src/main/java/com/volmit/iris/util/function/NoiseInjector.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface NoiseInjector { - double[] combine(double src, double value); -} diff --git a/src/main/java/com/volmit/iris/util/function/NoiseProvider.java b/src/main/java/com/volmit/iris/util/function/NoiseProvider.java deleted file mode 100644 index fe881fc2e..000000000 --- a/src/main/java/com/volmit/iris/util/function/NoiseProvider.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface NoiseProvider { - double noise(double x, double z); -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/function/NoiseProvider3.java b/src/main/java/com/volmit/iris/util/function/NoiseProvider3.java deleted file mode 100644 index 7120c0910..000000000 --- a/src/main/java/com/volmit/iris/util/function/NoiseProvider3.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -@FunctionalInterface -public interface NoiseProvider3 { - double noise(double x, double y, double z); -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/function/Supplier2.java b/src/main/java/com/volmit/iris/util/function/Supplier2.java deleted file mode 100644 index fbe4c5d9b..000000000 --- a/src/main/java/com/volmit/iris/util/function/Supplier2.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -public interface Supplier2 { - void get(T t, TT tt); -} diff --git a/src/main/java/com/volmit/iris/util/function/Supplier3.java b/src/main/java/com/volmit/iris/util/function/Supplier3.java deleted file mode 100644 index f79aed6da..000000000 --- a/src/main/java/com/volmit/iris/util/function/Supplier3.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -public interface Supplier3 { - void get(T t, TT tt, TTT ttt); -} diff --git a/src/main/java/com/volmit/iris/util/function/Supplier3R.java b/src/main/java/com/volmit/iris/util/function/Supplier3R.java deleted file mode 100644 index 77e8c9128..000000000 --- a/src/main/java/com/volmit/iris/util/function/Supplier3R.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.function; - -public interface Supplier3R { - TTTT get(T t, TT tt, TTT ttt); -} diff --git a/src/main/java/com/volmit/iris/util/hunk/Hunk.java b/src/main/java/com/volmit/iris/util/hunk/Hunk.java deleted file mode 100644 index 56f7d3b6f..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/Hunk.java +++ /dev/null @@ -1,1576 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.function.Consumer2; -import com.volmit.iris.util.function.Consumer3; -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.function.Consumer4IO; -import com.volmit.iris.util.function.Consumer5; -import com.volmit.iris.util.function.Consumer6; -import com.volmit.iris.util.function.Consumer8; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.function.Function4; -import com.volmit.iris.util.function.NoiseProvider; -import com.volmit.iris.util.function.NoiseProvider3; -import com.volmit.iris.util.function.Supplier3R; -import com.volmit.iris.util.hunk.storage.ArrayHunk; -import com.volmit.iris.util.hunk.storage.AtomicDoubleHunk; -import com.volmit.iris.util.hunk.storage.AtomicHunk; -import com.volmit.iris.util.hunk.storage.AtomicIntegerHunk; -import com.volmit.iris.util.hunk.storage.AtomicLongHunk; -import com.volmit.iris.util.hunk.storage.MappedHunk; -import com.volmit.iris.util.hunk.storage.SynchronizedArrayHunk; -import com.volmit.iris.util.hunk.view.BiomeGridHunkView; -import com.volmit.iris.util.hunk.view.ChunkBiomeHunkView; -import com.volmit.iris.util.hunk.view.ChunkDataHunkView; -import com.volmit.iris.util.hunk.view.ChunkHunkView; -import com.volmit.iris.util.hunk.view.DriftHunkView; -import com.volmit.iris.util.hunk.view.FringedHunkView; -import com.volmit.iris.util.hunk.view.FunctionalHunkView; -import com.volmit.iris.util.hunk.view.HunkView; -import com.volmit.iris.util.hunk.view.InvertedHunkView; -import com.volmit.iris.util.hunk.view.ListeningHunk; -import com.volmit.iris.util.hunk.view.ReadOnlyHunk; -import com.volmit.iris.util.hunk.view.SynchronizedHunkView; -import com.volmit.iris.util.hunk.view.WriteTrackHunk; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.interpolation.InterpolationMethod3D; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.stream.interpolation.Interpolated; -import org.bukkit.Chunk; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; -import org.bukkit.generator.ChunkGenerator.ChunkData; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Predicate; - -@SuppressWarnings("ALL") -public interface Hunk { - /** - * Create a hunk view from a source hunk. This view reads and writes through to - * the source hunk. Its is not a copy. - * - * @param - * the type - * @param src - * the source hunk - * @return the hunk view - */ - static Hunk view(Hunk src) { - return new HunkView(src); - } - - static Hunk convertedReadView(Hunk src, Function reader) { - return new FunctionalHunkView(src, reader, null); - } - - static Hunk convertedWriteView(Hunk src, Function writer) { - return new FunctionalHunkView(src, null, writer); - } - - static Hunk convertedReadWriteView(Hunk src, Function reader, Function writer) { - return new FunctionalHunkView(src, reader, writer); - } - - static Hunk view(BiomeGrid biome, int minHeight, int maxHeight) { - return new BiomeGridHunkView(biome, minHeight, maxHeight); - } - - static Hunk fringe(Hunk i, Hunk o) { - return new FringedHunkView<>(i, o); - } - - static Hunk view(ChunkData src) { - return new ChunkDataHunkView(src); - } - - static Hunk viewBlocks(Chunk src) { - return new ChunkHunkView(src); - } - - static Hunk viewBiomes(Chunk src) { - return new ChunkBiomeHunkView(src); - } - - static Hunk newHunk(int w, int h, int d) { - return newArrayHunk(w, h, d); - } - - @SafeVarargs - static Hunk newCombinedHunk(Hunk... hunks) { - return newCombinedArrayHunk(hunks); - } - - static Hunk newArrayHunk(int w, int h, int d) { - return new ArrayHunk<>(w, h, d); - } - - @SafeVarargs - static Hunk newCombinedArrayHunk(Hunk... hunks) { - return combined(Hunk::newArrayHunk, hunks); - } - - static Hunk newSynchronizedArrayHunk(int w, int h, int d) { - return new SynchronizedArrayHunk<>(w, h, d); - } - - @SafeVarargs - static Hunk newCombinedSynchronizedArrayHunk(Hunk... hunks) { - return combined(Hunk::newSynchronizedArrayHunk, hunks); - } - - static Hunk newMappedHunk(int w, int h, int d) { - return new MappedHunk<>(w, h, d); - } - - static Hunk newMappedHunkSynced(int w, int h, int d) { - return new MappedHunk(w, h, d).synchronize(); - } - - @SafeVarargs - static Hunk newCombinedMappedHunk(Hunk... hunks) { - return combined(Hunk::newMappedHunk, hunks); - } - - static Hunk newAtomicHunk(int w, int h, int d) { - return new AtomicHunk<>(w, h, d); - } - - @SafeVarargs - static Hunk newCombinedAtomicHunk(Hunk... hunks) { - return combined(Hunk::newAtomicHunk, hunks); - } - - static Hunk newAtomicDoubleHunk(int w, int h, int d) { - return new AtomicDoubleHunk(w, h, d); - } - - @SafeVarargs - static Hunk newCombinedAtomicDoubleHunk(Hunk... hunks) { - return combined(Hunk::newAtomicDoubleHunk, hunks); - } - - static Hunk newAtomicLongHunk(int w, int h, int d) { - return new AtomicLongHunk(w, h, d); - } - - @SafeVarargs - static Hunk newCombinedAtomicLongHunk(Hunk... hunks) { - return combined(Hunk::newAtomicLongHunk, hunks); - } - - static Hunk newAtomicIntegerHunk(int w, int h, int d) { - return new AtomicIntegerHunk(w, h, d); - } - - @SafeVarargs - static Hunk newCombinedAtomicIntegerHunk(Hunk... hunks) { - return combined(Hunk::newAtomicIntegerHunk, hunks); - } - - /** - * Creates a new bounding hunk from the given hunks - * - * @param - * the type - * @param factory - * the factory that creates a hunk - * @param hunks - * the hunks - * @return the new bounding hunk - */ - @SafeVarargs - static Hunk combined(Function3> factory, Hunk... hunks) { - int w = 0; - int h = 0; - int d = 0; - - for(Hunk i : hunks) { - w = Math.max(w, i.getWidth()); - h = Math.max(h, i.getHeight()); - d = Math.max(d, i.getDepth()); - } - - Hunk b = factory.apply(w, h, d); - - for(Hunk i : hunks) { - b.insert(i); - } - - return b; - } - - static void computeDual2D(int parallelism, Hunk a, Hunk b, Consumer5, Hunk> v) { - if(a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight() || a.getDepth() != b.getDepth()) { - throw new RuntimeException("Hunk sizes must match!"); - } - - if(a.get2DDimension(parallelism) == 1) { - v.accept(0, 0, 0, a, b); - return; - } - - BurstExecutor e = MultiBurst.burst.burst(parallelism); - KList rq = new KList(parallelism); - getDualSections2D(parallelism, a, b, (xx, yy, zz, ha, hr, r) -> e.queue(() -> - { - v.accept(xx, yy, zz, ha, hr); - - synchronized(rq) { - rq.add(r); - } - }), (x, y, z, hax, hbx) -> - { - a.insert(x, y, z, hax); - b.insert(x, y, z, hbx); - }); - e.complete(); - rq.forEach(Runnable::run); - return; - } - - static void getDualSections2D(int sections, Hunk a, Hunk b, Consumer6, Hunk, Runnable> v, Consumer5, Hunk> inserterAB) { - if(a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight() || a.getDepth() != b.getDepth()) { - throw new RuntimeException("Hunk sizes must match!"); - } - - int dim = a.get2DDimension(sections); - - if(sections <= 1) { - getDualSection(0, 0, 0, a.getWidth(), a.getHeight(), a.getDepth(), a, b, (ha, hr, r) -> v.accept(0, 0, 0, ha, hr, r), inserterAB); - return; - } - - int w = a.getWidth() / dim; - int wr = a.getWidth() - (w * dim); - int d = a.getDepth() / dim; - int dr = a.getDepth() - (d * dim); - int i, j; - - for(i = 0; i < a.getWidth(); i += w) { - int ii = i; - - for(j = 0; j < a.getDepth(); j += d) { - int jj = j; - getDualSection(i, 0, j, i + w + (i == 0 ? wr : 0), a.getHeight(), j + d + (j == 0 ? dr : 0), a, b, (ha, hr, r) -> v.accept(ii, 0, jj, ha, hr, r), inserterAB); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + dr : j; - } - } - } - - static void getDualSection(int x, int y, int z, int x1, int y1, int z1, Hunk a, Hunk b, Consumer3, Hunk, Runnable> v, Consumer5, Hunk> inserter) { - Hunk copya = a.crop(x, y, z, x1, y1, z1); - Hunk copyb = b.crop(x, y, z, x1, y1, z1); - v.accept(copya, copyb, () -> inserter.accept(x, y, z, copya, copyb)); - } - - /** - * Create a hunk that is optimized for specific uses - * - * @param w - * width - * @param h - * height - * @param d - * depth - * @param type - * the class type - * @param packed - * if the hunk is generally more than 50% full (non-null nodes) - * @param concurrent - * if this hunk must be thread safe - * @param - * the type - * @return the hunk - */ - static Hunk newHunk(int w, int h, int d, Class type, boolean packed, boolean concurrent) { - if(type.equals(Double.class)) { - return concurrent ? - packed ? (Hunk) newAtomicDoubleHunk(w, h, d) : newMappedHunk(w, h, d) - : packed ? newArrayHunk(w, h, d) : newMappedHunkSynced(w, h, d); - } - - if(type.equals(Integer.class)) { - return concurrent ? - packed ? (Hunk) newAtomicIntegerHunk(w, h, d) : newMappedHunk(w, h, d) - : packed ? newArrayHunk(w, h, d) : newMappedHunkSynced(w, h, d); - } - - if(type.equals(Long.class)) { - return concurrent ? - packed ? (Hunk) newAtomicLongHunk(w, h, d) : newMappedHunk(w, h, d) - : packed ? newArrayHunk(w, h, d) : newMappedHunkSynced(w, h, d); - } - - return concurrent ? - packed ? newAtomicHunk(w, h, d) : newMappedHunk(w, h, d) - : packed ? newArrayHunk(w, h, d) : newMappedHunkSynced(w, h, d); - } - - static IrisPosition rotatedBounding(int w, int h, int d, double x, double y, double z) { - int[] iii = {0, 0, 0}; - int[] aaa = {w, h, d}; - int[] aai = {w, h, 0}; - int[] iaa = {0, h, d}; - int[] aia = {w, 0, d}; - int[] iai = {0, h, 0}; - int[] iia = {0, 0, d}; - int[] aii = {w, 0, 0}; - rotate(x, y, z, iii); - rotate(x, y, z, aaa); - rotate(x, y, z, aai); - rotate(x, y, z, iaa); - rotate(x, y, z, aia); - rotate(x, y, z, iai); - rotate(x, y, z, iia); - rotate(x, y, z, aii); - int maxX = max(iii[0], aaa[0], aai[0], iaa[0], aia[0], iai[0], iia[0], aii[0]); - int minX = min(iii[0], aaa[0], aai[0], iaa[0], aia[0], iai[0], iia[0], aii[0]); - int maxY = max(iii[1], aaa[1], aai[1], iaa[1], aia[1], iai[1], iia[1], aii[1]); - int minY = min(iii[1], aaa[1], aai[1], iaa[1], aia[1], iai[1], iia[1], aii[1]); - int maxZ = max(iii[2], aaa[2], aai[2], iaa[2], aia[2], iai[2], iia[2], aii[2]); - int minZ = min(iii[2], aaa[2], aai[2], iaa[2], aia[2], iai[2], iia[2], aii[2]); - return new IrisPosition(maxX - minX, maxY - minY, maxZ - minZ); - } - - static int max(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8) { - return Math.max(Math.max(Math.max(a5, a6), Math.max(a7, a8)), Math.max(Math.max(a1, a2), Math.max(a3, a4))); - } - - static int min(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8) { - return Math.min(Math.min(Math.min(a5, a6), Math.min(a7, a8)), Math.min(Math.min(a1, a2), Math.min(a3, a4))); - } - - static void rotate(double x, double y, double z, int[] c) { - if(x % 360 != 0) { - rotateAroundX(Math.toRadians(x), c); - } - - if(y % 360 != 0) { - rotateAroundY(Math.toRadians(y), c); - } - - if(z % 360 != 0) { - rotateAroundZ(Math.toRadians(z), c); - } - } - - static void rotateAroundX(double a, int[] c) { - rotateAroundX(Math.cos(a), Math.sin(a), c); - } - - static void rotateAroundX(double cos, double sin, int[] c) { - int y = (int) Math.floor(cos * (double) (c[1] + 0.5) - sin * (double) (c[2] + 0.5)); - int z = (int) Math.floor(sin * (double) (c[1] + 0.5) + cos * (double) (c[2] + 0.5)); - c[1] = y; - c[2] = z; - } - - static void rotateAroundY(double a, int[] c) { - rotateAroundY(Math.cos(a), Math.sin(a), c); - } - - static void rotateAroundY(double cos, double sin, int[] c) { - int x = (int) Math.floor(cos * (double) (c[0] + 0.5) + sin * (double) (c[2] + 0.5)); - int z = (int) Math.floor(-sin * (double) (c[0] + 0.5) + cos * (double) (c[2] + 0.5)); - c[0] = x; - c[2] = z; - } - - static void rotateAroundZ(double a, int[] c) { - rotateAroundZ(Math.cos(a), Math.sin(a), c); - } - - static void rotateAroundZ(double cos, double sin, int[] c) { - int x = (int) Math.floor(cos * (double) (c[0] + 0.5) - sin * (double) (c[1] + 0.5)); - int y = (int) Math.floor(sin * (double) (c[0] + 0.5) + cos * (double) (c[1] + 0.5)); - c[0] = x; - c[1] = y; - } - - default boolean isMapped() { - return false; - } - - default int getEntryCount() { - return getWidth() * getHeight() * getDepth(); - } - - default Hunk listen(Consumer4 l) { - return new ListeningHunk<>(this, l); - } - - default Hunk synchronize() { - return new SynchronizedHunkView<>(this); - } - - default Hunk trackWrite(AtomicBoolean b) { - return new WriteTrackHunk(this, b); - } - - default Hunk readOnly() { - return new ReadOnlyHunk<>(this); - } - - default int getNonNullEntries() { - AtomicInteger count = new AtomicInteger(); - iterate((x, y, z, v) -> count.getAndAdd(1)); - - return count.get(); - } - - default boolean isAtomic() { - return false; - } - - default Hunk invertY() { - return new InvertedHunkView(this); - } - - default int getMaximumDimension() { - return Math.max(getWidth(), Math.max(getHeight(), getDepth())); - } - - default int getIdeal2DParallelism() { - return getMax2DParallelism() / 4; - } - - default int getIdeal3DParallelism() { - return getMax3DParallelism() / 8; - } - - default int getMinimumDimension() { - return Math.min(getWidth(), Math.min(getHeight(), getDepth())); - } - - default int getMax2DParallelism() { - return (int) Math.pow(getMinimumDimension() / 2f, 2); - } - - default int getMax3DParallelism() { - return (int) Math.pow(getMinimumDimension() / 2f, 3); - } - - default int filterDimension(int dim) { - if(dim <= 1) { - return 1; - } - - dim = dim % 2 != 0 ? dim + 1 : dim; - - if(dim > getMinimumDimension() / 2) { - if(dim <= 2) { - return 1; - } - - dim -= 2; - } - - return dim; - } - - default int get2DDimension(int sections) { - if(sections <= 1) { - return 1; - } - - return filterDimension((int) Math.ceil(Math.sqrt(sections))); - } - - default int get3DDimension(int sections) { - if(sections <= 1) { - return 1; - } - - return filterDimension((int) Math.ceil(Math.cbrt(sections))); - } - - /** - * Iterate surfaces on 2d. Raytraces with a front and a back which stretches - * through surfaces. Essentially what is returned is the following (in - * order)
- *
- *

- * The predicate is used to determine if the given block type is solid or not. - * - *
- *
- * ================================================
- * AX, AZ: Hunk Relative X and Z - * - *
- *
- * HX, HZ: Hunk Positional X and Z (in its parent hunk) - * - *
- *
- * TOP: The top of this surface (top+1 is air above a surface) - * - *
- *
- * BOTTOM: The bottom of this surface (bottom is the lowest SOLID surface before - * either air or bedrock going down further) - * - *
- *
- * LAST_BOTTOM: The previous bottom. If your surface is the top surface, this - * will be -1 as there is no bottom-of-surface above you. However if you are not - * the top surface, this value is equal to the next solid layer above TOP, such - * that ((LAST_BOTTOM - 1) - (TOP + 1)) is how many air blocks are between your - * surface and the surface above you - * - *
- *
- * HUNK: The hunk to set data to.
- * ================================================
- *
- * If we assume your chunk coordinates are x and z, then
- *
- * bX = (x * 16)
- * bZ = (z * 16)
- *
- * (ax, az, hx, hz, top, bottom, lastBottom, hunk) {
- * actualBlockX = ax+hx;
- * actualBlockZ = az+hz;
- *
- * hunkX = ax;
- * hunkZ = az;
- *
- * hunk.set(hunkX, ?, hunkZ, noise(actualBlockX, ?, actualBlockZ));
- * }
- * - * @param p - * the predicate - * @param c - * the consumer - * @return this - */ - default Hunk iterateSurfaces2D(Predicate p, Consumer8> c) { - return iterateSurfaces2D(getIdeal2DParallelism(), p, c); - } - - /** - * Iterate surfaces on 2d. Raytraces with a front and a back which stretches - * through surfaces. Essentially what is returned is the following (in - * order)
- *
- *

- * The predicate is used to determine if the given block type is solid or not. - * - *
- *
- * ================================================
- * AX, AZ: Hunk Relative X and Z - * - *
- *
- * HX, HZ: Hunk Positional X and Z (in its parent hunk) - * - *
- *
- * TOP: The top of this surface (top+1 is air above a surface) - * - *
- *
- * BOTTOM: The bottom of this surface (bottom is the lowest SOLID surface before - * either air or bedrock going down further) - * - *
- *
- * LAST_BOTTOM: The previous bottom. If your surface is the top surface, this - * will be -1 as there is no bottom-of-surface above you. However if you are not - * the top surface, this value is equal to the next solid layer above TOP, such - * that ((LAST_BOTTOM - 1) - (TOP + 1)) is how many air blocks are between your - * surface and the surface above you - * - *
- *
- * HUNK: The hunk to set data to.
- * ================================================
- *
- * If we assume your chunk coordinates are x and z, then
- *
- * bX = (x * 16)
- * bZ = (z * 16)
- *
- * (ax, az, hx, hz, top, bottom, lastBottom, hunk) {
- * actualBlockX = ax+hx;
- * actualBlockZ = az+hz;
- *
- * hunkX = ax;
- * hunkZ = az;
- *
- * hunk.set(hunkX, ?, hunkZ, noise(actualBlockX, ?, actualBlockZ));
- * }
- * - * @param parallelism - * the ideal threads to use on this - * @param p - * the predicate - * @param c - * the consumer - * @return this - */ - default Hunk iterateSurfaces2D(int parallelism, Predicate p, Consumer8> c) { - iterate2DTop(parallelism, (ax, az, hox, hoz, h) -> - { - int last = -1; - int in = getHeight() - 1; - boolean hitting = false; - for(int i = getHeight() - 1; i >= 0; i--) { - boolean solid = p.test(h.get(ax, i, az)); - - if(!hitting && solid) { - in = i; - hitting = true; - } else if(hitting && !solid) { - hitting = false; - c.accept(ax, az, hox, hoz, in, i - 1, last, h); - last = i - 1; - } - } - - if(hitting) { - c.accept(ax, az, hox, hoz, in, 0, last, h); - } - }); - - return this; - } - - /** - * Iterate on the xz top of this hunk. When using this consumer, given - *

- * consumer: (ax, az, hx, hz, hunk) - *

- * hunk.set(ax, ?, az, NOISE.get(ax+hx, az+hz)); - * - * @param c - * the consumer hunkX, hunkZ, hunkOffsetX, hunkOffsetZ. - * @return this - */ - default Hunk iterate2DTop(Consumer5> c) { - return iterate2DTop(getIdeal2DParallelism(), c); - } - - default Hunk drift(int x, int y, int z) { - return new DriftHunkView<>(this, x, y, z); - } - - /** - * Iterate on the xz top of this hunk. When using this consumer, given - *

- * consumer: (ax, az, hx, hz, hunk) - *

- * hunk.set(ax, ?, az, NOISE.get(ax+hx, az+hz)); - * - * @param parallelism - * the target parallelism value or 0 to disable - * @param c - * the consumer hunkX, hunkZ, hunkOffsetX, hunkOffsetZ. - * @return this - */ - default Hunk iterate2DTop(int parallelism, Consumer5> c) { - compute2D(parallelism, (x, y, z, h) -> - { - for(int i = 0; i < h.getWidth(); i++) { - for(int k = 0; k < h.getDepth(); k++) { - c.accept(i, k, x, z, h); - } - } - }); - - return this; - } - - default Hunk iterate(Predicate p, Consumer3 c) { - return iterate(getIdeal3DParallelism(), p, c); - } - - default Hunk iterate(int parallelism, Predicate p, Consumer3 c) { - iterate(parallelism, (x, y, z, t) -> - { - if(p.test(t)) { - c.accept(x, y, z); - } - }); - - return this; - } - - default Hunk iterate(Predicate p, Consumer4 c) { - return iterate(getIdeal3DParallelism(), p, c); - } - - default Hunk iterate(int parallelism, Predicate p, Consumer4 c) { - iterate(parallelism, (x, y, z, t) -> - { - if(p.test(t)) { - c.accept(x, y, z, t); - } - }); - - return this; - } - - default Hunk iterate(Consumer3 c) { - return iterate(getIdeal3DParallelism(), c); - } - - default Hunk iterateSync(Consumer3 c) { - for(int i = 0; i < getWidth(); i++) { - for(int j = 0; j < getHeight(); j++) { - for(int k = 0; k < getDepth(); k++) { - c.accept(i, j, k); - } - } - } - - return this; - } - - default Hunk iterateSync(Consumer4 c) { - for(int i = 0; i < getWidth(); i++) { - for(int j = 0; j < getHeight(); j++) { - for(int k = 0; k < getDepth(); k++) { - c.accept(i, j, k, get(i, j, k)); - } - } - } - - return this; - } - - default Hunk updateSync(Function4 c) { - for(int i = 0; i < getWidth(); i++) { - for(int j = 0; j < getHeight(); j++) { - for(int k = 0; k < getDepth(); k++) { - set(i, j, k, c.apply(i, j, k, get(i, j, k))); - } - } - } - - return this; - } - - default Hunk iterateSyncIO(Consumer4IO c) throws IOException { - for(int i = 0; i < getWidth(); i++) { - for(int j = 0; j < getHeight(); j++) { - for(int k = 0; k < getDepth(); k++) { - c.accept(i, j, k, get(i, j, k)); - } - } - } - - return this; - } - - default Hunk iterate(int parallelism, Consumer3 c) { - compute3D(parallelism, (x, y, z, h) -> - { - for(int i = 0; i < h.getWidth(); i++) { - for(int j = 0; j < h.getHeight(); j++) { - for(int k = 0; k < h.getDepth(); k++) { - c.accept(i + x, j + y, k + z); - } - } - } - }); - - return this; - } - - default Hunk iterate(Consumer4 c) { - return iterate(getIdeal3DParallelism(), c); - } - - default Hunk iterate(int parallelism, Consumer4 c) { - compute3D(parallelism, (x, y, z, h) -> - { - for(int i = 0; i < h.getWidth(); i++) { - for(int j = 0; j < h.getHeight(); j++) { - for(int k = 0; k < h.getDepth(); k++) { - c.accept(i + x, j + y, k + z, h.get(i, j, k)); - } - } - } - }); - - return this; - } - - default Hunk compute2D(Consumer4> v) { - return compute2D(getIdeal2DParallelism(), v); - } - - default Hunk compute2D(int parallelism, Consumer4> v) { - if(get2DDimension(parallelism) == 1) { - v.accept(0, 0, 0, this); - return this; - } - - BurstExecutor e = MultiBurst.burst.burst(parallelism); - - if(isAtomic()) { - getSectionsAtomic2D(parallelism, (xx, yy, zz, h) -> e.queue(() -> - { - v.accept(xx, yy, zz, h); - })); - - e.complete(); - } else { - KList rq = new KList(parallelism); - - getSections2D(parallelism, (xx, yy, zz, h, r) -> e.queue(() -> - { - v.accept(xx, yy, zz, h); - - synchronized(rq) { - rq.add(r); - } - }), this::insert); - - e.complete(); - rq.forEach(Runnable::run); - } - - return this; - } - - default Hunk compute2DYRange(int parallelism, int ymin, int ymax, Consumer4> v) { - if(get2DDimension(parallelism) == 1) { - v.accept(0, 0, 0, this); - return this; - } - - BurstExecutor e = MultiBurst.burst.burst(parallelism); - KList rq = new KList(parallelism); - getSections2DYLimit(parallelism, ymin, ymax, (xx, yy, zz, h, r) -> e.queue(() -> - { - v.accept(xx, yy, zz, h); - - synchronized(rq) { - rq.add(r); - } - }), this::insert); - e.complete(); - rq.forEach(Runnable::run); - return this; - } - - default Hunk compute3D(Consumer4> v) { - return compute3D(getIdeal3DParallelism(), v); - } - - default Hunk compute3D(int parallelism, Consumer4> v) { - if(get3DDimension(parallelism) == 1) { - v.accept(0, 0, 0, this); - return this; - } - - BurstExecutor e = MultiBurst.burst.burst(parallelism); - KList rq = new KList(parallelism); - getSections3D(parallelism, (xx, yy, zz, h, r) -> e.queue(() -> - { - v.accept(xx, yy, zz, h); - synchronized(rq) { - rq.add(r); - } - }), this::insert); - e.complete(); - rq.forEach(Runnable::run); - return this; - } - - default Hunk getSections2D(int sections, Consumer5, Runnable> v) { - return getSections2D(sections, v, this::insert); - } - - default Hunk getSectionsAtomic2D(int sections, Consumer4> v) { - int dim = get2DDimension(sections); - - if(sections <= 1) { - getAtomicSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh) -> v.accept(0, 0, 0, hh)); - return this; - } - - int w = getWidth() / dim; - int wr = getWidth() - (w * dim); - int d = getDepth() / dim; - int dr = getDepth() - (d * dim); - int i, j; - - for(i = 0; i < getWidth(); i += w) { - int ii = i; - - for(j = 0; j < getDepth(); j += d) { - int jj = j; - getAtomicSection(i, 0, j, i + w + (i == 0 ? wr : 0), getHeight(), j + d + (j == 0 ? dr : 0), (h) -> v.accept(ii, 0, jj, h)); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + dr : j; - } - } - - return this; - } - - default Hunk getSections2D(int sections, Consumer5, Runnable> v, Consumer4> inserter) { - int dim = get2DDimension(sections); - - if(sections <= 1) { - getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); - return this; - } - - int w = getWidth() / dim; - int wr = getWidth() - (w * dim); - int d = getDepth() / dim; - int dr = getDepth() - (d * dim); - int i, j; - - for(i = 0; i < getWidth(); i += w) { - int ii = i; - - for(j = 0; j < getDepth(); j += d) { - int jj = j; - getSection(i, 0, j, i + w + (i == 0 ? wr : 0), getHeight(), j + d + (j == 0 ? dr : 0), (h, r) -> v.accept(ii, 0, jj, h, r), inserter); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + dr : j; - } - } - - return this; - } - - default Hunk getSections2DYLimit(int sections, int ymin, int ymax, Consumer5, Runnable> v, Consumer4> inserter) { - int dim = get2DDimension(sections); - - if(sections <= 1) { - getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); - return this; - } - - int w = getWidth() / dim; - int wr = getWidth() - (w * dim); - int d = getDepth() / dim; - int dr = getDepth() - (d * dim); - int i, j; - - for(i = 0; i < getWidth(); i += w) { - int ii = i; - - for(j = 0; j < getDepth(); j += d) { - int jj = j; - getSection(i, ymin, j, i + w + (i == 0 ? wr : 0), ymax, j + d + (j == 0 ? dr : 0), (h, r) -> v.accept(ii, ymin, jj, h, r), inserter); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + dr : j; - } - } - - return this; - } - - default Hunk getSections3D(int sections, Consumer5, Runnable> v) { - return getSections3D(sections, v, (xx, yy, zz, c) -> insert(xx, yy, zz, c)); - } - - default Hunk getSections3D(int sections, Consumer5, Runnable> v, Consumer4> inserter) { - int dim = get3DDimension(sections); - - if(sections <= 1) { - getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); - return this; - } - - int w = getWidth() / dim; - int h = getHeight() / dim; - int d = getDepth() / dim; - int wr = getWidth() - (w * dim); - int hr = getHeight() - (h * dim); - int dr = getDepth() - (d * dim); - int i, j, k; - - for(i = 0; i < getWidth(); i += w) { - int ii = i; - - for(j = 0; j < getHeight(); j += d) { - int jj = j; - - for(k = 0; k < getDepth(); k += d) { - int kk = k; - getSection(ii, jj, kk, i + w + (i == 0 ? wr : 0), j + h + (j == 0 ? hr : 0), k + d + (k == 0 ? dr : 0), (hh, r) -> v.accept(ii, jj, kk, hh, r), inserter); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + hr : j; - k = k == 0 ? k + dr : k; - } - } - } - - return this; - } - - default Hunk getSection(int x, int y, int z, int x1, int y1, int z1, Consumer2, Runnable> v) { - return getSection(x, y, z, x1, y1, z1, v, (xx, yy, zz, c) -> insert(xx, yy, zz, c)); - } - - default Hunk getSection(int x, int y, int z, int x1, int y1, int z1, Consumer2, Runnable> v, Consumer4> inserter) { - Hunk copy = crop(x, y, z, x1, y1, z1); - v.accept(copy, () -> inserter.accept(x, y, z, copy)); - return this; - } - - default Hunk getAtomicSection(int x, int y, int z, int x1, int y1, int z1, Consumer> v) { - Hunk copy = croppedView(x, y, z, x1, y1, z1); - v.accept(copy); - return this; - } - - /** - * Create a new hunk from a section of this hunk. - * - * @param x1 - * The min x (inclusive) - * @param y1 - * The min y (inclusive) - * @param z1 - * The min z (inclusive) - * @param x2 - * The max x (exclusive) - * @param y2 - * The max y (exclusive) - * @param z2 - * The max z (exclusive) - * @return the new hunk (x2-x1, y2-y1, z2-z1) - */ - default ArrayHunk crop(int x1, int y1, int z1, int x2, int y2, int z2) { - ArrayHunk h = new ArrayHunk(x2 - x1, y2 - y1, z2 - z1); - - for(int i = x1; i < x2; i++) { - for(int j = y1; j < y2; j++) { - for(int k = z1; k < z2; k++) { - h.setRaw(i - x1, j - y1, k - z1, getRaw(i, j, k)); - } - } - } - - return h; - } - - /** - * Create a new view of this same hunk from a section of this hunk. - * Modifications are routed to this hunk! - * - * @param x1 - * The min x (inclusive) - * @param y1 - * The min y (inclusive) - * @param z1 - * The min z (inclusive) - * @param x2 - * The max x (exclusive) - * @param y2 - * The max y (exclusive) - * @param z2 - * The max z (exclusive) - * @return the cropped view of this hunk (x2-x1, y2-y1, z2-z1) - */ - default Hunk croppedView(int x1, int y1, int z1, int x2, int y2, int z2) { - return new HunkView(this, x2 - x1, y2 - y1, z2 - z1, x1, y1, z1); - } - - /** - * @return The X length - */ - int getWidth(); - - /** - * @return The Z length - */ - int getDepth(); - - /** - * @return The Y length - */ - int getHeight(); - - /** - * Set a region - * - * @param x1 - * inclusive 1st x - * @param y1 - * inclusive 1st y - * @param z1 - * inclusive 1st z - * @param x2 - * inclusive 2nd x - * @param y2 - * inclusive 2nd y - * @param z2 - * inclusive 2nd z - * @param t - * the value to set - */ - default void set(int x1, int y1, int z1, int x2, int y2, int z2, T t) { - for(int i = x1; i <= x2; i++) { - for(int j = y1; j <= y2; j++) { - for(int k = z1; k <= z2; k++) { - setRaw(i, j, k, t); - } - } - } - } - - /** - * Get the value to the closest valid position - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @return the value closest to the border of the hunk - */ - default T getClosest(int x, int y, int z) { - return getRaw(x >= getWidth() ? getWidth() - 1 : x < 0 ? 0 : x, y >= getHeight() ? getHeight() - 1 : y < 0 ? 0 : y, z >= getDepth() ? getDepth() - 1 : z < 0 ? 0 : z); - } - - default BlockPosition getCenter() { - return new BlockPosition(getCenterX(), getCenterY(), getCenterZ()); - } - - default int getCenterX() { - return (int) Math.floor(getWidth() / 2); - } - - default int getCenterY() { - return (int) Math.floor(getHeight() / 2); - } - - default int getCenterZ() { - return (int) Math.floor(getDepth() / 2); - } - - default void fill(T t) { - set(0, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1, t); - } - - /** - * Get a 1 node thick hunk representing the face of this hunk - * - * @param f - * the face - * @return the hunk view of this hunk - */ - default Hunk viewFace(HunkFace f) { - switch(f) { - case BOTTOM: - return croppedView(0, 0, 0, getWidth() - 1, 0, getDepth() - 1); - case EAST: - return croppedView(getWidth() - 1, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); - case NORTH: - return croppedView(0, 0, 0, getWidth() - 1, getHeight() - 1, 0); - case SOUTH: - return croppedView(0, 0, 0, 0, getHeight() - 1, getDepth() - 1); - case TOP: - return croppedView(0, getHeight() - 1, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); - case WEST: - return croppedView(0, 0, getDepth() - 1, getWidth() - 1, getHeight() - 1, getDepth() - 1); - default: - break; - } - - return null; - } - - /** - * Crop (copy) a 1 node thick hunk representing the face of this hunk - * - * @param f - * the face - * @return the hunk copy (face) of this hunk - */ - default Hunk cropFace(HunkFace f) { - switch(f) { - case BOTTOM: - return crop(0, 0, 0, getWidth() - 1, 0, getDepth() - 1); - case EAST: - return crop(getWidth() - 1, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); - case NORTH: - return crop(0, 0, 0, getWidth() - 1, getHeight() - 1, 0); - case SOUTH: - return crop(0, 0, 0, 0, getHeight() - 1, getDepth() - 1); - case TOP: - return crop(0, getHeight() - 1, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); - case WEST: - return crop(0, 0, getDepth() - 1, getWidth() - 1, getHeight() - 1, getDepth() - 1); - default: - break; - } - - return null; - } - - /** - * Set a value at the given position - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @param t - * the value - */ - default void set(int x, int y, int z, T t) { - if(!contains(x, y, z)) - { - Iris.warn("OUT OF BOUNDS " + x + " " + y + " "+ z + " in bounds " + getWidth() + " " + getHeight() + " " + getDepth() ); - return; - } - - setRaw(x, y, z, t); - } - - default void setIfExists(int x, int y, int z, T t) { - if(x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth()) { - return; - } - - setRaw(x, y, z, t); - } - - default T getIfExists(int x, int y, int z, T t) { - if(x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth()) { - return t; - } - - return getOr(x, y, z, t); - } - - default T getIfExists(int x, int y, int z) { - return getIfExists(x, y, z, null); - } - - /** - * Set a value at the given position without checking coordinate bounds - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @param t - * the value - */ - void setRaw(int x, int y, int z, T t); - - /** - * Get a value at the given position without checking coordinate bounds - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @return the value or null - */ - T getRaw(int x, int y, int z); - - /** - * Get a value at the given position - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @return the value or null - */ - default T get(int x, int y, int z) { - return getRaw(x, y, z); - } - - default T getOr(int x, int y, int z, T t) { - T v = getRaw(x, y, z); - - if(v == null) { - return t; - } - - return v; - } - - /** - * Insert a hunk into this one with an offset the inserted hunk - * - * @param offX - * the offset from zero for x - * @param offY - * the offset from zero for y - * @param offZ - * the offset from zero for z - * @param hunk - * the hunk to insert - */ - default void insert(int offX, int offY, int offZ, Hunk hunk) { - insert(offX, offY, offZ, hunk, false); - } - - default void insertSoftly(int offX, int offY, int offZ, Hunk hunk, Predicate shouldOverwrite) { - insertSoftly(offX, offY, offZ, hunk, false, shouldOverwrite); - } - - /** - * Insert a hunk into this one - * - * @param hunk - * the hunk to insert - */ - default void insert(Hunk hunk) { - insert(0, 0, 0, hunk, false); - } - - /** - * Returns the source of this hunk view. This could return another hunk view, - * not an actual source, however it does return it's underlying data source. If - * this hunk is a data source and not a view, it will return null. - * - * @return the source or null if this is already the source - */ - default Hunk getSource() { - return null; - } - - /** - * Insert a hunk into this one - * - * @param hunk - * the hunk to insert - * @param inverted - * invert the inserted hunk or not - */ - default void insert(Hunk hunk, boolean inverted) { - insert(0, 0, 0, hunk, inverted); - } - - /** - * Insert a hunk into this one with an offset and possibly inverting the y of - * the inserted hunk - * - * @param offX - * the offset from zero for x - * @param offY - * the offset from zero for y - * @param offZ - * the offset from zero for z - * @param hunk - * the hunk to insert - * @param invertY - * should the inserted hunk be inverted - */ - default void insert(int offX, int offY, int offZ, Hunk hunk, boolean invertY) { - for(int i = offX; i < offX + hunk.getWidth(); i++) { - for(int j = offY; j < offY + hunk.getHeight(); j++) { - for(int k = offZ; k < offZ + hunk.getDepth(); k++) { - setRaw(i, j, k, hunk.getRaw(i - offX, j - offY, k - offZ)); - } - } - } - } - - /** - * Insert a hunk into this one with an offset and possibly inverting the y of. Will never insert a node if its - * already used - * the inserted hunk - * - * @param offX - * the offset from zero for x - * @param offY - * the offset from zero for y - * @param offZ - * the offset from zero for z - * @param hunk - * the hunk to insert - * @param invertY - * should the inserted hunk be inverted - */ - default void insertSoftly(int offX, int offY, int offZ, Hunk hunk, boolean invertY, Predicate shouldOverwrite) { - for(int i = offX; i < offX + hunk.getWidth(); i++) { - for(int j = offY; j < offY + hunk.getHeight(); j++) { - for(int k = offZ; k < offZ + hunk.getDepth(); k++) { - if(shouldOverwrite.test(getRaw(i, j, k))) { - setRaw(i, j, k, hunk.getRaw(i - offX, j - offY, k - offZ)); - } - } - } - } - } - - /** - * Acts like fill, however if used by a mapped hunk, will simply clear it - * - * @param b - * the data to use for fill - */ - default void empty(T b) { - fill(b); - } - - /** - * Take a hunk and scale it up using interpolation - * - * @param scale - * the scale - * @param d - * the interpolation method - * @param interpolated - * the interpolated value converter - * @return the new hunk - */ - default Hunk interpolate3D(double scale, InterpolationMethod3D d, Interpolated interpolated) { - Hunk t = Hunk.newArrayHunk((int) (getWidth() * scale), (int) (getHeight() * scale), (int) (getDepth() * scale)); - NoiseProvider3 n3 = (x, y, z) -> interpolated.toDouble( - t.get((int) (x / scale), - (int) (y / scale), - (int) (z / scale))); - - for(int i = 0; i < t.getWidth(); i++) { - for(int j = 0; j < t.getHeight(); j++) { - for(int k = 0; k < t.getDepth(); k++) { - t.set(i, j, k, interpolated.fromDouble(IrisInterpolation.getNoise3D(d, i, j, k, scale, n3))); - } - } - } - - return t; - } - - /** - * Take a hunk and scale it up using interpolation - * 2D, (using only x and z) assumes the height is 1 - * - * @param scale - * the scale - * @param d - * the interpolation method - * @param interpolated - * the interpolated value converter - * @return the new hunk - */ - default Hunk interpolate2D(double scale, InterpolationMethod d, Interpolated interpolated) { - Hunk t = Hunk.newArrayHunk((int) (getWidth() * scale), 1, (int) (getDepth() * scale)); - NoiseProvider n2 = (x, z) -> interpolated.toDouble( - t.get((int) (x / scale), - 0, - (int) (z / scale))); - - for(int i = 0; i < t.getWidth(); i++) { - for(int j = 0; j < t.getDepth(); j++) { - t.set(i, 0, j, interpolated.fromDouble(IrisInterpolation.getNoise(d, i, j, scale, n2))); - } - } - - return t; - } - - default Hunk rotate(double x, double y, double z, Supplier3R> builder) { - int w = getWidth(); - int h = getHeight(); - int d = getDepth(); - int i, j, k; - int[] c = {w / 2, h / 2, d / 2}; - int[] b = {0, 0, 0}; - int[] iii = {0, 0, 0}; - int[] aaa = {w, h, d}; - int[] aai = {w, h, 0}; - int[] iaa = {0, h, d}; - int[] aia = {w, 0, d}; - int[] iai = {0, h, 0}; - int[] iia = {0, 0, d}; - int[] aii = {w, 0, 0}; - rotate(x, y, z, iii); - rotate(x, y, z, aaa); - rotate(x, y, z, aai); - rotate(x, y, z, iaa); - rotate(x, y, z, aia); - rotate(x, y, z, iai); - rotate(x, y, z, iia); - rotate(x, y, z, aii); - int maxX = max(iii[0], aaa[0], aai[0], iaa[0], aia[0], iai[0], iia[0], aii[0]); - int minX = min(iii[0], aaa[0], aai[0], iaa[0], aia[0], iai[0], iia[0], aii[0]); - int maxY = max(iii[1], aaa[1], aai[1], iaa[1], aia[1], iai[1], iia[1], aii[1]); - int minY = min(iii[1], aaa[1], aai[1], iaa[1], aia[1], iai[1], iia[1], aii[1]); - int maxZ = max(iii[2], aaa[2], aai[2], iaa[2], aia[2], iai[2], iia[2], aii[2]); - int minZ = min(iii[2], aaa[2], aai[2], iaa[2], aia[2], iai[2], iia[2], aii[2]); - Hunk r = builder.get(maxX - minX, maxY - minY, maxZ - minZ); - int[] cr = {(maxX - minX) / 2, (maxY - minY) / 2, (maxZ - minZ) / 2}; - - for(i = 0; i < w; i++) { - for(j = 0; j < h; j++) { - for(k = 0; k < d; k++) { - b[0] = i - c[0]; - b[1] = j - c[1]; - b[2] = k - c[2]; - rotate(x, y, z, b); - - try { - r.set(b[0] + cr[0], b[1] + cr[1], b[2] + cr[2], get(i, j, k)); - } catch(Throwable e) { - - } - } - } - } - - return r; - } - - default boolean isEmpty() { - return false; - } - - default boolean contains(int x, int y, int z) { - return x < getWidth() && x >= 0 && y < getHeight() && y >= 0 && z < getDepth() && z >= 0; - } - - default int volume() - { - return getWidth() * getDepth() * getHeight(); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/HunkFace.java b/src/main/java/com/volmit/iris/util/hunk/HunkFace.java deleted file mode 100644 index 8a245c7fc..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/HunkFace.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk; - -public enum HunkFace { - TOP, - BOTTOM, - EAST, - WEST, - NORTH, - SOUTH -} diff --git a/src/main/java/com/volmit/iris/util/hunk/HunkFactory.java b/src/main/java/com/volmit/iris/util/hunk/HunkFactory.java deleted file mode 100644 index a120cb454..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/HunkFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk; - -@FunctionalInterface -public interface HunkFactory { - Hunk create(int w, int h, int d); -} diff --git a/src/main/java/com/volmit/iris/util/hunk/bits/DataBits.java b/src/main/java/com/volmit/iris/util/hunk/bits/DataBits.java deleted file mode 100644 index 007d41cca..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/bits/DataBits.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.bits; - -import com.volmit.iris.util.data.Varint; -import org.apache.commons.lang3.Validate; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLongArray; -import java.util.function.IntConsumer; - -public class DataBits { - private static final int[] MAGIC = new int[] { - -1, -1, 0, Integer.MIN_VALUE, 0, 0, 1431655765, 1431655765, 0, Integer.MIN_VALUE, - 0, 1, 858993459, 858993459, 0, 715827882, 715827882, 0, 613566756, 613566756, - 0, Integer.MIN_VALUE, 0, 2, 477218588, 477218588, 0, 429496729, 429496729, 0, - 390451572, 390451572, 0, 357913941, 357913941, 0, 330382099, 330382099, 0, 306783378, - 306783378, 0, 286331153, 286331153, 0, Integer.MIN_VALUE, 0, 3, 252645135, 252645135, - 0, 238609294, 238609294, 0, 226050910, 226050910, 0, 214748364, 214748364, 0, - 204522252, 204522252, 0, 195225786, 195225786, 0, 186737708, 186737708, 0, 178956970, - 178956970, 0, 171798691, 171798691, 0, 165191049, 165191049, 0, 159072862, 159072862, - 0, 153391689, 153391689, 0, 148102320, 148102320, 0, 143165576, 143165576, 0, - 138547332, 138547332, 0, Integer.MIN_VALUE, 0, 4, 130150524, 130150524, 0, 126322567, - 126322567, 0, 122713351, 122713351, 0, 119304647, 119304647, 0, 116080197, 116080197, - 0, 113025455, 113025455, 0, 110127366, 110127366, 0, 107374182, 107374182, 0, - 104755299, 104755299, 0, 102261126, 102261126, 0, 99882960, 99882960, 0, 97612893, - 97612893, 0, 95443717, 95443717, 0, 93368854, 93368854, 0, 91382282, 91382282, - 0, 89478485, 89478485, 0, 87652393, 87652393, 0, 85899345, 85899345, 0, - 84215045, 84215045, 0, 82595524, 82595524, 0, 81037118, 81037118, 0, 79536431, - 79536431, 0, 78090314, 78090314, 0, 76695844, 76695844, 0, 75350303, 75350303, - 0, 74051160, 74051160, 0, 72796055, 72796055, 0, 71582788, 71582788, 0, - 70409299, 70409299, 0, 69273666, 69273666, 0, 68174084, 68174084, 0, Integer.MIN_VALUE, - 0, 5}; - - private final AtomicLongArray data; - private final int bits; - private final long mask; - private final int size; - private final int valuesPerLong; - private final int divideMul; - private final int divideAdd; - private final int divideShift; - - public DataBits(int bits, int length) { - this(bits, length, (AtomicLongArray) null); - } - - public DataBits(int bits, int length, DataInputStream din) throws IOException { - this(bits, length, longs(din, dataLength(bits, length))); - } - - public DataBits(int bits, int length, AtomicLongArray data) { - Validate.inclusiveBetween(1L, 32L, bits); - this.size = length; - this.bits = bits; - this.mask = (1L << bits) - 1L; - this.valuesPerLong = (char) (64 / bits); - int var3 = 3 * (valuesPerLong - 1); - this.divideMul = MAGIC[var3]; - this.divideAdd = MAGIC[var3 + 1]; - this.divideShift = MAGIC[var3 + 2]; - int var4 = (length + valuesPerLong - 1) / valuesPerLong; - - if(data != null) { - if(data.length() != var4) { - throw new RuntimeException("NO! Trying to load " + data.length() + " into actual size of " + var4 + " because length: " + length + " (bits: " + bits + ")"); - } - this.data = data; - } else { - this.data = new AtomicLongArray(var4); - } - } - - public String toString() { - return "DBits: " + size + "/" + bits + "[" + data.length() + "]"; - } - - private static int dataLength(int bits, int length) { - return (length + ((char) (64 / bits)) - 1) / ((char) (64 / bits)); - } - - private static AtomicLongArray longs(DataInputStream din, int longSize) throws IOException { - AtomicLongArray a = new AtomicLongArray(longSize); - - for(int i = 0; i < a.length(); i++) { - a.set(i, Varint.readUnsignedVarLong(din)); - } - - return a; - } - - public DataBits setBits(int newBits) { - if(bits != newBits) { - DataBits newData = new DataBits(newBits, size); - AtomicInteger c = new AtomicInteger(0); - - for(int i = 0; i < size; i++) { - newData.set(i, get(i)); - } - - return newData; - } - - return this; - } - - private int cellIndex(int var0) { - long var1 = Integer.toUnsignedLong(this.divideMul); - long var3 = Integer.toUnsignedLong(this.divideAdd); - return (int) (var0 * var1 + var3 >> 32L >> this.divideShift); - } - - @SuppressWarnings("PointlessBitwiseExpression") - public int getAndSet(int var0, int var1) { - Validate.inclusiveBetween(0L, (this.size - 1), var0); - Validate.inclusiveBetween(0L, this.mask, var1); - int var2 = cellIndex(var0); - long var3 = this.data.get(var2); - int var5 = (var0 - var2 * this.valuesPerLong) * this.bits; - int var6 = (int) (var3 >> var5 & this.mask); - this.data.set(var2, var3 & (this.mask << var5 ^ 0xFFFFFFFFFFFFFFFFL) | (var1 & this.mask) << var5); - return var6; - } - - @SuppressWarnings("PointlessBitwiseExpression") - public void set(int var0, int var1) { - Validate.inclusiveBetween(0L, (this.size - 1), var0); - Validate.inclusiveBetween(0L, this.mask, var1); - int var2 = cellIndex(var0); - long var3 = this.data.get(var2); - int var5 = (var0 - var2 * this.valuesPerLong) * this.bits; - - this.data.set(var2, var3 & (this.mask << var5 ^ 0xFFFFFFFFFFFFFFFFL) | (var1 & this.mask) << var5); - } - - public int get(int var0) { - Validate.inclusiveBetween(0L, (size - 1), var0); - int var1 = cellIndex(var0); - long var2 = this.data.get(var1); - int var4 = (var0 - var1 * valuesPerLong) * this.bits; - return (int) (var2 >> var4 & mask); - } - - public AtomicLongArray getRaw() { - return data; - } - - public int getSize() { - return size; - } - - public int getBits() { - return bits; - } - - public void getAll(IntConsumer var0) { - int var1 = 0; - for(int i = 0; i < data.length(); i++) { - long var5 = data.get(i); - for(int var7 = 0; var7 < valuesPerLong; var7++) { - var0.accept((int) (var5 & mask)); - var5 >>= bits; - if(++var1 >= size) { - return; - } - } - } - } - - public void write(DataOutputStream dos) throws IOException { - for(int i = 0; i < data.length(); i++) { - Varint.writeUnsignedVarLong(data.get(i), dos); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/bits/DataContainer.java b/src/main/java/com/volmit/iris/util/hunk/bits/DataContainer.java deleted file mode 100644 index c864c04a2..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/bits/DataContainer.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.bits; - -import com.volmit.iris.util.data.Varint; - -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -public class DataContainer { - protected static final int INITIAL_BITS = 3; - protected static final int LINEAR_BITS_LIMIT = 4; - protected static final int LINEAR_INITIAL_LENGTH = (int) Math.pow(2, LINEAR_BITS_LIMIT) + 1; - protected static final int[] BIT = computeBitLimits(); - private final AtomicReference> palette; - private final AtomicReference data; - private final AtomicInteger bits; - private final int length; - private final Writable writer; - - public DataContainer(Writable writer, int length) { - this.writer = writer; - this.length = length; - this.bits = new AtomicInteger(INITIAL_BITS); - this.data = new AtomicReference<>(new DataBits(INITIAL_BITS, length)); - this.palette = new AtomicReference<>(newPalette(INITIAL_BITS)); - } - - public DataContainer(DataInputStream din, Writable writer) throws IOException { - this.writer = writer; - this.length = Varint.readUnsignedVarInt(din); - this.palette = new AtomicReference<>(newPalette(din)); - this.data = new AtomicReference<>(new DataBits(palette.get().bits(), length, din)); - this.bits = new AtomicInteger(palette.get().bits()); - } - - public static String readBitString(DataInputStream din) throws IOException { - DataContainer c = new DataContainer<>(din, new Writable() { - @Override - public Character readNodeData(DataInputStream din) throws IOException { - return din.readChar(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Character character) throws IOException { - dos.writeChar(character); - } - }); - - StringBuilder sb = new StringBuilder(); - - for(int i = c.size() - 1; i >= 0; i--) { - sb.setCharAt(i, c.get(i)); - } - - return sb.toString(); - } - - public static void writeBitString(String s, DataOutputStream dos) throws IOException { - DataContainer c = new DataContainer<>(new Writable() { - @Override - public Character readNodeData(DataInputStream din) throws IOException { - return din.readChar(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Character character) throws IOException { - dos.writeChar(character); - } - }, s.length()); - - for(int i = 0; i < s.length(); i++) { - c.set(i, s.charAt(i)); - } - - c.writeDos(dos); - } - - public DataBits getData() { - return data.get(); - } - - public Palette getPalette() { - return palette.get(); - } - - public String toString() { - return "DataContainer <" + length + " x " + bits + " bits> -> Palette<" + palette.get().getClass().getSimpleName().replaceAll("\\QPalette\\E", "") + ">: " + palette.get().size() + - " " + data.get().toString() + " PalBit: " + palette.get().bits(); - } - - public byte[] write() throws IOException { - ByteArrayOutputStream boas = new ByteArrayOutputStream(); - write(boas); - return boas.toByteArray(); - } - - public void write(OutputStream out) throws IOException { - writeDos(new DataOutputStream(out)); - } - - public void writeDos(DataOutputStream dos) throws IOException { - Varint.writeUnsignedVarInt(length, dos); - Varint.writeUnsignedVarInt(palette.get().size(), dos); - palette.get().iterateIO((data, __) -> writer.writeNodeData(dos, data)); - data.get().write(dos); - dos.flush(); - } - - private Palette newPalette(DataInputStream din) throws IOException { - int paletteSize = Varint.readUnsignedVarInt(din); - Palette d = newPalette(bits(paletteSize + 1)); - d.from(paletteSize, writer, din); - return d; - } - - private Palette newPalette(int bits) { - if(bits <= LINEAR_BITS_LIMIT) { - return new LinearPalette<>(LINEAR_INITIAL_LENGTH); - } - - return new HashPalette<>(); - } - - public void ensurePaletted(T t) { - if(palette.get().id(t) == -1) { - expandOne(); - } - } - - public void set(int position, T t) { - synchronized(this) { - int id = palette.get().id(t); - - if(id == -1) { - expandOne(); - id = palette.get().add(t); - } - - data.get().set(position, id); - } - } - - private void expandOne() { - if(palette.get().size() + 1 >= BIT[bits.get()]) { - setBits(bits.get() + 1); - } - } - - public T get(int position) { - synchronized(this) { - int id = data.get().get(position) + 1; - - if(id <= 0) { - return null; - } - - return palette.get().get(id - 1); - } - } - - public void setBits(int bits) { - if(this.bits.get() != bits) { - if(this.bits.get() <= LINEAR_BITS_LIMIT != bits <= LINEAR_BITS_LIMIT) { - palette.set(newPalette(bits).from(palette.get())); - } - - this.bits.set(bits); - data.set(data.get().setBits(bits)); - } - } - - private static int[] computeBitLimits() { - int[] m = new int[16]; - - for(int i = 0; i < m.length; i++) { - m[i] = (int) Math.pow(2, i); - } - - return m; - } - - protected static int bits(int size) { - if(DataContainer.BIT[INITIAL_BITS] >= size) { - return INITIAL_BITS; - } - - for(int i = 0; i < DataContainer.BIT.length; i++) { - if(DataContainer.BIT[i] >= size) { - return i; - } - } - - return DataContainer.BIT.length - 1; - } - - public int size() { - return getData().getSize(); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/bits/HashPalette.java b/src/main/java/com/volmit/iris/util/hunk/bits/HashPalette.java deleted file mode 100644 index 7c48f4c14..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/bits/HashPalette.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.bits; - -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.function.Consumer2; - -import java.util.LinkedHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -public class HashPalette implements Palette { - private final LinkedHashMap palette; - private final KMap lookup; - private final AtomicInteger size; - - public HashPalette() { - this.size = new AtomicInteger(0); - this.palette = new LinkedHashMap<>(); - this.lookup = new KMap<>(); - add(null); - } - - @Override - public T get(int id) { - if(id < 0 || id >= size.get()) { - return null; - } - - return lookup.get(id); - } - - @Override - public int add(T t) { - int index = size.getAndIncrement(); - palette.put(t, index); - - if(t != null) { - lookup.put(index, t); - } - - return index; - } - - @Override - public int id(T t) { - if(t == null) { - return 0; - } - - Integer v = palette.get(t); - return v != null ? v : -1; - } - - @Override - public int size() { - return size.get() - 1; - } - - @Override - public void iterate(Consumer2 c) { - for(T i : palette.keySet()) { - if(i == null) { - continue; - } - - c.accept(i, id(i)); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/bits/LinearPalette.java b/src/main/java/com/volmit/iris/util/hunk/bits/LinearPalette.java deleted file mode 100644 index 2f244074c..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/bits/LinearPalette.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.bits; - -import com.volmit.iris.util.function.Consumer2; - -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.AtomicReferenceArray; - -public class LinearPalette implements Palette { - private final AtomicReference> palette; - private final AtomicInteger size; - - public LinearPalette(int initialSize) { - this.size = new AtomicInteger(0); - this.palette = new AtomicReference<>(new AtomicReferenceArray<>(initialSize)); - palette.get().set(size.getAndIncrement(), null); - } - - @Override - public T get(int id) { - if(id < 0 || id >= size.get()) { - return null; - } - - return palette.get().get(id); - } - - @Override - public int add(T t) { - int index = size.getAndIncrement(); - grow(index + 1); - palette.get().set(index, t); - return index; - } - - private void grow(int newLength) { - if(newLength > palette.get().length()) { - AtomicReferenceArray a = new AtomicReferenceArray<>(newLength + size.get()); - - for(int i = 0; i < palette.get().length(); i++) { - a.set(i, palette.get().get(i)); - } - - palette.set(a); - } - } - - @Override - public int id(T t) { - if(t == null) { - return 0; - } - - for(int i = 1; i < size() + 1; i++) { - if(t.equals(palette.get().get(i))) { - return i; - } - } - - return -1; - } - - @Override - public int size() { - return size.get() - 1; - } - - @Override - public void iterate(Consumer2 c) { - for(int i = 1; i < size() + 1; i++) { - c.accept(palette.get().get(i), i); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/bits/Palette.java b/src/main/java/com/volmit/iris/util/hunk/bits/Palette.java deleted file mode 100644 index b0e602a1c..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/bits/Palette.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.bits; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.function.Consumer2; -import com.volmit.iris.util.function.Consumer2IO; - -import java.io.DataInputStream; -import java.io.IOException; - -public interface Palette { - T get(int id); - - int add(T t); - - int id(T t); - - int size(); - - default int bits() { - return DataContainer.bits(size() + 1); - } - - void iterate(Consumer2 c); - - default void iterateIO(Consumer2IO c) { - iterate((a, b) -> { - try { - c.accept(a, b); - } catch(IOException e) { - e.printStackTrace(); - } - }); - } - - default Palette from(int size, Writable writable, DataInputStream in) throws IOException { - for(int i = 0; i < size; i++) { - add(writable.readNodeData(in)); - } - - return this; - } - - default Palette from(Palette oldPalette) { - oldPalette.iterate((k, v) -> add(k)); - return this; - } - - default KList list() { - KList t = new KList<>(); - iterate((tx, __) -> t.add(tx)); - return t; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/bits/Writable.java b/src/main/java/com/volmit/iris/util/hunk/bits/Writable.java deleted file mode 100644 index 45523f248..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/bits/Writable.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.bits; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public interface Writable { - T readNodeData(DataInputStream din) throws IOException; - - void writeNodeData(DataOutputStream dos, T t) throws IOException; -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/ArrayHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/ArrayHunk.java deleted file mode 100644 index fa213ef5f..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/ArrayHunk.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.util.Arrays; - -@SuppressWarnings("Lombok") -@Data -@EqualsAndHashCode(callSuper = false) -public class ArrayHunk extends StorageHunk implements Hunk { - private final T[] data; - - @SuppressWarnings("unchecked") - public ArrayHunk(int w, int h, int d) { - super(w, h, d); - data = (T[]) new Object[w * h * d]; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - data[index(x, y, z)] = t; - } - - @Override - public T getRaw(int x, int y, int z) { - return data[index(x, y, z)]; - } - - private int index(int x, int y, int z) { - return Cache.to1D(x, y, z, getWidth(), getHeight()); - } - - @Override - public void fill(T t) { - Arrays.fill(data, t); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/AtomicDoubleHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/AtomicDoubleHunk.java deleted file mode 100644 index 7df375a1d..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/AtomicDoubleHunk.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.google.common.util.concurrent.AtomicDoubleArray; -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import lombok.EqualsAndHashCode; - -@SuppressWarnings({"Lombok"}) -@Data -@EqualsAndHashCode(callSuper = false) -public class AtomicDoubleHunk extends StorageHunk implements Hunk { - private final AtomicDoubleArray data; - - public AtomicDoubleHunk(int w, int h, int d) { - super(w, h, d); - data = new AtomicDoubleArray(w * h * d); - } - - @Override - public boolean isAtomic() { - return true; - } - - @Override - public void setRaw(int x, int y, int z, Double t) { - data.set(index(x, y, z), t); - } - - @Override - public Double getRaw(int x, int y, int z) { - return data.get(index(x, y, z)); - } - - private int index(int x, int y, int z) { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/AtomicHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/AtomicHunk.java deleted file mode 100644 index b2297fa98..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/AtomicHunk.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.util.concurrent.atomic.AtomicReferenceArray; - -@SuppressWarnings({"Lombok"}) -@Data -@EqualsAndHashCode(callSuper = false) -public class AtomicHunk extends StorageHunk implements Hunk { - private final AtomicReferenceArray data; - - public AtomicHunk(int w, int h, int d) { - super(w, h, d); - data = new AtomicReferenceArray<>(w * h * d); - } - - @Override - public boolean isAtomic() { - return true; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - data.set(index(x, y, z), t); - } - - @Override - public T getRaw(int x, int y, int z) { - return data.get(index(x, y, z)); - } - - private int index(int x, int y, int z) { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/AtomicIntegerHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/AtomicIntegerHunk.java deleted file mode 100644 index 833d3c50e..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/AtomicIntegerHunk.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.util.concurrent.atomic.AtomicIntegerArray; - -@SuppressWarnings({"Lombok"}) -@Data -@EqualsAndHashCode(callSuper = false) -public class AtomicIntegerHunk extends StorageHunk implements Hunk { - private final AtomicIntegerArray data; - - public AtomicIntegerHunk(int w, int h, int d) { - super(w, h, d); - data = new AtomicIntegerArray(w * h * d); - } - - @Override - public boolean isAtomic() { - return true; - } - - @Override - public void setRaw(int x, int y, int z, Integer t) { - data.set(index(x, y, z), t); - } - - @Override - public Integer getRaw(int x, int y, int z) { - return data.get(index(x, y, z)); - } - - private int index(int x, int y, int z) { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/AtomicLongHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/AtomicLongHunk.java deleted file mode 100644 index 98b452584..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/AtomicLongHunk.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.util.concurrent.atomic.AtomicLongArray; - -@SuppressWarnings({"Lombok"}) -@Data -@EqualsAndHashCode(callSuper = false) -public class AtomicLongHunk extends StorageHunk implements Hunk { - private final AtomicLongArray data; - - public AtomicLongHunk(int w, int h, int d) { - super(w, h, d); - data = new AtomicLongArray(w * h * d); - } - - @Override - public boolean isAtomic() { - return true; - } - - @Override - public void setRaw(int x, int y, int z, Long t) { - data.set(index(x, y, z), t); - } - - @Override - public Long getRaw(int x, int y, int z) { - return data.get(index(x, y, z)); - } - - private int index(int x, int y, int z) { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/MappedHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/MappedHunk.java deleted file mode 100644 index c49cfe03d..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/MappedHunk.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.function.Consumer4IO; -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.io.IOException; -import java.util.Map; - -@SuppressWarnings({"Lombok"}) -@Data -@EqualsAndHashCode(callSuper = false) -public class MappedHunk extends StorageHunk implements Hunk { - private final Map data; - - public MappedHunk(int w, int h, int d) { - super(w, h, d); - data = new KMap<>(); - } - - public int getEntryCount() { - return data.size(); - } - - public boolean isMapped() { - return true; - } - - public boolean isEmpty() { - return data.isEmpty(); - } - - @Override - public void setRaw(int x, int y, int z, T t) { - if(t == null) { - data.remove(index(x, y, z)); - return; - } - - data.put(index(x, y, z), t); - } - - private Integer index(int x, int y, int z) { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } - - @Override - public synchronized Hunk iterateSync(Consumer4 c) { - int idx, z; - - for(Map.Entry g : data.entrySet()) { - idx = g.getKey(); - z = idx / (getWidth() * getHeight()); - idx -= (z * getWidth() * getHeight()); - c.accept(idx % getWidth(), idx / getWidth(), z, g.getValue()); - } - - return this; - } - - @Override - public synchronized Hunk iterateSyncIO(Consumer4IO c) throws IOException { - int idx, z; - - for(Map.Entry g : data.entrySet()) { - idx = g.getKey(); - z = idx / (getWidth() * getHeight()); - idx -= (z * getWidth() * getHeight()); - c.accept(idx % getWidth(), idx / getWidth(), z, g.getValue()); - } - - return this; - } - - @Override - public void empty(T b) { - data.clear(); - } - - @Override - public T getRaw(int x, int y, int z) { - return data.get(index(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/MappedSyncHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/MappedSyncHunk.java deleted file mode 100644 index 00bd79b6e..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/MappedSyncHunk.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.function.Consumer4IO; -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -@SuppressWarnings({"Lombok"}) -@Data -@EqualsAndHashCode(callSuper = false) -public class MappedSyncHunk extends StorageHunk implements Hunk { - private final Map data; - - public MappedSyncHunk(int w, int h, int d) { - super(w, h, d); - data = new HashMap<>(); - } - - public int getEntryCount() { - return data.size(); - } - - public boolean isMapped() { - return true; - } - - public boolean isEmpty() { - synchronized(data) { - return data.isEmpty(); - } - } - - @Override - public void setRaw(int x, int y, int z, T t) { - synchronized(data) { - if(t == null) { - data.remove(index(x, y, z)); - return; - } - - data.put(index(x, y, z), t); - } - } - - private Integer index(int x, int y, int z) { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } - - @Override - public synchronized Hunk iterateSync(Consumer4 c) { - synchronized(data) { - int idx, z; - - for(Map.Entry g : data.entrySet()) { - idx = g.getKey(); - z = idx / (getWidth() * getHeight()); - idx -= (z * getWidth() * getHeight()); - c.accept(idx % getWidth(), idx / getWidth(), z, g.getValue()); - } - - return this; - } - } - - @Override - public synchronized Hunk iterateSyncIO(Consumer4IO c) throws IOException { - synchronized(data) { - int idx, z; - - for(Map.Entry g : data.entrySet()) { - idx = g.getKey(); - z = idx / (getWidth() * getHeight()); - idx -= (z * getWidth() * getHeight()); - c.accept(idx % getWidth(), idx / getWidth(), z, g.getValue()); - } - - return this; - } - } - - @Override - public void empty(T b) { - synchronized(data) { - data.clear(); - } - } - - @Override - public T getRaw(int x, int y, int z) { - synchronized(data) { - return data.get(index(x, y, z)); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/PaletteHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/PaletteHunk.java deleted file mode 100644 index b4a8e489b..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/PaletteHunk.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.function.Consumer4IO; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.hunk.bits.DataContainer; -import com.volmit.iris.util.hunk.bits.Writable; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.io.IOException; - -@SuppressWarnings({"Lombok"}) -@Data -@EqualsAndHashCode(callSuper = false) -public class PaletteHunk extends StorageHunk implements Hunk { - private DataContainer data; - - public PaletteHunk(int w, int h, int d, Writable writer) { - super(w, h, d); - data = new DataContainer<>(writer, w * h * d); - } - - public void setPalette(DataContainer c) { - data = c; - } - - public boolean isMapped() { - return false; - } - - private int index(int x, int y, int z) { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } - - @Override - public synchronized Hunk iterateSync(Consumer4 c) { - for(int i = 0; i < getWidth(); i++) { - for(int j = 0; j < getHeight(); j++) { - for(int k = 0; k < getDepth(); k++) { - T t = getRaw(i, j, k); - if(t != null) { - c.accept(i, j, k, t); - } - } - } - } - return this; - } - - @Override - public synchronized Hunk iterateSyncIO(Consumer4IO c) throws IOException { - for(int i = 0; i < getWidth(); i++) { - for(int j = 0; j < getHeight(); j++) { - for(int k = 0; k < getDepth(); k++) { - T t = getRaw(i, j, k); - if(t != null) { - c.accept(i, j, k, t); - } - } - } - } - return this; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - data.set(index(x, y, z), t); - } - - @Override - public T getRaw(int x, int y, int z) { - return data.get(index(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/PaletteOrHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/PaletteOrHunk.java deleted file mode 100644 index c1bb25a06..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/PaletteOrHunk.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.function.Consumer4IO; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.hunk.bits.DataContainer; -import com.volmit.iris.util.hunk.bits.Writable; - -import java.io.IOException; -import java.util.function.Supplier; - -public abstract class PaletteOrHunk extends StorageHunk implements Hunk, Writable { - private final Hunk hunk; - - public PaletteOrHunk(int width, int height, int depth, boolean allow, Supplier> factory) { - super(width, height, depth); - hunk = (allow && (width * height * depth <= 4096)) ? new PaletteHunk<>(width, height, depth, this) : factory.get(); - } - - public DataContainer palette() { - return isPalette() ? ((PaletteHunk) hunk).getData() : null; - } - - public void setPalette(DataContainer c) { - if(isPalette()) { - ((PaletteHunk) hunk).setPalette(c); - } - } - - public boolean isPalette() { - return hunk instanceof PaletteHunk; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - hunk.setRaw(x, y, z, t); - } - - @Override - public T getRaw(int x, int y, int z) { - return hunk.getRaw(x, y, z); - } - - public int getEntryCount() { - return hunk.getEntryCount(); - } - - public boolean isMapped() { - return hunk.isMapped(); - } - - public boolean isEmpty() { - return hunk.isMapped(); - } - - @Override - public synchronized Hunk iterateSync(Consumer4 c) { - hunk.iterateSync(c); - return this; - } - - @Override - public synchronized Hunk iterateSyncIO(Consumer4IO c) throws IOException { - hunk.iterateSyncIO(c); - return this; - } - - @Override - public void empty(T b) { - hunk.empty(b); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/StorageHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/StorageHunk.java deleted file mode 100644 index 216a42be8..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/StorageHunk.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; - -@Data -public abstract class StorageHunk implements Hunk { - private final int width; - private final int height; - private final int depth; - - public StorageHunk(int width, int height, int depth) { - if(width <= 0 || height <= 0 || depth <= 0) { - throw new RuntimeException("Unsupported size " + width + " " + height + " " + depth); - } - - this.width = width; - this.height = height; - this.depth = depth; - } - - @Override - public abstract void setRaw(int x, int y, int z, T t); - - @Override - public abstract T getRaw(int x, int y, int z); -} diff --git a/src/main/java/com/volmit/iris/util/hunk/storage/SynchronizedArrayHunk.java b/src/main/java/com/volmit/iris/util/hunk/storage/SynchronizedArrayHunk.java deleted file mode 100644 index 7a6bdcc3b..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/storage/SynchronizedArrayHunk.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.storage; - -import com.volmit.iris.util.hunk.Hunk; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.util.Arrays; - -@SuppressWarnings({"Lombok"}) -@Data -@EqualsAndHashCode(callSuper = false) -public class SynchronizedArrayHunk extends StorageHunk implements Hunk { - private final T[] data; - - @SuppressWarnings("unchecked") - public SynchronizedArrayHunk(int w, int h, int d) { - super(w, h, d); - data = (T[]) new Object[w * h * d]; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - synchronized(data) { - data[index(x, y, z)] = t; - } - } - - @Override - public T getRaw(int x, int y, int z) { - synchronized(data) { - return data[index(x, y, z)]; - } - } - - private int index(int x, int y, int z) { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } - - @Override - public void fill(T t) { - synchronized(data) { - Arrays.fill(data, t); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/BiomeGridHunkHolder.java b/src/main/java/com/volmit/iris/util/hunk/view/BiomeGridHunkHolder.java deleted file mode 100644 index a7b066526..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/BiomeGridHunkHolder.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.engine.data.chunk.LinkedTerrainChunk; -import com.volmit.iris.util.hunk.storage.AtomicHunk; -import lombok.Getter; -import org.bukkit.block.Biome; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; - -@SuppressWarnings("ClassCanBeRecord") -public class BiomeGridHunkHolder extends AtomicHunk { - @Getter - private final BiomeGrid chunk; - private final int minHeight; - private final int maxHeight; - - public BiomeGridHunkHolder(BiomeGrid chunk, int minHeight, int maxHeight) { - super(16, maxHeight - minHeight, 16); - this.chunk = chunk; - this.minHeight = minHeight; - this.maxHeight = maxHeight; - } - - @Override - public int getWidth() { - return 16; - } - - @Override - public int getDepth() { - return 16; - } - - @Override - public int getHeight() { - return maxHeight - minHeight; - } - - public void apply() { - for(int i = 0; i < getHeight(); i++) { - for(int j = 0; j < getWidth(); j++) { - for(int k = 0; k < getDepth(); k++) { - Biome b = super.getRaw(j, i, k); - - if(b != null) - { - chunk.setBiome(j, i + minHeight, k, b); - } - } - } - } - } - - @Override - public Biome getRaw(int x, int y, int z) { - Biome b = super.getRaw(x, y, z); - - return b != null ? b : Biome.PLAINS; - } - - public void forceBiomeBaseInto(int x, int y, int z, Object somethingVeryDirty) { - if(chunk instanceof LinkedTerrainChunk) { - INMS.get().forceBiomeInto(x, y + minHeight, z, somethingVeryDirty, ((LinkedTerrainChunk) chunk).getRawBiome()); - return; - } - INMS.get().forceBiomeInto(x, y + minHeight, z, somethingVeryDirty, chunk); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/BiomeGridHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/BiomeGridHunkView.java deleted file mode 100644 index ce1654acd..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/BiomeGridHunkView.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.engine.data.chunk.LinkedTerrainChunk; -import com.volmit.iris.util.hunk.Hunk; -import lombok.Getter; -import org.bukkit.block.Biome; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; - -@SuppressWarnings("ClassCanBeRecord") -public class BiomeGridHunkView implements Hunk { - @Getter - private final BiomeGrid chunk; - private final int minHeight; - private final int maxHeight; - private int highest = -1000; - - public BiomeGridHunkView(BiomeGrid chunk, int minHeight, int maxHeight) { - this.chunk = chunk; - this.minHeight = minHeight; - this.maxHeight = maxHeight; - } - - @Override - public int getWidth() { - return 16; - } - - @Override - public int getDepth() { - return 16; - } - - @Override - public int getHeight() { - return maxHeight - minHeight; - } - - @Override - public void setRaw(int x, int y, int z, Biome t) { - chunk.setBiome(x, y + minHeight, z, t); - - if(y > highest) - { - highest = y; - Iris.info("Highest = " + highest); - } - } - - @Override - public Biome getRaw(int x, int y, int z) { - return chunk.getBiome(x, y + minHeight, z); - } - - public void forceBiomeBaseInto(int x, int y, int z, Object somethingVeryDirty) { - if(chunk instanceof LinkedTerrainChunk) { - INMS.get().forceBiomeInto(x, y + minHeight, z, somethingVeryDirty, ((LinkedTerrainChunk) chunk).getRawBiome()); - return; - } - INMS.get().forceBiomeInto(x, y + minHeight, z, somethingVeryDirty, chunk); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/ChunkBiomeHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/ChunkBiomeHunkView.java deleted file mode 100644 index 677225f18..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/ChunkBiomeHunkView.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.EditSVC; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.Chunk; -import org.bukkit.block.Biome; - -@SuppressWarnings("ClassCanBeRecord") -public class ChunkBiomeHunkView implements Hunk { - private final Chunk chunk; - - public ChunkBiomeHunkView(Chunk chunk) { - this.chunk = chunk; - } - - @Override - public int getWidth() { - return 16; - } - - @Override - public int getDepth() { - return 16; - } - - @Override - public int getHeight() { - return chunk.getWorld().getMaxHeight(); - } - - @Override - public void setRaw(int x, int y, int z, Biome t) { - if(t == null) { - return; - } - - Iris.service(EditSVC.class).setBiome(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16), t); - } - - @Override - public Biome getRaw(int x, int y, int z) { - return Iris.service(EditSVC.class) - .getBiome(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16)); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/ChunkDataHunkHolder.java b/src/main/java/com/volmit/iris/util/hunk/view/ChunkDataHunkHolder.java deleted file mode 100644 index cec67eb41..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/ChunkDataHunkHolder.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.hunk.storage.AtomicHunk; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.generator.ChunkGenerator.ChunkData; - -import java.util.concurrent.atomic.AtomicReferenceArray; - -@SuppressWarnings("ClassCanBeRecord") -public class ChunkDataHunkHolder extends AtomicHunk { - private static final BlockData AIR = Material.AIR.createBlockData(); - private final ChunkData chunk; - - public ChunkDataHunkHolder(ChunkData chunk) { - super(16, chunk.getMaxHeight() - chunk.getMinHeight(), 16); - this.chunk = chunk; - } - - @Override - public int getWidth() { - return 16; - } - - @Override - public int getDepth() { - return 16; - } - - @Override - public int getHeight() { - return chunk.getMaxHeight() - chunk.getMinHeight(); - } - - @Override - public BlockData getRaw(int x, int y, int z) { - BlockData b = super.getRaw(x, y, z); - - return b != null ? b : AIR; - } - - public void apply() { - for(int i = 0; i < getHeight(); i++) { - for(int j = 0; j < getWidth(); j++) { - for(int k = 0; k < getDepth(); k++) { - BlockData b = super.getRaw(j, i, k); - - if(b != null) - { - chunk.setBlock(j, i + chunk.getMinHeight(), k, b); - } - } - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/ChunkDataHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/ChunkDataHunkView.java deleted file mode 100644 index aa7fb9569..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/ChunkDataHunkView.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.block.data.BlockData; -import org.bukkit.generator.ChunkGenerator.ChunkData; - -@SuppressWarnings("ClassCanBeRecord") -public class ChunkDataHunkView implements Hunk { - private final ChunkData chunk; - - public ChunkDataHunkView(ChunkData chunk) { - this.chunk = chunk; - } - - @Override - public int getWidth() { - return 16; - } - - @Override - public int getDepth() { - return 16; - } - - @Override - public int getHeight() { - return chunk.getMaxHeight() - chunk.getMinHeight(); - } - - @Override - public void set(int x1, int y1, int z1, int x2, int y2, int z2, BlockData t) { - if(t == null) { - return; - } - - chunk.setRegion(x1, y1 + chunk.getMinHeight(), z1, x2, y2 + chunk.getMinHeight(), z2, t); - } - - @Override - public void setRaw(int x, int y, int z, BlockData t) { - if(t == null) { - return; - } - - chunk.setBlock(x, y + chunk.getMinHeight(), z, t); - } - - @Override - public BlockData getRaw(int x, int y, int z) { - return chunk.getBlockData(x, y + chunk.getMinHeight(), z); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/ChunkHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/ChunkHunkView.java deleted file mode 100644 index 4317e448e..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/ChunkHunkView.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.EditSVC; -import com.volmit.iris.util.hunk.Hunk; -import org.bukkit.Chunk; -import org.bukkit.block.data.BlockData; - -@SuppressWarnings("ClassCanBeRecord") -public class ChunkHunkView implements Hunk { - private final Chunk chunk; - - public ChunkHunkView(Chunk chunk) { - this.chunk = chunk; - } - - @Override - public int getWidth() { - return 16; - } - - @Override - public int getDepth() { - return 16; - } - - @Override - public int getHeight() { - return chunk.getWorld().getMaxHeight(); - } - - @Override - public void setRaw(int x, int y, int z, BlockData t) { - if(t == null) { - return; - } - - Iris.service(EditSVC.class).set(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16), t); - } - - @Override - public BlockData getRaw(int x, int y, int z) { - return Iris.service(EditSVC.class).get(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16)); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/DriftHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/DriftHunkView.java deleted file mode 100644 index 4c1242aef..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/DriftHunkView.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -@SuppressWarnings("ClassCanBeRecord") -public class DriftHunkView implements Hunk { - private final int ox; - private final int oy; - private final int oz; - private final Hunk src; - - public DriftHunkView(Hunk src, int ox, int oy, int oz) { - this.src = src; - this.ox = ox; - this.oy = oy; - this.oz = oz; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - src.setRaw(x + ox, y + oy, z + oz, t); - } - - @Override - public T getRaw(int x, int y, int z) { - return src.getRaw(x + ox, y + oy, z + oz); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/FringedHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/FringedHunkView.java deleted file mode 100644 index 2349d3646..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/FringedHunkView.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -@SuppressWarnings("ClassCanBeRecord") -public class FringedHunkView implements Hunk { - private final Hunk src; - private final Hunk out; - - public FringedHunkView(Hunk src, Hunk out) { - this.src = src; - this.out = out; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - out.setRaw(x, y, z, t); - } - - @Override - public T getRaw(int x, int y, int z) { - return src.getRaw(x, y, z); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/FunctionalHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/FunctionalHunkView.java deleted file mode 100644 index 341fc0116..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/FunctionalHunkView.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -import java.util.function.Function; - -public class FunctionalHunkView implements Hunk { - private final Hunk src; - private final Function converter; - private final Function backConverter; - - public FunctionalHunkView(Hunk src, Function converter, Function backConverter) { - this.src = src; - this.converter = converter; - this.backConverter = backConverter; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - if(backConverter == null) { - throw new UnsupportedOperationException("You cannot writeNodeData to this hunk (Read Only)"); - } - - src.setRaw(x, y, z, backConverter.apply(t)); - } - - @Override - public T getRaw(int x, int y, int z) { - if(converter == null) { - throw new UnsupportedOperationException("You cannot read this hunk (Write Only)"); - } - - return converter.apply(src.getRaw(x, y, z)); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public Hunk getSource() { - throw new UnsupportedOperationException("You cannot read this hunk's source because it's a different type."); - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/HunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/HunkView.java deleted file mode 100644 index ca4cf4dc2..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/HunkView.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -public class HunkView implements Hunk { - private final int ox; - private final int oy; - private final int oz; - private final int w; - private final int h; - private final int d; - private final Hunk src; - - public HunkView(Hunk src) { - this(src, src.getWidth(), src.getHeight(), src.getDepth()); - } - - public HunkView(Hunk src, int w, int h, int d) { - this(src, w, h, d, 0, 0, 0); - } - - public HunkView(Hunk src, int w, int h, int d, int ox, int oy, int oz) { - this.src = src; - this.w = w; - this.h = h; - this.d = d; - this.ox = ox; - this.oy = oy; - this.oz = oz; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - src.setRaw(x + ox, y + oy, z + oz, t); - } - - @Override - public T getRaw(int x, int y, int z) { - return src.getRaw(x + ox, y + oy, z + oz); - } - - @Override - public int getWidth() { - return w; - } - - @Override - public int getDepth() { - return d; - } - - @Override - public int getHeight() { - return h; - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/InvertedHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/InvertedHunkView.java deleted file mode 100644 index fc45ab195..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/InvertedHunkView.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -@SuppressWarnings("ClassCanBeRecord") -public class InvertedHunkView implements Hunk { - private final Hunk src; - - public InvertedHunkView(Hunk src) { - this.src = src; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - src.setRaw(x, (getHeight() - 1) - y, z, t); - } - - @Override - public T getRaw(int x, int y, int z) { - return src.getRaw(x, y, z); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/ListeningHunk.java b/src/main/java/com/volmit/iris/util/hunk/view/ListeningHunk.java deleted file mode 100644 index f33fb5734..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/ListeningHunk.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.hunk.Hunk; - -@SuppressWarnings("ClassCanBeRecord") -public class ListeningHunk implements Hunk { - private final Hunk src; - private final Consumer4 listener; - - public ListeningHunk(Hunk src, Consumer4 listener) { - this.src = src; - this.listener = listener; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - listener.accept(x, y, z, t); - src.setRaw(x, y, z, t); - } - - @Override - public T getRaw(int x, int y, int z) { - return src.getRaw(x, y, z); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/ReadOnlyHunk.java b/src/main/java/com/volmit/iris/util/hunk/view/ReadOnlyHunk.java deleted file mode 100644 index 8448b0468..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/ReadOnlyHunk.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -@SuppressWarnings("ClassCanBeRecord") -public class ReadOnlyHunk implements Hunk { - private final Hunk src; - - public ReadOnlyHunk(Hunk src) { - this.src = src; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - throw new IllegalStateException("This hunk is read only!"); - } - - @Override - public T getRaw(int x, int y, int z) { - return src.getRaw(x, y, z); - } - - @Override - public void set(int x1, int y1, int z1, int x2, int y2, int z2, T t) { - throw new IllegalStateException("This hunk is read only!"); - } - - @Override - public void fill(T t) { - throw new IllegalStateException("This hunk is read only!"); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/RotatedXHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/RotatedXHunkView.java deleted file mode 100644 index 623100a79..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/RotatedXHunkView.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -public class RotatedXHunkView implements Hunk { - private final Hunk src; - private final double sin; - private final double cos; - - public RotatedXHunkView(Hunk src, double deg) { - this.src = src; - this.sin = Math.sin(Math.toRadians(deg)); - this.cos = Math.cos(Math.toRadians(deg)); - } - - @Override - public void setRaw(int x, int y, int z, T t) { - int yc = (int) Math.round(cos * (getHeight() / 2f) - sin * (getDepth() / 2f)); - int zc = (int) Math.round(sin * (getHeight() / 2f) + cos * (getDepth() / 2f)); - src.setIfExists(x, - (int) Math.round(cos * (y - yc) - sin * (z - zc)) - yc, - (int) Math.round(sin * y - yc + cos * (z - zc)) - zc, - t); - } - - @Override - public T getRaw(int x, int y, int z) { - int yc = (int) Math.round(cos * (getHeight() / 2f) - sin * (getDepth() / 2f)); - int zc = (int) Math.round(sin * (getHeight() / 2f) + cos * (getDepth() / 2f)); - return src.getIfExists(x, - (int) Math.round(cos * (y - yc) - sin * (z - zc)) - yc, - (int) Math.round(sin * y - yc + cos * (z - zc)) - zc - ); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/RotatedYHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/RotatedYHunkView.java deleted file mode 100644 index 967ac0c32..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/RotatedYHunkView.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -public class RotatedYHunkView implements Hunk { - private final Hunk src; - private final double sin; - private final double cos; - - public RotatedYHunkView(Hunk src, double deg) { - this.src = src; - this.sin = Math.sin(Math.toRadians(deg)); - this.cos = Math.cos(Math.toRadians(deg)); - } - - @Override - public void setRaw(int x, int y, int z, T t) { - int xc = (int) Math.round(cos * (getWidth() / 2f) + sin * (getDepth() / 2f)); - int zc = (int) Math.round(-sin * (getWidth() / 2f) + cos * (getDepth() / 2f)); - src.setIfExists((int) - Math.round(cos * (x - xc) + sin * (z - zc)) - xc, - y, - (int) Math.round(-sin * (x - xc) + cos * (z - zc)) - zc, t); - } - - @Override - public T getRaw(int x, int y, int z) { - int xc = (int) Math.round(cos * (getWidth() / 2f) + sin * (getDepth() / 2f)); - int zc = (int) Math.round(-sin * (getWidth() / 2f) + cos * (getDepth() / 2f)); - return src.getIfExists( - (int) Math.round(cos * (x - xc) + sin * (z - zc)) - xc, - y, - (int) Math.round(-sin * (x - xc) + cos * (z - zc)) - zc - ); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/RotatedZHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/RotatedZHunkView.java deleted file mode 100644 index 8bf1bfb84..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/RotatedZHunkView.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -public class RotatedZHunkView implements Hunk { - private final Hunk src; - private final double sin; - private final double cos; - - public RotatedZHunkView(Hunk src, double deg) { - this.src = src; - this.sin = Math.sin(Math.toRadians(deg)); - this.cos = Math.cos(Math.toRadians(deg)); - } - - @Override - public void setRaw(int x, int y, int z, T t) { - int xc = (int) Math.round(cos * (getWidth() / 2f) - sin * (getHeight() / 2f)); - int yc = (int) Math.round(sin * (getWidth() / 2f) + cos * (getHeight() / 2f)); - src.setIfExists((int) Math.round(cos * (x - xc) - sin * (y - yc)) - xc, (int) Math.round(sin * (x - xc) + cos * (y - yc)) - yc, z, t); - } - - @Override - public T getRaw(int x, int y, int z) { - int xc = (int) Math.round(cos * (getWidth() / 2f) - sin * (getHeight() / 2f)); - int yc = (int) Math.round(sin * (getWidth() / 2f) + cos * (getHeight() / 2f)); - return src.getIfExists((int) Math.round(cos * (x - xc) - sin * (y - yc)) - xc, - (int) Math.round(sin * (x - xc) + cos * (y - yc)) - yc - , z); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/SynchronizedHunkView.java b/src/main/java/com/volmit/iris/util/hunk/view/SynchronizedHunkView.java deleted file mode 100644 index 757fa1b99..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/SynchronizedHunkView.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -@SuppressWarnings("ClassCanBeRecord") -public class SynchronizedHunkView implements Hunk { - private final Hunk src; - - public SynchronizedHunkView(Hunk src) { - this.src = src; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - synchronized(src) { - src.setRaw(x, y, z, t); - } - } - - @Override - public T getRaw(int x, int y, int z) { - return src.getRaw(x, y, z); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/hunk/view/WriteTrackHunk.java b/src/main/java/com/volmit/iris/util/hunk/view/WriteTrackHunk.java deleted file mode 100644 index 7b9605d5d..000000000 --- a/src/main/java/com/volmit/iris/util/hunk/view/WriteTrackHunk.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.hunk.view; - -import com.volmit.iris.util.hunk.Hunk; - -import java.util.concurrent.atomic.AtomicBoolean; - -@SuppressWarnings("ClassCanBeRecord") -public class WriteTrackHunk implements Hunk { - private final Hunk src; - private final AtomicBoolean b; - - public WriteTrackHunk(Hunk src, AtomicBoolean b) { - this.src = src; - this.b = b; - } - - @Override - public void setRaw(int x, int y, int z, T t) { - if(!b.get()) { - b.set(true); - } - - src.setRaw(x, y, z, t); - } - - @Override - public T getRaw(int x, int y, int z) { - return src.getRaw(x, y, z); - } - - @Override - public int getWidth() { - return src.getWidth(); - } - - @Override - public int getHeight() { - return src.getHeight(); - } - - @Override - public int getDepth() { - return src.getDepth(); - } - - @Override - public Hunk getSource() { - return src; - } -} diff --git a/src/main/java/com/volmit/iris/util/interpolation/InterpolationMethod.java b/src/main/java/com/volmit/iris/util/interpolation/InterpolationMethod.java deleted file mode 100644 index 715a094f0..000000000 --- a/src/main/java/com/volmit/iris/util/interpolation/InterpolationMethod.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.interpolation; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("An interpolation method (or function) is simply a method of smoothing a position based on surrounding points on a grid. Bicubic for example is smoother, but has 4 times the checks than Bilinear for example. Try using BILINEAR_STARCAST_9 for beautiful results.") -public enum InterpolationMethod { - @Desc("No interpolation. Nearest Neighbor (bad for terrain, great for performance).") - - NONE, - - @Desc("Uses 4 nearby points in a square to calculate a 2d slope. Very fast but creates square artifacts. See: https://en.wikipedia.org/wiki/Bilinear_interpolation") - - BILINEAR, - - @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 3 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") - - STARCAST_3, - - @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 6 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") - - STARCAST_6, - - @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 9 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") - - STARCAST_9, - - @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 12 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") - - STARCAST_12, - - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") - - BILINEAR_STARCAST_3, - - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") - - BILINEAR_STARCAST_6, - - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") - - BILINEAR_STARCAST_9, - - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") - - BILINEAR_STARCAST_12, - - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") - - HERMITE_STARCAST_3, - - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") - - HERMITE_STARCAST_6, - - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") - - HERMITE_STARCAST_9, - - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") - - HERMITE_STARCAST_12, - - @Desc("Uses bilinear but on a bezier curve. See: https://en.wikipedia.org/wiki/Bezier_curve") - - BILINEAR_BEZIER, - - @Desc("Uses Bilinear but with parametric curves alpha 2.") - - BILINEAR_PARAMETRIC_2, - - @Desc("Uses Bilinear but with parametric curves alpha 4.") - - BILINEAR_PARAMETRIC_4, - - @Desc("Uses Bilinear but with parametric curves alpha 1.5.") - - BILINEAR_PARAMETRIC_1_5, - - @Desc("Bicubic noise creates 4, 4-point splines for a total of 16 checks. Bcubic can go higher than expected and lower than expected right before a large change in slope.") - - BICUBIC, - - @Desc("Hermite is similar to bicubic, but faster and it can be tuned a little bit") - - HERMITE, - - @Desc("Essentially bicubic with zero tension") - - CATMULL_ROM_SPLINE, - - @Desc("Essentially bicubic with max tension") - - HERMITE_TENSE, - - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - - HERMITE_LOOSE, - - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - - HERMITE_LOOSE_HALF_POSITIVE_BIAS, - - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - - HERMITE_LOOSE_HALF_NEGATIVE_BIAS, - - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - - HERMITE_LOOSE_FULL_POSITIVE_BIAS, - - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - - HERMITE_LOOSE_FULL_NEGATIVE_BIAS, - -} diff --git a/src/main/java/com/volmit/iris/util/interpolation/InterpolationMethod3D.java b/src/main/java/com/volmit/iris/util/interpolation/InterpolationMethod3D.java deleted file mode 100644 index 08c36729f..000000000 --- a/src/main/java/com/volmit/iris/util/interpolation/InterpolationMethod3D.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.interpolation; - -import com.volmit.iris.engine.object.annotations.Desc; - -@Desc("An interpolation method (or function) is simply a method of smoothing a position based on surrounding points on a grid. Bicubic for example is smoother, but has 4 times the checks than Bilinear for example. Try using BILINEAR_STARCAST_9 for beautiful results.") -public enum InterpolationMethod3D { - TRILINEAR, - TRICUBIC, - TRIHERMITE, - TRISTARCAST_3, - TRISTARCAST_6, - TRISTARCAST_9, - TRISTARCAST_12, - TRILINEAR_TRISTARCAST_3, - TRILINEAR_TRISTARCAST_6, - TRILINEAR_TRISTARCAST_9, - TRILINEAR_TRISTARCAST_12, - NONE -} diff --git a/src/main/java/com/volmit/iris/util/interpolation/InterpolationType.java b/src/main/java/com/volmit/iris/util/interpolation/InterpolationType.java deleted file mode 100644 index c7aa23e09..000000000 --- a/src/main/java/com/volmit/iris/util/interpolation/InterpolationType.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.interpolation; - -public enum InterpolationType { - LINEAR, - PARAMETRIC_2, - PARAMETRIC_4, - BEZIER, - NONE -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/interpolation/IrisInterpolation.java b/src/main/java/com/volmit/iris/util/interpolation/IrisInterpolation.java deleted file mode 100644 index 2810296db..000000000 --- a/src/main/java/com/volmit/iris/util/interpolation/IrisInterpolation.java +++ /dev/null @@ -1,1049 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.interpolation; - -import com.google.common.util.concurrent.AtomicDouble; -import com.volmit.iris.engine.data.chunk.LinkedTerrainChunk; -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.function.Consumer2; -import com.volmit.iris.util.function.NoiseProvider; -import com.volmit.iris.util.function.NoiseProvider3; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; - -import java.math.BigDecimal; -import java.util.HashMap; - -public class IrisInterpolation { - public static CNG cng = NoiseStyle.SIMPLEX.create(new RNG()); - - public static double bezier(double t) { - return t * t * (3.0d - 2.0d * t); - } - - public static double parametric(double t, double alpha) { - double sqt = Math.pow(t, alpha); - return sqt / (alpha * (sqt - Math.pow(t, alpha - 1)) + 1.0d); - } - - public static float lerpf(float a, float b, float f) { - return a + (f * (b - a)); - } - - public static double lerpBezier(double a, double b, double f) { - return a + (bezier(f) * (b - a)); - } - - public static double sinCenter(double f) { - return Math.sin(f * Math.PI); - } - - public static double lerpCenterSinBezier(double a, double b, double f) { - return lerpBezier(a, b, sinCenter(f)); - } - - public static double lerpCenterSin(double a, double b, double f) { - return lerpBezier(a, b, sinCenter(f)); - } - - public static double lerpParametric(double a, double b, double f, double v) { - return a + (parametric(f, v) * (b - a)); - } - - public static double blerp(double a, double b, double c, double d, double tx, double ty, InterpolationType type) { - if(type.equals(InterpolationType.LINEAR)) { - return blerp(a, b, c, d, tx, ty); - } - - if(type.equals(InterpolationType.BEZIER)) { - return blerpBezier(a, b, c, d, tx, ty); - } - - if(type.equals(InterpolationType.PARAMETRIC_2)) { - return blerpParametric(a, b, c, d, tx, ty, 2); - } - - if(type.equals(InterpolationType.PARAMETRIC_4)) { - return blerpParametric(a, b, c, d, tx, ty, 4); - } - - return 0; - } - - public static double blerpBezier(double a, double b, double c, double d, double tx, double ty) { - return lerpBezier(lerpBezier(a, b, tx), lerpBezier(c, d, tx), ty); - } - - public static double blerpSinCenter(double a, double b, double c, double d, double tx, double ty) { - return lerpCenterSin(lerpCenterSin(a, b, tx), lerpCenterSin(c, d, tx), ty); - } - - public static double blerpParametric(double a, double b, double c, double d, double tx, double ty, double v) { - return lerpParametric(lerpParametric(a, b, tx, v), lerpParametric(c, d, tx, v), ty, v); - } - - public static double hermiteBezier(double p0, double p1, double p2, double p3, double mu, double tension, double bias) { - return bezier(hermite(p0, p1, p2, p3, mu, tension, bias)); - } - - public static double hermiteParametric(double p0, double p1, double p2, double p3, double mu, double tension, double bias, double a) { - return parametric(hermite(p0, p1, p2, p3, mu, tension, bias), a); - } - - public static double bihermiteBezier(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias) { - //@builder - return hermiteBezier( - hermiteBezier(p00, p01, p02, p03, muy, tension, bias), - hermiteBezier(p10, p11, p12, p13, muy, tension, bias), - hermiteBezier(p20, p21, p22, p23, muy, tension, bias), - hermiteBezier(p30, p31, p32, p33, muy, tension, bias), - mux, tension, bias); - //@done - } - - public static double bihermiteParametric(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias, double a) { - //@builder - return hermiteParametric( - hermiteParametric(p00, p01, p02, p03, muy, tension, bias, a), - hermiteParametric(p10, p11, p12, p13, muy, tension, bias, a), - hermiteParametric(p20, p21, p22, p23, muy, tension, bias, a), - hermiteParametric(p30, p31, p32, p33, muy, tension, bias, a), - mux, tension, bias, a); - //@done - } - - public static double cubicBezier(double p0, double p1, double p2, double p3, double mu) { - return bezier(cubic(p0, p1, p2, p3, mu)); - } - - public static double cubicParametric(double p0, double p1, double p2, double p3, double mu, double a) { - return parametric(cubic(p0, p1, p2, p3, mu), a); - } - - public static double hermite(double p0, double p1, double p2, double p3, double mu, double tension, double bias) { - double m0, m1, mu2, mu3; - double a0, a1, a2, a3; - - mu2 = mu * mu; - mu3 = mu2 * mu; - m0 = (p1 - p0) * (1 + bias) * (1 - tension) / 2; - m0 += (p2 - p1) * (1 - bias) * (1 - tension) / 2; - m1 = (p2 - p1) * (1 + bias) * (1 - tension) / 2; - m1 += (p3 - p2) * (1 - bias) * (1 - tension) / 2; - a0 = 2 * mu3 - 3 * mu2 + 1; - a1 = mu3 - 2 * mu2 + mu; - a2 = mu3 - mu2; - a3 = -2 * mu3 + 3 * mu2; - - return (a0 * p1 + a1 * m0 + a2 * m1 + a3 * p2); - } - - public static double cubic(double p0, double p1, double p2, double p3, double mu) { - double a0, a1, a2, a3, mu2; - - mu2 = mu * mu; - a0 = p3 - p2 - p0 + p1; - a1 = p0 - p1 - a0; - a2 = p2 - p0; - a3 = p1; - - return a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3; - } - - public static double bicubic(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy) { - //@builder - return cubic( - cubic(p00, p01, p02, p03, muy), - cubic(p10, p11, p12, p13, muy), - cubic(p20, p21, p22, p23, muy), - cubic(p30, p31, p32, p33, muy), - mux); - //@done - } - - public static double bihermite(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias) { - //@builder - return hermite( - hermite(p00, p01, p02, p03, muy, tension, bias), - hermite(p10, p11, p12, p13, muy, tension, bias), - hermite(p20, p21, p22, p23, muy, tension, bias), - hermite(p30, p31, p32, p33, muy, tension, bias), - mux, tension, bias); - //@done - } - - public static double trihermite(double p000, double p001, double p002, double p003, double p010, double p011, double p012, double p013, double p020, double p021, double p022, double p023, double p030, double p031, double p032, double p033, double p100, double p101, double p102, double p103, double p110, double p111, double p112, double p113, double p120, double p121, double p122, double p123, double p130, double p131, double p132, double p133, double p200, double p201, double p202, double p203, double p210, double p211, double p212, double p213, double p220, double p221, double p222, double p223, double p230, double p231, double p232, double p233, double p300, double p301, double p302, double p303, double p310, double p311, double p312, double p313, double p320, double p321, double p322, double p323, double p330, double p331, double p332, double p333, double mux, double muy, double muz, double tension, double bias) { - //@builder - return hermite( - bihermite(p000, p001, p002, p003, - p010, p011, p012, p013, - p020, p021, p022, p023, - p030, p031, p032, p033, - mux, muy, tension, bias), - bihermite(p100, p101, p102, p103, - p110, p111, p112, p113, - p120, p121, p122, p123, - p130, p131, p132, p133, - mux, muy, tension, bias), - bihermite(p200, p201, p202, p203, - p210, p211, p212, p213, - p220, p221, p222, p223, - p230, p231, p232, p233, - mux, muy, tension, bias), - bihermite(p300, p301, p302, p303, - p310, p311, p312, p313, - p320, p321, p322, p323, - p330, p331, p332, p333, - mux, muy, tension, bias), - muz, tension, bias); - //@done - } - - public static double tricubic(double p000, - double p001, - double p002, - double p003, - double p010, - double p011, - double p012, double p013, double p020, double p021, double p022, double p023, double p030, double p031, double p032, double p033, double p100, double p101, double p102, double p103, double p110, double p111, double p112, double p113, double p120, double p121, double p122, double p123, double p130, double p131, double p132, double p133, double p200, double p201, double p202, double p203, double p210, double p211, double p212, double p213, double p220, double p221, double p222, double p223, double p230, double p231, double p232, double p233, double p300, double p301, double p302, double p303, double p310, double p311, double p312, double p313, double p320, double p321, double p322, double p323, double p330, double p331, double p332, double p333, double mux, double muy, double muz) { - //@builder - return cubic( - bicubic(p000, p001, p002, p003, - p010, p011, p012, p013, - p020, p021, p022, p023, - p030, p031, p032, p033, - mux, muy), - bicubic(p100, p101, p102, p103, - p110, p111, p112, p113, - p120, p121, p122, p123, - p130, p131, p132, p133, - mux, muy), - bicubic(p200, p201, p202, p203, - p210, p211, p212, p213, - p220, p221, p222, p223, - p230, p231, p232, p233, - mux, muy), - bicubic(p300, p301, p302, p303, - p310, p311, p312, p313, - p320, p321, p322, p323, - p330, p331, p332, p333, - mux, muy), - muz); - //@done - } - - public static double lerp(double a, double b, double f) { - return a + (f * (b - a)); - } - - public static double blerp(double a, double b, double c, double d, double tx, double ty) { - return lerp(lerp(a, b, tx), lerp(c, d, tx), ty); - } - - public static double trilerp(double v1, double v2, double v3, double v4, double v5, double v6, double v7, double v8, double x, double y, double z) { - return lerp(blerp(v1, v2, v3, v4, x, y), blerp(v5, v6, v7, v8, x, y), z); - } - - public static double bicubicBezier(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy) { - //@builder - return cubicBezier( - cubicBezier(p00, p01, p02, p03, muy), - cubicBezier(p10, p11, p12, p13, muy), - cubicBezier(p20, p21, p22, p23, muy), - cubicBezier(p30, p31, p32, p33, muy), - mux); - //@done - } - - public static double bicubicParametric(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double a) { - //@builder - return cubicParametric( - cubicParametric(p00, p01, p02, p03, muy, a), - cubicParametric(p10, p11, p12, p13, muy, a), - cubicParametric(p20, p21, p22, p23, muy, a), - cubicParametric(p30, p31, p32, p33, muy, a), - mux, a); - //@done - } - - public static int getRadiusFactor(int coord, double radius) - { - if(radius == 2) {return coord >> 1;} - if(radius == 4) {return coord >> 2;} - if(radius == 8) {return coord >> 3;} - if(radius == 16) {return coord >> 4;} - if(radius == 32) {return coord >> 5;} - if(radius == 64) {return coord >> 6;} - if(radius == 128) {return coord >> 7;} - if(radius == 256) {return coord >> 8;} - if(radius == 512) {return coord >> 9;} - if(radius == 1024) {return coord >> 10;} - return (int) Math.floor(coord / radius); - } - - public static double getBilinearNoise(int x, int z, double rad, NoiseProvider n) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return blerp( - n.noise(x1, z1), - n.noise(x2, z1), - n.noise(x1, z2), - n.noise(x2, z2), - px, pz); - //@done - } - - public static void test(String m, Consumer2 f) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - - for(int i = 0; i < 8192; i++) { - f.accept(i, -i * 234); - } - - p.end(); - - System.out.println(m + ": " + Form.duration(p.getMilliseconds(), 8)); - } - - public static void printOptimizedSrc(boolean arrays) { - System.out.println(generateOptimizedStarcast(3, arrays)); - System.out.println(generateOptimizedStarcast(5, arrays)); - System.out.println(generateOptimizedStarcast(6, arrays)); - System.out.println(generateOptimizedStarcast(7, arrays)); - System.out.println(generateOptimizedStarcast(9, arrays)); - System.out.println(generateOptimizedStarcast(12, arrays)); - System.out.println(generateOptimizedStarcast(24, arrays)); - System.out.println(generateOptimizedStarcast(32, arrays)); - System.out.println(generateOptimizedStarcast(48, arrays)); - System.out.println(generateOptimizedStarcast(64, arrays)); - } - - public static String generateOptimizedStarcast(double checks, boolean array) { - double m = (360 / checks); - int ig = 0; - int igx = 0; - StringBuilder fb = new StringBuilder(); - StringBuilder sb = new StringBuilder(); - - if(array) { - fb.append("private static final double[] F").append((int) checks).append("A = {"); - } - - sb.append("private static double sc").append((int) checks).append("(int x, int z, double r, NoiseProvider n) {\n return ("); - for(int i = 0; i < 360; i += m) { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - String cof = new BigDecimal(cos).toPlainString(); - String sif = new BigDecimal(sin).toPlainString(); - String cc = array ? "F" + (int) checks + "A[" + (igx++) + "]" : "F" + (int) checks + "C" + ig; - String ss = array ? "F" + (int) checks + "A[" + (igx++) + "]" : "F" + (int) checks + "S" + ig; - - if(array) { - fb.append(ig > 0 ? (ig % 6 == 0 ? ",\n" : ",") : "").append(cof).append(",").append(sif); - } else { - fb.append("private static final double ").append(cc).append(" = ").append(cof).append(";\n"); - fb.append("private static final double ").append(ss).append(" = ").append(sif).append(";\n"); - } - - sb.append(ig > 0 ? "\n +" : "").append("n.noise(x + ((r * ").append(cc).append(") - (r * ").append(ss).append(")), z + ((r * ").append(ss).append(") + (r * ").append(cc).append(")))"); - ig++; - } - - if(array) { - fb.append("};"); - } - - sb.append(")/").append(checks).append("D;\n}"); - return fb + "\n" + sb; - } - - public static double getStarcast3D(int x, int y, int z, double rad, double checks, NoiseProvider3 n) { - return (Starcast.starcast(x, z, rad, checks, (xx, zz) -> n.noise(xx, y, zz)) - + Starcast.starcast(x, y, rad, checks, (xx, yy) -> n.noise(xx, yy, z)) - + Starcast.starcast(y, z, rad, checks, (yy, zz) -> n.noise(x, yy, zz))) / 3D; - } - - public static double getBilinearBezierNoise(int x, int z, double rad, NoiseProvider n) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return blerpBezier( - n.noise(x1, z1), - n.noise(x2, z1), - n.noise(x1, z2), - n.noise(x2, z2), - px, pz); - //@done - } - - public static double getBilinearParametricNoise(int x, int z, double rad, NoiseProvider n, double a) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return blerpParametric( - n.noise(x1, z1), - n.noise(x2, z1), - n.noise(x1, z2), - n.noise(x2, z2), - px, pz, a); - //@done - } - - public static double getTrilinear(int x, int y, int z, double rad, NoiseProvider3 n) { - return getTrilinear(x, y, z, rad, rad, rad, n); - } - - public static double getTrilinear(int x, int y, int z, double radx, double rady, double radz, NoiseProvider3 n) { - int fx = getRadiusFactor(x, radx); - int fy = getRadiusFactor(y, rady); - int fz = getRadiusFactor(z, radz); - int x1 = (int) Math.round(fx * radx); - int y1 = (int) Math.round(fy * rady); - int z1 = (int) Math.round(fz * radz); - int x2 = (int) Math.round((fx + 1) * radx); - int y2 = (int) Math.round((fy + 1) * rady); - int z2 = (int) Math.round((fz + 1) * radz); - double px = rangeScale(0, 1, x1, x2, x); - double py = rangeScale(0, 1, y1, y2, y); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return trilerp( - n.noise(x1, y1, z1), - n.noise(x2, y1, z1), - n.noise(x1, y2, z1), - n.noise(x2, y2, z1), - n.noise(x1, y1, z2), - n.noise(x2, y1, z2), - n.noise(x1, y2, z2), - n.noise(x2, y2, z2), - px, py, pz); - //@done - } - - public static double getTricubic(int x, int y, int z, double rad, NoiseProvider3 n) { - return getTricubic(x, y, z, rad, rad, rad, n); - } - - public static double getTricubic(int x, int y, int z, double radx, double rady, double radz, NoiseProvider3 n) { - int fx = getRadiusFactor(x, radx); - int fy = getRadiusFactor(y, rady); - int fz = getRadiusFactor(z, radz); - int x0 = (int) Math.round((fx - 1) * radx); - int y0 = (int) Math.round((fy - 1) * rady); - int z0 = (int) Math.round((fz - 1) * radz); - int x1 = (int) Math.round(fx * radx); - int y1 = (int) Math.round(fy * rady); - int z1 = (int) Math.round(fz * radz); - int x2 = (int) Math.round((fx + 1) * radx); - int y2 = (int) Math.round((fy + 1) * rady); - int z2 = (int) Math.round((fz + 1) * radz); - int x3 = (int) Math.round((fx + 2) * radx); - int y3 = (int) Math.round((fy + 2) * rady); - int z3 = (int) Math.round((fz + 2) * radz); - double px = rangeScale(0, 1, x1, x2, x); - double py = rangeScale(0, 1, y1, y2, y); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - //!!!!!!!!!!!!!!!!!! 2 1 3 - - return tricubic( - n.noise(x0, y0, z0), - n.noise(x0, y1, z0), - n.noise(x0, y2, z0), - n.noise(x0, y3, z0), - n.noise(x1, y0, z0), - n.noise(x1, y1, z0), - n.noise(x1, y2, z0), - n.noise(x1, y3, z0), - n.noise(x2, y0, z0), - n.noise(x2, y1, z0), - n.noise(x2, y2, z0), - n.noise(x2, y3, z0), - n.noise(x3, y0, z0), - n.noise(x3, y1, z0), - n.noise(x3, y2, z0), - n.noise(x3, y3, z0), - n.noise(x0, y0, z1), - n.noise(x0, y1, z1), - n.noise(x0, y2, z1), - n.noise(x0, y3, z1), - n.noise(x1, y0, z1), - n.noise(x1, y1, z1), - n.noise(x1, y2, z1), - n.noise(x1, y3, z1), - n.noise(x2, y0, z1), - n.noise(x2, y1, z1), - n.noise(x2, y2, z1), - n.noise(x2, y3, z1), - n.noise(x3, y0, z1), - n.noise(x3, y1, z1), - n.noise(x3, y2, z1), - n.noise(x3, y3, z1), - n.noise(x0, y0, z2), - n.noise(x0, y1, z2), - n.noise(x0, y2, z2), - n.noise(x0, y3, z2), - n.noise(x1, y0, z2), - n.noise(x1, y1, z2), - n.noise(x1, y2, z2), - n.noise(x1, y3, z2), - n.noise(x2, y0, z2), - n.noise(x2, y1, z2), - n.noise(x2, y2, z2), - n.noise(x2, y3, z2), - n.noise(x3, y0, z2), - n.noise(x3, y1, z2), - n.noise(x3, y2, z2), - n.noise(x3, y3, z2), - n.noise(x0, y0, z3), - n.noise(x0, y1, z3), - n.noise(x0, y2, z3), - n.noise(x0, y3, z3), - n.noise(x1, y0, z3), - n.noise(x1, y1, z3), - n.noise(x1, y2, z3), - n.noise(x1, y3, z3), - n.noise(x2, y0, z3), - n.noise(x2, y1, z3), - n.noise(x2, y2, z3), - n.noise(x2, y3, z3), - n.noise(x3, y0, z3), - n.noise(x3, y1, z3), - n.noise(x3, y2, z3), - n.noise(x3, y3, z3), - px, py, pz); - //@done - } - - public static double getTrihermite(int x, int y, int z, double rad, NoiseProvider3 n, double tension, double bias) { - return getTrihermite(x, y, z, rad, rad, rad, n, tension, bias); - } - - public static double getTrihermite(int x, int y, int z, double rad, NoiseProvider3 n) { - return getTrihermite(x, y, z, rad, rad, rad, n, 0D, 0D); - } - - public static double getTrihermite(int x, int y, int z, double radx, double rady, double radz, NoiseProvider3 n) { - return getTrihermite(x, y, z, radx, rady, radz, n, 0D, 0D); - } - - public static double getTrihermite(int x, int y, int z, double radx, double rady, double radz, NoiseProvider3 n, double tension, double bias) { - int fx = getRadiusFactor(x, radx); - int fy = getRadiusFactor(y, rady); - int fz = getRadiusFactor(z, radz); - int x0 = (int) Math.round((fx - 1) * radx); - int y0 = (int) Math.round((fy - 1) * rady); - int z0 = (int) Math.round((fz - 1) * radz); - int x1 = (int) Math.round(fx * radx); - int y1 = (int) Math.round(fy * rady); - int z1 = (int) Math.round(fz * radz); - int x2 = (int) Math.round((fx + 1) * radx); - int y2 = (int) Math.round((fy + 1) * rady); - int z2 = (int) Math.round((fz + 1) * radz); - int x3 = (int) Math.round((fx + 2) * radx); - int y3 = (int) Math.round((fy + 2) * rady); - int z3 = (int) Math.round((fz + 2) * radz); - double px = rangeScale(0, 1, x1, x2, x); - double py = rangeScale(0, 1, y1, y2, y); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - //!!!!!!!!!!!!!!!!!! 2 1 3 - - return trihermite( - n.noise(x0, y0, z0), - n.noise(x0, y1, z0), - n.noise(x0, y2, z0), - n.noise(x0, y3, z0), - n.noise(x1, y0, z0), - n.noise(x1, y1, z0), - n.noise(x1, y2, z0), - n.noise(x1, y3, z0), - n.noise(x2, y0, z0), - n.noise(x2, y1, z0), - n.noise(x2, y2, z0), - n.noise(x2, y3, z0), - n.noise(x3, y0, z0), - n.noise(x3, y1, z0), - n.noise(x3, y2, z0), - n.noise(x3, y3, z0), - n.noise(x0, y0, z1), - n.noise(x0, y1, z1), - n.noise(x0, y2, z1), - n.noise(x0, y3, z1), - n.noise(x1, y0, z1), - n.noise(x1, y1, z1), - n.noise(x1, y2, z1), - n.noise(x1, y3, z1), - n.noise(x2, y0, z1), - n.noise(x2, y1, z1), - n.noise(x2, y2, z1), - n.noise(x2, y3, z1), - n.noise(x3, y0, z1), - n.noise(x3, y1, z1), - n.noise(x3, y2, z1), - n.noise(x3, y3, z1), - n.noise(x0, y0, z2), - n.noise(x0, y1, z2), - n.noise(x0, y2, z2), - n.noise(x0, y3, z2), - n.noise(x1, y0, z2), - n.noise(x1, y1, z2), - n.noise(x1, y2, z2), - n.noise(x1, y3, z2), - n.noise(x2, y0, z2), - n.noise(x2, y1, z2), - n.noise(x2, y2, z2), - n.noise(x2, y3, z2), - n.noise(x3, y0, z2), - n.noise(x3, y1, z2), - n.noise(x3, y2, z2), - n.noise(x3, y3, z2), - n.noise(x0, y0, z3), - n.noise(x0, y1, z3), - n.noise(x0, y2, z3), - n.noise(x0, y3, z3), - n.noise(x1, y0, z3), - n.noise(x1, y1, z3), - n.noise(x1, y2, z3), - n.noise(x1, y3, z3), - n.noise(x2, y0, z3), - n.noise(x2, y1, z3), - n.noise(x2, y2, z3), - n.noise(x2, y3, z3), - n.noise(x3, y0, z3), - n.noise(x3, y1, z3), - n.noise(x3, y2, z3), - n.noise(x3, y3, z3), - px, py, pz, tension, bias); - //@done - } - - public static double getBilinearCenterSineNoise(int x, int z, double rad, NoiseProvider n) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return blerpSinCenter( - n.noise(x1, z1), - n.noise(x2, z1), - n.noise(x1, z2), - n.noise(x2, z2), - px, pz); - //@done - } - - public static double getBicubicNoise(int x, int z, double rad, NoiseProvider n) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bicubic( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz); - //@done - } - - public static double getBicubicBezierNoise(int x, int z, double rad, NoiseProvider n) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bicubicBezier( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz); - //@done - } - - public static double getBicubicParametricNoise(int x, int z, double rad, NoiseProvider n, double a) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bicubicParametric( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz, a); - //@done - } - - public static double getHermiteNoise(int x, int z, double rad, NoiseProvider n) { - return getHermiteNoise(x, z, rad, n, 0.5, 0); - } - - public static double getHermiteBezierNoise(int x, int z, double rad, NoiseProvider n) { - return getHermiteBezierNoise(x, z, rad, n, 0.5, 0); - } - - public static double getHermiteParametricNoise(int x, int z, double rad, NoiseProvider n, double a) { - return getHermiteParametricNoise(x, z, rad, n, 0.5, 0, a); - } - - public static double getHermiteNoise(int x, int z, double rad, NoiseProvider n, double t, double b) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bihermite( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz, t, b); - //@done - } - - public static double getHermiteBezierNoise(int x, int z, double rad, NoiseProvider n, double t, double b) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bihermiteBezier( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz, t, b); - //@done - } - - public static double getHermiteParametricNoise(int x, int z, double rad, NoiseProvider n, double t, double b, double a) { - int fx = getRadiusFactor(x, rad); - int fz = getRadiusFactor(z, rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bihermiteParametric( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz, t, b, a); - //@done - } - - public static double getRealRadius(InterpolationMethod method, double h) { - AtomicDouble rad = new AtomicDouble(h); - AtomicDouble accessX = new AtomicDouble(); - AtomicDouble accessZ = new AtomicDouble(); - NoiseProvider np = (x1, z1) -> { - double d = Math.max(Math.abs(x1), Math.abs(z1)); - if(d > rad.get()) { - rad.set(d); - } - return 0; - }; - getNoise(method, 0, 0, h, np); - return rad.get(); - } - - public static double getNoise3D(InterpolationMethod3D method, int x, int y, int z, double radx, double rady, double radz, NoiseProvider3 n) { - return switch(method) { - case TRILINEAR -> getTrilinear(x, y, z, radx, rady, radz, n); - case TRICUBIC -> getTricubic(x, y, z, radx, rady, radz, n); - case TRIHERMITE -> getTrihermite(x, y, z, radx, rady, radz, n); - case TRISTARCAST_3 -> getStarcast3D(x, y, z, radx, 3D, n); - case TRISTARCAST_6 -> getStarcast3D(x, y, z, radx, 6D, n); - case TRISTARCAST_9 -> getStarcast3D(x, y, z, radx, 9D, n); - case TRISTARCAST_12 -> getStarcast3D(x, y, z, radx, 12D, n); - case TRILINEAR_TRISTARCAST_3 -> getStarcast3D(x, y, z, radx, 3D, (xx, yy, zz) -> getTrilinear((int) xx, (int) yy, (int) zz, radx, rady, radz, n)); - case TRILINEAR_TRISTARCAST_6 -> getStarcast3D(x, y, z, radx, 6D, (xx, yy, zz) -> getTrilinear((int) xx, (int) yy, (int) zz, radx, rady, radz, n)); - case TRILINEAR_TRISTARCAST_9 -> getStarcast3D(x, y, z, radx, 9D, (xx, yy, zz) -> getTrilinear((int) xx, (int) yy, (int) zz, radx, rady, radz, n)); - case TRILINEAR_TRISTARCAST_12 -> getStarcast3D(x, y, z, radx, 12D, (xx, yy, zz) -> getTrilinear((int) xx, (int) yy, (int) zz, radx, rady, radz, n)); - case NONE -> n.noise(x, y, z); - }; - } - - public static Hunk getNoise3D(InterpolationMethod3D method, int xo, int yo, int zo, int w, int h, int d, double rad, NoiseProvider3 n) { - return getNoise3D(method, xo, yo, zo, w, h, d, rad, rad, rad, n); - } - - /** - * Get the interpolated 3D noise within a given cuboid size with offsets - * - * @param method - * the interpolation method to use - * @param xo - * the x offset for noise - * @param yo - * the y offset for noise - * @param zo - * the z offset for noise - * @param w - * the width of the result - * @param h - * the height of the result - * @param d - * the depth of the result - * @param radX - * the interpolation radius for the x axis - * @param radY - * the interpolation radius for the y axis - * @param radZ - * the interpolation radius for the z axis - * @param n - * the noise provider - * @return the resulting hunk of noise - */ - public static Hunk getNoise3D(InterpolationMethod3D method, int xo, int yo, int zo, int w, int h, int d, double radX, double radY, double radZ, NoiseProvider3 n) { - Hunk hunk = Hunk.newAtomicDoubleHunk(w, h, d); - HashMap cache = new HashMap<>(); - int i, j, k; - - for(i = 0; i < w; i++) { - int fi = i; - for(j = 0; j < h; j++) { - int fj = j; - for(k = 0; k < d; k++) { - int fk = k; - hunk.set(i, j, k, cache.computeIfAbsent((k * w * h) + (j * w) + i, (p) - -> getNoise3D(method, fi + xo, fj + yo, fk + zo, - radX, radY, radZ, n))); - } - } - } - - return hunk; - } - - public static double getNoise3D(InterpolationMethod3D method, int x, int y, int z, double rad, NoiseProvider3 n) { - return getNoise3D(method, x, y, z, rad, rad, rad, n); - } - - public static double getNoise(InterpolationMethod method, int x, int z, double h, NoiseProvider n) { - if(method.equals(InterpolationMethod.BILINEAR)) { - return getBilinearNoise(x, z, h, n); - } else if(method.equals(InterpolationMethod.STARCAST_3)) { - return Starcast.starcast(x, z, h, 3D, n); - } else if(method.equals(InterpolationMethod.STARCAST_6)) { - return Starcast.starcast(x, z, h, 6D, n); - } else if(method.equals(InterpolationMethod.STARCAST_9)) { - return Starcast.starcast(x, z, h, 9D, n); - } else if(method.equals(InterpolationMethod.STARCAST_12)) { - return Starcast.starcast(x, z, h, 12D, n); - } else if(method.equals(InterpolationMethod.BILINEAR_STARCAST_3)) { - return Starcast.starcast(x, z, h, 3D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); - } else if(method.equals(InterpolationMethod.BILINEAR_STARCAST_6)) { - return Starcast.starcast(x, z, h, 6D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); - } else if(method.equals(InterpolationMethod.BILINEAR_STARCAST_9)) { - return Starcast.starcast(x, z, h, 9D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); - } else if(method.equals(InterpolationMethod.BILINEAR_STARCAST_12)) { - return Starcast.starcast(x, z, h, 12D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); - } else if(method.equals(InterpolationMethod.HERMITE_STARCAST_3)) { - return Starcast.starcast(x, z, h, 3D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); - } else if(method.equals(InterpolationMethod.HERMITE_STARCAST_6)) { - return Starcast.starcast(x, z, h, 6D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); - } else if(method.equals(InterpolationMethod.HERMITE_STARCAST_9)) { - return Starcast.starcast(x, z, h, 9D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); - } else if(method.equals(InterpolationMethod.HERMITE_STARCAST_12)) { - return Starcast.starcast(x, z, h, 12D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); - } else if(method.equals(InterpolationMethod.BILINEAR_BEZIER)) { - return getBilinearBezierNoise(x, z, h, n); - } else if(method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_2)) { - return getBilinearParametricNoise(x, z, h, n, 2); - } else if(method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_4)) { - return getBilinearParametricNoise(x, z, h, n, 4); - } else if(method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_1_5)) { - return getBilinearParametricNoise(x, z, h, n, 1.5); - } else if(method.equals(InterpolationMethod.BICUBIC)) { - return getBilinearNoise(x, z, h, n); - } else if(method.equals(InterpolationMethod.HERMITE)) { - return getHermiteNoise(x, z, h, n); - } else if(method.equals(InterpolationMethod.HERMITE_TENSE)) { - return getHermiteNoise(x, z, h, n, 0.8D, 0D); - } else if(method.equals(InterpolationMethod.CATMULL_ROM_SPLINE)) { - return getHermiteNoise(x, z, h, n, 1D, 0D); - } else if(method.equals(InterpolationMethod.HERMITE_LOOSE)) { - return getHermiteNoise(x, z, h, n, 0D, 0D); - } else if(method.equals(InterpolationMethod.HERMITE_LOOSE_HALF_NEGATIVE_BIAS)) { - return getHermiteNoise(x, z, h, n, 0D, -0.5D); - } else if(method.equals(InterpolationMethod.HERMITE_LOOSE_HALF_POSITIVE_BIAS)) { - return getHermiteNoise(x, z, h, n, 0D, 0.5D); - } else if(method.equals(InterpolationMethod.HERMITE_LOOSE_FULL_NEGATIVE_BIAS)) { - return getHermiteNoise(x, z, h, n, 0D, -1D); - } else if(method.equals(InterpolationMethod.HERMITE_LOOSE_FULL_POSITIVE_BIAS)) { - return getHermiteNoise(x, z, h, n, 0D, 1D); - } - - return n.noise(x, z); - } - public static double rangeScale(double amin, double amax, double bmin, double bmax, double b) { - return amin + ((amax - amin) * ((b - bmin) / (bmax - bmin))); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/interpolation/Starcast.java b/src/main/java/com/volmit/iris/util/interpolation/Starcast.java deleted file mode 100644 index 546957220..000000000 --- a/src/main/java/com/volmit/iris/util/interpolation/Starcast.java +++ /dev/null @@ -1,767 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.interpolation; - -import com.volmit.iris.util.function.NoiseProvider; - -public class Starcast { - public static double starcast(int x, int z, double r, double checks, boolean optimized, NoiseProvider n) { - if(optimized) { - if(checks == 3) return sc3(x, z, r, n); - else if(checks == 5) return sc5(x, z, r, n); - else if(checks == 6) return sc6(x, z, r, n); - else if(checks == 7) return sc7(x, z, r, n); - else if(checks == 9) return sc9(x, z, r, n); - else if(checks == 12) return sc12(x, z, r, n); - else if(checks == 24) return sc24(x, z, r, n); - else if(checks == 32) return sc32(x, z, r, n); - else if(checks == 48) return sc48(x, z, r, n); - else if(checks == 64) return sc64(x, z, r, n); - } - - double m = 360D / checks; - double v = 0; - - for(int i = 0; i < 360; i += m) { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - double cx = x + ((r * cos) - (r * sin)); - double cz = z + ((r * sin) + (r * cos)); - v += n.noise(cx, cz); - } - - return v / checks; - } - - public static double starcast(int x, int z, double r, double checks, NoiseProvider n) { - return starcast(x, z, r, checks, true, n); - } - - private static final double F3C0 = 1; - private static final double F3S0 = 0; - private static final double F3C1 = -0.4999999999999997779553950749686919152736663818359375; - private static final double F3S1 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F3C2 = -0.500000000000000444089209850062616169452667236328125; - private static final double F3S2 = -0.86602540378443837454369713668711483478546142578125; - - private static double sc3(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F3C0) - (r * F3S0)), z + ((r * F3S0) + (r * F3C0))) - + n.noise(x + ((r * F3C1) - (r * F3S1)), z + ((r * F3S1) + (r * F3C1))) - + n.noise(x + ((r * F3C2) - (r * F3S2)), z + ((r * F3S2) + (r * F3C2)))) / 3.0D; - } - - private static final double F5C0 = 1; - private static final double F5S0 = 0; - private static final double F5C1 = 0.30901699437494745126286943559534847736358642578125; - private static final double F5S1 = 0.95105651629515353118193843329208903014659881591796875; - private static final double F5C2 = -0.80901699437494734024056697307969443500041961669921875; - private static final double F5S2 = 0.58778525229247324812575925534474663436412811279296875; - private static final double F5C3 = -0.80901699437494756228517189811100251972675323486328125; - private static final double F5S3 = -0.58778525229247302608115433031343854963779449462890625; - private static final double F5C4 = 0.3090169943749472292182645105640403926372528076171875; - private static final double F5S4 = -0.951056516295153642204240895807743072509765625; - - private static double sc5(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F5C0) - (r * F5S0)), z + ((r * F5S0) + (r * F5C0))) - + n.noise(x + ((r * F5C1) - (r * F5S1)), z + ((r * F5S1) + (r * F5C1))) - + n.noise(x + ((r * F5C2) - (r * F5S2)), z + ((r * F5S2) + (r * F5C2))) - + n.noise(x + ((r * F5C3) - (r * F5S3)), z + ((r * F5S3) + (r * F5C3))) - + n.noise(x + ((r * F5C4) - (r * F5S4)), z + ((r * F5S4) + (r * F5C4)))) / 5.0D; - } - - private static final double F6C0 = 1; - private static final double F6S0 = 0; - private static final double F6C1 = 0.50000000000000011102230246251565404236316680908203125; - private static final double F6S1 = 0.8660254037844385965883020617184229195117950439453125; - private static final double F6C2 = -0.4999999999999997779553950749686919152736663818359375; - private static final double F6S2 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F6C3 = -1; - private static final double F6S3 = 0.000000000000000122464679914735320717376402945839660462569212467758006379625612680683843791484832763671875; - private static final double F6C4 = -0.500000000000000444089209850062616169452667236328125; - private static final double F6S4 = -0.86602540378443837454369713668711483478546142578125; - private static final double F6C5 = 0.50000000000000011102230246251565404236316680908203125; - private static final double F6S5 = -0.8660254037844385965883020617184229195117950439453125; - - private static double sc6(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F6C0) - (r * F6S0)), z + ((r * F6S0) + (r * F6C0))) - + n.noise(x + ((r * F6C1) - (r * F6S1)), z + ((r * F6S1) + (r * F6C1))) - + n.noise(x + ((r * F6C2) - (r * F6S2)), z + ((r * F6S2) + (r * F6C2))) - + n.noise(x + ((r * F6C3) - (r * F6S3)), z + ((r * F6S3) + (r * F6C3))) - + n.noise(x + ((r * F6C4) - (r * F6S4)), z + ((r * F6S4) + (r * F6C4))) - + n.noise(x + ((r * F6C5) - (r * F6S5)), z + ((r * F6S5) + (r * F6C5)))) / 6.0D; - } - - private static final double F7C0 = 1; - private static final double F7S0 = 0; - private static final double F7C1 = 0.6293203910498375019955119569203816354274749755859375; - private static final double F7S1 = 0.77714596145697090179282895405776798725128173828125; - private static final double F7C2 = -0.207911690817759342575499204031075350940227508544921875; - private static final double F7S2 = 0.9781476007338056888329447247087955474853515625; - private static final double F7C3 = -0.891006524188367787786546614370308816432952880859375; - private static final double F7S3 = 0.45399049973954685999188995992881245911121368408203125; - private static final double F7C4 = -0.91354545764260086659902526662335731089115142822265625; - private static final double F7S4 = -0.406736643075800208269043878317461349070072174072265625; - private static final double F7C5 = -0.25881904510252062845410137015278451144695281982421875; - private static final double F7S5 = -0.96592582628906831221371476203785277903079986572265625; - private static final double F7C6 = 0.587785252292472915058851867797784507274627685546875; - private static final double F7S6 = -0.80901699437494756228517189811100251972675323486328125; - private static final double F7C7 = 0.99862953475457383323288240717374719679355621337890625; - private static final double F7S7 = -0.052335956242944368932423770957029773853719234466552734375; - - private static double sc7(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F7C0) - (r * F7S0)), z + ((r * F7S0) + (r * F7C0))) - + n.noise(x + ((r * F7C1) - (r * F7S1)), z + ((r * F7S1) + (r * F7C1))) - + n.noise(x + ((r * F7C2) - (r * F7S2)), z + ((r * F7S2) + (r * F7C2))) - + n.noise(x + ((r * F7C3) - (r * F7S3)), z + ((r * F7S3) + (r * F7C3))) - + n.noise(x + ((r * F7C4) - (r * F7S4)), z + ((r * F7S4) + (r * F7C4))) - + n.noise(x + ((r * F7C5) - (r * F7S5)), z + ((r * F7S5) + (r * F7C5))) - + n.noise(x + ((r * F7C6) - (r * F7S6)), z + ((r * F7S6) + (r * F7C6))) - + n.noise(x + ((r * F7C7) - (r * F7S7)), z + ((r * F7S7) + (r * F7C7)))) / 7.0D; - } - - private static final double F9C0 = 1; - private static final double F9S0 = 0; - private static final double F9C1 = 0.76604444311897801345168090847437269985675811767578125; - private static final double F9S1 = 0.642787609686539251896419955301098525524139404296875; - private static final double F9C2 = 0.17364817766693041445336120887077413499355316162109375; - private static final double F9S2 = 0.98480775301220802031565426659653894603252410888671875; - private static final double F9C3 = -0.4999999999999997779553950749686919152736663818359375; - private static final double F9S3 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F9C4 = -0.93969262078590831688273965482949279248714447021484375; - private static final double F9S4 = 0.342020143325668879441536773811094462871551513671875; - private static final double F9C5 = -0.939692620785908427905042117345146834850311279296875; - private static final double F9S5 = -0.3420201433256686573969318487797863781452178955078125; - private static final double F9C6 = -0.500000000000000444089209850062616169452667236328125; - private static final double F9S6 = -0.86602540378443837454369713668711483478546142578125; - private static final double F9C7 = 0.17364817766692997036415135880815796554088592529296875; - private static final double F9S7 = -0.98480775301220813133795672911219298839569091796875; - private static final double F9C8 = 0.76604444311897779140707598344306461513042449951171875; - private static final double F9S8 = -0.64278760968653958496332734284806065261363983154296875; - - private static double sc9(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F9C0) - (r * F9S0)), z + ((r * F9S0) + (r * F9C0))) - + n.noise(x + ((r * F9C1) - (r * F9S1)), z + ((r * F9S1) + (r * F9C1))) - + n.noise(x + ((r * F9C2) - (r * F9S2)), z + ((r * F9S2) + (r * F9C2))) - + n.noise(x + ((r * F9C3) - (r * F9S3)), z + ((r * F9S3) + (r * F9C3))) - + n.noise(x + ((r * F9C4) - (r * F9S4)), z + ((r * F9S4) + (r * F9C4))) - + n.noise(x + ((r * F9C5) - (r * F9S5)), z + ((r * F9S5) + (r * F9C5))) - + n.noise(x + ((r * F9C6) - (r * F9S6)), z + ((r * F9S6) + (r * F9C6))) - + n.noise(x + ((r * F9C7) - (r * F9S7)), z + ((r * F9S7) + (r * F9C7))) - + n.noise(x + ((r * F9C8) - (r * F9S8)), z + ((r * F9S8) + (r * F9C8)))) / 9.0D; - } - - private static final double F12C0 = 1; - private static final double F12S0 = 0; - private static final double F12C1 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F12S1 = 0.499999999999999944488848768742172978818416595458984375; - private static final double F12C2 = 0.50000000000000011102230246251565404236316680908203125; - private static final double F12S2 = 0.8660254037844385965883020617184229195117950439453125; - private static final double F12C3 = 0.0000000000000000612323399573676603586882014729198302312846062338790031898128063403419218957424163818359375; - private static final double F12S3 = 1; - private static final double F12C4 = -0.4999999999999997779553950749686919152736663818359375; - private static final double F12S4 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F12C5 = -0.86602540378443870761060452423407696187496185302734375; - private static final double F12S5 = 0.499999999999999944488848768742172978818416595458984375; - private static final double F12C6 = -1; - private static final double F12S6 = 0.000000000000000122464679914735320717376402945839660462569212467758006379625612680683843791484832763671875; - private static final double F12C7 = -0.8660254037844385965883020617184229195117950439453125; - private static final double F12S7 = -0.50000000000000011102230246251565404236316680908203125; - private static final double F12C8 = -0.500000000000000444089209850062616169452667236328125; - private static final double F12S8 = -0.86602540378443837454369713668711483478546142578125; - private static final double F12C9 = -0.00000000000000018369701987210296875011296034045003113559498615810217092558787044254131615161895751953125; - private static final double F12S9 = -1; - private static final double F12C10 = 0.50000000000000011102230246251565404236316680908203125; - private static final double F12S10 = -0.8660254037844385965883020617184229195117950439453125; - private static final double F12C11 = 0.86602540378443837454369713668711483478546142578125; - private static final double F12S11 = -0.500000000000000444089209850062616169452667236328125; - - private static double sc12(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F12C0) - (r * F12S0)), z + ((r * F12S0) + (r * F12C0))) - + n.noise(x + ((r * F12C1) - (r * F12S1)), z + ((r * F12S1) + (r * F12C1))) - + n.noise(x + ((r * F12C2) - (r * F12S2)), z + ((r * F12S2) + (r * F12C2))) - + n.noise(x + ((r * F12C3) - (r * F12S3)), z + ((r * F12S3) + (r * F12C3))) - + n.noise(x + ((r * F12C4) - (r * F12S4)), z + ((r * F12S4) + (r * F12C4))) - + n.noise(x + ((r * F12C5) - (r * F12S5)), z + ((r * F12S5) + (r * F12C5))) - + n.noise(x + ((r * F12C6) - (r * F12S6)), z + ((r * F12S6) + (r * F12C6))) - + n.noise(x + ((r * F12C7) - (r * F12S7)), z + ((r * F12S7) + (r * F12C7))) - + n.noise(x + ((r * F12C8) - (r * F12S8)), z + ((r * F12S8) + (r * F12C8))) - + n.noise(x + ((r * F12C9) - (r * F12S9)), z + ((r * F12S9) + (r * F12C9))) - + n.noise(x + ((r * F12C10) - (r * F12S10)), z + ((r * F12S10) + (r * F12C10))) - + n.noise(x + ((r * F12C11) - (r * F12S11)), z + ((r * F12S11) + (r * F12C11)))) / 12.0D; - } - - private static final double F24C0 = 1; - private static final double F24S0 = 0; - private static final double F24C1 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F24S1 = 0.25881904510252073947640383266843855381011962890625; - private static final double F24C2 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F24S2 = 0.499999999999999944488848768742172978818416595458984375; - private static final double F24C3 = 0.70710678118654757273731092936941422522068023681640625; - private static final double F24S3 = 0.707106781186547461715008466853760182857513427734375; - private static final double F24C4 = 0.50000000000000011102230246251565404236316680908203125; - private static final double F24S4 = 0.8660254037844385965883020617184229195117950439453125; - private static final double F24C5 = 0.25881904510252073947640383266843855381011962890625; - private static final double F24S5 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F24C6 = 0.0000000000000000612323399573676603586882014729198302312846062338790031898128063403419218957424163818359375; - private static final double F24S6 = 1; - private static final double F24C7 = -0.25881904510252085049870629518409259617328643798828125; - private static final double F24S7 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F24C8 = -0.4999999999999997779553950749686919152736663818359375; - private static final double F24S8 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F24C9 = -0.707106781186547461715008466853760182857513427734375; - private static final double F24S9 = 0.70710678118654757273731092936941422522068023681640625; - private static final double F24C10 = -0.86602540378443870761060452423407696187496185302734375; - private static final double F24S10 = 0.499999999999999944488848768742172978818416595458984375; - private static final double F24C11 = -0.965925826289068201191412299522198736667633056640625; - private static final double F24S11 = 0.258819045102521017032159988957573659718036651611328125; - private static final double F24C12 = -1; - private static final double F24S12 = 0.000000000000000122464679914735320717376402945839660462569212467758006379625612680683843791484832763671875; - private static final double F24C13 = -0.96592582628906831221371476203785277903079986572265625; - private static final double F24S13 = -0.258819045102520794987555063926265574991703033447265625; - private static final double F24C14 = -0.8660254037844385965883020617184229195117950439453125; - private static final double F24S14 = -0.50000000000000011102230246251565404236316680908203125; - private static final double F24C15 = -0.7071067811865476837596133918850682675838470458984375; - private static final double F24S15 = -0.707106781186547461715008466853760182857513427734375; - private static final double F24C16 = -0.500000000000000444089209850062616169452667236328125; - private static final double F24S16 = -0.86602540378443837454369713668711483478546142578125; - private static final double F24C17 = -0.25881904510252062845410137015278451144695281982421875; - private static final double F24S17 = -0.96592582628906831221371476203785277903079986572265625; - private static final double F24C18 = -0.00000000000000018369701987210296875011296034045003113559498615810217092558787044254131615161895751953125; - private static final double F24S18 = -1; - private static final double F24C19 = 0.258819045102520295387193982605822384357452392578125; - private static final double F24S19 = -0.9659258262890684232360172245535068213939666748046875; - private static final double F24C20 = 0.50000000000000011102230246251565404236316680908203125; - private static final double F24S20 = -0.8660254037844385965883020617184229195117950439453125; - private static final double F24C21 = 0.70710678118654735069270600433810614049434661865234375; - private static final double F24S21 = -0.7071067811865476837596133918850682675838470458984375; - private static final double F24C22 = 0.86602540378443837454369713668711483478546142578125; - private static final double F24S22 = -0.500000000000000444089209850062616169452667236328125; - private static final double F24C23 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F24S23 = -0.258819045102520683965252601410611532628536224365234375; - - private static double sc24(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F24C0) - (r * F24S0)), z + ((r * F24S0) + (r * F24C0))) - + n.noise(x + ((r * F24C1) - (r * F24S1)), z + ((r * F24S1) + (r * F24C1))) - + n.noise(x + ((r * F24C2) - (r * F24S2)), z + ((r * F24S2) + (r * F24C2))) - + n.noise(x + ((r * F24C3) - (r * F24S3)), z + ((r * F24S3) + (r * F24C3))) - + n.noise(x + ((r * F24C4) - (r * F24S4)), z + ((r * F24S4) + (r * F24C4))) - + n.noise(x + ((r * F24C5) - (r * F24S5)), z + ((r * F24S5) + (r * F24C5))) - + n.noise(x + ((r * F24C6) - (r * F24S6)), z + ((r * F24S6) + (r * F24C6))) - + n.noise(x + ((r * F24C7) - (r * F24S7)), z + ((r * F24S7) + (r * F24C7))) - + n.noise(x + ((r * F24C8) - (r * F24S8)), z + ((r * F24S8) + (r * F24C8))) - + n.noise(x + ((r * F24C9) - (r * F24S9)), z + ((r * F24S9) + (r * F24C9))) - + n.noise(x + ((r * F24C10) - (r * F24S10)), z + ((r * F24S10) + (r * F24C10))) - + n.noise(x + ((r * F24C11) - (r * F24S11)), z + ((r * F24S11) + (r * F24C11))) - + n.noise(x + ((r * F24C12) - (r * F24S12)), z + ((r * F24S12) + (r * F24C12))) - + n.noise(x + ((r * F24C13) - (r * F24S13)), z + ((r * F24S13) + (r * F24C13))) - + n.noise(x + ((r * F24C14) - (r * F24S14)), z + ((r * F24S14) + (r * F24C14))) - + n.noise(x + ((r * F24C15) - (r * F24S15)), z + ((r * F24S15) + (r * F24C15))) - + n.noise(x + ((r * F24C16) - (r * F24S16)), z + ((r * F24S16) + (r * F24C16))) - + n.noise(x + ((r * F24C17) - (r * F24S17)), z + ((r * F24S17) + (r * F24C17))) - + n.noise(x + ((r * F24C18) - (r * F24S18)), z + ((r * F24S18) + (r * F24C18))) - + n.noise(x + ((r * F24C19) - (r * F24S19)), z + ((r * F24S19) + (r * F24C19))) - + n.noise(x + ((r * F24C20) - (r * F24S20)), z + ((r * F24S20) + (r * F24C20))) - + n.noise(x + ((r * F24C21) - (r * F24S21)), z + ((r * F24S21) + (r * F24C21))) - + n.noise(x + ((r * F24C22) - (r * F24S22)), z + ((r * F24S22) + (r * F24C22))) - + n.noise(x + ((r * F24C23) - (r * F24S23)), z + ((r * F24S23) + (r * F24C23)))) / 24.0D; - } - - private static final double F32C0 = 1; - private static final double F32S0 = 0; - private static final double F32C1 = 0.9816271834476639757127713892259635031223297119140625; - private static final double F32S1 = 0.1908089953765448043565555735767702572047710418701171875; - private static final double F32C2 = 0.92718385456678742428948680753819644451141357421875; - private static final double F32S2 = 0.374606593415912014766178117497474886476993560791015625; - private static final double F32C3 = 0.838670567945424050293468098971061408519744873046875; - private static final double F32S3 = 0.54463903501502708426329490976058878004550933837890625; - private static final double F32C4 = 0.71933980033865119185776393351261503994464874267578125; - private static final double F32S4 = 0.6946583704589972541043607634492218494415283203125; - private static final double F32C5 = 0.57357643635104615942310601894860155880451202392578125; - private static final double F32S5 = 0.81915204428899179855960710483486764132976531982421875; - private static final double F32C6 = 0.406736643075800208269043878317461349070072174072265625; - private static final double F32S6 = 0.91354545764260086659902526662335731089115142822265625; - private static final double F32C7 = 0.224951054343864920159745679484331049025058746337890625; - private static final double F32S7 = 0.97437006478523524588553073044749908149242401123046875; - private static final double F32C8 = 0.034899496702501080214187112460422213189303874969482421875; - private static final double F32S8 = 0.99939082701909576211818375668372027575969696044921875; - private static final double F32C9 = -0.1564344650402308134484741231062798760831356048583984375; - private static final double F32S9 = 0.987688340595137770350220307591371238231658935546875; - private static final double F32C10 = -0.342020143325668712908083080037613399326801300048828125; - private static final double F32S10 = 0.939692620785908427905042117345146834850311279296875; - private static final double F32C11 = -0.515038074910054266553061097511090338230133056640625; - private static final double F32S11 = 0.8571673007021123336102164103067480027675628662109375; - private static final double F32C12 = -0.66913060635885823757007528911344707012176513671875; - private static final double F32S12 = 0.7431448254773942441175904605188407003879547119140625; - private static final double F32C13 = -0.79863551004729294024997443557367660105228424072265625; - private static final double F32S13 = 0.60181502315204815634075430352822877466678619384765625; - private static final double F32C14 = -0.8987940462991670376169395240140147507190704345703125; - private static final double F32S14 = 0.43837114678907729281576166613376699388027191162109375; - private static final double F32C15 = -0.965925826289068201191412299522198736667633056640625; - private static final double F32S15 = 0.258819045102521017032159988957573659718036651611328125; - private static final double F32C16 = -0.9975640502598241976528470331686548888683319091796875; - private static final double F32S16 = 0.06975647374412552448319502218510024249553680419921875; - private static final double F32C17 = -0.992546151641322094150154953240416944026947021484375; - private static final double F32S17 = -0.12186934340514730956694933183825924061238765716552734375; - private static final double F32C18 = -0.951056516295153642204240895807743072509765625; - private static final double F32S18 = -0.309016994374947284729415741821867413818836212158203125; - private static final double F32C19 = -0.87461970713939585220231265338952653110027313232421875; - private static final double F32S19 = -0.484809620246336947513299264755914919078350067138671875; - private static final double F32C20 = -0.76604444311897801345168090847437269985675811767578125; - private static final double F32S20 = -0.642787609686539251896419955301098525524139404296875; - private static final double F32C21 = -0.62932039104983783506241934446734376251697540283203125; - private static final double F32S21 = -0.77714596145697056872592156651080586016178131103515625; - private static final double F32C22 = -0.469471562785890750291173389996401965618133544921875; - private static final double F32S22 = -0.88294759285892698841280434862710535526275634765625; - private static final double F32C23 = -0.29237170472273710242205879694665782153606414794921875; - private static final double F32S23 = -0.9563047559630353244841671767062507569789886474609375; - private static final double F32C24 = -0.104528463267653359825004599770181812345981597900390625; - private static final double F32S24 = -0.99452189536827340088365190240438096225261688232421875; - private static final double F32C25 = 0.0871557427476578883140945208651828579604625701904296875; - private static final double F32S25 = -0.9961946980917455451987052583717741072177886962890625; - private static final double F32C26 = 0.275637355816999385371701691838097758591175079345703125; - private static final double F32S26 = -0.96126169593831878312784056106465868651866912841796875; - private static final double F32C27 = 0.45399049973954663794728503489750437438488006591796875; - private static final double F32S27 = -0.89100652418836789880884907688596285879611968994140625; - private static final double F32C28 = 0.61566147532565851374641852089553140103816986083984375; - private static final double F32S28 = -0.7880107536067217921527117141522467136383056640625; - private static final double F32C29 = 0.7547095802227719030241814834880642592906951904296875; - private static final double F32S29 = -0.65605902899050738685815531425760127604007720947265625; - private static final double F32C30 = 0.86602540378443837454369713668711483478546142578125; - private static final double F32S30 = -0.500000000000000444089209850062616169452667236328125; - private static final double F32C31 = 0.94551857559931684615861513520940206944942474365234375; - private static final double F32S31 = -0.3255681544571566998769185374840162694454193115234375; - private static final double F32C32 = 0.99026806874157025095684048210387118160724639892578125; - private static final double F32S32 = -0.1391731009600658819369556340461713261902332305908203125; - - private static double sc32(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F32C0) - (r * F32S0)), z + ((r * F32S0) + (r * F32C0))) - + n.noise(x + ((r * F32C1) - (r * F32S1)), z + ((r * F32S1) + (r * F32C1))) - + n.noise(x + ((r * F32C2) - (r * F32S2)), z + ((r * F32S2) + (r * F32C2))) - + n.noise(x + ((r * F32C3) - (r * F32S3)), z + ((r * F32S3) + (r * F32C3))) - + n.noise(x + ((r * F32C4) - (r * F32S4)), z + ((r * F32S4) + (r * F32C4))) - + n.noise(x + ((r * F32C5) - (r * F32S5)), z + ((r * F32S5) + (r * F32C5))) - + n.noise(x + ((r * F32C6) - (r * F32S6)), z + ((r * F32S6) + (r * F32C6))) - + n.noise(x + ((r * F32C7) - (r * F32S7)), z + ((r * F32S7) + (r * F32C7))) - + n.noise(x + ((r * F32C8) - (r * F32S8)), z + ((r * F32S8) + (r * F32C8))) - + n.noise(x + ((r * F32C9) - (r * F32S9)), z + ((r * F32S9) + (r * F32C9))) - + n.noise(x + ((r * F32C10) - (r * F32S10)), z + ((r * F32S10) + (r * F32C10))) - + n.noise(x + ((r * F32C11) - (r * F32S11)), z + ((r * F32S11) + (r * F32C11))) - + n.noise(x + ((r * F32C12) - (r * F32S12)), z + ((r * F32S12) + (r * F32C12))) - + n.noise(x + ((r * F32C13) - (r * F32S13)), z + ((r * F32S13) + (r * F32C13))) - + n.noise(x + ((r * F32C14) - (r * F32S14)), z + ((r * F32S14) + (r * F32C14))) - + n.noise(x + ((r * F32C15) - (r * F32S15)), z + ((r * F32S15) + (r * F32C15))) - + n.noise(x + ((r * F32C16) - (r * F32S16)), z + ((r * F32S16) + (r * F32C16))) - + n.noise(x + ((r * F32C17) - (r * F32S17)), z + ((r * F32S17) + (r * F32C17))) - + n.noise(x + ((r * F32C18) - (r * F32S18)), z + ((r * F32S18) + (r * F32C18))) - + n.noise(x + ((r * F32C19) - (r * F32S19)), z + ((r * F32S19) + (r * F32C19))) - + n.noise(x + ((r * F32C20) - (r * F32S20)), z + ((r * F32S20) + (r * F32C20))) - + n.noise(x + ((r * F32C21) - (r * F32S21)), z + ((r * F32S21) + (r * F32C21))) - + n.noise(x + ((r * F32C22) - (r * F32S22)), z + ((r * F32S22) + (r * F32C22))) - + n.noise(x + ((r * F32C23) - (r * F32S23)), z + ((r * F32S23) + (r * F32C23))) - + n.noise(x + ((r * F32C24) - (r * F32S24)), z + ((r * F32S24) + (r * F32C24))) - + n.noise(x + ((r * F32C25) - (r * F32S25)), z + ((r * F32S25) + (r * F32C25))) - + n.noise(x + ((r * F32C26) - (r * F32S26)), z + ((r * F32S26) + (r * F32C26))) - + n.noise(x + ((r * F32C27) - (r * F32S27)), z + ((r * F32S27) + (r * F32C27))) - + n.noise(x + ((r * F32C28) - (r * F32S28)), z + ((r * F32S28) + (r * F32C28))) - + n.noise(x + ((r * F32C29) - (r * F32S29)), z + ((r * F32S29) + (r * F32C29))) - + n.noise(x + ((r * F32C30) - (r * F32S30)), z + ((r * F32S30) + (r * F32C30))) - + n.noise(x + ((r * F32C31) - (r * F32S31)), z + ((r * F32S31) + (r * F32C31))) - + n.noise(x + ((r * F32C32) - (r * F32S32)), z + ((r * F32S32) + (r * F32C32)))) / 32.0D; - } - - private static final double F48C0 = 1; - private static final double F48S0 = 0; - private static final double F48C1 = 0.99254615164132198312785249072476290166378021240234375; - private static final double F48S1 = 0.12186934340514747610040302561174030415713787078857421875; - private static final double F48C2 = 0.97029572627599647294260876151383854448795318603515625; - private static final double F48S2 = 0.2419218955996677300479547056966111995279788970947265625; - private static final double F48C3 = 0.93358042649720174299687869279296137392520904541015625; - private static final double F48S3 = 0.3583679495453002683547083506709896028041839599609375; - private static final double F48C4 = 0.88294759285892698841280434862710535526275634765625; - private static final double F48S4 = 0.469471562785890805802324621254228986799716949462890625; - private static final double F48C5 = 0.81915204428899179855960710483486764132976531982421875; - private static final double F48S5 = 0.57357643635104604840080355643294751644134521484375; - private static final double F48C6 = 0.7431448254773942441175904605188407003879547119140625; - private static final double F48S6 = 0.66913060635885823757007528911344707012176513671875; - private static final double F48C7 = 0.656059028990507275835852851741947233676910400390625; - private static final double F48S7 = 0.75470958022277201404648394600371830165386199951171875; - private static final double F48C8 = 0.5591929034707467938147829045192338526248931884765625; - private static final double F48S8 = 0.82903757255504173517834942686022259294986724853515625; - private static final double F48C9 = 0.453990499739546804480738728670985437929630279541015625; - private static final double F48S9 = 0.891006524188367787786546614370308816432952880859375; - private static final double F48C10 = 0.342020143325668823930385542553267441689968109130859375; - private static final double F48S10 = 0.93969262078590831688273965482949279248714447021484375; - private static final double F48C11 = 0.224951054343864920159745679484331049025058746337890625; - private static final double F48S11 = 0.97437006478523524588553073044749908149242401123046875; - private static final double F48C12 = 0.10452846326765345696951925447137909941375255584716796875; - private static final double F48S12 = 0.9945218953682732898613494398887269198894500732421875; - private static final double F48C13 = -0.01745240643728347695873281963940826244652271270751953125; - private static final double F48S13 = 0.9998476951563912695775115935248322784900665283203125; - private static final double F48C14 = -0.139173100960065354581018937096814624965190887451171875; - private static final double F48S14 = 0.9902680687415703619791429446195252239704132080078125; - private static final double F48C15 = -0.25881904510252085049870629518409259617328643798828125; - private static final double F48S15 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F48C16 = -0.37460659341591207027732934875530190765857696533203125; - private static final double F48S16 = 0.92718385456678742428948680753819644451141357421875; - private static final double F48C17 = -0.4848096202463370030244504960137419402599334716796875; - private static final double F48S17 = 0.87461970713939585220231265338952653110027313232421875; - private static final double F48C18 = -0.58778525229247302608115433031343854963779449462890625; - private static final double F48S18 = 0.80901699437494745126286943559534847736358642578125; - private static final double F48C19 = -0.6819983600624983655080768585321493446826934814453125; - private static final double F48S19 = 0.73135370161917057085787519099540077149868011474609375; - private static final double F48C20 = -0.76604444311897790242937844595871865749359130859375; - private static final double F48S20 = 0.6427876096865394739410248803324066102504730224609375; - private static final double F48C21 = -0.83867056794542393927116563645540736615657806396484375; - private static final double F48S21 = 0.54463903501502730630789983479189686477184295654296875; - private static final double F48C22 = -0.8987940462991670376169395240140147507190704345703125; - private static final double F48S22 = 0.43837114678907729281576166613376699388027191162109375; - private static final double F48C23 = -0.94551857559931684615861513520940206944942474365234375; - private static final double F48S23 = 0.32556815445715658885461607496836222708225250244140625; - private static final double F48C24 = -0.9781476007338056888329447247087955474853515625; - private static final double F48S24 = 0.2079116908177593148199235884021618403494358062744140625; - private static final double F48C25 = -0.9961946980917455451987052583717741072177886962890625; - private static final double F48S25 = 0.087155742747658193625426292783231474459171295166015625; - private static final double F48C26 = -0.99939082701909576211818375668372027575969696044921875; - private static final double F48S26 = -0.034899496702500899802945610872484394349157810211181640625; - private static final double F48C27 = -0.987688340595137770350220307591371238231658935546875; - private static final double F48S27 = -0.156434465040230730181747276219539344310760498046875; - private static final double F48C28 = -0.9612616959383188941501430235803127288818359375; - private static final double F48S28 = -0.27563735581699899679364307303330861032009124755859375; - private static final double F48C29 = -0.92050485345244037471701403774204663932323455810546875; - private static final double F48S29 = -0.390731128489273549231342030907399021089076995849609375; - private static final double F48C30 = -0.8660254037844385965883020617184229195117950439453125; - private static final double F48S30 = -0.50000000000000011102230246251565404236316680908203125; - private static final double F48C31 = -0.798635510047292829227671973058022558689117431640625; - private static final double F48S31 = -0.60181502315204837838535922855953685939311981201171875; - private static final double F48C32 = -0.71933980033865108083546147099696099758148193359375; - private static final double F48S32 = -0.69465837045899736512666322596487589180469512939453125; - private static final double F48C33 = -0.62932039104983783506241934446734376251697540283203125; - private static final double F48S33 = -0.77714596145697056872592156651080586016178131103515625; - private static final double F48C34 = -0.52991926423320501182701036668731831014156341552734375; - private static final double F48S34 = -0.84804809615642595677087456351728178560733795166015625; - private static final double F48C35 = -0.42261826174069916373099431439186446368694305419921875; - private static final double F48S35 = -0.90630778703665004769618462887592613697052001953125; - private static final double F48C36 = -0.30901699437494756228517189811100251972675323486328125; - private static final double F48S36 = -0.95105651629515353118193843329208903014659881591796875; - private static final double F48C37 = -0.1908089953765446100675262641743756830692291259765625; - private static final double F48S37 = -0.9816271834476639757127713892259635031223297119140625; - private static final double F48C38 = -0.069756473744125579994346253442927263677120208740234375; - private static final double F48S38 = -0.9975640502598241976528470331686548888683319091796875; - private static final double F48C39 = 0.05233595624294394565989563261609873734414577484130859375; - private static final double F48S39 = -0.99862953475457383323288240717374719679355621337890625; - private static final double F48C40 = 0.17364817766692997036415135880815796554088592529296875; - private static final double F48S40 = -0.98480775301220813133795672911219298839569091796875; - private static final double F48C41 = 0.292371704722736713844000178141868673264980316162109375; - private static final double F48S41 = -0.95630475596303543550646963922190479934215545654296875; - private static final double F48C42 = 0.406736643075799764179834028254845179617404937744140625; - private static final double F48S42 = -0.91354545764260108864363019165466539561748504638671875; - private static final double F48C43 = 0.51503807491005415553075863499543629586696624755859375; - private static final double F48S43 = -0.8571673007021123336102164103067480027675628662109375; - private static final double F48C44 = 0.61566147532565851374641852089553140103816986083984375; - private static final double F48S44 = -0.7880107536067217921527117141522467136383056640625; - private static final double F48C45 = 0.70710678118654735069270600433810614049434661865234375; - private static final double F48S45 = -0.7071067811865476837596133918850682675838470458984375; - private static final double F48C46 = 0.7880107536067220141973166391835547983646392822265625; - private static final double F48S46 = -0.61566147532565818067951113334856927394866943359375; - private static final double F48C47 = 0.857167300702112111565611485275439918041229248046875; - private static final double F48S47 = -0.5150380749100544885976660225423984229564666748046875; - private static final double F48C48 = 0.9135454576426009776213277291390113532543182373046875; - private static final double F48S48 = -0.40673664307580015275789264705963432788848876953125; - private static final double F48C49 = 0.9563047559630353244841671767062507569789886474609375; - private static final double F48S49 = -0.292371704722737157933210028204484842717647552490234375; - private static final double F48C50 = 0.98480775301220802031565426659653894603252410888671875; - private static final double F48S50 = -0.1736481776669303866977855932418606244027614593505859375; - private static final double F48C51 = 0.99862953475457383323288240717374719679355621337890625; - private static final double F48S51 = -0.052335956242944368932423770957029773853719234466552734375; - - private static double sc48(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F48C0) - (r * F48S0)), z + ((r * F48S0) + (r * F48C0))) - + n.noise(x + ((r * F48C1) - (r * F48S1)), z + ((r * F48S1) + (r * F48C1))) - + n.noise(x + ((r * F48C2) - (r * F48S2)), z + ((r * F48S2) + (r * F48C2))) - + n.noise(x + ((r * F48C3) - (r * F48S3)), z + ((r * F48S3) + (r * F48C3))) - + n.noise(x + ((r * F48C4) - (r * F48S4)), z + ((r * F48S4) + (r * F48C4))) - + n.noise(x + ((r * F48C5) - (r * F48S5)), z + ((r * F48S5) + (r * F48C5))) - + n.noise(x + ((r * F48C6) - (r * F48S6)), z + ((r * F48S6) + (r * F48C6))) - + n.noise(x + ((r * F48C7) - (r * F48S7)), z + ((r * F48S7) + (r * F48C7))) - + n.noise(x + ((r * F48C8) - (r * F48S8)), z + ((r * F48S8) + (r * F48C8))) - + n.noise(x + ((r * F48C9) - (r * F48S9)), z + ((r * F48S9) + (r * F48C9))) - + n.noise(x + ((r * F48C10) - (r * F48S10)), z + ((r * F48S10) + (r * F48C10))) - + n.noise(x + ((r * F48C11) - (r * F48S11)), z + ((r * F48S11) + (r * F48C11))) - + n.noise(x + ((r * F48C12) - (r * F48S12)), z + ((r * F48S12) + (r * F48C12))) - + n.noise(x + ((r * F48C13) - (r * F48S13)), z + ((r * F48S13) + (r * F48C13))) - + n.noise(x + ((r * F48C14) - (r * F48S14)), z + ((r * F48S14) + (r * F48C14))) - + n.noise(x + ((r * F48C15) - (r * F48S15)), z + ((r * F48S15) + (r * F48C15))) - + n.noise(x + ((r * F48C16) - (r * F48S16)), z + ((r * F48S16) + (r * F48C16))) - + n.noise(x + ((r * F48C17) - (r * F48S17)), z + ((r * F48S17) + (r * F48C17))) - + n.noise(x + ((r * F48C18) - (r * F48S18)), z + ((r * F48S18) + (r * F48C18))) - + n.noise(x + ((r * F48C19) - (r * F48S19)), z + ((r * F48S19) + (r * F48C19))) - + n.noise(x + ((r * F48C20) - (r * F48S20)), z + ((r * F48S20) + (r * F48C20))) - + n.noise(x + ((r * F48C21) - (r * F48S21)), z + ((r * F48S21) + (r * F48C21))) - + n.noise(x + ((r * F48C22) - (r * F48S22)), z + ((r * F48S22) + (r * F48C22))) - + n.noise(x + ((r * F48C23) - (r * F48S23)), z + ((r * F48S23) + (r * F48C23))) - + n.noise(x + ((r * F48C24) - (r * F48S24)), z + ((r * F48S24) + (r * F48C24))) - + n.noise(x + ((r * F48C25) - (r * F48S25)), z + ((r * F48S25) + (r * F48C25))) - + n.noise(x + ((r * F48C26) - (r * F48S26)), z + ((r * F48S26) + (r * F48C26))) - + n.noise(x + ((r * F48C27) - (r * F48S27)), z + ((r * F48S27) + (r * F48C27))) - + n.noise(x + ((r * F48C28) - (r * F48S28)), z + ((r * F48S28) + (r * F48C28))) - + n.noise(x + ((r * F48C29) - (r * F48S29)), z + ((r * F48S29) + (r * F48C29))) - + n.noise(x + ((r * F48C30) - (r * F48S30)), z + ((r * F48S30) + (r * F48C30))) - + n.noise(x + ((r * F48C31) - (r * F48S31)), z + ((r * F48S31) + (r * F48C31))) - + n.noise(x + ((r * F48C32) - (r * F48S32)), z + ((r * F48S32) + (r * F48C32))) - + n.noise(x + ((r * F48C33) - (r * F48S33)), z + ((r * F48S33) + (r * F48C33))) - + n.noise(x + ((r * F48C34) - (r * F48S34)), z + ((r * F48S34) + (r * F48C34))) - + n.noise(x + ((r * F48C35) - (r * F48S35)), z + ((r * F48S35) + (r * F48C35))) - + n.noise(x + ((r * F48C36) - (r * F48S36)), z + ((r * F48S36) + (r * F48C36))) - + n.noise(x + ((r * F48C37) - (r * F48S37)), z + ((r * F48S37) + (r * F48C37))) - + n.noise(x + ((r * F48C38) - (r * F48S38)), z + ((r * F48S38) + (r * F48C38))) - + n.noise(x + ((r * F48C39) - (r * F48S39)), z + ((r * F48S39) + (r * F48C39))) - + n.noise(x + ((r * F48C40) - (r * F48S40)), z + ((r * F48S40) + (r * F48C40))) - + n.noise(x + ((r * F48C41) - (r * F48S41)), z + ((r * F48S41) + (r * F48C41))) - + n.noise(x + ((r * F48C42) - (r * F48S42)), z + ((r * F48S42) + (r * F48C42))) - + n.noise(x + ((r * F48C43) - (r * F48S43)), z + ((r * F48S43) + (r * F48C43))) - + n.noise(x + ((r * F48C44) - (r * F48S44)), z + ((r * F48S44) + (r * F48C44))) - + n.noise(x + ((r * F48C45) - (r * F48S45)), z + ((r * F48S45) + (r * F48C45))) - + n.noise(x + ((r * F48C46) - (r * F48S46)), z + ((r * F48S46) + (r * F48C46))) - + n.noise(x + ((r * F48C47) - (r * F48S47)), z + ((r * F48S47) + (r * F48C47))) - + n.noise(x + ((r * F48C48) - (r * F48S48)), z + ((r * F48S48) + (r * F48C48))) - + n.noise(x + ((r * F48C49) - (r * F48S49)), z + ((r * F48S49) + (r * F48C49))) - + n.noise(x + ((r * F48C50) - (r * F48S50)), z + ((r * F48S50) + (r * F48C50))) - + n.noise(x + ((r * F48C51) - (r * F48S51)), z + ((r * F48S51) + (r * F48C51)))) / 48.0D; - } - - private static final double F64C0 = 1; - private static final double F64S0 = 0; - private static final double F64C1 = 0.9961946980917455451987052583717741072177886962890625; - private static final double F64S1 = 0.0871557427476581658698506771543179638683795928955078125; - private static final double F64C2 = 0.98480775301220802031565426659653894603252410888671875; - private static final double F64S2 = 0.1736481776669303311866343619840336032211780548095703125; - private static final double F64C3 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F64S3 = 0.25881904510252073947640383266843855381011962890625; - private static final double F64C4 = 0.939692620785908427905042117345146834850311279296875; - private static final double F64S4 = 0.342020143325668712908083080037613399326801300048828125; - private static final double F64C5 = 0.90630778703664993667388216636027209460735321044921875; - private static final double F64S5 = 0.422618261740699441286750470680999569594860076904296875; - private static final double F64C6 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F64S6 = 0.499999999999999944488848768742172978818416595458984375; - private static final double F64C7 = 0.81915204428899179855960710483486764132976531982421875; - private static final double F64S7 = 0.57357643635104604840080355643294751644134521484375; - private static final double F64C8 = 0.76604444311897801345168090847437269985675811767578125; - private static final double F64S8 = 0.642787609686539251896419955301098525524139404296875; - private static final double F64C9 = 0.70710678118654757273731092936941422522068023681640625; - private static final double F64S9 = 0.707106781186547461715008466853760182857513427734375; - private static final double F64C10 = 0.64278760968653936291872241781675256788730621337890625; - private static final double F64S10 = 0.76604444311897801345168090847437269985675811767578125; - private static final double F64C11 = 0.57357643635104615942310601894860155880451202392578125; - private static final double F64S11 = 0.81915204428899179855960710483486764132976531982421875; - private static final double F64C12 = 0.50000000000000011102230246251565404236316680908203125; - private static final double F64S12 = 0.8660254037844385965883020617184229195117950439453125; - private static final double F64C13 = 0.422618261740699441286750470680999569594860076904296875; - private static final double F64S13 = 0.90630778703664993667388216636027209460735321044921875; - private static final double F64C14 = 0.342020143325668823930385542553267441689968109130859375; - private static final double F64S14 = 0.93969262078590831688273965482949279248714447021484375; - private static final double F64C15 = 0.25881904510252073947640383266843855381011962890625; - private static final double F64S15 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F64C16 = 0.17364817766693041445336120887077413499355316162109375; - private static final double F64S16 = 0.98480775301220802031565426659653894603252410888671875; - private static final double F64C17 = 0.087155742747658138114275061525404453277587890625; - private static final double F64S17 = 0.9961946980917455451987052583717741072177886962890625; - private static final double F64C18 = 0.0000000000000000612323399573676603586882014729198302312846062338790031898128063403419218957424163818359375; - private static final double F64S18 = 1; - private static final double F64C19 = -0.08715574274765823525878971622660174034535884857177734375; - private static final double F64S19 = 0.9961946980917455451987052583717741072177886962890625; - private static final double F64C20 = -0.1736481776669303034310587463551200926303863525390625; - private static final double F64S20 = 0.98480775301220802031565426659653894603252410888671875; - private static final double F64C21 = -0.25881904510252085049870629518409259617328643798828125; - private static final double F64S21 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F64C22 = -0.342020143325668712908083080037613399326801300048828125; - private static final double F64S22 = 0.939692620785908427905042117345146834850311279296875; - private static final double F64C23 = -0.422618261740699330264448008165345527231693267822265625; - private static final double F64S23 = 0.90630778703665004769618462887592613697052001953125; - private static final double F64C24 = -0.4999999999999997779553950749686919152736663818359375; - private static final double F64S24 = 0.86602540378443870761060452423407696187496185302734375; - private static final double F64C25 = -0.57357643635104615942310601894860155880451202392578125; - private static final double F64S25 = 0.8191520442889916875373046423192135989665985107421875; - private static final double F64C26 = -0.64278760968653936291872241781675256788730621337890625; - private static final double F64S26 = 0.76604444311897801345168090847437269985675811767578125; - private static final double F64C27 = -0.707106781186547461715008466853760182857513427734375; - private static final double F64S27 = 0.70710678118654757273731092936941422522068023681640625; - private static final double F64C28 = -0.76604444311897790242937844595871865749359130859375; - private static final double F64S28 = 0.6427876096865394739410248803324066102504730224609375; - private static final double F64C29 = -0.81915204428899190958190956735052168369293212890625; - private static final double F64S29 = 0.57357643635104593737850109391729347407817840576171875; - private static final double F64C30 = -0.86602540378443870761060452423407696187496185302734375; - private static final double F64S30 = 0.499999999999999944488848768742172978818416595458984375; - private static final double F64C31 = -0.90630778703664993667388216636027209460735321044921875; - private static final double F64S31 = 0.4226182617406994967979017019388265907764434814453125; - private static final double F64C32 = -0.93969262078590831688273965482949279248714447021484375; - private static final double F64S32 = 0.342020143325668879441536773811094462871551513671875; - private static final double F64C33 = -0.965925826289068201191412299522198736667633056640625; - private static final double F64S33 = 0.258819045102521017032159988957573659718036651611328125; - private static final double F64C34 = -0.98480775301220802031565426659653894603252410888671875; - private static final double F64S34 = 0.1736481776669302756754831307262065820395946502685546875; - private static final double F64C35 = -0.9961946980917455451987052583717741072177886962890625; - private static final double F64S35 = 0.087155742747658193625426292783231474459171295166015625; - private static final double F64C36 = -1; - private static final double F64S36 = 0.000000000000000122464679914735320717376402945839660462569212467758006379625612680683843791484832763671875; - private static final double F64C37 = -0.9961946980917455451987052583717741072177886962890625; - private static final double F64S37 = -0.0871557427476579438252457521230098791420459747314453125; - private static final double F64C38 = -0.98480775301220802031565426659653894603252410888671875; - private static final double F64S38 = -0.173648177666930469964512440128601156175136566162109375; - private static final double F64C39 = -0.96592582628906831221371476203785277903079986572265625; - private static final double F64S39 = -0.258819045102520794987555063926265574991703033447265625; - private static final double F64C40 = -0.939692620785908427905042117345146834850311279296875; - private static final double F64S40 = -0.3420201433256686573969318487797863781452178955078125; - private static final double F64C41 = -0.90630778703665004769618462887592613697052001953125; - private static final double F64S41 = -0.42261826174069927475329677690751850605010986328125; - private static final double F64C42 = -0.8660254037844385965883020617184229195117950439453125; - private static final double F64S42 = -0.50000000000000011102230246251565404236316680908203125; - private static final double F64C43 = -0.81915204428899179855960710483486764132976531982421875; - private static final double F64S43 = -0.57357643635104615942310601894860155880451202392578125; - private static final double F64C44 = -0.76604444311897801345168090847437269985675811767578125; - private static final double F64S44 = -0.642787609686539251896419955301098525524139404296875; - private static final double F64C45 = -0.7071067811865476837596133918850682675838470458984375; - private static final double F64S45 = -0.707106781186547461715008466853760182857513427734375; - private static final double F64C46 = -0.6427876096865394739410248803324066102504730224609375; - private static final double F64S46 = -0.76604444311897790242937844595871865749359130859375; - private static final double F64C47 = -0.57357643635104638146771094397990964353084564208984375; - private static final double F64S47 = -0.81915204428899157651500217980355955660343170166015625; - private static final double F64C48 = -0.500000000000000444089209850062616169452667236328125; - private static final double F64S48 = -0.86602540378443837454369713668711483478546142578125; - private static final double F64C49 = -0.42261826174069916373099431439186446368694305419921875; - private static final double F64S49 = -0.90630778703665004769618462887592613697052001953125; - private static final double F64C50 = -0.34202014332566854637462938626413233578205108642578125; - private static final double F64S50 = -0.939692620785908427905042117345146834850311279296875; - private static final double F64C51 = -0.25881904510252062845410137015278451144695281982421875; - private static final double F64S51 = -0.96592582628906831221371476203785277903079986572265625; - private static final double F64C52 = -0.1736481776669303311866343619840336032211780548095703125; - private static final double F64S52 = -0.98480775301220802031565426659653894603252410888671875; - private static final double F64C53 = -0.08715574274765824913657752404105849564075469970703125; - private static final double F64S53 = -0.9961946980917455451987052583717741072177886962890625; - private static final double F64C54 = -0.00000000000000018369701987210296875011296034045003113559498615810217092558787044254131615161895751953125; - private static final double F64S54 = -1; - private static final double F64C55 = 0.0871557427476578883140945208651828579604625701904296875; - private static final double F64S55 = -0.9961946980917455451987052583717741072177886962890625; - private static final double F64C56 = 0.17364817766692997036415135880815796554088592529296875; - private static final double F64S56 = -0.98480775301220813133795672911219298839569091796875; - private static final double F64C57 = 0.258819045102520295387193982605822384357452392578125; - private static final double F64S57 = -0.9659258262890684232360172245535068213939666748046875; - private static final double F64C58 = 0.34202014332566899046383923632674850523471832275390625; - private static final double F64S58 = -0.93969262078590831688273965482949279248714447021484375; - private static final double F64C59 = 0.42261826174069960782020416445448063313961029052734375; - private static final double F64S59 = -0.90630778703664993667388216636027209460735321044921875; - private static final double F64C60 = 0.50000000000000011102230246251565404236316680908203125; - private static final double F64S60 = -0.8660254037844385965883020617184229195117950439453125; - private static final double F64C61 = 0.57357643635104604840080355643294751644134521484375; - private static final double F64S61 = -0.81915204428899179855960710483486764132976531982421875; - private static final double F64C62 = 0.642787609686539251896419955301098525524139404296875; - private static final double F64S62 = -0.7660444431189781244739833709900267422199249267578125; - private static final double F64C63 = 0.70710678118654735069270600433810614049434661865234375; - private static final double F64S63 = -0.7071067811865476837596133918850682675838470458984375; - private static final double F64C64 = 0.76604444311897779140707598344306461513042449951171875; - private static final double F64S64 = -0.64278760968653958496332734284806065261363983154296875; - private static final double F64C65 = 0.81915204428899157651500217980355955660343170166015625; - private static final double F64S65 = -0.573576436351046492490013406495563685894012451171875; - private static final double F64C66 = 0.86602540378443837454369713668711483478546142578125; - private static final double F64S66 = -0.500000000000000444089209850062616169452667236328125; - private static final double F64C67 = 0.90630778703665004769618462887592613697052001953125; - private static final double F64S67 = -0.422618261740699219242145545649691484868526458740234375; - private static final double F64C68 = 0.939692620785908427905042117345146834850311279296875; - private static final double F64S68 = -0.342020143325668601885780617521959356963634490966796875; - private static final double F64C69 = 0.96592582628906831221371476203785277903079986572265625; - private static final double F64S69 = -0.258819045102520683965252601410611532628536224365234375; - private static final double F64C70 = 0.98480775301220802031565426659653894603252410888671875; - private static final double F64S70 = -0.1736481776669303866977855932418606244027614593505859375; - private static final double F64C71 = 0.9961946980917455451987052583717741072177886962890625; - private static final double F64S71 = -0.08715574274765831852551656311334227211773395538330078125; - - private static double sc64(int x, int z, double r, NoiseProvider n) { - return (n.noise(x + ((r * F64C0) - (r * F64S0)), z + ((r * F64S0) + (r * F64C0))) - + n.noise(x + ((r * F64C1) - (r * F64S1)), z + ((r * F64S1) + (r * F64C1))) - + n.noise(x + ((r * F64C2) - (r * F64S2)), z + ((r * F64S2) + (r * F64C2))) - + n.noise(x + ((r * F64C3) - (r * F64S3)), z + ((r * F64S3) + (r * F64C3))) - + n.noise(x + ((r * F64C4) - (r * F64S4)), z + ((r * F64S4) + (r * F64C4))) - + n.noise(x + ((r * F64C5) - (r * F64S5)), z + ((r * F64S5) + (r * F64C5))) - + n.noise(x + ((r * F64C6) - (r * F64S6)), z + ((r * F64S6) + (r * F64C6))) - + n.noise(x + ((r * F64C7) - (r * F64S7)), z + ((r * F64S7) + (r * F64C7))) - + n.noise(x + ((r * F64C8) - (r * F64S8)), z + ((r * F64S8) + (r * F64C8))) - + n.noise(x + ((r * F64C9) - (r * F64S9)), z + ((r * F64S9) + (r * F64C9))) - + n.noise(x + ((r * F64C10) - (r * F64S10)), z + ((r * F64S10) + (r * F64C10))) - + n.noise(x + ((r * F64C11) - (r * F64S11)), z + ((r * F64S11) + (r * F64C11))) - + n.noise(x + ((r * F64C12) - (r * F64S12)), z + ((r * F64S12) + (r * F64C12))) - + n.noise(x + ((r * F64C13) - (r * F64S13)), z + ((r * F64S13) + (r * F64C13))) - + n.noise(x + ((r * F64C14) - (r * F64S14)), z + ((r * F64S14) + (r * F64C14))) - + n.noise(x + ((r * F64C15) - (r * F64S15)), z + ((r * F64S15) + (r * F64C15))) - + n.noise(x + ((r * F64C16) - (r * F64S16)), z + ((r * F64S16) + (r * F64C16))) - + n.noise(x + ((r * F64C17) - (r * F64S17)), z + ((r * F64S17) + (r * F64C17))) - + n.noise(x + ((r * F64C18) - (r * F64S18)), z + ((r * F64S18) + (r * F64C18))) - + n.noise(x + ((r * F64C19) - (r * F64S19)), z + ((r * F64S19) + (r * F64C19))) - + n.noise(x + ((r * F64C20) - (r * F64S20)), z + ((r * F64S20) + (r * F64C20))) - + n.noise(x + ((r * F64C21) - (r * F64S21)), z + ((r * F64S21) + (r * F64C21))) - + n.noise(x + ((r * F64C22) - (r * F64S22)), z + ((r * F64S22) + (r * F64C22))) - + n.noise(x + ((r * F64C23) - (r * F64S23)), z + ((r * F64S23) + (r * F64C23))) - + n.noise(x + ((r * F64C24) - (r * F64S24)), z + ((r * F64S24) + (r * F64C24))) - + n.noise(x + ((r * F64C25) - (r * F64S25)), z + ((r * F64S25) + (r * F64C25))) - + n.noise(x + ((r * F64C26) - (r * F64S26)), z + ((r * F64S26) + (r * F64C26))) - + n.noise(x + ((r * F64C27) - (r * F64S27)), z + ((r * F64S27) + (r * F64C27))) - + n.noise(x + ((r * F64C28) - (r * F64S28)), z + ((r * F64S28) + (r * F64C28))) - + n.noise(x + ((r * F64C29) - (r * F64S29)), z + ((r * F64S29) + (r * F64C29))) - + n.noise(x + ((r * F64C30) - (r * F64S30)), z + ((r * F64S30) + (r * F64C30))) - + n.noise(x + ((r * F64C31) - (r * F64S31)), z + ((r * F64S31) + (r * F64C31))) - + n.noise(x + ((r * F64C32) - (r * F64S32)), z + ((r * F64S32) + (r * F64C32))) - + n.noise(x + ((r * F64C33) - (r * F64S33)), z + ((r * F64S33) + (r * F64C33))) - + n.noise(x + ((r * F64C34) - (r * F64S34)), z + ((r * F64S34) + (r * F64C34))) - + n.noise(x + ((r * F64C35) - (r * F64S35)), z + ((r * F64S35) + (r * F64C35))) - + n.noise(x + ((r * F64C36) - (r * F64S36)), z + ((r * F64S36) + (r * F64C36))) - + n.noise(x + ((r * F64C37) - (r * F64S37)), z + ((r * F64S37) + (r * F64C37))) - + n.noise(x + ((r * F64C38) - (r * F64S38)), z + ((r * F64S38) + (r * F64C38))) - + n.noise(x + ((r * F64C39) - (r * F64S39)), z + ((r * F64S39) + (r * F64C39))) - + n.noise(x + ((r * F64C40) - (r * F64S40)), z + ((r * F64S40) + (r * F64C40))) - + n.noise(x + ((r * F64C41) - (r * F64S41)), z + ((r * F64S41) + (r * F64C41))) - + n.noise(x + ((r * F64C42) - (r * F64S42)), z + ((r * F64S42) + (r * F64C42))) - + n.noise(x + ((r * F64C43) - (r * F64S43)), z + ((r * F64S43) + (r * F64C43))) - + n.noise(x + ((r * F64C44) - (r * F64S44)), z + ((r * F64S44) + (r * F64C44))) - + n.noise(x + ((r * F64C45) - (r * F64S45)), z + ((r * F64S45) + (r * F64C45))) - + n.noise(x + ((r * F64C46) - (r * F64S46)), z + ((r * F64S46) + (r * F64C46))) - + n.noise(x + ((r * F64C47) - (r * F64S47)), z + ((r * F64S47) + (r * F64C47))) - + n.noise(x + ((r * F64C48) - (r * F64S48)), z + ((r * F64S48) + (r * F64C48))) - + n.noise(x + ((r * F64C49) - (r * F64S49)), z + ((r * F64S49) + (r * F64C49))) - + n.noise(x + ((r * F64C50) - (r * F64S50)), z + ((r * F64S50) + (r * F64C50))) - + n.noise(x + ((r * F64C51) - (r * F64S51)), z + ((r * F64S51) + (r * F64C51))) - + n.noise(x + ((r * F64C52) - (r * F64S52)), z + ((r * F64S52) + (r * F64C52))) - + n.noise(x + ((r * F64C53) - (r * F64S53)), z + ((r * F64S53) + (r * F64C53))) - + n.noise(x + ((r * F64C54) - (r * F64S54)), z + ((r * F64S54) + (r * F64C54))) - + n.noise(x + ((r * F64C55) - (r * F64S55)), z + ((r * F64S55) + (r * F64C55))) - + n.noise(x + ((r * F64C56) - (r * F64S56)), z + ((r * F64S56) + (r * F64C56))) - + n.noise(x + ((r * F64C57) - (r * F64S57)), z + ((r * F64S57) + (r * F64C57))) - + n.noise(x + ((r * F64C58) - (r * F64S58)), z + ((r * F64S58) + (r * F64C58))) - + n.noise(x + ((r * F64C59) - (r * F64S59)), z + ((r * F64S59) + (r * F64C59))) - + n.noise(x + ((r * F64C60) - (r * F64S60)), z + ((r * F64S60) + (r * F64C60))) - + n.noise(x + ((r * F64C61) - (r * F64S61)), z + ((r * F64S61) + (r * F64C61))) - + n.noise(x + ((r * F64C62) - (r * F64S62)), z + ((r * F64S62) + (r * F64C62))) - + n.noise(x + ((r * F64C63) - (r * F64S63)), z + ((r * F64S63) + (r * F64C63))) - + n.noise(x + ((r * F64C64) - (r * F64S64)), z + ((r * F64S64) + (r * F64C64))) - + n.noise(x + ((r * F64C65) - (r * F64S65)), z + ((r * F64S65) + (r * F64C65))) - + n.noise(x + ((r * F64C66) - (r * F64S66)), z + ((r * F64S66) + (r * F64C66))) - + n.noise(x + ((r * F64C67) - (r * F64S67)), z + ((r * F64S67) + (r * F64C67))) - + n.noise(x + ((r * F64C68) - (r * F64S68)), z + ((r * F64S68) + (r * F64C68))) - + n.noise(x + ((r * F64C69) - (r * F64S69)), z + ((r * F64S69) + (r * F64C69))) - + n.noise(x + ((r * F64C70) - (r * F64S70)), z + ((r * F64S70) + (r * F64C70))) - + n.noise(x + ((r * F64C71) - (r * F64S71)), z + ((r * F64S71) + (r * F64C71)))) / 64.0D; - } -} diff --git a/src/main/java/com/volmit/iris/util/inventorygui/Element.java b/src/main/java/com/volmit/iris/util/inventorygui/Element.java deleted file mode 100644 index af0006ed5..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/Element.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.data.MaterialBlock; -import com.volmit.iris.util.scheduling.Callback; -import org.bukkit.inventory.ItemStack; - -@SuppressWarnings("ALL") -public interface Element { - MaterialBlock getMaterial(); - - Element setMaterial(MaterialBlock b); - - boolean isEnchanted(); - - Element setEnchanted(boolean enchanted); - - String getId(); - - String getName(); - - Element setName(String name); - - double getProgress(); - - Element setProgress(double progress); - - short getEffectiveDurability(); - - int getCount(); - - Element setCount(int c); - - ItemStack computeItemStack(); - - Element setBackground(boolean bg); - - boolean isBackgrond(); - - Element addLore(String loreLine); - - KList getLore(); - - Element call(ElementEvent event, Element context); - - Element onLeftClick(Callback clicked); - - Element onRightClick(Callback clicked); - - Element onShiftLeftClick(Callback clicked); - - Element onShiftRightClick(Callback clicked); - - Element onDraggedInto(Callback into); - - Element onOtherDraggedInto(Callback other); -} diff --git a/src/main/java/com/volmit/iris/util/inventorygui/ElementEvent.java b/src/main/java/com/volmit/iris/util/inventorygui/ElementEvent.java deleted file mode 100644 index 8c373938a..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/ElementEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -/** - * Element Event. - * - * @author cyberpwn - */ -public enum ElementEvent { - LEFT, - RIGHT, - SHIFT_LEFT, - SHIFT_RIGHT, - DRAG_INTO, - OTHER_DRAG_INTO -} diff --git a/src/main/java/com/volmit/iris/util/inventorygui/RandomColor.java b/src/main/java/com/volmit/iris/util/inventorygui/RandomColor.java deleted file mode 100644 index ac32bf375..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/RandomColor.java +++ /dev/null @@ -1,527 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Random; - -/** - * Credit to https://github.com/lzyzsd/AndroidRandomColor - */ -public class RandomColor { - - public static int hueOffset = 0; - private final Random random; - private final HashMap colors = new HashMap<>(); - - public RandomColor() { - loadColorBounds(); - random = new Random(); - } - - public RandomColor(long seed) { - loadColorBounds(); - random = new Random(); - random.setSeed(seed); - } - - public RandomColor(Random random) { - loadColorBounds(); - this.random = random; - } - - private int getColor(int hue, int saturation, int brightness) { - return java.awt.Color.getHSBColor((float) (hue + hueOffset % 360) / 360, (float) saturation / 100, (float) brightness / 100).getRGB(); - } - - public int randomColor() { - return randomColor(0, null, null); - } - - public int randomColor(int value, SaturationType saturationType, Luminosity luminosity) { - int hue = value; - hue = pickHue(hue); - int saturation = pickSaturation(hue, saturationType, luminosity); - int brightness = pickBrightness(hue, saturation, luminosity); - - return getColor(hue, saturation, brightness); - } - - public int randomColor(Color color, SaturationType saturationType, Luminosity luminosity) { - int hue = pickHue(color.name()); - int saturation = pickSaturation(hue, saturationType, luminosity); - int brightness = pickBrightness(hue, saturation, luminosity); - - return getColor(hue, saturation, brightness); - } - - public int[] randomColor(int count) { - if(count <= 0) { - throw new IllegalArgumentException("count must be greater than 0"); - } - - int[] colors = new int[count]; - for(int i = 0; i < count; i++) { - colors[i] = randomColor(); - } - - return colors; - } - - public int randomColor(Color color) { - int hue = pickHue(color.name()); - int saturation = pickSaturation(color, null, null); - int brightness = pickBrightness(color, saturation, null); - - int colorValue = getColor(hue, saturation, brightness); - return colorValue; - } - - public int[] random(Color color, int count) { - if(count <= 0) { - throw new IllegalArgumentException("count must be greater than 0"); - } - - int[] colors = new int[count]; - for(int i = 0; i < count; i++) { - colors[i] = randomColor(color); - } - - return colors; - } - - private int pickHue(int hue) { - Range hueRange = getHueRange(hue); - return doPickHue(hueRange); - } - - private int doPickHue(Range hueRange) { - int hue = randomWithin(hueRange); - - // Instead of storing red as two seperate ranges, - // we group them, using negative numbers - if(hue < 0) { - hue = 360 + hue; - } - - return hue; - } - - private int pickHue(String name) { - Range hueRange = getHueRange(name); - return doPickHue(hueRange); - } - - private Range getHueRange(int number) { - if(number < 360 && number > 0) { - return new Range(number, number); - } - - return new Range(0, 360); - } - - private Range getHueRange(String name) { - if(colors.containsKey(name)) { - return colors.get(name).getHueRange(); - } - - return new Range(0, 360); - } - - private int pickSaturation(int hue, SaturationType saturationType, Luminosity luminosity) { - return pickSaturation(getColorInfo(hue), saturationType, luminosity); - } - - private int pickSaturation(Color color, SaturationType saturationType, Luminosity luminosity) { - ColorInfo colorInfo = colors.get(color.name()); - return pickSaturation(colorInfo, saturationType, luminosity); - } - - private int pickSaturation(ColorInfo colorInfo, SaturationType saturationType, Luminosity luminosity) { - if(saturationType != null) { - switch(saturationType) { - case RANDOM: - return randomWithin(new Range(0, 100)); - case MONOCHROME: - return 0; - case HIGH: - return randomWithin(new Range(75, 100)); - case MEDIUM: - return randomWithin(new Range(55, 75)); - case LOW: - return randomWithin(new Range(35, 55)); - } - } - - if(colorInfo == null) { - return 0; - } - - Range saturationRange = colorInfo.getSaturationRange(); - - int min = saturationRange.start; - int max = saturationRange.end; - - if(luminosity != null) { - switch(luminosity) { - case LIGHT: - min = 55; - break; - case BRIGHT: - min = max - 10; - break; - case DARK: - max = 55; - break; - } - } - - return randomWithin(new Range(min, max)); - } - - private int pickBrightness(int hue, int saturation, Luminosity luminosity) { - ColorInfo colorInfo = getColorInfo(hue); - - return pickBrightness(colorInfo, saturation, luminosity); - } - - private int pickBrightness(Color color, int saturation, Luminosity luminosity) { - ColorInfo colorInfo = colors.get(color.name()); - - return pickBrightness(colorInfo, saturation, luminosity); - } - - private int pickBrightness(ColorInfo colorInfo, int saturation, Luminosity luminosity) { - int min = getMinimumBrightness(colorInfo, saturation), - max = 100; - - if(luminosity != null) { - switch(luminosity) { - - case DARK: - max = min + 20; - break; - - case LIGHT: - min = (max + min) / 2; - break; - - case RANDOM: - min = 0; - max = 100; - break; - } - } - - return randomWithin(new Range(min, max)); - } - - private int getMinimumBrightness(ColorInfo colorInfo, int saturation) { - if(colorInfo == null) { - return 0; - } - - List lowerBounds = colorInfo.getLowerBounds(); - for(int i = 0; i < lowerBounds.size() - 1; i++) { - - int s1 = lowerBounds.get(i).start, - v1 = lowerBounds.get(i).end; - - if(i == lowerBounds.size() - 1) { - break; - } - int s2 = lowerBounds.get(i + 1).start, - v2 = lowerBounds.get(i + 1).end; - - if(saturation >= s1 && saturation <= s2) { - - float m = (v2 - v1) / (float) (s2 - s1), - b = v1 - m * s1; - - return (int) (m * saturation + b); - } - - } - - return 0; - } - - private ColorInfo getColorInfo(int hue) { - // Maps red colors to make picking hue easier - if(hue >= 334 && hue <= 360) { - hue -= 360; - } - - for(String key : colors.keySet()) { - ColorInfo colorInfo = colors.get(key); - if(colorInfo.getHueRange() != null && colorInfo.getHueRange().contain(hue)) { - return colorInfo; - } - } - - return null; - } - - private int randomWithin(Range range) { - return (int) Math.floor(range.start + random.nextDouble() * (range.end + 1 - range.start)); - } - - public void defineColor(String name, Range hueRange, List lowerBounds) { - int sMin = lowerBounds.get(0).start; - int sMax = lowerBounds.get(lowerBounds.size() - 1).start; - int bMin = lowerBounds.get(lowerBounds.size() - 1).end; - int bMax = lowerBounds.get(0).end; - - colors.put(name, new ColorInfo(hueRange, new Range(sMin, sMax), new Range(bMin, bMax), lowerBounds)); - } - - private void loadColorBounds() { - List lowerBounds1 = new ArrayList<>(); - lowerBounds1.add(new Range(0, 0)); - lowerBounds1.add(new Range(100, 0)); - defineColor( - Color.MONOCHROME.name(), - new Range(0, 0), - lowerBounds1 - ); - - List lowerBounds2 = new ArrayList<>(); - lowerBounds2.add(new Range(20, 100)); - lowerBounds2.add(new Range(30, 92)); - lowerBounds2.add(new Range(40, 89)); - lowerBounds2.add(new Range(50, 85)); - lowerBounds2.add(new Range(60, 78)); - lowerBounds2.add(new Range(70, 70)); - lowerBounds2.add(new Range(80, 60)); - lowerBounds2.add(new Range(90, 55)); - lowerBounds2.add(new Range(100, 50)); - defineColor( - Color.RED.name(), - new Range(-26, 18), - lowerBounds2 - ); - - List lowerBounds3 = new ArrayList(); - lowerBounds3.add(new Range(20, 100)); - lowerBounds3.add(new Range(30, 93)); - lowerBounds3.add(new Range(40, 88)); - lowerBounds3.add(new Range(50, 86)); - lowerBounds3.add(new Range(60, 85)); - lowerBounds3.add(new Range(70, 70)); - lowerBounds3.add(new Range(100, 70)); - defineColor( - Color.ORANGE.name(), - new Range(19, 46), - lowerBounds3 - ); - - List lowerBounds4 = new ArrayList<>(); - lowerBounds4.add(new Range(25, 100)); - lowerBounds4.add(new Range(40, 94)); - lowerBounds4.add(new Range(50, 89)); - lowerBounds4.add(new Range(60, 86)); - lowerBounds4.add(new Range(70, 84)); - lowerBounds4.add(new Range(80, 82)); - lowerBounds4.add(new Range(90, 80)); - lowerBounds4.add(new Range(100, 75)); - - defineColor( - Color.YELLOW.name(), - new Range(47, 62), - lowerBounds4 - ); - - List lowerBounds5 = new ArrayList<>(); - lowerBounds5.add(new Range(30, 100)); - lowerBounds5.add(new Range(40, 90)); - lowerBounds5.add(new Range(50, 85)); - lowerBounds5.add(new Range(60, 81)); - lowerBounds5.add(new Range(70, 74)); - lowerBounds5.add(new Range(80, 64)); - lowerBounds5.add(new Range(90, 50)); - lowerBounds5.add(new Range(100, 40)); - - defineColor( - Color.GREEN.name(), - new Range(63, 178), - lowerBounds5 - ); - - List lowerBounds6 = new ArrayList<>(); - lowerBounds6.add(new Range(20, 100)); - lowerBounds6.add(new Range(30, 86)); - lowerBounds6.add(new Range(40, 80)); - lowerBounds6.add(new Range(50, 74)); - lowerBounds6.add(new Range(60, 60)); - lowerBounds6.add(new Range(70, 52)); - lowerBounds6.add(new Range(80, 44)); - lowerBounds6.add(new Range(90, 39)); - lowerBounds6.add(new Range(100, 35)); - - defineColor( - Color.BLUE.name(), - new Range(179, 257), - lowerBounds6 - ); - - List lowerBounds7 = new ArrayList<>(); - lowerBounds7.add(new Range(20, 100)); - lowerBounds7.add(new Range(30, 87)); - lowerBounds7.add(new Range(40, 79)); - lowerBounds7.add(new Range(50, 70)); - lowerBounds7.add(new Range(60, 65)); - lowerBounds7.add(new Range(70, 59)); - lowerBounds7.add(new Range(80, 52)); - lowerBounds7.add(new Range(90, 45)); - lowerBounds7.add(new Range(100, 42)); - - defineColor( - Color.PURPLE.name(), - new Range(258, 282), - lowerBounds7 - ); - - List lowerBounds8 = new ArrayList<>(); - lowerBounds8.add(new Range(20, 100)); - lowerBounds8.add(new Range(30, 90)); - lowerBounds8.add(new Range(40, 86)); - lowerBounds8.add(new Range(60, 84)); - lowerBounds8.add(new Range(80, 80)); - lowerBounds8.add(new Range(90, 75)); - lowerBounds8.add(new Range(100, 73)); - - defineColor( - Color.PINK.name(), - new Range(283, 334), - lowerBounds8 - ); - } - - public enum SaturationType { - RANDOM, MONOCHROME, HIGH, LOW, MEDIUM - } - - public enum Luminosity { - BRIGHT, LIGHT, DARK, RANDOM - } - - public enum Color { - MONOCHROME, RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE, PINK - } - - public static class ColorInfo { - Range hueRange; - Range saturationRange; - Range brightnessRange; - List lowerBounds; - - public ColorInfo(Range hueRange, Range saturationRange, Range brightnessRange, List lowerBounds) { - this.hueRange = hueRange; - this.saturationRange = saturationRange; - this.brightnessRange = brightnessRange; - this.lowerBounds = lowerBounds; - } - - public Range getHueRange() { - return hueRange; - } - - public void setHueRange(Range hueRange) { - this.hueRange = hueRange; - } - - public Range getSaturationRange() { - return saturationRange; - } - - public void setSaturationRange(Range saturationRange) { - this.saturationRange = saturationRange; - } - - public Range getBrightnessRange() { - return brightnessRange; - } - - public void setBrightnessRange(Range brightnessRange) { - this.brightnessRange = brightnessRange; - } - - public List getLowerBounds() { - return lowerBounds; - } - - public void setLowerBounds(List lowerBounds) { - this.lowerBounds = lowerBounds; - } - } - - public static class Range { - int start; - int end; - - public Range(int start, int end) { - this.start = start; - this.end = end; - } - - public boolean contain(int value) { - return value >= start && value <= end; - } - - @Override - public String toString() { - return "start: " + start + " end: " + end; - } - } - - public static class Options { - int hue; - SaturationType saturationType; - Luminosity luminosity; - - public int getHue() { - return hue; - } - - public void setHue(int hue) { - this.hue = hue; - } - - public SaturationType getSaturationType() { - return saturationType; - } - - public void setSaturationType(SaturationType saturationType) { - this.saturationType = saturationType; - } - - public Luminosity getLuminosity() { - return luminosity; - } - - public void setLuminosity(Luminosity luminosity) { - this.luminosity = luminosity; - } - } - -} - - diff --git a/src/main/java/com/volmit/iris/util/inventorygui/UIElement.java b/src/main/java/com/volmit/iris/util/inventorygui/UIElement.java deleted file mode 100644 index c6c89d2c5..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/UIElement.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.data.MaterialBlock; -import com.volmit.iris.util.scheduling.Callback; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -public class UIElement implements Element { - private final String id; - private final KList lore; - private MaterialBlock material; - private boolean enchanted; - private String name; - private double progress; - private boolean bg; - private Callback eLeft; - private Callback eRight; - private Callback eShiftLeft; - private Callback eShiftRight; - private Callback eDraggedInto; - private Callback eOtherDraggedInto; - private int count; - - public UIElement(String id) { - this.id = id; - lore = new KList<>(); - enchanted = false; - count = 1; - material = new MaterialBlock(Material.AIR); - } - - @Override - public MaterialBlock getMaterial() { - return material; - } - - @Override - public UIElement setMaterial(MaterialBlock material) { - this.material = material; - return this; - } - - public Double clip(double value, double min, double max) { - return Math.min(max, Math.max(min, value)); - } - - @Override - public boolean isEnchanted() { - return enchanted; - } - - @Override - public UIElement setEnchanted(boolean enchanted) { - this.enchanted = enchanted; - return this; - } - - @Override - public String getId() { - return id; - } - - @Override - public String getName() { - return name; - } - - @Override - public UIElement setName(String name) { - this.name = name; - return this; - } - - @Override - public KList getLore() { - return lore; - } - - @Override - public UIElement onLeftClick(Callback clicked) { - eLeft = clicked; - return this; - } - - @Override - public UIElement onRightClick(Callback clicked) { - eRight = clicked; - return this; - } - - @Override - public UIElement onShiftLeftClick(Callback clicked) { - eShiftLeft = clicked; - return this; - } - - @Override - public UIElement onShiftRightClick(Callback clicked) { - eShiftRight = clicked; - return this; - } - - @Override - public UIElement onDraggedInto(Callback into) { - eDraggedInto = into; - return this; - } - - @Override - public UIElement onOtherDraggedInto(Callback other) { - eOtherDraggedInto = other; - return this; - } - - @Override - public Element call(ElementEvent event, Element context) { - try { - switch(event) { - case DRAG_INTO -> { - eDraggedInto.run(context); - return this; - } - case LEFT -> { - eLeft.run(context); - return this; - } - case OTHER_DRAG_INTO -> { - eOtherDraggedInto.run(context); - return this; - } - case RIGHT -> { - eRight.run(context); - return this; - } - case SHIFT_LEFT -> { - eShiftLeft.run(context); - return this; - } - case SHIFT_RIGHT -> { - eShiftRight.run(context); - return this; - } - } - } catch(NullPointerException e) { - Iris.reportError(e); - - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return this; - } - - @Override - public Element addLore(String loreLine) { - getLore().add(loreLine); - return this; - } - - @Override - public Element setBackground(boolean bg) { - this.bg = bg; - return this; - } - - @Override - public boolean isBackgrond() { - return bg; - } - - @Override - public Element setCount(int c) { - count = clip(c, 1, 64).intValue(); - return this; - } - - @Override - public int getCount() { - return count; - } - - @SuppressWarnings("deprecation") - @Override - public ItemStack computeItemStack() { - try { - ItemStack is = new ItemStack(getMaterial().getMaterial(), getCount(), getEffectiveDurability()); - ItemMeta im = is.getItemMeta(); - im.setDisplayName(getName()); - im.setLore(getLore().copy()); - - if(isEnchanted()) { - im.addEnchant(Enchantment.DURABILITY, 1, true); - } - - is.setItemMeta(im); - return is; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return null; - } - - @Override - public Element setProgress(double progress) { - this.progress = clip(progress, 0D, 1D); - return this; - } - - @Override - public double getProgress() { - return progress; - } - - @Override - public short getEffectiveDurability() { - if(getMaterial().getMaterial().getMaxDurability() == 0) { - return 0; - } else { - int prog = (int) ((double) getMaterial().getMaterial().getMaxDurability() * (1D - getProgress())); - return clip(prog, 1, (getMaterial().getMaterial().getMaxDurability() - 1)).shortValue(); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/inventorygui/UIStaticDecorator.java b/src/main/java/com/volmit/iris/util/inventorygui/UIStaticDecorator.java deleted file mode 100644 index 8f10c8db3..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/UIStaticDecorator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -import com.volmit.iris.util.data.MaterialBlock; -import org.bukkit.Material; - -@SuppressWarnings("ClassCanBeRecord") -public class UIStaticDecorator implements WindowDecorator { - private final Element element; - - public UIStaticDecorator(Element element) { - this.element = element == null ? new UIElement("bg").setMaterial(new MaterialBlock(Material.AIR)) : element; - } - - @Override - public Element onDecorateBackground(Window window, int position, int row) { - return element; - } -} diff --git a/src/main/java/com/volmit/iris/util/inventorygui/UIVoidDecorator.java b/src/main/java/com/volmit/iris/util/inventorygui/UIVoidDecorator.java deleted file mode 100644 index 62d5ed317..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/UIVoidDecorator.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -public class UIVoidDecorator implements WindowDecorator { - @Override - public Element onDecorateBackground(Window window, int position, int row) { - return null; - } -} - diff --git a/src/main/java/com/volmit/iris/util/inventorygui/UIWindow.java b/src/main/java/com/volmit/iris/util/inventorygui/UIWindow.java deleted file mode 100644 index be3131902..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/UIWindow.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.scheduling.Callback; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -public class UIWindow implements Window, Listener { - private final Player viewer; - private final KMap elements; - private WindowDecorator decorator; - private Callback eClose; - private WindowResolution resolution; - private String title; - private boolean visible; - private int viewportPosition; - private int viewportSize; - private int highestRow; - private Inventory inventory; - private int clickcheck; - private boolean doubleclicked; - - public UIWindow(Player viewer) { - clickcheck = 0; - doubleclicked = false; - this.viewer = viewer; - this.elements = new KMap<>(); - setTitle(""); - setDecorator(new UIVoidDecorator()); - setResolution(WindowResolution.W9_H6); - setViewportHeight(clip(3, 1, getResolution().getMaxHeight()).intValue()); - setViewportPosition(0); - } - - @EventHandler - public void on(InventoryClickEvent e) { - if(!e.getWhoClicked().equals(viewer)) { - return; - } - - if(!isVisible()) { - return; - } - - // 1.14 bukkit api change, removed getTitle() and getName() from Inventory.class - if(!viewer.getOpenInventory().getTitle().equals(title)) { - return; - } - - if(e.getClickedInventory() == null) { - return; - } - - if(!e.getView().getType().equals(getResolution().getType())) { - return; - } - - if(e.getClickedInventory().getType().equals(getResolution().getType())) { - Element element = getElement(getLayoutPosition(e.getSlot()), getLayoutRow(e.getSlot())); - - switch(e.getAction()) { - case CLONE_STACK: - case UNKNOWN: - case SWAP_WITH_CURSOR: - case PLACE_SOME: - case PLACE_ONE: - case PLACE_ALL: - case PICKUP_SOME: - case PICKUP_ONE: - case PICKUP_HALF: - case PICKUP_ALL: - case NOTHING: - case MOVE_TO_OTHER_INVENTORY: - case HOTBAR_SWAP: - case HOTBAR_MOVE_AND_READD: - case DROP_ONE_SLOT: - case DROP_ONE_CURSOR: - case DROP_ALL_SLOT: - case DROP_ALL_CURSOR: - case COLLECT_TO_CURSOR: - break; - } - - switch(e.getClick()) { - case DOUBLE_CLICK: - doubleclicked = true; - break; - case LEFT: - - clickcheck++; - - if(clickcheck == 1) { - J.s(() -> - { - if(clickcheck == 1) { - clickcheck = 0; - - if(element != null) { - element.call(ElementEvent.LEFT, element); - } - } - }); - } else if(clickcheck == 2) { - J.s(() -> - { - if(doubleclicked) { - doubleclicked = false; - } else { - scroll(1); - } - - clickcheck = 0; - }); - } - - break; - case RIGHT: - if(element != null) { - element.call(ElementEvent.RIGHT, element); - } else { - scroll(-1); - } - break; - case SHIFT_LEFT: - if(element != null) { - element.call(ElementEvent.SHIFT_LEFT, element); - } - break; - case SHIFT_RIGHT: - if(element != null) { - element.call(ElementEvent.SHIFT_RIGHT, element); - } - break; - case SWAP_OFFHAND: - case UNKNOWN: - case WINDOW_BORDER_RIGHT: - case WINDOW_BORDER_LEFT: - case NUMBER_KEY: - case MIDDLE: - case DROP: - case CREATIVE: - case CONTROL_DROP: - default: - break; - } - } - - e.setCancelled(true); - - } - - @EventHandler - public void on(InventoryCloseEvent e) { - if(!e.getPlayer().equals(viewer)) { - return; - } - - if(!e.getPlayer().getOpenInventory().getTitle().equals(title)) { - return; - } - - if(isVisible()) { - close(); - callClosed(); - } - } - - @Override - public WindowDecorator getDecorator() { - return decorator; - } - - @Override - public UIWindow setDecorator(WindowDecorator decorator) { - this.decorator = decorator; - return this; - } - - @Override - public UIWindow close() { - setVisible(false); - return this; - } - - @Override - public UIWindow open() { - setVisible(true); - return this; - } - - @Override - public boolean isVisible() { - return visible; - } - - @Override - public UIWindow setVisible(boolean visible) { - if(isVisible() == visible) { - return this; - } - - if(visible) { - Bukkit.getPluginManager().registerEvents(this, Iris.instance); - - if(getResolution().getType().equals(InventoryType.CHEST)) { - inventory = Bukkit.createInventory(null, getViewportHeight() * 9, getTitle()); - } else { - inventory = Bukkit.createInventory(null, getResolution().getType(), getTitle()); - } - - viewer.openInventory(inventory); - this.visible = visible; - updateInventory(); - } else { - this.visible = visible; - HandlerList.unregisterAll(this); - viewer.closeInventory(); - } - - this.visible = visible; - return this; - } - - @Override - public int getViewportPosition() { - return viewportPosition; - } - - @Override - public UIWindow setViewportPosition(int viewportPosition) { - this.viewportPosition = viewportPosition; - scroll(0); - updateInventory(); - - return this; - } - - @Override - public int getMaxViewportPosition() { - return Math.max(0, highestRow - getViewportHeight()); - } - - @Override - public UIWindow scroll(int direction) { - viewportPosition = (int) clip(viewportPosition + direction, 0, getMaxViewportPosition()).doubleValue(); - updateInventory(); - - return this; - } - - @Override - public int getViewportHeight() { - return viewportSize; - } - - @Override - public UIWindow setViewportHeight(int height) { - viewportSize = (int) clip(height, 1, getResolution().getMaxHeight()).doubleValue(); - - if(isVisible()) { - reopen(); - } - - return this; - } - - @Override - public String getTitle() { - return title; - } - - @Override - public UIWindow setTitle(String title) { - this.title = title; - - if(isVisible()) { - reopen(); - } - - return this; - } - - @Override - public UIWindow setElement(int position, int row, Element e) { - if(row > highestRow) { - highestRow = row; - } - - elements.put(getRealPosition((int) clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset()).doubleValue(), row), e); - updateInventory(); - return this; - } - - @Override - public Element getElement(int position, int row) { - return elements.get(getRealPosition((int) clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset()).doubleValue(), row)); - } - - @Override - public Player getViewer() { - return viewer; - } - - @Override - public UIWindow onClosed(Callback window) { - eClose = window; - return this; - } - - @Override - public int getViewportSlots() { - return getViewportHeight() * getResolution().getWidth(); - } - - @Override - public int getLayoutRow(int viewportSlottedPosition) { - return getRow(getRealLayoutPosition(viewportSlottedPosition)); - } - - @Override - public int getLayoutPosition(int viewportSlottedPosition) { - return getPosition(viewportSlottedPosition); - } - - @Override - public int getRealLayoutPosition(int viewportSlottedPosition) { - return getRealPosition(getPosition(viewportSlottedPosition), getRow(viewportSlottedPosition) + getViewportPosition()); - } - - @Override - public int getRealPosition(int position, int row) { - return (int) (((row * getResolution().getWidth()) + getResolution().getMaxWidthOffset()) + clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset())); - } - - @Override - public int getRow(int realPosition) { - return realPosition / getResolution().getWidth(); - } - - @Override - public int getPosition(int realPosition) { - return (realPosition % getResolution().getWidth()) - getResolution().getMaxWidthOffset(); - } - - @Override - public Window callClosed() { - if(eClose != null) { - eClose.run(this); - } - - return this; - } - - @Override - public boolean hasElement(int position, int row) { - return getElement(position, row) != null; - } - - @Override - public WindowResolution getResolution() { - return resolution; - } - - public Double clip(double value, double min, double max) { - return Math.min(max, Math.max(min, value)); - } - - @Override - public Window setResolution(WindowResolution resolution) { - close(); - this.resolution = resolution; - setViewportHeight((int) clip(getViewportHeight(), 1, getResolution().getMaxHeight()).doubleValue()); - return this; - } - - @Override - public Window clearElements() { - highestRow = 0; - elements.clear(); - updateInventory(); - return this; - } - - @Override - public Window updateInventory() { - if(isVisible()) { - ItemStack[] is = inventory.getContents(); - @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") KSet isf = new KSet<>(); - - for(int i = 0; i < is.length; i++) { - ItemStack isc = is[i]; - ItemStack isx = computeItemStack(i); - int layoutRow = getLayoutRow(i); - int layoutPosition = getLayoutPosition(i); - - if(isx != null && !hasElement(layoutPosition, layoutRow)) { - ItemStack gg = isx.clone(); - gg.setAmount(gg.getAmount() + 1); - isf.add(gg); - } - - if(((isc == null) != (isx == null)) || isx != null && isc != null && !isc.equals(isx)) { - inventory.setItem(i, isx); - } - } - } - - return this; - } - - @Override - public ItemStack computeItemStack(int viewportSlot) { - int layoutRow = getLayoutRow(viewportSlot); - int layoutPosition = getLayoutPosition(viewportSlot); - Element e = hasElement(layoutPosition, layoutRow) ? getElement(layoutPosition, layoutRow) : getDecorator().onDecorateBackground(this, layoutPosition, layoutRow); - - if(e != null) { - return e.computeItemStack(); - } - - return null; - } - - @Override - public Window reopen() { - return this.close().open(); - } -} diff --git a/src/main/java/com/volmit/iris/util/inventorygui/Window.java b/src/main/java/com/volmit/iris/util/inventorygui/Window.java deleted file mode 100644 index e2ee91ac6..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/Window.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -import com.volmit.iris.util.scheduling.Callback; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -public interface Window { - WindowDecorator getDecorator(); - - Window setDecorator(WindowDecorator decorator); - - WindowResolution getResolution(); - - Window setResolution(WindowResolution resolution); - - Window clearElements(); - - Window close(); - - Window open(); - - Window callClosed(); - - Window updateInventory(); - - ItemStack computeItemStack(int viewportSlot); - - int getLayoutRow(int viewportSlottedPosition); - - int getLayoutPosition(int viewportSlottedPosition); - - int getRealLayoutPosition(int viewportSlottedPosition); - - int getRealPosition(int position, int row); - - int getRow(int realPosition); - - int getPosition(int realPosition); - - boolean isVisible(); - - Window setVisible(boolean visible); - - int getViewportPosition(); - - Window setViewportPosition(int position); - - int getViewportSlots(); - - int getMaxViewportPosition(); - - Window scroll(int direction); - - int getViewportHeight(); - - Window setViewportHeight(int height); - - String getTitle(); - - Window setTitle(String title); - - boolean hasElement(int position, int row); - - Window setElement(int position, int row, Element e); - - Element getElement(int position, int row); - - Player getViewer(); - - Window reopen(); - - Window onClosed(Callback window); -} diff --git a/src/main/java/com/volmit/iris/util/inventorygui/WindowDecorator.java b/src/main/java/com/volmit/iris/util/inventorygui/WindowDecorator.java deleted file mode 100644 index c0ec1006d..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/WindowDecorator.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -public interface WindowDecorator { - Element onDecorateBackground(Window window, int position, int row); -} diff --git a/src/main/java/com/volmit/iris/util/inventorygui/WindowResolution.java b/src/main/java/com/volmit/iris/util/inventorygui/WindowResolution.java deleted file mode 100644 index 01c8c3d6b..000000000 --- a/src/main/java/com/volmit/iris/util/inventorygui/WindowResolution.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.inventorygui; - -import org.bukkit.event.inventory.InventoryType; - -public enum WindowResolution { - W9_H6(9, 6, InventoryType.CHEST), - W5_H1(5, 1, InventoryType.HOPPER), - W3_H3(3, 3, InventoryType.DROPPER); - - private final int width; - private final int maxHeight; - private final InventoryType type; - - WindowResolution(int w, int h, InventoryType type) { - this.width = w; - this.maxHeight = h; - this.type = type; - } - - public int getMaxWidthOffset() { - return (getWidth() - 1) / 2; - } - - public int getWidth() { - return width; - } - - public int getMaxHeight() { - return maxHeight; - } - - public InventoryType getType() { - return type; - } -} diff --git a/src/main/java/com/volmit/iris/util/io/Converter.java b/src/main/java/com/volmit/iris/util/io/Converter.java deleted file mode 100644 index 01e326a44..000000000 --- a/src/main/java/com/volmit/iris/util/io/Converter.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import java.io.File; - -public interface Converter { - String getInExtension(); - - @SuppressWarnings("SameReturnValue") - String getOutExtension(); - - void convert(File in, File out); -} diff --git a/src/main/java/com/volmit/iris/util/io/CustomOutputStream.java b/src/main/java/com/volmit/iris/util/io/CustomOutputStream.java deleted file mode 100644 index b1cb2a268..000000000 --- a/src/main/java/com/volmit/iris/util/io/CustomOutputStream.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.zip.GZIPOutputStream; - -public class CustomOutputStream extends GZIPOutputStream { - public CustomOutputStream(OutputStream out, int level) throws IOException { - super(out); - def.setLevel(level); - } -} diff --git a/src/main/java/com/volmit/iris/util/io/FileWatcher.java b/src/main/java/com/volmit/iris/util/io/FileWatcher.java deleted file mode 100644 index 91b719c18..000000000 --- a/src/main/java/com/volmit/iris/util/io/FileWatcher.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import java.io.File; - -public class FileWatcher { - protected final File file; - private long lastModified; - private long size; - - public FileWatcher(File file) { - this.file = file; - readProperties(); - } - - protected void readProperties() { - boolean exists = file.exists(); - lastModified = exists ? file.lastModified() : -1; - size = exists ? file.isDirectory() ? -2 : file.length() : -1; - } - - public boolean checkModified() { - long m = lastModified; - long g = size; - boolean mod = false; - readProperties(); - - if(lastModified != m || g != size) { - mod = true; - } - - return mod; - } -} diff --git a/src/main/java/com/volmit/iris/util/io/FolderWatcher.java b/src/main/java/com/volmit/iris/util/io/FolderWatcher.java deleted file mode 100644 index 2c0a2f98a..000000000 --- a/src/main/java/com/volmit/iris/util/io/FolderWatcher.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; - -import java.io.File; - -public class FolderWatcher extends FileWatcher { - private KMap watchers; - private KList changed; - private KList created; - private KList deleted; - - public FolderWatcher(File file) { - super(file); - } - - protected void readProperties() { - if(watchers == null) { - watchers = new KMap<>(); - changed = new KList<>(); - created = new KList<>(); - deleted = new KList<>(); - } - - if(file.isDirectory()) { - for(File i : file.listFiles()) { - if(!watchers.containsKey(i)) { - watchers.put(i, new FolderWatcher(i)); - } - } - - for(File i : watchers.k()) { - if(!i.exists()) { - watchers.remove(i); - } - } - } else { - super.readProperties(); - } - } - - public boolean checkModified() { - changed.clear(); - created.clear(); - deleted.clear(); - - if(file.isDirectory()) { - KMap w = watchers.copy(); - readProperties(); - - for(File i : w.keySet()) { - if(!watchers.containsKey(i)) { - deleted.add(i); - } - } - - for(File i : watchers.keySet()) { - if(!w.containsKey(i)) { - created.add(i); - } else { - FolderWatcher fw = watchers.get(i); - if(fw.checkModified()) { - changed.add(fw.file); - } - - changed.addAll(fw.getChanged()); - created.addAll(fw.getCreated()); - deleted.addAll(fw.getDeleted()); - } - } - - return !changed.isEmpty() || !created.isEmpty() || !deleted.isEmpty(); - } - - return super.checkModified(); - } - - public boolean checkModifiedFast() { - if(watchers == null || watchers.isEmpty()) { - return checkModified(); - } - - changed.clear(); - created.clear(); - deleted.clear(); - - if(file.isDirectory()) { - for(File i : watchers.keySet()) { - FolderWatcher fw = watchers.get(i); - if(fw.checkModifiedFast()) { - changed.add(fw.file); - } - - changed.addAll(fw.getChanged()); - created.addAll(fw.getCreated()); - deleted.addAll(fw.getDeleted()); - } - - return !changed.isEmpty() || !created.isEmpty() || !deleted.isEmpty(); - } - - return super.checkModified(); - } - - public KMap getWatchers() { - return watchers; - } - - public KList getChanged() { - return changed; - } - - public KList getCreated() { - return created; - } - - public KList getDeleted() { - return deleted; - } - - public void clear() { - watchers.clear(); - changed.clear(); - deleted.clear(); - created.clear(); - } -} diff --git a/src/main/java/com/volmit/iris/util/io/IO.java b/src/main/java/com/volmit/iris/util/io/IO.java deleted file mode 100644 index 4b4728f72..000000000 --- a/src/main/java/com/volmit/iris/util/io/IO.java +++ /dev/null @@ -1,1786 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.format.Form; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.CharArrayWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.nio.charset.StandardCharsets; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.function.Consumer; -import java.util.zip.GZIPInputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -@SuppressWarnings("ALL") -public class IO { - /** - * The Unix directory separator character. - */ - public static final char DIR_SEPARATOR_UNIX = '/'; - /** - * The Windows directory separator character. - */ - public static final char DIR_SEPARATOR_WINDOWS = '\\'; - /** - * The system directory separator character. - */ - public static final char DIR_SEPARATOR = File.separatorChar; - /** - * The Unix line separator string. - */ - public static final String LINE_SEPARATOR_UNIX = "\n"; - /** - * The Windows line separator string. - */ - public static final String LINE_SEPARATOR_WINDOWS = "\r\n"; - /** - * The system line separator string. - */ - public static final String LINE_SEPARATOR; - - /** - * The default buffer size to use. - */ - private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; - private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); - - static { - // avoid security issues - StringWriter buf = new StringWriter(4); - PrintWriter out = new PrintWriter(buf); - out.println(); - LINE_SEPARATOR = buf.toString(); - } - - public static String decompress(String gz) throws IOException { - ByteArrayInputStream bin = new ByteArrayInputStream(Base64.getUrlDecoder().decode(gz)); - GZIPInputStream gzi = new GZIPInputStream(bin); - ByteArrayOutputStream boas = new ByteArrayOutputStream(); - IO.fullTransfer(gzi, boas, 256); - gzi.close(); - - return boas.toString(); - } - - public static byte[] sdecompress(String compressed) throws IOException { - ByteArrayInputStream bin = new ByteArrayInputStream(Base64.getUrlDecoder().decode(compressed)); - GZIPInputStream gzi = new GZIPInputStream(bin); - ByteArrayOutputStream boas = new ByteArrayOutputStream(); - IO.fullTransfer(gzi, boas, 256); - gzi.close(); - - return boas.toByteArray(); - } - - public static String encode(byte[] data) { - return Base64.getUrlEncoder().encodeToString(data); - } - - public static byte[] decode(String u) { - return Base64.getUrlDecoder().decode(u); - } - - public static String hash(String b) { - try { - MessageDigest d = MessageDigest.getInstance("SHA-256"); - return bytesToHex(d.digest(b.getBytes(StandardCharsets.UTF_8))); - } catch(NoSuchAlgorithmException e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return "¯\\_(ツ)_/¯"; - } - - public static String hash(File b) { - try { - MessageDigest d = MessageDigest.getInstance("SHA-256"); - DigestInputStream din = new DigestInputStream(new FileInputStream(b), d); - fullTransfer(din, new VoidOutputStream(), 8192); - din.close(); - return bytesToHex(din.getMessageDigest().digest()); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return "¯\\_(ツ)_/¯"; - } - - public static String bytesToHex(byte[] bytes) { - char[] hexChars = new char[bytes.length * 2]; - for(int j = 0; j < bytes.length; j++) { - int v = bytes[j] & 0xFF; - hexChars[j * 2] = hexArray[v >>> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; - } - - return new String(hexChars).toUpperCase(); - } - - public static String print(byte[] bytes) { - return Form.memSize(bytes.length, 2) + "[" + bytesToHex(bytes) + "]"; - } - - public static String longsToHex(long[] bytes) { - byte[] v = new byte[bytes.length * 8]; - - for(int i = 0; i < bytes.length; i++) { - v[i * 8] = (byte) (bytes[i] >>> 56); - v[(i * 8) + 1] = (byte) (bytes[i] >>> 48); - v[(i * 8) + 2] = (byte) (bytes[i] >>> 40); - v[(i * 8) + 3] = (byte) (bytes[i] >>> 32); - v[(i * 8) + 4] = (byte) (bytes[i] >>> 24); - v[(i * 8) + 5] = (byte) (bytes[i] >>> 16); - v[(i * 8) + 6] = (byte) (bytes[i] >>> 8); - v[(i * 8) + 7] = (byte) (bytes[i] >>> 0); - } - - return bytesToHex(v); - } - - /** - * Transfers the length of the buffer amount of data from the input stream to - * the output stream - * - * @param in - * the input - * @param out - * the output - * @return the actual transfered amount - * @throws IOException - * shit happens - */ - public static int transfer(InputStream in, OutputStream out, byte[] buffer) throws IOException { - int r = in.read(buffer); - - if(r != -1) { - out.write(buffer, 0, r); - } - - return r; - } - - /** - * Transfers the length of the buffer amount of data from the input stream to - * the output stream - * - * @param in - * the input - * @param out - * the output - * @param targetBuffer - * the buffer and size to use - * @param totalSize - * the total amount to transfer - * @return the actual transfered amount - * @throws IOException - * shit happens - */ - public static long transfer(InputStream in, OutputStream out, int targetBuffer, long totalSize) throws IOException { - long total = totalSize; - long wrote = 0; - byte[] buf = new byte[targetBuffer]; - int r = 0; - - while((r = in.read(buf, 0, (int) (total < targetBuffer ? total : targetBuffer))) != -1) { - total -= r; - out.write(buf, 0, r); - wrote += r; - - if(total <= 0) { - break; - } - } - - return wrote; - } - - /** - * Fully move data from a finite inputstream to an output stream using a buffer - * size of 8192. This does NOT close streams. - * - * @return total size transfered - */ - public static long fillTransfer(InputStream in, OutputStream out) throws IOException { - return fullTransfer(in, out, 8192); - } - - public static void deleteUp(File f) { - if(f.exists()) { - f.delete(); - - if(f.getParentFile().list().length == 0) { - deleteUp(f.getParentFile()); - } - } - } - - /** - * Fully move data from a finite inputstream to an output stream using a given - * buffer size. This does NOT close streams. - * - * @param in - * the input stream to read from - * @param out - * the output stream to writeNodeData to - * @param bufferSize - * the target buffer size - * @return total size transfered - * @throws IOException - * shit happens - */ - public static long fullTransfer(InputStream in, OutputStream out, int bufferSize) throws IOException { - long wrote = 0; - byte[] buf = new byte[bufferSize]; - int r = 0; - - while((r = in.read(buf)) != -1) { - out.write(buf, 0, r); - wrote += r; - } - - return wrote; - } - - /** - * Recursive delete (deleting folders) - * - * @param f - * the file to delete (and subfiles if folder) - */ - public static void delete(File f) { - if(f == null || !f.exists()) { - return; - } - - if(f.isDirectory()) { - for(File i : f.listFiles()) { - delete(i); - } - } - - f.delete(); - } - - public static long size(File file) { - long s = 0; - - if(file.exists()) { - if(file.isDirectory()) { - for(File i : file.listFiles()) { - s += size(i); - } - } else { - s += file.length(); - } - } - - return s; - } - - public static long count(File file) { - long s = 0; - - if(file.exists()) { - if(file.isDirectory()) { - for(File i : file.listFiles()) { - s += count(i); - } - } else { - s++; - } - } - - return s; - } - - public static long transfer(InputStream in, OutputStream out, byte[] buf, int totalSize) throws IOException { - long total = totalSize; - long wrote = 0; - int r = 0; - - while((r = in.read(buf, 0, (int) (total < buf.length ? total : buf.length))) != -1) { - total -= r; - out.write(buf, 0, r); - wrote += r; - - if(total <= 0) { - break; - } - } - - return wrote; - } - - public static void readEntry(File zipfile, String entryname, Consumer v) throws IOException { - ZipFile file = new ZipFile(zipfile); - Throwable x = null; - - try { - Enumeration entries = file.entries(); - while(entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - - if(entryname.equals(entry.getName())) { - InputStream in = file.getInputStream(entry); - v.accept(in); - } - } - } catch(Exception ex) { - Iris.reportError(ex); - x = ex.getCause(); - } finally { - file.close(); - } - - if(x != null) { - throw new IOException("Failed to read zip entry, however it has been closed safely.", x); - } - } - - public static void writeAll(File f, Object c) throws IOException { - try { - f.getParentFile().mkdirs(); - } catch(Throwable ignored) { - - } - - PrintWriter pw = new PrintWriter(new FileWriter(f)); - pw.println(c.toString()); - pw.close(); - } - - public static void writeAll(File f, OutputStream c) throws IOException { - f.getParentFile().mkdirs(); - FileInputStream in = new FileInputStream(f); - IO.fullTransfer(in, c, 8192); - in.close(); - } - - public static String readAll(File f) throws IOException { - FileReader fr; - try { - fr = new FileReader(f); - } catch(IOException e) { - Iris.reportError(e); - throw e; - } - BufferedReader bu = new BufferedReader(fr); - StringBuilder c = new StringBuilder(); - String l = ""; - - while((l = bu.readLine()) != null) { - c.append(l).append("\n"); - } - - bu.close(); - - return c.toString(); - } - - public static String readAll(InputStream in) throws IOException { - BufferedReader bu = new BufferedReader(new InputStreamReader(in)); - StringBuilder c = new StringBuilder(); - String l = ""; - - while((l = bu.readLine()) != null) { - c.append(l).append("\n"); - } - - bu.close(); - - return c.toString(); - } - - /** - * Implements the same behaviour as the "touch" utility on Unix. It creates a - * new file with size 0 or, if the file exists already, it is opened and closed - * without modifying it, but updating the file date and time. - * - * @param file - * the File to touch - * @throws IOException - * If an I/O problem occurs - */ - public static void touch(File file) throws IOException { - if(!file.exists()) { - OutputStream out = new FileOutputStream(file); - out.close(); - } - file.setLastModified(System.currentTimeMillis()); - } - - /** - * Copies a file to a new location preserving the file date. - *

- * This method copies the contents of the specified source file to the specified - * destination file. The directory holding the destination file is created if it - * does not exist. If the destination file exists, then this method will - * overwrite it. - * - * @param srcFile - * an existing file to copy, must not be null - * @param destFile - * the new file, must not be null - * @throws NullPointerException - * if source or destination is null - * @throws IOException - * if source or destination is invalid - * @throws IOException - * if an IO error occurs during copying - */ - public static void copyFile(File srcFile, File destFile) throws IOException { - copyFile(srcFile, destFile, true); - } - - /** - * Copies a file to a new location. - *

- * This method copies the contents of the specified source file to the specified - * destination file. The directory holding the destination file is created if it - * does not exist. If the destination file exists, then this method will - * overwrite it. - * - * @param srcFile - * an existing file to copy, must not be null - * @param destFile - * the new file, must not be null - * @param preserveFileDate - * true if the file date of the copy should be the same as the - * original - * @throws NullPointerException - * if source or destination is null - * @throws IOException - * if source or destination is invalid - * @throws IOException - * if an IO error occurs during copying - */ - public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { - if(srcFile == null) { - throw new NullPointerException("Source must not be null"); - } - if(destFile == null) { - throw new NullPointerException("Destination must not be null"); - } - if(!srcFile.exists()) { - throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); - } - if(srcFile.isDirectory()) { - throw new IOException("Source '" + srcFile + "' exists but is a directory"); - } - if(srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) { - throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); - } - if(destFile.getParentFile() != null && !destFile.getParentFile().exists()) { - if(!destFile.getParentFile().mkdirs()) { - throw new IOException("Destination '" + destFile + "' directory cannot be created"); - } - } - if(destFile.exists() && !destFile.canWrite()) { - throw new IOException("Destination '" + destFile + "' exists but is read-only"); - } - doCopyFile(srcFile, destFile, preserveFileDate); - } - - // ----------------------------------------------------------------------- - - /** - * Internal copy file method. - * - * @param srcFile - * the validated source file, not null - * @param destFile - * the validated destination file, not null - * @param preserveFileDate - * whether to preserve the file date - * @throws IOException - * if an error occurs - */ - private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { - if(destFile.exists() && destFile.isDirectory()) { - throw new IOException("Destination '" + destFile + "' exists but is a directory"); - } - - FileInputStream input = new FileInputStream(srcFile); - try { - FileOutputStream output = new FileOutputStream(destFile); - try { - IO.copy(input, output); - } finally { - output.close(); - } - } finally { - input.close(); - } - - if(srcFile.length() != destFile.length()) { - throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); - } - if(preserveFileDate) { - destFile.setLastModified(srcFile.lastModified()); - } - } - - /** - * Unconditionally close an Reader. - *

- * Equivalent to {@link Reader#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - * - * @param input - * the Reader to close, may be null or already closed - */ - public static void closeQuietly(Reader input) { - try { - if(input != null) { - input.close(); - } - } catch(IOException e) { - Iris.reportError(e); - // ignore - } - } - - /** - * Unconditionally close a Writer. - *

- * Equivalent to {@link Writer#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - * - * @param output - * the Writer to close, may be null or already closed - */ - public static void closeQuietly(Writer output) { - try { - if(output != null) { - output.close(); - } - } catch(IOException e) { - Iris.reportError(e); - // ignore - } - } - - /** - * Unconditionally close an InputStream. - *

- * Equivalent to {@link InputStream#close()}, except any exceptions will be - * ignored. This is typically used in finally blocks. - * - * @param input - * the InputStream to close, may be null or already closed - */ - public static void closeQuietly(InputStream input) { - try { - if(input != null) { - input.close(); - } - } catch(IOException e) { - Iris.reportError(e); - // ignore - } - } - - // read toByteArray - // ----------------------------------------------------------------------- - - /** - * Unconditionally close an OutputStream. - *

- * Equivalent to {@link OutputStream#close()}, except any exceptions will be - * ignored. This is typically used in finally blocks. - * - * @param output - * the OutputStream to close, may be null or already closed - */ - public static void closeQuietly(OutputStream output) { - try { - if(output != null) { - output.close(); - } - } catch(IOException e) { - Iris.reportError(e); - // ignore - } - } - - /** - * Get the contents of an InputStream as a byte[]. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from - * @return the requested byte array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static byte[] toByteArray(InputStream input) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output); - return output.toByteArray(); - } - - /** - * Get the contents of a Reader as a byte[] using the - * default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @return the requested byte array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static byte[] toByteArray(Reader input) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output); - return output.toByteArray(); - } - - /** - * Get the contents of a Reader as a byte[] using the - * specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @param encoding - * the encoding to use, null means platform default - * @return the requested byte array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static byte[] toByteArray(Reader input, String encoding) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output, encoding); - return output.toByteArray(); - } - - // read char[] - // ----------------------------------------------------------------------- - - /** - * Get the contents of a String as a byte[] using the - * default character encoding of the platform. - *

- * This is the same as {@link String#getBytes()}. - * - * @param input - * the String to convert - * @return the requested byte array - * @deprecated Use {@link String#getBytes()} - */ - @Deprecated - public static byte[] toByteArray(String input) { - return input.getBytes(); - } - - /** - * Get the contents of an InputStream as a character array using - * the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is - * the InputStream to read from - * @return the requested character array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static char[] toCharArray(InputStream is) throws IOException { - CharArrayWriter output = new CharArrayWriter(); - copy(is, output); - return output.toCharArray(); - } - - /** - * Get the contents of an InputStream as a character array using - * the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is - * the InputStream to read from - * @param encoding - * the encoding to use, null means platform default - * @return the requested character array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static char[] toCharArray(InputStream is, String encoding) throws IOException { - CharArrayWriter output = new CharArrayWriter(); - copy(is, output, encoding); - return output.toCharArray(); - } - - // read toString - // ----------------------------------------------------------------------- - - /** - * Get the contents of a Reader as a character array. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @return the requested character array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static char[] toCharArray(Reader input) throws IOException { - CharArrayWriter sw = new CharArrayWriter(); - copy(input, sw); - return sw.toCharArray(); - } - - /** - * Get the contents of an InputStream as a String using the default - * character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static String toString(InputStream input) throws IOException { - StringWriter sw = new StringWriter(); - copy(input, sw); - return sw.toString(); - } - - /** - * Get the contents of an InputStream as a String using the - * specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from - * @param encoding - * the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static String toString(InputStream input, String encoding) throws IOException { - StringWriter sw = new StringWriter(); - copy(input, sw, encoding); - return sw.toString(); - } - - /** - * Get the contents of a Reader as a String. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static String toString(Reader input) throws IOException { - StringWriter sw = new StringWriter(); - copy(input, sw); - return sw.toString(); - } - - /** - * Get the contents of a byte[] as a String using the default - * character encoding of the platform. - * - * @param input - * the byte array to read from - * @return the requested String - * @deprecated Use {@link String#String(byte[])} - */ - @Deprecated - public static String toString(byte[] input) { - return new String(input); - } - - // readLines - // ----------------------------------------------------------------------- - - /** - * Get the contents of a byte[] as a String using the specified - * character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input - * the byte array to read from - * @param encoding - * the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs (never occurs) - * @deprecated Use {@link String#String(byte[], String)} - */ - @Deprecated - public static String toString(byte[] input, String encoding) throws IOException { - if(encoding == null) { - return new String(input); - } else { - return new String(input, encoding); - } - } - - /** - * Get the contents of an InputStream as a list of Strings, one - * entry per line, using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from, not null - * @return the list of Strings, never null - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static List readLines(InputStream input) throws IOException { - InputStreamReader reader = new InputStreamReader(input); - return readLines(reader); - } - - /** - * Get the contents of an InputStream as a list of Strings, one - * entry per line, using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from, not null - * @param encoding - * the encoding to use, null means platform default - * @return the list of Strings, never null - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static List readLines(InputStream input, String encoding) throws IOException { - if(encoding == null) { - return readLines(input); - } else { - InputStreamReader reader = new InputStreamReader(input, encoding); - return readLines(reader); - } - } - - // ----------------------------------------------------------------------- - - /** - * Get the contents of a Reader as a list of Strings, one entry per - * line. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from, not null - * @return the list of Strings, never null - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static List readLines(Reader input) throws IOException { - BufferedReader reader = new BufferedReader(input); - List list = new ArrayList(); - String line = reader.readLine(); - while(line != null) { - list.add(line); - line = reader.readLine(); - } - return list; - } - - /** - * Convert the specified string to an input stream, encoded as bytes using the - * default character encoding of the platform. - * - * @param input - * the string to convert - * @return an input stream - * @since Commons IO 1.1 - */ - public static InputStream toInputStream(String input) { - byte[] bytes = input.getBytes(); - return new ByteArrayInputStream(bytes); - } - - // writeNodeData byte[] - // ----------------------------------------------------------------------- - - /** - * Convert the specified string to an input stream, encoded as bytes using the - * specified character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input - * the string to convert - * @param encoding - * the encoding to use, null means platform default - * @return an input stream - * @throws IOException - * if the encoding is invalid - * @since Commons IO 1.1 - */ - public static InputStream toInputStream(String input, String encoding) throws IOException { - byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes(); - return new ByteArrayInputStream(bytes); - } - - /** - * Writes bytes from a byte[] to an OutputStream. - * - * @param data - * the byte array to writeNodeData, do not modify during output, null ignored - * @param output - * the OutputStream to writeNodeData to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(byte[] data, OutputStream output) throws IOException { - if(data != null) { - output.write(data); - } - } - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the default character encoding of the platform. - *

- * This method uses {@link String#String(byte[])}. - * - * @param data - * the byte array to writeNodeData, do not modify during output, null ignored - * @param output - * the Writer to writeNodeData to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(byte[] data, Writer output) throws IOException { - if(data != null) { - output.write(new String(data)); - } - } - - // writeNodeData char[] - // ----------------------------------------------------------------------- - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#String(byte[], String)}. - * - * @param data - * the byte array to writeNodeData, do not modify during output, null ignored - * @param output - * the Writer to writeNodeData to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(byte[] data, Writer output, String encoding) throws IOException { - if(data != null) { - if(encoding == null) { - write(data, output); - } else { - output.write(new String(data, encoding)); - } - } - } - - /** - * Writes chars from a char[] to a Writer using the - * default character encoding of the platform. - * - * @param data - * the char array to writeNodeData, do not modify during output, null ignored - * @param output - * the Writer to writeNodeData to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(char[] data, Writer output) throws IOException { - if(data != null) { - output.write(data); - } - } - - /** - * Writes chars from a char[] to bytes on an - * OutputStream. - *

- * This method uses {@link String#String(char[])} and {@link String#getBytes()}. - * - * @param data - * the char array to writeNodeData, do not modify during output, null ignored - * @param output - * the OutputStream to writeNodeData to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(char[] data, OutputStream output) throws IOException { - if(data != null) { - output.write(new String(data).getBytes()); - } - } - - // writeNodeData String - // ----------------------------------------------------------------------- - - /** - * Writes chars from a char[] to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#String(char[])} and - * {@link String#getBytes(String)}. - * - * @param data - * the char array to writeNodeData, do not modify during output, null ignored - * @param output - * the OutputStream to writeNodeData to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(char[] data, OutputStream output, String encoding) throws IOException { - if(data != null) { - if(encoding == null) { - write(data, output); - } else { - output.write(new String(data).getBytes(encoding)); - } - } - } - - /** - * Writes chars from a String to a Writer. - * - * @param data - * the String to writeNodeData, null ignored - * @param output - * the Writer to writeNodeData to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(String data, Writer output) throws IOException { - if(data != null) { - output.write(data); - } - } - - /** - * Writes chars from a String to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data - * the String to writeNodeData, null ignored - * @param output - * the OutputStream to writeNodeData to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(String data, OutputStream output) throws IOException { - if(data != null) { - output.write(data.getBytes()); - } - } - - // writeNodeData StringBuffer - // ----------------------------------------------------------------------- - - /** - * Writes chars from a String to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data - * the String to writeNodeData, null ignored - * @param output - * the OutputStream to writeNodeData to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(String data, OutputStream output, String encoding) throws IOException { - if(data != null) { - if(encoding == null) { - write(data, output); - } else { - output.write(data.getBytes(encoding)); - } - } - } - - /** - * Writes chars from a StringBuffer to a Writer. - * - * @param data - * the StringBuffer to writeNodeData, null ignored - * @param output - * the Writer to writeNodeData to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(StringBuffer data, Writer output) throws IOException { - if(data != null) { - output.write(data.toString()); - } - } - - /** - * Writes chars from a StringBuffer to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data - * the StringBuffer to writeNodeData, null ignored - * @param output - * the OutputStream to writeNodeData to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(StringBuffer data, OutputStream output) throws IOException { - if(data != null) { - output.write(data.toString().getBytes()); - } - } - - // writeLines - // ----------------------------------------------------------------------- - - /** - * Writes chars from a StringBuffer to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data - * the StringBuffer to writeNodeData, null ignored - * @param output - * the OutputStream to writeNodeData to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException { - if(data != null) { - if(encoding == null) { - write(data, output); - } else { - output.write(data.toString().getBytes(encoding)); - } - } - } - - /** - * Writes the toString() value of each item in a collection to an - * OutputStream line by line, using the default character encoding - * of the platform and the specified line ending. - * - * @param lines - * the lines to writeNodeData, null entries produce blank lines - * @param lineEnding - * the line separator to use, null is system default - * @param output - * the OutputStream to writeNodeData to, not null, not closed - * @throws NullPointerException - * if the output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, OutputStream output) throws IOException { - if(lines == null) { - return; - } - if(lineEnding == null) { - lineEnding = LINE_SEPARATOR; - } - for(Iterator it = lines.iterator(); it.hasNext(); ) { - Object line = it.next(); - if(line != null) { - output.write(line.toString().getBytes()); - } - output.write(lineEnding.getBytes()); - } - } - - /** - * Writes the toString() value of each item in a collection to an - * OutputStream line by line, using the specified character - * encoding and the specified line ending. - *

- * Character encoding names can be found at - * IANA. - * - * @param lines - * the lines to writeNodeData, null entries produce blank lines - * @param lineEnding - * the line separator to use, null is system default - * @param output - * the OutputStream to writeNodeData to, not null, not closed - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if the output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, OutputStream output, String encoding) throws IOException { - if(encoding == null) { - writeLines(lines, lineEnding, output); - } else { - if(lines == null) { - return; - } - if(lineEnding == null) { - lineEnding = LINE_SEPARATOR; - } - for(Iterator it = lines.iterator(); it.hasNext(); ) { - Object line = it.next(); - if(line != null) { - output.write(line.toString().getBytes(encoding)); - } - output.write(lineEnding.getBytes(encoding)); - } - } - } - - // copy from InputStream - // ----------------------------------------------------------------------- - - /** - * Writes the toString() value of each item in a collection to a - * Writer line by line, using the specified line ending. - * - * @param lines - * the lines to writeNodeData, null entries produce blank lines - * @param lineEnding - * the line separator to use, null is system default - * @param writer - * the Writer to writeNodeData to, not null, not closed - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, Writer writer) throws IOException { - if(lines == null) { - return; - } - if(lineEnding == null) { - lineEnding = LINE_SEPARATOR; - } - for(Iterator it = lines.iterator(); it.hasNext(); ) { - Object line = it.next(); - if(line != null) { - writer.write(line.toString()); - } - writer.write(lineEnding); - } - } - - /** - * Copy bytes from an InputStream to an OutputStream. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * Large streams (over 2GB) will return a bytes copied value of -1 - * after the copy has completed since the correct number of bytes cannot be - * returned as an int. For large streams use the - * copyLarge(InputStream, OutputStream) method. - * - * @param input - * the InputStream to read from - * @param output - * the OutputStream to writeNodeData to - * @return the number of bytes copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @throws ArithmeticException - * if the byte count is too large - * @since Commons IO 1.1 - */ - public static int copy(InputStream input, OutputStream output) throws IOException { - long count = copyLarge(input, output); - if(count > Integer.MAX_VALUE) { - return -1; - } - return (int) count; - } - - /** - * Copy bytes from a large (over 2GB) InputStream to an - * OutputStream. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from - * @param output - * the OutputStream to writeNodeData to - * @return the number of bytes copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.3 - */ - public static long copyLarge(InputStream input, OutputStream output) throws IOException { - byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; - long count = 0; - int n = 0; - while(-1 != (n = input.read(buffer))) { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * Copy bytes from an InputStream to chars on a Writer - * using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * This method uses {@link InputStreamReader}. - * - * @param input - * the InputStream to read from - * @param output - * the Writer to writeNodeData to - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void copy(InputStream input, Writer output) throws IOException { - InputStreamReader in = new InputStreamReader(input); - copy(in, output); - } - - // copy from Reader - // ----------------------------------------------------------------------- - - /** - * Copy bytes from an InputStream to chars on a Writer - * using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link InputStreamReader}. - * - * @param input - * the InputStream to read from - * @param output - * the Writer to writeNodeData to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void copy(InputStream input, Writer output, String encoding) throws IOException { - if(encoding == null) { - copy(input, output); - } else { - InputStreamReader in = new InputStreamReader(input, encoding); - copy(in, output); - } - } - - /** - * Copy chars from a Reader to a Writer. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Large streams (over 2GB) will return a chars copied value of -1 - * after the copy has completed since the correct number of chars cannot be - * returned as an int. For large streams use the - * copyLarge(Reader, Writer) method. - * - * @param input - * the Reader to read from - * @param output - * the Writer to writeNodeData to - * @return the number of characters copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @throws ArithmeticException - * if the character count is too large - * @since Commons IO 1.1 - */ - public static int copy(Reader input, Writer output) throws IOException { - long count = copyLarge(input, output); - if(count > Integer.MAX_VALUE) { - return -1; - } - return (int) count; - } - - /** - * Copy chars from a large (over 2GB) Reader to a - * Writer. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @param output - * the Writer to writeNodeData to - * @return the number of characters copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.3 - */ - public static long copyLarge(Reader input, Writer output) throws IOException { - char[] buffer = new char[DEFAULT_BUFFER_SIZE]; - long count = 0; - int n = 0; - while(-1 != (n = input.read(buffer))) { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the default character encoding of the - * platform, and calling flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- * This method uses {@link OutputStreamWriter}. - * - * @param input - * the Reader to read from - * @param output - * the OutputStream to writeNodeData to - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void copy(Reader input, OutputStream output) throws IOException { - OutputStreamWriter out = new OutputStreamWriter(output); - copy(input, out); - // have to flush here. - out.flush(); - } - - // content equals - // ----------------------------------------------------------------------- - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the specified character encoding, and calling - * flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Character encoding names can be found at - * IANA. - *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- * This method uses {@link OutputStreamWriter}. - * - * @param input - * the Reader to read from - * @param output - * the OutputStream to writeNodeData to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void copy(Reader input, OutputStream output, String encoding) throws IOException { - if(encoding == null) { - copy(input, output); - } else { - OutputStreamWriter out = new OutputStreamWriter(output, encoding); - copy(input, out); - // we have to flush here. - out.flush(); - } - } - - /** - * Compare the contents of two Streams to determine if they are equal or not. - *

- * This method buffers the input internally using - * BufferedInputStream if they are not already buffered. - * - * @param input1 - * the first stream - * @param input2 - * the second stream - * @return true if the content of the streams are equal or they both don't - * exist, false otherwise - * @throws NullPointerException - * if either input is null - * @throws IOException - * if an I/O error occurs - */ - public static boolean contentEquals(InputStream input1, InputStream input2) throws IOException { - if(!(input1 instanceof BufferedInputStream)) { - input1 = new BufferedInputStream(input1); - } - if(!(input2 instanceof BufferedInputStream)) { - input2 = new BufferedInputStream(input2); - } - - int ch = input1.read(); - while(-1 != ch) { - int ch2 = input2.read(); - if(ch != ch2) { - return false; - } - ch = input1.read(); - } - - int ch2 = input2.read(); - return (ch2 == -1); - } - - /** - * Compare the contents of two Readers to determine if they are equal or not. - *

- * This method buffers the input internally using BufferedReader if - * they are not already buffered. - * - * @param input1 - * the first reader - * @param input2 - * the second reader - * @return true if the content of the readers are equal or they both don't - * exist, false otherwise - * @throws NullPointerException - * if either input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static boolean contentEquals(Reader input1, Reader input2) throws IOException { - if(!(input1 instanceof BufferedReader)) { - input1 = new BufferedReader(input1); - } - if(!(input2 instanceof BufferedReader)) { - input2 = new BufferedReader(input2); - } - - int ch = input1.read(); - while(-1 != ch) { - int ch2 = input2.read(); - if(ch != ch2) { - return false; - } - ch = input1.read(); - } - - int ch2 = input2.read(); - return (ch2 == -1); - } -} diff --git a/src/main/java/com/volmit/iris/util/io/IORunnable.java b/src/main/java/com/volmit/iris/util/io/IORunnable.java deleted file mode 100644 index ba2064491..000000000 --- a/src/main/java/com/volmit/iris/util/io/IORunnable.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import java.io.IOException; - -public interface IORunnable { - void run() throws IOException; -} diff --git a/src/main/java/com/volmit/iris/util/io/InstanceState.java b/src/main/java/com/volmit/iris/util/io/InstanceState.java deleted file mode 100644 index 1695642d2..000000000 --- a/src/main/java/com/volmit/iris/util/io/InstanceState.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import com.volmit.iris.util.math.RNG; - -import java.io.File; -import java.io.IOException; - -public class InstanceState { - public static int getInstanceId() { - try { - return Integer.parseInt(IO.readAll(instanceFile()).trim()); - } catch(Throwable e) { - e.printStackTrace(); - } - - return -1; - } - - public static void updateInstanceId() { - try { - IO.writeAll(instanceFile(), RNG.r.imax() + ""); - } catch(IOException e) { - e.printStackTrace(); - } - } - - private static File instanceFile() { - File f = new File("plugins/Iris/cache/instance"); - f.getParentFile().mkdirs(); - return f; - } -} diff --git a/src/main/java/com/volmit/iris/util/io/JarScanner.java b/src/main/java/com/volmit/iris/util/io/JarScanner.java deleted file mode 100644 index af04772b9..000000000 --- a/src/main/java/com/volmit/iris/util/io/JarScanner.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KSet; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -public class JarScanner { - private final KSet> classes; - private final File jar; - private final String superPackage; - - /** - * Create a scanner - * - * @param jar - * the path to the jar - */ - public JarScanner(File jar, String superPackage) { - this.jar = jar; - this.classes = new KSet<>(); - this.superPackage = superPackage; - } - - /** - * Scan the jar - * - * @throws IOException - * bad things happen - */ - public void scan() throws IOException { - classes.clear(); - FileInputStream fin = new FileInputStream(jar); - ZipInputStream zip = new ZipInputStream(fin); - - for(ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { - if(!entry.isDirectory() && entry.getName().endsWith(".class")) { - if(entry.getName().contains("$")) { - continue; - } - - String c = entry.getName().replaceAll("/", ".").replace(".class", ""); - - if(c.startsWith(superPackage)) { - try { - Class clazz = Class.forName(c); - classes.add(clazz); - } catch(ClassNotFoundException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - } - } - - zip.close(); - } - - /** - * Get the scanned clases - * - * @return a gset of classes - */ - public KSet> getClasses() { - return classes; - } - - /** - * Get the file object for the jar - * - * @return a file object representing the jar - */ - public File getJar() { - return jar; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/io/ReactiveFolder.java b/src/main/java/com/volmit/iris/util/io/ReactiveFolder.java deleted file mode 100644 index 12e91035c..000000000 --- a/src/main/java/com/volmit/iris/util/io/ReactiveFolder.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.function.Consumer3; - -import java.io.File; - -public class ReactiveFolder { - private final File folder; - private final Consumer3, KList, KList> hotload; - private FolderWatcher fw; - private int checkCycle = 0; - - public ReactiveFolder(File folder, Consumer3, KList, KList> hotload) { - this.folder = folder; - this.hotload = hotload; - this.fw = new FolderWatcher(folder); - fw.checkModified(); - } - - public void checkIgnore() { - fw = new FolderWatcher(folder); - } - - public boolean check() { - checkCycle++; - boolean modified = false; - - if(checkCycle % 3 == 0 ? fw.checkModified() : fw.checkModifiedFast()) { - for(File i : fw.getCreated()) { - if(i.getName().endsWith(".iob") || i.getName().endsWith(".json") || i.getName().endsWith(".js")) { - if(i.getPath().contains(".iris")) { - continue; - } - - modified = true; - break; - } - } - - if(!modified) { - for(File i : fw.getChanged()) { - if(i.getPath().contains(".iris")) { - continue; - } - - if(i.getName().endsWith(".iob") || i.getName().endsWith(".json") || i.getName().endsWith(".js")) { - modified = true; - break; - } - } - } - - if(!modified) { - for(File i : fw.getDeleted()) { - if(i.getPath().contains(".iris")) { - continue; - } - - if(i.getName().endsWith(".iob") || i.getName().endsWith(".json") || i.getName().endsWith(".js")) { - modified = true; - break; - } - } - } - } - - if(modified) { - hotload.accept(fw.getCreated(), fw.getChanged(), fw.getDeleted()); - } - - return fw.checkModified(); - } - - public void clear() { - fw.clear(); - } -} diff --git a/src/main/java/com/volmit/iris/util/io/VoidOutputStream.java b/src/main/java/com/volmit/iris/util/io/VoidOutputStream.java deleted file mode 100644 index 7855e9908..000000000 --- a/src/main/java/com/volmit/iris/util/io/VoidOutputStream.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.io; - -import java.io.OutputStream; - -public class VoidOutputStream extends OutputStream { - @Override - public void write(int b) { - // poof - } -} diff --git a/src/main/java/com/volmit/iris/util/json/HTTP.java b/src/main/java/com/volmit/iris/util/json/HTTP.java deleted file mode 100644 index 417a7e406..000000000 --- a/src/main/java/com/volmit/iris/util/json/HTTP.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -import java.util.Iterator; - -/** - * Convert an HTTP header to a JSONObject and back. - * - * @author JSON.org - * @version 2014-05-03 - */ -public class HTTP { - - /** - * Carriage return/line feed. - */ - public static final String CRLF = "\r\n"; - - /** - * Convert an HTTP header string into a JSONObject. It can be a request - * header or a response header. A request header will contain - * - *

-     * {
-     *    Method: "POST" (for example),
-     *    "Request-URI": "/" (for example),
-     *    "HTTP-Version": "HTTP/1.1" (for example)
-     * }
-     * 
- *

- * A response header will contain - * - *

-     * {
-     *    "HTTP-Version": "HTTP/1.1" (for example),
-     *    "Status-Code": "200" (for example),
-     *    "Reason-Phrase": "OK" (for example)
-     * }
-     * 
- *

- * In addition, the other parameters in the header will be captured, using - * the HTTP field names as JSON names, so that - * - *

-     *    Date: Sun, 26 May 2002 18:06:04 GMT
-     *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
-     *    Cache-Control: no-cache
-     * 
- *

- * become - * - *

-     * {...
-     *    Date: "Sun, 26 May 2002 18:06:04 GMT",
-     *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
-     *    "Cache-Control": "no-cache",
-     * ...}
-     * 
- *

- * It does no further checking or conversion. It does not parse dates. It - * does not do '%' transforms on URLs. - * - * @param string - * An HTTP header string. - * @return A JSONObject containing the elements and attributes of the XML - * string. - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; - - token = x.nextToken(); - if(token.toUpperCase().startsWith("HTTP")) { - - // Response - - jo.put("HTTP-Version", token); - jo.put("Status-Code", x.nextToken()); - jo.put("Reason-Phrase", x.nextTo('\0')); - x.next(); - - } else { - - // Request - - jo.put("Method", token); - jo.put("Request-URI", x.nextToken()); - jo.put("HTTP-Version", x.nextToken()); - } - - // Fields - - while(x.more()) { - String name = x.nextTo(':'); - x.next(':'); - jo.put(name, x.nextTo('\0')); - x.next(); - } - return jo; - } - - /** - * Convert a JSONObject into an HTTP header. A request header must contain - * - *

-     * {
-     *    Method: "POST" (for example),
-     *    "Request-URI": "/" (for example),
-     *    "HTTP-Version": "HTTP/1.1" (for example)
-     * }
-     * 
- *

- * A response header must contain - * - *

-     * {
-     *    "HTTP-Version": "HTTP/1.1" (for example),
-     *    "Status-Code": "200" (for example),
-     *    "Reason-Phrase": "OK" (for example)
-     * }
-     * 
- *

- * Any other members of the JSONObject will be output as HTTP fields. The - * result will end with two CRLF pairs. - * - * @param jo - * A JSONObject - * @return An HTTP header string. - * @throws JSONException - * if the object does not contain enough information. - */ - public static String toString(JSONObject jo) throws JSONException { - Iterator keys = jo.keys(); - String string; - StringBuilder sb = new StringBuilder(); - if(jo.has("Status-Code") && jo.has("Reason-Phrase")) { - sb.append(jo.getString("HTTP-Version")); - sb.append(' '); - sb.append(jo.getString("Status-Code")); - sb.append(' '); - sb.append(jo.getString("Reason-Phrase")); - } else if(jo.has("Method") && jo.has("Request-URI")) { - sb.append(jo.getString("Method")); - sb.append(' '); - sb.append('"'); - sb.append(jo.getString("Request-URI")); - sb.append('"'); - sb.append(' '); - sb.append(jo.getString("HTTP-Version")); - } else { - throw new JSONException("Not enough material for an HTTP header."); - } - sb.append(CRLF); - while(keys.hasNext()) { - string = keys.next(); - if(!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { - sb.append(string); - sb.append(": "); - sb.append(jo.getString(string)); - sb.append(CRLF); - } - } - sb.append(CRLF); - return sb.toString(); - } -} diff --git a/src/main/java/com/volmit/iris/util/json/HTTPTokener.java b/src/main/java/com/volmit/iris/util/json/HTTPTokener.java deleted file mode 100644 index fb8deaecd..000000000 --- a/src/main/java/com/volmit/iris/util/json/HTTPTokener.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -/** - * The HTTPTokener extends the JSONTokener to provide additional methods for the - * parsing of HTTP headers. - * - * @author JSON.org - * @version 2014-05-03 - */ -public class HTTPTokener extends JSONTokener { - - /** - * Construct an HTTPTokener from a string. - * - * @param string - * A source string. - */ - public HTTPTokener(String string) { - super(string); - } - - /** - * Get the next token or string. This is used in parsing HTTP headers. - * - * @return A String. - */ - public String nextToken() throws JSONException { - char c; - char q; - StringBuilder sb = new StringBuilder(); - do { - c = next(); - } while(Character.isWhitespace(c)); - if(c == '"' || c == '\'') { - q = c; - for(; ; ) { - c = next(); - if(c < ' ') { - throw syntaxError("Unterminated string."); - } - if(c == q) { - return sb.toString(); - } - sb.append(c); - } - } - for(; ; ) { - if(c == 0 || Character.isWhitespace(c)) { - return sb.toString(); - } - sb.append(c); - c = next(); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/json/JSONArray.java b/src/main/java/com/volmit/iris/util/json/JSONArray.java deleted file mode 100644 index d89e6de46..000000000 --- a/src/main/java/com/volmit/iris/util/json/JSONArray.java +++ /dev/null @@ -1,1125 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -import com.volmit.iris.Iris; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.Array; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; - -/** - * A JSONArray is an ordered sequence of values. Its external text form is a - * string wrapped in square brackets with commas separating the values. The - * internal form is an object having get and opt - * methods for accessing the values by index, and put methods for - * adding or replacing values. The values can be any of these types: - * Boolean, JSONArray, JSONObject, - * Number, String, or the - * JSONObject.NULL object. - *

- * The constructor can convert a JSON text into a Java object. The - * toString method converts to JSON text. - *

- * A get method returns a value if one can be found, and throws an - * exception if one cannot be found. An opt method returns a - * default value instead of throwing an exception, and so is useful for - * obtaining optional values. - *

- * The generic get() and opt() methods return an - * object which you can cast or query for type. There are also typed - * get and opt methods that do type checking and type - * coercion for you. - *

- * The texts produced by the toString methods strictly conform to - * JSON syntax rules. The constructors are more forgiving in the texts they will - * accept: - *

    - *
  • An extra , (comma) may appear just - * before the closing bracket.
  • - *
  • The null value will be inserted when there is , - *  (comma) elision.
  • - *
  • Strings may be quoted with ' (single - * quote).
  • - *
  • Strings do not need to be quoted at all if they do not begin with a quote - * or single quote, and if they do not contain leading or trailing spaces, and - * if they do not contain any of these characters: - * { } [ ] / \ : , # and if they do not look like numbers and if - * they are not the reserved words true, false, or - * null.
  • - *
- * - * @author JSON.org - * @version 2015-07-22 - */ -@SuppressWarnings("ALL") -public class JSONArray implements Iterable { - - /** - * The arrayList where the JSONArray's properties are kept. - */ - private final ArrayList myArrayList; - - /** - * Construct an empty JSONArray. - */ - public JSONArray() { - this.myArrayList = new ArrayList(); - } - - /** - * Construct a JSONArray from a JSONTokener. - * - * @param x - * A JSONTokener - * @throws JSONException - * If there is a syntax error. - */ - public JSONArray(JSONTokener x) throws JSONException { - this(); - if(x.nextClean() != '[') { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if(x.nextClean() != ']') { - x.back(); - for(; ; ) { - if(x.nextClean() == ',') { - x.back(); - this.myArrayList.add(JSONObject.NULL); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); - } - switch(x.nextClean()) { - case ',': - if(x.nextClean() == ']') { - return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - } - } - } - - /** - * Construct a JSONArray from a source JSON text. - * - * @param source - * A string that begins with [ (left - * bracket) and ends with ]   - * (right bracket). - * @throws JSONException - * If there is a syntax error. - */ - public JSONArray(String source) throws JSONException { - this(new JSONTokener(source)); - } - - /** - * Construct a JSONArray from a Collection. - * - * @param collection - * A Collection. - */ - public JSONArray(Collection collection) { - this.myArrayList = new ArrayList(); - if(collection != null) { - Iterator iter = collection.iterator(); - while(iter.hasNext()) { - this.myArrayList.add(JSONObject.wrap(iter.next())); - } - } - } - - /** - * Construct a JSONArray from an array - * - * @throws JSONException - * If not an array. - */ - public JSONArray(Object array) throws JSONException { - this(); - if(array.getClass().isArray()) { - int length = Array.getLength(array); - for(int i = 0; i < length; i += 1) { - this.put(JSONObject.wrap(Array.get(array, i))); - } - } else { - throw new JSONException("JSONArray initial value should be a string or collection or array."); - } - } - - @Override - public Iterator iterator() { - return myArrayList.iterator(); - } - - /** - * Get the object value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return An object value. - * @throws JSONException - * If there is no value for the index. - */ - public Object get(int index) throws JSONException { - Object object = this.opt(index); - if(object == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return object; - } - - /** - * Get the boolean value associated with an index. The string values "true" - * and "false" are converted to boolean. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - * @throws JSONException - * If there is no value for the index or if the value is not - * convertible to boolean. - */ - public boolean getBoolean(int index) throws JSONException { - Object object = this.get(index); - if(object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) { - return false; - } else if(object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONArray[" + index + "] is not a boolean."); - } - - /** - * Get the double value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. - */ - public double getDouble(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } - - /** - * Get the enum value associated with an index. - * - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @return The enum value at the index location - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ - public > E getEnum(Class clazz, int index) throws JSONException { - E val = optEnum(clazz, index); - if(val == null) { - // JSONException should really take a throwable argument. - // If it did, I would re-implement this with the Enum.valueOf - // method and place any thrown exception in the JSONException - throw new JSONException("JSONObject[" + JSONObject.quote(Integer.toString(index)) + "] is not an enum of type " + JSONObject.quote(clazz.getSimpleName()) + "."); - } - return val; - } - - /** - * Get the BigDecimal value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigDecimal. - */ - public BigDecimal getBigDecimal(int index) throws JSONException { - Object object = this.get(index); - try { - return new BigDecimal(object.toString()); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONArray[" + index + "] could not convert to BigDecimal."); - } - } - - /** - * Get the BigInteger value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigInteger. - */ - public BigInteger getBigInteger(int index) throws JSONException { - Object object = this.get(index); - try { - return new BigInteger(object.toString()); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONArray[" + index + "] could not convert to BigInteger."); - } - } - - /** - * Get the int value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value is not a number. - */ - public int getInt(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } - - /** - * Get the JSONArray associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONArray value. - * @throws JSONException - * If there is no value for the index. or if the value is not a - * JSONArray - */ - public JSONArray getJSONArray(int index) throws JSONException { - Object object = this.get(index); - if(object instanceof JSONArray) { - return (JSONArray) object; - } - throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); - } - - /** - * Get the JSONObject associated with an index. - * - * @param index - * subscript - * @return A JSONObject value. - * @throws JSONException - * If there is no value for the index or if the value is not a - * JSONObject - */ - public JSONObject getJSONObject(int index) throws JSONException { - Object object = this.get(index); - if(object instanceof JSONObject) { - return (JSONObject) object; - } - throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); - } - - /** - * Get the long value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. - */ - public long getLong(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } - - /** - * Get the string associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A string value. - * @throws JSONException - * If there is no string value for the index. - */ - public String getString(int index) throws JSONException { - Object object = this.get(index); - if(object instanceof String) { - return (String) object; - } - throw new JSONException("JSONArray[" + index + "] not a string."); - } - - /** - * Determine if the value is null. - * - * @param index - * The index must be between 0 and length() - 1. - * @return true if the value at the index is null, or if there is no value. - */ - public boolean isNull(int index) { - return JSONObject.NULL.equals(this.opt(index)); - } - - /** - * Make a string from the contents of this JSONArray. The - * separator string is inserted between each element. Warning: - * This method assumes that the data structure is acyclical. - * - * @param separator - * A string that will be inserted between the elements. - * @return a string. - * @throws JSONException - * If the array contains an invalid number. - */ - public String join(String separator) throws JSONException { - int len = this.length(); - StringBuilder sb = new StringBuilder(); - - for(int i = 0; i < len; i += 1) { - if(i > 0) { - sb.append(separator); - } - sb.append(JSONObject.valueToString(this.myArrayList.get(i))); - } - return sb.toString(); - } - - /** - * Get the number of elements in the JSONArray, included nulls. - * - * @return The length (or size). - */ - public int length() { - return this.myArrayList.size(); - } - - /** - * Get the optional object value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return An object value, or null if there is no object at that index. - */ - public Object opt(int index) { - return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index); - } - - /** - * Get the optional boolean value associated with an index. It returns false - * if there is no value at that index, or if the value is not Boolean.TRUE - * or the String "true". - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - */ - public boolean optBoolean(int index) { - return this.optBoolean(index, false); - } - - /** - * Get the optional boolean value associated with an index. It returns the - * defaultValue if there is no value at that index or if it is not a Boolean - * or the String "true" or "false" (case insensitive). - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * A boolean default. - * @return The truth. - */ - public boolean optBoolean(int index, boolean defaultValue) { - try { - return this.getBoolean(index); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get the optional double value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public double optDouble(int index) { - return this.optDouble(index, Double.NaN); - } - - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * subscript - * @param defaultValue - * The default value. - * @return The value. - */ - public double optDouble(int index, double defaultValue) { - try { - return this.getDouble(index); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get the optional int value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public int optInt(int index) { - return this.optInt(index, 0); - } - - /** - * Get the optional int value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public int optInt(int index, int defaultValue) { - try { - return this.getInt(index); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @return The enum value at the index location or null if not found - */ - public > E optEnum(Class clazz, int index) { - return this.optEnum(clazz, index, null); - } - - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default in case the value is not found - * @return The enum value at the index location or defaultValue if the value - * is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, int index, E defaultValue) { - try { - Object val = this.opt(index); - if(JSONObject.NULL.equals(val)) { - return defaultValue; - } - if(clazz.isAssignableFrom(val.getClass())) { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } catch(IllegalArgumentException e) { - Iris.reportError(e); - return defaultValue; - } catch(NullPointerException e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get the optional BigInteger value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the - * value is not a number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public BigInteger optBigInteger(int index, BigInteger defaultValue) { - try { - return this.getBigInteger(index); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get the optional BigDecimal value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the - * value is not a number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { - try { - return this.getBigDecimal(index); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get the optional JSONArray associated with an index. - * - * @param index - * subscript - * @return A JSONArray value, or null if the index has no value, or if the - * value is not a JSONArray. - */ - public JSONArray optJSONArray(int index) { - Object o = this.opt(index); - return o instanceof JSONArray ? (JSONArray) o : null; - } - - /** - * Get the optional JSONObject associated with an index. Null is returned if - * the key is not found, or null if the index has no value, or if the value - * is not a JSONObject. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index) { - Object o = this.opt(index); - return o instanceof JSONObject ? (JSONObject) o : null; - } - - /** - * Get the optional long value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public long optLong(int index) { - return this.optLong(index, 0); - } - - /** - * Get the optional long value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public long optLong(int index, long defaultValue) { - try { - return this.getLong(index); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get the optional string value associated with an index. It returns an - * empty string if there is no value at that index. If the value is not a - * string and is not null, then it is coverted to a string. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A String value. - */ - public String optString(int index) { - return this.optString(index, ""); - } - - /** - * Get the optional string associated with an index. The defaultValue is - * returned if the key is not found. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return A String value. - */ - public String optString(int index, String defaultValue) { - Object object = this.opt(index); - return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); - } - - /** - * Append a boolean value. This increases the array's length by one. - * - * @param value - * A boolean value. - * @return this. - */ - public JSONArray put(boolean value) { - this.put(value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param value - * A Collection value. - * @return this. - */ - public JSONArray put(Collection value) { - this.put(new JSONArray(value)); - return this; - } - - /** - * Append a double value. This increases the array's length by one. - * - * @param value - * A double value. - * @return this. - * @throws JSONException - * if the value is not finite. - */ - public JSONArray put(double value) throws JSONException { - Double d = Double.valueOf(value); - JSONObject.testValidity(d); - this.put(d); - return this; - } - - /** - * Append an int value. This increases the array's length by one. - * - * @param value - * An int value. - * @return this. - */ - public JSONArray put(int value) { - this.put(Integer.valueOf(value)); - return this; - } - - /** - * Append an long value. This increases the array's length by one. - * - * @param value - * A long value. - * @return this. - */ - public JSONArray put(long value) { - this.put(Long.valueOf(value)); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONObject which - * is produced from a Map. - * - * @param value - * A Map value. - * @return this. - */ - public JSONArray put(Map value) { - this.put(new JSONObject(value)); - return this; - } - - /** - * Append an object value. This increases the array's length by one. - * - * @param value - * An object value. The value should be a Boolean, Double, - * Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. - * @return this. - */ - public JSONArray put(Object value) { - this.myArrayList.add(value); - return this; - } - - /** - * Put or replace a boolean value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index - * The subscript. - * @param value - * A boolean value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, boolean value) throws JSONException { - this.put(index, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param index - * The subscript. - * @param value - * A Collection value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is not finite. - */ - public JSONArray put(int index, Collection value) throws JSONException { - this.put(index, new JSONArray(value)); - return this; - } - - /** - * Put or replace a double value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A double value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is not finite. - */ - public JSONArray put(int index, double value) throws JSONException { - this.put(index, Double.valueOf(value)); - return this; - } - - /** - * Put or replace an int value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * An int value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, int value) throws JSONException { - this.put(index, Integer.valueOf(value)); - return this; - } - - /** - * Put or replace a long value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A long value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, long value) throws JSONException { - this.put(index, Long.valueOf(value)); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONObject that - * is produced from a Map. - * - * @param index - * The subscript. - * @param value - * The Map value. - * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. - */ - public JSONArray put(int index, Map value) throws JSONException { - this.put(index, new JSONObject(value)); - return this; - } - - /** - * Put or replace an object value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index - * The subscript. - * @param value - * The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. - */ - public JSONArray put(int index, Object value) throws JSONException { - JSONObject.testValidity(value); - if(index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if(index < this.length()) { - this.myArrayList.set(index, value); - } else { - while(index != this.length()) { - this.put(JSONObject.NULL); - } - this.put(value); - } - return this; - } - - /** - * Remove an index and close the hole. - * - * @param index - * The index of the element to be removed. - * @return The value that was associated with the index, or null if there - * was no value. - */ - public Object remove(int index) { - return index >= 0 && index < this.length() ? this.myArrayList.remove(index) : null; - } - - /** - * Determine if two JSONArrays are similar. They must contain similar - * sequences. - * - * @param other - * The other JSONArray - * @return true if they are equal - */ - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean similar(Object other) { - if(!(other instanceof JSONArray)) { - return false; - } - int len = this.length(); - if(len != ((JSONArray) other).length()) { - return false; - } - for(int i = 0; i < len; i += 1) { - Object valueThis = this.get(i); - Object valueOther = ((JSONArray) other).get(i); - if(valueThis instanceof JSONObject) { - if(!((JSONObject) valueThis).similar(valueOther)) { - return false; - } - } else if(valueThis instanceof JSONArray) { - if(!((JSONArray) valueThis).similar(valueOther)) { - return false; - } - } else if(!valueThis.equals(valueOther)) { - return false; - } - } - return true; - } - - /** - * Produce a JSONObject by combining a JSONArray of names with the values of - * this JSONArray. - * - * @param names - * A JSONArray containing a list of key strings. These will be - * paired with the values. - * @return A JSONObject, or null if there are no names or if this JSONArray - * has no values. - * @throws JSONException - * If any of the names are null. - */ - public JSONObject toJSONObject(JSONArray names) throws JSONException { - if(names == null || names.length() == 0 || this.length() == 0) { - return null; - } - JSONObject jo = new JSONObject(); - for(int i = 0; i < names.length(); i += 1) { - jo.put(names.getString(i), this.opt(i)); - } - return jo; - } - - /** - * Make a JSON text of this JSONArray. For compactness, no unnecessary - * whitespace is added. If it is not possible to produce a syntactically - * correct JSON text then null will be returned instead. This could occur if - * the array contains an invalid number. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, transmittable representation of the - * array. - */ - @Override - public String toString() { - try { - return this.toString(0); - } catch(Exception e) { - Iris.reportError(e); - return null; - } - } - - /** - * Make a prettyprinted JSON text of this JSONArray. Warning: This method - * assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, transmittable representation of the - * object, beginning with [ (left - * bracket) and ending with ]   - * (right bracket). - */ - public String toString(int indentFactor) throws JSONException { - StringWriter sw = new StringWriter(); - synchronized(sw.getBuffer()) { - return this.write(sw, indentFactor, 0).toString(); - } - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @param indent - * The indention of the top level. - * @return The writer. - */ - Writer write(Writer writer, int indentFactor, int indent) throws JSONException { - try { - boolean commanate = false; - int length = this.length(); - writer.write('['); - - if(length == 1) { - JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); - } else if(length != 0) { - final int newindent = indent + indentFactor; - - for(int i = 0; i < length; i += 1) { - if(commanate) { - writer.write(','); - } - if(indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, newindent); - JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); - commanate = true; - } - if(indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, indent); - } - writer.write(']'); - return writer; - } catch(IOException e) { - throw new JSONException(e); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/json/JSONException.java b/src/main/java/com/volmit/iris/util/json/JSONException.java deleted file mode 100644 index 27cbf9c37..000000000 --- a/src/main/java/com/volmit/iris/util/json/JSONException.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -/** - * The JSONException is thrown by the JSON.org classes when things are amiss. - * - * @author JSON.org - * @version 2014-05-03 - */ -public class JSONException extends RuntimeException { - private static final long serialVersionUID = 0; - private Throwable cause; - - /** - * Constructs a JSONException with an explanatory message. - * - * @param message - * Detail about the reason for the exception. - */ - public JSONException(String message) { - super(message); - } - - /** - * Constructs a new JSONException with the specified cause. - * - * @param cause - * The cause. - */ - public JSONException(Throwable cause) { - super(cause.getMessage()); - this.cause = cause; - } - - /** - * Returns the cause of this exception or null if the cause is nonexistent - * or unknown. - * - * @return the cause of this exception or null if the cause is nonexistent - * or unknown. - */ - @Override - public Throwable getCause() { - return this.cause; - } -} diff --git a/src/main/java/com/volmit/iris/util/json/JSONML.java b/src/main/java/com/volmit/iris/util/json/JSONML.java deleted file mode 100644 index b90963bee..000000000 --- a/src/main/java/com/volmit/iris/util/json/JSONML.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -import java.util.Iterator; - -/** - * This provides static methods to convert an XML text into a JSONArray or - * JSONObject, and to covert a JSONArray or JSONObject into an XML text using - * the JsonML transform. - * - * @author JSON.org - * @version 2014-05-03 - */ -public class JSONML { - - /** - * Parse XML values and store them in a JSONArray. - * - * @param x - * The XMLTokener containing the source string. - * @param arrayForm - * true if array form, false if object form. - * @param ja - * The JSONArray that is containing the current tag or null if we - * are at the outermost level. - * @return A JSONArray if the value is the outermost tag, otherwise null. - */ - private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { - String attribute; - char c; - String closeTag = null; - int i; - JSONArray newja = null; - JSONObject newjo = null; - Object token; - String tagName = null; - - // Test for and skip past these forms: - // - // - // - // - - while(true) { - if(!x.more()) { - throw x.syntaxError("Bad XML"); - } - token = x.nextContent(); - if(token == XML.LT) { - token = x.nextToken(); - if(token instanceof Character) { - if(token == XML.SLASH) { - - // Close tag "); - } else { - x.back(); - } - } else if(c == '[') { - token = x.nextToken(); - if(token.equals("CDATA") && x.next() == '[') { - if(ja != null) { - ja.put(x.nextCDATA()); - } - } else { - throw x.syntaxError("Expected 'CDATA['"); - } - } else { - i = 1; - do { - token = x.nextMeta(); - if(token == null) { - throw x.syntaxError("Missing '>' after ' 0); - } - } else if(token == XML.QUEST) { - - // "); - } else { - throw x.syntaxError("Misshaped tag"); - } - - // Open tag < - - } else { - if(!(token instanceof String)) { - throw x.syntaxError("Bad tagName '" + token + "'."); - } - tagName = (String) token; - newja = new JSONArray(); - newjo = new JSONObject(); - if(arrayForm) { - newja.put(tagName); - if(ja != null) { - ja.put(newja); - } - } else { - newjo.put("tagName", tagName); - if(ja != null) { - ja.put(newjo); - } - } - token = null; - for(; ; ) { - if(token == null) { - token = x.nextToken(); - } - if(token == null) { - throw x.syntaxError("Misshaped tag"); - } - if(!(token instanceof String)) { - break; - } - - // attribute = value - - attribute = (String) token; - if(!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { - throw x.syntaxError("Reserved attribute."); - } - token = x.nextToken(); - if(token == XML.EQ) { - token = x.nextToken(); - if(!(token instanceof String)) { - throw x.syntaxError("Missing value"); - } - newjo.accumulate(attribute, XML.stringToValue((String) token)); - token = null; - } else { - newjo.accumulate(attribute, ""); - } - } - if(arrayForm && newjo.length() > 0) { - newja.put(newjo); - } - - // Empty tag <.../> - - if(token == XML.SLASH) { - if(x.nextToken() != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - if(ja == null) { - if(arrayForm) { - return newja; - } else { - return newjo; - } - } - - // Content, between <...> and - - } else { - if(token != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - closeTag = (String) parse(x, arrayForm, newja); - if(closeTag != null) { - if(!closeTag.equals(tagName)) { - throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); - } - tagName = null; - if(!arrayForm && newja.length() > 0) { - newjo.put("childNodes", newja); - } - if(ja == null) { - if(arrayForm) { - return newja; - } else { - return newjo; - } - } - } - } - } - } else { - if(ja != null) { - ja.put(token instanceof String ? XML.stringToValue((String) token) : token); - } - } - } - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONArray using the JsonML transform. Each XML tag is represented as a - * JSONArray in which the first element is the tag name. If the tag has - * attributes, then the second element will be JSONObject containing the - * name/value pairs. If the tag contains children, then strings and - * JSONArrays will represent the child tags. Comments, prologs, DTDs, and - * <[ [ ]]> are ignored. - * - * @param string - * The source string. - * @return A JSONArray containing the structured data from the XML string. - */ - public static JSONArray toJSONArray(String string) throws JSONException { - return toJSONArray(new XMLTokener(string)); - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONArray using the JsonML transform. Each XML tag is represented as a - * JSONArray in which the first element is the tag name. If the tag has - * attributes, then the second element will be JSONObject containing the - * name/value pairs. If the tag contains children, then strings and - * JSONArrays will represent the child content and tags. Comments, prologs, - * DTDs, and <[ [ ]]> are ignored. - * - * @param x - * An XMLTokener. - * @return A JSONArray containing the structured data from the XML string. - */ - public static JSONArray toJSONArray(XMLTokener x) throws JSONException { - return (JSONArray) parse(x, true, null); - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject using the JsonML transform. Each XML tag is represented as a - * JSONObject with a "tagName" property. If the tag has attributes, then the - * attributes will be in the JSONObject as properties. If the tag contains - * children, the object will have a "childNodes" property which will be an - * array of strings and JsonML JSONObjects. - *

- * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * - * @param x - * An XMLTokener of the XML source text. - * @return A JSONObject containing the structured data from the XML string. - */ - public static JSONObject toJSONObject(XMLTokener x) throws JSONException { - return (JSONObject) parse(x, false, null); - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject using the JsonML transform. Each XML tag is represented as a - * JSONObject with a "tagName" property. If the tag has attributes, then the - * attributes will be in the JSONObject as properties. If the tag contains - * children, the object will have a "childNodes" property which will be an - * array of strings and JsonML JSONObjects. - *

- * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * - * @param string - * The XML source text. - * @return A JSONObject containing the structured data from the XML string. - */ - public static JSONObject toJSONObject(String string) throws JSONException { - return toJSONObject(new XMLTokener(string)); - } - - /** - * Reverse the JSONML transformation, making an XML text from a JSONArray. - * - * @param ja - * A JSONArray. - * @return An XML string. - */ - public static String toString(JSONArray ja) throws JSONException { - int i; - JSONObject jo; - String key; - Iterator keys; - int length; - Object object; - StringBuilder sb = new StringBuilder(); - String tagName; - String value; - - // Emit = length) { - sb.append('/'); - } else { - sb.append('>'); - do { - object = ja.get(i); - i += 1; - if(object != null) { - if(object instanceof String) { - sb.append(XML.escape(object.toString())); - } else if(object instanceof JSONObject) { - sb.append(toString((JSONObject) object)); - } else if(object instanceof JSONArray) { - sb.append(toString((JSONArray) object)); - } else { - sb.append(object); - } - } - } while(i < length); - sb.append('<'); - sb.append('/'); - sb.append(tagName); - } - sb.append('>'); - return sb.toString(); - } - - /** - * Reverse the JSONML transformation, making an XML text from a JSONObject. - * The JSONObject must contain a "tagName" property. If it has children, - * then it must have a "childNodes" property containing an array of objects. - * The other properties are attributes with string values. - * - * @param jo - * A JSONObject. - * @return An XML string. - */ - public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - String key; - Iterator keys; - int length; - Object object; - String tagName; - String value; - - // Emit '); - length = ja.length(); - for(i = 0; i < length; i += 1) { - object = ja.get(i); - if(object != null) { - if(object instanceof String) { - sb.append(XML.escape(object.toString())); - } else if(object instanceof JSONObject) { - sb.append(toString((JSONObject) object)); - } else if(object instanceof JSONArray) { - sb.append(toString((JSONArray) object)); - } else { - sb.append(object); - } - } - } - sb.append('<'); - sb.append('/'); - sb.append(tagName); - } - sb.append('>'); - return sb.toString(); - } -} diff --git a/src/main/java/com/volmit/iris/util/json/JSONObject.java b/src/main/java/com/volmit/iris/util/json/JSONObject.java deleted file mode 100644 index f94d1f102..000000000 --- a/src/main/java/com/volmit/iris/util/json/JSONObject.java +++ /dev/null @@ -1,1820 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - -import com.volmit.iris.Iris; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.ResourceBundle; -import java.util.Set; - -/** - * A JSONObject is an unordered collection of name/value pairs. Its external - * form is a string wrapped in curly braces with colons between the names and - * values, and commas between the values and names. The internal form is an - * object having get and opt methods for accessing the - * values by name, and put methods for adding or replacing values - * by name. The values can be any of these types: Boolean, - * JSONArray, JSONObject, Number, - * String, or the JSONObject.NULL object. A JSONObject - * constructor can be used to convert an external form JSON text into an - * internal form whose values can be retrieved with the get and - * opt methods, or to convert values into a JSON text using the - * put and toString methods. A get method - * returns a value if one can be found, and throws an exception if one cannot be - * found. An opt method returns a default value instead of throwing - * an exception, and so is useful for obtaining optional values. - *

- * The generic get() and opt() methods return an - * object, which you can cast or query for type. There are also typed - * get and opt methods that do type checking and type - * coercion for you. The opt methods differ from the get methods in that they do - * not throw. Instead, they return a specified value, such as null. - *

- * The put methods add or replace values in an object. For example, - * - *

- * myString = new JSONObject().put("JSON", "Hello, World!").toString();
- * 
- *

- * produces the string {"JSON": "Hello, World"}. - *

- * The texts produced by the toString methods strictly conform to - * the JSON syntax rules. The constructors are more forgiving in the texts they - * will accept: - *

    - *
  • An extra , (comma) may appear just - * before the closing brace.
  • - *
  • Strings may be quoted with ' (single - * quote).
  • - *
  • Strings do not need to be quoted at all if they do not begin with a quote - * or single quote, and if they do not contain leading or trailing spaces, and - * if they do not contain any of these characters: - * { } [ ] / \ : , # and if they do not look like numbers and if - * they are not the reserved words true, false, or - * null.
  • - *
- * - * @author JSON.org - * @version 2015-07-22 - */ -@SuppressWarnings("ALL") -public class JSONObject { - /** - * It is sometimes more convenient and less ambiguous to have a - * NULL object than to use Java's null value. - * JSONObject.NULL.equals(null) returns true. - * JSONObject.NULL.toString() returns "null". - */ - public static final Object NULL = new Null(); - /** - * The map where the JSONObject's properties are kept. - */ - private final LinkedHashMap map; - - /** - * Construct an empty JSONObject. - */ - public JSONObject() { - this.map = new LinkedHashMap<>(); - } - - /** - * Construct a JSONObject from a subset of another JSONObject. An array of - * strings is used to identify the keys that should be copied. Missing keys - * are ignored. - * - * @param jo - * A JSONObject. - * @param names - * An array of strings. - * @throws JSONException - * If a value is a non-finite number or if a name is - * duplicated. - */ - public JSONObject(JSONObject jo, String[] names) { - this(); - for(int i = 0; i < names.length; i += 1) { - try { - this.putOnce(names[i], jo.opt(names[i])); - } catch(Exception e) { - Iris.reportError(e); - } - } - } - - /** - * Construct a JSONObject from a JSONTokener. - * - * @param x - * A JSONTokener object containing the source string. - * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. - */ - public JSONObject(JSONTokener x) throws JSONException { - this(); - char c; - String key; - - if(x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for(; ; ) { - c = x.nextClean(); - switch(c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); - } - - // The key is followed by ':'. - - c = x.nextClean(); - if(c != ':') { - throw x.syntaxError("Expected a ':' after a key"); - } - this.putOnce(key, x.nextValue()); - - // Pairs are separated by ','. - - switch(x.nextClean()) { - case ';': - case ',': - if(x.nextClean() == '}') { - return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); - } - } - } - - /** - * Construct a JSONObject from a Map. - * - * @param map - * A map object that can be used to initialize the contents of - * the JSONObject. - */ - public JSONObject(Map map) { - this.map = new LinkedHashMap<>(); - if(map != null) { - Iterator> i = map.entrySet().iterator(); - while(i.hasNext()) { - Entry entry = i.next(); - Object value = entry.getValue(); - if(value != null) { - this.map.put(entry.getKey(), wrap(value)); - } - } - } - } - - /** - * Construct a JSONObject from an Object using bean getters. It reflects on - * all of the public methods of the object. For each of the methods with no - * parameters and a name starting with "get" or - * "is" followed by an uppercase letter, the method is invoked, - * and a key and the value returned from the getter method are put into the - * new JSONObject. - *

- * The key is formed by removing the "get" or "is" - * prefix. If the second remaining character is not upper case, then the - * first character is converted to lower case. - *

- * For example, if an object has a method named "getName", and - * if the result of calling object.getName() is - * "Larry Fine", then the JSONObject will contain - * "name": "Larry Fine". - * - * @param bean - * An object that has getter methods that should be used to make - * a JSONObject. - */ - public JSONObject(Object bean) { - this(); - this.populateMap(bean); - } - - /** - * Construct a JSONObject from an Object, using reflection to find the - * public members. The resulting JSONObject's keys will be the strings from - * the names array, and the values will be the field values associated with - * those keys in the object. If a key is not found or not visible, then it - * will not be copied into the new JSONObject. - * - * @param object - * An object that has fields that should be used to make a - * JSONObject. - * @param names - * An array of strings, the names of the fields to be obtained - * from the object. - */ - public JSONObject(Object object, String[] names) { - this(); - Class c = object.getClass(); - for(int i = 0; i < names.length; i += 1) { - String name = names[i]; - try { - this.putOpt(name, c.getField(name).get(object)); - } catch(Exception e) { - Iris.reportError(e); - } - } - } - - /** - * Construct a JSONObject from a source JSON text string. This is the most - * commonly used JSONObject constructor. - * - * @param source - * A string beginning with { (left - * brace) and ending with }   - * (right brace). - * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. - */ - public JSONObject(String source) throws JSONException { - this(new JSONTokener(source)); - } - - /** - * Construct a JSONObject from a ResourceBundle. - * - * @param baseName - * The ResourceBundle base name. - * @param locale - * The Locale to load the ResourceBundle for. - * @throws JSONException - * If any JSONExceptions are detected. - */ - public JSONObject(String baseName, Locale locale) throws JSONException { - this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); - - // Iterate through the keys in the bundle. - - Enumeration keys = bundle.getKeys(); - while(keys.hasMoreElements()) { - Object key = keys.nextElement(); - if(key != null) { - - // Go through the path, ensuring that there is a nested - // JSONObject for each - // segment except the last. Add the value using the last - // segment's name into - // the deepest nested JSONObject. - - String[] path = ((String) key).split("\\."); - int last = path.length - 1; - JSONObject target = this; - for(int i = 0; i < last; i += 1) { - String segment = path[i]; - JSONObject nextTarget = target.optJSONObject(segment); - if(nextTarget == null) { - nextTarget = new JSONObject(); - target.put(segment, nextTarget); - } - target = nextTarget; - } - target.put(path[last], bundle.getString((String) key)); - } - } - } - - /** - * Produce a string from a double. The string "null" will be returned if the - * number is not finite. - * - * @param d - * A double. - * @return A String. - */ - public static String doubleToString(double d) { - if(Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } - - // Shave off trailing zeros and decimal point, if possible. - - String string = Double.toString(d); - if(string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { - while(string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if(string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - /** - * Get an array of field names from a JSONObject. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(JSONObject jo) { - int length = jo.length(); - if(length == 0) { - return null; - } - Iterator iterator = jo.keys(); - String[] names = new String[length]; - int i = 0; - while(iterator.hasNext()) { - names[i] = iterator.next(); - i += 1; - } - return names; - } - - /** - * Get an array of field names from an Object. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(Object object) { - if(object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if(length == 0) { - return null; - } - String[] names = new String[length]; - for(int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - - /** - * Produce a string from a Number. - * - * @param number - * A Number - * @return A String. - * @throws JSONException - * If n is a non-finite number. - */ - public static String numberToString(Number number) throws JSONException { - if(number == null) { - throw new JSONException("Null pointer"); - } - testValidity(number); - - // Shave off trailing zeros and decimal point, if possible. - - String string = number.toString(); - if(string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { - while(string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if(string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - /** - * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { - w.write("\\u"); - hhhh = Integer.toHexString(c); - w.write("0000", 0, 4 - hhhh.length()); - w.write(hhhh); - } else { - w.write(c); - } - } - } - w.write('"'); - return w; - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * - * @param string - * A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) { - Double d; - if(string.equals("")) { - return string; - } - if(string.equalsIgnoreCase("true")) { - return Boolean.TRUE; - } - if(string.equalsIgnoreCase("false")) { - return Boolean.FALSE; - } - if(string.equalsIgnoreCase("null")) { - return JSONObject.NULL; - } - - /* - * If it might be a number, try converting it. If a number cannot be - * produced, then the value will just be a string. - */ - - char b = string.charAt(0); - if((b >= '0' && b <= '9') || b == '-') { - try { - if(string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) { - d = Double.valueOf(string); - if(!d.isInfinite() && !d.isNaN()) { - return d; - } - } else { - Long myLong = Long.valueOf(string); - if(string.equals(myLong.toString())) { - if(myLong == myLong.intValue()) { - return myLong.intValue(); - } else { - return myLong; - } - } - } - } catch(Exception e) { - Iris.reportError(e); - } - } - return string; - } - - /** - * Throw an exception if the object is a NaN or infinite number. - * - * @param o - * The object to test. - * @throws JSONException - * If o is a non-finite number. - */ - public static void testValidity(Object o) throws JSONException { - if(o != null) { - if(o instanceof Double) { - if(((Double) o).isInfinite() || ((Double) o).isNaN()) { - throw new JSONException("JSON does not allow non-finite numbers."); - } - } else if(o instanceof Float) { - if(((Float) o).isInfinite() || ((Float) o).isNaN()) { - throw new JSONException("JSON does not allow non-finite numbers."); - } - } - } - } - - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce the - * JSON text. The method is required to produce a strictly conforming text. - * If the object does not contain a toJSONString method (which is the most - * common case), then a text will be produced by other means. If the value - * is an array or Collection, then a JSONArray will be made from it and its - * toJSONString method will be called. If the value is a MAP, then a - * JSONObject will be made from it and its toJSONString method will be - * called. Otherwise, the value's toString method will be called, and the - * result will be quoted. - * - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param value - * The value to be serialized. - * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. - */ - public static String valueToString(Object value) throws JSONException { - if(value == null || value.equals(null)) { - return "null"; - } - if(value instanceof JSONString) { - Object object; - try { - object = ((JSONString) value).toJSONString(); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException(e); - } - if(object instanceof String) { - return (String) object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - if(value instanceof Number) { - return numberToString((Number) value); - } - if(value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { - return value.toString(); - } - if(value instanceof Map) { - @SuppressWarnings("unchecked") - Map map = (Map) value; - return new JSONObject(map).toString(); - } - if(value instanceof Collection) { - @SuppressWarnings("unchecked") - Collection coll = (Collection) value; - return new JSONArray(coll).toString(); - } - if(value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - return quote(value.toString()); - } - - /** - * Wrap an object, if necessary. If the object is null, return the NULL - * object. If it is an array or collection, wrap it in a JSONArray. If it is - * a map, wrap it in a JSONObject. If it is a standard property (Double, - * String, et al) then it is already wrapped. Otherwise, if it comes from - * one of the java packages, turn it into a string. And if it doesn't, try - * to wrap it in a JSONObject. If the wrapping fails, then null is returned. - * - * @param object - * The object to wrap - * @return The wrapped value - */ - public static Object wrap(Object object) { - try { - if(object == null) { - return NULL; - } - if(object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String || object instanceof BigInteger || object instanceof BigDecimal) { - return object; - } - - if(object instanceof Collection) { - @SuppressWarnings("unchecked") - Collection coll = (Collection) object; - return new JSONArray(coll); - } - if(object.getClass().isArray()) { - return new JSONArray(object); - } - if(object instanceof Map) { - @SuppressWarnings("unchecked") - Map map = (Map) object; - return new JSONObject(map); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; - if(objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null) { - return object.toString(); - } - return new JSONObject(object); - } catch(Exception e) { - Iris.reportError(e); - return null; - } - } - - static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException { - if(value == null || value.equals(null)) { - writer.write("null"); - } else if(value instanceof JSONObject) { - ((JSONObject) value).write(writer, indentFactor, indent); - } else if(value instanceof JSONArray) { - ((JSONArray) value).write(writer, indentFactor, indent); - } else if(value instanceof Map) { - @SuppressWarnings("unchecked") - Map map = (Map) value; - new JSONObject(map).write(writer, indentFactor, indent); - } else if(value instanceof Collection) { - @SuppressWarnings("unchecked") - Collection coll = (Collection) value; - new JSONArray(coll).write(writer, indentFactor, indent); - } else if(value.getClass().isArray()) { - new JSONArray(value).write(writer, indentFactor, indent); - } else if(value instanceof Number) { - writer.write(numberToString((Number) value)); - } else if(value instanceof Boolean) { - writer.write(value.toString()); - } else if(value instanceof JSONString) { - Object o; - try { - o = ((JSONString) value).toJSONString(); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : quote(value.toString())); - } else { - quote(value.toString(), writer); - } - return writer; - } - - static final void indent(Writer writer, int indent) throws IOException { - for(int i = 0; i < indent; i += 1) { - writer.write(' '); - } - } - - /** - * Accumulate values under a key. It is similar to the put method except - * that if there is already an object stored under the key then a JSONArray - * is stored under the key to hold all of the accumulated values. If there - * is already a JSONArray, then the new value is appended to it. In - * contrast, the put method replaces the previous value. - *

- * If only one value is accumulated that is not a JSONArray, then the result - * will be the same as using put. But if multiple values are accumulated, - * then the result will be like append. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is an invalid number or if the key is null. - */ - public JSONObject accumulate(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if(object == null) { - this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); - } else if(object instanceof JSONArray) { - ((JSONArray) object).put(value); - } else { - this.put(key, new JSONArray().put(object).put(value)); - } - return this; - } - - /** - * Append values to the array under a key. If the key does not exist in the - * JSONObject, then the key is put in the JSONObject with its value being a - * JSONArray containing the value parameter. If the key was already - * associated with a JSONArray, then the value parameter is appended to it. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the key is null or if the current value associated with - * the key is not a JSONArray. - */ - public JSONObject append(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if(object == null) { - this.put(key, new JSONArray().put(value)); - } else if(object instanceof JSONArray) { - this.put(key, ((JSONArray) object).put(value)); - } else { - throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); - } - return this; - } - - /** - * Get the value object associated with a key. - * - * @param key - * A key string. - * @return The object associated with the key. - * @throws JSONException - * if the key is not found. - */ - public Object get(String key) throws JSONException { - if(key == null) { - throw new JSONException("Null key."); - } - Object object = this.opt(key); - if(object == null) { - throw new JSONException("JSONObject[" + quote(key) + "] not found."); - } - return object; - } - - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ - public > E getEnum(Class clazz, String key) throws JSONException { - E val = optEnum(clazz, key); - if(val == null) { - // JSONException should really take a throwable argument. - // If it did, I would re-implement this with the Enum.valueOf - // method and place any thrown exception in the JSONException - throw new JSONException("JSONObject[" + quote(key) + "] is not an enum of type " + quote(clazz.getSimpleName()) + "."); - } - return val; - } - - /** - * Get the boolean value associated with a key. - * - * @param key - * A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or - * "false". - */ - public boolean getBoolean(String key) throws JSONException { - Object object = this.get(key); - if(object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) { - return false; - } else if(object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); - } - - /** - * Get the BigInteger value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to BigInteger. - */ - public BigInteger getBigInteger(String key) throws JSONException { - Object object = this.get(key); - try { - return new BigInteger(object.toString()); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigInteger."); - } - } - - /** - * Get the BigDecimal value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to BigDecimal. - */ - public BigDecimal getBigDecimal(String key) throws JSONException { - Object object = this.get(key); - try { - return new BigDecimal(object.toString()); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigDecimal."); - } - } - - /** - * Get the double value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public double getDouble(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); - } - } - - /** - * Get the int value associated with a key. - * - * @param key - * A key string. - * @return The integer value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an integer. - */ - public int getInt(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); - } - } - - /** - * Get the JSONArray value associated with a key. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException { - Object object = this.get(key); - if(object instanceof JSONArray) { - return (JSONArray) object; - } - throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); - } - - /** - * Get the JSONObject value associated with a key. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException { - Object object = this.get(key); - if(object instanceof JSONObject) { - return (JSONObject) object; - } - throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); - } - - /** - * Get the long value associated with a key. - * - * @param key - * A key string. - * @return The long value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to a long. - */ - public long getLong(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); - } catch(Exception e) { - Iris.reportError(e); - throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); - } - } - - /** - * Get the string associated with a key. - * - * @param key - * A key string. - * @return A string which is the value. - * @throws JSONException - * if there is no string value for the key. - */ - public String getString(String key) throws JSONException { - Object object = this.get(key); - if(object instanceof String) { - return (String) object; - } - throw new JSONException("JSONObject[" + quote(key) + "] not a string."); - } - - /** - * Determine if the JSONObject contains a specific key. - * - * @param key - * A key string. - * @return true if the key exists in the JSONObject. - */ - public boolean has(String key) { - return this.map.containsKey(key); - } - - /** - * Increment a property of a JSONObject. If there is no such property, - * create one with a value of 1. If there is such a property, and if it is - * an Integer, Long, Double, or Float, then add one to it. - * - * @param key - * A key string. - * @return this. - * @throws JSONException - * If there is already a property with this name that is not an - * Integer, Long, Double, or Float. - */ - public JSONObject increment(String key) throws JSONException { - Object value = this.opt(key); - if(value == null) { - this.put(key, 1); - } else if(value instanceof BigInteger) { - this.put(key, ((BigInteger) value).add(BigInteger.ONE)); - } else if(value instanceof BigDecimal) { - this.put(key, ((BigDecimal) value).add(BigDecimal.ONE)); - } else if(value instanceof Integer) { - this.put(key, (Integer) value + 1); - } else if(value instanceof Long) { - this.put(key, (Long) value + 1); - } else if(value instanceof Double) { - this.put(key, (Double) value + 1); - } else if(value instanceof Float) { - this.put(key, (Float) value + 1); - } else { - throw new JSONException("Unable to increment [" + quote(key) + "]."); - } - return this; - } - - /** - * Determine if the value associated with the key is null or if there is no - * value. - * - * @param key - * A key string. - * @return true if there is no value associated with the key or if the value - * is the JSONObject.NULL object. - */ - public boolean isNull(String key) { - return JSONObject.NULL.equals(this.opt(key)); - } - - /** - * Get an enumeration of the keys of the JSONObject. - * - * @return An iterator of the keys. - */ - public Iterator keys() { - return this.keySet().iterator(); - } - - /** - * Get a set of keys of the JSONObject. - * - * @return A keySet. - */ - public Set keySet() { - return this.map.keySet(); - } - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() { - return this.map.size(); - } - - /** - * Produce a JSONArray containing the names of the elements of this - * JSONObject. - * - * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. - */ - public JSONArray names() { - JSONArray ja = new JSONArray(); - Iterator keys = this.keys(); - while(keys.hasNext()) { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; - } - - /** - * Get an optional value associated with a key. - * - * @param key - * A key string. - * @return An object which is the value, or null if there is no value. - */ - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key or null if not found - */ - public > E optEnum(Class clazz, String key) { - return this.optEnum(clazz, key, null); - } - - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @param defaultValue - * The default in case the value is not found - * @return The enum value associated with the key or defaultValue if the - * value is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, String key, E defaultValue) { - try { - Object val = this.opt(key); - if(NULL.equals(val)) { - return defaultValue; - } - if(clazz.isAssignableFrom(val.getClass())) { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } catch(IllegalArgumentException e) { - Iris.reportError(e); - return defaultValue; - } catch(NullPointerException e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get an optional boolean associated with a key. It returns false if there - * is no such key, or if the value is not Boolean.TRUE or the String "true". - * - * @param key - * A key string. - * @return The truth. - */ - public boolean optBoolean(String key) { - return this.optBoolean(key, false); - } - - /** - * Get an optional boolean associated with a key. It returns the - * defaultValue if there is no such key, or if it is not a Boolean or the - * String "true" or "false" (case insensitive). - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) { - try { - return this.getBoolean(key); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get an optional double associated with a key, or NaN if there is no such - * key or if its value is not a number. If the value is a string, an attempt - * will be made to evaluate it as a number. - * - * @param key - * A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return this.optDouble(key, Double.NaN); - } - - /** - * Get an optional BigInteger associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigInteger optBigInteger(String key, BigInteger defaultValue) { - try { - return this.getBigInteger(key); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get an optional BigDecimal associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { - try { - return this.getBigDecimal(key); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get an optional double associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) { - try { - return this.getDouble(key); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get an optional int value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public int optInt(String key) { - return this.optInt(key, 0); - } - - /** - * Get an optional int value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) { - try { - return this.getInt(key); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get an optional JSONArray associated with a key. It returns null if there - * is no such key, or if its value is not a JSONArray. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) { - Object o = this.opt(key); - return o instanceof JSONArray ? (JSONArray) o : null; - } - - /** - * Get an optional JSONObject associated with a key. It returns null if - * there is no such key, or if its value is not a JSONObject. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - */ - public JSONObject optJSONObject(String key) { - Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject) object : null; - } - - /** - * Get an optional long value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public long optLong(String key) { - return this.optLong(key, 0); - } - - /** - * Get an optional long value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) { - try { - return this.getLong(key); - } catch(Exception e) { - Iris.reportError(e); - return defaultValue; - } - } - - /** - * Get an optional string associated with a key. It returns an empty string - * if there is no such key. If the value is not a string and is not null, - * then it is converted to a string. - * - * @param key - * A key string. - * @return A string which is the value. - */ - public String optString(String key) { - return this.optString(key, ""); - } - - /** - * Get an optional string associated with a key. It returns the defaultValue - * if there is no such key. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) { - Object object = this.opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); - } - - private void populateMap(Object bean) { - Class klass = bean.getClass(); - - // If klass is a System class then set includeSuperClass to false. - - boolean includeSuperClass = klass.getClassLoader() != null; - - Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); - for(int i = 0; i < methods.length; i += 1) { - try { - Method method = methods[i]; - if(Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); - String key = ""; - if(name.startsWith("get")) { - if("getClass".equals(name) || "getDeclaringClass".equals(name)) { - key = ""; - } else { - key = name.substring(3); - } - } else if(name.startsWith("is")) { - key = name.substring(2); - } - if(key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { - if(key.length() == 1) { - key = key.toLowerCase(); - } else if(!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() + key.substring(1); - } - - Object result = method.invoke(bean, (Object[]) null); - if(result != null) { - this.map.put(key, wrap(result)); - } - } - } - } catch(Exception e) { - Iris.reportError(e); - } - } - } - - /** - * Put a key/boolean pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A boolean which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, boolean value) throws JSONException { - this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONArray which is produced from a Collection. - * - * @param key - * A key string. - * @param value - * A Collection value. - * @return this. - */ - public JSONObject put(String key, Collection value) throws JSONException { - this.put(key, new JSONArray(value)); - return this; - } - - /** - * Put a key/double pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A double which is the value. - * @return this. - * @throws JSONException - * If the key is null or if the number is invalid. - */ - public JSONObject put(String key, double value) throws JSONException { - this.put(key, Double.valueOf(value)); - return this; - } - - /** - * Put a key/int pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * An int which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, int value) throws JSONException { - this.put(key, Integer.valueOf(value)); - return this; - } - - /** - * Put a key/long pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A long which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, long value) throws JSONException { - this.put(key, Long.valueOf(value)); - return this; - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONObject which is produced from a Map. - * - * @param key - * A key string. - * @param value - * A Map value. - * @return this. - */ - public JSONObject put(String key, Map value) throws JSONException { - this.put(key, new JSONObject(value)); - return this; - } - - /** - * Put a key/value pair in the JSONObject. If the value is null, then the - * key will be removed from the JSONObject if it is present. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is non-finite number or if the key is null. - */ - public JSONObject put(String key, Object value) throws JSONException { - if(key == null) { - throw new NullPointerException("Null key."); - } - if(value != null) { - testValidity(value); - this.map.put(key, value); - } else { - this.remove(key); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null, and only if there is not already a member with that - * name. - * - * @param key - * string - * @param value - * object - * @return this. - * @throws JSONException - * if the key is a duplicate - */ - public JSONObject putOnce(String key, Object value) throws JSONException { - if(key != null && value != null) { - if(this.opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - this.put(key, value); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is a non-finite number. - */ - public JSONObject putOpt(String key, Object value) throws JSONException { - if(key != null && value != null) { - this.put(key, value); - } - return this; - } - - /** - * Remove a name and its value, if present. - * - * @param key - * The name to be removed. - * @return The value that was associated with the name, or null if there was - * no value. - */ - public Object remove(String key) { - return this.map.remove(key); - } - - /** - * Determine if two JSONObjects are similar. They must contain the same set - * of names which must be associated with similar values. - * - * @param other - * The other JSONObject - * @return true if they are equal - */ - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean similar(Object other) { - try { - if(!(other instanceof JSONObject)) { - return false; - } - Set set = this.keySet(); - if(!set.equals(((JSONObject) other).keySet())) { - return false; - } - Iterator iterator = set.iterator(); - while(iterator.hasNext()) { - String name = iterator.next(); - Object valueThis = this.get(name); - Object valueOther = ((JSONObject) other).get(name); - if(valueThis instanceof JSONObject) { - if(!((JSONObject) valueThis).similar(valueOther)) { - return false; - } - } else if(valueThis instanceof JSONArray) { - if(!((JSONArray) valueThis).similar(valueOther)) { - return false; - } - } else if(!valueThis.equals(valueOther)) { - return false; - } - } - return true; - } catch(Throwable e) { - Iris.reportError(e); - return false; - } - } - - /** - * Produce a JSONArray containing the values of the members of this - * JSONObject. - * - * @param names - * A JSONArray containing a list of key strings. This determines - * the sequence of the values in the result. - * @return A JSONArray of values. - * @throws JSONException - * If any of the values are non-finite numbers. - */ - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if(names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for(int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace is - * added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - */ - public String toString() { - try { - return this.toString(0); - } catch(Exception e) { - Iris.reportError(e); - return null; - } - } - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the object contains an invalid number. - */ - public String toString(int indentFactor) throws JSONException { - StringWriter w = new StringWriter(); - synchronized(w.getBuffer()) { - return this.write(w, indentFactor, 0).toString(); - } - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - */ - Writer write(Writer writer, int indentFactor, int indent) throws JSONException { - try { - boolean commanate = false; - final int length = this.length(); - Iterator keys = this.keys(); - writer.write('{'); - - if(length == 1) { - Object key = keys.next(); - writer.write(quote(key.toString())); - writer.write(':'); - if(indentFactor > 0) { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, indent); - } else if(length != 0) { - final int newindent = indent + indentFactor; - while(keys.hasNext()) { - Object key = keys.next(); - if(commanate) { - writer.write(','); - } - if(indentFactor > 0) { - writer.write('\n'); - } - indent(writer, newindent); - writer.write(quote(key.toString())); - writer.write(':'); - if(indentFactor > 0) { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, newindent); - commanate = true; - } - if(indentFactor > 0) { - writer.write('\n'); - } - indent(writer, indent); - } - writer.write('}'); - return writer; - } catch(IOException e) { - Iris.reportError(e); - throw new JSONException(e); - } - } - - /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. - */ - private static final class Null { - - /** - * There is only intended to be a single instance of the NULL object, so - * the clone method returns itself. - * - * @return NULL. - */ - @Override - protected final Object clone() { - return this; - } - - /** - * A Null object is equal to the null value and to itself. - * - * @param object - * An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object or - * null. - */ - @Override - public boolean equals(Object object) { - return object == null || object == this; - } - - /** - * Get the "null" string value. - * - * @return The string "null". - */ - public String toString() { - return "null"; - } - } -} diff --git a/src/main/java/com/volmit/iris/util/json/JSONString.java b/src/main/java/com/volmit/iris/util/json/JSONString.java deleted file mode 100644 index 0facad9fa..000000000 --- a/src/main/java/com/volmit/iris/util/json/JSONString.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -/** - * The JSONString interface allows a toJSONString() - * method so that a class can change the behavior of - * JSONObject.toString(), JSONArray.toString(), and - * JSONWriter.value(Object). The - * toJSONString method will be used instead of the default behavior - * of using the Object's toString() method and quoting the result. - */ -public interface JSONString { - /** - * The toJSONString method allows a class to produce its own - * JSON serialization. - * - * @return A strictly syntactically correct JSON text. - */ - String toJSONString(); -} diff --git a/src/main/java/com/volmit/iris/util/json/JSONStringer.java b/src/main/java/com/volmit/iris/util/json/JSONStringer.java deleted file mode 100644 index a9ab7ed27..000000000 --- a/src/main/java/com/volmit/iris/util/json/JSONStringer.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -import java.io.StringWriter; - -/** - * JSONStringer provides a quick and convenient way of producing JSON text. The - * texts produced strictly conform to JSON syntax rules. No whitespace is added, - * so the results are ready for transmission or storage. Each instance of - * JSONStringer can produce one JSON text. - *

- * A JSONStringer instance provides a value method for appending - * values to the text, and a key method for adding keys before - * values in objects. There are array and endArray - * methods that make and bound array values, and object and - * endObject methods which make and bound object values. All of - * these methods return the JSONWriter instance, permitting cascade style. For - * example, - * - *

- * myString = new JSONStringer().object().key("JSON").value("Hello, World!").endObject().toString();
- * 
- *

- * which produces the string - * - *

- * {"JSON":"Hello, World!"}
- * 
- *

- * The first method called must be array or object. - * There are no methods for adding commas or colons. JSONStringer adds them for - * you. Objects and arrays can be nested up to 20 levels deep. - *

- * This can sometimes be easier than using a JSONObject to build a string. - * - * @author JSON.org - * @version 2008-09-18 - */ -public class JSONStringer extends JSONWriter { - /** - * Make a fresh JSONStringer. It can be used to build one JSON text. - */ - public JSONStringer() { - super(new StringWriter()); - } - - /** - * Return the JSON text. This method is used to obtain the product of the - * JSONStringer instance. It will return null if there was a - * problem in the construction of the JSON text (such as the calls to - * array were not properly balanced with calls to - * endArray). - * - * @return The JSON text. - */ - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; - } -} diff --git a/src/main/java/com/volmit/iris/util/json/JSONTokener.java b/src/main/java/com/volmit/iris/util/json/JSONTokener.java deleted file mode 100644 index 14a57dd7a..000000000 --- a/src/main/java/com/volmit/iris/util/json/JSONTokener.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -import com.volmit.iris.Iris; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; - -/** - * A JSONTokener takes a source string and extracts characters and tokens from - * it. It is used by the JSONObject and JSONArray constructors to parse JSON - * source strings. - * - * @author JSON.org - * @version 2014-05-03 - */ -@SuppressWarnings("ALL") -public class JSONTokener { - - private final Reader reader; - private long character; - private boolean eof; - private long index; - private long line; - private char previous; - private boolean usePrevious; - - /** - * Construct a JSONTokener from a Reader. - * - * @param reader - * A reader. - */ - public JSONTokener(Reader reader) { - this.reader = reader.markSupported() ? reader : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.line = 1; - } - - /** - * Construct a JSONTokener from an InputStream. - * - * @param inputStream - * The source. - */ - public JSONTokener(InputStream inputStream) throws JSONException { - this(new InputStreamReader(inputStream)); - } - - /** - * Construct a JSONTokener from a string. - * - * @param s - * A source string. - */ - public JSONTokener(String s) { - this(new StringReader(s)); - } - - /** - * Get the hex value of a character (base16). - * - * @param c - * A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. - */ - public static int dehexchar(char c) { - if(c >= '0' && c <= '9') { - return c - '0'; - } - if(c >= 'A' && c <= 'F') { - return c - ('A' - 10); - } - if(c >= 'a' && c <= 'f') { - return c - ('a' - 10); - } - return -1; - } - - /** - * Back up one character. This provides a sort of lookahead capability, so - * that you can test for a digit or letter before attempting to parse the - * next number or identifier. - */ - public void back() throws JSONException { - if(this.usePrevious || this.index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.index -= 1; - this.character -= 1; - this.usePrevious = true; - this.eof = false; - } - - public boolean end() { - return this.eof && !this.usePrevious; - } - - /** - * Determine if the source string still contains characters that next() can - * consume. - * - * @return true if not yet at the end of the source. - */ - public boolean more() throws JSONException { - this.next(); - if(this.end()) { - return false; - } - this.back(); - return true; - } - - /** - * Get the next character in the source string. - * - * @return The next character, or 0 if past the end of the source string. - */ - public char next() throws JSONException { - int c; - if(this.usePrevious) { - this.usePrevious = false; - c = this.previous; - } else { - try { - c = this.reader.read(); - } catch(IOException e) { - Iris.reportError(e); - throw new JSONException(e); - } - - if(c <= 0) { // End of stream - this.eof = true; - c = 0; - } - } - this.index += 1; - if(this.previous == '\r') { - this.line += 1; - this.character = c == '\n' ? 0 : 1; - } else if(c == '\n') { - this.line += 1; - this.character = 0; - } else { - this.character += 1; - } - this.previous = (char) c; - return this.previous; - } - - /** - * Consume the next character, and check that it matches a specified - * character. - * - * @param c - * The character to match. - * @return The character. - * @throws JSONException - * if the character does not match. - */ - public char next(char c) throws JSONException { - char n = this.next(); - if(n != c) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); - } - return n; - } - - /** - * Get the next n characters. - * - * @param n - * The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not n characters - * remaining in the source string. - */ - public String next(int n) throws JSONException { - if(n == 0) { - return ""; - } - - char[] chars = new char[n]; - int pos = 0; - - while(pos < n) { - chars[pos] = this.next(); - if(this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } - - /** - * Get the next char in the string, skipping whitespace. - * - * @return A character, or 0 if there are no more characters. - */ - public char nextClean() throws JSONException { - for(; ; ) { - char c = this.next(); - if(c == 0 || c > ' ') { - return c; - } - } - } - - /** - * Return the characters up to the next close quote character. Backslash - * processing is done. The formal JSON format does not allow strings in - * single quotes, but an implementation is allowed to accept them. - * - * @param quote - * The quoting character, either "  - * (double quote) or '  - * (single quote). - * @return A String. - * @throws JSONException - * Unterminated string. - */ - public String nextString(char quote) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for(; ; ) { - c = this.next(); - switch(c) { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch(c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - sb.append((char) Integer.parseInt(this.next(4), 16)); - break; - case '"': - case '\'': - case '\\': - case '/': - sb.append(c); - break; - default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if(c == quote) { - return sb.toString(); - } - sb.append(c); - } - } - } - - /** - * Get the text up but not including the specified character or the end of - * line, whichever comes first. - * - * @param delimiter - * A delimiter character. - * @return A string. - */ - public String nextTo(char delimiter) throws JSONException { - StringBuilder sb = new StringBuilder(); - for(; ; ) { - char c = this.next(); - if(c == delimiter || c == 0 || c == '\n' || c == '\r') { - if(c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - /** - * Get the text up but not including one of the specified delimiter - * characters or the end of line, whichever comes first. - * - * @param delimiters - * A set of delimiter characters. - * @return A string, trimmed. - */ - public String nextTo(String delimiters) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for(; ; ) { - c = this.next(); - if(delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { - if(c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - /** - * Get the next value. The value can be a Boolean, Double, Integer, - * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * - * @return An object. - * @throws JSONException - * If syntax error. - */ - public Object nextValue() throws JSONException { - char c = this.nextClean(); - String string; - - switch(c) { - case '"': - case '\'': - return this.nextString(c); - case '{': - this.back(); - return new JSONObject(this); - case '[': - this.back(); - return new JSONArray(this); - } - - /* - * Handle unquoted text. This could be the values true, false, or null, - * or it can be a number. An implementation (such as this one) is - * allowed to also accept non-standard forms. - * - * Accumulate characters until we reach the end of the text or a - * formatting character. - */ - - StringBuilder sb = new StringBuilder(); - while(c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { - sb.append(c); - c = this.next(); - } - this.back(); - - string = sb.toString().trim(); - if("".equals(string)) { - throw this.syntaxError("Missing value"); - } - return JSONObject.stringToValue(string); - } - - /** - * Skip characters until the next character is the requested character. If - * the requested character is not found, no characters are skipped. - * - * @param to - * A character to skip to. - * @return The requested character, or zero if the requested character is - * not found. - */ - public char skipTo(char to) throws JSONException { - char c; - try { - long startIndex = this.index; - long startCharacter = this.character; - long startLine = this.line; - this.reader.mark(1000000); - do { - c = this.next(); - if(c == 0) { - this.reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; - return c; - } - } while(c != to); - } catch(IOException e) { - Iris.reportError(e); - throw new JSONException(e); - } - this.back(); - return c; - } - - /** - * Make a JSONException to signal a syntax error. - * - * @param message - * The error message. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message) { - return new JSONException(message + this); - } - - /** - * Make a printable string of this JSONTokener. - * - * @return " at {index} [character {character} line {line}]" - */ - public String toString() { - return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; - } -} diff --git a/src/main/java/com/volmit/iris/util/json/JSONWriter.java b/src/main/java/com/volmit/iris/util/json/JSONWriter.java deleted file mode 100644 index affb1e65e..000000000 --- a/src/main/java/com/volmit/iris/util/json/JSONWriter.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -import com.volmit.iris.Iris; - -import java.io.IOException; -import java.io.Writer; - -/** - * JSONWriter provides a quick and convenient way of producing JSON text. The - * texts produced strictly conform to JSON syntax rules. No whitespace is added, - * so the results are ready for transmission or storage. Each instance of - * JSONWriter can produce one JSON text. - *

- * A JSONWriter instance provides a value method for appending - * values to the text, and a key method for adding keys before - * values in objects. There are array and endArray - * methods that make and bound array values, and object and - * endObject methods which make and bound object values. All of - * these methods return the JSONWriter instance, permitting a cascade style. For - * example, - * - *

- * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
- * 
- *

- * which writes - * - *

- * {"JSON":"Hello, World!"}
- * 
- *

- * The first method called must be array or object. - * There are no methods for adding commas or colons. JSONWriter adds them for - * you. Objects and arrays can be nested up to 20 levels deep. - *

- * This can sometimes be easier than using a JSONObject to build a string. - * - * @author JSON.org - * @version 2011-11-24 - */ -public class JSONWriter { - private static final int maxdepth = 200; - /** - * The writer that will receive the output. - */ - protected final Writer writer; - /** - * The object/array stack. - */ - private final JSONObject[] stack; - /** - * The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k' - * (key), 'o' (object). - */ - protected char mode; - /** - * The comma flag determines if a comma should be output before the next - * value. - */ - private boolean comma; - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; - - /** - * Make a fresh JSONWriter. It can be used to build one JSON text. - */ - public JSONWriter(Writer w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } - - /** - * Append a value. - * - * @param string - * A string value. - * @return this - * @throws JSONException - * If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException { - if(string == null) { - throw new JSONException("Null pointer"); - } - if(this.mode == 'o' || this.mode == 'a') { - try { - if(this.comma && this.mode == 'a') { - this.writer.write(','); - } - this.writer.write(string); - } catch(IOException e) { - Iris.reportError(e); - throw new JSONException(e); - } - if(this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } - - /** - * Begin appending a new array. All values until the balancing - * endArray will be appended to this array. The - * endArray method must be called to mark the array's end. - * - * @return this - * @throws JSONException - * If the nesting is too deep, or if the object is started in - * the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException { - if(this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } - - /** - * End something. - * - * @param mode - * Mode - * @param c - * Closing character - * @return this - * @throws JSONException - * If unbalanced. - */ - private JSONWriter end(char mode, char c) throws JSONException { - if(this.mode != mode) { - throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); - } - this.pop(mode); - try { - this.writer.write(c); - } catch(IOException e) { - Iris.reportError(e); - throw new JSONException(e); - } - this.comma = true; - return this; - } - - /** - * End an array. This method most be called to balance calls to - * array. - * - * @return this - * @throws JSONException - * If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } - - /** - * End an object. This method most be called to balance calls to - * object. - * - * @return this - * @throws JSONException - * If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); - } - - /** - * Append a key. The key will be associated with the next value. In an - * object, every value must be preceded by a key. - * - * @param string - * A key string. - * @return this - * @throws JSONException - * If the key is out of place. For example, keys do not belong - * in arrays or if the key is null. - */ - public JSONWriter key(String string) throws JSONException { - if(string == null) { - throw new JSONException("Null key."); - } - if(this.mode == 'k') { - try { - this.stack[this.top - 1].putOnce(string, Boolean.TRUE); - if(this.comma) { - this.writer.write(','); - } - this.writer.write(JSONObject.quote(string)); - this.writer.write(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch(IOException e) { - Iris.reportError(e); - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } - - /** - * Begin appending a new object. All keys and values until the balancing - * endObject will be appended to this object. The - * endObject method must be called to mark the object's end. - * - * @return this - * @throws JSONException - * If the nesting is too deep, or if the object is started in - * the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException { - if(this.mode == 'i') { - this.mode = 'o'; - } - if(this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); - - } - - /** - * Pop an array or object scope. - * - * @param c - * The scope to close. - * @throws JSONException - * If nesting is wrong. - */ - private void pop(char c) throws JSONException { - if(this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if(m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; - } - - /** - * Push an array or object scope. - * - * @param jo - * The scope to open. - * @throws JSONException - * If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException { - if(this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } - - /** - * Append either the value true or the value false - * . - * - * @param b - * A boolean. - * @return this - */ - public JSONWriter value(boolean b) throws JSONException { - return this.append(b ? "true" : "false"); - } - - /** - * Append a double value. - * - * @param d - * A double. - * @return this - * @throws JSONException - * If the number is not finite. - */ - public JSONWriter value(double d) throws JSONException { - return this.value(Double.valueOf(d)); - } - - /** - * Append a long value. - * - * @param l - * A long. - * @return this - */ - public JSONWriter value(long l) throws JSONException { - return this.append(Long.toString(l)); - } - - /** - * Append an object value. - * - * @param object - * The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements - * JSONString. - * @return this - * @throws JSONException - * If the value is out of sequence. - */ - public JSONWriter value(Object object) throws JSONException { - return this.append(JSONObject.valueToString(object)); - } -} diff --git a/src/main/java/com/volmit/iris/util/json/XML.java b/src/main/java/com/volmit/iris/util/json/XML.java deleted file mode 100644 index 510ae034c..000000000 --- a/src/main/java/com/volmit/iris/util/json/XML.java +++ /dev/null @@ -1,499 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -import com.volmit.iris.Iris; - -import java.util.Iterator; - -/** - * This provides static methods to convert an XML text into a JSONObject, and to - * covert a JSONObject into an XML text. - * - * @author JSON.org - * @version 2014-05-03 - */ -public class XML { - - /** - * The Character '&'. - */ - public static final Character AMP = '&'; - - /** - * The Character '''. - */ - public static final Character APOS = '\''; - - /** - * The Character '!'. - */ - public static final Character BANG = '!'; - - /** - * The Character '='. - */ - public static final Character EQ = '='; - - /** - * The Character '>'. - */ - public static final Character GT = '>'; - - /** - * The Character '<'. - */ - public static final Character LT = '<'; - - /** - * The Character '?'. - */ - public static final Character QUEST = '?'; - - /** - * The Character '"'. - */ - public static final Character QUOT = '"'; - - /** - * The Character '/'. - */ - public static final Character SLASH = '/'; - - /** - * Replace special characters with XML escapes: - * - *

-     * & (ampersand) is replaced by &amp;
-     * < (less than) is replaced by &lt;
-     * > (greater than) is replaced by &gt;
-     * " (double quote) is replaced by &quot;
-     * 
- * - * @param string - * The string to be escaped. - * @return The escaped string. - */ - public static String escape(String string) { - StringBuilder sb = new StringBuilder(string.length()); - for(int i = 0, length = string.length(); i < length; i++) { - char c = string.charAt(i); - switch(c) { - case '&' -> sb.append("&"); - case '<' -> sb.append("<"); - case '>' -> sb.append(">"); - case '"' -> sb.append("""); - case '\'' -> sb.append("'"); - default -> sb.append(c); - } - } - return sb.toString(); - } - - /** - * Throw an exception if the string contains whitespace. Whitespace is not - * allowed in tagNames and attributes. - * - * @param string - * A string. - */ - public static void noSpace(String string) throws JSONException { - int i, length = string.length(); - if(length == 0) { - throw new JSONException("Empty string."); - } - for(i = 0; i < length; i += 1) { - if(Character.isWhitespace(string.charAt(i))) { - throw new JSONException("'" + string + "' contains a space character."); - } - } - } - - /** - * Scan the content following the named tag, attaching it to the context. - * - * @param x - * The XMLTokener containing the source string. - * @param context - * The JSONObject that will include the new material. - * @param name - * The tag name. - * @return true if the close tag is processed. - */ - private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { - char c; - int i; - JSONObject jsonobject = null; - String string; - String tagName; - Object token; - - // Test for and skip past these forms: - // - // - // - // - // Report errors for these forms: - // <> - // <= - // << - - token = x.nextToken(); - - // "); - return false; - } - x.back(); - } else if(c == '[') { - token = x.nextToken(); - if("CDATA".equals(token)) { - if(x.next() == '[') { - string = x.nextCDATA(); - if(string.length() > 0) { - context.accumulate("content", string); - } - return false; - } - } - throw x.syntaxError("Expected 'CDATA['"); - } - i = 1; - do { - token = x.nextMeta(); - if(token == null) { - throw x.syntaxError("Missing '>' after ' 0); - return false; - } else if(token == QUEST) { - - // "); - return false; - } else if(token == SLASH) { - - // Close tag - - } else if(token == SLASH) { - if(x.nextToken() != GT) { - throw x.syntaxError("Misshaped tag"); - } - if(jsonobject.length() > 0) { - context.accumulate(tagName, jsonobject); - } else { - context.accumulate(tagName, ""); - } - return false; - - // Content, between <...> and - - } else if(token == GT) { - for(; ; ) { - token = x.nextContent(); - if(token == null) { - if(tagName != null) { - throw x.syntaxError("Unclosed tag " + tagName); - } - return false; - } else if(token instanceof String) { - string = (String) token; - if(string.length() > 0) { - jsonobject.accumulate("content", XML.stringToValue(string)); - } - - // Nested element - - } else if(token == LT) { - if(parse(x, jsonobject, tagName)) { - if(jsonobject.length() == 0) { - context.accumulate(tagName, ""); - } else if(jsonobject.length() == 1 && jsonobject.opt("content") != null) { - context.accumulate(tagName, jsonobject.opt("content")); - } else { - context.accumulate(tagName, jsonobject); - } - return false; - } - } - } - } else { - throw x.syntaxError("Misshaped tag"); - } - } - } - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. This is much less ambitious than - * JSONObject.stringToValue, especially because it does not attempt to - * convert plus forms, octal forms, hex forms, or E forms lacking decimal - * points. - * - * @param string - * A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) { - if("true".equalsIgnoreCase(string)) { - return Boolean.TRUE; - } - if("false".equalsIgnoreCase(string)) { - return Boolean.FALSE; - } - if("null".equalsIgnoreCase(string)) { - return JSONObject.NULL; - } - - // If it might be a number, try converting it, first as a Long, and then - // as a - // Double. If that doesn't work, return the string. - - try { - char initial = string.charAt(0); - if(initial == '-' || (initial >= '0' && initial <= '9')) { - Long value = Long.valueOf(string); - if(value.toString().equals(string)) { - return value; - } - } - } catch(Exception ignore) { - Iris.reportError(ignore); - try { - Double value = Double.valueOf(string); - if(value.toString().equals(string)) { - return value; - } - } catch(Exception e) { - Iris.reportError(e); - } - } - return string; - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject. Some information may be lost in this transformation because - * JSON is a data format and XML is a document format. XML uses elements, - * attributes, and content text, while JSON uses unordered collections of - * name/value pairs and arrays of values. JSON does not does not like to - * distinguish between elements and attributes. Sequences of similar - * elements are represented as JSONArrays. Content text may be placed in a - * "content" member. Comments, prologs, DTDs, and <[ [ ]]> - * are ignored. - * - * @param string - * The source string. - * @return A JSONObject containing the structured data from the XML string. - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - XMLTokener x = new XMLTokener(string); - while(x.more() && x.skipPast("<")) { - parse(x, jo, null); - } - return jo; - } - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * - * @param object - * A JSONObject. - * @return A string. - */ - public static String toString(Object object) throws JSONException { - return toString(object, null); - } - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * - * @param object - * A JSONObject. - * @param tagName - * The optional name of the enclosing tag. - * @return A string. - */ - public static String toString(Object object, String tagName) throws JSONException { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - JSONObject jo; - String key; - Iterator keys; - int length; - String string; - Object value; - if(object instanceof JSONObject) { - - // Emit - - if(tagName != null) { - sb.append('<'); - sb.append(tagName); - sb.append('>'); - } - - // Loop thru the keys. - - jo = (JSONObject) object; - keys = jo.keys(); - while(keys.hasNext()) { - key = keys.next(); - value = jo.opt(key); - if(value == null) { - value = ""; - } - string = value instanceof String ? (String) value : null; - - // Emit content in body - - if("content".equals(key)) { - if(value instanceof JSONArray) { - ja = (JSONArray) value; - length = ja.length(); - for(i = 0; i < length; i += 1) { - if(i > 0) { - sb.append('\n'); - } - sb.append(escape(ja.get(i).toString())); - } - } else { - sb.append(escape(value.toString())); - } - - // Emit an array of similar keys - - } else if(value instanceof JSONArray) { - ja = (JSONArray) value; - length = ja.length(); - for(i = 0; i < length; i += 1) { - value = ja.get(i); - if(value instanceof JSONArray) { - sb.append('<'); - sb.append(key); - sb.append('>'); - sb.append(toString(value)); - sb.append("'); - } else { - sb.append(toString(value, key)); - } - } - } else if("".equals(value)) { - sb.append('<'); - sb.append(key); - sb.append("/>"); - - // Emit a new tag - - } else { - sb.append(toString(value, key)); - } - } - if(tagName != null) { - - // Emit the close tag - - sb.append("'); - } - return sb.toString(); - - // XML does not have good support for arrays. If an array appears in - // a place - // where XML is lacking, synthesize an element. - - } else { - if(object.getClass().isArray()) { - object = new JSONArray(object); - } - if(object instanceof JSONArray) { - ja = (JSONArray) object; - length = ja.length(); - for(i = 0; i < length; i += 1) { - sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); - } - return sb.toString(); - } else { - string = (object == null) ? "null" : escape(object.toString()); - return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/json/XMLTokener.java b/src/main/java/com/volmit/iris/util/json/XMLTokener.java deleted file mode 100644 index f27bfd5ab..000000000 --- a/src/main/java/com/volmit/iris/util/json/XMLTokener.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.json; - - -/** - * The XMLTokener extends the JSONTokener to provide additional methods for the - * parsing of XML texts. - * - * @author JSON.org - * @version 2014-05-03 - */ -public class XMLTokener extends JSONTokener { - - /** - * The table of entity values. It initially contains Character values for - * amp, apos, gt, lt, quot. - */ - public static final java.util.HashMap entity; - - static { - entity = new java.util.HashMap<>(8); - entity.put("amp", XML.AMP); - entity.put("apos", XML.APOS); - entity.put("gt", XML.GT); - entity.put("lt", XML.LT); - entity.put("quot", XML.QUOT); - } - - /** - * Construct an XMLTokener from a string. - * - * @param s - * A source string. - */ - public XMLTokener(String s) { - super(s); - } - - /** - * Get the text in the CDATA block. - * - * @return The string up to the ]]>. - * @throws JSONException - * If the ]]> is not found. - */ - public String nextCDATA() throws JSONException { - char c; - int i; - StringBuilder sb = new StringBuilder(); - for(; ; ) { - c = next(); - if(end()) { - throw syntaxError("Unclosed CDATA"); - } - sb.append(c); - i = sb.length() - 3; - if(i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { - sb.setLength(i); - return sb.toString(); - } - } - } - - /** - * Get the next XML outer token, trimming whitespace. There are two kinds of - * tokens: the '<' character which begins a markup tag, and the content text - * between markup tags. - * - * @return A string, or a '<' Character, or null if there is no more source - * text. - */ - public Object nextContent() throws JSONException { - char c; - StringBuilder sb; - do { - c = next(); - } while(Character.isWhitespace(c)); - if(c == 0) { - return null; - } - if(c == '<') { - return XML.LT; - } - sb = new StringBuilder(); - for(; ; ) { - if(c == '<' || c == 0) { - back(); - return sb.toString().trim(); - } - if(c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - c = next(); - } - } - - /** - * Return the next entity. These entities are translated to Characters: - * & ' > < ". - * - * @param ampersand - * An ampersand character. - * @return A Character or an entity String if the entity is not recognized. - * @throws JSONException - * If missing ';' in XML entity. - */ - public Object nextEntity(char ampersand) throws JSONException { - StringBuilder sb = new StringBuilder(); - for(; ; ) { - char c = next(); - if(Character.isLetterOrDigit(c) || c == '#') { - sb.append(Character.toLowerCase(c)); - } else if(c == ';') { - break; - } else { - throw syntaxError("Missing ';' in XML entity: &" + sb); - } - } - String string = sb.toString(); - Object object = entity.get(string); - return object != null ? object : ampersand + string + ";"; - } - - /** - * Returns the next XML meta token. This is used for skipping over - * and structures. - * - * @return Syntax characters (< > / = ! ?) are returned as - * Character, and strings and names are returned as Boolean. We - * don't care what the values actually are. - * @throws JSONException - * If a string is not properly closed or if the XML is badly - * structured. - */ - public Object nextMeta() throws JSONException { - char c; - char q; - do { - c = next(); - } while(Character.isWhitespace(c)); - switch(c) { - case 0: - throw syntaxError("Misshaped meta tag"); - case '<': - return XML.LT; - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - for(; ; ) { - c = next(); - if(c == 0) { - throw syntaxError("Unterminated string"); - } - if(c == q) { - return Boolean.TRUE; - } - } - default: - for(; ; ) { - c = next(); - if(Character.isWhitespace(c)) { - return Boolean.TRUE; - } - switch(c) { - case 0, '<', '>', '/', '=', '!', '?', '"', '\'' -> { - back(); - return Boolean.TRUE; - } - } - } - } - } - - /** - * Get the next XML Token. These tokens are found inside of angle brackets. - * It may be one of these characters: / > = ! ? or it may be a - * string wrapped in single quotes or double quotes, or it may be a name. - * - * @return a String or a Character. - * @throws JSONException - * If the XML is not well formed. - */ - public Object nextToken() throws JSONException { - char c; - char q; - StringBuilder sb; - do { - c = next(); - } while(Character.isWhitespace(c)); - switch(c) { - case 0: - throw syntaxError("Misshaped element"); - case '<': - throw syntaxError("Misplaced '<'"); - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - - // Quoted string - - case '"': - case '\'': - q = c; - sb = new StringBuilder(); - for(; ; ) { - c = next(); - if(c == 0) { - throw syntaxError("Unterminated string"); - } - if(c == q) { - return sb.toString(); - } - if(c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - } - default: - - // Name - - sb = new StringBuilder(); - for(; ; ) { - sb.append(c); - c = next(); - if(Character.isWhitespace(c)) { - return sb.toString(); - } - switch(c) { - case 0: - return sb.toString(); - case '>': - case '/': - case '=': - case '!': - case '?': - case '[': - case ']': - back(); - return sb.toString(); - case '<': - case '"': - case '\'': - throw syntaxError("Bad character in a name"); - } - } - } - } - - /** - * Skip characters until past the requested string. If it is not found, we - * are left at the end of the source with a result of false. - * - * @param to - * A string to skip past. - */ - public boolean skipPast(String to) throws JSONException { - boolean b; - char c; - int i; - int j; - int offset = 0; - int length = to.length(); - char[] circle = new char[length]; - - /* - * First fill the circle buffer with as many characters as are in the to - * string. If we reach an early end, bail. - */ - - for(i = 0; i < length; i += 1) { - c = next(); - if(c == 0) { - return false; - } - circle[i] = c; - } - - /* We will loop, possibly for all of the remaining characters. */ - - for(; ; ) { - j = offset; - b = true; - - /* Compare the circle buffer with the to string. */ - - for(i = 0; i < length; i += 1) { - if(circle[j] != to.charAt(i)) { - b = false; - break; - } - j += 1; - if(j >= length) { - j -= length; - } - } - - /* If we exit the loop with b intact, then victory is ours. */ - - if(b) { - return true; - } - - /* - * Get the next character. If there isn't one, then defeat is ours. - */ - - c = next(); - if(c == 0) { - return false; - } - /* - * Shove the character in the circle buffer and advance the circle - * offset. The offset is mod n. - */ - circle[offset] = c; - offset += 1; - if(offset >= length) { - offset -= length; - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/mantle/Mantle.java b/src/main/java/com/volmit/iris/util/mantle/Mantle.java deleted file mode 100644 index e08222ed8..000000000 --- a/src/main/java/com/volmit/iris/util/mantle/Mantle.java +++ /dev/null @@ -1,609 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.mantle; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.tools.IrisToolbelt; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.mantle.EngineMantle; -import com.volmit.iris.engine.mantle.MantleWriter; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.documentation.BlockCoordinates; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.documentation.RegionCoordinates; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.matter.Matter; -import com.volmit.iris.util.matter.MatterSlice; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.HyperLock; -import com.volmit.iris.util.parallel.MultiBurst; -import lombok.Getter; -import org.bukkit.Chunk; - -import java.io.EOFException; -import java.io.File; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * The mantle can store any type of data slice anywhere and manage regions & IO on it's own. - * This class is fully thread safe read & writeNodeData - */ -public class Mantle { - private final File dataFolder; - private final int worldHeight; - private final Map lastUse; - @Getter - private final Map loadedRegions; - private final HyperLock hyperLock; - private final KSet unload; - private final AtomicBoolean closed; - private final MultiBurst ioBurst; - private final AtomicBoolean io; - - /** - * Create a new mantle - * - * @param dataFolder - * the data folder - * @param worldHeight - * the world's height (in blocks) - */ - @BlockCoordinates - public Mantle(File dataFolder, int worldHeight) { - this.hyperLock = new HyperLock(); - this.closed = new AtomicBoolean(false); - this.dataFolder = dataFolder; - this.worldHeight = worldHeight; - this.io = new AtomicBoolean(false); - dataFolder.mkdirs(); - unload = new KSet<>(); - loadedRegions = new KMap<>(); - lastUse = new KMap<>(); - ioBurst = MultiBurst.burst; - Iris.debug("Opened The Mantle " + C.DARK_AQUA + dataFolder.getAbsolutePath()); - } - - /** - * Get the file for a region - * - * @param folder - * the folder - * @param x - * the x coord - * @param z - * the z coord - * @return the file - */ - public static File fileForRegion(File folder, int x, int z) { - return fileForRegion(folder, key(x, z)); - } - - /** - * Get the file for the given region - * - * @param folder - * the data folder - * @param key - * the region key - * @return the file - */ - public static File fileForRegion(File folder, Long key) { - File f = new File(folder, "p." + key + ".ttp"); - if(!f.getParentFile().exists()) { - f.getParentFile().mkdirs(); - } - return f; - } - - /** - * Get the long value representing a chunk or region coordinate - * - * @param x - * the x - * @param z - * the z - * @return the value - */ - public static Long key(int x, int z) { - return Cache.key(x, z); - } - - /** - * Raise a flag if it is lowered currently, If the flag was raised, execute the runnable - * - * @param x - * the chunk x - * @param z - * the chunk z - * @param flag - * the flag to raise - * @param r - * the runnable to fire if the flag is now raised (and was previously lowered) - */ - @ChunkCoordinates - public void raiseFlag(int x, int z, MantleFlag flag, Runnable r) { - if(!hasFlag(x, z, flag)) { - flag(x, z, flag, true); - r.run(); - } - } - - /** - * Obtain a cached writer which only contains cached chunks. - * This avoids locking on regions when writing to lots of chunks - * - * @param x - * the x chunk - * @param z - * the z chunk - * @param radius - * the radius chunks - * @return the writer - */ - @ChunkCoordinates - public MantleWriter write(EngineMantle engineMantle, int x, int z, int radius) { - return new MantleWriter(engineMantle, this, x, z, radius); - } - - /** - * Lower a flag if it is raised. If the flag was lowered (meaning it was previously raised), execute the runnable - * - * @param x - * the chunk x - * @param z - * the chunk z - * @param flag - * the flag to lower - * @param r - * the runnable that is fired if the flag was raised but is now lowered - */ - @ChunkCoordinates - public void lowerFlag(int x, int z, MantleFlag flag, Runnable r) { - if(hasFlag(x, z, flag)) { - flag(x, z, flag, false); - r.run(); - } - } - - @ChunkCoordinates - public MantleChunk getChunk(int x, int z) { - return get(x >> 5, z >> 5).getOrCreate(x & 31, z & 31); - } - - /** - * Flag or unflag a chunk - * - * @param x - * the chunk x - * @param z - * the chunk z - * @param flag - * the flag - * @param flagged - * should it be set to flagged or not - */ - @ChunkCoordinates - public void flag(int x, int z, MantleFlag flag, boolean flagged) { - get(x >> 5, z >> 5).getOrCreate(x & 31, z & 31).flag(flag, flagged); - } - - public void deleteChunk(int x, int z) { - get(x >> 5, z >> 5).delete(x & 31, z & 31); - } - - /** - * Check very quickly if a tectonic plate exists via cached or the file system - * - * @param x - * the x region coordinate - * @param z - * the z region coordinate - * @return true if it exists - */ - @RegionCoordinates - public boolean hasTectonicPlate(int x, int z) { - Long k = key(x, z); - return loadedRegions.containsKey(k) || fileForRegion(dataFolder, k).exists(); - } - - /** - * Iterate data in a chunk - * - * @param x - * the chunk x - * @param z - * the chunk z - * @param type - * the type of data to iterate - * @param iterator - * the iterator (x,y,z,data) -> do stuff - * @param - * the type of data to iterate - */ - @ChunkCoordinates - public void iterateChunk(int x, int z, Class type, Consumer4 iterator) { - if(!hasTectonicPlate(x >> 5, z >> 5)) { - return; - } - - get(x >> 5, z >> 5).getOrCreate(x & 31, z & 31).iterate(type, iterator); - } - - /** - * Does this chunk have a flag on it? - * - * @param x - * the x - * @param z - * the z - * @param flag - * the flag to test - * @return true if it's flagged - */ - @ChunkCoordinates - public boolean hasFlag(int x, int z, MantleFlag flag) { - if(!hasTectonicPlate(x >> 5, z >> 5)) { - return false; - } - - return get(x >> 5, z >> 5).getOrCreate(x & 31, z & 31).isFlagged(flag); - } - - /** - * Set data T at the given block position. This method will attempt to find a - * Tectonic Plate either by loading it or creating a new one. This method uses - * the hyper lock packaged with each Mantle. The hyperlock allows locking of multiple - * threads at a single region while still allowing other threads to continue - * reading & writing other regions. Hyperlocks are slow sync, but in multicore - * environments, they drastically speed up loading & saving large counts of plates - * - * @param x - * the block's x coordinate - * @param y - * the block's y coordinate - * @param z - * the block's z coordinate - * @param t - * the data to set at the block - * @param - * the type of data (generic method) - */ - @BlockCoordinates - public void set(int x, int y, int z, T t) { - if(closed.get()) { - throw new RuntimeException("The Mantle is closed"); - } - - if(y < 0 || y >= worldHeight) { - return; - } - - Matter matter = get((x >> 4) >> 5, (z >> 4) >> 5) - .getOrCreate((x >> 4) & 31, (z >> 4) & 31) - .getOrCreate(y >> 4); - matter.slice(matter.getClass(t)) - .set(x & 15, y & 15, z & 15, t); - } - - @BlockCoordinates - public void remove(int x, int y, int z, Class t) { - if(closed.get()) { - throw new RuntimeException("The Mantle is closed"); - } - - if(y < 0 || y >= worldHeight) { - return; - } - - Matter matter = get((x >> 4) >> 5, (z >> 4) >> 5) - .getOrCreate((x >> 4) & 31, (z >> 4) & 31) - .getOrCreate(y >> 4); - matter.slice(t) - .set(x & 15, y & 15, z & 15, null); - } - - /** - * Gets the data at the current block position This method will attempt to find a - * Tectonic Plate either by loading it or creating a new one. This method uses - * the hyper lock packaged with each Mantle. The hyperlock allows locking of multiple - * threads at a single region while still allowing other threads to continue - * reading & writing other regions. Hyperlocks are slow sync, but in multicore - * environments, they drastically speed up loading & saving large counts of plates - * - * @param x - * the block's x coordinate - * @param y - * the block's y coordinate - * @param z - * the block's z coordinate - * @param t - * the class representing the type of data being requested - * @param - * the type assumed from the provided class - * @return the returned result (or null) if it doesnt exist - */ - @SuppressWarnings("unchecked") - @BlockCoordinates - public T get(int x, int y, int z, Class t) { - if(closed.get()) { - throw new RuntimeException("The Mantle is closed"); - } - - if(!hasTectonicPlate((x >> 4) >> 5, (z >> 4) >> 5)) { - return null; - } - - if(y < 0 || y >= worldHeight) { - return null; - } - - return (T) get((x >> 4) >> 5, (z >> 4) >> 5) - .getOrCreate((x >> 4) & 31, (z >> 4) & 31) - .getOrCreate(y >> 4).slice(t) - .get(x & 15, y & 15, z & 15); - } - - /** - * Is this mantle closed - * - * @return true if it is - */ - public boolean isClosed() { - return closed.get(); - } - - public void set(int x, int y, int z, Matter matter) - { - for(MatterSlice i : matter.getSliceMap().values()) - { - i.iterate((mx, my, mz, v) -> set(mx + x, my + y, mz + z, v)); - } - } - - /** - * Closes the Mantle. By closing the mantle, you can no longer read or writeNodeData - * any data to the mantle or it's Tectonic Plates. Closing will also flush any - * loaded regions to the disk in parallel. - */ - public synchronized void close() { - Iris.debug("Closing The Mantle " + C.DARK_AQUA + dataFolder.getAbsolutePath()); - if(closed.get()) { - return; - } - - closed.set(true); - BurstExecutor b = ioBurst.burst(loadedRegions.size()); - for(Long i : loadedRegions.keySet()) { - b.queue(() -> { - try { - loadedRegions.get(i).write(fileForRegion(dataFolder, i)); - } catch(IOException e) { - e.printStackTrace(); - } - }); - } - - try { - b.complete(); - } catch(Throwable e) { - Iris.reportError(e); - } - - loadedRegions.clear(); - Iris.debug("The Mantle has Closed " + C.DARK_AQUA + dataFolder.getAbsolutePath()); - } - - /** - * Save & unload regions that have not been used for more than the - * specified amount of milliseconds - * - * @param idleDuration - * the duration - */ - public synchronized void trim(long idleDuration) { - if(closed.get()) { - throw new RuntimeException("The Mantle is closed"); - } - - io.set(true); - Iris.debug("Trimming Tectonic Plates older than " + Form.duration((double) idleDuration, 0)); - unload.clear(); - - for(Long i : lastUse.keySet()) { - hyperLock.withLong(i, () -> { - if(M.ms() - lastUse.get(i) >= idleDuration) { - unload.add(i); - } - }); - } - - for(Long i : unload) { - hyperLock.withLong(i, () -> { - TectonicPlate m = loadedRegions.remove(i); - lastUse.remove(i); - - try { - m.write(fileForRegion(dataFolder, i)); - } catch(IOException e) { - e.printStackTrace(); - } - - Iris.debug("Unloaded Tectonic Plate " + C.DARK_GREEN + Cache.keyX(i) + " " + Cache.keyZ(i)); - }); - } - io.set(false); - } - - /** - * This retreives a future of the Tectonic Plate at the given coordinates. - * All methods accessing tectonic plates should go through this method - * - * @param x - * the region x - * @param z - * the region z - * @return the future of a tectonic plate. - */ - @RegionCoordinates - private TectonicPlate get(int x, int z) { - if(io.get()) { - try { - return getSafe(x, z).get(); - } catch(InterruptedException e) { - e.printStackTrace(); - } catch(ExecutionException e) { - e.printStackTrace(); - } - } - - TectonicPlate p = loadedRegions.get(key(x, z)); - - if(p != null) { - return p; - } - - try { - return getSafe(x, z).get(); - } catch(InterruptedException e) { - Iris.warn("Failed to get Tectonic Plate " + x + " " + z + " Due to a thread intterruption (hotload?)"); - Iris.reportError(e); - } catch(ExecutionException e) { - Iris.warn("Failed to get Tectonic Plate " + x + " " + z + " Due to a thread execution exception (engine close?)"); - Iris.reportError(e); - } - - Iris.warn("Retrying to get " + x + " " + z + " Mantle Region"); - return get(x, z); - } - - /** - * This retreives a future of the Tectonic Plate at the given coordinates. - * All methods accessing tectonic plates should go through this method - * - * @param x - * the region x - * @param z - * the region z - * @return the future of a tectonic plate. - */ - @RegionCoordinates - private Future getSafe(int x, int z) { - Long k = key(x, z); - TectonicPlate p = loadedRegions.get(k); - - if(p != null) { - lastUse.put(k, M.ms()); - return CompletableFuture.completedFuture(p); - } - - return ioBurst.completeValue(() -> hyperLock.withResult(x, z, () -> { - lastUse.put(k, M.ms()); - TectonicPlate region = loadedRegions.get(k); - - if(region != null) { - return region; - } - - File file = fileForRegion(dataFolder, x, z); - - if(file.exists()) { - try { - Iris.addPanic("reading.tectonic-plate", file.getAbsolutePath()); - region = TectonicPlate.read(worldHeight, file); - - if(region.getX() != x || region.getZ() != z) { - Iris.warn("Loaded Tectonic Plate " + x + "," + z + " but read it as " + region.getX() + "," + region.getZ() + "... Assuming " + x + "," + z); - } - - loadedRegions.put(k, region); - Iris.debug("Loaded Tectonic Plate " + C.DARK_GREEN + x + " " + z + C.DARK_AQUA + " " + file.getName()); - } catch(Throwable e) { - Iris.error("Failed to read Tectonic Plate " + file.getAbsolutePath() + " creating a new chunk instead."); - Iris.reportError(e); - if (!(e instanceof EOFException)) { - e.printStackTrace(); - } - Iris.panic(); - region = new TectonicPlate(worldHeight, x, z); - loadedRegions.put(k, region); - Iris.debug("Created new Tectonic Plate (Due to Load Failure) " + C.DARK_GREEN + x + " " + z); - } - - return region; - } - - region = new TectonicPlate(worldHeight, x, z); - loadedRegions.put(k, region); - Iris.debug("Created new Tectonic Plate " + C.DARK_GREEN + x + " " + z); - return region; - })); - } - - public void saveAll() { - - } - - public int getWorldHeight() { - return worldHeight; - } - - public MantleChunk getChunk(Chunk e) { - return getChunk(e.getX(), e.getZ()); - } - - public void deleteChunkSlice(int x, int z, Class c) { - if(!IrisToolbelt.toolbeltConfiguration.isEmpty() && IrisToolbelt.toolbeltConfiguration.getOrDefault("retain.mantle." + c.getCanonicalName(), false)) - { - return; - } - - getChunk(x, z).deleteSlices(c); - } - - public int getLoadedRegionCount() { - return loadedRegions.size(); - } - - public void set(int x, int y, int z, MatterSlice slice) { - if(slice.isEmpty()) { - return; - } - - slice.iterateSync((xx, yy, zz, t) -> set(x + xx, y + yy, z + zz, t)); - } - - public boolean isLoaded(Chunk c) { - return loadedRegions.containsKey(key(c.getX() >> 5, c.getZ() >> 5)); - } - - public boolean shouldReduce(Engine engine) { - return !engine.isStudio() || IrisSettings.get().getPerformance().isTrimMantleInStudio(); - } -} diff --git a/src/main/java/com/volmit/iris/util/mantle/MantleChunk.java b/src/main/java/com/volmit/iris/util/mantle/MantleChunk.java deleted file mode 100644 index 385bb12d8..000000000 --- a/src/main/java/com/volmit/iris/util/mantle/MantleChunk.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.mantle; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.function.Consumer4; -import com.volmit.iris.util.matter.IrisMatter; -import com.volmit.iris.util.matter.Matter; -import com.volmit.iris.util.matter.MatterSlice; -import lombok.Getter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.concurrent.atomic.AtomicIntegerArray; -import java.util.concurrent.atomic.AtomicReferenceArray; - -/** - * Represents a mantle chunk. Mantle chunks contain sections of matter (see matter api) - * Mantle Chunks are fully atomic & thread safe - */ -public class MantleChunk { - @Getter - private final int x; - @Getter - private final int z; - private final AtomicIntegerArray flags; - private final AtomicReferenceArray sections; - - /** - * Create a mantle chunk - * - * @param sectionHeight - * the height of the world in sections (blocks >> 4) - */ - @ChunkCoordinates - public MantleChunk(int sectionHeight, int x, int z) { - sections = new AtomicReferenceArray<>(sectionHeight); - flags = new AtomicIntegerArray(MantleFlag.values().length); - this.x = x; - this.z = z; - - for(int i = 0; i < flags.length(); i++) { - flags.set(i, 0); - } - } - - /** - * Load a mantle chunk from a data stream - * - * @param sectionHeight - * the height of the world in sections (blocks >> 4) - * @param din - * the data input - * @throws IOException - * shit happens - * @throws ClassNotFoundException - * shit happens - */ - public MantleChunk(int sectionHeight, DataInputStream din) throws IOException, ClassNotFoundException { - this(sectionHeight, din.readByte(), din.readByte()); - int s = din.readByte(); - - for(int i = 0; i < flags.length(); i++) { - flags.set(i, din.readBoolean() ? 1 : 0); - } - - for(int i = 0; i < s; i++) { - Iris.addPanic("read.section", "Section[" + i + "]"); - if(din.readBoolean()) { - sections.set(i, Matter.readDin(din)); - } - } - } - - public void flag(MantleFlag flag, boolean f) { - flags.set(flag.ordinal(), f ? 1 : 0); - } - - public void raiseFlag(MantleFlag flag, Runnable r) { - if(!isFlagged(flag)) { - flag(flag, true); - r.run(); - } - } - - public boolean isFlagged(MantleFlag flag) { - return flags.get(flag.ordinal()) == 1; - } - - /** - * Check if a section exists (same as get(section) != null) - * - * @param section - * the section (0 - (worldHeight >> 4)) - * @return true if it exists - */ - @ChunkCoordinates - public boolean exists(int section) { - return get(section) != null; - } - - /** - * Get thje matter at the given section or null if it doesnt exist - * - * @param section - * the section (0 - (worldHeight >> 4)) - * @return the matter or null if it doesnt exist - */ - @ChunkCoordinates - public Matter get(int section) { - return sections.get(section); - } - - /** - * Clear all matter from this chunk - */ - public void clear() { - for(int i = 0; i < sections.length(); i++) { - delete(i); - } - } - - /** - * Delete the matter from the given section - * - * @param section - * the section (0 - (worldHeight >> 4)) - */ - @ChunkCoordinates - public void delete(int section) { - sections.set(section, null); - } - - /** - * Get or create a new matter section at the given section - * - * @param section - * the section (0 - (worldHeight >> 4)) - * @return the matter - */ - @ChunkCoordinates - public Matter getOrCreate(int section) { - Matter matter = get(section); - - if(matter == null) { - matter = new IrisMatter(16, 16, 16); - sections.set(section, matter); - } - - return matter; - } - - /** - * Write this chunk to a data stream - * - * @param dos - * the stream - * @throws IOException - * shit happens - */ - public void write(DataOutputStream dos) throws IOException { - dos.writeByte(x); - dos.writeByte(z); - dos.writeByte(sections.length()); - - for(int i = 0; i < flags.length(); i++) { - dos.writeBoolean(flags.get(i) == 1); - } - - for(int i = 0; i < sections.length(); i++) { - trimSlice(i); - - if(exists(i)) { - dos.writeBoolean(true); - Matter matter = get(i); - matter.writeDos(dos); - } else { - dos.writeBoolean(false); - } - } - } - - private void trimSlice(int i) { - if(exists(i)) { - Matter m = get(i); - - if(m.getSliceMap().isEmpty()) { - sections.set(i, null); - } else { - m.trimSlices(); - if(m.getSliceMap().isEmpty()) { - sections.set(i, null); - } - } - } - } - - public void iterate(Class type, Consumer4 iterator) { - for(int i = 0; i < sections.length(); i++) { - int bs = (i << 4); - Matter matter = get(i); - - if(matter != null) { - MatterSlice t = matter.getSlice(type); - - if(t != null) { - t.iterateSync((a, b, c, f) -> iterator.accept(a, b + bs, c, f)); - } - } - } - } - - public void deleteSlices(Class c) { - for(int i = 0; i < sections.length(); i++) { - Matter m = sections.get(i); - if(m != null && m.hasSlice(c)) { - m.deleteSlice(c); - } - } - } - - public void trimSlices() { - for(int i = 0; i < sections.length(); i++) { - if(exists(i)) { - trimSlice(i); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/mantle/MantleFlag.java b/src/main/java/com/volmit/iris/util/mantle/MantleFlag.java deleted file mode 100644 index 03d98dee6..000000000 --- a/src/main/java/com/volmit/iris/util/mantle/MantleFlag.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.mantle; - -import com.volmit.iris.util.collection.StateList; - -public enum MantleFlag { - OBJECT, - UPDATE, - JIGSAW, - FEATURE, - INITIAL_SPAWNED, - REAL, - CARVED, - FLUID_BODIES, - INITIAL_SPAWNED_MARKER, - CLEANED, - PLANNED, - ETCHED, - TILE; - - static StateList getStateList() { - return new StateList(MantleFlag.values()); - } -} diff --git a/src/main/java/com/volmit/iris/util/mantle/TectonicPlate.java b/src/main/java/com/volmit/iris/util/mantle/TectonicPlate.java deleted file mode 100644 index 6d1a88342..000000000 --- a/src/main/java/com/volmit/iris/util/mantle/TectonicPlate.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.mantle; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.EnginePanic; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.util.documentation.ChunkCoordinates; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import lombok.Getter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.concurrent.atomic.AtomicReferenceArray; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -/** - * Tectonic Plates are essentially representations of regions in minecraft. - * Tectonic Plates are fully atomic & thread safe - */ -public class TectonicPlate { - private final int sectionHeight; - private final AtomicReferenceArray chunks; - - @Getter - private final int x; - - @Getter - private final int z; - - /** - * Create a new tectonic plate - * - * @param worldHeight - * the height of the world - */ - public TectonicPlate(int worldHeight, int x, int z) { - this.sectionHeight = worldHeight >> 4; - this.chunks = new AtomicReferenceArray<>(1024); - this.x = x; - this.z = z; - } - - /** - * Load a tectonic plate from a data stream - * - * @param worldHeight - * the height of the world - * @param din - * the data input - * @throws IOException - * shit happens yo - * @throws ClassNotFoundException - * real shit bro - */ - public TectonicPlate(int worldHeight, DataInputStream din) throws IOException, ClassNotFoundException { - this(worldHeight, din.readInt(), din.readInt()); - for(int i = 0; i < chunks.length(); i++) { - if(din.readBoolean()) { - Iris.addPanic("read-chunk", "Chunk[" + i + "]"); - chunks.set(i, new MantleChunk(sectionHeight, din)); - EnginePanic.saveLast(); - } - } - } - - public static TectonicPlate read(int worldHeight, File file) throws IOException, ClassNotFoundException { - FileInputStream fin = new FileInputStream(file); - GZIPInputStream gzi = new GZIPInputStream(fin); - DataInputStream din = new DataInputStream(gzi); - TectonicPlate p = new TectonicPlate(worldHeight, din); - din.close(); - - return p; - } - - /** - * Check if a chunk exists in this plate or not (same as get(x, z) != null) - * - * @param x - * the chunk relative x (0-31) - * @param z - * the chunk relative z (0-31) - * @return true if the chunk exists - */ - @ChunkCoordinates - public boolean exists(int x, int z) { - return get(x, z) != null; - } - - /** - * Get a chunk at the given coordinates or null if it doesnt exist - * - * @param x - * the chunk relative x (0-31) - * @param z - * the chunk relative z (0-31) - * @return the chunk or null if it doesnt exist - */ - @ChunkCoordinates - public MantleChunk get(int x, int z) { - return chunks.get(index(x, z)); - } - - /** - * Clear all chunks from this tectonic plate - */ - public void clear() { - for(int i = 0; i < chunks.length(); i++) { - chunks.set(i, null); - } - } - - /** - * Delete a chunk from this tectonic plate - * - * @param x - * the chunk relative x (0-31) - * @param z - * the chunk relative z (0-31) - */ - @ChunkCoordinates - public void delete(int x, int z) { - chunks.set(index(x, z), null); - } - - /** - * Get a tectonic plate, or create one and insert it & return it if it diddnt exist - * - * @param x - * the chunk relative x (0-31) - * @param z - * the chunk relative z (0-31) - * @return the chunk (read or created & inserted) - */ - @ChunkCoordinates - public MantleChunk getOrCreate(int x, int z) { - MantleChunk chunk = get(x, z); - - if(chunk == null) { - chunk = new MantleChunk(sectionHeight, x & 31, z & 31); - chunks.set(index(x, z), chunk); - } - - return chunk; - } - - @ChunkCoordinates - private int index(int x, int z) { - return Cache.to1D(x, z, 0, 32, 32); - } - - /** - * Write this tectonic plate to file - * - * @param file - * the file to writeNodeData it to - * @throws IOException - * shit happens - */ - public void write(File file) throws IOException { - PrecisionStopwatch p = PrecisionStopwatch.start(); - FileOutputStream fos = new FileOutputStream(file); - GZIPOutputStream gzo = new GZIPOutputStream(fos); - DataOutputStream dos = new DataOutputStream(gzo); - write(dos); - dos.close(); - Iris.debug("Saved Tectonic Plate " + C.DARK_GREEN + file.getName().split("\\Q.\\E")[0] + C.RED + " in " + Form.duration(p.getMilliseconds(), 2)); - } - - /** - * Write this tectonic plate to a data stream - * - * @param dos - * the data output - * @throws IOException - * shit happens - */ - public void write(DataOutputStream dos) throws IOException { - dos.writeInt(x); - dos.writeInt(z); - - for(int i = 0; i < chunks.length(); i++) { - MantleChunk chunk = chunks.get(i); - - if(chunk != null) { - dos.writeBoolean(true); - chunk.write(dos); - } else { - dos.writeBoolean(false); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/math/AlignedPoint.java b/src/main/java/com/volmit/iris/util/math/AlignedPoint.java deleted file mode 100644 index 15ce5cb72..000000000 --- a/src/main/java/com/volmit/iris/util/math/AlignedPoint.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -public class AlignedPoint { - private double x; - private double y; - private double z; - - public double getX() { - return x; - } - - public double getY() { - return y; - } - - public double getZ() { - return z; - } - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/math/Average.java b/src/main/java/com/volmit/iris/util/math/Average.java deleted file mode 100644 index ba66e81f6..000000000 --- a/src/main/java/com/volmit/iris/util/math/Average.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.util.data.DoubleArrayUtils; - -/** - * Provides an incredibly fast averaging object. It swaps values from a sum - * using an array. Averages do not use any form of looping. An average of 10,000 - * entries is the same speed as an average with 5 entries. - * - * @author cyberpwn - */ -public class Average { - protected final double[] values; - protected int cursor; - private double average; - private double lastSum; - private boolean dirty; - private boolean brandNew; - - /** - * Create an average holder - * - * @param size - * the size of entries to keep - */ - public Average(int size) { - values = new double[size]; - DoubleArrayUtils.fill(values, 0); - brandNew = true; - average = 0; - cursor = 0; - lastSum = 0; - dirty = false; - } - - /** - * Put a value into the average (rolls over if full) - * - * @param i - * the value - */ - public void put(double i) { - - dirty = true; - - if(brandNew) { - DoubleArrayUtils.fill(values, i); - lastSum = size() * i; - brandNew = false; - return; - } - - double current = values[cursor]; - lastSum = (lastSum - current) + i; - values[cursor] = i; - cursor = cursor + 1 < size() ? cursor + 1 : 0; - } - - /** - * Get the current average - * - * @return the average - */ - public double getAverage() { - if(dirty) { - calculateAverage(); - return getAverage(); - } - - return average; - } - - private void calculateAverage() { - average = lastSum / (double) size(); - dirty = false; - } - - public int size() { - return values.length; - } - - public boolean isDirty() { - return dirty; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/AxisAlignedBB.java b/src/main/java/com/volmit/iris/util/math/AxisAlignedBB.java deleted file mode 100644 index c7fe7a006..000000000 --- a/src/main/java/com/volmit/iris/util/math/AxisAlignedBB.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.data.Cuboid; -import org.bukkit.World; -import org.bukkit.util.BlockVector; - -public class AxisAlignedBB { - private final double xa; - private final double xb; - private final double ya; - private final double yb; - private final double za; - private final double zb; - - public AxisAlignedBB(double xa, double xb, double ya, double yb, double za, double zb) { - this.xa = xa; - this.xb = xb; - this.ya = ya; - this.yb = yb; - this.za = za; - this.zb = zb; - } - - public AxisAlignedBB(AlignedPoint a, AlignedPoint b) { - this(a.getX(), b.getX(), a.getY(), b.getY(), a.getZ(), b.getZ()); - } - - public AxisAlignedBB(IrisPosition a, IrisPosition b) { - this(a.getX(), b.getX(), a.getY(), b.getY(), a.getZ(), b.getZ()); - } - - public AxisAlignedBB shifted(IrisPosition p) { - return shifted(p.getX(), p.getY(), p.getZ()); - } - - public AxisAlignedBB shifted(double x, double y, double z) { - return new AxisAlignedBB(min().add(new IrisPosition((int) x, (int) y, (int) z)), max().add(new IrisPosition((int) x, (int) y, (int) z))); - } - - public boolean contains(AlignedPoint p) { - return p.getX() >= xa && p.getX() <= xb && p.getY() >= ya && p.getZ() <= yb && p.getZ() >= za && p.getZ() <= zb; - } - - public boolean contains(IrisPosition p) { - return p.getX() >= xa && p.getX() <= xb && p.getY() >= ya && p.getZ() <= yb && p.getZ() >= za && p.getZ() <= zb; - } - - public boolean intersects(AxisAlignedBB s) { - return this.xb >= s.xa && this.yb >= s.ya && this.zb >= s.za && s.xb >= this.xa && s.yb >= this.ya && s.zb >= this.za; - } - - public IrisPosition max() { - return new IrisPosition((int) xb, (int) yb, (int) zb); - } - - - public BlockVector maxbv() { - return new BlockVector((int) xb, (int) yb, (int) zb); - } - - public IrisPosition min() { - return new IrisPosition((int) xa, (int) ya, (int) za); - } - - public BlockVector minbv() { - return new BlockVector((int) xa, (int) ya, (int) za); - } - - public Cuboid toCuboid(World world) { - return new Cuboid(min().toLocation(world), max().toLocation(world)); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/math/BlockPosition.java b/src/main/java/com/volmit/iris/util/math/BlockPosition.java deleted file mode 100644 index 8f1500d5d..000000000 --- a/src/main/java/com/volmit/iris/util/math/BlockPosition.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import lombok.Data; -import org.bukkit.World; -import org.bukkit.block.Block; - -import java.util.Objects; - -@Data -public class BlockPosition { - //Magic numbers - private static final int m1 = 1 + MathHelper.f(MathHelper.c(30000000)); - private static final int m2 = 64 - (m1 * 2); - private static final long m3 = m1 + m2; - private static final long m5 = (1L << m2) - 1L; - private static final long m4 = (1L << m1) - 1L; - private static final long m6 = (1L << m1) - 1L; - private int x; - private int y; - private int z; - - public BlockPosition(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } - - public static long toLong(int x, int y, int z) { - long var3 = 0L; - var3 |= (x & m4) << m3; - var3 |= (y & m5); - var3 |= (z & m6) << m2; - return var3; - } - - @Override - public int hashCode() { - return Objects.hash(x, y, z); - } - - public boolean equals(Object o) { - if(o == null) { - return false; - } - - if(o instanceof BlockPosition ot) { - - return ot.x == x && ot.y == y && ot.z == z; - } - - return false; - } - - public int getChunkX() { - return x >> 4; - } - - public int getChunkZ() { - return z >> 4; - } - - public boolean is(int x, int z) { - return this.x == x && this.z == z; - } - - public boolean is(int x, int y, int z) { - return this.x == x && this.y == y && this.z == z; - } - - public long asLong() { - return toLong(getX(), getY(), getZ()); - } - - public Block toBlock(World world) { - return world.getBlockAt(x, y, z); - } - - public BlockPosition add(int x, int y, int z) { - return new BlockPosition(this.x + x, this.y + y, this.z + z); - } - - public void min(BlockPosition i) { - setX(Math.min(i.getX(), getX())); - setY(Math.min(i.getY(), getY())); - setZ(Math.min(i.getZ(), getZ())); - } - - public void max(BlockPosition i) { - setX(Math.max(i.getX(), getX())); - setY(Math.max(i.getY(), getY())); - setZ(Math.max(i.getZ(), getZ())); - } -} diff --git a/src/main/java/com/volmit/iris/util/math/CDou.java b/src/main/java/com/volmit/iris/util/math/CDou.java deleted file mode 100644 index f64daa2fc..000000000 --- a/src/main/java/com/volmit/iris/util/math/CDou.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -@SuppressWarnings("ALL") -public class CDou { - private final double max; - private double number; - - public CDou(double max) { - number = 0; - this.max = max; - } - - public CDou set(double n) { - number = n; - circ(); - return this; - } - - public CDou add(double a) { - number += a; - circ(); - return this; - } - - public CDou sub(double a) { - number -= a; - circ(); - return this; - } - - public double get() { - return number; - } - - public void circ() { - if(number < 0) { - number = max - (Math.abs(number) > max ? max : Math.abs(number)); - } - - number = number % (max); - } -} diff --git a/src/main/java/com/volmit/iris/util/math/DOP.java b/src/main/java/com/volmit/iris/util/math/DOP.java deleted file mode 100644 index 1ea0a4a36..000000000 --- a/src/main/java/com/volmit/iris/util/math/DOP.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import org.bukkit.util.Vector; - -public abstract class DOP { - private final String type; - - public DOP(String type) { - this.type = type; - } - - public abstract Vector op(Vector v); - - public String getType() { - return type; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Direction.java b/src/main/java/com/volmit/iris/util/math/Direction.java deleted file mode 100644 index 72e0c4e0a..000000000 --- a/src/main/java/com/volmit/iris/util/math/Direction.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.util.collection.GBiset; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.Cuboid.CuboidDirection; -import org.bukkit.Axis; -import org.bukkit.block.BlockFace; -import org.bukkit.util.Vector; - -import java.util.Map; - -/** - * Directions - * - * @author cyberpwn - */ -public enum Direction { - U(0, 1, 0, CuboidDirection.Up), - D(0, -1, 0, CuboidDirection.Down), - N(0, 0, -1, CuboidDirection.North), - S(0, 0, 1, CuboidDirection.South), - E(1, 0, 0, CuboidDirection.East), - W(-1, 0, 0, CuboidDirection.West); - - private static KMap, DOP> permute = null; - - private final int x; - private final int y; - private final int z; - private final CuboidDirection f; - - Direction(int x, int y, int z, CuboidDirection f) { - this.x = x; - this.y = y; - this.z = z; - this.f = f; - } - - public static Direction getDirection(BlockFace f) { - return switch(f) { - case DOWN -> D; - case EAST, EAST_SOUTH_EAST, EAST_NORTH_EAST -> E; - case NORTH, NORTH_WEST, NORTH_NORTH_WEST, NORTH_NORTH_EAST, NORTH_EAST -> N; - case SELF, UP -> U; - case SOUTH, SOUTH_WEST, SOUTH_SOUTH_WEST, SOUTH_SOUTH_EAST, SOUTH_EAST -> S; - case WEST, WEST_SOUTH_WEST, WEST_NORTH_WEST -> W; - }; - - } - - public static Direction closest(Vector v) { - double m = Double.MAX_VALUE; - Direction s = null; - - for(Direction i : values()) { - Vector x = i.toVector(); - double g = x.dot(v); - - if(g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static Direction closest(Vector v, Direction... d) { - double m = Double.MAX_VALUE; - Direction s = null; - - for(Direction i : d) { - Vector x = i.toVector(); - double g = x.distance(v); - - if(g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static Direction closest(Vector v, KList d) { - double m = Double.MAX_VALUE; - Direction s = null; - - for(Direction i : d) { - Vector x = i.toVector(); - double g = x.distance(v); - - if(g < m) { - m = g; - s = i; - } - } - - return s; - } - - public static KList news() { - return new KList().add(N, E, W, S); - } - - public static Direction getDirection(Vector v) { - Vector k = VectorMath.triNormalize(v.clone().normalize()); - - for(Direction i : udnews()) { - if(i.x == k.getBlockX() && i.y == k.getBlockY() && i.z == k.getBlockZ()) { - return i; - } - } - - return Direction.N; - } - - public static KList udnews() { - return new KList().add(U, D, N, E, W, S); - } - - /** - * Get the directional value from the given byte from common directional blocks - * (MUST BE BETWEEN 0 and 5 INCLUSIVE) - * - * @param b - * the byte - * @return the direction or null if the byte is outside of the inclusive range - * 0-5 - */ - public static Direction fromByte(byte b) { - if(b > 5 || b < 0) { - return null; - } - - if(b == 0) { - return D; - } else if(b == 1) { - return U; - } else if(b == 2) { - return N; - } else if(b == 3) { - return S; - } else if(b == 4) { - return W; - } else { - return E; - } - } - - public static void calculatePermutations() { - if(permute != null) { - return; - } - - permute = new KMap<>(); - - for(Direction i : udnews()) { - for(Direction j : udnews()) { - GBiset b = new GBiset<>(i, j); - - if(i.equals(j)) { - permute.put(b, new DOP("DIRECT") { - @Override - public Vector op(Vector v) { - return v; - } - }); - } else if(i.reverse().equals(j)) { - if(i.isVertical()) { - permute.put(b, new DOP("R180CCZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCZ(VectorMath.rotate90CCZ(v)); - } - }); - } else { - permute.put(b, new DOP("R180CCY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCY(VectorMath.rotate90CCY(v)); - } - }); - } - } else if(getDirection(VectorMath.rotate90CX(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CX") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CX(v); - } - }); - } else if(getDirection(VectorMath.rotate90CCX(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCX") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCX(v); - } - }); - } else if(getDirection(VectorMath.rotate90CY(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CY(v); - } - }); - } else if(getDirection(VectorMath.rotate90CCY(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCY") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCY(v); - } - }); - } else if(getDirection(VectorMath.rotate90CZ(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CZ(v); - } - }); - } else if(getDirection(VectorMath.rotate90CCZ(i.toVector())).equals(j)) { - permute.put(b, new DOP("R90CCZ") { - @Override - public Vector op(Vector v) { - return VectorMath.rotate90CCZ(v); - } - }); - } else { - permute.put(b, new DOP("FAIL") { - @Override - public Vector op(Vector v) { - return v; - } - }); - } - } - } - } - - @Override - public String toString() { - return switch(this) { - case D -> "Down"; - case E -> "East"; - case N -> "North"; - case S -> "South"; - case U -> "Up"; - case W -> "West"; - }; - - } - - public boolean isVertical() { - return equals(D) || equals(U); - } - - public Vector toVector() { - return new Vector(x, y, z); - } - - public boolean isCrooked(Direction to) { - if(equals(to.reverse())) { - return false; - } - - return !equals(to); - } - - public Vector angle(Vector initial, Direction d) { - calculatePermutations(); - - for(Map.Entry, DOP> entry : permute.entrySet()) { - GBiset i = entry.getKey(); - if(i.getA().equals(this) && i.getB().equals(d)) { - return entry.getValue().op(initial); - } - } - - return initial; - } - - public Direction reverse() { - switch(this) { - case D: - return U; - case E: - return W; - case N: - return S; - case S: - return N; - case U: - return D; - case W: - return E; - default: - break; - } - - return null; - } - - public int x() { - return x; - } - - public int y() { - return y; - } - - public int z() { - return z; - } - - public CuboidDirection f() { - return f; - } - - /** - * Get the byte value represented in some directional blocks - * - * @return the byte value - */ - public byte byteValue() { - switch(this) { - case D: - return 0; - case E: - return 5; - case N: - return 2; - case S: - return 3; - case U: - return 1; - case W: - return 4; - default: - break; - } - - return -1; - } - - public BlockFace getFace() { - return switch(this) { - case D -> BlockFace.DOWN; - case E -> BlockFace.EAST; - case N -> BlockFace.NORTH; - case S -> BlockFace.SOUTH; - case U -> BlockFace.UP; - case W -> BlockFace.WEST; - }; - - } - - public Axis getAxis() { - return switch(this) { - case D, U -> Axis.Y; - case E, W -> Axis.X; - case N, S -> Axis.Z; - }; - - } -} diff --git a/src/main/java/com/volmit/iris/util/math/FinalInteger.java b/src/main/java/com/volmit/iris/util/math/FinalInteger.java deleted file mode 100644 index 6c934061d..000000000 --- a/src/main/java/com/volmit/iris/util/math/FinalInteger.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.util.scheduling.Wrapper; - -/** - * Represents a number that can be finalized and be changed - * - * @author cyberpwn - */ -public class FinalInteger extends Wrapper { - public FinalInteger(Integer t) { - super(t); - } - - /** - * Add to this value - * - * @param i - * the number to add to this value (value = value + i) - */ - public void add(int i) { - set(get() + i); - } - - /** - * Subtract from this value - * - * @param i - * the number to subtract from this value (value = value - i) - */ - public void sub(int i) { - set(get() - i); - } -} diff --git a/src/main/java/com/volmit/iris/util/math/INode.java b/src/main/java/com/volmit/iris/util/math/INode.java deleted file mode 100644 index db739855a..000000000 --- a/src/main/java/com/volmit/iris/util/math/INode.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import lombok.Data; -import org.bukkit.util.Vector; - -@Data -public class INode { - - private Vector position; - private double tension; - private double bias; - private double continuity; - - public INode() { - this(new Vector(0, 0, 0)); - } - - public INode(INode other) { - this.position = other.position; - - this.tension = other.tension; - this.bias = other.bias; - this.continuity = other.continuity; - } - - public INode(Vector position) { - this.position = position; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/math/IrisMathHelper.java b/src/main/java/com/volmit/iris/util/math/IrisMathHelper.java deleted file mode 100644 index 87ca5bb81..000000000 --- a/src/main/java/com/volmit/iris/util/math/IrisMathHelper.java +++ /dev/null @@ -1,452 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import java.util.Random; -import java.util.UUID; -import java.util.function.IntPredicate; - -public class IrisMathHelper { - public static final float a; - private static final Random c; - private static final int[] d; - private static final double e; - private static final double[] f; - private static final double[] g; - - static { - a = c(2.0f); - c = new Random(); - d = new int[] {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; - e = Double.longBitsToDouble(4805340802404319232L); - f = new double[257]; - g = new double[257]; - for(int var2 = 0; var2 < 257; ++var2) { - final double var3 = var2 / 256.0; - final double var4 = Math.asin(var3); - IrisMathHelper.g[var2] = Math.cos(var4); - IrisMathHelper.f[var2] = var4; - } - } - - public static float c(final float var0) { - return (float) Math.sqrt(var0); - } - - public static float sqrt(final double var0) { - return (float) Math.sqrt(var0); - } - - public static int d(final float var0) { - final int var = (int) var0; - return (var0 < var) ? (var - 1) : var; - } - - public static int floor(final double var0) { - final int var = (int) var0; - return (var0 < var) ? (var - 1) : var; - } - - public static long d(final double var0) { - final long var = (long) var0; - return (var0 < var) ? (var - 1L) : var; - } - - public static float e(final float var0) { - return Math.abs(var0); - } - - public static int a(final int var0) { - return Math.abs(var0); - } - - public static int f(final float var0) { - final int var = (int) var0; - return (var0 > var) ? (var + 1) : var; - } - - public static int f(final double var0) { - final int var = (int) var0; - return (var0 > var) ? (var + 1) : var; - } - - public static int clamp(final int var0, final int var1, final int var2) { - if(var0 < var1) { - return var1; - } - return Math.min(var0, var2); - } - - public static float a(final float var0, final float var1, final float var2) { - if(var0 < var1) { - return var1; - } - return Math.min(var0, var2); - } - - public static double a(final double var0, final double var2, final double var4) { - if(var0 < var2) { - return var2; - } - return Math.min(var0, var4); - } - - public static double b(final double var0, final double var2, final double var4) { - if(var4 < 0.0) { - return var0; - } - if(var4 > 1.0) { - return var2; - } - return d(var4, var0, var2); - } - - public static double a(double var0, double var2) { - if(var0 < 0.0) { - var0 = -var0; - } - if(var2 < 0.0) { - var2 = -var2; - } - return Math.max(var0, var2); - } - - public static int a(final int var0, final int var1) { - return Math.floorDiv(var0, var1); - } - - public static int nextInt(final Random var0, final int var1, final int var2) { - if(var1 >= var2) { - return var1; - } - return var0.nextInt(var2 - var1 + 1) + var1; - } - - public static float a(final Random var0, final float var1, final float var2) { - if(var1 >= var2) { - return var1; - } - return var0.nextFloat() * (var2 - var1) + var1; - } - - public static double a(final Random var0, final double var1, final double var3) { - if(var1 >= var3) { - return var1; - } - return var0.nextDouble() * (var3 - var1) + var1; - } - - public static double a(final long[] var0) { - long var = 0L; - for(final long var2 : var0) { - var += var2; - } - return var / (double) var0.length; - } - - public static boolean b(final double var0, final double var2) { - return Math.abs(var2 - var0) < 9.999999747378752E-6; - } - - public static int b(final int var0, final int var1) { - return Math.floorMod(var0, var1); - } - - public static float g(final float var0) { - float var = var0 % 360.0f; - if(var >= 180.0f) { - var -= 360.0f; - } - if(var < -180.0f) { - var += 360.0f; - } - return var; - } - - public static double g(final double var0) { - double var = var0 % 360.0; - if(var >= 180.0) { - var -= 360.0; - } - if(var < -180.0) { - var += 360.0; - } - return var; - } - - public static float c(final float var0, final float var1) { - return g(var1 - var0); - } - - public static float d(final float var0, final float var1) { - return e(c(var0, var1)); - } - - public static float b(final float var0, final float var1, final float var2) { - final float var3 = c(var0, var1); - final float var4 = a(var3, -var2, var2); - return var1 - var4; - } - - public static float c(final float var0, final float var1, float var2) { - var2 = e(var2); - if(var0 < var1) { - return a(var0 + var2, var0, var1); - } - return a(var0 - var2, var1, var0); - } - - public static float d(final float var0, final float var1, final float var2) { - final float var3 = c(var0, var1); - return c(var0, var0 + var3, var2); - } - - public static int c(final int var0) { - int var = var0 - 1; - var |= var >> 1; - var |= var >> 2; - var |= var >> 4; - var |= var >> 8; - var |= var >> 16; - return var + 1; - } - - public static boolean d(final int var0) { - return var0 != 0 && (var0 & var0 - 1) == 0x0; - } - - public static int e(int var0) { - var0 = (d(var0) ? var0 : c(var0)); - return IrisMathHelper.d[(int) (var0 * 125613361L >> 27) & 0x1F]; - } - - public static int f(final int var0) { - return e(var0) - (d(var0) ? 0 : 1); - } - - public static int c(final int var0, int var1) { - if(var1 == 0) { - return 0; - } - if(var0 == 0) { - return var1; - } - if(var0 < 0) { - var1 *= -1; - } - final int var2 = var0 % var1; - if(var2 == 0) { - return var0; - } - return var0 + var1 - var2; - } - - public static float h(final float var0) { - return var0 - d(var0); - } - - public static double h(final double var0) { - return var0 - d(var0); - } - - public static long c(final int var0, final int var1, final int var2) { - long var3 = (var0 * 3129871L) ^ var2 * 116129781L ^ (long) var1; - var3 = var3 * var3 * 42317861L + var3 * 11L; - return var3 >> 16; - } - - public static UUID a(final Random var0) { - final long var = (var0.nextLong() & 0xFFFFFFFFFFFF0FFFL) | 0x4000L; - final long var2 = (var0.nextLong() & 0x3FFFFFFFFFFFFFFFL) | Long.MIN_VALUE; - return new UUID(var, var2); - } - - public static UUID a() { - return a(IrisMathHelper.c); - } - - public static double c(final double var0, final double var2, final double var4) { - return (var0 - var2) / (var4 - var2); - } - - public static double d(double var0, double var2) { - final double var3 = var2 * var2 + var0 * var0; - if(Double.isNaN(var3)) { - return Double.NaN; - } - final boolean var4 = var0 < 0.0; - if(var4) { - var0 = -var0; - } - final boolean var5 = var2 < 0.0; - if(var5) { - var2 = -var2; - } - final boolean var6 = var0 > var2; - if(var6) { - final double var7 = var2; - var2 = var0; - var0 = var7; - } - final double var7 = i(var3); - var2 *= var7; - var0 *= var7; - final double var8 = IrisMathHelper.e + var0; - final int var9 = (int) Double.doubleToRawLongBits(var8); - final double var10 = IrisMathHelper.f[var9]; - final double var11 = IrisMathHelper.g[var9]; - final double var12 = var8 - IrisMathHelper.e; - final double var13 = var0 * var11 - var2 * var12; - final double var14 = (6.0 + var13 * var13) * var13 * 0.16666666666666666; - double var15 = var10 + var14; - if(var6) { - var15 = 1.5707963267948966 - var15; - } - if(var5) { - var15 = 3.141592653589793 - var15; - } - if(var4) { - var15 = -var15; - } - return var15; - } - - public static double i(double var0) { - final double var = 0.5 * var0; - long var2 = Double.doubleToRawLongBits(var0); - var2 = 6910469410427058090L - (var2 >> 1); - var0 = Double.longBitsToDouble(var2); - var0 *= 1.5 - var * var0 * var0; - return var0; - } - - public static int f(final float var0, final float var1, final float var2) { - final int var3 = (int) (var0 * 6.0f) % 6; - final float var4 = var0 * 6.0f - var3; - final float var5 = var2 * (1.0f - var1); - final float var6 = var2 * (1.0f - var4 * var1); - final float var7 = var2 * (1.0f - (1.0f - var4) * var1); - float var8 = 0.0f; - float var9 = 0.0f; - float var10 = 0.0f; - switch(var3) { - case 0 -> { - var8 = var2; - var9 = var7; - var10 = var5; - } - case 1 -> { - var8 = var6; - var9 = var2; - var10 = var5; - } - case 2 -> { - var8 = var5; - var9 = var2; - var10 = var7; - } - case 3 -> { - var8 = var5; - var9 = var6; - var10 = var2; - } - case 4 -> { - var8 = var7; - var9 = var5; - var10 = var2; - } - case 5 -> { - var8 = var2; - var9 = var5; - var10 = var6; - } - default -> throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + var0 + ", " + var1 + ", " + var2); - } - final int var11 = clamp((int) (var8 * 255.0f), 0, 255); - final int var12 = clamp((int) (var9 * 255.0f), 0, 255); - final int var13 = clamp((int) (var10 * 255.0f), 0, 255); - return var11 << 16 | var12 << 8 | var13; - } - - public static int g(int var0) { - var0 ^= var0 >>> 16; - var0 *= -2048144789; - var0 ^= var0 >>> 13; - var0 *= -1028477387; - var0 ^= var0 >>> 16; - return var0; - } - - public static int a(int var0, final int var1, final IntPredicate var2) { - int var3 = var1 - var0; - while(var3 > 0) { - final int var4 = var3 / 2; - final int var5 = var0 + var4; - if(var2.test(var5)) { - var3 = var4; - } else { - var0 = var5 + 1; - var3 -= var4 + 1; - } - } - return var0; - } - - public static float g(final float var0, final float var1, final float var2) { - return var1 + var0 * (var2 - var1); - } - - public static double d(final double var0, final double var2, final double var4) { - return var2 + var0 * (var4 - var2); - } - - public static double a(final double var0, final double var2, final double var4, final double var6, final double var8, final double var10) { - return d(var2, d(var0, var4, var6), d(var0, var8, var10)); - } - - public static double a(final double var0, final double var2, final double var4, final double var6, final double var8, final double var10, final double var12, final double var14, final double var16, final double var18, final double var20) { - return d(var4, a(var0, var2, var6, var8, var10, var12), a(var0, var2, var14, var16, var18, var20)); - } - - public static double j(final double var0) { - return var0 * var0 * var0 * (var0 * (var0 * 6.0 - 15.0) + 10.0); - } - - public static int k(final double var0) { - if(var0 == 0.0) { - return 0; - } - return (var0 > 0.0) ? 1 : -1; - } - - @Deprecated - public static float j(final float var0, final float var1, final float var2) { - float var3; - for(var3 = var1 - var0; var3 < -180.0f; var3 += 360.0f) { - } - while(var3 >= 180.0f) { - var3 -= 360.0f; - } - return var0 + var2 * var3; - } - - public static float k(final float var0) { - return var0 * var0; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/math/KochanekBartelsInterpolation.java b/src/main/java/com/volmit/iris/util/math/KochanekBartelsInterpolation.java deleted file mode 100644 index 6c5449d12..000000000 --- a/src/main/java/com/volmit/iris/util/math/KochanekBartelsInterpolation.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import org.bukkit.util.Vector; - -import java.util.Collections; -import java.util.List; - -public class KochanekBartelsInterpolation implements PathInterpolation { - - private List nodes; - private Vector[] coeffA; - private Vector[] coeffB; - private Vector[] coeffC; - private Vector[] coeffD; - private double scaling; - - public KochanekBartelsInterpolation() { - setNodes(Collections.emptyList()); - } - - @Override - public void setNodes(List nodes) { - this.nodes = nodes; - recalc(); - } - - private void recalc() { - final int nNodes = nodes.size(); - coeffA = new Vector[nNodes]; - coeffB = new Vector[nNodes]; - coeffC = new Vector[nNodes]; - coeffD = new Vector[nNodes]; - - if(nNodes == 0) { - return; - } - - INode nodeB = nodes.get(0); - double tensionB = nodeB.getTension(); - double biasB = nodeB.getBias(); - double continuityB = nodeB.getContinuity(); - for(int i = 0; i < nNodes; ++i) { - final double tensionA = tensionB; - final double biasA = biasB; - final double continuityA = continuityB; - - if(i + 1 < nNodes) { - nodeB = nodes.get(i + 1); - tensionB = nodeB.getTension(); - biasB = nodeB.getBias(); - continuityB = nodeB.getContinuity(); - } - - // Kochanek-Bartels tangent coefficients - final double ta = (1 - tensionA) * (1 + biasA) * (1 + continuityA) / 2; // Factor for lhs of d[i] - final double tb = (1 - tensionA) * (1 - biasA) * (1 - continuityA) / 2; // Factor for rhs of d[i] - final double tc = (1 - tensionB) * (1 + biasB) * (1 - continuityB) / 2; // Factor for lhs of d[i+1] - final double td = (1 - tensionB) * (1 - biasB) * (1 + continuityB) / 2; // Factor for rhs of d[i+1] - - coeffA[i] = linearCombination(i, -ta, ta - tb - tc + 2, tb + tc - td - 2, td); - coeffB[i] = linearCombination(i, 2 * ta, -2 * ta + 2 * tb + tc - 3, -2 * tb - tc + td + 3, -td); - coeffC[i] = linearCombination(i, -ta, ta - tb, tb, 0); - //coeffD[i] = linearCombination(i, 0, 1, 0, 0); - coeffD[i] = retrieve(i); // this is an optimization - } - - scaling = nodes.size() - 1; - } - - /** - * Returns the linear combination of the given coefficients with the nodes adjacent to baseIndex. - * - * @param baseIndex - * node index - * @param f1 - * coefficient for baseIndex-1 - * @param f2 - * coefficient for baseIndex - * @param f3 - * coefficient for baseIndex+1 - * @param f4 - * coefficient for baseIndex+2 - * @return linear combination of nodes[n-1..n+2] with f1..4 - */ - private Vector linearCombination(int baseIndex, double f1, double f2, double f3, double f4) { - final Vector r1 = retrieve(baseIndex - 1).multiply(f1); - final Vector r2 = retrieve(baseIndex).multiply(f2); - final Vector r3 = retrieve(baseIndex + 1).multiply(f3); - final Vector r4 = retrieve(baseIndex + 2).multiply(f4); - - return r1.add(r2).add(r3).add(r4); - } - - /** - * Retrieves a node. Indexes are clamped to the valid range. - * - * @param index - * node index to retrieve - * @return nodes[clamp(0, nodes.length - 1)] - */ - private Vector retrieve(int index) { - if(index < 0) { - return fastRetrieve(0); - } - - if(index >= nodes.size()) { - return fastRetrieve(nodes.size() - 1); - } - - return fastRetrieve(index); - } - - private Vector fastRetrieve(int index) { - return nodes.get(index).getPosition(); - } - - @Override - public Vector getPosition(double position) { - if(coeffA == null) { - throw new IllegalStateException("Must call setNodes first."); - } - - if(position > 1) { - return null; - } - - position *= scaling; - - final int index = (int) Math.floor(position); - final double remainder = position - index; - - final Vector a = coeffA[index]; - final Vector b = coeffB[index]; - final Vector c = coeffC[index]; - final Vector d = coeffD[index]; - - return a.multiply(remainder).add(b).multiply(remainder).add(c).multiply(remainder).add(d); - } - - @Override - public Vector get1stDerivative(double position) { - if(coeffA == null) { - throw new IllegalStateException("Must call setNodes first."); - } - - if(position > 1) { - return null; - } - - position *= scaling; - - final int index = (int) Math.floor(position); - //final double remainder = position - index; - - final Vector a = coeffA[index]; - final Vector b = coeffB[index]; - final Vector c = coeffC[index]; - - return a.multiply(1.5 * position - 3.0 * index).add(b).multiply(2.0 * position).add(a.multiply(1.5 * index).subtract(b).multiply(2.0 * index)).add(c).multiply(scaling); - } - - @Override - public double arcLength(double positionA, double positionB) { - if(coeffA == null) { - throw new IllegalStateException("Must call setNodes first."); - } - - if(positionA > positionB) { - return arcLength(positionB, positionA); - } - - positionA *= scaling; - positionB *= scaling; - - final int indexA = (int) Math.floor(positionA); - final double remainderA = positionA - indexA; - - final int indexB = (int) Math.floor(positionB); - final double remainderB = positionB - indexB; - - return arcLengthRecursive(indexA, remainderA, indexB, remainderB); - } - - /** - * Assumes a < b. - */ - private double arcLengthRecursive(int indexLeft, double remainderLeft, int indexRight, double remainderRight) { - switch(indexRight - indexLeft) { - case 0: - return arcLengthRecursive(indexLeft, remainderLeft, remainderRight); - - case 1: - // This case is merely a speed-up for a very common case - return arcLengthRecursive(indexLeft, remainderLeft, 1.0) - + arcLengthRecursive(indexRight, 0.0, remainderRight); - - default: - return arcLengthRecursive(indexLeft, remainderLeft, indexRight - 1, 1.0) - + arcLengthRecursive(indexRight, 0.0, remainderRight); - } - } - - private double arcLengthRecursive(int index, double remainderLeft, double remainderRight) { - final Vector a = coeffA[index].multiply(3.0); - final Vector b = coeffB[index].multiply(2.0); - final Vector c = coeffC[index]; - - final int nPoints = 8; - - double accum = a.multiply(remainderLeft).add(b).multiply(remainderLeft).add(c).length() / 2.0; - for(int i = 1; i < nPoints - 1; ++i) { - double t = ((double) i) / nPoints; - t = (remainderRight - remainderLeft) * t + remainderLeft; - accum += a.multiply(t).add(b).multiply(t).add(c).length(); - } - - accum += a.multiply(remainderRight).add(b).multiply(remainderRight).add(c).length() / 2.0; - return accum * (remainderRight - remainderLeft) / nPoints; - } - - @Override - public int getSegment(double position) { - if(coeffA == null) { - throw new IllegalStateException("Must call setNodes first."); - } - - if(position > 1) { - return Integer.MAX_VALUE; - } - - position *= scaling; - - return (int) Math.floor(position); - } - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/math/M.java b/src/main/java/com/volmit/iris/util/math/M.java deleted file mode 100644 index 648d52966..000000000 --- a/src/main/java/com/volmit/iris/util/math/M.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; -import java.util.regex.Matcher; - -/** - * Math - * - * @author cyberpwn - */ -public class M { - private static final int precision = 128; - private static final int modulus = 360 * precision; - private static final float[] sin = new float[modulus]; - public static int tick = 0; - - static { - for(int i = 0; i < sin.length; i++) { - sin[i] = (float) Math.sin((i * Math.PI) / (precision * 180)); - } - } - - /** - * Scales B by an external range change so that
- *
- * BMIN < B < BMAX
- * AMIN < RESULT < AMAX
- *
- * So Given rangeScale(0, 20, 0, 10, 5) -> 10
- * 0 < 5 < 10
- * 0 < ? < 20
- *
- * would return 10 - * - * @param amin - * the resulting minimum - * @param amax - * the resulting maximum - * @param bmin - * the initial minimum - * @param bmax - * the initial maximum - * @param b - * the initial value - * @return the resulting value - */ - public static double rangeScale(double amin, double amax, double bmin, double bmax, double b) { - return amin + ((amax - amin) * ((b - bmin) / (bmax - bmin))); - } - - /** - * Get the percent (inverse lerp) from "from" to "to" where "at". - *

- * If from = 0 and to = 100 and at = 25 then it would return 0.25 - * - * @param from - * the from - * @param to - * the to - * @param at - * the at - * @return the percent - */ - public static double lerpInverse(double from, double to, double at) { - return M.rangeScale(0, 1, from, to, at); - } - - /** - * Linear interpolation from a to b where f is the percent across - * - * @param a - * the first pos (0) - * @param b - * the second pos (1) - * @param f - * the percent - * @return the value - */ - public static double lerp(double a, double b, double f) { - return a + (f * (b - a)); - } - - /** - * Bilinear interpolation - * - * @param a - * the first point (0, 0) - * @param b - * the second point (1, 0) - * @param c - * the third point (0, 1) - * @param d - * the fourth point (1, 1) - * @return the bilerped value - */ - public static double bilerp(double a, double b, double c, double d, double x, double y) { - return lerp(lerp(a, b, x), lerp(c, d, x), y); - } - - /** - * Trilinear interpolation - * - * @param a - * the first point (0, 0, 0) - * @param b - * the second point (1, 0, 0) - * @param c - * the third point (0, 0, 1) - * @param d - * the fourth point (1, 0, 1) - * @param e - * the fifth point (0, 1, 0) - * @param f - * the sixth point (1, 1, 0) - * @param g - * the seventh point (0, 1, 1) - * @param h - * the eighth point (1, 1, 1) - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @return the trilerped value - */ - public static double trilerp(double a, double b, double c, double d, double e, double f, double g, double h, double x, double y, double z) { - return lerp(bilerp(a, b, c, d, x, y), bilerp(e, f, g, h, x, y), z); - } - - /** - * Clip a value - * - * @param value - * the value - * @param min - * the min - * @param max - * the max - * @return the clipped value - */ - @SuppressWarnings("unchecked") - public static T clip(T value, T min, T max) { - return (T) Double.valueOf(Math.min(max.doubleValue(), Math.max(min.doubleValue(), value.doubleValue()))); - } - - /** - * Get true or false based on random percent - * - * @param d - * between 0 and 1 - * @return true if true - */ - public static boolean r(Double d) { - //noinspection ReplaceNullCheck - if(d == null) { - return Math.random() < 0.5; - } - - return Math.random() < d; - } - - /** - * Get the ticks per second from a time in nanoseconds, the rad can be used for - * multiple ticks - * - * @param ns - * the time in nanoseconds - * @param rad - * the radius of the time - * @return the ticks per second in double form - */ - public static double tps(long ns, int rad) { - return (20.0 * (ns / 50000000.0)) / rad; - } - - /** - * Get the number of ticks from a time in nanoseconds - * - * @param ns - * the nanoseconds - * @return the amount of ticks - */ - public static double ticksFromNS(long ns) { - return (ns / 50000000.0); - } - - /** - * Get a random int from to (inclusive) - * - * @param f - * the from - * @param t - * the to - * @return the value - */ - public static int irand(int f, int t) { - return f + (int) (Math.random() * ((t - f) + 1)); - } - - /** - * Get a random float from to (inclusive) - * - * @param f - * the from - * @param t - * the to - * @return the value - */ - public static float frand(float f, float t) { - return f + (float) (Math.random() * ((t - f) + 1)); - } - - /** - * Get a random double from to (inclusive) - * - * @param f - * the from - * @param t - * the to - * @return the value - */ - public static double drand(double f, double t) { - return f + (Math.random() * ((t - f) + 1)); - } - - /** - * Get system Nanoseconds - * - * @return nanoseconds (current) - */ - public static long ns() { - return System.nanoTime(); - } - - /** - * Get the current millisecond time - * - * @return milliseconds - */ - public static long ms() { - return System.currentTimeMillis(); - } - - /** - * Fast sin function - * - * @param a - * the number - * @return the sin - */ - public static float sin(float a) { - return sinLookup((int) (a * precision + 0.5f)); - } - - /** - * Fast cos function - * - * @param a - * the number - * @return the cos - */ - public static float cos(float a) { - return sinLookup((int) ((a + 90f) * precision + 0.5f)); - } - - /** - * Fast tan function - * - * @param a - * the number - * @return the tan - */ - public static float tan(float a) { - float c = cos(a); - return sin(a) / (c == 0 ? 0.0000001f : c); - } - - /** - * Biggest number - * - * @return the biggest one - */ - @SuppressWarnings("unchecked") - public static T max(T... doubles) { - double max = Double.MIN_VALUE; - - for(T i : doubles) { - if(i.doubleValue() > max) { - max = i.doubleValue(); - } - } - - return (T) Double.valueOf(max); - } - - /** - * Smallest number - * - * @param doubles - * the numbers - * @return the smallest one - */ - @SuppressWarnings("unchecked") - public static T min(T... doubles) { - double min = Double.MAX_VALUE; - - for(T i : doubles) { - if(i.doubleValue() < min) { - min = i.doubleValue(); - } - } - - return (T) Double.valueOf(min); - } - - /** - * Evaluates an expression using javascript engine and returns the double - * result. This can take variable parameters, so you need to define them. - * Parameters are defined as $[0-9]. For example evaluate("4$0/$1", 1, 2); This - * makes the expression (4x1)/2 == 2. Keep note that you must use 0-9, you - * cannot skip, or start at a number other than 0. - * - * @param expression - * the expression with variables - * @param args - * the arguments/variables - * @return the resulting double value - * @throws ScriptException - * ... gg - * @throws IndexOutOfBoundsException - * learn to count - */ - public static double evaluate(String expression, Double... args) throws ScriptException, IndexOutOfBoundsException { - for(int i = 0; i < args.length; i++) { - String current = "$" + i; - - if(expression.contains(current)) { - expression = expression.replaceAll(Matcher.quoteReplacement(current), args[i] + ""); - } - } - - return evaluate(expression); - } - - /** - * Evaluates an expression using javascript engine and returns the double - * - * @param expression - * the mathimatical expression - * @return the double result - * @throws ScriptException - * ... gg - */ - public static double evaluate(String expression) throws ScriptException { - ScriptEngineManager mgr = new ScriptEngineManager(); - ScriptEngine scriptEngine = mgr.getEngineByName("JavaScript"); - - return Double.parseDouble(scriptEngine.eval(expression).toString()); - } - - /** - * is the number "is" within from-to - * - * @param from - * the lower end - * @param to - * the upper end - * @param is - * the check - * @return true if its within - */ - public static boolean within(int from, int to, int is) { - return is >= from && is <= to; - } - - /** - * Get the amount of days past since the epoch time (1970 jan 1 utc) - * - * @return the epoch days - */ - public static long epochDays() { - return epochDays(M.ms()); - } - - /** - * Get the amount of days past since the epoch time (1970 jan 1 utc) - * - * @param ms - * the time in milliseconds - * @return the epoch days - */ - private static long epochDays(long ms) { - return ms / 1000 / 60 / 60 / 24; - } - - private static float sinLookup(int a) { - return a >= 0 ? sin[a % (modulus)] : -sin[-a % (modulus)]; - } - - public static boolean interval(int tickInterval) { - return tick % (tickInterval <= 0 ? 1 : tickInterval) == 0; - } - -} diff --git a/src/main/java/com/volmit/iris/util/math/MathHelper.java b/src/main/java/com/volmit/iris/util/math/MathHelper.java deleted file mode 100644 index 924b58419..000000000 --- a/src/main/java/com/volmit/iris/util/math/MathHelper.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import java.util.Random; -import java.util.UUID; -import java.util.function.IntPredicate; - -public class MathHelper { - public static final float a = 3.1415927F; - public static final float b = 1.5707964F; - public static final float c = 6.2831855F; - public static final float d = 0.017453292F; - public static final float e = 57.295776F; - public static final float f = 1.0E-5F; - public static final float g = c(2.0F); - private static final int h = 1024; - private static final float i = 1024.0F; - private static final long j = 61440L; - private static final long k = 16384L; - private static final long l = -4611686018427387904L; - private static final long m = -9223372036854775808L; - private static final float n = 10430.378F; - private static final Random p = new Random(); - private static final int[] q = new int[] {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; - private static final double r = 0.16666666666666666D; - private static final int s = 8; - private static final int t = 257; - private static final double u = Double.longBitsToDouble(4805340802404319232L); - private static final double[] v = new double[257]; - private static final double[] w = new double[257]; - - static { - for(int var0 = 0; var0 < 257; ++var0) { - double var1 = (double) var0 / 256.0D; - double var3 = Math.asin(var1); - w[var0] = Math.cos(var3); - v[var0] = var3; - } - - } - - public MathHelper() { - } - - public static float c(float var0) { - return (float) Math.sqrt(var0); - } - - public static int d(float var0) { - int var1 = (int) var0; - return var0 < (float) var1 ? var1 - 1 : var1; - } - - public static int a(double var0) { - return (int) (var0 + 1024.0D) - 1024; - } - - public static int floor(double var0) { - int var2 = (int) var0; - return var0 < (double) var2 ? var2 - 1 : var2; - } - - public static long c(double var0) { - long var2 = (long) var0; - return var0 < (double) var2 ? var2 - 1L : var2; - } - - public static int d(double var0) { - return (int) (var0 >= 0.0D ? var0 : -var0 + 1.0D); - } - - public static float e(float var0) { - return Math.abs(var0); - } - - public static int a(int var0) { - return Math.abs(var0); - } - - public static int f(float var0) { - int var1 = (int) var0; - return var0 > (float) var1 ? var1 + 1 : var1; - } - - public static int e(double var0) { - int var2 = (int) var0; - return var0 > (double) var2 ? var2 + 1 : var2; - } - - public static byte a(byte var0, byte var1, byte var2) { - if(var0 < var1) { - return var1; - } else { - return var0 > var2 ? var2 : var0; - } - } - - public static int clamp(int var0, int var1, int var2) { - if(var0 < var1) { - return var1; - } else { - return Math.min(var0, var2); - } - } - - public static long a(long var0, long var2, long var4) { - if(var0 < var2) { - return var2; - } else { - return Math.min(var0, var4); - } - } - - public static float a(float var0, float var1, float var2) { - if(var0 < var1) { - return var1; - } else { - return Math.min(var0, var2); - } - } - - public static double a(double var0, double var2, double var4) { - if(var0 < var2) { - return var2; - } else { - return Math.min(var0, var4); - } - } - - public static double b(double var0, double var2, double var4) { - if(var4 < 0.0D) { - return var0; - } else { - return var4 > 1.0D ? var2 : d(var4, var0, var2); - } - } - - public static float b(float var0, float var1, float var2) { - if(var2 < 0.0F) { - return var0; - } else { - return var2 > 1.0F ? var1 : h(var2, var0, var1); - } - } - - public static double a(double var0, double var2) { - if(var0 < 0.0D) { - var0 = -var0; - } - - if(var2 < 0.0D) { - var2 = -var2; - } - - return Math.max(var0, var2); - } - - public static int a(int var0, int var1) { - return Math.floorDiv(var0, var1); - } - - public static int nextInt(Random var0, int var1, int var2) { - return var1 >= var2 ? var1 : var0.nextInt(var2 - var1 + 1) + var1; - } - - public static float a(Random var0, float var1, float var2) { - return var1 >= var2 ? var1 : var0.nextFloat() * (var2 - var1) + var1; - } - - public static double a(Random var0, double var1, double var3) { - return var1 >= var3 ? var1 : var0.nextDouble() * (var3 - var1) + var1; - } - - public static double a(long[] var0) { - long var1 = 0L; - long[] var3 = var0; - int var4 = var0.length; - - for(int var5 = 0; var5 < var4; ++var5) { - long var6 = var3[var5]; - var1 += var6; - } - - return (double) var1 / (double) var0.length; - } - - public static boolean a(float var0, float var1) { - return Math.abs(var1 - var0) < 1.0E-5F; - } - - public static boolean b(double var0, double var2) { - return Math.abs(var2 - var0) < 9.999999747378752E-6D; - } - - public static int b(int var0, int var1) { - return Math.floorMod(var0, var1); - } - - public static float b(float var0, float var1) { - return (var0 % var1 + var1) % var1; - } - - public static double c(double var0, double var2) { - return (var0 % var2 + var2) % var2; - } - - public static int b(int var0) { - int var1 = var0 % 360; - if(var1 >= 180) { - var1 -= 360; - } - - if(var1 < -180) { - var1 += 360; - } - - return var1; - } - - public static float g(float var0) { - float var1 = var0 % 360.0F; - if(var1 >= 180.0F) { - var1 -= 360.0F; - } - - if(var1 < -180.0F) { - var1 += 360.0F; - } - - return var1; - } - - public static double f(double var0) { - double var2 = var0 % 360.0D; - if(var2 >= 180.0D) { - var2 -= 360.0D; - } - - if(var2 < -180.0D) { - var2 += 360.0D; - } - - return var2; - } - - public static float c(float var0, float var1) { - return g(var1 - var0); - } - - public static float d(float var0, float var1) { - return e(c(var0, var1)); - } - - public static float c(float var0, float var1, float var2) { - float var3 = c(var0, var1); - float var4 = a(var3, -var2, var2); - return var1 - var4; - } - - public static float d(float var0, float var1, float var2) { - var2 = e(var2); - return var0 < var1 ? a(var0 + var2, var0, var1) : a(var0 - var2, var1, var0); - } - - public static float e(float var0, float var1, float var2) { - float var3 = c(var0, var1); - return d(var0, var0 + var3, var2); - } - - public static double a(String var0, double var1) { - try { - return Double.parseDouble(var0); - } catch(Throwable var4) { - return var1; - } - } - - public static double a(String var0, double var1, double var3) { - return Math.max(var3, a(var0, var1)); - } - - public static int c(int var0) { - int var1 = var0 - 1; - var1 |= var1 >> 1; - var1 |= var1 >> 2; - var1 |= var1 >> 4; - var1 |= var1 >> 8; - var1 |= var1 >> 16; - return var1 + 1; - } - - public static boolean d(int var0) { - return var0 != 0 && (var0 & var0 - 1) == 0; - } - - public static int e(int var0) { - var0 = d(var0) ? var0 : c(var0); - return q[(int) ((long) var0 * 125613361L >> 27) & 31]; - } - - public static int f(int var0) { - return e(var0) - (d(var0) ? 0 : 1); - } - - public static int f(float var0, float var1, float var2) { - return b(d(var0 * 255.0F), d(var1 * 255.0F), d(var2 * 255.0F)); - } - - public static int b(int var0, int var1, int var2) { - int var3 = (var0 << 8) + var1; - var3 = (var3 << 8) + var2; - return var3; - } - - public static int c(int var0, int var1) { - int var2 = (var0 & 16711680) >> 16; - int var3 = (var1 & 16711680) >> 16; - int var4 = (var0 & '\uff00') >> 8; - int var5 = (var1 & '\uff00') >> 8; - int var6 = (var0 & 255); - int var7 = (var1 & 255); - int var8 = (int) ((float) var2 * (float) var3 / 255.0F); - int var9 = (int) ((float) var4 * (float) var5 / 255.0F); - int var10 = (int) ((float) var6 * (float) var7 / 255.0F); - return var0 & -16777216 | var8 << 16 | var9 << 8 | var10; - } - - public static int a(int var0, float var1, float var2, float var3) { - int var4 = (var0 & 16711680) >> 16; - int var5 = (var0 & '\uff00') >> 8; - int var6 = (var0 & 255); - int var7 = (int) ((float) var4 * var1); - int var8 = (int) ((float) var5 * var2); - int var9 = (int) ((float) var6 * var3); - return var0 & -16777216 | var7 << 16 | var8 << 8 | var9; - } - - public static float h(float var0) { - return var0 - (float) d(var0); - } - - public static double g(double var0) { - return var0 - (double) c(var0); - } - - public static long c(int var0, int var1, int var2) { - long var3 = (long) (var0 * 3129871) ^ (long) var2 * 116129781L ^ (long) var1; - var3 = var3 * var3 * 42317861L + var3 * 11L; - return var3 >> 16; - } - - public static UUID a(Random var0) { - long var1 = var0.nextLong() & -61441L | 16384L; - long var3 = var0.nextLong() & 4611686018427387903L | -9223372036854775808L; - return new UUID(var1, var3); - } - - public static UUID a() { - return a(p); - } - - public static double c(double var0, double var2, double var4) { - return (var0 - var2) / (var4 - var2); - } - - public static double d(double var0, double var2) { - double var4 = var2 * var2 + var0 * var0; - if(Double.isNaN(var4)) { - return 0.0D; - } else { - boolean var6 = var0 < 0.0D; - if(var6) { - var0 = -var0; - } - - boolean var7 = var2 < 0.0D; - if(var7) { - var2 = -var2; - } - - boolean var8 = var0 > var2; - double var9; - if(var8) { - var9 = var2; - var2 = var0; - var0 = var9; - } - - var9 = h(var4); - var2 *= var9; - var0 *= var9; - double var11 = u + var0; - int var13 = (int) Double.doubleToRawLongBits(var11); - double var14 = v[var13]; - double var16 = w[var13]; - double var18 = var11 - u; - double var20 = var0 * var16 - var2 * var18; - double var22 = (6.0D + var20 * var20) * var20 * 0.16666666666666666D; - double var24 = var14 + var22; - if(var8) { - var24 = 1.5707963267948966D - var24; - } - - if(var7) { - var24 = 3.141592653589793D - var24; - } - - if(var6) { - var24 = -var24; - } - - return var24; - } - } - - public static float i(float var0) { - float var1 = 0.5F * var0; - int var2 = Float.floatToIntBits(var0); - var2 = 1597463007 - (var2 >> 1); - var0 = Float.intBitsToFloat(var2); - var0 *= 1.5F - var1 * var0 * var0; - return var0; - } - - public static double h(double var0) { - double var2 = 0.5D * var0; - long var4 = Double.doubleToRawLongBits(var0); - var4 = 6910469410427058090L - (var4 >> 1); - var0 = Double.longBitsToDouble(var4); - var0 *= 1.5D - var2 * var0 * var0; - return var0; - } - - public static float j(float var0) { - int var1 = Float.floatToIntBits(var0); - var1 = 1419967116 - var1 / 3; - float var2 = Float.intBitsToFloat(var1); - var2 = 0.6666667F * var2 + 1.0F / (3.0F * var2 * var2 * var0); - var2 = 0.6666667F * var2 + 1.0F / (3.0F * var2 * var2 * var0); - return var2; - } - - public static int g(float var0, float var1, float var2) { - int var3 = (int) (var0 * 6.0F) % 6; - float var4 = var0 * 6.0F - (float) var3; - float var5 = var2 * (1.0F - var1); - float var6 = var2 * (1.0F - var4 * var1); - float var7 = var2 * (1.0F - (1.0F - var4) * var1); - float var8; - float var9; - float var10; - switch(var3) { - case 0: - var8 = var2; - var9 = var7; - var10 = var5; - break; - case 1: - var8 = var6; - var9 = var2; - var10 = var5; - break; - case 2: - var8 = var5; - var9 = var2; - var10 = var7; - break; - case 3: - var8 = var5; - var9 = var6; - var10 = var2; - break; - case 4: - var8 = var7; - var9 = var5; - var10 = var2; - break; - case 5: - var8 = var2; - var9 = var5; - var10 = var6; - break; - default: - throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + var0 + ", " + var1 + ", " + var2); - } - - int var11 = clamp((int) (var8 * 255.0F), 0, 255); - int var12 = clamp((int) (var9 * 255.0F), 0, 255); - int var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - } - - public static int g(int var0) { - var0 ^= var0 >>> 16; - var0 *= -2048144789; - var0 ^= var0 >>> 13; - var0 *= -1028477387; - var0 ^= var0 >>> 16; - return var0; - } - - public static long a(long var0) { - var0 ^= var0 >>> 33; - var0 *= -49064778989728563L; - var0 ^= var0 >>> 33; - var0 *= -4265267296055464877L; - var0 ^= var0 >>> 33; - return var0; - } - - public static double[] a(double... var0) { - float var1 = 0.0F; - double[] var2f = var0; - int var3 = var0.length; - - for(int var4 = 0; var4 < var3; ++var4) { - double var5 = var2f[var4]; - var1 = (float) ((double) var1 + var5); - } - - int var2; - for(var2 = 0; var2 < var0.length; ++var2) { - var0[var2] /= var1; - } - - for(var2 = 0; var2 < var0.length; ++var2) { - var0[var2] += var2 == 0 ? 0.0D : var0[var2 - 1]; - } - - return var0; - } - - public static int a(Random var0, double[] var1) { - double var2 = var0.nextDouble(); - - for(int var4 = 0; var4 < var1.length; ++var4) { - if(var2 < var1[var4]) { - return var4; - } - } - - return var1.length; - } - - public static double[] a(double var0, double var2, double var4, int var6, int var7) { - double[] var8 = new double[var7 - var6 + 1]; - int var9 = 0; - - for(int var10 = var6; var10 <= var7; ++var10) { - var8[var9] = Math.max(0.0D, var0 * StrictMath.exp(-((double) var10 - var4) * ((double) var10 - var4) / (2.0D * var2 * var2))); - ++var9; - } - - return var8; - } - - public static double[] a(double var0, double var2, double var4, double var6, double var8, double var10, int var12, int var13) { - double[] var14 = new double[var13 - var12 + 1]; - int var15 = 0; - - for(int var16 = var12; var16 <= var13; ++var16) { - var14[var15] = Math.max(0.0D, var0 * StrictMath.exp(-((double) var16 - var4) * ((double) var16 - var4) / (2.0D * var2 * var2)) + var6 * StrictMath.exp(-((double) var16 - var10) * ((double) var16 - var10) / (2.0D * var8 * var8))); - ++var15; - } - - return var14; - } - - public static double[] a(double var0, double var2, int var4, int var5) { - double[] var6 = new double[var5 - var4 + 1]; - int var7 = 0; - - for(int var8 = var4; var8 <= var5; ++var8) { - var6[var7] = Math.max(var0 * StrictMath.log(var8) + var2, 0.0D); - ++var7; - } - - return var6; - } - - public static int a(int var0, int var1, IntPredicate var2) { - int var3 = var1 - var0; - - while(var3 > 0) { - int var4 = var3 / 2; - int var5 = var0 + var4; - if(var2.test(var5)) { - var3 = var4; - } else { - var0 = var5 + 1; - var3 -= var4 + 1; - } - } - - return var0; - } - - public static float h(float var0, float var1, float var2) { - return var1 + var0 * (var2 - var1); - } - - public static double d(double var0, double var2, double var4) { - return var2 + var0 * (var4 - var2); - } - - public static double a(double var0, double var2, double var4, double var6, double var8, double var10) { - return d(var2, d(var0, var4, var6), d(var0, var8, var10)); - } - - public static double a(double var0, double var2, double var4, double var6, double var8, double var10, double var12, double var14, double var16, double var18, double var20) { - return d(var4, a(var0, var2, var6, var8, var10, var12), a(var0, var2, var14, var16, var18, var20)); - } - - public static double i(double var0) { - return var0 * var0 * var0 * (var0 * (var0 * 6.0D - 15.0D) + 10.0D); - } - - public static double j(double var0) { - return 30.0D * var0 * var0 * (var0 - 1.0D) * (var0 - 1.0D); - } - - public static int k(double var0) { - if(var0 == 0.0D) { - return 0; - } else { - return var0 > 0.0D ? 1 : -1; - } - } - - public static float i(float var0, float var1, float var2) { - return var1 + var0 * g(var2 - var1); - } - - public static float j(float var0, float var1, float var2) { - return Math.min(var0 * var0 * 0.6F + var1 * var1 * ((3.0F + var1) / 4.0F) + var2 * var2 * 0.8F, 1.0F); - } - - @Deprecated - public static float k(float var0, float var1, float var2) { - float var3; - for(var3 = var1 - var0; var3 < -180.0F; var3 += 360.0F) { - } - - while(var3 >= 180.0F) { - var3 -= 360.0F; - } - - return var0 + var2 * var3; - } - - @Deprecated - public static float l(double var0) { - while(var0 >= 180.0D) { - var0 -= 360.0D; - } - - while(var0 < -180.0D) { - var0 += 360.0D; - } - - return (float) var0; - } - - public static float e(float var0, float var1) { - return (Math.abs(var0 % var1 - var1 * 0.5F) - var1 * 0.25F) / (var1 * 0.25F); - } - - public static float k(float var0) { - return var0 * var0; - } - - public static double m(double var0) { - return var0 * var0; - } - - public static int h(int var0) { - return var0 * var0; - } - - public static double a(double var0, double var2, double var4, double var6, double var8) { - return b(var6, var8, c(var0, var2, var4)); - } - - public static double b(double var0, double var2, double var4, double var6, double var8) { - return d(c(var0, var2, var4), var6, var8); - } - - public static double n(double var0) { - return var0 + (2.0D * (new Random(floor(var0 * 3000.0D))).nextDouble() - 1.0D) * 1.0E-7D / 2.0D; - } - - public static int d(int var0, int var1) { - return (var0 + var1 - 1) / var1 * var1; - } - - public static int b(Random var0, int var1, int var2) { - return var0.nextInt(var2 - var1 + 1) + var1; - } - - public static float b(Random var0, float var1, float var2) { - return var0.nextFloat() * (var2 - var1) + var1; - } - - public static float c(Random var0, float var1, float var2) { - return var1 + (float) var0.nextGaussian() * var2; - } - - public static double a(int var0, double var1, int var3) { - return Math.sqrt((double) (var0 * var0) + var1 * var1 + (double) (var3 * var3)); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/math/PathInterpolation.java b/src/main/java/com/volmit/iris/util/math/PathInterpolation.java deleted file mode 100644 index 03f84f696..000000000 --- a/src/main/java/com/volmit/iris/util/math/PathInterpolation.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import org.bukkit.util.Vector; - -import java.util.List; - -public interface PathInterpolation { - - /** - * Sets nodes to be used by subsequent calls to - * {@link #getPosition(double)} and the other methods. - * - * @param nodes - * the nodes - */ - void setNodes(List nodes); - - /** - * Gets the result of f(position). - * - * @param position - * the position to interpolate - * @return the result - */ - Vector getPosition(double position); - - /** - * Gets the result of f'(position). - * - * @param position - * the position to interpolate - * @return the result - */ - Vector get1stDerivative(double position); - - /** - * Gets the result of ∫ab|f'(t)| dt.
- * That means it calculates the arc length (in meters) between positionA - * and positionB. - * - * @param positionA - * lower limit - * @param positionB - * upper limit - * @return the arc length - */ - double arcLength(double positionA, double positionB); - - /** - * Get the segment position. - * - * @param position - * the position - * @return the segment position - */ - int getSegment(double position); - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/math/Point3d.java b/src/main/java/com/volmit/iris/util/math/Point3d.java deleted file mode 100644 index d1743a59f..000000000 --- a/src/main/java/com/volmit/iris/util/math/Point3d.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * A 3 element point that is represented by double precision floating point - * x,y,z coordinates. - */ -public class Point3d extends Tuple3d implements java.io.Serializable { - - // Compatible with 1.1 - static final long serialVersionUID = 5718062286069042927L; - - /** - * Constructs and initializes a Point3d from the specified xyz coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - */ - public Point3d(double x, double y, double z) { - super(x, y, z); - } - - - /** - * Constructs and initializes a Point3d from the array of length 3. - * - * @param p - * the array of length 3 containing xyz in order - */ - public Point3d(double[] p) { - super(p); - } - - - /** - * Constructs and initializes a Point3d from the specified Point3d. - * - * @param p1 - * the Point3d containing the initialization x y z data - */ - public Point3d(Point3d p1) { - super(p1); - } - - - /** - * Constructs and initializes a Point3d from the specified Point3f. - * - * @param p1 - * the Point3f containing the initialization x y z data - */ - public Point3d(Point3f p1) { - super(p1); - } - - - /** - * Constructs and initializes a Point3d from the specified Tuple3f. - * - * @param t1 - * the Tuple3f containing the initialization x y z data - */ - public Point3d(Tuple3f t1) { - super(t1); - } - - - /** - * Constructs and initializes a Point3d from the specified Tuple3d. - * - * @param t1 - * the Tuple3d containing the initialization x y z data - */ - public Point3d(Tuple3d t1) { - super(t1); - } - - - /** - * Constructs and initializes a Point3d to (0,0,0). - */ - public Point3d() { - super(); - } - - - /** - * Returns the square of the distance between this point and point p1. - * - * @param p1 - * the other point - * @return the square of the distance - */ - public final double distanceSquared(Point3d p1) { - double dx, dy, dz; - - dx = this.x - p1.x; - dy = this.y - p1.y; - dz = this.z - p1.z; - return (dx * dx + dy * dy + dz * dz); - } - - - /** - * Returns the distance between this point and point p1. - * - * @param p1 - * the other point - * @return the distance - */ - public final double distance(Point3d p1) { - double dx, dy, dz; - - dx = this.x - p1.x; - dy = this.y - p1.y; - dz = this.z - p1.z; - return Math.sqrt(dx * dx + dy * dy + dz * dz); - } - - - /** - * Computes the L-1 (Manhattan) distance between this point and - * point p1. The L-1 distance is equal to: - * abs(x1-x2) + abs(y1-y2) + abs(z1-z2). - * - * @param p1 - * the other point - * @return the L-1 distance - */ - public final double distanceL1(Point3d p1) { - return Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) + - Math.abs(this.z - p1.z); - } - - - /** - * Computes the L-infinite distance between this point and - * point p1. The L-infinite distance is equal to - * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. - * - * @param p1 - * the other point - * @return the L-infinite distance - */ - public final double distanceLinf(Point3d p1) { - double tmp; - tmp = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y)); - - return Math.max(tmp, Math.abs(this.z - p1.z)); - } - - - /** - * Multiplies each of the x,y,z components of the Point4d parameter - * by 1/w and places the projected values into this point. - * - * @param p1 - * the source Point4d, which is not modified - */ - public final void project(Point4d p1) { - double oneOw; - - oneOw = 1 / p1.w; - x = p1.x * oneOw; - y = p1.y * oneOw; - z = p1.z * oneOw; - - } - - -} diff --git a/src/main/java/com/volmit/iris/util/math/Point3f.java b/src/main/java/com/volmit/iris/util/math/Point3f.java deleted file mode 100644 index 78ef274b5..000000000 --- a/src/main/java/com/volmit/iris/util/math/Point3f.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * A 3 element point that is represented by single precision floating point - * x,y,z coordinates. - */ -public class Point3f extends Tuple3f implements java.io.Serializable { - - - // Compatible with 1.1 - static final long serialVersionUID = -8689337816398030143L; - - /** - * Constructs and initializes a Point3f from the specified xyz coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - */ - public Point3f(float x, float y, float z) { - super(x, y, z); - } - - - /** - * Constructs and initializes a Point3f from the array of length 3. - * - * @param p - * the array of length 3 containing xyz in order - */ - public Point3f(float[] p) { - super(p); - } - - - /** - * Constructs and initializes a Point3f from the specified Point3f. - * - * @param p1 - * the Point3f containing the initialization x y z data - */ - public Point3f(Point3f p1) { - super(p1); - } - - - /** - * Constructs and initializes a Point3f from the specified Point3d. - * - * @param p1 - * the Point3d containing the initialization x y z data - */ - public Point3f(Point3d p1) { - super(p1); - } - - - /** - * Constructs and initializes a Point3f from the specified Tuple3f. - * - * @param t1 - * the Tuple3f containing the initialization x y z data - */ - public Point3f(Tuple3f t1) { - super(t1); - } - - - /** - * Constructs and initializes a Point3f from the specified Tuple3d. - * - * @param t1 - * the Tuple3d containing the initialization x y z data - */ - public Point3f(Tuple3d t1) { - super(t1); - } - - - /** - * Constructs and initializes a Point3f to (0,0,0). - */ - public Point3f() { - super(); - } - - - /** - * Computes the square of the distance between this point and - * point p1. - * - * @param p1 - * the other point - * @return the square of the distance - */ - public final float distanceSquared(Point3f p1) { - float dx, dy, dz; - - dx = this.x - p1.x; - dy = this.y - p1.y; - dz = this.z - p1.z; - return dx * dx + dy * dy + dz * dz; - } - - - /** - * Computes the distance between this point and point p1. - * - * @param p1 - * the other point - * @return the distance - */ - public final float distance(Point3f p1) { - float dx, dy, dz; - - dx = this.x - p1.x; - dy = this.y - p1.y; - dz = this.z - p1.z; - return (float) Math.sqrt(dx * dx + dy * dy + dz * dz); - } - - - /** - * Computes the L-1 (Manhattan) distance between this point and - * point p1. The L-1 distance is equal to: - * abs(x1-x2) + abs(y1-y2) + abs(z1-z2). - * - * @param p1 - * the other point - * @return the L-1 distance - */ - public final float distanceL1(Point3f p1) { - return (Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) + Math.abs(this.z - p1.z)); - } - - - /** - * Computes the L-infinite distance between this point and - * point p1. The L-infinite distance is equal to - * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. - * - * @param p1 - * the other point - * @return the L-infinite distance - */ - public final float distanceLinf(Point3f p1) { - float tmp; - tmp = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y)); - return (Math.max(tmp, Math.abs(this.z - p1.z))); - - } - - - /** - * Multiplies each of the x,y,z components of the Point4f parameter - * by 1/w and places the projected values into this point. - * - * @param p1 - * the source Point4f, which is not modified - */ - public final void project(Point4f p1) { - float oneOw; - - oneOw = 1 / p1.w; - x = p1.x * oneOw; - y = p1.y * oneOw; - z = p1.z * oneOw; - - } - - -} diff --git a/src/main/java/com/volmit/iris/util/math/Point4d.java b/src/main/java/com/volmit/iris/util/math/Point4d.java deleted file mode 100644 index 79ba4e246..000000000 --- a/src/main/java/com/volmit/iris/util/math/Point4d.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * A 4 element vector represented by double precision floating point - * x,y,z,w coordinates. - */ -public class Point4d extends Tuple4d implements java.io.Serializable { - - // Compatible with 1.1 - static final long serialVersionUID = 1733471895962736949L; - - - /** - * Constructs and initializes a Point4d from the specified xyzw coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - * @param w - * the w coordinate - */ - public Point4d(double x, double y, double z, double w) { - super(x, y, z, w); - } - - /** - * Constructs and initializes a Point4d from the coordinates contained - * in the array. - * - * @param p - * the array of length 4 containing xyzw in order - */ - public Point4d(double[] p) { - super(p); - } - - - /** - * Constructs and initializes a Point4d from the specified Point4d. - * - * @param p1 - * the Point4d containing the initialization x y z w data - */ - public Point4d(Point4d p1) { - super(p1); - } - - - /** - * Constructs and initializes a Point4d from the specified Point4f. - * - * @param p1 - * the Point4f containing the initialization x y z w data - */ - public Point4d(Point4f p1) { - super(p1); - } - - - /** - * Constructs and initializes a Point4d from the specified Tuple4f. - * - * @param t1 - * the Tuple4f containing the initialization x y z w data - */ - public Point4d(Tuple4f t1) { - super(t1); - } - - - /** - * Constructs and initializes a Point4d from the specified Tuple4d. - * - * @param t1 - * the Tuple4d containing the initialization x y z w data - */ - public Point4d(Tuple4d t1) { - super(t1); - } - - - /** - * Constructs and initializes a Point4d from the specified Tuple3d. - * The x,y,z components of this point are set to the corresponding - * components of tuple t1. The w component of this point - * is set to 1. - * - * @param t1 - * the tuple to be copied - * @since vecmath 1.2 - */ - public Point4d(Tuple3d t1) { - super(t1.x, t1.y, t1.z, 1.0); - } - - - /** - * Constructs and initializes a Point4d to (0,0,0,0). - */ - public Point4d() { - super(); - } - - - /** - * Sets the x,y,z components of this point to the corresponding - * components of tuple t1. The w component of this point - * is set to 1. - * - * @param t1 - * the tuple to be copied - * @since vecmath 1.2 - */ - public final void set(Tuple3d t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = 1.0; - } - - - /** - * Returns the square of the distance between this point and point p1. - * - * @param p1 - * the first point - * @return the square of distance between this point and point p1 - */ - public final double distanceSquared(Point4d p1) { - double dx, dy, dz, dw; - - dx = this.x - p1.x; - dy = this.y - p1.y; - dz = this.z - p1.z; - dw = this.w - p1.w; - return (dx * dx + dy * dy + dz * dz + dw * dw); - } - - - /** - * Returns the distance between this point and point p1. - * - * @param p1 - * the first point - * @return the distance between these this point and point p1. - */ - public final double distance(Point4d p1) { - double dx, dy, dz, dw; - - dx = this.x - p1.x; - dy = this.y - p1.y; - dz = this.z - p1.z; - dw = this.w - p1.w; - return Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw); - } - - - /** - * Computes the L-1 (Manhattan) distance between this point and - * point p1. The L-1 distance is equal to: - * abs(x1-x2) + abs(y1-y2) + abs(z1-z2) + abs(w1-w2). - * - * @param p1 - * the other point - * @return the L-1 distance - */ - public final double distanceL1(Point4d p1) { - return Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) + - Math.abs(this.z - p1.z) + Math.abs(this.w - p1.w); - } - - /** - * Computes the L-infinite distance between this point and - * point p1. The L-infinite distance is equal to - * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. - * - * @param p1 - * the other point - * @return the L-infinite distance - */ - public final double distanceLinf(Point4d p1) { - double t1, t2; - t1 = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y)); - t2 = Math.max(Math.abs(this.z - p1.z), Math.abs(this.w - p1.w)); - - return Math.max(t1, t2); - } - - /** - * Multiplies each of the x,y,z components of the Point4d parameter - * by 1/w, places the projected values into this point, and places - * a 1 as the w parameter of this point. - * - * @param p1 - * the source Point4d, which is not modified - */ - public final void project(Point4d p1) { - double oneOw; - - oneOw = 1 / p1.w; - x = p1.x * oneOw; - y = p1.y * oneOw; - z = p1.z * oneOw; - w = 1.0; - - } - - -} diff --git a/src/main/java/com/volmit/iris/util/math/Point4f.java b/src/main/java/com/volmit/iris/util/math/Point4f.java deleted file mode 100644 index ab4fc954f..000000000 --- a/src/main/java/com/volmit/iris/util/math/Point4f.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * A 4 element point represented by single precision floating point x,y,z,w - * coordinates. - */ -public class Point4f extends Tuple4f implements java.io.Serializable { - - - // Compatible with 1.1 - static final long serialVersionUID = 4643134103185764459L; - - /** - * Constructs and initializes a Point4f from the specified xyzw coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - * @param w - * the w coordinate - */ - public Point4f(float x, float y, float z, float w) { - super(x, y, z, w); - } - - - /** - * Constructs and initializes a Point4f from the array of length 4. - * - * @param p - * the array of length 4 containing xyzw in order - */ - public Point4f(float[] p) { - super(p); - } - - - /** - * Constructs and initializes a Point4f from the specified Point4f. - * - * @param p1 - * the Point4f containing the initialization x y z w data - */ - public Point4f(Point4f p1) { - super(p1); - } - - - /** - * Constructs and initializes a Point4f from the specified Point4d. - * - * @param p1 - * the Point4d containing the initialization x y z w data - */ - public Point4f(Point4d p1) { - super(p1); - } - - - /** - * Constructs and initializes a Point4f from the specified Tuple4f. - * - * @param t1 - * the Tuple4f containing the initialization x y z w data - */ - public Point4f(Tuple4f t1) { - super(t1); - } - - - /** - * Constructs and initializes a Point4f from the specified Tuple4d. - * - * @param t1 - * the Tuple4d containing the initialization x y z w data - */ - public Point4f(Tuple4d t1) { - super(t1); - } - - - /** - * Constructs and initializes a Point4f from the specified Tuple3f. - * The x,y,z components of this point are set to the corresponding - * components of tuple t1. The w component of this point - * is set to 1. - * - * @param t1 - * the tuple to be copied - * @since vecmath 1.2 - */ - public Point4f(Tuple3f t1) { - super(t1.x, t1.y, t1.z, 1.0f); - } - - - /** - * Constructs and initializes a Point4f to (0,0,0,0). - */ - public Point4f() { - super(); - } - - - /** - * Sets the x,y,z components of this point to the corresponding - * components of tuple t1. The w component of this point - * is set to 1. - * - * @param t1 - * the tuple to be copied - * @since vecmath 1.2 - */ - public final void set(Tuple3f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = 1.0f; - } - - - /** - * Computes the square of the distance between this point and point p1. - * - * @param p1 - * the other point - * @return the square of distance between these two points as a float - */ - public final float distanceSquared(Point4f p1) { - float dx, dy, dz, dw; - - dx = this.x - p1.x; - dy = this.y - p1.y; - dz = this.z - p1.z; - dw = this.w - p1.w; - return (dx * dx + dy * dy + dz * dz + dw * dw); - } - - - /** - * Computes the distance between this point and point p1. - * - * @param p1 - * the other point - * @return the distance between the two points - */ - public final float distance(Point4f p1) { - float dx, dy, dz, dw; - - dx = this.x - p1.x; - dy = this.y - p1.y; - dz = this.z - p1.z; - dw = this.w - p1.w; - return (float) Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw); - } - - - /** - * Computes the L-1 (Manhattan) distance between this point and - * point p1. The L-1 distance is equal to: - * abs(x1-x2) + abs(y1-y2) + abs(z1-z2) + abs(w1-w2). - * - * @param p1 - * the other point - * @return the L-1 distance - */ - public final float distanceL1(Point4f p1) { - return (Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) + Math.abs(this.z - p1.z) + Math.abs(this.w - p1.w)); - } - - - /** - * Computes the L-infinite distance between this point and - * point p1. The L-infinite distance is equal to - * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. - * - * @param p1 - * the other point - * @return the L-infinite distance - */ - public final float distanceLinf(Point4f p1) { - float t1, t2; - t1 = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y)); - t2 = Math.max(Math.abs(this.z - p1.z), Math.abs(this.w - p1.w)); - - return (Math.max(t1, t2)); - - } - - /** - * Multiplies each of the x,y,z components of the Point4f parameter - * by 1/w, places the projected values into this point, and places - * a 1 as the w parameter of this point. - * - * @param p1 - * the source Point4f, which is not modified - */ - public final void project(Point4f p1) { - float oneOw; - - oneOw = 1 / p1.w; - x = p1.x * oneOw; - y = p1.y * oneOw; - z = p1.z * oneOw; - w = 1.0f; - - } - -} diff --git a/src/main/java/com/volmit/iris/util/math/Position2.java b/src/main/java/com/volmit/iris/util/math/Position2.java deleted file mode 100644 index d30e4e8b5..000000000 --- a/src/main/java/com/volmit/iris/util/math/Position2.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.engine.object.IrisPosition; -import org.bukkit.util.Vector; - -public class Position2 { - private int x; - private int z; - - public Position2(int x, int z) { - this.x = x; - this.z = z; - } - - public Position2(Vector center) { - this.x = center.getBlockX(); - this.z = center.getBlockZ(); - } - - public int getX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getZ() { - return z; - } - - public void setZ(int z) { - this.z = z; - } - - public String toString() { - return "[" + x + "," + z + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + x; - result = prime * result + z; - return result; - } - - public Position2 regionToChunk() { - return new Position2(x << 5, z << 5); - } - - @Override - public boolean equals(Object obj) { - if(this == obj) { - return true; - } - if(!(obj instanceof Position2 other)) { - return false; - } - return x == other.x && z == other.z; - } - - public double distance(Position2 center) { - return Math.pow(center.getX() - x, 2) + Math.pow(center.getZ() - z, 2); - } - - public Position2 add(int x, int z) { - return new Position2(this.x + x, this.z + z); - } - - public Position2 blockToChunk() { - return new Position2(x >> 4, z >> 4); - } - - public IrisPosition toIris() { - return new IrisPosition(x, 23, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/math/RNG.java b/src/main/java/com/volmit/iris/util/math/RNG.java deleted file mode 100644 index 02fb804ab..000000000 --- a/src/main/java/com/volmit/iris/util/math/RNG.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Random; -import java.util.UUID; - -public class RNG extends Random { - public static final RNG r = new RNG(); - private static final char[] CHARGEN = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-=!@#$%^&*()_+`~[];',./<>?:\\\"{}|\\\\".toCharArray(); - private static final long serialVersionUID = 5222938581174415179L; - private final long sx; - - public RNG() { - super(); - sx = 0; - } - - public RNG(long seed) { - super(seed); - this.sx = seed; - } - - /** - * Creates a seed (long) from the hash of the seed string - * - * @param seed - * the seed (string) - */ - public RNG(String seed) { - this(UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).getLeastSignificantBits() + UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).getMostSignificantBits() + (seed.length() * 32564L)); - } - - public RNG nextParallelRNG(int signature) { - return new RNG(sx + signature); - } - - public RNG nextParallelRNG(long signature) { - return new RNG(sx + signature); - } - - public String s(int length) { - StringBuilder sb = new StringBuilder(); - - for(int i = 0; i < length; i++) { - sb.append(c()); - } - - return sb.toString(); - } - - public char c() { - return CHARGEN[i(CHARGEN.length - 1)]; - } - - /** - * Pick a random enum - * - * @param t - * the enum class - * @return the enum - */ - public T e(Class t) { - T[] c = t.getEnumConstants(); - return c[i(c.length)]; - } - - public boolean b() { - return nextBoolean(); - } - - public boolean b(double percent) { - return d() > percent; - } - - public short si(int lowerBound, int upperBound) { - return (short) (lowerBound + (nextFloat() * ((upperBound - lowerBound) + 1))); - } - - public short si(int upperBound) { - return si(0, upperBound); - } - - public short si() { - return si(1); - } - - public float f(float lowerBound, float upperBound) { - return lowerBound + (nextFloat() * ((upperBound - lowerBound))); - } - - public float f(float upperBound) { - return f(0, upperBound); - } - - public float f() { - return f(1); - } - - public double d(double lowerBound, double upperBound) { - if(lowerBound > upperBound) { - return M.lerp(upperBound, lowerBound, nextDouble()); - } - - return M.lerp(lowerBound, upperBound, nextDouble()); - } - - public double d(double upperBound) { - return d(0, upperBound); - } - - public double d() { - return d(1); - } - - public int i(int lowerBound, int upperBound) { - return (int) Math.floor(d(lowerBound, upperBound)); - } - - public int i(int upperBound) { - return i(Math.min(upperBound, 0), Math.max(0, upperBound)); - } - - public long l(long lowerBound, long upperBound) { - return Math.round(d(lowerBound, upperBound)); - } - - public long l(long upperBound) { - return l(0, upperBound); - } - - public int imax() { - return i(Integer.MIN_VALUE, Integer.MAX_VALUE); - } - - public long lmax() { - return l(Long.MIN_VALUE, Long.MAX_VALUE); - } - - public float fmax() { - return f(Float.MIN_VALUE, Float.MAX_VALUE); - } - - public double dmax() { - return d(Double.MIN_VALUE, Double.MAX_VALUE); - } - - public short simax() { - return si(Short.MIN_VALUE, Short.MAX_VALUE); - } - - public boolean chance(double chance) { - return chance >= nextDouble(); - } - - public T pick(List pieces) { - if(pieces.isEmpty()) { - return null; - } - - if(pieces.size() == 1) { - return pieces.get(0); - } - - return pieces.get(nextInt(pieces.size())); - } - - public long getSeed() { - return sx; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/RollingSequence.java b/src/main/java/com/volmit/iris/util/math/RollingSequence.java deleted file mode 100644 index 116bbe6af..000000000 --- a/src/main/java/com/volmit/iris/util/math/RollingSequence.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.util.collection.KList; - -public class RollingSequence extends Average { - private double median; - private double max; - private double min; - private boolean dirtyMedian; - private int dirtyExtremes; - private boolean precision; - - public RollingSequence(int size) { - super(size); - median = 0; - min = 0; - max = 0; - setPrecision(false); - } - - public double addLast(int amt) { - double f = 0; - - for(int i = 0; i < Math.min(values.length, amt); i++) { - f += values[i]; - } - - return f; - } - - public boolean isPrecision() { - return precision; - } - - public void setPrecision(boolean p) { - this.precision = p; - } - - public double getMin() { - if(dirtyExtremes > (isPrecision() ? 0 : values.length)) { - resetExtremes(); - } - - return min; - } - - public double getMax() { - if(dirtyExtremes > (isPrecision() ? 0 : values.length)) { - resetExtremes(); - } - - return max; - } - - public double getMedian() { - if(dirtyMedian) { - recalculateMedian(); - } - - return median; - } - - private void recalculateMedian() { - median = new KList().forceAdd(values).sort().middleValue(); - dirtyMedian = false; - } - - public void resetExtremes() { - max = Integer.MIN_VALUE; - min = Integer.MAX_VALUE; - - for(double i : values) { - max = M.max(max, i); - min = M.min(min, i); - } - - dirtyExtremes = 0; - } - - public void put(double i) { - super.put(i); - dirtyMedian = true; - dirtyExtremes++; - max = M.max(max, i); - min = M.min(min, i); - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Spiral.java b/src/main/java/com/volmit/iris/util/math/Spiral.java deleted file mode 100644 index c3aed05d1..000000000 --- a/src/main/java/com/volmit/iris/util/math/Spiral.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import org.jetbrains.annotations.NotNull; - -import java.util.Iterator; - -/** - * Represents a spiraler which can start from any point within Long.MAX_VALUE by Long.MAX_VALUE and iterate anywhere. - */ -@Data -@RequiredArgsConstructor -public class Spiral implements Iterable { - private final Position2 start; - private final long max; - - @SuppressWarnings("ConstantConditions") - public static Position2 next(Position2 p) { - int x = p.getX(); - int z = p.getZ(); - int ax = Math.abs(x); - int az = Math.abs(z); - - if(x == 0 && z == 0) { - return p.add(1, 0); - } - - if(ax == az) { - if(x > 0 && z > 0) return left(p); - else if(x < 0 && z > 0) return down(p); - else if(x < 0 && z < 0) return right(p); - else if(x > 0 && z < 0) return up(p); - } else { - if(x > z && ax > az) return up(p); - else if(x < z && ax < az) return left(p); - else if(x < z && ax > az) return down(p); - else if(x > z && ax < az) return right(p); - } - - return p; - } - - public static Spiral from(Position2 p, long iterations) { - return new Spiral(p, iterations); - } - - private static Position2 down(Position2 p) { - return p.add(0, -1); - } - - private static Position2 up(Position2 p) { - return p.add(0, 1); - } - - private static Position2 left(Position2 p) { - return p.add(-1, 0); - } - - private static Position2 right(Position2 p) { - return p.add(1, 0); - } - - @NotNull - @Override - public Iterator iterator() { - return new SpiralIterator(0, this, start); - } - - @AllArgsConstructor - static class SpiralIterator implements Iterator { - private long itr = 0; - private final Spiral s; - private Position2 cursor; - - @Override - public boolean hasNext() { - return itr < s.getMax(); - } - - @Override - public Position2 next() { - Position2 m = cursor; - cursor = Spiral.next(cursor); - itr++; - return m; - } - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Spiraled.java b/src/main/java/com/volmit/iris/util/math/Spiraled.java deleted file mode 100644 index b9b6e8cff..000000000 --- a/src/main/java/com/volmit/iris/util/math/Spiraled.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -@FunctionalInterface -public interface Spiraled { - void on(int x, int z); -} diff --git a/src/main/java/com/volmit/iris/util/math/Spiraler.java b/src/main/java/com/volmit/iris/util/math/Spiraler.java deleted file mode 100644 index 6cd30c823..000000000 --- a/src/main/java/com/volmit/iris/util/math/Spiraler.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -@SuppressWarnings("EmptyMethod") -public class Spiraler { - private final Spiraled spiraled; - int x, z, dx, dz, sizeX, sizeZ, t, maxI, i; - int ox, oz; - - public Spiraler(int sizeX, int sizeZ, Spiraled spiraled) { - ox = 0; - oz = 0; - this.spiraled = spiraled; - retarget(sizeX, sizeZ); - } - - static void Spiral(int X, int Y) { - - } - - public void drain() { - while(hasNext()) { - next(); - } - } - - public Spiraler setOffset(int ox, int oz) { - this.ox = ox; - this.oz = oz; - return this; - } - - public void retarget(int sizeX, int sizeZ) { - this.sizeX = sizeX; - this.sizeZ = sizeZ; - x = z = dx = 0; - dz = -1; - i = 0; - t = Math.max(sizeX, sizeZ); - maxI = t * t; - } - - public boolean hasNext() { - return i < maxI; - } - - public void next() { - if((-sizeX / 2 <= x) && (x <= sizeX / 2) && (-sizeZ / 2 <= z) && (z <= sizeZ / 2)) { - spiraled.on(x + ox, z + ox); - } - - if((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z))) { - t = dx; - dx = -dz; - dz = t; - } - x += dx; - z += dz; - i++; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Tuple2d.java b/src/main/java/com/volmit/iris/util/math/Tuple2d.java deleted file mode 100644 index 937298d01..000000000 --- a/src/main/java/com/volmit/iris/util/math/Tuple2d.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.Iris; - -/** - * A generic 2-element tuple that is represented by double-precision - * floating point x,y coordinates. - */ -public abstract class Tuple2d implements java.io.Serializable, Cloneable { - - static final long serialVersionUID = 6205762482756093838L; - - /** - * The x coordinate. - */ - public double x; - - /** - * The y coordinate. - */ - public double y; - - - /** - * Constructs and initializes a Tuple2d from the specified xy coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - */ - public Tuple2d(double x, double y) { - this.x = x; - this.y = y; - } - - - /** - * Constructs and initializes a Tuple2d from the specified array. - * - * @param t - * the array of length 2 containing xy in order - */ - public Tuple2d(double[] t) { - this.x = t[0]; - this.y = t[1]; - } - - - /** - * Constructs and initializes a Tuple2d from the specified Tuple2d. - * - * @param t1 - * the Tuple2d containing the initialization x y data - */ - public Tuple2d(Tuple2d t1) { - this.x = t1.x; - this.y = t1.y; - } - - - /** - * Constructs and initializes a Tuple2d from the specified Tuple2f. - * - * @param t1 - * the Tuple2f containing the initialization x y data - */ - public Tuple2d(Tuple2f t1) { - this.x = t1.x; - this.y = t1.y; - } - - /** - * Constructs and initializes a Tuple2d to (0,0). - */ - public Tuple2d() { - this.x = 0.0; - this.y = 0.0; - } - - - /** - * Sets the value of this tuple to the specified xy coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - */ - public final void set(double x, double y) { - this.x = x; - this.y = y; - } - - - /** - * Sets the value of this tuple from the 2 values specified in - * the array. - * - * @param t - * the array of length 2 containing xy in order - */ - public final void set(double[] t) { - this.x = t[0]; - this.y = t[1]; - } - - - /** - * Sets the value of this tuple to the value of the Tuple2d argument. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple2d t1) { - this.x = t1.x; - this.y = t1.y; - } - - - /** - * Sets the value of this tuple to the value of Tuple2f t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple2f t1) { - this.x = t1.x; - this.y = t1.y; - } - - /** - * Copies the value of the elements of this tuple into the array t. - * - * @param t - * the array that will contain the values of the vector - */ - public final void get(double[] t) { - t[0] = this.x; - t[1] = this.y; - } - - - /** - * Sets the value of this tuple to the vector sum of tuples t1 and t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void add(Tuple2d t1, Tuple2d t2) { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - } - - - /** - * Sets the value of this tuple to the vector sum of itself and tuple t1. - * - * @param t1 - * the other tuple - */ - public final void add(Tuple2d t1) { - this.x += t1.x; - this.y += t1.y; - } - - - /** - * Sets the value of this tuple to the vector difference of - * tuple t1 and t2 (this = t1 - t2). - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void sub(Tuple2d t1, Tuple2d t2) { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - } - - - /** - * Sets the value of this tuple to the vector difference of - * itself and tuple t1 (this = this - t1). - * - * @param t1 - * the other vector - */ - public final void sub(Tuple2d t1) { - this.x -= t1.x; - this.y -= t1.y; - } - - - /** - * Sets the value of this tuple to the negation of tuple t1. - * - * @param t1 - * the source vector - */ - public final void negate(Tuple2d t1) { - this.x = -t1.x; - this.y = -t1.y; - } - - - /** - * Negates the value of this vector in place. - */ - public final void negate() { - this.x = -this.x; - this.y = -this.y; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1. - * - * @param s - * the scalar value - * @param t1 - * the source tuple - */ - public final void scale(double s, Tuple2d t1) { - this.x = s * t1.x; - this.y = s * t1.y; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself. - * - * @param s - * the scalar value - */ - public final void scale(double s) { - this.x *= s; - this.y *= s; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1 and then adds tuple t2 (this = s*t1 + t2). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be multipled - * @param t2 - * the tuple to be added - */ - public final void scaleAdd(double s, Tuple2d t1, Tuple2d t2) { - this.x = s * t1.x + t2.x; - this.y = s * t1.y + t2.y; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself and then adds tuple t1 (this = s*this + t1). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be added - */ - public final void scaleAdd(double s, Tuple2d t1) { - this.x = s * this.x + t1.x; - this.y = s * this.y + t1.y; - } - - - /** - * Returns a hash code value based on the data values in this - * object. Two different Tuple2d objects with identical data values - * (i.e., Tuple2d.equals returns true) will return the same hash - * code value. Two objects with different data members may return the - * same hash value, although this is not likely. - * - * @return the integer hash code value - */ - public int hashCode() { - long bits = 1L; - bits = 31L * bits + VecMathUtil.doubleToLongBits(x); - bits = 31L * bits + VecMathUtil.doubleToLongBits(y); - return (int) (bits ^ (bits >> 32)); - } - - - /** - * Returns true if all of the data members of Tuple2d t1 are - * equal to the corresponding data members in this Tuple2d. - * - * @param t1 - * the vector with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple2d t1) { - try { - return (this.x == t1.x && this.y == t1.y); - } catch(NullPointerException e2) { - Iris.reportError(e2); - return false; - } - - } - - /** - * Returns true if the Object t1 is of type Tuple2d and all of the - * data members of t1 are equal to the corresponding data members in - * this Tuple2d. - * - * @param t1 - * the object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) { - try { - Tuple2d t2 = (Tuple2d) t1; - return (this.x == t2.x && this.y == t2.y); - } catch(NullPointerException | ClassCastException e2) { - Iris.reportError(e2); - return false; - } - - } - - /** - * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, - * otherwise returns false. The L-infinite - * distance is equal to MAX[abs(x1-x2), abs(y1-y2)]. - * - * @param t1 - * the tuple to be compared to this tuple - * @param epsilon - * the threshold value - * @return true or false - */ - public boolean epsilonEquals(Tuple2d t1, double epsilon) { - double diff; - - diff = x - t1.x; - if(Double.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = y - t1.y; - if(Double.isNaN(diff)) return false; - return !((diff < 0 ? -diff : diff) > epsilon); - } - - /** - * Returns a string that contains the values of this Tuple2d. - * The form is (x,y). - * - * @return the String representation - */ - public String toString() { - return ("(" + this.x + ", " + this.y + ")"); - } - - - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clamp(double min, double max, Tuple2d t) { - if(t.x > max) { - x = max; - } else x = Math.max(t.x, min); - - if(t.y > max) { - y = max; - } else y = Math.max(t.y, min); - - } - - - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMin(double min, Tuple2d t) { - x = Math.max(t.x, min); - - y = Math.max(t.y, min); - - } - - - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMax(double max, Tuple2d t) { - x = Math.min(t.x, max); - - y = Math.min(t.y, max); - - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * - * @param t - * the source tuple, which will not be modified - */ - public final void absolute(Tuple2d t) { - x = Math.abs(t.x); - y = Math.abs(t.y); - } - - - /** - * Clamps this tuple to the range [low, high]. - * - * @param min - * the lowest value in this tuple after clamping - * @param max - * the highest value in this tuple after clamping - */ - public final void clamp(double min, double max) { - if(x > max) { - x = max; - } else if(x < min) { - x = min; - } - - if(y > max) { - y = max; - } else if(y < min) { - y = min; - } - - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * - * @param min - * the lowest value in this tuple after clamping - */ - public final void clampMin(double min) { - if(x < min) x = min; - if(y < min) y = min; - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * - * @param max - * the highest value in the tuple after clamping - */ - public final void clampMax(double max) { - if(x > max) x = max; - if(y > max) y = max; - } - - - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() { - x = Math.abs(x); - y = Math.abs(y); - } - - - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - * @param alpha - * the alpha interpolation parameter - */ - public final void interpolate(Tuple2d t1, Tuple2d t2, double alpha) { - this.x = (1 - alpha) * t1.x + alpha * t2.x; - this.y = (1 - alpha) * t1.y + alpha * t2.y; - } - - - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * - * @param t1 - * the first tuple - * @param alpha - * the alpha interpolation parameter - */ - public final void interpolate(Tuple2d t1, double alpha) { - this.x = (1 - alpha) * this.x + alpha * t1.x; - this.y = (1 - alpha) * this.y + alpha * t1.y; - - } - - /** - * Creates a new object of the same class as this object. - * - * @return a clone of this instance. - * @throws OutOfMemoryError - * if there is not enough memory. - * @see java.lang.Cloneable - * @since vecmath 1.3 - */ - public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch(CloneNotSupportedException e) { - Iris.reportError(e); - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } - } - - - /** - * Get the x coordinate. - * - * @return the x coordinate. - * @since vecmath 1.5 - */ - public final double getX() { - return x; - } - - - /** - * Set the x coordinate. - * - * @param x - * value to x coordinate. - * @since vecmath 1.5 - */ - public final void setX(double x) { - this.x = x; - } - - - /** - * Get the y coordinate. - * - * @return the y coordinate. - * @since vecmath 1.5 - */ - public final double getY() { - return y; - } - - - /** - * Set the y coordinate. - * - * @param y - * value to y coordinate. - * @since vecmath 1.5 - */ - public final void setY(double y) { - this.y = y; - } - -} diff --git a/src/main/java/com/volmit/iris/util/math/Tuple2f.java b/src/main/java/com/volmit/iris/util/math/Tuple2f.java deleted file mode 100644 index a96f65c81..000000000 --- a/src/main/java/com/volmit/iris/util/math/Tuple2f.java +++ /dev/null @@ -1,615 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.Iris; - -/** - * A generic 2-element tuple that is represented by single-precision - * floating point x,y coordinates. - */ -public abstract class Tuple2f implements java.io.Serializable, Cloneable { - - static final long serialVersionUID = 9011180388985266884L; - - /** - * The x coordinate. - */ - public float x; - - /** - * The y coordinate. - */ - public float y; - - - /** - * Constructs and initializes a Tuple2f from the specified xy coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - */ - public Tuple2f(float x, float y) { - this.x = x; - this.y = y; - } - - - /** - * Constructs and initializes a Tuple2f from the specified array. - * - * @param t - * the array of length 2 containing xy in order - */ - public Tuple2f(float[] t) { - this.x = t[0]; - this.y = t[1]; - } - - - /** - * Constructs and initializes a Tuple2f from the specified Tuple2f. - * - * @param t1 - * the Tuple2f containing the initialization x y data - */ - public Tuple2f(Tuple2f t1) { - this.x = t1.x; - this.y = t1.y; - } - - - /** - * Constructs and initializes a Tuple2f from the specified Tuple2d. - * - * @param t1 - * the Tuple2d containing the initialization x y data - */ - public Tuple2f(Tuple2d t1) { - this.x = (float) t1.x; - this.y = (float) t1.y; - } - - - /** - * Constructs and initializes a Tuple2f to (0,0). - */ - public Tuple2f() { - this.x = (float) 0.0; - this.y = (float) 0.0; - } - - - /** - * Sets the value of this tuple to the specified xy coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - */ - public final void set(float x, float y) { - this.x = x; - this.y = y; - } - - - /** - * Sets the value of this tuple from the 2 values specified in - * the array. - * - * @param t - * the array of length 2 containing xy in order - */ - public final void set(float[] t) { - this.x = t[0]; - this.y = t[1]; - } - - - /** - * Sets the value of this tuple to the value of the Tuple2f argument. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple2f t1) { - this.x = t1.x; - this.y = t1.y; - } - - - /** - * Sets the value of this tuple to the value of the Tuple2d argument. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple2d t1) { - this.x = (float) t1.x; - this.y = (float) t1.y; - } - - - /** - * Copies the value of the elements of this tuple into the array t. - * - * @param t - * the array that will contain the values of the vector - */ - public final void get(float[] t) { - t[0] = this.x; - t[1] = this.y; - } - - - /** - * Sets the value of this tuple to the vector sum of tuples t1 and t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void add(Tuple2f t1, Tuple2f t2) { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - } - - - /** - * Sets the value of this tuple to the vector sum of itself and tuple t1. - * - * @param t1 - * the other tuple - */ - public final void add(Tuple2f t1) { - this.x += t1.x; - this.y += t1.y; - } - - - /** - * Sets the value of this tuple to the vector difference of - * tuple t1 and t2 (this = t1 - t2). - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void sub(Tuple2f t1, Tuple2f t2) { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - } - - - /** - * Sets the value of this tuple to the vector difference of - * itself and tuple t1 (this = this - t1). - * - * @param t1 - * the other tuple - */ - public final void sub(Tuple2f t1) { - this.x -= t1.x; - this.y -= t1.y; - } - - - /** - * Sets the value of this tuple to the negation of tuple t1. - * - * @param t1 - * the source tuple - */ - public final void negate(Tuple2f t1) { - this.x = -t1.x; - this.y = -t1.y; - } - - - /** - * Negates the value of this vector in place. - */ - public final void negate() { - this.x = -this.x; - this.y = -this.y; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1. - * - * @param s - * the scalar value - * @param t1 - * the source tuple - */ - public final void scale(float s, Tuple2f t1) { - this.x = s * t1.x; - this.y = s * t1.y; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself. - * - * @param s - * the scalar value - */ - public final void scale(float s) { - this.x *= s; - this.y *= s; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1 and then adds tuple t2 (this = s*t1 + t2). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be multipled - * @param t2 - * the tuple to be added - */ - public final void scaleAdd(float s, Tuple2f t1, Tuple2f t2) { - this.x = s * t1.x + t2.x; - this.y = s * t1.y + t2.y; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself and then adds tuple t1 (this = s*this + t1). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be added - */ - public final void scaleAdd(float s, Tuple2f t1) { - this.x = s * this.x + t1.x; - this.y = s * this.y + t1.y; - } - - - /** - * Returns a hash code value based on the data values in this - * object. Two different Tuple2f objects with identical data values - * (i.e., Tuple2f.equals returns true) will return the same hash - * code value. Two objects with different data members may return the - * same hash value, although this is not likely. - * - * @return the integer hash code value - */ - public int hashCode() { - long bits = 1L; - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(x); - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(y); - return (int) (bits ^ (bits >> 32)); - } - - - /** - * Returns true if all of the data members of Tuple2f t1 are - * equal to the corresponding data members in this Tuple2f. - * - * @param t1 - * the vector with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple2f t1) { - try { - return (this.x == t1.x && this.y == t1.y); - } catch(NullPointerException e2) { - Iris.reportError(e2); - return false; - } - - } - - /** - * Returns true if the Object t1 is of type Tuple2f and all of the - * data members of t1 are equal to the corresponding data members in - * this Tuple2f. - * - * @param t1 - * the object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) { - try { - Tuple2f t2 = (Tuple2f) t1; - return (this.x == t2.x && this.y == t2.y); - } catch(NullPointerException | ClassCastException e2) { - Iris.reportError(e2); - return false; - } - - } - - /** - * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, - * otherwise returns false. The L-infinite - * distance is equal to MAX[abs(x1-x2), abs(y1-y2)]. - * - * @param t1 - * the tuple to be compared to this tuple - * @param epsilon - * the threshold value - * @return true or false - */ - public boolean epsilonEquals(Tuple2f t1, float epsilon) { - float diff; - - diff = x - t1.x; - if(Float.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = y - t1.y; - if(Float.isNaN(diff)) return false; - return !((diff < 0 ? -diff : diff) > epsilon); - } - - /** - * Returns a string that contains the values of this Tuple2f. - * The form is (x,y). - * - * @return the String representation - */ - public String toString() { - return ("(" + this.x + ", " + this.y + ")"); - } - - - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clamp(float min, float max, Tuple2f t) { - if(t.x > max) { - x = max; - } else x = Math.max(t.x, min); - - if(t.y > max) { - y = max; - } else y = Math.max(t.y, min); - - } - - - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMin(float min, Tuple2f t) { - x = Math.max(t.x, min); - - y = Math.max(t.y, min); - - } - - - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMax(float max, Tuple2f t) { - x = Math.min(t.x, max); - - y = Math.min(t.y, max); - - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * - * @param t - * the source tuple, which will not be modified - */ - public final void absolute(Tuple2f t) { - x = Math.abs(t.x); - y = Math.abs(t.y); - } - - - /** - * Clamps this tuple to the range [low, high]. - * - * @param min - * the lowest value in this tuple after clamping - * @param max - * the highest value in this tuple after clamping - */ - public final void clamp(float min, float max) { - if(x > max) { - x = max; - } else if(x < min) { - x = min; - } - - if(y > max) { - y = max; - } else if(y < min) { - y = min; - } - - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * - * @param min - * the lowest value in this tuple after clamping - */ - public final void clampMin(float min) { - if(x < min) x = min; - if(y < min) y = min; - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * - * @param max - * the highest value in the tuple after clamping - */ - public final void clampMax(float max) { - if(x > max) x = max; - if(y > max) y = max; - } - - - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() { - x = Math.abs(x); - y = Math.abs(y); - } - - - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - * @param alpha - * the alpha interpolation parameter - */ - public final void interpolate(Tuple2f t1, Tuple2f t2, float alpha) { - this.x = (1 - alpha) * t1.x + alpha * t2.x; - this.y = (1 - alpha) * t1.y + alpha * t2.y; - - } - - - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * - * @param t1 - * the first tuple - * @param alpha - * the alpha interpolation parameter - */ - public final void interpolate(Tuple2f t1, float alpha) { - - this.x = (1 - alpha) * this.x + alpha * t1.x; - this.y = (1 - alpha) * this.y + alpha * t1.y; - - } - - /** - * Creates a new object of the same class as this object. - * - * @return a clone of this instance. - * @throws OutOfMemoryError - * if there is not enough memory. - * @see java.lang.Cloneable - * @since vecmath 1.3 - */ - public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch(CloneNotSupportedException e) { - Iris.reportError(e); - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } - } - - - /** - * Get the x coordinate. - * - * @return the x coordinate. - * @since vecmath 1.5 - */ - public final float getX() { - return x; - } - - - /** - * Set the x coordinate. - * - * @param x - * value to x coordinate. - * @since vecmath 1.5 - */ - public final void setX(float x) { - this.x = x; - } - - - /** - * Get the y coordinate. - * - * @return the y coordinate. - * @since vecmath 1.5 - */ - public final float getY() { - return y; - } - - - /** - * Set the y coordinate. - * - * @param y - * value to y coordinate. - * @since vecmath 1.5 - */ - public final void setY(float y) { - this.y = y; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Tuple3d.java b/src/main/java/com/volmit/iris/util/math/Tuple3d.java deleted file mode 100644 index e033e7382..000000000 --- a/src/main/java/com/volmit/iris/util/math/Tuple3d.java +++ /dev/null @@ -1,773 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.Iris; - -/** - * A generic 3-element tuple that is represented by double-precision - * floating point x,y,z coordinates. - */ -public abstract class Tuple3d implements java.io.Serializable, Cloneable { - - static final long serialVersionUID = 5542096614926168415L; - - /** - * The x coordinate. - */ - public double x; - - /** - * The y coordinate. - */ - public double y; - - /** - * The z coordinate. - */ - public double z; - - - /** - * Constructs and initializes a Tuple3d from the specified xyz coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - */ - public Tuple3d(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - /** - * Constructs and initializes a Tuple3d from the array of length 3. - * - * @param t - * the array of length 3 containing xyz in order - */ - public Tuple3d(double[] t) { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - } - - /** - * Constructs and initializes a Tuple3d from the specified Tuple3d. - * - * @param t1 - * the Tuple3d containing the initialization x y z data - */ - public Tuple3d(Tuple3d t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - } - - /** - * Constructs and initializes a Tuple3d from the specified Tuple3f. - * - * @param t1 - * the Tuple3f containing the initialization x y z data - */ - public Tuple3d(Tuple3f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - } - - /** - * Constructs and initializes a Tuple3d to (0,0,0). - */ - public Tuple3d() { - this.x = 0.0; - this.y = 0.0; - this.z = 0.0; - } - - /** - * Sets the value of this tuple to the specified xyz coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - */ - public final void set(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - /** - * Sets the value of this tuple to the value of the xyz coordinates - * located in the array of length 3. - * - * @param t - * the array of length 3 containing xyz in order - */ - public final void set(double[] t) { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - } - - /** - * Sets the value of this tuple to the value of tuple t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple3d t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - } - - /** - * Sets the value of this tuple to the value of tuple t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple3f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - } - - /** - * Copies the x,y,z coordinates of this tuple into the array t - * of length 3. - * - * @param t - * the target array - */ - public final void get(double[] t) { - t[0] = this.x; - t[1] = this.y; - t[2] = this.z; - } - - - /** - * Copies the x,y,z coordinates of this tuple into the tuple t. - * - * @param t - * the Tuple3d object into which the values of this object are copied - */ - public final void get(Tuple3d t) { - t.x = this.x; - t.y = this.y; - t.z = this.z; - } - - - /** - * Sets the value of this tuple to the sum of tuples t1 and t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void add(Tuple3d t1, Tuple3d t2) { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - this.z = t1.z + t2.z; - } - - - /** - * Sets the value of this tuple to the sum of itself and t1. - * - * @param t1 - * the other tuple - */ - public final void add(Tuple3d t1) { - this.x += t1.x; - this.y += t1.y; - this.z += t1.z; - } - - /** - * Sets the value of this tuple to the difference of tuples - * t1 and t2 (this = t1 - t2). - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void sub(Tuple3d t1, Tuple3d t2) { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - this.z = t1.z - t2.z; - } - - /** - * Sets the value of this tuple to the difference - * of itself and t1 (this = this - t1). - * - * @param t1 - * the other tuple - */ - public final void sub(Tuple3d t1) { - this.x -= t1.x; - this.y -= t1.y; - this.z -= t1.z; - } - - - /** - * Sets the value of this tuple to the negation of tuple t1. - * - * @param t1 - * the source tuple - */ - public final void negate(Tuple3d t1) { - this.x = -t1.x; - this.y = -t1.y; - this.z = -t1.z; - } - - - /** - * Negates the value of this tuple in place. - */ - public final void negate() { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1. - * - * @param s - * the scalar value - * @param t1 - * the source tuple - */ - public final void scale(double s, Tuple3d t1) { - this.x = s * t1.x; - this.y = s * t1.y; - this.z = s * t1.z; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself. - * - * @param s - * the scalar value - */ - public final void scale(double s) { - this.x *= s; - this.y *= s; - this.z *= s; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1 and then adds tuple t2 (this = s*t1 + t2). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be multipled - * @param t2 - * the tuple to be added - */ - public final void scaleAdd(double s, Tuple3d t1, Tuple3d t2) { - this.x = s * t1.x + t2.x; - this.y = s * t1.y + t2.y; - this.z = s * t1.z + t2.z; - } - - - /** - * @deprecated Use scaleAdd(double,Tuple3d) instead - */ - @Deprecated - public final void scaleAdd(double s, Tuple3f t1) { - scaleAdd(s, new Point3d(t1)); - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself and then adds tuple t1 (this = s*this + t1). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be added - */ - public final void scaleAdd(double s, Tuple3d t1) { - this.x = s * this.x + t1.x; - this.y = s * this.y + t1.y; - this.z = s * this.z + t1.z; - } - - - /** - * Returns a string that contains the values of this Tuple3d. - * The form is (x,y,z). - * - * @return the String representation - */ - public String toString() { - return "(" + this.x + ", " + this.y + ", " + this.z + ")"; - } - - - /** - * Returns a hash code value based on the data values in this - * object. Two different Tuple3d objects with identical data values - * (i.e., Tuple3d.equals returns true) will return the same hash - * code value. Two objects with different data members may return the - * same hash value, although this is not likely. - * - * @return the integer hash code value - */ - public int hashCode() { - long bits = 1L; - bits = 31L * bits + VecMathUtil.doubleToLongBits(x); - bits = 31L * bits + VecMathUtil.doubleToLongBits(y); - bits = 31L * bits + VecMathUtil.doubleToLongBits(z); - return (int) (bits ^ (bits >> 32)); - } - - - /** - * Returns true if all of the data members of Tuple3d t1 are - * equal to the corresponding data members in this Tuple3d. - * - * @param t1 - * the tuple with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple3d t1) { - try { - return (this.x == t1.x && this.y == t1.y && this.z == t1.z); - } catch(NullPointerException e2) { - Iris.reportError(e2); - return false; - } - } - - /** - * Returns true if the Object t1 is of type Tuple3d and all of the - * data members of t1 are equal to the corresponding data members in - * this Tuple3d. - * - * @param t1 - * the Object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) { - try { - Tuple3d t2 = (Tuple3d) t1; - return (this.x == t2.x && this.y == t2.y && this.z == t2.z); - } catch(ClassCastException | NullPointerException e1) { - Iris.reportError(e1); - return false; - } - - } - - /** - * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, - * otherwise returns false. The L-infinite - * distance is equal to MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. - * - * @param t1 - * the tuple to be compared to this tuple - * @param epsilon - * the threshold value - * @return true or false - */ - public boolean epsilonEquals(Tuple3d t1, double epsilon) { - double diff; - - diff = x - t1.x; - if(Double.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = y - t1.y; - if(Double.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = z - t1.z; - if(Double.isNaN(diff)) return false; - return !((diff < 0 ? -diff : diff) > epsilon); - - } - - - /** - * @deprecated Use clamp(double,double,Tuple3d) instead - */ - @Deprecated - public final void clamp(float min, float max, Tuple3d t) { - clamp(min, (double) max, t); - } - - - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clamp(double min, double max, Tuple3d t) { - if(t.x > max) { - x = max; - } else x = Math.max(t.x, min); - - if(t.y > max) { - y = max; - } else y = Math.max(t.y, min); - - if(t.z > max) { - z = max; - } else z = Math.max(t.z, min); - - } - - - /** - * @deprecated Use clampMin(double,Tuple3d) instead - */ - @Deprecated - public final void clampMin(float min, Tuple3d t) { - clampMin((double) min, t); - } - - - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMin(double min, Tuple3d t) { - x = Math.max(t.x, min); - - y = Math.max(t.y, min); - - z = Math.max(t.z, min); - - } - - - /** - * @deprecated Use clampMax(double,Tuple3d) instead - */ - @Deprecated - public final void clampMax(float max, Tuple3d t) { - clampMax((double) max, t); - } - - - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMax(double max, Tuple3d t) { - x = Math.min(t.x, max); - - y = Math.min(t.y, max); - - z = Math.min(t.z, max); - - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * - * @param t - * the source tuple, which will not be modified - */ - public final void absolute(Tuple3d t) { - x = Math.abs(t.x); - y = Math.abs(t.y); - z = Math.abs(t.z); - - } - - - /** - * @deprecated Use clamp(double,double) instead - */ - @Deprecated - public final void clamp(float min, float max) { - clamp(min, (double) max); - } - - - /** - * Clamps this tuple to the range [low, high]. - * - * @param min - * the lowest value in this tuple after clamping - * @param max - * the highest value in this tuple after clamping - */ - public final void clamp(double min, double max) { - if(x > max) { - x = max; - } else if(x < min) { - x = min; - } - - if(y > max) { - y = max; - } else if(y < min) { - y = min; - } - - if(z > max) { - z = max; - } else if(z < min) { - z = min; - } - - } - - - /** - * @deprecated Use clampMin(double) instead - */ - @Deprecated - public final void clampMin(float min) { - clampMin((double) min); - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * - * @param min - * the lowest value in this tuple after clamping - */ - public final void clampMin(double min) { - if(x < min) x = min; - if(y < min) y = min; - if(z < min) z = min; - } - - - /** - * @deprecated Use clampMax(double) instead - */ - @Deprecated - public final void clampMax(float max) { - clampMax((double) max); - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * - * @param max - * the highest value in the tuple after clamping - */ - public final void clampMax(double max) { - if(x > max) x = max; - if(y > max) y = max; - if(z > max) z = max; - } - - - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); - } - - - /** - * @deprecated Use interpolate(Tuple3d,Tuple3d,double) instead - */ - @Deprecated - public final void interpolate(Tuple3d t1, Tuple3d t2, float alpha) { - interpolate(t1, t2, (double) alpha); - } - - - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - * @param alpha - * the alpha interpolation parameter - */ - public final void interpolate(Tuple3d t1, Tuple3d t2, double alpha) { - this.x = (1 - alpha) * t1.x + alpha * t2.x; - this.y = (1 - alpha) * t1.y + alpha * t2.y; - this.z = (1 - alpha) * t1.z + alpha * t2.z; - } - - - /** - * @deprecated Use interpolate(Tuple3d,double) instead - */ - @Deprecated - public final void interpolate(Tuple3d t1, float alpha) { - interpolate(t1, (double) alpha); - } - - - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * - * @param t1 - * the first tuple - * @param alpha - * the alpha interpolation parameter - */ - public final void interpolate(Tuple3d t1, double alpha) { - this.x = (1 - alpha) * this.x + alpha * t1.x; - this.y = (1 - alpha) * this.y + alpha * t1.y; - this.z = (1 - alpha) * this.z + alpha * t1.z; - } - - /** - * Creates a new object of the same class as this object. - * - * @return a clone of this instance. - * @throws OutOfMemoryError - * if there is not enough memory. - * @see java.lang.Cloneable - * @since vecmath 1.3 - */ - public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch(CloneNotSupportedException e) { - Iris.reportError(e); - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } - } - - /** - * Get the x coordinate. - * - * @return the x coordinate. - * @since vecmath 1.5 - */ - public final double getX() { - return x; - } - - - /** - * Set the x coordinate. - * - * @param x - * value to x coordinate. - * @since vecmath 1.5 - */ - public final void setX(double x) { - this.x = x; - } - - - /** - * Get the y coordinate. - * - * @return the y coordinate. - * @since vecmath 1.5 - */ - public final double getY() { - return y; - } - - - /** - * Set the y coordinate. - * - * @param y - * value to y coordinate. - * @since vecmath 1.5 - */ - public final void setY(double y) { - this.y = y; - } - - /** - * Get the z coordinate. - * - * @return the z coordinate. - * @since vecmath 1.5 - */ - public final double getZ() { - return z; - } - - - /** - * Set the z coordinate. - * - * @param z - * value to z coordinate. - * @since vecmath 1.5 - */ - public final void setZ(double z) { - this.z = z; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Tuple3f.java b/src/main/java/com/volmit/iris/util/math/Tuple3f.java deleted file mode 100644 index 44deb8a9a..000000000 --- a/src/main/java/com/volmit/iris/util/math/Tuple3f.java +++ /dev/null @@ -1,710 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.Iris; - -/** - * A generic 3-element tuple that is represented by single precision-floating - * point x,y,z coordinates. - */ -public abstract class Tuple3f implements java.io.Serializable, Cloneable { - - static final long serialVersionUID = 5019834619484343712L; - - /** - * The x coordinate. - */ - public float x; - - /** - * The y coordinate. - */ - public float y; - - /** - * The z coordinate. - */ - public float z; - - - /** - * Constructs and initializes a Tuple3f from the specified xyz coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - */ - public Tuple3f(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } - - - /** - * Constructs and initializes a Tuple3f from the array of length 3. - * - * @param t - * the array of length 3 containing xyz in order - */ - public Tuple3f(float[] t) { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - } - - - /** - * Constructs and initializes a Tuple3f from the specified Tuple3f. - * - * @param t1 - * the Tuple3f containing the initialization x y z data - */ - public Tuple3f(Tuple3f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - } - - - /** - * Constructs and initializes a Tuple3f from the specified Tuple3d. - * - * @param t1 - * the Tuple3d containing the initialization x y z data - */ - public Tuple3f(Tuple3d t1) { - this.x = (float) t1.x; - this.y = (float) t1.y; - this.z = (float) t1.z; - } - - - /** - * Constructs and initializes a Tuple3f to (0,0,0). - */ - public Tuple3f() { - this.x = 0.0f; - this.y = 0.0f; - this.z = 0.0f; - } - - - /** - * Returns a string that contains the values of this Tuple3f. - * The form is (x,y,z). - * - * @return the String representation - */ - public String toString() { - return "(" + this.x + ", " + this.y + ", " + this.z + ")"; - } - - - /** - * Sets the value of this tuple to the specified xyz coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - */ - public final void set(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } - - - /** - * Sets the value of this tuple to the xyz coordinates specified in - * the array of length 3. - * - * @param t - * the array of length 3 containing xyz in order - */ - public final void set(float[] t) { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - } - - - /** - * Sets the value of this tuple to the value of tuple t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple3f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - } - - - /** - * Sets the value of this tuple to the value of tuple t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple3d t1) { - this.x = (float) t1.x; - this.y = (float) t1.y; - this.z = (float) t1.z; - } - - - /** - * Gets the value of this tuple and copies the values into t. - * - * @param t - * the array of length 3 into which the values are copied - */ - public final void get(float[] t) { - t[0] = this.x; - t[1] = this.y; - t[2] = this.z; - } - - - /** - * Gets the value of this tuple and copies the values into t. - * - * @param t - * the Tuple3f object into which the values of this object are copied - */ - public final void get(Tuple3f t) { - t.x = this.x; - t.y = this.y; - t.z = this.z; - } - - - /** - * Sets the value of this tuple to the vector sum of tuples t1 and t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void add(Tuple3f t1, Tuple3f t2) { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - this.z = t1.z + t2.z; - } - - - /** - * Sets the value of this tuple to the vector sum of itself and tuple t1. - * - * @param t1 - * the other tuple - */ - public final void add(Tuple3f t1) { - this.x += t1.x; - this.y += t1.y; - this.z += t1.z; - } - - - /** - * Sets the value of this tuple to the vector difference - * of tuples t1 and t2 (this = t1 - t2). - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void sub(Tuple3f t1, Tuple3f t2) { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - this.z = t1.z - t2.z; - } - - - /** - * Sets the value of this tuple to the vector difference of - * itself and tuple t1 (this = this - t1) . - * - * @param t1 - * the other tuple - */ - public final void sub(Tuple3f t1) { - this.x -= t1.x; - this.y -= t1.y; - this.z -= t1.z; - } - - - /** - * Sets the value of this tuple to the negation of tuple t1. - * - * @param t1 - * the source tuple - */ - public final void negate(Tuple3f t1) { - this.x = -t1.x; - this.y = -t1.y; - this.z = -t1.z; - } - - - /** - * Negates the value of this tuple in place. - */ - public final void negate() { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - } - - - /** - * Sets the value of this vector to the scalar multiplication - * of tuple t1. - * - * @param s - * the scalar value - * @param t1 - * the source tuple - */ - public final void scale(float s, Tuple3f t1) { - this.x = s * t1.x; - this.y = s * t1.y; - this.z = s * t1.z; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of the scale factor with this. - * - * @param s - * the scalar value - */ - public final void scale(float s) { - this.x *= s; - this.y *= s; - this.z *= s; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1 and then adds tuple t2 (this = s*t1 + t2). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be scaled and added - * @param t2 - * the tuple to be added without a scale - */ - public final void scaleAdd(float s, Tuple3f t1, Tuple3f t2) { - this.x = s * t1.x + t2.x; - this.y = s * t1.y + t2.y; - this.z = s * t1.z + t2.z; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself and then adds tuple t1 (this = s*this + t1). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be added - */ - public final void scaleAdd(float s, Tuple3f t1) { - this.x = s * this.x + t1.x; - this.y = s * this.y + t1.y; - this.z = s * this.z + t1.z; - } - - - /** - * Returns true if the Object t1 is of type Tuple3f and all of the - * data members of t1 are equal to the corresponding data members in - * this Tuple3f. - * - * @param t1 - * the vector with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple3f t1) { - try { - return (this.x == t1.x && this.y == t1.y && this.z == t1.z); - } catch(NullPointerException e2) { - Iris.reportError(e2); - return false; - } - } - - /** - * Returns true if the Object t1 is of type Tuple3f and all of the - * data members of t1 are equal to the corresponding data members in - * this Tuple3f. - * - * @param t1 - * the Object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) { - try { - Tuple3f t2 = (Tuple3f) t1; - return (this.x == t2.x && this.y == t2.y && this.z == t2.z); - } catch(NullPointerException | ClassCastException e2) { - Iris.reportError(e2); - return false; - } - } - - - /** - * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, - * otherwise returns false. The L-infinite - * distance is equal to MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. - * - * @param t1 - * the tuple to be compared to this tuple - * @param epsilon - * the threshold value - * @return true or false - */ - public boolean epsilonEquals(Tuple3f t1, float epsilon) { - float diff; - - diff = x - t1.x; - if(Float.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = y - t1.y; - if(Float.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = z - t1.z; - if(Float.isNaN(diff)) return false; - return !((diff < 0 ? -diff : diff) > epsilon); - - } - - - /** - * Returns a hash code value based on the data values in this - * object. Two different Tuple3f objects with identical data values - * (i.e., Tuple3f.equals returns true) will return the same hash - * code value. Two objects with different data members may return the - * same hash value, although this is not likely. - * - * @return the integer hash code value - */ - public int hashCode() { - long bits = 1L; - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(x); - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(y); - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(z); - return (int) (bits ^ (bits >> 32)); - } - - - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clamp(float min, float max, Tuple3f t) { - if(t.x > max) { - x = max; - } else x = Math.max(t.x, min); - - if(t.y > max) { - y = max; - } else y = Math.max(t.y, min); - - if(t.z > max) { - z = max; - } else z = Math.max(t.z, min); - - } - - - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMin(float min, Tuple3f t) { - x = Math.max(t.x, min); - - y = Math.max(t.y, min); - - z = Math.max(t.z, min); - - } - - - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMax(float max, Tuple3f t) { - x = Math.min(t.x, max); - - y = Math.min(t.y, max); - - z = Math.min(t.z, max); - - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * - * @param t - * the source tuple, which will not be modified - */ - public final void absolute(Tuple3f t) { - x = Math.abs(t.x); - y = Math.abs(t.y); - z = Math.abs(t.z); - } - - - /** - * Clamps this tuple to the range [low, high]. - * - * @param min - * the lowest value in this tuple after clamping - * @param max - * the highest value in this tuple after clamping - */ - public final void clamp(float min, float max) { - if(x > max) { - x = max; - } else if(x < min) { - x = min; - } - - if(y > max) { - y = max; - } else if(y < min) { - y = min; - } - - if(z > max) { - z = max; - } else if(z < min) { - z = min; - } - - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * - * @param min - * the lowest value in this tuple after clamping - */ - public final void clampMin(float min) { - if(x < min) x = min; - if(y < min) y = min; - if(z < min) z = min; - - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * - * @param max - * the highest value in the tuple after clamping - */ - public final void clampMax(float max) { - if(x > max) x = max; - if(y > max) y = max; - if(z > max) z = max; - - } - - - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); - - } - - - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - * @param alpha - * the alpha interpolation parameter - */ - public final void interpolate(Tuple3f t1, Tuple3f t2, float alpha) { - this.x = (1 - alpha) * t1.x + alpha * t2.x; - this.y = (1 - alpha) * t1.y + alpha * t2.y; - this.z = (1 - alpha) * t1.z + alpha * t2.z; - - - } - - - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * - * @param t1 - * the first tuple - * @param alpha - * the alpha interpolation parameter - */ - public final void interpolate(Tuple3f t1, float alpha) { - this.x = (1 - alpha) * this.x + alpha * t1.x; - this.y = (1 - alpha) * this.y + alpha * t1.y; - this.z = (1 - alpha) * this.z + alpha * t1.z; - - - } - - /** - * Creates a new object of the same class as this object. - * - * @return a clone of this instance. - * @throws OutOfMemoryError - * if there is not enough memory. - * @see java.lang.Cloneable - * @since vecmath 1.3 - */ - public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch(CloneNotSupportedException e) { - Iris.reportError(e); - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } - } - - - /** - * Get the x coordinate. - * - * @return the x coordinate. - * @since vecmath 1.5 - */ - public final float getX() { - return x; - } - - - /** - * Set the x coordinate. - * - * @param x - * value to x coordinate. - * @since vecmath 1.5 - */ - public final void setX(float x) { - this.x = x; - } - - - /** - * Get the y coordinate. - * - * @return the y coordinate. - * @since vecmath 1.5 - */ - public final float getY() { - return y; - } - - - /** - * Set the y coordinate. - * - * @param y - * value to y coordinate. - * @since vecmath 1.5 - */ - public final void setY(float y) { - this.y = y; - } - - /** - * Get the z coordinate. - * - * @return the z coordinate - * @since vecmath 1.5 - */ - public final float getZ() { - return z; - } - - - /** - * Set the Z coordinate. - * - * @param z - * value to z coordinate. - * @since vecmath 1.5 - */ - public final void setZ(float z) { - this.z = z; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Tuple4d.java b/src/main/java/com/volmit/iris/util/math/Tuple4d.java deleted file mode 100644 index b056932f9..000000000 --- a/src/main/java/com/volmit/iris/util/math/Tuple4d.java +++ /dev/null @@ -1,874 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.Iris; - -/** - * A 4 element tuple represented by double precision floating point - * x,y,z,w coordinates. - */ -public abstract class Tuple4d implements java.io.Serializable, Cloneable { - - static final long serialVersionUID = -4748953690425311052L; - - /** - * The x coordinate. - */ - public double x; - - /** - * The y coordinate. - */ - public double y; - - /** - * The z coordinate. - */ - public double z; - - /** - * The w coordinate. - */ - public double w; - - - /** - * Constructs and initializes a Tuple4d from the specified xyzw coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - * @param w - * the w coordinate - */ - public Tuple4d(double x, double y, double z, double w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - - /** - * Constructs and initializes a Tuple4d from the coordinates contained - * in the array. - * - * @param t - * the array of length 4 containing xyzw in order - */ - public Tuple4d(double[] t) { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - this.w = t[3]; - } - - - /** - * Constructs and initializes a Tuple4d from the specified Tuple4d. - * - * @param t1 - * the Tuple4d containing the initialization x y z w data - */ - public Tuple4d(Tuple4d t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; - } - - - /** - * Constructs and initializes a Tuple4d from the specified Tuple4f. - * - * @param t1 - * the Tuple4f containing the initialization x y z w data - */ - public Tuple4d(Tuple4f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; - } - - - /** - * Constructs and initializes a Tuple4d to (0,0,0,0). - */ - public Tuple4d() { - this.x = 0.0; - this.y = 0.0; - this.z = 0.0; - this.w = 0.0; - } - - - /** - * Sets the value of this tuple to the specified xyzw coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - * @param w - * the w coordinate - */ - public final void set(double x, double y, double z, double w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - - /** - * Sets the value of this tuple to the specified xyzw coordinates. - * - * @param t - * the array of length 4 containing xyzw in order - */ - public final void set(double[] t) { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - this.w = t[3]; - } - - - /** - * Sets the value of this tuple to the value of tuple t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple4d t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; - } - - - /** - * Sets the value of this tuple to the value of tuple t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple4f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; - } - - - /** - * Gets the value of this tuple and places it into the array t of - * length four in x,y,z,w order. - * - * @param t - * the array of length four - */ - public final void get(double[] t) { - t[0] = this.x; - t[1] = this.y; - t[2] = this.z; - t[3] = this.w; - } - - - /** - * Gets the value of this tuple and places it into the Tuple4d - * argument of - * length four in x,y,z,w order. - * - * @param t - * the Tuple into which the values will be copied - */ - public final void get(Tuple4d t) { - t.x = this.x; - t.y = this.y; - t.z = this.z; - t.w = this.w; - } - - - /** - * Sets the value of this tuple to the tuple sum of tuples t1 and t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void add(Tuple4d t1, Tuple4d t2) { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - this.z = t1.z + t2.z; - this.w = t1.w + t2.w; - } - - - /** - * Sets the value of this tuple to the sum of itself and tuple t1. - * - * @param t1 - * the other tuple - */ - public final void add(Tuple4d t1) { - this.x += t1.x; - this.y += t1.y; - this.z += t1.z; - this.w += t1.w; - } - - - /** - * Sets the value of this tuple to the difference - * of tuples t1 and t2 (this = t1 - t2). - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void sub(Tuple4d t1, Tuple4d t2) { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - this.z = t1.z - t2.z; - this.w = t1.w - t2.w; - } - - - /** - * Sets the value of this tuple to the difference of itself - * and tuple t1 (this = this - t1). - * - * @param t1 - * the other tuple - */ - public final void sub(Tuple4d t1) { - this.x -= t1.x; - this.y -= t1.y; - this.z -= t1.z; - this.w -= t1.w; - } - - - /** - * Sets the value of this tuple to the negation of tuple t1. - * - * @param t1 - * the source tuple - */ - public final void negate(Tuple4d t1) { - this.x = -t1.x; - this.y = -t1.y; - this.z = -t1.z; - this.w = -t1.w; - } - - - /** - * Negates the value of this tuple in place. - */ - public final void negate() { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - this.w = -this.w; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of the scale factor with the tuple t1. - * - * @param s - * the scalar value - * @param t1 - * the source tuple - */ - public final void scale(double s, Tuple4d t1) { - this.x = s * t1.x; - this.y = s * t1.y; - this.z = s * t1.z; - this.w = s * t1.w; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of the scale factor with this. - * - * @param s - * the scalar value - */ - public final void scale(double s) { - this.x *= s; - this.y *= s; - this.z *= s; - this.w *= s; - } - - - /** - * Sets the value of this tuple to the scalar multiplication by s - * of tuple t1 plus tuple t2 (this = s*t1 + t2). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be multipled - * @param t2 - * the tuple to be added - */ - public final void scaleAdd(double s, Tuple4d t1, Tuple4d t2) { - this.x = s * t1.x + t2.x; - this.y = s * t1.y + t2.y; - this.z = s * t1.z + t2.z; - this.w = s * t1.w + t2.w; - } - - - /** - * @deprecated Use scaleAdd(double,Tuple4d) instead - */ - @Deprecated - public final void scaleAdd(float s, Tuple4d t1) { - scaleAdd((double) s, t1); - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself and then adds tuple t1 (this = s*this + t1). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be added - */ - public final void scaleAdd(double s, Tuple4d t1) { - this.x = s * this.x + t1.x; - this.y = s * this.y + t1.y; - this.z = s * this.z + t1.z; - this.w = s * this.w + t1.w; - } - - - /** - * Returns a string that contains the values of this Tuple4d. - * The form is (x,y,z,w). - * - * @return the String representation - */ - public String toString() { - return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.w + ")"; - } - - - /** - * Returns true if all of the data members of Tuple4d t1 are - * equal to the corresponding data members in this Tuple4d. - * - * @param t1 - * the tuple with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple4d t1) { - try { - return (this.x == t1.x && this.y == t1.y && this.z == t1.z - && this.w == t1.w); - } catch(NullPointerException e2) { - Iris.reportError(e2); - return false; - } - } - - /** - * Returns true if the Object t1 is of type Tuple4d and all of the - * data members of t1 are equal to the corresponding data members in - * this Tuple4d. - * - * @param t1 - * the object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) { - try { - - Tuple4d t2 = (Tuple4d) t1; - return (this.x == t2.x && this.y == t2.y && - this.z == t2.z && this.w == t2.w); - } catch(NullPointerException | ClassCastException e2) { - Iris.reportError(e2); - return false; - } - } - - - /** - * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, - * otherwise returns false. The L-infinite - * distance is equal to - * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. - * - * @param t1 - * the tuple to be compared to this tuple - * @param epsilon - * the threshold value - * @return true or false - */ - public boolean epsilonEquals(Tuple4d t1, double epsilon) { - double diff; - - diff = x - t1.x; - if(Double.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = y - t1.y; - if(Double.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = z - t1.z; - if(Double.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = w - t1.w; - if(Double.isNaN(diff)) return false; - return !((diff < 0 ? -diff : diff) > epsilon); - - } - - - /** - * Returns a hash code value based on the data values in this - * object. Two different Tuple4d objects with identical data values - * (i.e., Tuple4d.equals returns true) will return the same hash - * code value. Two objects with different data members may return the - * same hash value, although this is not likely. - * - * @return the integer hash code value - */ - public int hashCode() { - long bits = 1L; - bits = 31L * bits + VecMathUtil.doubleToLongBits(x); - bits = 31L * bits + VecMathUtil.doubleToLongBits(y); - bits = 31L * bits + VecMathUtil.doubleToLongBits(z); - bits = 31L * bits + VecMathUtil.doubleToLongBits(w); - return (int) (bits ^ (bits >> 32)); - } - - - /** - * @deprecated Use clamp(double,double,Tuple4d) instead - */ - @Deprecated - public final void clamp(float min, float max, Tuple4d t) { - clamp(min, (double) max, t); - } - - - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clamp(double min, double max, Tuple4d t) { - if(t.x > max) { - x = max; - } else x = Math.max(t.x, min); - - if(t.y > max) { - y = max; - } else y = Math.max(t.y, min); - - if(t.z > max) { - z = max; - } else z = Math.max(t.z, min); - - if(t.w > max) { - w = max; - } else w = Math.max(t.w, min); - - } - - - /** - * @deprecated Use clampMin(double,Tuple4d) instead - */ - @Deprecated - public final void clampMin(float min, Tuple4d t) { - clampMin((double) min, t); - } - - - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMin(double min, Tuple4d t) { - x = Math.max(t.x, min); - - y = Math.max(t.y, min); - - z = Math.max(t.z, min); - - w = Math.max(t.w, min); - - } - - - /** - * @deprecated Use clampMax(double,Tuple4d) instead - */ - @Deprecated - public final void clampMax(float max, Tuple4d t) { - clampMax((double) max, t); - } - - - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMax(double max, Tuple4d t) { - x = Math.min(t.x, max); - - y = Math.min(t.y, max); - - z = Math.min(t.z, max); - - if(t.w > max) { - w = max; - } else { - w = t.z; - } - - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * - * @param t - * the source tuple, which will not be modified - */ - public final void absolute(Tuple4d t) { - x = Math.abs(t.x); - y = Math.abs(t.y); - z = Math.abs(t.z); - w = Math.abs(t.w); - - } - - - /** - * @deprecated Use clamp(double,double) instead - */ - @Deprecated - public final void clamp(float min, float max) { - clamp(min, (double) max); - } - - - /** - * Clamps this tuple to the range [low, high]. - * - * @param min - * the lowest value in this tuple after clamping - * @param max - * the highest value in this tuple after clamping - */ - public final void clamp(double min, double max) { - if(x > max) { - x = max; - } else if(x < min) { - x = min; - } - - if(y > max) { - y = max; - } else if(y < min) { - y = min; - } - - if(z > max) { - z = max; - } else if(z < min) { - z = min; - } - - if(w > max) { - w = max; - } else if(w < min) { - w = min; - } - - } - - - /** - * @deprecated Use clampMin(double) instead - */ - @Deprecated - public final void clampMin(float min) { - clampMin((double) min); - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * - * @param min - * the lowest value in this tuple after clamping - */ - public final void clampMin(double min) { - if(x < min) x = min; - if(y < min) y = min; - if(z < min) z = min; - if(w < min) w = min; - } - - - /** - * @deprecated Use clampMax(double) instead - */ - @Deprecated - public final void clampMax(float max) { - clampMax((double) max); - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * - * @param max - * the highest value in the tuple after clamping - */ - public final void clampMax(double max) { - if(x > max) x = max; - if(y > max) y = max; - if(z > max) z = max; - if(w > max) w = max; - - } - - - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); - w = Math.abs(w); - - } - - - /** - * @deprecated Use interpolate(Tuple4d,Tuple4d,double) instead - */ - @Deprecated - public void interpolate(Tuple4d t1, Tuple4d t2, float alpha) { - interpolate(t1, t2, (double) alpha); - } - - - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - * @param alpha - * the alpha interpolation parameter - */ - public void interpolate(Tuple4d t1, Tuple4d t2, double alpha) { - this.x = (1 - alpha) * t1.x + alpha * t2.x; - this.y = (1 - alpha) * t1.y + alpha * t2.y; - this.z = (1 - alpha) * t1.z + alpha * t2.z; - this.w = (1 - alpha) * t1.w + alpha * t2.w; - } - - - /** - * @deprecated Use interpolate(Tuple4d,double) instead - */ - @Deprecated - public void interpolate(Tuple4d t1, float alpha) { - interpolate(t1, (double) alpha); - } - - - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * - * @param t1 - * the first tuple - * @param alpha - * the alpha interpolation parameter - */ - public void interpolate(Tuple4d t1, double alpha) { - this.x = (1 - alpha) * this.x + alpha * t1.x; - this.y = (1 - alpha) * this.y + alpha * t1.y; - this.z = (1 - alpha) * this.z + alpha * t1.z; - this.w = (1 - alpha) * this.w + alpha * t1.w; - } - - /** - * Creates a new object of the same class as this object. - * - * @return a clone of this instance. - * @throws OutOfMemoryError - * if there is not enough memory. - * @see java.lang.Cloneable - * @since vecmath 1.3 - */ - public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch(CloneNotSupportedException e) { - Iris.reportError(e); - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } - } - - /** - * Get the x coordinate. - * - * @return the x coordinate. - * @since vecmath 1.5 - */ - public final double getX() { - return x; - } - - - /** - * Set the x coordinate. - * - * @param x - * value to x coordinate. - * @since vecmath 1.5 - */ - public final void setX(double x) { - this.x = x; - } - - - /** - * Get the y coordinate. - * - * @return the y coordinate. - * @since vecmath 1.5 - */ - public final double getY() { - return y; - } - - - /** - * Set the y coordinate. - * - * @param y - * value to y coordinate. - * @since vecmath 1.5 - */ - public final void setY(double y) { - this.y = y; - } - - /** - * Get the z coordinate. - * - * @return the z coordinate. - * @since vecmath 1.5 - */ - public final double getZ() { - return z; - } - - - /** - * Set the z coordinate. - * - * @param z - * value to z coordinate. - * @since vecmath 1.5 - */ - public final void setZ(double z) { - this.z = z; - } - - - /** - * Get the w coordinate. - * - * @return the w coordinate. - * @since vecmath 1.5 - */ - public final double getW() { - return w; - } - - - /** - * Set the w coordinate. - * - * @param w - * value to w coordinate. - * @since vecmath 1.5 - */ - public final void setW(double w) { - this.w = w; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Tuple4f.java b/src/main/java/com/volmit/iris/util/math/Tuple4f.java deleted file mode 100644 index d345a62df..000000000 --- a/src/main/java/com/volmit/iris/util/math/Tuple4f.java +++ /dev/null @@ -1,789 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.Iris; - -/** - * A 4-element tuple represented by single-precision floating point x,y,z,w - * coordinates. - */ -public abstract class Tuple4f implements java.io.Serializable, Cloneable { - - static final long serialVersionUID = 7068460319248845763L; - - /** - * The x coordinate. - */ - public float x; - - /** - * The y coordinate. - */ - public float y; - - /** - * The z coordinate. - */ - public float z; - - /** - * The w coordinate. - */ - public float w; - - - /** - * Constructs and initializes a Tuple4f from the specified xyzw coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - * @param w - * the w coordinate - */ - public Tuple4f(float x, float y, float z, float w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - - /** - * Constructs and initializes a Tuple4f from the array of length 4. - * - * @param t - * the array of length 4 containing xyzw in order - */ - public Tuple4f(float[] t) { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - this.w = t[3]; - } - - - /** - * Constructs and initializes a Tuple4f from the specified Tuple4f. - * - * @param t1 - * the Tuple4f containing the initialization x y z w data - */ - public Tuple4f(Tuple4f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; - } - - - /** - * Constructs and initializes a Tuple4f from the specified Tuple4d. - * - * @param t1 - * the Tuple4d containing the initialization x y z w data - */ - public Tuple4f(Tuple4d t1) { - this.x = (float) t1.x; - this.y = (float) t1.y; - this.z = (float) t1.z; - this.w = (float) t1.w; - } - - - /** - * Constructs and initializes a Tuple4f to (0,0,0,0). - */ - public Tuple4f() { - this.x = 0.0f; - this.y = 0.0f; - this.z = 0.0f; - this.w = 0.0f; - } - - - /** - * Sets the value of this tuple to the specified xyzw coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - * @param w - * the w coordinate - */ - public final void set(float x, float y, float z, float w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - - /** - * Sets the value of this tuple to the specified coordinates in the - * array of length 4. - * - * @param t - * the array of length 4 containing xyzw in order - */ - public final void set(float[] t) { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - this.w = t[3]; - } - - - /** - * Sets the value of this tuple to the value of tuple t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple4f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; - } - - - /** - * Sets the value of this tuple to the value of tuple t1. - * - * @param t1 - * the tuple to be copied - */ - public final void set(Tuple4d t1) { - this.x = (float) t1.x; - this.y = (float) t1.y; - this.z = (float) t1.z; - this.w = (float) t1.w; - } - - - /** - * Copies the values of this tuple into the array t. - * - * @param t - * the array - */ - public final void get(float[] t) { - t[0] = this.x; - t[1] = this.y; - t[2] = this.z; - t[3] = this.w; - } - - - /** - * Copies the values of this tuple into the tuple t. - * - * @param t - * the target tuple - */ - public final void get(Tuple4f t) { - t.x = this.x; - t.y = this.y; - t.z = this.z; - t.w = this.w; - } - - - /** - * Sets the value of this tuple to the sum of tuples t1 and t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void add(Tuple4f t1, Tuple4f t2) { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - this.z = t1.z + t2.z; - this.w = t1.w + t2.w; - } - - - /** - * Sets the value of this tuple to the sum of itself and t1. - * - * @param t1 - * the other tuple - */ - public final void add(Tuple4f t1) { - this.x += t1.x; - this.y += t1.y; - this.z += t1.z; - this.w += t1.w; - } - - - /** - * Sets the value of this tuple to the difference - * of tuples t1 and t2 (this = t1 - t2). - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - */ - public final void sub(Tuple4f t1, Tuple4f t2) { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - this.z = t1.z - t2.z; - this.w = t1.w - t2.w; - } - - - /** - * Sets the value of this tuple to the difference - * of itself and t1 (this = this - t1). - * - * @param t1 - * the other tuple - */ - public final void sub(Tuple4f t1) { - this.x -= t1.x; - this.y -= t1.y; - this.z -= t1.z; - this.w -= t1.w; - } - - - /** - * Sets the value of this tuple to the negation of tuple t1. - * - * @param t1 - * the source tuple - */ - public final void negate(Tuple4f t1) { - this.x = -t1.x; - this.y = -t1.y; - this.z = -t1.z; - this.w = -t1.w; - } - - - /** - * Negates the value of this tuple in place. - */ - public final void negate() { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - this.w = -this.w; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1. - * - * @param s - * the scalar value - * @param t1 - * the source tuple - */ - public final void scale(float s, Tuple4f t1) { - this.x = s * t1.x; - this.y = s * t1.y; - this.z = s * t1.z; - this.w = s * t1.w; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of the scale factor with this. - * - * @param s - * the scalar value - */ - public final void scale(float s) { - this.x *= s; - this.y *= s; - this.z *= s; - this.w *= s; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1 plus tuple t2 (this = s*t1 + t2). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be multipled - * @param t2 - * the tuple to be added - */ - public final void scaleAdd(float s, Tuple4f t1, Tuple4f t2) { - this.x = s * t1.x + t2.x; - this.y = s * t1.y + t2.y; - this.z = s * t1.z + t2.z; - this.w = s * t1.w + t2.w; - } - - - /** - * Sets the value of this tuple to the scalar multiplication - * of itself and then adds tuple t1 (this = s*this + t1). - * - * @param s - * the scalar value - * @param t1 - * the tuple to be added - */ - public final void scaleAdd(float s, Tuple4f t1) { - this.x = s * this.x + t1.x; - this.y = s * this.y + t1.y; - this.z = s * this.z + t1.z; - this.w = s * this.w + t1.w; - } - - - /** - * Returns a string that contains the values of this Tuple4f. - * The form is (x,y,z,w). - * - * @return the String representation - */ - public String toString() { - return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.w + ")"; - } - - /** - * Returns true if all of the data members of Tuple4f t1 are - * equal to the corresponding data members in this Tuple4f. - * - * @param t1 - * the vector with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple4f t1) { - try { - return (this.x == t1.x && this.y == t1.y && this.z == t1.z - && this.w == t1.w); - } catch(NullPointerException e2) { - Iris.reportError(e2); - return false; - } - } - - /** - * Returns true if the Object t1 is of type Tuple4f and all of the - * data members of t1 are equal to the corresponding data members in - * this Tuple4f. - * - * @param t1 - * the object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) { - try { - Tuple4f t2 = (Tuple4f) t1; - return (this.x == t2.x && this.y == t2.y && - this.z == t2.z && this.w == t2.w); - } catch(NullPointerException | ClassCastException e2) { - Iris.reportError(e2); - return false; - } - } - - - /** - * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, - * otherwise returns false. The L-infinite - * distance is equal to - * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. - * - * @param t1 - * the tuple to be compared to this tuple - * @param epsilon - * the threshold value - * @return true or false - */ - public boolean epsilonEquals(Tuple4f t1, float epsilon) { - float diff; - - diff = x - t1.x; - if(Float.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = y - t1.y; - if(Float.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = z - t1.z; - if(Float.isNaN(diff)) return false; - if((diff < 0 ? -diff : diff) > epsilon) return false; - - diff = w - t1.w; - if(Float.isNaN(diff)) return false; - return !((diff < 0 ? -diff : diff) > epsilon); - } - - - /** - * Returns a hash code value based on the data values in this - * object. Two different Tuple4f objects with identical data values - * (i.e., Tuple4f.equals returns true) will return the same hash - * code value. Two objects with different data members may return the - * same hash value, although this is not likely. - * - * @return the integer hash code value - */ - public int hashCode() { - long bits = 1L; - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(x); - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(y); - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(z); - bits = 31L * bits + (long) VecMathUtil.floatToIntBits(w); - return (int) (bits ^ (bits >> 32)); - } - - - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clamp(float min, float max, Tuple4f t) { - if(t.x > max) { - x = max; - } else x = Math.max(t.x, min); - - if(t.y > max) { - y = max; - } else y = Math.max(t.y, min); - - if(t.z > max) { - z = max; - } else z = Math.max(t.z, min); - - if(t.w > max) { - w = max; - } else w = Math.max(t.w, min); - - } - - - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * - * @param min - * the lowest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMin(float min, Tuple4f t) { - x = Math.max(t.x, min); - - y = Math.max(t.y, min); - - z = Math.max(t.z, min); - - w = Math.max(t.w, min); - - - } - - - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * - * @param max - * the highest value in the tuple after clamping - * @param t - * the source tuple, which will not be modified - */ - public final void clampMax(float max, Tuple4f t) { - x = Math.min(t.x, max); - - y = Math.min(t.y, max); - - z = Math.min(t.z, max); - - if(t.w > max) { - w = max; - } else { - w = t.z; - } - - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * - * @param t - * the source tuple, which will not be modified - */ - public final void absolute(Tuple4f t) { - x = Math.abs(t.x); - y = Math.abs(t.y); - z = Math.abs(t.z); - w = Math.abs(t.w); - } - - - /** - * Clamps this tuple to the range [low, high]. - * - * @param min - * the lowest value in this tuple after clamping - * @param max - * the highest value in this tuple after clamping - */ - public final void clamp(float min, float max) { - if(x > max) { - x = max; - } else if(x < min) { - x = min; - } - - if(y > max) { - y = max; - } else if(y < min) { - y = min; - } - - if(z > max) { - z = max; - } else if(z < min) { - z = min; - } - - if(w > max) { - w = max; - } else if(w < min) { - w = min; - } - - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * - * @param min - * the lowest value in this tuple after clamping - */ - public final void clampMin(float min) { - if(x < min) x = min; - if(y < min) y = min; - if(z < min) z = min; - if(w < min) w = min; - - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * - * @param max - * the highest value in the tuple after clamping - */ - public final void clampMax(float max) { - if(x > max) x = max; - if(y > max) y = max; - if(z > max) z = max; - if(w > max) w = max; - - } - - - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); - w = Math.abs(w); - } - - - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * - * @param t1 - * the first tuple - * @param t2 - * the second tuple - * @param alpha - * the alpha interpolation parameter - */ - public void interpolate(Tuple4f t1, Tuple4f t2, float alpha) { - this.x = (1 - alpha) * t1.x + alpha * t2.x; - this.y = (1 - alpha) * t1.y + alpha * t2.y; - this.z = (1 - alpha) * t1.z + alpha * t2.z; - this.w = (1 - alpha) * t1.w + alpha * t2.w; - - } - - - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * - * @param t1 - * the first tuple - * @param alpha - * the alpha interpolation parameter - */ - public void interpolate(Tuple4f t1, float alpha) { - this.x = (1 - alpha) * this.x + alpha * t1.x; - this.y = (1 - alpha) * this.y + alpha * t1.y; - this.z = (1 - alpha) * this.z + alpha * t1.z; - this.w = (1 - alpha) * this.w + alpha * t1.w; - - } - - /** - * Creates a new object of the same class as this object. - * - * @return a clone of this instance. - * @throws OutOfMemoryError - * if there is not enough memory. - * @see java.lang.Cloneable - * @since vecmath 1.3 - */ - public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch(CloneNotSupportedException e) { - Iris.reportError(e); - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } - } - - /** - * Get the x coordinate. - * - * @return the x coordinate. - * @since vecmath 1.5 - */ - public final float getX() { - return x; - } - - - /** - * Set the x coordinate. - * - * @param x - * value to x coordinate. - * @since vecmath 1.5 - */ - public final void setX(float x) { - this.x = x; - } - - - /** - * Get the y coordinate. - * - * @return the y coordinate. - * @since vecmath 1.5 - */ - public final float getY() { - return y; - } - - - /** - * Set the y coordinate. - * - * @param y - * value to y coordinate. - * @since vecmath 1.5 - */ - public final void setY(float y) { - this.y = y; - } - - /** - * Get the z coordinate. - * - * @return the z coordinate. - * @since vecmath 1.5 - */ - public final float getZ() { - return z; - } - - - /** - * Set the z coordinate. - * - * @param z - * value to z coordinate. - * @since vecmath 1.5 - */ - public final void setZ(float z) { - this.z = z; - } - - - /** - * Get the w coordinate. - * - * @return the w coordinate. - * @since vecmath 1.5 - */ - public final float getW() { - return w; - } - - - /** - * Set the w coordinate. - * - * @param w - * value to w coordinate. - * @since vecmath 1.5 - */ - public final void setW(float w) { - this.w = w; - } -} diff --git a/src/main/java/com/volmit/iris/util/math/VecMathUtil.java b/src/main/java/com/volmit/iris/util/math/VecMathUtil.java deleted file mode 100644 index cc0e20551..000000000 --- a/src/main/java/com/volmit/iris/util/math/VecMathUtil.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * Utility vecmath class used when computing the hash code for vecmath - * objects containing float or double values. This fixes Issue 36. - */ -class VecMathUtil { - /** - * Do not construct an instance of this class. - */ - private VecMathUtil() { - } - - /** - * Returns the representation of the specified floating-point - * value according to the IEEE 754 floating-point "single format" - * bit layout, after first mapping -0.0 to 0.0. This method is - * identical to Float.floatToIntBits(float) except that an integer - * value of 0 is returned for a floating-point value of - * -0.0f. This is done for the purpose of computing a hash code - * that satisfies the contract of hashCode() and equals(). The - * equals() method in each vecmath class does a pair-wise "==" - * test on each floating-point field in the class (e.g., x, y, and - * z for a Tuple3f). Since 0.0f == -0.0f returns true, - * we must also return the same hash code for two objects, one of - * which has a field with a value of -0.0f and the other of which - * has a cooresponding field with a value of 0.0f. - * - * @param f - * an input floating-point number - * @return the integer bits representing that floating-point - * number, after first mapping -0.0f to 0.0f - */ - static int floatToIntBits(float f) { - // Check for +0 or -0 - if(f == 0.0f) { - return 0; - } else { - return Float.floatToIntBits(f); - } - } - - /** - * Returns the representation of the specified floating-point - * value according to the IEEE 754 floating-point "double format" - * bit layout, after first mapping -0.0 to 0.0. This method is - * identical to Double.doubleToLongBits(double) except that an - * integer value of 0L is returned for a floating-point value of - * -0.0. This is done for the purpose of computing a hash code - * that satisfies the contract of hashCode() and equals(). The - * equals() method in each vecmath class does a pair-wise "==" - * test on each floating-point field in the class (e.g., x, y, and - * z for a Tuple3d). Since 0.0 == -0.0 returns true, we - * must also return the same hash code for two objects, one of - * which has a field with a value of -0.0 and the other of which - * has a cooresponding field with a value of 0.0. - * - * @param d - * an input double precision floating-point number - * @return the integer bits representing that floating-point - * number, after first mapping -0.0f to 0.0f - */ - static long doubleToLongBits(double d) { - // Check for +0 or -0 - if(d == 0.0) { - return 0L; - } else { - return Double.doubleToLongBits(d); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/math/Vector2d.java b/src/main/java/com/volmit/iris/util/math/Vector2d.java deleted file mode 100644 index 099fad899..000000000 --- a/src/main/java/com/volmit/iris/util/math/Vector2d.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * A 2-element vector that is represented by double-precision floating - * point x,y coordinates. - */ -public class Vector2d extends Tuple2d implements java.io.Serializable { - - // Combatible with 1.1 - static final long serialVersionUID = 8572646365302599857L; - - /** - * Constructs and initializes a Vector2d from the specified xy coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - */ - public Vector2d(double x, double y) { - super(x, y); - } - - - /** - * Constructs and initializes a Vector2d from the specified array. - * - * @param v - * the array of length 2 containing xy in order - */ - public Vector2d(double[] v) { - super(v); - } - - - /** - * Constructs and initializes a Vector2d from the specified Vector2d. - * - * @param v1 - * the Vector2d containing the initialization x y data - */ - public Vector2d(Vector2d v1) { - super(v1); - } - - - /** - * Constructs and initializes a Vector2d from the specified Vector2f. - * - * @param v1 - * the Vector2f containing the initialization x y data - */ - public Vector2d(Vector2f v1) { - super(v1); - } - - - /** - * Constructs and initializes a Vector2d from the specified Tuple2d. - * - * @param t1 - * the Tuple2d containing the initialization x y data - */ - public Vector2d(Tuple2d t1) { - super(t1); - } - - - /** - * Constructs and initializes a Vector2d from the specified Tuple2f. - * - * @param t1 - * the Tuple2f containing the initialization x y data - */ - public Vector2d(Tuple2f t1) { - super(t1); - } - - - /** - * Constructs and initializes a Vector2d to (0,0). - */ - public Vector2d() { - super(); - } - - - /** - * Computes the dot product of the this vector and vector v1. - * - * @param v1 - * the other vector - */ - public final double dot(Vector2d v1) { - return (this.x * v1.x + this.y * v1.y); - } - - - /** - * Returns the length of this vector. - * - * @return the length of this vector - */ - public final double length() { - return Math.sqrt(this.x * this.x + this.y * this.y); - } - - /** - * Returns the squared length of this vector. - * - * @return the squared length of this vector - */ - public final double lengthSquared() { - return (this.x * this.x + this.y * this.y); - } - - /** - * Sets the value of this vector to the normalization of vector v1. - * - * @param v1 - * the un-normalized vector - */ - public final void normalize(Vector2d v1) { - double norm; - - norm = 1.0 / Math.sqrt(v1.x * v1.x + v1.y * v1.y); - this.x = v1.x * norm; - this.y = v1.y * norm; - } - - /** - * Normalizes this vector in place. - */ - public final void normalize() { - double norm; - - norm = 1.0 / Math.sqrt(this.x * this.x + this.y * this.y); - this.x *= norm; - this.y *= norm; - } - - - /** - * Returns the angle in radians between this vector and the vector - * parameter; the return value is constrained to the range [0,PI]. - * - * @param v1 - * the other vector - * @return the angle in radians in the range [0,PI] - */ - public final double angle(Vector2d v1) { - double vDot = this.dot(v1) / (this.length() * v1.length()); - if(vDot < -1.0) vDot = -1.0; - if(vDot > 1.0) vDot = 1.0; - return Math.acos(vDot); - - } - - -} diff --git a/src/main/java/com/volmit/iris/util/math/Vector2f.java b/src/main/java/com/volmit/iris/util/math/Vector2f.java deleted file mode 100644 index 83c7685d8..000000000 --- a/src/main/java/com/volmit/iris/util/math/Vector2f.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * A 2-element vector that is represented by single-precision floating - * point x,y coordinates. - */ -public class Vector2f extends Tuple2f implements java.io.Serializable { - - // Combatible with 1.1 - static final long serialVersionUID = -2168194326883512320L; - - /** - * Constructs and initializes a Vector2f from the specified xy coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - */ - public Vector2f(float x, float y) { - super(x, y); - } - - - /** - * Constructs and initializes a Vector2f from the specified array. - * - * @param v - * the array of length 2 containing xy in order - */ - public Vector2f(float[] v) { - super(v); - } - - - /** - * Constructs and initializes a Vector2f from the specified Vector2f. - * - * @param v1 - * the Vector2f containing the initialization x y data - */ - public Vector2f(Vector2f v1) { - super(v1); - } - - - /** - * Constructs and initializes a Vector2f from the specified Vector2d. - * - * @param v1 - * the Vector2d containing the initialization x y data - */ - public Vector2f(Vector2d v1) { - super(v1); - } - - - /** - * Constructs and initializes a Vector2f from the specified Tuple2f. - * - * @param t1 - * the Tuple2f containing the initialization x y data - */ - public Vector2f(Tuple2f t1) { - super(t1); - } - - - /** - * Constructs and initializes a Vector2f from the specified Tuple2d. - * - * @param t1 - * the Tuple2d containing the initialization x y data - */ - public Vector2f(Tuple2d t1) { - super(t1); - } - - - /** - * Constructs and initializes a Vector2f to (0,0). - */ - public Vector2f() { - super(); - } - - - /** - * Computes the dot product of the this vector and vector v1. - * - * @param v1 - * the other vector - */ - public final float dot(Vector2f v1) { - return (this.x * v1.x + this.y * v1.y); - } - - - /** - * Returns the length of this vector. - * - * @return the length of this vector - */ - public final float length() { - return (float) Math.sqrt(this.x * this.x + this.y * this.y); - } - - /** - * Returns the squared length of this vector. - * - * @return the squared length of this vector - */ - public final float lengthSquared() { - return (this.x * this.x + this.y * this.y); - } - - /** - * Sets the value of this vector to the normalization of vector v1. - * - * @param v1 - * the un-normalized vector - */ - public final void normalize(Vector2f v1) { - float norm; - - norm = (float) (1.0 / Math.sqrt(v1.x * v1.x + v1.y * v1.y)); - this.x = v1.x * norm; - this.y = v1.y * norm; - } - - /** - * Normalizes this vector in place. - */ - public final void normalize() { - float norm; - - norm = (float) - (1.0 / Math.sqrt(this.x * this.x + this.y * this.y)); - this.x *= norm; - this.y *= norm; - } - - - /** - * Returns the angle in radians between this vector and the vector - * parameter; the return value is constrained to the range [0,PI]. - * - * @param v1 - * the other vector - * @return the angle in radians in the range [0,PI] - */ - public final float angle(Vector2f v1) { - double vDot = this.dot(v1) / (this.length() * v1.length()); - if(vDot < -1.0) vDot = -1.0; - if(vDot > 1.0) vDot = 1.0; - return ((float) (Math.acos(vDot))); - } - - -} diff --git a/src/main/java/com/volmit/iris/util/math/Vector3d.java b/src/main/java/com/volmit/iris/util/math/Vector3d.java deleted file mode 100644 index bf51a6ff1..000000000 --- a/src/main/java/com/volmit/iris/util/math/Vector3d.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * A 3-element vector that is represented by double-precision floating point - * x,y,z coordinates. If this value represents a normal, then it should - * be normalized. - */ -public class Vector3d extends Tuple3d implements java.io.Serializable { - - // Combatible with 1.1 - static final long serialVersionUID = 3761969948420550442L; - - /** - * Constructs and initializes a Vector3d from the specified xyz coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - */ - public Vector3d(double x, double y, double z) { - super(x, y, z); - } - - - /** - * Constructs and initializes a Vector3d from the array of length 3. - * - * @param v - * the array of length 3 containing xyz in order - */ - public Vector3d(double[] v) { - super(v); - } - - - /** - * Constructs and initializes a Vector3d from the specified Vector3d. - * - * @param v1 - * the Vector3d containing the initialization x y z data - */ - public Vector3d(Vector3d v1) { - super(v1); - } - - - /** - * Constructs and initializes a Vector3d from the specified Vector3f. - * - * @param v1 - * the Vector3f containing the initialization x y z data - */ - public Vector3d(Vector3f v1) { - super(v1); - } - - - /** - * Constructs and initializes a Vector3d from the specified Tuple3f. - * - * @param t1 - * the Tuple3f containing the initialization x y z data - */ - public Vector3d(Tuple3f t1) { - super(t1); - } - - - /** - * Constructs and initializes a Vector3d from the specified Tuple3d. - * - * @param t1 - * the Tuple3d containing the initialization x y z data - */ - public Vector3d(Tuple3d t1) { - super(t1); - } - - - /** - * Constructs and initializes a Vector3d to (0,0,0). - */ - public Vector3d() { - super(); - } - - - /** - * Sets this vector to the vector cross product of vectors v1 and v2. - * - * @param v1 - * the first vector - * @param v2 - * the second vector - */ - public final void cross(Vector3d v1, Vector3d v2) { - double x, y; - - x = v1.y * v2.z - v1.z * v2.y; - y = v2.x * v1.z - v2.z * v1.x; - this.z = v1.x * v2.y - v1.y * v2.x; - this.x = x; - this.y = y; - } - - - /** - * Sets the value of this vector to the normalization of vector v1. - * - * @param v1 - * the un-normalized vector - */ - public final void normalize(Vector3d v1) { - double norm; - - norm = 1.0 / Math.sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z); - this.x = v1.x * norm; - this.y = v1.y * norm; - this.z = v1.z * norm; - } - - - /** - * Normalizes this vector in place. - */ - public final void normalize() { - double norm; - - norm = 1.0 / Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); - this.x *= norm; - this.y *= norm; - this.z *= norm; - } - - - /** - * Returns the dot product of this vector and vector v1. - * - * @param v1 - * the other vector - * @return the dot product of this and v1 - */ - public final double dot(Vector3d v1) { - return (this.x * v1.x + this.y * v1.y + this.z * v1.z); - } - - - /** - * Returns the squared length of this vector. - * - * @return the squared length of this vector - */ - public final double lengthSquared() { - return (this.x * this.x + this.y * this.y + this.z * this.z); - } - - - /** - * Returns the length of this vector. - * - * @return the length of this vector - */ - public final double length() { - return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); - } - - - /** - * Returns the angle in radians between this vector and the vector - * parameter; the return value is constrained to the range [0,PI]. - * - * @param v1 - * the other vector - * @return the angle in radians in the range [0,PI] - */ - public final double angle(Vector3d v1) { - double vDot = this.dot(v1) / (this.length() * v1.length()); - if(vDot < -1.0) vDot = -1.0; - if(vDot > 1.0) vDot = 1.0; - return Math.acos(vDot); - } - - -} diff --git a/src/main/java/com/volmit/iris/util/math/Vector3f.java b/src/main/java/com/volmit/iris/util/math/Vector3f.java deleted file mode 100644 index 0bd55fb10..000000000 --- a/src/main/java/com/volmit/iris/util/math/Vector3f.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -/** - * A 3-element vector that is represented by single-precision floating point - * x,y,z coordinates. If this value represents a normal, then it should - * be normalized. - */ -public class Vector3f extends Tuple3f implements java.io.Serializable { - - // Combatible with 1.1 - static final long serialVersionUID = -7031930069184524614L; - - /** - * Constructs and initializes a Vector3f from the specified xyz coordinates. - * - * @param x - * the x coordinate - * @param y - * the y coordinate - * @param z - * the z coordinate - */ - public Vector3f(float x, float y, float z) { - super(x, y, z); - } - - - /** - * Constructs and initializes a Vector3f from the array of length 3. - * - * @param v - * the array of length 3 containing xyz in order - */ - public Vector3f(float[] v) { - super(v); - } - - - /** - * Constructs and initializes a Vector3f from the specified Vector3f. - * - * @param v1 - * the Vector3f containing the initialization x y z data - */ - public Vector3f(Vector3f v1) { - super(v1); - } - - - /** - * Constructs and initializes a Vector3f from the specified Vector3d. - * - * @param v1 - * the Vector3d containing the initialization x y z data - */ - public Vector3f(Vector3d v1) { - super(v1); - } - - - /** - * Constructs and initializes a Vector3f from the specified Tuple3f. - * - * @param t1 - * the Tuple3f containing the initialization x y z data - */ - public Vector3f(Tuple3f t1) { - super(t1); - } - - - /** - * Constructs and initializes a Vector3f from the specified Tuple3d. - * - * @param t1 - * the Tuple3d containing the initialization x y z data - */ - public Vector3f(Tuple3d t1) { - super(t1); - } - - - /** - * Constructs and initializes a Vector3f to (0,0,0). - */ - public Vector3f() { - super(); - } - - - /** - * Returns the squared length of this vector. - * - * @return the squared length of this vector - */ - public final float lengthSquared() { - return (this.x * this.x + this.y * this.y + this.z * this.z); - } - - /** - * Returns the length of this vector. - * - * @return the length of this vector - */ - public final float length() { - return (float) - Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); - } - - - /** - * Sets this vector to be the vector cross product of vectors v1 and v2. - * - * @param v1 - * the first vector - * @param v2 - * the second vector - */ - public final void cross(Vector3f v1, Vector3f v2) { - float x, y; - - x = v1.y * v2.z - v1.z * v2.y; - y = v2.x * v1.z - v2.z * v1.x; - this.z = v1.x * v2.y - v1.y * v2.x; - this.x = x; - this.y = y; - } - - /** - * Computes the dot product of this vector and vector v1. - * - * @param v1 - * the other vector - * @return the dot product of this vector and v1 - */ - public final float dot(Vector3f v1) { - return (this.x * v1.x + this.y * v1.y + this.z * v1.z); - } - - /** - * Sets the value of this vector to the normalization of vector v1. - * - * @param v1 - * the un-normalized vector - */ - public final void normalize(Vector3f v1) { - float norm; - - norm = (float) (1.0 / Math.sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z)); - this.x = v1.x * norm; - this.y = v1.y * norm; - this.z = v1.z * norm; - } - - /** - * Normalizes this vector in place. - */ - public final void normalize() { - float norm; - - norm = (float) - (1.0 / Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z)); - this.x *= norm; - this.y *= norm; - this.z *= norm; - } - - - /** - * Returns the angle in radians between this vector and the vector - * parameter; the return value is constrained to the range [0,PI]. - * - * @param v1 - * the other vector - * @return the angle in radians in the range [0,PI] - */ - public final float angle(Vector3f v1) { - double vDot = this.dot(v1) / (this.length() * v1.length()); - if(vDot < -1.0) vDot = -1.0; - if(vDot > 1.0) vDot = 1.0; - return ((float) (Math.acos(vDot))); - } - -} diff --git a/src/main/java/com/volmit/iris/util/math/VectorMath.java b/src/main/java/com/volmit/iris/util/math/VectorMath.java deleted file mode 100644 index ec6de00ce..000000000 --- a/src/main/java/com/volmit/iris/util/math/VectorMath.java +++ /dev/null @@ -1,641 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.math; - -import com.volmit.iris.util.collection.GListAdapter; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.format.Form; -import org.bukkit.Axis; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Entity; -import org.bukkit.util.Vector; - -/** - * Vector utilities - * - * @author cyberpwn - */ -public class VectorMath { - public static Vector scaleStatic(Axis x, Vector v, double amt) { - return switch(x) { - case X -> scaleX(v, amt); - case Y -> scaleY(v, amt); - case Z -> scaleZ(v, amt); - }; - - } - - public static Vector scaleX(Vector v, double amt) { - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); - double rx = x == 0 ? 1 : amt / x; - - return new Vector(x * rx, y * rx, z * rx); - } - - public static Vector scaleY(Vector v, double amt) { - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); - double rx = y == 0 ? 1 : amt / y; - - return new Vector(x * rx, y * rx, z * rx); - } - - public static Vector scaleZ(Vector v, double amt) { - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); - double rx = z == 0 ? 1 : amt / z; - - return new Vector(x * rx, y * rx, z * rx); - } - - public static Vector reverseXZ(Vector v) { - v.setX(-v.getX()); - v.setZ(-v.getZ()); - return v; - } - - public static boolean isLookingNear(Location a, Location b, double maxOff) { - Vector perfect = VectorMath.direction(a, b); - Vector actual = a.getDirection(); - - return perfect.distance(actual) <= maxOff; - } - - public static Vector rotate(Direction current, Direction to, Vector v) { - if(current.equals(to)) { - return v; - } else if(current.equals(to.reverse())) { - if(current.isVertical()) { - return new Vector(v.getX(), -v.getY(), v.getZ()); - } else { - return new Vector(-v.getX(), v.getY(), -v.getZ()); - } - } else { - Vector c = current.toVector().clone().add(to.toVector()); - - if(c.getX() == 0) { - if(c.getY() != c.getZ()) { - return rotate90CX(v); - } - - return rotate90CCX(v); - } else if(c.getY() == 0) { - if(c.getX() != c.getZ()) { - return rotate90CY(v); - } - - return rotate90CCY(v); - } else if(c.getZ() == 0) { - if(c.getX() != c.getY()) { - return rotate90CZ(v); - } - - return rotate90CCZ(v); - } - } - - return v; - } - - // Y X 0 0 - // X Z 0 0 - - // 0 X Y 0 - // 0 Z X 0 - - public static Vector rotate(Direction current, Direction to, Vector v, int w, int h, int d) { - if(current.equals(to)) { - return v; - } else if(current.equals(to.reverse())) { - if(current.isVertical()) { - return new Vector(v.getX(), -v.getY() + h, v.getZ()); - } else { - return new Vector(-v.getX() + w, v.getY(), -v.getZ() + d); - } - } else { - Vector c = current.toVector().clone().add(to.toVector()); - - if(c.getX() == 0) { - if(c.getY() != c.getZ()) { - return rotate90CX(v, d); - } - - return rotate90CCX(v, h); - } else if(c.getY() == 0) { - if(c.getX() != c.getZ()) { - return rotate90CY(v, d); - } - - return rotate90CCY(v, w); - } else if(c.getZ() == 0) { - if(c.getX() != c.getY()) { - return rotate90CZ(v, w); - } - - return rotate90CCZ(v, h); - } - } - - return v; - } - - public static Vector rotate90CX(Vector v) { - return new Vector(v.getX(), -v.getZ(), v.getY()); - } - - public static Vector rotate90CCX(Vector v) { - return new Vector(v.getX(), v.getZ(), -v.getY()); - } - - public static Vector rotate90CY(Vector v) { - return new Vector(-v.getZ(), v.getY(), v.getX()); - } - - public static Vector rotate90CCY(Vector v) { - return new Vector(v.getZ(), v.getY(), -v.getX()); - } - - public static Vector rotate90CZ(Vector v) { - return new Vector(v.getY(), -v.getX(), v.getZ()); - } - - public static Vector rotate90CCZ(Vector v) { - return new Vector(-v.getY(), v.getX(), v.getZ()); - } - - public static Vector rotate90CX(Vector v, int s) { - return new Vector(v.getX(), -v.getZ() + s, v.getY()); - } - - public static Vector rotate90CCX(Vector v, int s) { - return new Vector(v.getX(), v.getZ(), -v.getY() + s); - } - - public static Vector rotate90CY(Vector v, int s) { - return new Vector(-v.getZ() + s, v.getY(), v.getX()); - } - - public static Vector rotate90CCY(Vector v, int s) { - return new Vector(v.getZ(), v.getY(), -v.getX() + s); - } - - public static Vector rotate90CZ(Vector v, int s) { - return new Vector(v.getY(), -v.getX() + s, v.getZ()); - } - - public static Vector rotate90CCZ(Vector v, int s) { - return new Vector(-v.getY() + s, v.getX(), v.getZ()); - } - - public static Vector getAxis(Direction current, Direction to) { - if(current.equals(Direction.U) || current.equals(Direction.D)) { - if(to.equals(Direction.U) || to.equals(Direction.D)) { - return new Vector(1, 0, 0); - } else { - if(current.equals(Direction.N) || current.equals(Direction.S)) { - return Direction.E.toVector(); - } else { - return Direction.S.toVector(); - } - } - } - - return new Vector(0, 1, 0); - } - - private static double round(double value, int precision) { - return Double.parseDouble(Form.f(value, precision)); - } - - public static Vector clip(Vector v, int decimals) { - v.setX(round(v.getX(), decimals)); - v.setY(round(v.getY(), decimals)); - v.setZ(round(v.getZ(), decimals)); - return v; - } - - public static Vector rotateVectorCC(Vector vec, Vector axis, double deg) { - double theta = Math.toRadians(deg); - double x, y, z; - double u, v, w; - x = vec.getX(); - y = vec.getY(); - z = vec.getZ(); - u = axis.getX(); - v = axis.getY(); - w = axis.getZ(); - double f = u * x + v * y + w * z; - double xPrime = u * (f) * (1d - Math.cos(theta)) + x * Math.cos(theta) + (-w * y + v * z) * Math.sin(theta); - double yPrime = v * (f) * (1d - Math.cos(theta)) + y * Math.cos(theta) + (w * x - u * z) * Math.sin(theta); - double zPrime = w * (f) * (1d - Math.cos(theta)) + z * Math.cos(theta) + (-v * x + u * y) * Math.sin(theta); - - return clip(new Vector(xPrime, yPrime, zPrime), 4); - } - - /** - * Get all SIMPLE block faces from a more specific block face (SOUTH_EAST) = - * (south, east) - * - * @param f - * the block face - * @return multiple faces, or one if the face is already simple - */ - public static KList split(BlockFace f) { - KList faces = new KList<>(); - - switch(f) { - case DOWN: - faces.add(BlockFace.DOWN); - break; - case EAST: - faces.add(BlockFace.EAST); - break; - case EAST_NORTH_EAST: - faces.add(BlockFace.EAST); - faces.add(BlockFace.EAST); - faces.add(BlockFace.NORTH); - break; - case EAST_SOUTH_EAST: - faces.add(BlockFace.EAST); - faces.add(BlockFace.EAST); - faces.add(BlockFace.SOUTH); - break; - case NORTH: - faces.add(BlockFace.NORTH); - break; - case NORTH_EAST: - faces.add(BlockFace.NORTH); - faces.add(BlockFace.EAST); - break; - case NORTH_NORTH_EAST: - faces.add(BlockFace.NORTH); - faces.add(BlockFace.NORTH); - faces.add(BlockFace.EAST); - break; - case NORTH_NORTH_WEST: - faces.add(BlockFace.NORTH); - faces.add(BlockFace.NORTH); - faces.add(BlockFace.WEST); - break; - case NORTH_WEST: - faces.add(BlockFace.NORTH); - faces.add(BlockFace.WEST); - break; - case SELF: - faces.add(BlockFace.SELF); - break; - case SOUTH: - faces.add(BlockFace.SOUTH); - break; - case SOUTH_EAST: - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.EAST); - break; - case SOUTH_SOUTH_EAST: - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.EAST); - break; - case SOUTH_SOUTH_WEST: - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.WEST); - break; - case SOUTH_WEST: - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.WEST); - break; - case UP: - faces.add(BlockFace.UP); - break; - case WEST: - faces.add(BlockFace.WEST); - break; - case WEST_NORTH_WEST: - faces.add(BlockFace.WEST); - faces.add(BlockFace.WEST); - faces.add(BlockFace.NORTH); - break; - case WEST_SOUTH_WEST: - faces.add(BlockFace.WEST); - faces.add(BlockFace.WEST); - faces.add(BlockFace.SOUTH); - break; - default: - break; - } - - return faces; - } - - /** - * Get a normalized vector going from a location to another - * - * @param from - * from here - * @param to - * to here - * @return the normalized vector direction - */ - public static Vector direction(Location from, Location to) { - return to.clone().subtract(from.clone()).toVector().normalize(); - } - - public static Vector directionNoNormal(Location from, Location to) { - return to.clone().subtract(from.clone()).toVector(); - } - - /** - * Get the vector direction from the yaw and pitch - * - * @param yaw - * the yaw - * @param pitch - * the pitch - * @return the vector - */ - public static Vector toVector(float yaw, float pitch) { - return new Vector(Math.cos(pitch) * Math.cos(yaw), Math.sin(pitch), Math.cos(pitch) * Math.sin(-yaw)); - } - - /** - * Add an impulse (force) to an entity - * - * @param e - * the entity - * @param v - * the vector - */ - public static void impulse(Entity e, Vector v) { - impulse(e, v, 1.0); - } - - /** - * Add an impulse (force) on an entity - * - * @param e - * the entity - * @param v - * the vector - * @param effectiveness - * the effectiveness - */ - public static void impulse(Entity e, Vector v, double effectiveness) { - Vector vx = e.getVelocity(); - vx.add(v.clone().multiply(effectiveness)); - e.setVelocity(vx); - } - - /** - * Reverse a direction - * - * @param v - * the direction - * @return the reversed direction - */ - public static Vector reverse(Vector v) { - if(v.getX() != 0) { - v.setX(-v.getX()); - } - - if(v.getY() != 0) { - v.setY(-v.getY()); - } - - if(v.getZ() != 0) { - v.setZ(-v.getZ()); - } - - return v; - } - - /** - * Get a speed value from a vector (velocity) - * - * @param v - * the vector - * @return the speed - */ - public static double getSpeed(Vector v) { - Vector vi = new Vector(0, 0, 0); - Vector vt = new Vector(0, 0, 0).add(v); - - return vi.distance(vt); - } - - /** - * Shift all vectors based on the given vector - * - * @param vector - * the vector direction to shift the vectors - * @param vectors - * the vectors to be shifted - * @return the shifted vectors - */ - public static KList shift(Vector vector, KList vectors) { - return new KList<>(new GListAdapter() { - @Override - public Vector onAdapt(Vector from) { - return from.add(vector); - } - }.adapt(vectors)); - } - - /** - * Attempt to get the blockFace for the vector (will be tri-normalized) - * - * @param v - * the vector - * @return the block face or null - */ - public static BlockFace getBlockFace(Vector v) { - Vector p = triNormalize(v); - - for(BlockFace i : BlockFace.values()) { - if(p.getX() == i.getModX() && p.getY() == i.getModY() && p.getZ() == i.getModZ()) { - return i; - } - } - - for(BlockFace i : BlockFace.values()) { - if(p.getX() == i.getModX() && p.getZ() == i.getModZ()) { - return i; - } - } - - for(BlockFace i : BlockFace.values()) { - if(p.getY() == i.getModY() && p.getZ() == i.getModZ()) { - return i; - } - } - - for(BlockFace i : BlockFace.values()) { - if(p.getX() == i.getModX() || p.getY() == i.getModY()) { - return i; - } - } - - for(BlockFace i : BlockFace.values()) { - if(p.getX() == i.getModX() || p.getY() == i.getModY() || p.getZ() == i.getModZ()) { - return i; - } - } - - return null; - } - - /** - * Angle the vector in a self relative direction - * - * @param v - * the initial direction - * @param amt - * the amount to shift in the direction - * @return the shifted direction - */ - public static Vector angleLeft(Vector v, float amt) { - Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); - l.setDirection(v); - float y = l.getYaw(); - float p = l.getPitch(); - CDou cy = new CDou(360); - CDou cp = new CDou(180); - cy.set(y); - cp.set(p); - cy.sub(amt); - l.setYaw((float) cy.get()); - l.setPitch((float) cp.get()); - - return l.getDirection(); - } - - /** - * Angle the vector in a self relative direction - * - * @param v - * the initial direction - * @param amt - * the amount to shift in the direction - * @return the shifted direction - */ - public static Vector angleRight(Vector v, float amt) { - Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); - l.setDirection(v); - float y = l.getYaw(); - float p = l.getPitch(); - CDou cy = new CDou(360); - CDou cp = new CDou(180); - cy.set(y); - cp.set(p); - cy.add(amt); - l.setYaw((float) cy.get()); - l.setPitch((float) cp.get()); - - return l.getDirection(); - } - - /** - * Angle the vector in a self relative direction - * - * @param v - * the initial direction - * @param amt - * the amount to shift in the direction - * @return the shifted direction - */ - public static Vector angleUp(Vector v, float amt) { - Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); - l.setDirection(v); - float y = l.getYaw(); - float p = l.getPitch(); - CDou cy = new CDou(360); - cy.set(y); - l.setYaw((float) cy.get()); - l.setPitch(Math.max(-90, p - amt)); - - return l.getDirection(); - } - - /** - * Angle the vector in a self relative direction - * - * @param v - * the initial direction - * @param amt - * the amount to shift in the direction - * @return the shifted direction - */ - public static Vector angleDown(Vector v, float amt) { - Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); - l.setDirection(v); - float y = l.getYaw(); - float p = l.getPitch(); - CDou cy = new CDou(360); - cy.set(y); - l.setYaw((float) cy.get()); - l.setPitch(Math.min(90, p + amt)); - - return l.getDirection(); - } - - /** - * (clone) Force normalize the vector into three points, 1, 0, or -1. If the - * value is > 0.333 (1) if the value is less than -0.333 (-1) else 0 - * - * @param direction - * the direction - * @return the vector - */ - public static Vector triNormalize(Vector direction) { - Vector v = direction.clone(); - v.normalize(); - - if(v.getX() > 0.333) { - v.setX(1); - } else if(v.getX() < -0.333) { - v.setX(-1); - } else { - v.setX(0); - } - - if(v.getY() > 0.333) { - v.setY(1); - } else if(v.getY() < -0.333) { - v.setY(-1); - } else { - v.setY(0); - } - - if(v.getZ() > 0.333) { - v.setZ(1); - } else if(v.getZ() < -0.333) { - v.setZ(-1); - } else { - v.setZ(0); - } - - return v; - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/IrisMatter.java b/src/main/java/com/volmit/iris/util/matter/IrisMatter.java deleted file mode 100644 index f5fac9bda..000000000 --- a/src/main/java/com/volmit/iris/util/matter/IrisMatter.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.json.JSONObject; -import com.volmit.iris.util.plugin.VolmitSender; -import lombok.Getter; - -public class IrisMatter extends IrisRegistrant implements Matter { - protected static final KMap, MatterSlice> slicers = buildSlicers(); - - @Getter - private final MatterHeader header; - - @Getter - private final int width; - - @Getter - private final int height; - - @Getter - private final int depth; - - @Getter - private final KMap, MatterSlice> sliceMap; - - public IrisMatter(int width, int height, int depth) { - if(width < 1 || height < 1 || depth < 1) { - throw new RuntimeException("Invalid Matter Size " + width + "x" + height + "x" + depth); - } - - this.width = width; - this.height = height; - this.depth = depth; - this.header = new MatterHeader(); - this.sliceMap = new KMap<>(); - } - - private static KMap, MatterSlice> buildSlicers() { - KMap, MatterSlice> c = new KMap<>(); - for(Object i : Iris.initialize("com.volmit.iris.util.matter.slices", Sliced.class)) { - MatterSlice s = (MatterSlice) i; - c.put(s.getType(), s); - } - - return c; - } - - @Override - public MatterSlice createSlice(Class type, Matter m) { - MatterSlice slice = slicers.get(type); - - if(slice == null) { - return null; - } - - try { - return slice.getClass().getConstructor(int.class, int.class, int.class).newInstance(getWidth(), getHeight(), getDepth()); - } catch(Throwable e) { - e.printStackTrace(); - } - - return null; - } - - @Override - public String getFolderName() { - return "matter"; - } - - @Override - public String getTypeName() { - return "matter"; - } - - @Override - public void scanForErrors(JSONObject p, VolmitSender sender) { - - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/Matter.java b/src/main/java/com/volmit/iris/util/matter/Matter.java deleted file mode 100644 index d9b2a65fd..000000000 --- a/src/main/java/com/volmit/iris/util/matter/Matter.java +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.IrisObject; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Entity; -import org.bukkit.util.BlockVector; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; - -/** - * When Red Matter isn't enough - *

- * UVI width - * UVI height - * UVI depth - * UVI sliceCount - * UTF author - * UVL createdAt - * UVI version - * UTF sliceType (canonical class name) - * UVI nodeCount (for each slice) - * UVI position [(z * w * h) + (y * w) + x] - * ??? nodeData - */ -public interface Matter { - int VERSION = 1; - - static long convert(File folder) - { - if(folder.isDirectory()) - { - long v = 0; - - for(File i : folder.listFiles()) - { - v += convert(i); - } - - return v; - } - - else - { - IrisObject object = new IrisObject(1,1,1); - try { - long fs = folder.length(); - object.read(folder); - Matter.from(object).write(folder); - Iris.info("Converted " + folder.getPath() + " Saved " + (fs - folder.length())); - } catch(Throwable e) { - Iris.error("Failed to convert " + folder.getPath()); - e.printStackTrace(); - } - } - - return 0; - } - - static Matter from(IrisObject object) { - object.clean(); - object.shrinkwrap(); - BlockVector min = new BlockVector(); - Matter m = new IrisMatter(Math.max(object.getW(), 1)+1, Math.max( object.getH(), 1)+1, Math.max( object.getD(), 1)+1); - - for(BlockVector i : object.getBlocks().keySet()) { - min.setX(Math.min(min.getX(), i.getX())); - min.setY(Math.min(min.getY(), i.getY())); - min.setZ(Math.min(min.getZ(), i.getZ())); - } - - for(BlockVector i : object.getBlocks().keySet()) { - m.slice(BlockData.class).set(i.getBlockX() - min.getBlockX(), i.getBlockY() - min.getBlockY(), i.getBlockZ() - min.getBlockZ(), object.getBlocks().get(i)); - } - - return m; - } - - static Matter read(File f) throws IOException, ClassNotFoundException { - FileInputStream in = new FileInputStream(f); - Matter m = read(in); - in.close(); - return m; - } - - default Matter copy() { - Matter m = new IrisMatter(getWidth(), getHeight(), getDepth()); - getSliceMap().forEach((k, v) -> m.slice(k).forceInject(v)); - return m; - } - - static Matter read(InputStream in) throws IOException, ClassNotFoundException { - return read(in, (b) -> new IrisMatter(b.getX(), b.getY(), b.getZ())); - } - - static Matter readDin(DataInputStream in) throws IOException, ClassNotFoundException { - return readDin(in, (b) -> new IrisMatter(b.getX(), b.getY(), b.getZ())); - } - - /** - * Reads the input stream into a matter object using a matter factory. - * Does not close the input stream. Be a man, close it yourself. - * - * @param in - * the input stream - * @param matterFactory - * the matter factory (size) -> new MatterImpl(size); - * @return the matter object - * @throws IOException - * shit happens yo - */ - static Matter read(InputStream in, Function matterFactory) throws IOException, ClassNotFoundException { - return readDin(new DataInputStream(in), matterFactory); - } - - static Matter readDin(DataInputStream din, Function matterFactory) throws IOException, ClassNotFoundException { - Matter matter = matterFactory.apply(new BlockPosition( - din.readInt(), - din.readInt(), - din.readInt())); - Iris.addPanic("read.matter.size", matter.getWidth() + "x" + matter.getHeight() + "x" + matter.getDepth()); - int sliceCount = din.readByte(); - Iris.addPanic("read.matter.slicecount", sliceCount + ""); - - matter.getHeader().read(din); - Iris.addPanic("read.matter.header", matter.getHeader().toString()); - - for(int i = 0; i < sliceCount; i++) { - Iris.addPanic("read.matter.slice", i + ""); - String cn = din.readUTF(); - Iris.addPanic("read.matter.slice.class", cn); - try { - Class type = Class.forName(cn); - MatterSlice slice = matter.createSlice(type, matter); - slice.read(din); - matter.putSlice(type, slice); - } catch(Throwable e) { - e.printStackTrace(); - throw new IOException("Can't read class '" + cn + "' (slice count reverse at " + sliceCount + ")"); - } - } - - return matter; - } - - /** - * Get the header information - * - * @return the header info - */ - MatterHeader getHeader(); - - /** - * Get the width of this matter - * - * @return the width - */ - int getWidth(); - - /** - * Get the height of this matter - * - * @return the height - */ - int getHeight(); - - /** - * Get the depth of this matter - * - * @return the depth - */ - int getDepth(); - - /** - * Get the center of this matter - * - * @return the center - */ - default BlockPosition getCenter() { - return new BlockPosition(getCenterX(), getCenterY(), getCenterZ()); - } - - /** - * Create a slice from the given type (full is false) - * - * @param type - * the type class - * @param matter - * the matter this slice will go into (size provider) - * @param - * the type - * @return the slice (or null if not supported) - */ - MatterSlice createSlice(Class type, Matter matter); - - /** - * Get the size of this matter - * - * @return the size - */ - default BlockPosition getSize() { - return new BlockPosition(getWidth(), getHeight(), getDepth()); - } - - /** - * Get the center X of this matter - * - * @return the center X - */ - default int getCenterX() { - return (int) Math.round(getWidth() / 2D); - } - - /** - * Get the center Y of this matter - * - * @return the center Y - */ - default int getCenterY() { - return (int) Math.round(getHeight() / 2D); - } - - /** - * Get the center Z of this matter - * - * @return the center Z - */ - default int getCenterZ() { - return (int) Math.round(getDepth() / 2D); - } - - /** - * Return the slice for the given type - * - * @param t - * the type class - * @param - * the type - * @return the slice or null - */ - default MatterSlice getSlice(Class t) { - return (MatterSlice) getSliceMap().get(t); - } - - /** - * Delete the slice for the given type - * - * @param c - * the type class - * @param - * the type - * @return the deleted slice, or null if it diddn't exist - */ - default MatterSlice deleteSlice(Class c) { - return (MatterSlice) getSliceMap().remove(c); - } - - /** - * Put a given slice type - * - * @param c - * the slice type class - * @param slice - * the slice to assign to the type - * @param - * the slice type - * @return the overwritten slice if there was an existing slice of that type - */ - default MatterSlice putSlice(Class c, MatterSlice slice) { - return (MatterSlice) getSliceMap().put(c, slice); - } - - default Class getClass(Object w) { - Class c = w.getClass(); - - if(w instanceof World) { - c = World.class; - } else if(w instanceof BlockData) { - c = BlockData.class; - } else if(w instanceof Entity) { - c = Entity.class; - } - - return c; - } - - default MatterSlice slice(Class c) { - MatterSlice slice = (MatterSlice) getSlice(c); - if(slice == null) { - slice = (MatterSlice) createSlice(c, this); - - if(slice == null) { - try { - throw new RuntimeException("Bad slice " + c.getCanonicalName()); - } catch(Throwable e) { - e.printStackTrace(); - } - - return null; - } - - putSlice(c, slice); - } - - return slice; - } - - /** - * Rotate a matter object into a new object - * - * @param x - * the x rotation (degrees) - * @param y - * the y rotation (degrees) - * @param z - * the z rotation (degrees) - * @return the new rotated matter object - */ - default Matter rotate(double x, double y, double z) { - IrisPosition rs = Hunk.rotatedBounding(getWidth(), getHeight(), getDepth(), x, y, z); - Matter n = new IrisMatter(rs.getX(), rs.getY(), rs.getZ()); - n.getHeader().setAuthor(getHeader().getAuthor()); - n.getHeader().setCreatedAt(getHeader().getCreatedAt()); - - for(Class i : getSliceTypes()) { - getSlice(i).rotateSliceInto(n, x, y, z); - } - - return n; - } - - /** - * Check if a slice exists for a given type - * - * @param c - * the slice class type - * @return true if it exists - */ - default boolean hasSlice(Class c) { - return getSlice(c) != null; - } - - /** - * Remove all slices - */ - default void clearSlices() { - getSliceMap().clear(); - } - - /** - * Get the set backing the slice map keys (slice types) - * - * @return the slice types - */ - default Set> getSliceTypes() { - return getSliceMap().keySet(); - } - - /** - * Get all slices - * - * @return the real slice map - */ - Map, MatterSlice> getSliceMap(); - - default void write(File f) throws IOException { - OutputStream out = new FileOutputStream(f); - write(out); - out.close(); - } - - /** - * Remove any slices that are empty - */ - default void trimSlices() { - Set> drop = null; - - for(Class i : getSliceTypes()) { - if(getSlice(i).getEntryCount() == 0) { - if(drop == null) { - drop = new KSet<>(); - } - - drop.add(i); - } - } - - if(drop != null) { - for(Class i : drop) { - deleteSlice(i); - } - } - } - - /** - * Writes the data to the output stream. The data will be flushed to the provided output - * stream however the provided stream will NOT BE CLOSED, so be sure to actually close it - * - * @param out - * the output stream - * @throws IOException - * shit happens yo - */ - default void write(OutputStream out) throws IOException { - writeDos(new DataOutputStream(out)); - } - - default void writeDos(DataOutputStream dos) throws IOException { - trimSlices(); - dos.writeInt(getWidth()); - dos.writeInt(getHeight()); - dos.writeInt(getDepth()); - dos.writeByte(getSliceTypes().size()); - getHeader().write(dos); - - for(Class i : getSliceTypes()) { - getSlice(i).write(dos); - } - } - - default int getTotalCount() { - int m = 0; - - for(MatterSlice i : getSliceMap().values()) { - m += i.getEntryCount(); - } - - return m; - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterCavern.java b/src/main/java/com/volmit/iris/util/matter/MatterCavern.java deleted file mode 100644 index fc86d2cf9..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterCavern.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class MatterCavern { - private final boolean cavern; - private final String customBiome; - private final byte liquid; // 0 none 1 water 2 lava - - public boolean isAir() { - return liquid == 0; - } - - public boolean isWater() { - return liquid == 1; - } - - public boolean isLava() { - return liquid == 2; - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterEntity.java b/src/main/java/com/volmit/iris/util/matter/MatterEntity.java deleted file mode 100644 index 52fb3958a..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterEntity.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.util.nbt.tag.CompoundTag; -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class MatterEntity { - private final double xOff; - private final double yOff; - private final double zOff; - private final CompoundTag entityData; -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterEntityGroup.java b/src/main/java/com/volmit/iris/util/matter/MatterEntityGroup.java deleted file mode 100644 index c04ec7166..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterEntityGroup.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.util.collection.KList; -import lombok.Data; - -@Data -public class MatterEntityGroup { - private final KList entities = new KList<>(); -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterFilter.java b/src/main/java/com/volmit/iris/util/matter/MatterFilter.java deleted file mode 100644 index 3f4dac01e..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterFilter.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -@FunctionalInterface -public interface MatterFilter { - T update(int x, int y, int z, T t); -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterFluidBody.java b/src/main/java/com/volmit/iris/util/matter/MatterFluidBody.java deleted file mode 100644 index 116b4e8da..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterFluidBody.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class MatterFluidBody { - private final boolean body; - private final String customBiome; - private final boolean lava; -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterHeader.java b/src/main/java/com/volmit/iris/util/matter/MatterHeader.java deleted file mode 100644 index 73fc78d16..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterHeader.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.util.math.M; -import lombok.Data; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Data -public class MatterHeader { - private String author = ""; - private long createdAt = M.ms(); - private int version = Matter.VERSION; - - public void write(DataOutputStream out) throws IOException { - out.writeUTF(author); - out.writeLong(createdAt); - out.writeShort(version); - } - - public void read(DataInputStream din) throws IOException { - setAuthor(din.readUTF()); - setCreatedAt(din.readLong()); - setVersion(din.readShort()); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterMarker.java b/src/main/java/com/volmit/iris/util/matter/MatterMarker.java deleted file mode 100644 index dab5ff6ac..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterMarker.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class MatterMarker { - private final String tag; -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/matter/MatterPalette.java b/src/main/java/com/volmit/iris/util/matter/MatterPalette.java deleted file mode 100644 index a06e636d1..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterPalette.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.util.data.DataPalette; -import com.volmit.iris.util.data.IOAdapter; -import com.volmit.iris.util.data.Varint; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class MatterPalette implements IOAdapter { - private final MatterSlice slice; - private final DataPalette palette; - - public MatterPalette(MatterSlice slice) { - this.slice = slice; - palette = new DataPalette(); - } - - public MatterPalette(MatterSlice slice, DataInputStream din) throws IOException { - this.slice = slice; - palette = DataPalette.getPalette(this, din); - } - - public void writeNode(T t, DataOutputStream dos) throws IOException { - Varint.writeUnsignedVarInt(palette.getIndex(t), dos); - } - - public T readNode(DataInputStream din) throws IOException { - return palette.get(Varint.readUnsignedVarInt(din)); - } - - public void writePalette(DataOutputStream dos) throws IOException { - palette.write(this, dos); - } - - @Override - public void write(T t, DataOutputStream dos) throws IOException { - slice.writeNode(t, dos); - } - - @Override - public T read(DataInputStream din) throws IOException { - return slice.readNode(din); - } - - public void assign(T b) { - palette.getIndex(b); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterPlacer.java b/src/main/java/com/volmit/iris/util/matter/MatterPlacer.java deleted file mode 100644 index 808a3ad9b..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterPlacer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.util.mantle.Mantle; - -public interface MatterPlacer { - int getHeight(int x, int z, boolean ignoreFluid); - - Mantle getMantle(); - - default void set(int x, int y, int z, T t) { - getMantle().set(x, y, z, t); - } - - default T get(int x, int y, int z, Class t) { - return getMantle().get(x, y, z, t); - } - - default void set(int x, int y, int z, Matter matter) { - for(MatterSlice i : matter.getSliceMap().values()) { - set(x, y, z, i); - } - } - - default void set(int x, int y, int z, MatterSlice slice) { - getMantle().set(x, y, z, slice); - } - - default int getHeight(int x, int z) { - return getHeight(x, z, true); - } - - default int getHeightOrFluid(int x, int z) { - return getHeight(x, z, false); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterReader.java b/src/main/java/com/volmit/iris/util/matter/MatterReader.java deleted file mode 100644 index 4d0b6516c..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterReader.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -@FunctionalInterface -public interface MatterReader { - T readMatter(W w, int x, int y, int z); -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterSlice.java b/src/main/java/com/volmit/iris/util/matter/MatterSlice.java deleted file mode 100644 index f3d416db0..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterSlice.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.util.data.Varint; -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.data.palette.PaletteType; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.hunk.bits.DataContainer; -import com.volmit.iris.util.hunk.bits.Writable; -import com.volmit.iris.util.hunk.storage.PaletteOrHunk; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Entity; -import org.bukkit.util.BlockVector; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public interface MatterSlice extends Hunk, PaletteType, Writable { - Class getType(); - - Palette getGlobalPalette(); - - @Override - default void writePaletteNode(DataOutputStream dos, T s) throws IOException { - writeNode(s, dos); - } - - @Override - default void writeNodeData(DataOutputStream dos, T s) throws IOException { - writeNode(s, dos); - } - - @Override - default T readPaletteNode(DataInputStream din) throws IOException { - return readNode(din); - } - - @Override - default T readNodeData(DataInputStream din) throws IOException { - return readNode(din); - } - - default void applyFilter(MatterFilter filter) { - updateSync(filter::update); - } - - default void inject(MatterSlice slice) { - iterateSync(slice::set); - } - - default void forceInject(MatterSlice slice) { - inject((MatterSlice) slice); - } - - void writeNode(T b, DataOutputStream dos) throws IOException; - - T readNode(DataInputStream din) throws IOException; - - MatterWriter writeInto(Class mediumType); - - MatterReader readFrom(Class mediumType); - - default Class getClass(Object w) { - Class c = w.getClass(); - - if(w instanceof World) { - c = World.class; - } else if(w instanceof BlockData) { - c = BlockData.class; - } else if(w instanceof Entity) { - c = Entity.class; - } - - return c; - } - - default boolean writeInto(Location location) { - return writeInto(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - - default boolean writeInto(W w, int x, int y, int z) { - MatterWriter injector = (MatterWriter) writeInto(getClass(w)); - - if(injector == null) { - return false; - } - - iterateSync((a, b, c, t) -> injector.writeMatter(w, t, a + x, b + y, c + z)); - - return true; - } - - default boolean readFrom(Location location) { - return readFrom(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - - default boolean readFrom(W w, int x, int y, int z) { - MatterReader ejector = (MatterReader) readFrom(getClass(w)); - - if(ejector == null) { - return false; - } - - for(int i = x; i < x + getWidth(); i++) { - for(int j = y; j < y + getHeight(); j++) { - for(int k = z; k < z + getDepth(); k++) { - T v = ejector.readMatter(w, i, j, k); - - if(v != null) { - set(i - x, j - y, k - z, v); - } - } - } - } - - return true; - } - - default boolean canWrite(Class mediumType) { - return writeInto(mediumType) != null; - } - - default boolean canRead(Class mediumType) { - return readFrom(mediumType) != null; - } - - default int getBitsPer(int needed) { - int target = 1; - for(int i = 1; i < 8; i++) { - if(Math.pow(2, i) > needed) { - target = i; - break; - } - } - - return target; - } - - default void write(DataOutputStream dos) throws IOException { - dos.writeUTF(getType().getCanonicalName()); - - if((this instanceof PaletteOrHunk f && f.isPalette())) { - f.palette().writeDos(dos); - return; - } - - int w = getWidth(); - int h = getHeight(); - MatterPalette palette = new MatterPalette(this); - iterateSync((x, y, z, b) -> palette.assign(b)); - palette.writePalette(dos); - dos.writeBoolean(isMapped()); - - if(isMapped()) { - Varint.writeUnsignedVarInt(getEntryCount(), dos); - iterateSyncIO((x, y, z, b) -> { - Varint.writeUnsignedVarInt(Cache.to1D(x, y, z, w, h), dos); - palette.writeNode(b, dos); - }); - } else { - iterateSyncIO((x, y, z, b) -> palette.writeNode(b, dos)); - } - } - - default void read(DataInputStream din) throws IOException { - if((this instanceof PaletteOrHunk f && f.isPalette())) { - f.setPalette(new DataContainer<>(din, this)); - return; - } - - int w = getWidth(); - int h = getHeight(); - MatterPalette palette = new MatterPalette(this, din); - if(din.readBoolean()) { - int nodes = Varint.readUnsignedVarInt(din); - int[] pos; - - while(nodes-- > 0) { - pos = Cache.to3D(Varint.readUnsignedVarInt(din), w, h); - setRaw(pos[0], pos[1], pos[2], palette.readNode(din)); - } - } else { - iterateSyncIO((x, y, z, b) -> setRaw(x, y, z, palette.readNode(din))); - } - } - - default void rotateSliceInto(Matter n, double x, double y, double z) { - rotate(x, y, z, (_x, _y, _z) -> n.slice(getType())); - } - - default boolean containsKey(BlockVector v) { - return get(v.getBlockX(), v.getBlockY(), v.getBlockZ()) != null; - } - - default void put(BlockVector v, T d) { - set(v.getBlockX(), v.getBlockY(), v.getBlockZ(), d); - } - - default T get(BlockVector v) { - return get(v.getBlockX(), v.getBlockY(), v.getBlockZ()); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/MatterUpdate.java b/src/main/java/com/volmit/iris/util/matter/MatterUpdate.java deleted file mode 100644 index 10f2cb2bc..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterUpdate.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class MatterUpdate { - private final boolean update; -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/matter/MatterWriter.java b/src/main/java/com/volmit/iris/util/matter/MatterWriter.java deleted file mode 100644 index b4135cb5d..000000000 --- a/src/main/java/com/volmit/iris/util/matter/MatterWriter.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -@FunctionalInterface -public interface MatterWriter { - void writeMatter(W w, T d, int x, int y, int z); -} diff --git a/src/main/java/com/volmit/iris/util/matter/Sliced.java b/src/main/java/com/volmit/iris/util/matter/Sliced.java deleted file mode 100644 index d310a1081..000000000 --- a/src/main/java/com/volmit/iris/util/matter/Sliced.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(RetentionPolicy.RUNTIME) -public @interface Sliced { - -} diff --git a/src/main/java/com/volmit/iris/util/matter/TileWrapper.java b/src/main/java/com/volmit/iris/util/matter/TileWrapper.java deleted file mode 100644 index 3758a30ca..000000000 --- a/src/main/java/com/volmit/iris/util/matter/TileWrapper.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.engine.object.TileData; -import lombok.Data; - -@Data -public class TileWrapper { - private final TileData data; -} diff --git a/src/main/java/com/volmit/iris/util/matter/WorldMatter.java b/src/main/java/com/volmit/iris/util/matter/WorldMatter.java deleted file mode 100644 index 8b3185ea5..000000000 --- a/src/main/java/com/volmit/iris/util/matter/WorldMatter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.data.Cuboid; -import org.bukkit.Location; -import org.bukkit.block.data.BlockData; - -public class WorldMatter { - public static void placeMatter(Matter matter, Location at) { - if(matter.hasSlice(BlockData.class)) { - matter.slice(BlockData.class).writeInto(at); - } - - if(matter.hasSlice(MatterEntityGroup.class)) { - matter.slice(MatterEntityGroup.class).writeInto(at); - } - - if(matter.hasSlice(TileWrapper.class)) { - matter.slice(TileWrapper.class).writeInto(at); - } - } - - public static Matter createMatter(String author, Location a, Location b) { - Cuboid c = new Cuboid(a, b); - Matter s = new IrisMatter(c.getSizeX(), c.getSizeY(), c.getSizeZ()); - Iris.info(s.getWidth() + " " + s.getHeight() + " " + s.getDepth()); - s.getHeader().setAuthor(author); - s.slice(BlockData.class).readFrom(c.getLowerNE()); - s.slice(MatterEntityGroup.class).readFrom(c.getLowerNE()); - s.slice(TileWrapper.class).readFrom(c.getLowerNE()); - s.trimSlices(); - - return s; - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/BlockMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/BlockMatter.java deleted file mode 100644 index 6e98c3e37..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/BlockMatter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.Sliced; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class BlockMatter extends RawMatter { - public static final BlockData AIR = Material.AIR.createBlockData(); - - public BlockMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - public BlockMatter(int width, int height, int depth) { - super(width, height, depth, BlockData.class); - registerWriter(World.class, ((w, d, x, y, z) -> w.getBlockAt(x, y, z).setBlockData(d))); - registerReader(World.class, (w, x, y, z) -> { - BlockData d = w.getBlockAt(x, y, z).getBlockData(); - return d.getMaterial().isAir() ? null : d; - }); - } - - @Override - public void writeNode(BlockData b, DataOutputStream dos) throws IOException { - dos.writeUTF(b.getAsString(true)); - } - - @Override - public BlockData readNode(DataInputStream din) throws IOException { - return Bukkit.createBlockData(din.readUTF()); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/BooleanMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/BooleanMatter.java deleted file mode 100644 index 7f1ee1410..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/BooleanMatter.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.Sliced; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class BooleanMatter extends RawMatter { - public BooleanMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - public BooleanMatter(int width, int height, int depth) { - super(width, height, depth, Boolean.class); - } - - @Override - public void writeNode(Boolean b, DataOutputStream dos) throws IOException { - dos.writeBoolean(b); - } - - @Override - public Boolean readNode(DataInputStream din) throws IOException { - return din.readBoolean(); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/CavernMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/CavernMatter.java deleted file mode 100644 index 66a00c916..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/CavernMatter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.MatterCavern; -import com.volmit.iris.util.matter.Sliced; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class CavernMatter extends RawMatter { - public static final MatterCavern EMPTY = new MatterCavern(false, "", (byte) 0); - public static final MatterCavern BASIC = new MatterCavern(true, "", (byte) 0); - - public CavernMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - public CavernMatter(int width, int height, int depth) { - super(width, height, depth, MatterCavern.class); - } - - public static MatterCavern get(String customBiome, int liquid) { - return new MatterCavern(true, customBiome, (byte) liquid); - } - - @Override - public void writeNode(MatterCavern b, DataOutputStream dos) throws IOException { - dos.writeBoolean(b.isCavern()); - dos.writeUTF(b.getCustomBiome()); - dos.writeByte(b.getLiquid()); - } - - @Override - public MatterCavern readNode(DataInputStream din) throws IOException { - boolean b = din.readBoolean(); - String v = din.readUTF(); - byte l = din.readByte(); - - return new MatterCavern(b, v, l); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/CompoundMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/CompoundMatter.java deleted file mode 100644 index 288f2d332..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/CompoundMatter.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.matter.Sliced; -import com.volmit.iris.util.nbt.tag.CompoundTag; - -@Sliced -public class CompoundMatter extends NBTMatter { - public static final CompoundTag EMPTY = new CompoundTag(); - - public CompoundMatter() { - this(1, 1, 1); - } - - public CompoundMatter(int width, int height, int depth) { - super(width, height, depth, CompoundTag.class, EMPTY); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/EntityMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/EntityMatter.java deleted file mode 100644 index 99d774294..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/EntityMatter.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.engine.object.IrisPosition; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.Varint; -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.MatterEntity; -import com.volmit.iris.util.matter.MatterEntityGroup; -import com.volmit.iris.util.matter.MatterReader; -import com.volmit.iris.util.matter.Sliced; -import com.volmit.iris.util.nbt.io.NBTUtil; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Entity; -import org.bukkit.util.BoundingBox; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class EntityMatter extends RawMatter { - public static final MatterEntityGroup EMPTY = new MatterEntityGroup(); - private transient KMap> entityCache = new KMap<>(); - - public EntityMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - public EntityMatter(int width, int height, int depth) { - super(width, height, depth, MatterEntityGroup.class); - registerWriter(World.class, ((w, d, x, y, z) -> { - for(MatterEntity i : d.getEntities()) { - Location realPosition = new Location(w, x + i.getXOff(), y + i.getYOff(), z + i.getZOff()); - INMS.get().deserializeEntity(i.getEntityData(), realPosition); - } - })); - registerReader(World.class, (w, x, y, z) -> { - IrisPosition pos = new IrisPosition(x, y, z); - KList entities = entityCache.get(pos); - MatterEntityGroup g = new MatterEntityGroup(); - if(entities != null) { - for(Entity i : entities) { - g.getEntities().add(new MatterEntity( - Math.abs(i.getLocation().getX()) - Math.abs(i.getLocation().getBlockX()), - Math.abs(i.getLocation().getY()) - Math.abs(i.getLocation().getBlockY()), - Math.abs(i.getLocation().getZ()) - Math.abs(i.getLocation().getBlockZ()), - INMS.get().serializeEntity(i) - )); - } - - return g; - } - - return null; - }); - } - - /** - * The readFrom is overridden only if W is a Bukkit World, instead of looping - * across every block position, we simply use getNearbyEntities and cache each - * block position with a list of entities within that block, and directly feed - * the reader with the entities we capture. - * - * @param w - * the world - * @param x - * the x offset - * @param y - * the y offset - * @param z - * the z offset - * @param - * the type - * @return true if we read - */ - @Override - public synchronized boolean readFrom(W w, int x, int y, int z) { - if(!(w instanceof World)) { - return super.readFrom(w, x, y, z); - } - - MatterReader reader = (MatterReader) readFrom(World.class); - - if(reader == null) { - return false; - } - - entityCache = new KMap<>(); - - for(Entity i : ((World) w).getNearbyEntities(new BoundingBox(x, y, z, x + getWidth(), y + getHeight(), z + getHeight()))) { - entityCache.computeIfAbsent(new IrisPosition(i.getLocation()), - k -> new KList<>()).add(i); - } - - for(IrisPosition i : entityCache.keySet()) { - MatterEntityGroup g = reader.readMatter(w, i.getX(), i.getY(), i.getZ()); - - if(g != null) { - set(i.getX() - x, i.getY() - y, i.getZ() - z, g); - } - } - - entityCache.clear(); - - return true; - } - - @Override - public void writeNode(MatterEntityGroup b, DataOutputStream dos) throws IOException { - Varint.writeUnsignedVarInt(b.getEntities().size(), dos); - for(MatterEntity i : b.getEntities()) { - dos.writeByte((int) (i.getXOff() * 255) + Byte.MIN_VALUE); - dos.writeByte((int) (i.getYOff() * 255) + Byte.MIN_VALUE); - dos.writeByte((int) (i.getZOff() * 255) + Byte.MIN_VALUE); - NBTUtil.write(i.getEntityData(), dos, false); - } - } - - @Override - public MatterEntityGroup readNode(DataInputStream din) throws IOException { - MatterEntityGroup g = new MatterEntityGroup(); - int c = Varint.readUnsignedVarInt(din); - - while(c-- > 0) { - g.getEntities().add(new MatterEntity( - ((int) din.readByte() - Byte.MIN_VALUE) / 255F, - ((int) din.readByte() - Byte.MIN_VALUE) / 255F, - ((int) din.readByte() - Byte.MIN_VALUE) / 255F, - (CompoundTag) NBTUtil.read(din, false).getTag())); - } - - return g; - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/IntMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/IntMatter.java deleted file mode 100644 index 3620341d7..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/IntMatter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.data.Varint; -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.Sliced; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class IntMatter extends RawMatter { - public IntMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - public IntMatter(int width, int height, int depth) { - super(width, height, depth, Integer.class); - } - - @Override - public void writeNode(Integer b, DataOutputStream dos) throws IOException { - Varint.writeSignedVarInt(b, dos); - } - - @Override - public Integer readNode(DataInputStream din) throws IOException { - return Varint.readSignedVarInt(din); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/LongMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/LongMatter.java deleted file mode 100644 index 54add3104..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/LongMatter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.data.Varint; -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.Sliced; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class LongMatter extends RawMatter { - public LongMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - public LongMatter(int width, int height, int depth) { - super(width, height, depth, Long.class); - } - - @Override - public void writeNode(Long b, DataOutputStream dos) throws IOException { - Varint.writeSignedVarLong(b, dos); - } - - @Override - public Long readNode(DataInputStream din) throws IOException { - return Varint.readSignedVarLong(din); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/MarkerMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/MarkerMatter.java deleted file mode 100644 index 85e1cb16c..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/MarkerMatter.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.MatterMarker; -import com.volmit.iris.util.matter.Sliced; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class MarkerMatter extends RawMatter { - public static final MatterMarker NONE = new MatterMarker("none"); - public static final MatterMarker CAVE_FLOOR = new MatterMarker("cave_floor"); - public static final MatterMarker CAVE_CEILING = new MatterMarker("cave_ceiling"); - private static final KMap markers = new KMap<>(); - - public MarkerMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - public MarkerMatter(int width, int height, int depth) { - super(width, height, depth, MatterMarker.class); - } - - @Override - public void writeNode(MatterMarker b, DataOutputStream dos) throws IOException { - dos.writeUTF(b.getTag()); - } - - @Override - public MatterMarker readNode(DataInputStream din) throws IOException { - return markers.computeIfAbsent(din.readUTF(), MatterMarker::new); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/NBTMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/NBTMatter.java deleted file mode 100644 index 81bd0f6bb..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/NBTMatter.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.nbt.io.NBTUtil; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class NBTMatter> extends RawMatter { - public NBTMatter(int width, int height, int depth, Class c, T e) { - super(width, height, depth, c); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - @Override - public void writeNode(T b, DataOutputStream dos) throws IOException { - NBTUtil.write(b, dos, false); - } - - @Override - public T readNode(DataInputStream din) throws IOException { - return (T) NBTUtil.read(din, false).getTag(); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/RawMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/RawMatter.java deleted file mode 100644 index 746b2e338..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/RawMatter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.hunk.storage.MappedHunk; -import com.volmit.iris.util.hunk.storage.PaletteOrHunk; -import com.volmit.iris.util.matter.MatterReader; -import com.volmit.iris.util.matter.MatterSlice; -import com.volmit.iris.util.matter.MatterWriter; -import lombok.Getter; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public abstract class RawMatter extends PaletteOrHunk implements MatterSlice { - protected final KMap, MatterWriter> writers; - protected final KMap, MatterReader> readers; - @Getter - private final Class type; - - public RawMatter(int width, int height, int depth, Class type) { - super(width, height, depth, true, () -> new MappedHunk<>(width, height, depth)); - writers = new KMap<>(); - readers = new KMap<>(); - this.type = type; - } - - protected void registerWriter(Class mediumType, MatterWriter injector) { - writers.put(mediumType, injector); - } - - protected void registerReader(Class mediumType, MatterReader injector) { - readers.put(mediumType, injector); - } - - @Override - public MatterWriter writeInto(Class mediumType) { - return (MatterWriter) writers.get(mediumType); - } - - @Override - public MatterReader readFrom(Class mediumType) { - return (MatterReader) readers.get(mediumType); - } - - @Override - public abstract void writeNode(T b, DataOutputStream dos) throws IOException; - - @Override - public abstract T readNode(DataInputStream din) throws IOException; -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/RegistryMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/RegistryMatter.java deleted file mode 100644 index d61773049..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/RegistryMatter.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.core.loader.IrisRegistrant; -import com.volmit.iris.util.context.IrisContext; -import com.volmit.iris.util.data.palette.Palette; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class RegistryMatter extends RawMatter { - public RegistryMatter(int width, int height, int depth, Class c, T e) { - super(width, height, depth, c); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - @Override - public void writeNode(T b, DataOutputStream dos) throws IOException { - dos.writeUTF(b.getLoadKey()); - } - - @Override - public T readNode(DataInputStream din) throws IOException { - IrisContext context = IrisContext.get(); - return (T) context.getData().getLoaders().get(getType()).load(din.readUTF()); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/SpawnerMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/SpawnerMatter.java deleted file mode 100644 index 75ec22257..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/SpawnerMatter.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.engine.object.IrisSpawner; -import com.volmit.iris.util.matter.Sliced; - -@Sliced -public class SpawnerMatter extends RegistryMatter { - public SpawnerMatter() { - this(1, 1, 1); - } - - public SpawnerMatter(int width, int height, int depth) { - super(width, height, depth, IrisSpawner.class, new IrisSpawner()); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/StringMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/StringMatter.java deleted file mode 100644 index 5039bd96b..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/StringMatter.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.Sliced; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class StringMatter extends RawMatter { - public StringMatter() { - this(1, 1, 1); - } - - public StringMatter(int width, int height, int depth) { - super(width, height, depth, String.class); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - @Override - public void writeNode(String b, DataOutputStream dos) throws IOException { - dos.writeUTF(b); - } - - @Override - public String readNode(DataInputStream din) throws IOException { - return din.readUTF(); - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/TileMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/TileMatter.java deleted file mode 100644 index e4fe4a947..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/TileMatter.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.engine.object.TileData; -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.Sliced; -import com.volmit.iris.util.matter.TileWrapper; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import org.bukkit.Location; -import org.bukkit.World; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@SuppressWarnings("rawtypes") -@Sliced -public class TileMatter extends RawMatter { - - public TileMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return null; - } - - public TileMatter(int width, int height, int depth) { - super(width, height, depth, TileWrapper.class); - registerWriter(World.class, (w, d, x, y, z) -> { - CompoundTag tag = commonNbt(x, y, z, d.getData().getTileId()); - INMS.get().deserializeTile(d.getData().toNBT(d.getData().toNBT(tag)), new Location(w, x, y, z)); - Iris.warn("S: " + tag); - }); - registerReader(World.class, (w, x, y, z) -> { - TileData d = TileData.getTileState(w.getBlockAt(new Location(w, x, y, z))); - if(d == null) - return null; - return new TileWrapper(d); - }); - } - - public void writeNode(TileWrapper b, DataOutputStream dos) throws IOException { - b.getData().toBinary(dos); - } - - public TileWrapper readNode(DataInputStream din) throws IOException { - return new TileWrapper(TileData.read(din)); - } - - private CompoundTag commonNbt(int x, int y, int z, String mobId) { - CompoundTag tag = new CompoundTag(); - tag.putInt("x", x); - tag.putInt("y", y); - tag.putInt("z", z); - tag.putBoolean("keepPacked", false); - tag.putString("id", mobId); - return tag; - } -} diff --git a/src/main/java/com/volmit/iris/util/matter/slices/UpdateMatter.java b/src/main/java/com/volmit/iris/util/matter/slices/UpdateMatter.java deleted file mode 100644 index 03de55ac6..000000000 --- a/src/main/java/com/volmit/iris/util/matter/slices/UpdateMatter.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.matter.slices; - -import com.volmit.iris.util.data.palette.GlobalPalette; -import com.volmit.iris.util.data.palette.Palette; -import com.volmit.iris.util.matter.MatterUpdate; -import com.volmit.iris.util.matter.Sliced; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -@Sliced -public class UpdateMatter extends RawMatter { - public static final MatterUpdate ON = new MatterUpdate(true); - public static final MatterUpdate OFF = new MatterUpdate(false); - private static final Palette GLOBAL = new GlobalPalette<>(OFF, ON); - - public UpdateMatter() { - this(1, 1, 1); - } - - @Override - public Palette getGlobalPalette() { - return GLOBAL; - } - - public UpdateMatter(int width, int height, int depth) { - super(width, height, depth, MatterUpdate.class); - } - - @Override - public void writeNode(MatterUpdate b, DataOutputStream dos) throws IOException { - dos.writeBoolean(b.isUpdate()); - } - - @Override - public MatterUpdate readNode(DataInputStream din) throws IOException { - return din.readBoolean() ? ON : OFF; - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/NBTDeserializer.java b/src/main/java/com/volmit/iris/util/nbt/io/NBTDeserializer.java deleted file mode 100644 index 3cc42d2e4..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/NBTDeserializer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.engine.data.io.Deserializer; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.GZIPInputStream; - -public class NBTDeserializer implements Deserializer { - - private final boolean compressed; - - public NBTDeserializer() { - this(true); - } - - public NBTDeserializer(boolean compressed) { - this.compressed = compressed; - } - - @Override - public NamedTag fromStream(InputStream stream) throws IOException { - NBTInputStream nbtIn; - if(compressed) { - nbtIn = new NBTInputStream(new GZIPInputStream(stream)); - } else { - nbtIn = new NBTInputStream(stream); - } - return nbtIn.readTag(Tag.DEFAULT_MAX_DEPTH); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/NBTInputStream.java b/src/main/java/com/volmit/iris/util/nbt/io/NBTInputStream.java deleted file mode 100644 index ee14af5c0..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/NBTInputStream.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.engine.data.io.ExceptionBiFunction; -import com.volmit.iris.engine.data.io.MaxDepthIO; -import com.volmit.iris.util.nbt.tag.ByteArrayTag; -import com.volmit.iris.util.nbt.tag.ByteTag; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.DoubleTag; -import com.volmit.iris.util.nbt.tag.EndTag; -import com.volmit.iris.util.nbt.tag.FloatTag; -import com.volmit.iris.util.nbt.tag.IntArrayTag; -import com.volmit.iris.util.nbt.tag.IntTag; -import com.volmit.iris.util.nbt.tag.ListTag; -import com.volmit.iris.util.nbt.tag.LongArrayTag; -import com.volmit.iris.util.nbt.tag.LongTag; -import com.volmit.iris.util.nbt.tag.ShortTag; -import com.volmit.iris.util.nbt.tag.StringTag; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -public class NBTInputStream extends DataInputStream implements MaxDepthIO { - - private static final Map, IOException>> readers = new HashMap<>(); - private static final Map> idClassMapping = new HashMap<>(); - - static { - put(EndTag.ID, (i, d) -> EndTag.INSTANCE, EndTag.class); - put(ByteTag.ID, (i, d) -> readByte(i), ByteTag.class); - put(ShortTag.ID, (i, d) -> readShort(i), ShortTag.class); - put(IntTag.ID, (i, d) -> readInt(i), IntTag.class); - put(LongTag.ID, (i, d) -> readLong(i), LongTag.class); - put(FloatTag.ID, (i, d) -> readFloat(i), FloatTag.class); - put(DoubleTag.ID, (i, d) -> readDouble(i), DoubleTag.class); - put(ByteArrayTag.ID, (i, d) -> readByteArray(i), ByteArrayTag.class); - put(StringTag.ID, (i, d) -> readString(i), StringTag.class); - put(ListTag.ID, NBTInputStream::readListTag, ListTag.class); - put(CompoundTag.ID, NBTInputStream::readCompound, CompoundTag.class); - put(IntArrayTag.ID, (i, d) -> readIntArray(i), IntArrayTag.class); - put(LongArrayTag.ID, (i, d) -> readLongArray(i), LongArrayTag.class); - } - - public NBTInputStream(InputStream in) { - super(in); - } - - private static void put(byte id, ExceptionBiFunction, IOException> reader, Class clazz) { - readers.put(id, reader); - idClassMapping.put(id, clazz); - } - - private static ByteTag readByte(NBTInputStream in) throws IOException { - return new ByteTag(in.readByte()); - } - - private static ShortTag readShort(NBTInputStream in) throws IOException { - return new ShortTag(in.readShort()); - } - - private static IntTag readInt(NBTInputStream in) throws IOException { - return new IntTag(in.readInt()); - } - - private static LongTag readLong(NBTInputStream in) throws IOException { - return new LongTag(in.readLong()); - } - - private static FloatTag readFloat(NBTInputStream in) throws IOException { - return new FloatTag(in.readFloat()); - } - - private static DoubleTag readDouble(NBTInputStream in) throws IOException { - return new DoubleTag(in.readDouble()); - } - - private static StringTag readString(NBTInputStream in) throws IOException { - return new StringTag(in.readUTF()); - } - - private static ByteArrayTag readByteArray(NBTInputStream in) throws IOException { - ByteArrayTag bat = new ByteArrayTag(new byte[in.readInt()]); - in.readFully(bat.getValue()); - return bat; - } - - private static IntArrayTag readIntArray(NBTInputStream in) throws IOException { - int l = in.readInt(); - int[] data = new int[l]; - IntArrayTag iat = new IntArrayTag(data); - for(int i = 0; i < l; i++) { - data[i] = in.readInt(); - } - return iat; - } - - private static LongArrayTag readLongArray(NBTInputStream in) throws IOException { - int l = in.readInt(); - long[] data = new long[l]; - LongArrayTag iat = new LongArrayTag(data); - for(int i = 0; i < l; i++) { - data[i] = in.readLong(); - } - return iat; - } - - private static ListTag readListTag(NBTInputStream in, int maxDepth) throws IOException { - byte listType = in.readByte(); - ListTag list = ListTag.createUnchecked(idClassMapping.get(listType)); - int length = in.readInt(); - if(length < 0) { - length = 0; - } - for(int i = 0; i < length; i++) { - list.addUnchecked(in.readTag(listType, in.decrementMaxDepth(maxDepth))); - } - return list; - } - - private static CompoundTag readCompound(NBTInputStream in, int maxDepth) throws IOException { - CompoundTag comp = new CompoundTag(); - for(int id = in.readByte() & 0xFF; id != 0; id = in.readByte() & 0xFF) { - String key = in.readUTF(); - Tag element = in.readTag((byte) id, in.decrementMaxDepth(maxDepth)); - comp.put(key, element); - } - return comp; - } - - public NamedTag readTag(int maxDepth) throws IOException { - byte id = readByte(); - return new NamedTag(readUTF(), readTag(id, maxDepth)); - } - - public Tag readRawTag(int maxDepth) throws IOException { - byte id = readByte(); - return readTag(id, maxDepth); - } - - private Tag readTag(byte type, int maxDepth) throws IOException { - ExceptionBiFunction, IOException> f; - if((f = readers.get(type)) == null) { - throw new IOException("invalid tag id \"" + type + "\""); - } - return f.accept(this, maxDepth); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/NBTOutputStream.java b/src/main/java/com/volmit/iris/util/nbt/io/NBTOutputStream.java deleted file mode 100644 index ee4290bcb..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/NBTOutputStream.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.engine.data.io.ExceptionTriConsumer; -import com.volmit.iris.engine.data.io.MaxDepthIO; -import com.volmit.iris.util.nbt.tag.ByteArrayTag; -import com.volmit.iris.util.nbt.tag.ByteTag; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.DoubleTag; -import com.volmit.iris.util.nbt.tag.EndTag; -import com.volmit.iris.util.nbt.tag.FloatTag; -import com.volmit.iris.util.nbt.tag.IntArrayTag; -import com.volmit.iris.util.nbt.tag.IntTag; -import com.volmit.iris.util.nbt.tag.ListTag; -import com.volmit.iris.util.nbt.tag.LongArrayTag; -import com.volmit.iris.util.nbt.tag.LongTag; -import com.volmit.iris.util.nbt.tag.ShortTag; -import com.volmit.iris.util.nbt.tag.StringTag; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; - -public class NBTOutputStream extends DataOutputStream implements MaxDepthIO { - - private static final Map, Integer, IOException>> writers = new HashMap<>(); - private static final Map, Byte> classIdMapping = new HashMap<>(); - - static { - put(EndTag.ID, (o, t, d) -> { - }, EndTag.class); - put(ByteTag.ID, (o, t, d) -> writeByte(o, t), ByteTag.class); - put(ShortTag.ID, (o, t, d) -> writeShort(o, t), ShortTag.class); - put(IntTag.ID, (o, t, d) -> writeInt(o, t), IntTag.class); - put(LongTag.ID, (o, t, d) -> writeLong(o, t), LongTag.class); - put(FloatTag.ID, (o, t, d) -> writeFloat(o, t), FloatTag.class); - put(DoubleTag.ID, (o, t, d) -> writeDouble(o, t), DoubleTag.class); - put(ByteArrayTag.ID, (o, t, d) -> writeByteArray(o, t), ByteArrayTag.class); - put(StringTag.ID, (o, t, d) -> writeString(o, t), StringTag.class); - put(ListTag.ID, NBTOutputStream::writeList, ListTag.class); - put(CompoundTag.ID, NBTOutputStream::writeCompound, CompoundTag.class); - put(IntArrayTag.ID, (o, t, d) -> writeIntArray(o, t), IntArrayTag.class); - put(LongArrayTag.ID, (o, t, d) -> writeLongArray(o, t), LongArrayTag.class); - } - - public NBTOutputStream(OutputStream out) { - super(out); - } - - private static void put(byte id, ExceptionTriConsumer, Integer, IOException> f, Class clazz) { - writers.put(id, f); - classIdMapping.put(clazz, id); - } - - static byte idFromClass(Class clazz) { - Byte id = classIdMapping.get(clazz); - if(id == null) { - throw new IllegalArgumentException("unknown Tag class " + clazz.getName()); - } - return id; - } - - private static void writeByte(NBTOutputStream out, Tag tag) throws IOException { - out.writeByte(((ByteTag) tag).asByte()); - } - - private static void writeShort(NBTOutputStream out, Tag tag) throws IOException { - out.writeShort(((ShortTag) tag).asShort()); - } - - private static void writeInt(NBTOutputStream out, Tag tag) throws IOException { - out.writeInt(((IntTag) tag).asInt()); - } - - private static void writeLong(NBTOutputStream out, Tag tag) throws IOException { - out.writeLong(((LongTag) tag).asLong()); - } - - private static void writeFloat(NBTOutputStream out, Tag tag) throws IOException { - out.writeFloat(((FloatTag) tag).asFloat()); - } - - private static void writeDouble(NBTOutputStream out, Tag tag) throws IOException { - out.writeDouble(((DoubleTag) tag).asDouble()); - } - - private static void writeString(NBTOutputStream out, Tag tag) throws IOException { - out.writeUTF(((StringTag) tag).getValue()); - } - - private static void writeByteArray(NBTOutputStream out, Tag tag) throws IOException { - out.writeInt(((ByteArrayTag) tag).length()); - out.write(((ByteArrayTag) tag).getValue()); - } - - private static void writeIntArray(NBTOutputStream out, Tag tag) throws IOException { - out.writeInt(((IntArrayTag) tag).length()); - for(int i : ((IntArrayTag) tag).getValue()) { - out.writeInt(i); - } - } - - private static void writeLongArray(NBTOutputStream out, Tag tag) throws IOException { - out.writeInt(((LongArrayTag) tag).length()); - for(long l : ((LongArrayTag) tag).getValue()) { - out.writeLong(l); - } - } - - private static void writeList(NBTOutputStream out, Tag tag, int maxDepth) throws IOException { - out.writeByte(idFromClass(((ListTag) tag).getTypeClass())); - out.writeInt(((ListTag) tag).size()); - for(Tag t : ((ListTag) tag)) { - out.writeRawTag(t, out.decrementMaxDepth(maxDepth)); - } - } - - private static void writeCompound(NBTOutputStream out, Tag tag, int maxDepth) throws IOException { - for(Map.Entry> entry : (CompoundTag) tag) { - if(entry.getValue().getID() == 0) { - throw new IOException("end tag not allowed"); - } - out.writeByte(entry.getValue().getID()); - out.writeUTF(entry.getKey()); - out.writeRawTag(entry.getValue(), out.decrementMaxDepth(maxDepth)); - } - out.writeByte(0); - } - - public void writeTag(NamedTag tag, int maxDepth) throws IOException { - writeByte(tag.getTag().getID()); - if(tag.getTag().getID() != 0) { - writeUTF(tag.getName() == null ? "" : tag.getName()); - } - writeRawTag(tag.getTag(), maxDepth); - } - - public void writeTag(Tag tag, int maxDepth) throws IOException { - writeByte(tag.getID()); - if(tag.getID() != 0) { - writeUTF(""); - } - writeRawTag(tag, maxDepth); - } - - public void writeRawTag(Tag tag, int maxDepth) throws IOException { - ExceptionTriConsumer, Integer, IOException> f; - if((f = writers.get(tag.getID())) == null) { - throw new IOException("invalid tag \"" + tag.getID() + "\""); - } - f.accept(this, tag, maxDepth); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/NBTSerializer.java b/src/main/java/com/volmit/iris/util/nbt/io/NBTSerializer.java deleted file mode 100644 index 104852fa4..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/NBTSerializer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.engine.data.io.Serializer; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.zip.GZIPOutputStream; - -public class NBTSerializer implements Serializer { - - private final boolean compressed; - - public NBTSerializer() { - this(true); - } - - public NBTSerializer(boolean compressed) { - this.compressed = compressed; - } - - @Override - public void toStream(NamedTag object, OutputStream out) throws IOException { - NBTOutputStream nbtOut; - if(compressed) { - nbtOut = new NBTOutputStream(new GZIPOutputStream(out, true)); - } else { - nbtOut = new NBTOutputStream(out); - } - nbtOut.writeTag(object, Tag.DEFAULT_MAX_DEPTH); - nbtOut.flush(); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/NBTUtil.java b/src/main/java/com/volmit/iris/util/nbt/io/NBTUtil.java deleted file mode 100644 index a28df3aca..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/NBTUtil.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PushbackInputStream; -import java.util.zip.GZIPInputStream; - -public final class NBTUtil { - - private NBTUtil() { - } - - public static void write(NamedTag tag, File file, boolean compressed) throws IOException { - try(FileOutputStream fos = new FileOutputStream(file)) { - new NBTSerializer(compressed).toStream(tag, fos); - } - } - - public static void write(NamedTag tag, OutputStream out, boolean compressed) throws IOException { - new NBTSerializer(compressed).toStream(tag, out); - } - - public static void write(Tag tag, OutputStream out, boolean compressed) throws IOException { - write(new NamedTag(null, tag), out, compressed); - } - - public static void write(NamedTag tag, String file, boolean compressed) throws IOException { - write(tag, new File(file), compressed); - } - - public static void write(NamedTag tag, File file) throws IOException { - write(tag, file, true); - } - - public static void write(NamedTag tag, String file) throws IOException { - write(tag, new File(file), true); - } - - public static void write(Tag tag, File file, boolean compressed) throws IOException { - write(new NamedTag(null, tag), file, compressed); - } - - public static void write(Tag tag, String file, boolean compressed) throws IOException { - write(new NamedTag(null, tag), new File(file), compressed); - } - - public static void write(Tag tag, File file) throws IOException { - write(new NamedTag(null, tag), file, true); - } - - public static void write(Tag tag, String file) throws IOException { - write(new NamedTag(null, tag), new File(file), true); - } - - public static NamedTag read(File file, boolean compressed) throws IOException { - try(FileInputStream fis = new FileInputStream(file)) { - return new NBTDeserializer(compressed).fromStream(fis); - } - } - - public static NamedTag read(InputStream in, boolean compressed) throws IOException { - return new NBTDeserializer(compressed).fromStream(in); - } - - public static NamedTag read(String file, boolean compressed) throws IOException { - return read(new File(file), compressed); - } - - public static NamedTag read(File file) throws IOException { - try(FileInputStream fis = new FileInputStream(file)) { - return new NBTDeserializer(false).fromStream(detectDecompression(fis)); - } - } - - public static NamedTag read(String file) throws IOException { - return read(new File(file)); - } - - private static InputStream detectDecompression(InputStream is) throws IOException { - PushbackInputStream pbis = new PushbackInputStream(is, 2); - int signature = (pbis.read() & 0xFF) + (pbis.read() << 8); - pbis.unread(signature >> 8); - pbis.unread(signature & 0xFF); - if(signature == GZIPInputStream.GZIP_MAGIC) { - return new GZIPInputStream(pbis); - } - return pbis; - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/NamedTag.java b/src/main/java/com/volmit/iris/util/nbt/io/NamedTag.java deleted file mode 100644 index 904617a71..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/NamedTag.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.util.nbt.tag.Tag; - -public class NamedTag { - - private String name; - private Tag tag; - - public NamedTag(String name, Tag tag) { - this.name = name; - this.tag = tag; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Tag getTag() { - return tag; - } - - public void setTag(Tag tag) { - this.tag = tag; - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/ParseException.java b/src/main/java/com/volmit/iris/util/nbt/io/ParseException.java deleted file mode 100644 index 1e77b722b..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/ParseException.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import java.io.IOException; - -public class ParseException extends IOException { - - public ParseException(String msg) { - super(msg); - } - - public ParseException(String msg, String value, int index) { - super(msg + " at: " + formatError(value, index)); - } - - private static String formatError(String value, int index) { - StringBuilder builder = new StringBuilder(); - int i = Math.min(value.length(), index); - if(i > 35) { - builder.append("..."); - } - builder.append(value, Math.max(0, i - 35), i); - builder.append("<--[HERE]"); - return builder.toString(); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/SNBTDeserializer.java b/src/main/java/com/volmit/iris/util/nbt/io/SNBTDeserializer.java deleted file mode 100644 index bd6c50ef5..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/SNBTDeserializer.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.engine.data.io.StringDeserializer; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.stream.Collectors; - -public class SNBTDeserializer implements StringDeserializer> { - - @Override - public Tag fromReader(Reader reader) throws IOException { - return fromReader(reader, Tag.DEFAULT_MAX_DEPTH); - } - - public Tag fromReader(Reader reader, int maxDepth) throws IOException { - BufferedReader bufferedReader; - if(reader instanceof BufferedReader) { - bufferedReader = (BufferedReader) reader; - } else { - bufferedReader = new BufferedReader(reader); - } - return SNBTParser.parse(bufferedReader.lines().collect(Collectors.joining()), maxDepth); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/SNBTParser.java b/src/main/java/com/volmit/iris/util/nbt/io/SNBTParser.java deleted file mode 100644 index 2321cb7bf..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/SNBTParser.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.io.MaxDepthIO; -import com.volmit.iris.util.nbt.tag.ArrayTag; -import com.volmit.iris.util.nbt.tag.ByteArrayTag; -import com.volmit.iris.util.nbt.tag.ByteTag; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.DoubleTag; -import com.volmit.iris.util.nbt.tag.EndTag; -import com.volmit.iris.util.nbt.tag.FloatTag; -import com.volmit.iris.util.nbt.tag.IntArrayTag; -import com.volmit.iris.util.nbt.tag.IntTag; -import com.volmit.iris.util.nbt.tag.ListTag; -import com.volmit.iris.util.nbt.tag.LongArrayTag; -import com.volmit.iris.util.nbt.tag.LongTag; -import com.volmit.iris.util.nbt.tag.ShortTag; -import com.volmit.iris.util.nbt.tag.StringTag; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -public final class SNBTParser implements MaxDepthIO { - - private static final Pattern - FLOAT_LITERAL_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.?|\\d*\\.\\d+)(?:e[-+]?\\d+)?f$", Pattern.CASE_INSENSITIVE), - DOUBLE_LITERAL_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.?|\\d*\\.\\d+)(?:e[-+]?\\d+)?d$", Pattern.CASE_INSENSITIVE), - DOUBLE_LITERAL_NO_SUFFIX_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.|\\d*\\.\\d+)(?:e[-+]?\\d+)?$", Pattern.CASE_INSENSITIVE), - BYTE_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+b$", Pattern.CASE_INSENSITIVE), - SHORT_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+s$", Pattern.CASE_INSENSITIVE), - INT_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+$", Pattern.CASE_INSENSITIVE), - LONG_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+l$", Pattern.CASE_INSENSITIVE), - NUMBER_PATTERN = Pattern.compile("^[-+]?\\d+$"); - - private final StringPointer ptr; - - private SNBTParser(String string) { - this.ptr = new StringPointer(string); - } - - public static Tag parse(String string, int maxDepth) throws ParseException { - SNBTParser parser = new SNBTParser(string); - Tag tag = parser.parseAnything(maxDepth); - parser.ptr.skipWhitespace(); - if(parser.ptr.hasNext()) { - throw parser.ptr.parseException("invalid characters after end of snbt"); - } - return tag; - } - - public static Tag parse(String string) throws ParseException { - return parse(string, Tag.DEFAULT_MAX_DEPTH); - } - - private Tag parseAnything(int maxDepth) throws ParseException { - ptr.skipWhitespace(); - switch(ptr.currentChar()) { - case '{': - return parseCompoundTag(maxDepth); - case '[': - if(ptr.hasCharsLeft(2) && ptr.lookAhead(1) != '"' && ptr.lookAhead(2) == ';') { - return parseNumArray(); - } - return parseListTag(maxDepth); - } - return parseStringOrLiteral(); - } - - private Tag parseStringOrLiteral() throws ParseException { - ptr.skipWhitespace(); - if(ptr.currentChar() == '"') { - return new StringTag(ptr.parseQuotedString()); - } - String s = ptr.parseSimpleString(); - if(s.isEmpty()) { - throw new ParseException("expected non empty value"); - } - if(FLOAT_LITERAL_PATTERN.matcher(s).matches()) { - return new FloatTag(Float.parseFloat(s.substring(0, s.length() - 1))); - } else if(BYTE_LITERAL_PATTERN.matcher(s).matches()) { - try { - return new ByteTag(Byte.parseByte(s.substring(0, s.length() - 1))); - } catch(NumberFormatException ex) { - Iris.reportError(ex); - throw ptr.parseException("byte not in range: \"" + s.substring(0, s.length() - 1) + "\""); - } - } else if(SHORT_LITERAL_PATTERN.matcher(s).matches()) { - try { - return new ShortTag(Short.parseShort(s.substring(0, s.length() - 1))); - } catch(NumberFormatException ex) { - Iris.reportError(ex); - throw ptr.parseException("short not in range: \"" + s.substring(0, s.length() - 1) + "\""); - } - } else if(LONG_LITERAL_PATTERN.matcher(s).matches()) { - try { - return new LongTag(Long.parseLong(s.substring(0, s.length() - 1))); - } catch(NumberFormatException ex) { - Iris.reportError(ex); - throw ptr.parseException("long not in range: \"" + s.substring(0, s.length() - 1) + "\""); - } - } else if(INT_LITERAL_PATTERN.matcher(s).matches()) { - try { - return new IntTag(Integer.parseInt(s)); - } catch(NumberFormatException ex) { - Iris.reportError(ex); - throw ptr.parseException("int not in range: \"" + s.substring(0, s.length() - 1) + "\""); - } - } else if(DOUBLE_LITERAL_PATTERN.matcher(s).matches()) { - return new DoubleTag(Double.parseDouble(s.substring(0, s.length() - 1))); - } else if(DOUBLE_LITERAL_NO_SUFFIX_PATTERN.matcher(s).matches()) { - return new DoubleTag(Double.parseDouble(s)); - } else if("true".equalsIgnoreCase(s)) { - return new ByteTag(true); - } else if("false".equalsIgnoreCase(s)) { - return new ByteTag(false); - } - return new StringTag(s); - } - - private CompoundTag parseCompoundTag(int maxDepth) throws ParseException { - ptr.expectChar('{'); - - CompoundTag compoundTag = new CompoundTag(); - - ptr.skipWhitespace(); - while(ptr.hasNext() && ptr.currentChar() != '}') { - ptr.skipWhitespace(); - String key = ptr.currentChar() == '"' ? ptr.parseQuotedString() : ptr.parseSimpleString(); - if(key.isEmpty()) { - throw new ParseException("empty keys are not allowed"); - } - ptr.expectChar(':'); - - compoundTag.put(key, parseAnything(decrementMaxDepth(maxDepth))); - - if(!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar('}'); - return compoundTag; - } - - private ListTag parseListTag(int maxDepth) throws ParseException { - ptr.expectChar('['); - ptr.skipWhitespace(); - ListTag list = ListTag.createUnchecked(EndTag.class); - while(ptr.currentChar() != ']') { - Tag element = parseAnything(decrementMaxDepth(maxDepth)); - try { - list.addUnchecked(element); - } catch(IllegalArgumentException ex) { - Iris.reportError(ex); - throw ptr.parseException(ex.getMessage()); - } - if(!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar(']'); - return list; - } - - private ArrayTag parseNumArray() throws ParseException { - ptr.expectChar('['); - char arrayType = ptr.next(); - ptr.expectChar(';'); - ptr.skipWhitespace(); - switch(arrayType) { - case 'B': - return parseByteArrayTag(); - case 'I': - return parseIntArrayTag(); - case 'L': - return parseLongArrayTag(); - } - throw new ParseException("invalid array type '" + arrayType + "'"); - } - - private ByteArrayTag parseByteArrayTag() throws ParseException { - List byteList = new ArrayList<>(); - while(ptr.currentChar() != ']') { - String s = ptr.parseSimpleString(); - ptr.skipWhitespace(); - if(NUMBER_PATTERN.matcher(s).matches()) { - try { - byteList.add(Byte.parseByte(s)); - } catch(NumberFormatException ex) { - Iris.reportError(ex); - throw ptr.parseException("byte not in range: \"" + s + "\""); - } - } else { - throw ptr.parseException("invalid byte in ByteArrayTag: \"" + s + "\""); - } - if(!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar(']'); - byte[] bytes = new byte[byteList.size()]; - for(int i = 0; i < byteList.size(); i++) { - bytes[i] = byteList.get(i); - } - return new ByteArrayTag(bytes); - } - - private IntArrayTag parseIntArrayTag() throws ParseException { - List intList = new ArrayList<>(); - while(ptr.currentChar() != ']') { - String s = ptr.parseSimpleString(); - ptr.skipWhitespace(); - if(NUMBER_PATTERN.matcher(s).matches()) { - try { - intList.add(Integer.parseInt(s)); - } catch(NumberFormatException ex) { - Iris.reportError(ex); - throw ptr.parseException("int not in range: \"" + s + "\""); - } - } else { - throw ptr.parseException("invalid int in IntArrayTag: \"" + s + "\""); - } - if(!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar(']'); - return new IntArrayTag(intList.stream().mapToInt(i -> i).toArray()); - } - - private LongArrayTag parseLongArrayTag() throws ParseException { - List longList = new ArrayList<>(); - while(ptr.currentChar() != ']') { - String s = ptr.parseSimpleString(); - ptr.skipWhitespace(); - if(NUMBER_PATTERN.matcher(s).matches()) { - try { - longList.add(Long.parseLong(s)); - } catch(NumberFormatException ex) { - Iris.reportError(ex); - throw ptr.parseException("long not in range: \"" + s + "\""); - } - } else { - throw ptr.parseException("invalid long in LongArrayTag: \"" + s + "\""); - } - if(!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar(']'); - return new LongArrayTag(longList.stream().mapToLong(l -> l).toArray()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/SNBTSerializer.java b/src/main/java/com/volmit/iris/util/nbt/io/SNBTSerializer.java deleted file mode 100644 index 0ae5250e7..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/SNBTSerializer.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.engine.data.io.StringSerializer; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.IOException; -import java.io.Writer; - -public class SNBTSerializer implements StringSerializer> { - - @Override - public void toWriter(Tag tag, Writer writer) throws IOException { - SNBTWriter.write(tag, writer); - } - - public void toWriter(Tag tag, Writer writer, int maxDepth) throws IOException { - SNBTWriter.write(tag, writer, maxDepth); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/SNBTUtil.java b/src/main/java/com/volmit/iris/util/nbt/io/SNBTUtil.java deleted file mode 100644 index 250b8781f..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/SNBTUtil.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.IOException; - -public class SNBTUtil { - - public static String toSNBT(Tag tag) throws IOException { - return new SNBTSerializer().toString(tag); - } - - public static Tag fromSNBT(String string) throws IOException { - return new SNBTDeserializer().fromString(string); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/SNBTWriter.java b/src/main/java/com/volmit/iris/util/nbt/io/SNBTWriter.java deleted file mode 100644 index f8d68e0c2..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/SNBTWriter.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -import com.volmit.iris.engine.data.io.MaxDepthIO; -import com.volmit.iris.util.nbt.tag.ByteArrayTag; -import com.volmit.iris.util.nbt.tag.ByteTag; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.DoubleTag; -import com.volmit.iris.util.nbt.tag.EndTag; -import com.volmit.iris.util.nbt.tag.FloatTag; -import com.volmit.iris.util.nbt.tag.IntArrayTag; -import com.volmit.iris.util.nbt.tag.IntTag; -import com.volmit.iris.util.nbt.tag.ListTag; -import com.volmit.iris.util.nbt.tag.LongArrayTag; -import com.volmit.iris.util.nbt.tag.LongTag; -import com.volmit.iris.util.nbt.tag.ShortTag; -import com.volmit.iris.util.nbt.tag.StringTag; -import com.volmit.iris.util.nbt.tag.Tag; - -import java.io.IOException; -import java.io.Writer; -import java.lang.reflect.Array; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * SNBTWriter creates an SNBT String. - */ -@SuppressWarnings("ClassCanBeRecord") -public final class SNBTWriter implements MaxDepthIO { - - private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z_.+\\-]+"); - - private final Writer writer; - - private SNBTWriter(Writer writer) { - this.writer = writer; - } - - public static void write(Tag tag, Writer writer, int maxDepth) throws IOException { - new SNBTWriter(writer).writeAnything(tag, maxDepth); - } - - public static void write(Tag tag, Writer writer) throws IOException { - write(tag, writer, Tag.DEFAULT_MAX_DEPTH); - } - - public static String escapeString(String s) { - if(!NON_QUOTE_PATTERN.matcher(s).matches()) { - StringBuilder sb = new StringBuilder(); - sb.append('"'); - for(int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if(c == '\\' || c == '"') { - sb.append('\\'); - } - sb.append(c); - } - sb.append('"'); - return sb.toString(); - } - return s; - } - - private void writeAnything(Tag tag, int maxDepth) throws IOException { - switch(tag.getID()) { - case EndTag.ID: - //do nothing - break; - case ByteTag.ID: - writer.append(Byte.toString(((ByteTag) tag).asByte())).write('b'); - break; - case ShortTag.ID: - writer.append(Short.toString(((ShortTag) tag).asShort())).write('s'); - break; - case IntTag.ID: - writer.write(Integer.toString(((IntTag) tag).asInt())); - break; - case LongTag.ID: - writer.append(Long.toString(((LongTag) tag).asLong())).write('l'); - break; - case FloatTag.ID: - writer.append(Float.toString(((FloatTag) tag).asFloat())).write('f'); - break; - case DoubleTag.ID: - writer.append(Double.toString(((DoubleTag) tag).asDouble())).write('d'); - break; - case ByteArrayTag.ID: - writeArray(((ByteArrayTag) tag).getValue(), ((ByteArrayTag) tag).length(), "B"); - break; - case StringTag.ID: - writer.write(escapeString(((StringTag) tag).getValue())); - break; - case ListTag.ID: - writer.write('['); - for(int i = 0; i < ((ListTag) tag).size(); i++) { - writer.write(i == 0 ? "" : ","); - writeAnything(((ListTag) tag).get(i), decrementMaxDepth(maxDepth)); - } - writer.write(']'); - break; - case CompoundTag.ID: - writer.write('{'); - boolean first = true; - for(Map.Entry> entry : (CompoundTag) tag) { - writer.write(first ? "" : ","); - writer.append(escapeString(entry.getKey())).write(':'); - writeAnything(entry.getValue(), decrementMaxDepth(maxDepth)); - first = false; - } - writer.write('}'); - break; - case IntArrayTag.ID: - writeArray(((IntArrayTag) tag).getValue(), ((IntArrayTag) tag).length(), "I"); - break; - case LongArrayTag.ID: - writeArray(((LongArrayTag) tag).getValue(), ((LongArrayTag) tag).length(), "L"); - break; - default: - throw new IOException("unknown tag with id \"" + tag.getID() + "\""); - } - } - - private void writeArray(Object array, int length, String prefix) throws IOException { - writer.append('[').append(prefix).write(';'); - for(int i = 0; i < length; i++) { - writer.append(i == 0 ? "" : ",").write(Array.get(array, i).toString()); - } - writer.write(']'); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/io/StringPointer.java b/src/main/java/com/volmit/iris/util/nbt/io/StringPointer.java deleted file mode 100644 index 4847dac70..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/io/StringPointer.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.io; - -public class StringPointer { - - private final String value; - private int index; - - public StringPointer(String value) { - this.value = value; - } - - private static boolean isSimpleChar(char c) { - return c >= 'a' && c <= 'z' - || c >= 'A' && c <= 'Z' - || c >= '0' && c <= '9' - || c == '-' - || c == '+' - || c == '.' - || c == '_'; - } - - public String parseSimpleString() { - int oldIndex = index; - while(hasNext() && isSimpleChar(currentChar())) { - index++; - } - return value.substring(oldIndex, index); - } - - public String parseQuotedString() throws ParseException { - int oldIndex = ++index; //ignore beginning quotes - StringBuilder sb = null; - boolean escape = false; - while(hasNext()) { - char c = next(); - if(escape) { - if(c != '\\' && c != '"') { - throw parseException("invalid escape of '" + c + "'"); - } - escape = false; - } else { - if(c == '\\') { //escape - escape = true; - if(sb != null) { - continue; - } - sb = new StringBuilder(value.substring(oldIndex, index - 1)); - continue; - } - if(c == '"') { - return sb == null ? value.substring(oldIndex, index - 1) : sb.toString(); - } - } - if(sb != null) { - sb.append(c); - } - } - throw parseException("missing end quote"); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean nextArrayElement() { - skipWhitespace(); - if(hasNext() && currentChar() == ',') { - index++; - skipWhitespace(); - return true; - } - return false; - } - - public void expectChar(char c) throws ParseException { - skipWhitespace(); - boolean hasNext = hasNext(); - if(hasNext && currentChar() == c) { - index++; - return; - } - throw parseException("expected '" + c + "' but got " + (hasNext ? "'" + currentChar() + "'" : "EOF")); - } - - public void skipWhitespace() { - while(hasNext() && Character.isWhitespace(currentChar())) { - index++; - } - } - - public boolean hasNext() { - return index < value.length(); - } - - public boolean hasCharsLeft(int num) { - return this.index + num < value.length(); - } - - public char currentChar() { - return value.charAt(index); - } - - public char next() { - return value.charAt(index++); - } - - public void skip(int offset) { - index += offset; - } - - public char lookAhead(int offset) { - return value.charAt(index + offset); - } - - public ParseException parseException(String msg) { - return new ParseException(msg, value, index); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/Chunk.java b/src/main/java/com/volmit/iris/util/nbt/mca/Chunk.java deleted file mode 100644 index 3eba24125..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/Chunk.java +++ /dev/null @@ -1,653 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.nbt.io.NBTDeserializer; -import com.volmit.iris.util.nbt.io.NBTSerializer; -import com.volmit.iris.util.nbt.io.NamedTag; -import com.volmit.iris.util.nbt.mca.palette.MCABiomeContainer; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.ListTag; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.RandomAccessFile; - -import static com.volmit.iris.util.nbt.mca.LoadFlags.*; - -public class Chunk { - public static final int DEFAULT_DATA_VERSION = 2730; - private final KMap sections = new KMap<>(); - private boolean partial; - private int lastMCAUpdate; - private CompoundTag data; - private int dataVersion; - private long lastUpdate; - private long inhabitedTime; - private MCABiomeContainer biomes; - private CompoundTag heightMaps; - private CompoundTag carvingMasks; - private ListTag entities; - private ListTag tileEntities; - private ListTag tileTicks; - private ListTag liquidTicks; - private ListTag> lights; - private ListTag> liquidsToBeTicked; - private ListTag> toBeTicked; - private ListTag> postProcessing; - private String status; - private CompoundTag structures; - - Chunk(int lastMCAUpdate) { - this.lastMCAUpdate = lastMCAUpdate; - } - - /** - * Create a new chunk based on raw base data from a region file. - * - * @param data - * The raw base data to be used. - */ - public Chunk(CompoundTag data) { - this.data = data; - initReferences(ALL_DATA); - setStatus("full"); - } - - public static Chunk newChunk() { - Chunk c = new Chunk(0); - c.dataVersion = DEFAULT_DATA_VERSION; - c.data = new CompoundTag(); - c.biomes = INMS.get().newBiomeContainer(0, 256); - c.data.put("Level", defaultLevel()); - c.status = "full"; - return c; - } - - private static CompoundTag defaultLevel() { - CompoundTag level = new CompoundTag(); - level.putString("Status", "full"); - level.putString("Generator", "Iris Headless " + Iris.instance.getDescription().getVersion()); - return level; - } - - private void initReferences(long loadFlags) { - if(data == null) { - throw new NullPointerException("data cannot be null"); - } - CompoundTag level; - if((level = data.getCompoundTag("Level")) == null) { - throw new IllegalArgumentException("data does not contain \"Level\" tag"); - } - dataVersion = data.getInt("DataVersion"); - inhabitedTime = level.getLong("InhabitedTime"); - lastUpdate = level.getLong("LastUpdate"); - if((loadFlags & BIOMES) != 0) { - biomes = INMS.get().newBiomeContainer(0, 256, level.getIntArray("Biomes")); - } - if((loadFlags & HEIGHTMAPS) != 0) { - heightMaps = level.getCompoundTag("Heightmaps"); - } - if((loadFlags & CARVING_MASKS) != 0) { - carvingMasks = level.getCompoundTag("CarvingMasks"); - } - if((loadFlags & ENTITIES) != 0) { - entities = level.containsKey("Entities") ? level.getListTag("Entities").asCompoundTagList() : null; - } - if((loadFlags & TILE_ENTITIES) != 0) { - tileEntities = level.containsKey("TileEntities") ? level.getListTag("TileEntities").asCompoundTagList() : null; - } - if((loadFlags & TILE_TICKS) != 0) { - tileTicks = level.containsKey("TileTicks") ? level.getListTag("TileTicks").asCompoundTagList() : null; - } - if((loadFlags & LIQUID_TICKS) != 0) { - liquidTicks = level.containsKey("LiquidTicks") ? level.getListTag("LiquidTicks").asCompoundTagList() : null; - } - if((loadFlags & LIGHTS) != 0) { - lights = level.containsKey("Lights") ? level.getListTag("Lights").asListTagList() : null; - } - if((loadFlags & LIQUIDS_TO_BE_TICKED) != 0) { - liquidsToBeTicked = level.containsKey("LiquidsToBeTicked") ? level.getListTag("LiquidsToBeTicked").asListTagList() : null; - } - if((loadFlags & TO_BE_TICKED) != 0) { - toBeTicked = level.containsKey("ToBeTicked") ? level.getListTag("ToBeTicked").asListTagList() : null; - } - if((loadFlags & POST_PROCESSING) != 0) { - postProcessing = level.containsKey("PostProcessing") ? level.getListTag("PostProcessing").asListTagList() : null; - } - status = level.getString("Status"); - if((loadFlags & STRUCTURES) != 0) { - structures = level.getCompoundTag("Structures"); - } - if((loadFlags & (BLOCK_LIGHTS | BLOCK_STATES | SKY_LIGHT)) != 0 && level.containsKey("Sections")) { - for(CompoundTag section : level.getListTag("Sections").asCompoundTagList()) { - int sectionIndex = section.getByte("Y"); - if(sectionIndex > 15 || sectionIndex < 0) { - continue; - } - Section newSection = new Section(section, dataVersion, loadFlags); - if(newSection.isEmpty()) { - continue; - } - sections.put(sectionIndex, newSection); - } - } - - // If we haven't requested the full set of data we can drop the underlying raw data to let the GC handle it. - if(loadFlags != ALL_DATA) { - data = null; - partial = true; - } else { - partial = false; - } - } - - /** - * Serializes this chunk to a RandomAccessFile. - * - * @param raf - * The RandomAccessFile to be written to. - * @param xPos - * The x-coordinate of the chunk. - * @param zPos - * The z-coodrinate of the chunk. - * @return The amount of bytes written to the RandomAccessFile. - * @throws UnsupportedOperationException - * When something went wrong during writing. - * @throws IOException - * When something went wrong during writing. - */ - public int serialize(RandomAccessFile raf, int xPos, int zPos) throws IOException { - if(partial) { - throw new UnsupportedOperationException("Partially loaded chunks cannot be serialized"); - } - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - try(BufferedOutputStream nbtOut = new BufferedOutputStream(CompressionType.ZLIB.compress(baos))) { - new NBTSerializer(false).toStream(new NamedTag(null, updateHandle(xPos, zPos)), nbtOut); - } - - byte[] rawData = baos.toByteArray(); - raf.writeInt(rawData.length + 1); // including the byte to store the compression type - raf.writeByte(CompressionType.ZLIB.getID()); - raf.write(rawData); - return rawData.length + 5; - } - - /** - * Reads chunk data from a RandomAccessFile. The RandomAccessFile must already be at the correct position. - * - * @param raf - * The RandomAccessFile to read the chunk data from. - * @throws IOException - * When something went wrong during reading. - */ - public void deserialize(RandomAccessFile raf) throws IOException { - deserialize(raf, ALL_DATA); - } - - /** - * Reads chunk data from a RandomAccessFile. The RandomAccessFile must already be at the correct position. - * - * @param raf - * The RandomAccessFile to read the chunk data from. - * @param loadFlags - * A logical or of {@link LoadFlags} constants indicating what data should be loaded - * @throws IOException - * When something went wrong during reading. - */ - public void deserialize(RandomAccessFile raf, long loadFlags) throws IOException { - byte compressionTypeByte = raf.readByte(); - CompressionType compressionType = CompressionType.getFromID(compressionTypeByte); - if(compressionType == null) { - throw new IOException("invalid compression type " + compressionTypeByte); - } - BufferedInputStream dis = new BufferedInputStream(compressionType.decompress(new FileInputStream(raf.getFD()))); - NamedTag tag = new NBTDeserializer(false).fromStream(dis); - if(tag != null && tag.getTag() instanceof CompoundTag) { - data = (CompoundTag) tag.getTag(); - initReferences(loadFlags); - } else { - throw new IOException("invalid data tag: " + (tag == null ? "null" : tag.getClass().getName())); - } - } - - /** - * Fetches a biome id at a specific block in this chunk. - * The coordinates can be absolute coordinates or relative to the region or chunk. - * - * @param blockX - * The x-coordinate of the block. - * @param blockY - * The y-coordinate of the block. - * @param blockZ - * The z-coordinate of the block. - * @return The biome id or -1 if the biomes are not correctly initialized. - */ - public synchronized int getBiomeAt(int blockX, int blockY, int blockZ) { - return biomes.getBiome(blockX, blockY, blockZ); - } - - /** - * Sets a biome id at a specific block column. - * The coordinates can be absolute coordinates or relative to the region or chunk. - * - * @param blockX - * The x-coordinate of the block column. - * @param blockZ - * The z-coordinate of the block column. - * @param biomeID - * The biome id to be set. - * When set to a negative number, Minecraft will replace it with the block column's default biome. - */ - public synchronized void setBiomeAt(int blockX, int blockY, int blockZ, int biomeID) { - biomes.setBiome(blockX, blockY, blockZ, biomeID); - } - - int getBiomeIndex(int biomeX, int biomeY, int biomeZ) { - return biomeY * 64 + biomeZ * 4 + biomeX; - } - - public CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { - int s = MCAUtil.blockToChunk(blockY); - - Section section = sections.get(s); - if(section == null) { - return null; - } - return section.getBlockStateAt(blockX, blockY, blockZ); - } - - /** - * Sets a block state at a specific location. - * The block coordinates can be absolute or relative to the region or chunk. - * - * @param blockX - * The x-coordinate of the block. - * @param blockY - * The y-coordinate of the block. - * @param blockZ - * The z-coordinate of the block. - * @param state - * The block state to be set. - * @param cleanup - * When true, it will cleanup all palettes of this chunk. - * This option should only be used moderately to avoid unnecessary recalculation of the palette indices. - * Recalculating the Palette should only be executed once right before saving the Chunk to file. - */ - public void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { - int sectionIndex = MCAUtil.blockToChunk(blockY); - - Section section = sections.get(sectionIndex); - if(section == null) { - section = Section.newSection(); - sections.put(sectionIndex, section); - } - section.setBlockStateAt(blockX, blockY, blockZ, state, cleanup); - } - - /** - * @return The DataVersion of this chunk. - */ - public int getDataVersion() { - return dataVersion; - } - - /** - * Sets the DataVersion of this chunk. This does not check if the data of this chunk conforms - * to that DataVersion, that is the responsibility of the developer. - * - * @param dataVersion - * The DataVersion to be set. - */ - public void setDataVersion(int dataVersion) { - this.dataVersion = dataVersion; - } - - /** - * @return The timestamp when this region file was last updated in seconds since 1970-01-01. - */ - public int getLastMCAUpdate() { - return lastMCAUpdate; - } - - /** - * Sets the timestamp when this region file was last updated in seconds since 1970-01-01. - * - * @param lastMCAUpdate - * The time in seconds since 1970-01-01. - */ - public void setLastMCAUpdate(int lastMCAUpdate) { - this.lastMCAUpdate = lastMCAUpdate; - } - - /** - * @return The generation station of this chunk. - */ - public String getStatus() { - return status; - } - - /** - * Sets the generation status of this chunk. - * - * @param status - * The generation status of this chunk. - */ - public void setStatus(String status) { - this.status = status; - } - - /** - * Fetches the section at the given y-coordinate. - * - * @param sectionY - * The y-coordinate of the section in this chunk ranging from 0 to 15. - * @return The Section. - */ - public Section getSection(int sectionY) { - return sections.get(sectionY); - } - - /** - * Sets a section at a givesn y-coordinate - * - * @param sectionY - * The y-coordinate of the section in this chunk ranging from 0 to 15. - * @param section - * The section to be set. - */ - public void setSection(int sectionY, Section section) { - sections.put(sectionY, section); - } - - /** - * @return The timestamp when this chunk was last updated as a UNIX timestamp. - */ - public long getLastUpdate() { - return lastUpdate; - } - - /** - * Sets the time when this chunk was last updated as a UNIX timestamp. - * - * @param lastUpdate - * The UNIX timestamp. - */ - public void setLastUpdate(long lastUpdate) { - this.lastUpdate = lastUpdate; - } - - /** - * @return The cumulative amount of time players have spent in this chunk in ticks. - */ - public long getInhabitedTime() { - return inhabitedTime; - } - - /** - * Sets the cumulative amount of time players have spent in this chunk in ticks. - * - * @param inhabitedTime - * The time in ticks. - */ - public void setInhabitedTime(long inhabitedTime) { - this.inhabitedTime = inhabitedTime; - } - - /** - * @return The height maps of this chunk. - */ - public CompoundTag getHeightMaps() { - return heightMaps; - } - - /** - * Sets the height maps of this chunk. - * - * @param heightMaps - * The height maps. - */ - public void setHeightMaps(CompoundTag heightMaps) { - this.heightMaps = heightMaps; - } - - /** - * @return The carving masks of this chunk. - */ - public CompoundTag getCarvingMasks() { - return carvingMasks; - } - - /** - * Sets the carving masks of this chunk. - * - * @param carvingMasks - * The carving masks. - */ - public void setCarvingMasks(CompoundTag carvingMasks) { - this.carvingMasks = carvingMasks; - } - - /** - * @return The entities of this chunk. - */ - public ListTag getEntities() { - return entities; - } - - /** - * Sets the entities of this chunk. - * - * @param entities - * The entities. - */ - public void setEntities(ListTag entities) { - this.entities = entities; - } - - /** - * @return The tile entities of this chunk. - */ - public ListTag getTileEntities() { - return tileEntities; - } - - /** - * Sets the tile entities of this chunk. - * - * @param tileEntities - * The tile entities of this chunk. - */ - public void setTileEntities(ListTag tileEntities) { - this.tileEntities = tileEntities; - } - - /** - * @return The tile ticks of this chunk. - */ - public ListTag getTileTicks() { - return tileTicks; - } - - /** - * Sets the tile ticks of this chunk. - * - * @param tileTicks - * Thee tile ticks. - */ - public void setTileTicks(ListTag tileTicks) { - this.tileTicks = tileTicks; - } - - /** - * @return The liquid ticks of this chunk. - */ - public ListTag getLiquidTicks() { - return liquidTicks; - } - - /** - * Sets the liquid ticks of this chunk. - * - * @param liquidTicks - * The liquid ticks. - */ - public void setLiquidTicks(ListTag liquidTicks) { - this.liquidTicks = liquidTicks; - } - - /** - * @return The light sources in this chunk. - */ - public ListTag> getLights() { - return lights; - } - - /** - * Sets the light sources in this chunk. - * - * @param lights - * The light sources. - */ - public void setLights(ListTag> lights) { - this.lights = lights; - } - - /** - * @return THe liquids to be ticked in this chunk. - */ - public ListTag> getLiquidsToBeTicked() { - return liquidsToBeTicked; - } - - /** - * Sets the liquids to be ticked in this chunk. - * - * @param liquidsToBeTicked - * The liquids to be ticked. - */ - public void setLiquidsToBeTicked(ListTag> liquidsToBeTicked) { - this.liquidsToBeTicked = liquidsToBeTicked; - } - - /** - * @return Stuff to be ticked in this chunk. - */ - public ListTag> getToBeTicked() { - return toBeTicked; - } - - /** - * Sets stuff to be ticked in this chunk. - * - * @param toBeTicked - * The stuff to be ticked. - */ - public void setToBeTicked(ListTag> toBeTicked) { - this.toBeTicked = toBeTicked; - } - - /** - * @return Things that are in post processing in this chunk. - */ - public ListTag> getPostProcessing() { - return postProcessing; - } - - /** - * Sets things to be post processed in this chunk. - * - * @param postProcessing - * The things to be post processed. - */ - public void setPostProcessing(ListTag> postProcessing) { - this.postProcessing = postProcessing; - } - - /** - * @return Data about structures in this chunk. - */ - public CompoundTag getStructures() { - return structures; - } - - /** - * Sets data about structures in this chunk. - * - * @param structures - * The data about structures. - */ - public void setStructures(CompoundTag structures) { - this.structures = structures; - } - - int getBlockIndex(int blockX, int blockZ) { - return (blockZ & 0xF) * 16 + (blockX & 0xF); - } - - public void cleanupPalettesAndBlockStates() { - for(Section section : sections.values()) { - if(section != null) { - section.cleanupPaletteAndBlockStates(); - } - } - } - - public CompoundTag updateHandle(int xPos, int zPos) { - data.putInt("DataVersion", dataVersion); - CompoundTag level = data.getCompoundTag("Level"); - level.putInt("xPos", xPos); - level.putInt("zPos", zPos); - level.putLong("LastUpdate", lastUpdate); - level.putLong("InhabitedTime", inhabitedTime); - level.putIntArray("Biomes", biomes.getData()); - if(heightMaps != null) level.put("Heightmaps", heightMaps); - if(carvingMasks != null) level.put("CarvingMasks", carvingMasks); - if(entities != null) level.put("Entities", entities); - if(tileEntities != null) level.put("TileEntities", tileEntities); - if(tileTicks != null) level.put("TileTicks", tileTicks); - if(liquidTicks != null) level.put("LiquidTicks", liquidTicks); - if(lights != null) level.put("Lights", lights); - if(liquidsToBeTicked != null) level.put("LiquidsToBeTicked", liquidsToBeTicked); - if(toBeTicked != null) level.put("ToBeTicked", toBeTicked); - if(postProcessing != null) level.put("PostProcessing", postProcessing); - level.putString("Status", status); - if(structures != null) level.put("Structures", structures); - ListTag sections = new ListTag<>(CompoundTag.class); - - for(int i : this.sections.keySet()) { - if(this.sections.get(i) != null) { - sections.add(this.sections.get(i).updateHandle(i)); - } - } - - level.put("Sections", sections); - return data; - } - - public int sectionCount() { - return sections.size(); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/CompressionType.java b/src/main/java/com/volmit/iris/util/nbt/mca/CompressionType.java deleted file mode 100644 index 5c1e6ed3a..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/CompressionType.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; -import java.util.zip.InflaterInputStream; - -public enum CompressionType { - - NONE(0, t -> t, t -> t), - GZIP(1, GZIPOutputStream::new, GZIPInputStream::new), - ZLIB(2, DeflaterOutputStream::new, InflaterInputStream::new); - - private final byte id; - private final ExceptionFunction compressor; - private final ExceptionFunction decompressor; - - CompressionType(int id, - ExceptionFunction compressor, - ExceptionFunction decompressor) { - this.id = (byte) id; - this.compressor = compressor; - this.decompressor = decompressor; - } - - public static CompressionType getFromID(byte id) { - for(CompressionType c : CompressionType.values()) { - if(c.id == id) { - return c; - } - } - return null; - } - - public byte getID() { - return id; - } - - public OutputStream compress(OutputStream out) throws IOException { - return compressor.accept(out); - } - - public InputStream decompress(InputStream in) throws IOException { - return decompressor.accept(in); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/ExceptionFunction.java b/src/main/java/com/volmit/iris/util/nbt/mca/ExceptionFunction.java deleted file mode 100644 index 3138bc33d..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/ExceptionFunction.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca; - -@FunctionalInterface -public interface ExceptionFunction { - - R accept(T t) throws E; -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/LoadFlags.java b/src/main/java/com/volmit/iris/util/nbt/mca/LoadFlags.java deleted file mode 100644 index 234c6156d..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/LoadFlags.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca; - -public class LoadFlags { - - public static final long BIOMES = 0x0001; - public static final long HEIGHTMAPS = 0x0002; - public static final long CARVING_MASKS = 0x0004; - public static final long ENTITIES = 0x0008; - public static final long TILE_ENTITIES = 0x0010; - public static final long TILE_TICKS = 0x0040; - public static final long LIQUID_TICKS = 0x0080; - public static final long TO_BE_TICKED = 0x0100; - public static final long POST_PROCESSING = 0x0200; - public static final long STRUCTURES = 0x0400; - public static final long BLOCK_LIGHTS = 0x0800; - public static final long BLOCK_STATES = 0x1000; - public static final long SKY_LIGHT = 0x2000; - public static final long LIGHTS = 0x4000; - public static final long LIQUIDS_TO_BE_TICKED = 0x8000; - - public static final long ALL_DATA = 0xffffffffffffffffL; - - -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/MCAFile.java b/src/main/java/com/volmit/iris/util/nbt/mca/MCAFile.java deleted file mode 100644 index 8504bd4bb..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/MCAFile.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.Position2; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.scheduling.J; - -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicReferenceArray; - -@SuppressWarnings("ALL") -public class MCAFile { - - /** - * The default chunk data version used when no custom version is supplied. - */ - public static final int DEFAULT_DATA_VERSION = 1628; - - private final int regionX; - private final int regionZ; - private AtomicReferenceArray chunks; - private ConcurrentLinkedQueue afterSave; - - /** - * MCAFile represents a world save file used by Minecraft to store world - * data on the hard drive. - * This constructor needs the x- and z-coordinates of the stored region, - * which can usually be taken from the file name {@code r.x.z.mca} - * - * @param regionX - * The x-coordinate of this region. - * @param regionZ - * The z-coordinate of this region. - */ - public MCAFile(int regionX, int regionZ) { - this.regionX = regionX; - this.regionZ = regionZ; - afterSave = new ConcurrentLinkedQueue<>(); - } - - /** - * Calculates the index of a chunk from its x- and z-coordinates in this region. - * This works with absolute and relative coordinates. - * - * @param chunkX - * The x-coordinate of the chunk. - * @param chunkZ - * The z-coordinate of the chunk. - * @return The index of this chunk. - */ - public static int getChunkIndex(int chunkX, int chunkZ) { - return (chunkX & 0x1F) + (chunkZ & 0x1F) * 32; - } - - /** - * Reads an .mca file from a {@code RandomAccessFile} into this object. - * This method does not perform any cleanups on the data. - * - * @param raf - * The {@code RandomAccessFile} to read from. - * @throws IOException - * If something went wrong during deserialization. - */ - public void deserialize(RandomAccessFile raf) throws IOException { - deserialize(raf, LoadFlags.ALL_DATA); - } - - /** - * Reads an .mca file from a {@code RandomAccessFile} into this object. - * This method does not perform any cleanups on the data. - * - * @param raf - * The {@code RandomAccessFile} to read from. - * @param loadFlags - * A logical or of {@link LoadFlags} constants indicating what data should be loaded - * @throws IOException - * If something went wrong during deserialization. - */ - public void deserialize(RandomAccessFile raf, long loadFlags) throws IOException { - chunks = new AtomicReferenceArray<>(1024); - for(int i = 0; i < 1024; i++) { - raf.seek(i * 4); - int offset = raf.read() << 16; - offset |= (raf.read() & 0xFF) << 8; - offset |= raf.read() & 0xFF; - if(raf.readByte() == 0) { - continue; - } - raf.seek(4096 + i * 4); - int timestamp = raf.readInt(); - Chunk chunk = new Chunk(timestamp); - raf.seek(4096L * offset + 4); //+4: skip data size - chunk.deserialize(raf, loadFlags); - chunks.set(i, chunk); - } - } - - public KList samplePositions(RandomAccessFile raf) throws IOException { - KList p2 = new KList<>(); - chunks = new AtomicReferenceArray<>(1024); - int x = 0; - int z = 0; - for(int i = 0; i < 1024; i++) { - x++; - z++; - - raf.seek(i * 4); - int offset = raf.read() << 16; - offset |= (raf.read() & 0xFF) << 8; - offset |= raf.read() & 0xFF; - if(raf.readByte() == 0) { - continue; - } - p2.add(new Position2(x & 31, (z / 31) & 31)); - } - return p2; - } - - public AtomicReferenceArray getChunks() { - return chunks; - } - - /** - * Calls {@link MCAFile#serialize(RandomAccessFile, boolean)} without updating any timestamps. - * - * @param raf - * The {@code RandomAccessFile} to writeNodeData to. - * @return The amount of chunks written to the file. - * @throws IOException - * If something went wrong during serialization. - * @see MCAFile#serialize(RandomAccessFile, boolean) - */ - public int serialize(RandomAccessFile raf) throws IOException { - return serialize(raf, false); - } - - /** - * Serializes this object to an .mca file. - * This method does not perform any cleanups on the data. - * - * @param raf - * The {@code RandomAccessFile} to writeNodeData to. - * @param changeLastUpdate - * Whether it should update all timestamps that show - * when this file was last updated. - * @return The amount of chunks written to the file. - * @throws IOException - * If something went wrong during serialization. - */ - public int serialize(RandomAccessFile raf, boolean changeLastUpdate) throws IOException { - int globalOffset = 2; - int lastWritten = 0; - int timestamp = (int) (System.currentTimeMillis() / 1000L); - int chunksWritten = 0; - int chunkXOffset = MCAUtil.regionToChunk(regionX); - int chunkZOffset = MCAUtil.regionToChunk(regionZ); - - if(chunks == null) { - return 0; - } - - for(int cx = 0; cx < 32; cx++) { - for(int cz = 0; cz < 32; cz++) { - int index = getChunkIndex(cx, cz); - Chunk chunk = chunks.get(index); - if(chunk == null) { - continue; - } - raf.seek(4096L * globalOffset); - lastWritten = chunk.serialize(raf, chunkXOffset + cx, chunkZOffset + cz); - - if(lastWritten == 0) { - continue; - } - - chunksWritten++; - - int sectors = (lastWritten >> 12) + (lastWritten % 4096 == 0 ? 0 : 1); - - raf.seek(index * 4L); - raf.writeByte(globalOffset >>> 16); - raf.writeByte(globalOffset >> 8 & 0xFF); - raf.writeByte(globalOffset & 0xFF); - raf.writeByte(sectors); - - // writeNodeData timestamp - raf.seek(index * 4L + 4096); - raf.writeInt(changeLastUpdate ? timestamp : chunk.getLastMCAUpdate()); - - globalOffset += sectors; - } - } - - // padding - if(lastWritten % 4096 != 0) { - raf.seek(globalOffset * 4096L - 1); - raf.write(0); - } - - J.a(() -> { - afterSave.forEach(i -> i.run()); - }, 20); - - return chunksWritten; - } - - /** - * Set a specific Chunk at a specific index. The index must be in range of 0 - 1023. - * - * @param index - * The index of the Chunk. - * @param chunk - * The Chunk to be set. - * @throws IndexOutOfBoundsException - * If index is not in the range. - */ - public void setChunk(int index, Chunk chunk) { - checkIndex(index); - if(chunks == null) { - chunks = new AtomicReferenceArray<>(1024); - } - chunks.set(index, chunk); - } - - /** - * Set a specific Chunk at a specific chunk location. - * The x- and z-value can be absolute chunk coordinates or they can be relative to the region origin. - * - * @param chunkX - * The x-coordinate of the Chunk. - * @param chunkZ - * The z-coordinate of the Chunk. - * @param chunk - * The chunk to be set. - */ - public void setChunk(int chunkX, int chunkZ, Chunk chunk) { - setChunk(getChunkIndex(chunkX, chunkZ), chunk); - } - - /** - * Returns the chunk data of a chunk at a specific index in this file. - * - * @param index - * The index of the chunk in this file. - * @return The chunk data. - */ - public Chunk getChunk(int index) { - checkIndex(index); - if(chunks == null) { - return null; - } - return chunks.get(index); - } - - /** - * Returns the chunk data of a chunk in this file. - * - * @param chunkX - * The x-coordinate of the chunk. - * @param chunkZ - * The z-coordinate of the chunk. - * @return The chunk data. - */ - public Chunk getChunk(int chunkX, int chunkZ) { - return getChunk(getChunkIndex(chunkX, chunkZ)); - } - - public boolean hasChunk(int chunkX, int chunkZ) { - return getChunk(chunkX, chunkZ) != null; - } - - private int checkIndex(int index) { - if(index < 0 || index > 1023) { - throw new IndexOutOfBoundsException(); - } - return index; - } - - private Chunk createChunkIfMissing(int blockX, int blockZ) { - int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); - Chunk chunk = getChunk(chunkX, chunkZ); - if(chunk == null) { - chunk = Chunk.newChunk(); - setChunk(getChunkIndex(chunkX, chunkZ), chunk); - } - return chunk; - } - - public void setBiomeAt(int blockX, int blockY, int blockZ, int biomeID) { - createChunkIfMissing(blockX, blockZ).setBiomeAt(blockX, blockY, blockZ, biomeID); - } - - /** - * Fetches the biome id at a specific block. - * - * @param blockX - * The x-coordinate of the block. - * @param blockY - * The y-coordinate of the block. - * @param blockZ - * The z-coordinate of the block. - * @return The biome id if the chunk exists and the chunk has biomes, otherwise -1. - */ - public int getBiomeAt(int blockX, int blockY, int blockZ) { - int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); - Chunk chunk = getChunk(getChunkIndex(chunkX, chunkZ)); - if(chunk == null) { - return -1; - } - return chunk.getBiomeAt(blockX, blockY, blockZ); - } - - /** - * Set a block state at a specific block location. - * The block coordinates can be absolute coordinates or they can be relative to the region. - * - * @param blockX - * The x-coordinate of the block. - * @param blockY - * The y-coordinate of the block. - * @param blockZ - * The z-coordinate of the block. - * @param state - * The block state to be set. - * @param cleanup - * Whether the Palette and the BLockStates should be recalculated after adding the block state. - */ - public void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { - createChunkIfMissing(blockX, blockZ).setBlockStateAt(blockX, blockY, blockZ, state, cleanup); - } - - /** - * Fetches a block state at a specific block location. - * The block coordinates can be absolute coordinates or they can be relative to the region. - * - * @param blockX - * The x-coordinate of the block. - * @param blockY - * The y-coordinate of the block. - * @param blockZ - * The z-coordinate of the block. - * @return The block state or null if the chunk or the section do not exist. - */ - public CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { - int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); - Chunk chunk = getChunk(chunkX, chunkZ); - if(chunk == null) { - return null; - } - return chunk.getBlockStateAt(blockX, blockY, blockZ); - } - - public void afterSave(Runnable o) { - afterSave.add(o); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/MCAUtil.java b/src/main/java/com/volmit/iris/util/nbt/mca/MCAUtil.java deleted file mode 100644 index ec3472cf5..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/MCAUtil.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.Position2; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Provides main and utility functions to read and writeNodeData .mca files and - * to convert block, chunk and region coordinates. - */ -public final class MCAUtil { - - private static final Pattern mcaFilePattern = Pattern.compile("^.*r\\.(?-?\\d+)\\.(?-?\\d+)\\.mca$"); - - private MCAUtil() { - } - - /** - * @param file - * The file to read the data from. - * @return An in-memory representation of the MCA file with decompressed chunk data. - * @throws IOException - * if something during deserialization goes wrong. - * @see MCAUtil#read(File) - */ - public static MCAFile read(String file) throws IOException { - return read(new File(file), LoadFlags.ALL_DATA); - } - - /** - * Reads an MCA file and loads all of its chunks. - * - * @param file - * The file to read the data from. - * @return An in-memory representation of the MCA file with decompressed chunk data. - * @throws IOException - * if something during deserialization goes wrong. - */ - public static MCAFile read(File file) throws IOException { - return read(file, LoadFlags.ALL_DATA); - } - - /** - * @param file - * The file to read the data from. - * @param loadFlags - * A logical or of {@link LoadFlags} constants indicating what data should be loaded - * @return An in-memory representation of the MCA file with decompressed chunk data. - * @throws IOException - * if something during deserialization goes wrong. - * @see MCAUtil#read(File) - */ - public static MCAFile read(String file, long loadFlags) throws IOException { - return read(new File(file), loadFlags); - } - - /** - * Reads an MCA file and loads all of its chunks. - * - * @param file - * The file to read the data from. - * @param loadFlags - * A logical or of {@link LoadFlags} constants indicating what data should be loaded - * @return An in-memory representation of the MCA file with decompressed chunk data - * @throws IOException - * if something during deserialization goes wrong. - */ - public static MCAFile read(File file, long loadFlags) throws IOException { - MCAFile mcaFile = newMCAFile(file); - try(RandomAccessFile raf = new RandomAccessFile(file, "r")) { - mcaFile.deserialize(raf, loadFlags); - return mcaFile; - } - } - - public static KList sampleChunkPositions(File file) throws IOException { - MCAFile mcaFile = newMCAFile(file); - try(RandomAccessFile raf = new RandomAccessFile(file, "r")) { - return mcaFile.samplePositions(raf); - } - } - - /** - * Calls {@link MCAUtil#write(MCAFile, File, boolean)} without changing the timestamps. - * - * @param file - * The file to writeNodeData to. - * @param mcaFile - * The data of the MCA file to writeNodeData. - * @return The amount of chunks written to the file. - * @throws IOException - * If something goes wrong during serialization. - * @see MCAUtil#write(MCAFile, File, boolean) - */ - public static int write(MCAFile mcaFile, String file) throws IOException { - return write(mcaFile, new File(file), false); - } - - /** - * Calls {@link MCAUtil#write(MCAFile, File, boolean)} without changing the timestamps. - * - * @param file - * The file to writeNodeData to. - * @param mcaFile - * The data of the MCA file to writeNodeData. - * @return The amount of chunks written to the file. - * @throws IOException - * If something goes wrong during serialization. - * @see MCAUtil#write(MCAFile, File, boolean) - */ - public static int write(MCAFile mcaFile, File file) throws IOException { - return write(mcaFile, file, false); - } - - /** - * @param file - * The file to writeNodeData to. - * @param mcaFile - * The data of the MCA file to writeNodeData. - * @param changeLastUpdate - * Whether to adjust the timestamps of when the file was saved. - * @return The amount of chunks written to the file. - * @throws IOException - * If something goes wrong during serialization. - * @see MCAUtil#write(MCAFile, File, boolean) - */ - public static int write(MCAFile mcaFile, String file, boolean changeLastUpdate) throws IOException { - return write(mcaFile, new File(file), changeLastUpdate); - } - - /** - * Writes an {@code MCAFile} object to disk. It optionally adjusts the timestamps - * when the file was last saved to the current date and time or leaves them at - * the value set by either loading an already existing MCA file or setting them manually.
- * If the file already exists, it is completely overwritten by the new file (no modification). - * - * @param file - * The file to writeNodeData to. - * @param mcaFile - * The data of the MCA file to writeNodeData. - * @param changeLastUpdate - * Whether to adjust the timestamps of when the file was saved. - * @return The amount of chunks written to the file. - * @throws IOException - * If something goes wrong during serialization. - */ - public static int write(MCAFile mcaFile, File file, boolean changeLastUpdate) throws IOException { - if(mcaFile == null) { - return 0; - } - - File to = file; - if(file.exists()) { - to = File.createTempFile(to.getName(), null); - } - int chunks; - try(RandomAccessFile raf = new RandomAccessFile(to, "rw")) { - chunks = mcaFile.serialize(raf, changeLastUpdate); - } - - if(chunks > 0 && to != file) { - Files.move(to.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); - } - - return chunks; - } - - /** - * Turns the chunks coordinates into region coordinates and calls - * {@link MCAUtil#createNameFromRegionLocation(int, int)} - * - * @param chunkX - * The x-value of the location of the chunk. - * @param chunkZ - * The z-value of the location of the chunk. - * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" - */ - public static String createNameFromChunkLocation(int chunkX, int chunkZ) { - return createNameFromRegionLocation(chunkToRegion(chunkX), chunkToRegion(chunkZ)); - } - - /** - * Turns the block coordinates into region coordinates and calls - * {@link MCAUtil#createNameFromRegionLocation(int, int)} - * - * @param blockX - * The x-value of the location of the block. - * @param blockZ - * The z-value of the location of the block. - * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" - */ - public static String createNameFromBlockLocation(int blockX, int blockZ) { - return createNameFromRegionLocation(blockToRegion(blockX), blockToRegion(blockZ)); - } - - /** - * Creates a filename string from provided chunk coordinates. - * - * @param regionX - * The x-value of the location of the region. - * @param regionZ - * The z-value of the location of the region. - * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" - */ - public static String createNameFromRegionLocation(int regionX, int regionZ) { - return "r." + regionX + "." + regionZ + ".mca"; - } - - /** - * Turns a block coordinate value into a chunk coordinate value. - * - * @param block - * The block coordinate value. - * @return The chunk coordinate value. - */ - public static int blockToChunk(int block) { - return block >> 4; - } - - /** - * Turns a block coordinate value into a region coordinate value. - * - * @param block - * The block coordinate value. - * @return The region coordinate value. - */ - public static int blockToRegion(int block) { - return block >> 9; - } - - /** - * Turns a chunk coordinate value into a region coordinate value. - * - * @param chunk - * The chunk coordinate value. - * @return The region coordinate value. - */ - public static int chunkToRegion(int chunk) { - return chunk >> 5; - } - - /** - * Turns a region coordinate value into a chunk coordinate value. - * - * @param region - * The region coordinate value. - * @return The chunk coordinate value. - */ - public static int regionToChunk(int region) { - return region << 5; - } - - /** - * Turns a region coordinate value into a block coordinate value. - * - * @param region - * The region coordinate value. - * @return The block coordinate value. - */ - public static int regionToBlock(int region) { - return region << 9; - } - - /** - * Turns a chunk coordinate value into a block coordinate value. - * - * @param chunk - * The chunk coordinate value. - * @return The block coordinate value. - */ - public static int chunkToBlock(int chunk) { - return chunk << 4; - } - - public static MCAFile newMCAFile(File file) { - Matcher m = mcaFilePattern.matcher(file.getName()); - if(m.find()) { - return new MCAFile(Integer.parseInt(m.group("regionX")), Integer.parseInt(m.group("regionZ"))); - } - throw new IllegalArgumentException("invalid mca file name: " + file.getName()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/NBTWorld.java b/src/main/java/com/volmit/iris/util/nbt/mca/NBTWorld.java deleted file mode 100644 index a8c4adf4a..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/NBTWorld.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.data.B; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.StringTag; -import com.volmit.iris.util.parallel.HyperLock; -import org.bukkit.NamespacedKey; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - -import java.io.File; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; - -public class NBTWorld { - private static final BlockData AIR = B.get("AIR"); - private static final Map blockDataCache = new KMap<>(); - private static final Function BLOCK_DATA_COMPUTE = (blockData) -> { - CompoundTag s = new CompoundTag(); - String data = blockData.getAsString(true); - NamespacedKey key = blockData.getMaterial().getKey(); - s.putString("Name", key.getNamespace() + ":" + key.getKey()); - - if(data.contains("[")) { - String raw = data.split("\\Q[\\E")[1].replaceAll("\\Q]\\E", ""); - CompoundTag props = new CompoundTag(); - if(raw.contains(",")) { - for(String i : raw.split("\\Q,\\E")) { - String[] m = i.split("\\Q=\\E"); - String k = m[0]; - String v = m[1]; - props.put(k, new StringTag(v)); - } - } else { - String[] m = raw.split("\\Q=\\E"); - String k = m[0]; - String v = m[1]; - props.put(k, new StringTag(v)); - } - s.put("Properties", props); - } - - return s; - }; - private static final Map biomeIds = computeBiomeIDs(); - private final KMap loadedRegions; - private final HyperLock hyperLock = new HyperLock(); - private final KMap lastUse; - private final File worldFolder; - private final ExecutorService saveQueue; - - public NBTWorld(File worldFolder) { - this.worldFolder = worldFolder; - this.loadedRegions = new KMap<>(); - this.lastUse = new KMap<>(); - saveQueue = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r); - t.setName("Iris MCA Writer"); - t.setPriority(Thread.MIN_PRIORITY); - return t; - }); - } - - public static BlockData getBlockData(CompoundTag tag) { - if(tag == null) { - return B.getAir(); - } - - StringBuilder p = new StringBuilder(tag.getString("Name")); - - if(tag.containsKey("Properties")) { - CompoundTag props = tag.getCompoundTag("Properties"); - p.append('['); - - for(String i : props.keySet()) { - p.append(i).append('=').append(props.getString(i)).append(','); - } - - p.deleteCharAt(p.length() - 1).append(']'); - } - - BlockData b = B.getOrNull(p.toString()); - - if(b == null) { - return B.getAir(); - } - - return b; - } - - public static CompoundTag getCompound(BlockData bd) { - return blockDataCache.computeIfAbsent(bd, BLOCK_DATA_COMPUTE); - } - - private static Map computeBiomeIDs() { - Map biomeIds = new KMap<>(); - - for(Biome biome : Biome.values()) { - if(!biome.name().equals("CUSTOM")) { - biomeIds.put(biome, INMS.get().getBiomeId(biome)); - } - } - - return biomeIds; - } - - public void close() { - - for(Long i : loadedRegions.k()) { - queueSaveUnload(Cache.keyX(i), Cache.keyZ(i)); - } - - saveQueue.shutdown(); - try { - while(!saveQueue.awaitTermination(3, TimeUnit.SECONDS)) { - Iris.info("Still Waiting to save MCA Files..."); - } - } catch(InterruptedException e) { - e.printStackTrace(); - } - } - - public void flushNow() { - for(Long i : loadedRegions.k()) { - doSaveUnload(Cache.keyX(i), Cache.keyZ(i)); - } - } - - public void queueSaveUnload(int x, int z) { - saveQueue.submit(() -> doSaveUnload(x, z)); - } - - public void doSaveUnload(int x, int z) { - MCAFile f = getMCAOrNull(x, z); - if(f != null) { - unloadRegion(x, z); - } - - saveRegion(x, z, f); - } - - public void save() { - boolean saving = true; - - for(Long i : loadedRegions.k()) { - int x = Cache.keyX(i); - int z = Cache.keyZ(i); - - if(!lastUse.containsKey(i)) { - lastUse.put(i, M.ms()); - } - - if(shouldUnload(x, z)) { - queueSaveUnload(x, z); - } - } - - Iris.debug("Regions: " + C.GOLD + loadedRegions.size() + C.LIGHT_PURPLE); - } - - public void queueSave() { - - } - - public synchronized void unloadRegion(int x, int z) { - long key = Cache.key(x, z); - loadedRegions.remove(key); - lastUse.remove(key); - Iris.debug("Unloaded Region " + C.GOLD + x + " " + z); - } - - public void saveRegion(int x, int z) { - long k = Cache.key(x, z); - MCAFile mca = getMCAOrNull(x, z); - try { - MCAUtil.write(mca, getRegionFile(x, z), true); - Iris.debug("Saved Region " + C.GOLD + x + " " + z); - } catch(IOException e) { - Iris.error("Failed to save region " + getRegionFile(x, z).getPath()); - e.printStackTrace(); - } - } - - public void saveRegion(int x, int z, MCAFile mca) { - try { - MCAUtil.write(mca, getRegionFile(x, z), true); - Iris.debug("Saved Region " + C.GOLD + x + " " + z); - } catch(IOException e) { - Iris.error("Failed to save region " + getRegionFile(x, z).getPath()); - e.printStackTrace(); - } - } - - public boolean shouldUnload(int x, int z) { - return getIdleDuration(x, z) > 60000; - } - - public File getRegionFile(int x, int z) { - return new File(worldFolder, "region/r." + x + "." + z + ".mca"); - } - - public BlockData getBlockData(int x, int y, int z) { - try { - CompoundTag tag = getChunkSection(x >> 4, y >> 4, z >> 4).getBlockStateAt(x & 15, y & 15, z & 15); - - if(tag == null) { - return AIR; - } - - return getBlockData(tag); - } catch(Throwable e) { - Iris.reportError(e); - - } - return AIR; - } - - public void setBlockData(int x, int y, int z, BlockData data) { - getChunkSection(x >> 4, y >> 4, z >> 4).setBlockStateAt(x & 15, y & 15, z & 15, getCompound(data), false); - } - - public int getBiomeId(Biome b) { - return biomeIds.get(b); - } - - public void setBiome(int x, int y, int z, Biome biome) { - getChunk(x >> 4, z >> 4).setBiomeAt(x & 15, y, z & 15, biomeIds.get(biome)); - } - - public Section getChunkSection(int x, int y, int z) { - Chunk c = getChunk(x, z); - Section s = c.getSection(y); - - if(s == null) { - s = Section.newSection(); - c.setSection(y, s); - } - - return s; - } - - public Chunk getChunk(int x, int z) { - return getChunk(getMCA(x >> 5, z >> 5), x, z); - } - - public Chunk getChunk(MCAFile mca, int x, int z) { - Chunk c = mca.getChunk(x & 31, z & 31); - - if(c == null) { - c = Chunk.newChunk(); - mca.setChunk(x & 31, z & 31, c); - } - - return c; - } - - public Chunk getNewChunk(MCAFile mca, int x, int z) { - Chunk c = Chunk.newChunk(); - mca.setChunk(x & 31, z & 31, c); - - return c; - } - - public long getIdleDuration(int x, int z) { - return hyperLock.withResult(x, z, () -> { - Long l = lastUse.get(Cache.key(x, z)); - return l == null ? 0 : (M.ms() - l); - }); - } - - public MCAFile getMCA(int x, int z) { - long key = Cache.key(x, z); - - return hyperLock.withResult(x, z, () -> { - lastUse.put(key, M.ms()); - - MCAFile mcaf = loadedRegions.get(key); - - if(mcaf == null) { - mcaf = new MCAFile(x, z); - loadedRegions.put(key, mcaf); - } - - return mcaf; - }); - } - - public MCAFile getMCAOrNull(int x, int z) { - long key = Cache.key(x, z); - - return hyperLock.withResult(x, z, () -> { - if(loadedRegions.containsKey(key)) { - lastUse.put(key, M.ms()); - return loadedRegions.get(key); - } - - return null; - }); - } - - public int size() { - return loadedRegions.size(); - } - - public boolean isLoaded(int x, int z) { - return loadedRegions.containsKey(Cache.key(x, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/Section.java b/src/main/java/com/volmit/iris/util/nbt/mca/Section.java deleted file mode 100644 index 53fcfae41..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/Section.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca; - -import com.volmit.iris.core.nms.INMS; -import com.volmit.iris.util.nbt.mca.palette.MCAPaletteAccess; -import com.volmit.iris.util.nbt.tag.ByteArrayTag; -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.ListTag; - - -public class Section { - private CompoundTag data; - private MCAPaletteAccess palette; - private byte[] blockLight; - private byte[] skyLight; - - public Section(CompoundTag sectionRoot, int dataVersion) { - this(sectionRoot, dataVersion, LoadFlags.ALL_DATA); - } - - public Section(CompoundTag sectionRoot, int dataVersion, long loadFlags) { - data = sectionRoot; - ListTag rawPalette = sectionRoot.getListTag("Palette"); - if(rawPalette == null) { - return; - } - palette = INMS.get().createPalette(); - palette.readFromSection(sectionRoot); - ByteArrayTag blockLight = sectionRoot.getByteArrayTag("BlockLight"); - ByteArrayTag skyLight = sectionRoot.getByteArrayTag("SkyLight"); - this.blockLight = blockLight != null ? blockLight.getValue() : null; - this.skyLight = skyLight != null ? skyLight.getValue() : null; - } - - Section() { - } - - /** - * Creates an empty Section with base values. - * - * @return An empty Section - */ - public static Section newSection() { - Section s = new Section(); - s.data = new CompoundTag(); - s.palette = INMS.get().createPalette(); - return s; - } - - /** - * Checks whether the data of this Section is empty. - * - * @return true if empty - */ - public boolean isEmpty() { - return data == null; - } - - /** - * Fetches a block state based on a block location from this section. - * The coordinates represent the location of the block inside of this Section. - * - * @param blockX - * The x-coordinate of the block in this Section - * @param blockY - * The y-coordinate of the block in this Section - * @param blockZ - * The z-coordinate of the block in this Section - * @return The block state data of this block. - */ - public synchronized CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { - synchronized(palette) { - return palette.getBlock(blockX & 15, blockY & 15, blockZ & 15); - } - } - - /** - * Attempts to add a block state for a specific block location in this Section. - * - * @param blockX - * The x-coordinate of the block in this Section - * @param blockY - * The y-coordinate of the block in this Section - * @param blockZ - * The z-coordinate of the block in this Section - * @param state - * The block state to be set - */ - public synchronized void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { - synchronized(palette) { - palette.setBlock(blockX & 15, blockY & 15, blockZ & 15, state); - } - } - - /** - * This method recalculates the palette and its indices. - * This should only be used moderately to avoid unnecessary recalculation of the palette indices. - * Recalculating the Palette should only be executed once right before saving the Section to file. - */ - public void cleanupPaletteAndBlockStates() { - - } - - /** - * @return The block light array of this Section - */ - public synchronized byte[] getBlockLight() { - return blockLight; - } - - /** - * Sets the block light array for this section. - * - * @param blockLight - * The block light array - * @throws IllegalArgumentException - * When the length of the array is not 2048 - */ - public synchronized void setBlockLight(byte[] blockLight) { - if(blockLight != null && blockLight.length != 2048) { - throw new IllegalArgumentException("BlockLight array must have a length of 2048"); - } - this.blockLight = blockLight; - } - - /** - * @return The sky light values of this Section - */ - public synchronized byte[] getSkyLight() { - return skyLight; - } - - /** - * Sets the sky light values of this section. - * - * @param skyLight - * The custom sky light values - * @throws IllegalArgumentException - * If the length of the array is not 2048 - */ - public synchronized void setSkyLight(byte[] skyLight) { - if(skyLight != null && skyLight.length != 2048) { - throw new IllegalArgumentException("SkyLight array must have a length of 2048"); - } - this.skyLight = skyLight; - } - - /** - * Updates the raw CompoundTag that this Section is based on. - * This must be called before saving a Section to disk if the Section was manually created - * to set the Y of this Section. - * - * @param y - * The Y-value of this Section - * @return A reference to the raw CompoundTag this Section is based on - */ - public synchronized CompoundTag updateHandle(int y) { - data.putByte("Y", (byte) y); - - if(palette != null) { - synchronized(palette) { - palette.writeToSection(data); - } - } - if(blockLight != null) { - data.putByteArray("BlockLight", blockLight); - } - if(skyLight != null) { - data.putByteArray("SkyLight", skyLight); - } - return data; - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCABiomeContainer.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCABiomeContainer.java deleted file mode 100644 index 60ff7eb26..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCABiomeContainer.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -public interface MCABiomeContainer { - int[] getData(); - - void setBiome(int x, int y, int z, int id); - - int getBiome(int x, int y, int z); -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCABitStorage.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCABitStorage.java deleted file mode 100644 index cc9d20bf9..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCABitStorage.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import org.apache.commons.lang3.Validate; - -import java.util.function.IntConsumer; - -public class MCABitStorage { - private static final int[] MAGIC = new int[] { - -1, -1, 0, Integer.MIN_VALUE, 0, 0, 1431655765, 1431655765, 0, Integer.MIN_VALUE, - 0, 1, 858993459, 858993459, 0, 715827882, 715827882, 0, 613566756, 613566756, - 0, Integer.MIN_VALUE, 0, 2, 477218588, 477218588, 0, 429496729, 429496729, 0, - 390451572, 390451572, 0, 357913941, 357913941, 0, 330382099, 330382099, 0, 306783378, - 306783378, 0, 286331153, 286331153, 0, Integer.MIN_VALUE, 0, 3, 252645135, 252645135, - 0, 238609294, 238609294, 0, 226050910, 226050910, 0, 214748364, 214748364, 0, - 204522252, 204522252, 0, 195225786, 195225786, 0, 186737708, 186737708, 0, 178956970, - 178956970, 0, 171798691, 171798691, 0, 165191049, 165191049, 0, 159072862, 159072862, - 0, 153391689, 153391689, 0, 148102320, 148102320, 0, 143165576, 143165576, 0, - 138547332, 138547332, 0, Integer.MIN_VALUE, 0, 4, 130150524, 130150524, 0, 126322567, - 126322567, 0, 122713351, 122713351, 0, 119304647, 119304647, 0, 116080197, 116080197, - 0, 113025455, 113025455, 0, 110127366, 110127366, 0, 107374182, 107374182, 0, - 104755299, 104755299, 0, 102261126, 102261126, 0, 99882960, 99882960, 0, 97612893, - 97612893, 0, 95443717, 95443717, 0, 93368854, 93368854, 0, 91382282, 91382282, - 0, 89478485, 89478485, 0, 87652393, 87652393, 0, 85899345, 85899345, 0, - 84215045, 84215045, 0, 82595524, 82595524, 0, 81037118, 81037118, 0, 79536431, - 79536431, 0, 78090314, 78090314, 0, 76695844, 76695844, 0, 75350303, 75350303, - 0, 74051160, 74051160, 0, 72796055, 72796055, 0, 71582788, 71582788, 0, - 70409299, 70409299, 0, 69273666, 69273666, 0, 68174084, 68174084, 0, Integer.MIN_VALUE, - 0, 5}; - - private final long[] data; - - private final int bits; - - private final long mask; - - private final int size; - - private final int valuesPerLong; - - private final int divideMul; - - private final int divideAdd; - - private final int divideShift; - - public MCABitStorage(int bits, int length) { - this(bits, length, null); - } - - public MCABitStorage(int bits, int length, long[] data) { - Validate.inclusiveBetween(1L, 32L, bits); - this.size = length; - this.bits = bits; - this.mask = (1L << bits) - 1L; - this.valuesPerLong = (char) (64 / bits); - int var3 = 3 * (this.valuesPerLong - 1); - this.divideMul = MAGIC[var3]; - this.divideAdd = MAGIC[var3 + 1]; - this.divideShift = MAGIC[var3 + 2]; - int var4 = (length + this.valuesPerLong - 1) / this.valuesPerLong; - if(data != null) { - if(data.length != var4) - throw new RuntimeException("NO!"); - this.data = data; - } else { - this.data = new long[var4]; - } - } - - private int cellIndex(int var0) { - long var1 = Integer.toUnsignedLong(this.divideMul); - long var3 = Integer.toUnsignedLong(this.divideAdd); - return (int) (var0 * var1 + var3 >> 32L >> this.divideShift); - } - - public int getAndSet(int var0, int var1) { - Validate.inclusiveBetween(0L, (this.size - 1), var0); - Validate.inclusiveBetween(0L, this.mask, var1); - int var2 = cellIndex(var0); - long var3 = this.data[var2]; - int var5 = (var0 - var2 * this.valuesPerLong) * this.bits; - int var6 = (int) (var3 >> var5 & this.mask); - this.data[var2] = var3 & (this.mask << var5 ^ 0xFFFFFFFFFFFFFFFFL) | (var1 & this.mask) << var5; - return var6; - } - - public void set(int var0, int var1) { - Validate.inclusiveBetween(0L, (this.size - 1), var0); - Validate.inclusiveBetween(0L, this.mask, var1); - int var2 = cellIndex(var0); - long var3 = this.data[var2]; - int var5 = (var0 - var2 * this.valuesPerLong) * this.bits; - this.data[var2] = var3 & (this.mask << var5 ^ 0xFFFFFFFFFFFFFFFFL) | (var1 & this.mask) << var5; - } - - public int get(int var0) { - Validate.inclusiveBetween(0L, (this.size - 1), var0); - int var1 = cellIndex(var0); - long var2 = this.data[var1]; - int var4 = (var0 - var1 * this.valuesPerLong) * this.bits; - return (int) (var2 >> var4 & this.mask); - } - - public long[] getRaw() { - return this.data; - } - - public int getSize() { - return this.size; - } - - public int getBits() { - return this.bits; - } - - public void getAll(IntConsumer var0) { - int var1 = 0; - for(long var5 : this.data) { - for(int var7 = 0; var7 < this.valuesPerLong; var7++) { - var0.accept((int) (var5 & this.mask)); - var5 >>= this.bits; - if(++var1 >= this.size) - return; - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAChunkBiomeContainer.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAChunkBiomeContainer.java deleted file mode 100644 index 1a7834893..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAChunkBiomeContainer.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.Arrays; - -public class MCAChunkBiomeContainer { - private static final Logger LOGGER = LogManager.getLogger(); - private static final int WIDTH_BITS = MCAMth.ceillog2(16) - 2; - private static final int HORIZONTAL_MASK = (1 << WIDTH_BITS) - 1; - private static final int PACKED_X_LENGTH = 1 + MCAMth.log2(MCAMth.smallestEncompassingPowerOfTwo(30000000)); - private static final int PACKED_Z_LENGTH = PACKED_X_LENGTH; - public static final int PACKED_Y_LENGTH = 64 - PACKED_X_LENGTH - PACKED_Z_LENGTH; - public static final int MAX_SIZE = 1 << WIDTH_BITS + WIDTH_BITS + PACKED_Y_LENGTH - 2; - - public final MCAIdMap biomeRegistry; - - private final T[] biomes; - - private final int quartMinY; - - private final int quartHeight; - - protected MCAChunkBiomeContainer(MCAIdMap registry, int minHeight, int maxHeight, T[] abiomebase) { - this.biomeRegistry = registry; - this.biomes = abiomebase; - this.quartMinY = MCAQuartPos.fromBlock(minHeight); - this.quartHeight = MCAQuartPos.fromBlock(maxHeight) - 1; - } - - public MCAChunkBiomeContainer(MCAIdMap registry, int min, int max) { - this(registry, min, max, new int[(1 << WIDTH_BITS + WIDTH_BITS) * ceilDiv(max - min, 4)]); - } - - public MCAChunkBiomeContainer(MCAIdMap registry, int minHeight, int maxHeight, int[] aint) { - this(registry, minHeight, maxHeight, (T[]) new Object[aint.length]); - int i = -1; - for(int j = 0; j < this.biomes.length; j++) { - int k = aint[j]; - T biomebase = registry.byId(k); - if(biomebase == null) { - if(i == -1) - i = j; - this.biomes[j] = registry.byId(0); - } else { - this.biomes[j] = biomebase; - } - } - if(i != -1) - LOGGER.warn("Invalid biome data received, starting from {}: {}", Integer.valueOf(i), Arrays.toString(aint)); - } - - private static int ceilDiv(int i, int j) { - return (i + j - 1) / j; - } - - public int[] writeBiomes() { - int[] aint = new int[this.biomes.length]; - for(int i = 0; i < this.biomes.length; i++) - aint[i] = this.biomeRegistry.getId(this.biomes[i]); - return aint; - } - - public T getBiome(int i, int j, int k) { - int l = i & HORIZONTAL_MASK; - int i1 = MCAMth.clamp(j - this.quartMinY, 0, this.quartHeight); - int j1 = k & HORIZONTAL_MASK; - return this.biomes[i1 << WIDTH_BITS + WIDTH_BITS | j1 << WIDTH_BITS | l]; - } - - public void setBiome(int i, int j, int k, T biome) { - int l = i & HORIZONTAL_MASK; - int i1 = MCAMth.clamp(j - this.quartMinY, 0, this.quartHeight); - int j1 = k & HORIZONTAL_MASK; - this.biomes[i1 << WIDTH_BITS + WIDTH_BITS | j1 << WIDTH_BITS | l] = biome; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCACountConsumer.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCACountConsumer.java deleted file mode 100644 index 89e4a24ce..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCACountConsumer.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -@FunctionalInterface -public interface MCACountConsumer { - void accept(T paramT, int paramInt); -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCACrudeIncrementalIntIdentityHashBiMap.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCACrudeIncrementalIntIdentityHashBiMap.java deleted file mode 100644 index 08957cc2c..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCACrudeIncrementalIntIdentityHashBiMap.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.google.common.base.Predicates; -import com.google.common.collect.Iterators; - -import java.util.Arrays; -import java.util.Iterator; - -public class MCACrudeIncrementalIntIdentityHashBiMap implements MCAIdMap { - public static final int NOT_FOUND = -1; - - private static final Object EMPTY_SLOT = null; - - private static final float LOADFACTOR = 0.8F; - - private K[] keys; - - private int[] values; - - private K[] byId; - - private int nextId; - - private int size; - - public MCACrudeIncrementalIntIdentityHashBiMap(int var0) { - var0 = (int) (var0 / 0.8F); - this.keys = (K[]) new Object[var0]; - this.values = new int[var0]; - this.byId = (K[]) new Object[var0]; - } - - public int getId(K var0) { - return getValue(indexOf(var0, hash(var0))); - } - - - public K byId(int var0) { - if(var0 < 0 || var0 >= this.byId.length) - return null; - return this.byId[var0]; - } - - private int getValue(int var0) { - if(var0 == -1) - return -1; - return this.values[var0]; - } - - public boolean contains(K var0) { - return (getId(var0) != -1); - } - - public boolean contains(int var0) { - return (byId(var0) != null); - } - - public int add(K var0) { - int var1 = nextId(); - addMapping(var0, var1); - return var1; - } - - private int nextId() { - while(this.nextId < this.byId.length && this.byId[this.nextId] != null) - this.nextId++; - return this.nextId; - } - - private void grow(int var0) { - K[] var1 = this.keys; - int[] var2 = this.values; - this.keys = (K[]) new Object[var0]; - this.values = new int[var0]; - this.byId = (K[]) new Object[var0]; - this.nextId = 0; - this.size = 0; - for(int var3 = 0; var3 < var1.length; var3++) { - if(var1[var3] != null) - addMapping(var1[var3], var2[var3]); - } - } - - public void addMapping(K var0, int var1) { - int var2 = Math.max(var1, this.size + 1); - if(var2 >= this.keys.length * 0.8F) { - int i = this.keys.length << 1; - while(i < var1) - i <<= 1; - grow(i); - } - int var3 = findEmpty(hash(var0)); - this.keys[var3] = var0; - this.values[var3] = var1; - this.byId[var1] = var0; - this.size++; - if(var1 == this.nextId) - this.nextId++; - } - - private int hash(K var0) { - return (MCAMth.murmurHash3Mixer(System.identityHashCode(var0)) & Integer.MAX_VALUE) % this.keys.length; - } - - private int indexOf(K var0, int var1) { - int var2; - for(var2 = var1; var2 < this.keys.length; var2++) { - if(this.keys[var2] == var0) - return var2; - if(this.keys[var2] == EMPTY_SLOT) - return -1; - } - for(var2 = 0; var2 < var1; var2++) { - if(this.keys[var2] == var0) - return var2; - if(this.keys[var2] == EMPTY_SLOT) - return -1; - } - return -1; - } - - private int findEmpty(int var0) { - int var1; - for(var1 = var0; var1 < this.keys.length; var1++) { - if(this.keys[var1] == EMPTY_SLOT) - return var1; - } - for(var1 = 0; var1 < var0; var1++) { - if(this.keys[var1] == EMPTY_SLOT) - return var1; - } - throw new RuntimeException("Overflowed :("); - } - - public Iterator iterator() { - return (Iterator) Iterators.filter(Iterators.forArray((Object[]) this.byId), Predicates.notNull()); - } - - public void clear() { - Arrays.fill(this.keys, null); - Arrays.fill(this.byId, null); - this.nextId = 0; - this.size = 0; - } - - public int size() { - return this.size; - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAGlobalPalette.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAGlobalPalette.java deleted file mode 100644 index a7ce1296c..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAGlobalPalette.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.volmit.iris.util.nbt.tag.ListTag; - -import java.util.function.Predicate; - -public class MCAGlobalPalette implements MCAPalette { - private final MCAIdMapper registry; - - private final T defaultValue; - - public MCAGlobalPalette(MCAIdMapper var0, T var1) { - this.registry = var0; - this.defaultValue = var1; - } - - public int idFor(T var0) { - int var1 = this.registry.getId(var0); - return (var1 == -1) ? 0 : var1; - } - - public boolean maybeHas(Predicate var0) { - return true; - } - - public T valueFor(int var0) { - T var1 = this.registry.byId(var0); - return (var1 == null) ? this.defaultValue : var1; - } - - public int getSize() { - return this.registry.size(); - } - - public void read(ListTag var0) { - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAHashMapPalette.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAHashMapPalette.java deleted file mode 100644 index dfc8f4186..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAHashMapPalette.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.ListTag; - -import java.util.function.Function; -import java.util.function.Predicate; - -public class MCAHashMapPalette implements MCAPalette { - private final MCAIdMapper registry; - - private final MCACrudeIncrementalIntIdentityHashBiMap values; - - private final MCAPaletteResize resizeHandler; - - private final Function reader; - - private final Function writer; - - private final int bits; - - public MCAHashMapPalette(MCAIdMapper var0, int var1, MCAPaletteResize var2, Function var3, Function var4) { - this.registry = var0; - this.bits = var1; - this.resizeHandler = var2; - this.reader = var3; - this.writer = var4; - this.values = new MCACrudeIncrementalIntIdentityHashBiMap(1 << var1); - } - - public int idFor(T var0) { - int var1 = this.values.getId(var0); - if(var1 == -1) { - var1 = this.values.add(var0); - if(var1 >= 1 << this.bits) - var1 = this.resizeHandler.onResize(this.bits + 1, var0); - } - return var1; - } - - public boolean maybeHas(Predicate var0) { - for(int var1 = 0; var1 < getSize(); var1++) { - if(var0.test(this.values.byId(var1))) - return true; - } - return false; - } - - public T valueFor(int var0) { - return this.values.byId(var0); - } - - public int getSize() { - return this.values.size(); - } - - public void read(ListTag var0) { - this.values.clear(); - for(int var1 = 0; var1 < var0.size(); var1++) - this.values.add(this.reader.apply((CompoundTag) var0.get(var1))); - } - - public void write(ListTag var0) { - for(int var1 = 0; var1 < getSize(); var1++) - var0.add(this.writer.apply(this.values.byId(var1))); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAIdMap.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAIdMap.java deleted file mode 100644 index 047821a9e..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAIdMap.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -public interface MCAIdMap extends Iterable { - int getId(T paramT); - - T byId(int paramInt); -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAIdMapper.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAIdMapper.java deleted file mode 100644 index 040a17c0b..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAIdMapper.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.google.common.base.Predicates; -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import it.unimi.dsi.fastutil.Hash; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenCustomHashMap; - -import java.util.Iterator; -import java.util.List; - -public class MCAIdMapper implements MCAIdMap { - public static final int DEFAULT = -1; - private final Object2IntMap tToId; - private final List idToT; - private int nextId; - - public MCAIdMapper(Object2IntMap tToId, List idToT, int nextId) { - this.tToId = tToId; - this.idToT = idToT; - this.nextId = nextId; - } - - public MCAIdMapper() { - this(512); - } - - public MCAIdMapper(int var0) { - this.idToT = Lists.newArrayListWithExpectedSize(var0); - this.tToId = new Object2IntOpenCustomHashMap<>(var0, IdentityStrategy.INSTANCE); - } - - public void addMapping(T var0, int var1) { - this.tToId.put(var0, Integer.valueOf(var1)); - while(this.idToT.size() <= var1) - this.idToT.add(null); - this.idToT.set(var1, var0); - if(this.nextId <= var1) - this.nextId = var1 + 1; - } - - public void add(T var0) { - addMapping(var0, this.nextId); - } - - public int getId(T var0) { - Integer var1 = this.tToId.get(var0); - return (var1 == null) ? -1 : var1.intValue(); - } - - public final T byId(int var0) { - if(var0 >= 0 && var0 < this.idToT.size()) - return this.idToT.get(var0); - return null; - } - - public Iterator iterator() { - return Iterators.filter(this.idToT.iterator(), Predicates.notNull()); - } - - public boolean contains(int var0) { - return (byId(var0) != null); - } - - public int size() { - return this.tToId.size(); - } - - enum IdentityStrategy implements Hash.Strategy { - INSTANCE; - - IdentityStrategy() { - } - - public int hashCode(Object var0) { - return System.identityHashCode(var0); - } - - public boolean equals(Object var0, Object var1) { - return var0 == var1; - } - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCALinearPalette.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCALinearPalette.java deleted file mode 100644 index 9eabcce0d..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCALinearPalette.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.ListTag; - -import java.util.function.Function; -import java.util.function.Predicate; - -public class MCALinearPalette implements MCAPalette { - private final MCAIdMapper registry; - - private final T[] values; - - private final MCAPaletteResize resizeHandler; - - private final Function reader; - - private final int bits; - - private int size; - - public MCALinearPalette(MCAIdMapper var0, int var1, MCAPaletteResize var2, Function var3) { - this.registry = var0; - this.values = (T[]) new Object[1 << var1]; - this.bits = var1; - this.resizeHandler = var2; - this.reader = var3; - } - - public int idFor(T var0) { - int var1; - for(var1 = 0; var1 < this.size; var1++) { - if(this.values[var1] == var0) - return var1; - } - var1 = this.size; - if(var1 < this.values.length) { - this.values[var1] = var0; - this.size++; - return var1; - } - return this.resizeHandler.onResize(this.bits + 1, var0); - } - - public boolean maybeHas(Predicate var0) { - for(int var1 = 0; var1 < this.size; var1++) { - if(var0.test(this.values[var1])) - return true; - } - return false; - } - - public T valueFor(int var0) { - if(var0 >= 0 && var0 < this.size) - return this.values[var0]; - return null; - } - - public int getSize() { - return this.size; - } - - public void read(ListTag var0) { - for(int var1 = 0; var1 < var0.size(); var1++) { - this.values[var1] = this.reader.apply((CompoundTag) var0.get(var1)); - } - this.size = var0.size(); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAMth.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAMth.java deleted file mode 100644 index f11853070..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAMth.java +++ /dev/null @@ -1,712 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import java.util.Random; -import java.util.UUID; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class MCAMth { - public static final float PI = 3.1415927F; - public static final float HALF_PI = 1.5707964F; - public static final float TWO_PI = 6.2831855F; - public static final float DEG_TO_RAD = 0.017453292F; - public static final float RAD_TO_DEG = 57.295776F; - public static final float EPSILON = 1.0E-5F; - public static final float SQRT_OF_TWO = sqrt(2.0F); - private static final int BIG_ENOUGH_INT = 1024; - private static final float BIG_ENOUGH_FLOAT = 1024.0F; - private static final long UUID_VERSION = 61440L; - private static final long UUID_VERSION_TYPE_4 = 16384L; - private static final long UUID_VARIANT = -4611686018427387904L; - private static final long UUID_VARIANT_2 = -9223372036854775808L; - private static final float SIN_SCALE = 10430.378F; - - private static final float[] SIN; - private static final Random RANDOM = new Random(); - private static final int[] MULTIPLY_DE_BRUIJN_BIT_POSITION = new int[] { - 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, - 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, - 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, - 10, 9}; - private static final double ONE_SIXTH = 0.16666666666666666D; - private static final int FRAC_EXP = 8; - private static final int LUT_SIZE = 257; - private static final double FRAC_BIAS = Double.longBitsToDouble(4805340802404319232L); - private static final double[] ASIN_TAB = new double[257]; - private static final double[] COS_TAB = new double[257]; - - static { - SIN = make(new float[65536], var0 -> { - for(int var1 = 0; var1 < var0.length; var1++) - var0[var1] = (float) Math.sin(var1 * Math.PI * 2.0D / 65536.0D); - }); - } - - static { - for(int var0 = 0; var0 < 257; var0++) { - double var1 = var0 / 256.0D; - double var3 = Math.asin(var1); - COS_TAB[var0] = Math.cos(var3); - ASIN_TAB[var0] = var3; - } - } - - public static T make(Supplier var0) { - return var0.get(); - } - - public static T make(T var0, Consumer var1) { - var1.accept(var0); - return var0; - } - - public static float sin(float var0) { - return SIN[(int) (var0 * 10430.378F) & 0xFFFF]; - } - - public static float cos(float var0) { - return SIN[(int) (var0 * 10430.378F + 16384.0F) & 0xFFFF]; - } - - public static float sqrt(float var0) { - return (float) Math.sqrt(var0); - } - - public static int floor(float var0) { - int var1 = (int) var0; - return (var0 < var1) ? (var1 - 1) : var1; - } - - public static int fastFloor(double var0) { - return (int) (var0 + 1024.0D) - 1024; - } - - public static int floor(double var0) { - int var2 = (int) var0; - return (var0 < var2) ? (var2 - 1) : var2; - } - - public static long lfloor(double var0) { - long var2 = (long) var0; - return (var0 < var2) ? (var2 - 1L) : var2; - } - - public static int absFloor(double var0) { - return (int) ((var0 >= 0.0D) ? var0 : (-var0 + 1.0D)); - } - - public static float abs(float var0) { - return Math.abs(var0); - } - - public static int abs(int var0) { - return Math.abs(var0); - } - - public static int ceil(float var0) { - int var1 = (int) var0; - return (var0 > var1) ? (var1 + 1) : var1; - } - - public static int ceil(double var0) { - int var2 = (int) var0; - return (var0 > var2) ? (var2 + 1) : var2; - } - - public static byte clamp(byte var0, byte var1, byte var2) { - if(var0 < var1) - return var1; - if(var0 > var2) - return var2; - return var0; - } - - public static int clamp(int var0, int var1, int var2) { - if(var0 < var1) - return var1; - if(var0 > var2) - return var2; - return var0; - } - - public static long clamp(long var0, long var2, long var4) { - if(var0 < var2) - return var2; - if(var0 > var4) - return var4; - return var0; - } - - public static float clamp(float var0, float var1, float var2) { - if(var0 < var1) - return var1; - if(var0 > var2) - return var2; - return var0; - } - - public static double clamp(double var0, double var2, double var4) { - if(var0 < var2) - return var2; - if(var0 > var4) - return var4; - return var0; - } - - public static double clampedLerp(double var0, double var2, double var4) { - if(var4 < 0.0D) - return var0; - if(var4 > 1.0D) - return var2; - return lerp(var4, var0, var2); - } - - public static float clampedLerp(float var0, float var1, float var2) { - if(var2 < 0.0F) - return var0; - if(var2 > 1.0F) - return var1; - return lerp(var2, var0, var1); - } - - public static double absMax(double var0, double var2) { - if(var0 < 0.0D) - var0 = -var0; - if(var2 < 0.0D) - var2 = -var2; - return (var0 > var2) ? var0 : var2; - } - - public static int intFloorDiv(int var0, int var1) { - return Math.floorDiv(var0, var1); - } - - public static int nextInt(Random var0, int var1, int var2) { - if(var1 >= var2) - return var1; - return var0.nextInt(var2 - var1 + 1) + var1; - } - - public static float nextFloat(Random var0, float var1, float var2) { - if(var1 >= var2) - return var1; - return var0.nextFloat() * (var2 - var1) + var1; - } - - public static double nextDouble(Random var0, double var1, double var3) { - if(var1 >= var3) - return var1; - return var0.nextDouble() * (var3 - var1) + var1; - } - - public static double average(long[] var0) { - long var1 = 0L; - for(long var6 : var0) - var1 += var6; - return var1 / var0.length; - } - - public static boolean equal(float var0, float var1) { - return (Math.abs(var1 - var0) < 1.0E-5F); - } - - public static boolean equal(double var0, double var2) { - return (Math.abs(var2 - var0) < 9.999999747378752E-6D); - } - - public static int positiveModulo(int var0, int var1) { - return Math.floorMod(var0, var1); - } - - public static float positiveModulo(float var0, float var1) { - return (var0 % var1 + var1) % var1; - } - - public static double positiveModulo(double var0, double var2) { - return (var0 % var2 + var2) % var2; - } - - public static int wrapDegrees(int var0) { - int var1 = var0 % 360; - if(var1 >= 180) - var1 -= 360; - if(var1 < -180) - var1 += 360; - return var1; - } - - public static float wrapDegrees(float var0) { - float var1 = var0 % 360.0F; - if(var1 >= 180.0F) - var1 -= 360.0F; - if(var1 < -180.0F) - var1 += 360.0F; - return var1; - } - - public static double wrapDegrees(double var0) { - double var2 = var0 % 360.0D; - if(var2 >= 180.0D) - var2 -= 360.0D; - if(var2 < -180.0D) - var2 += 360.0D; - return var2; - } - - public static float degreesDifference(float var0, float var1) { - return wrapDegrees(var1 - var0); - } - - public static float degreesDifferenceAbs(float var0, float var1) { - return abs(degreesDifference(var0, var1)); - } - - public static float rotateIfNecessary(float var0, float var1, float var2) { - float var3 = degreesDifference(var0, var1); - float var4 = clamp(var3, -var2, var2); - return var1 - var4; - } - - public static float approach(float var0, float var1, float var2) { - var2 = abs(var2); - if(var0 < var1) - return clamp(var0 + var2, var0, var1); - return clamp(var0 - var2, var1, var0); - } - - public static float approachDegrees(float var0, float var1, float var2) { - float var3 = degreesDifference(var0, var1); - return approach(var0, var0 + var3, var2); - } - - public static int getInt(String var0, int var1) { - return Integer.valueOf(var0, var1); - } - - public static int getInt(String var0, int var1, int var2) { - return Math.max(var2, getInt(var0, var1)); - } - - public static double getDouble(String var0, double var1) { - try { - return Double.parseDouble(var0); - } catch(Throwable var3) { - return var1; - } - } - - public static double getDouble(String var0, double var1, double var3) { - return Math.max(var3, getDouble(var0, var1)); - } - - public static int smallestEncompassingPowerOfTwo(int var0) { - int var1 = var0 - 1; - var1 |= var1 >> 1; - var1 |= var1 >> 2; - var1 |= var1 >> 4; - var1 |= var1 >> 8; - var1 |= var1 >> 16; - return var1 + 1; - } - - public static boolean isPowerOfTwo(int var0) { - return (var0 != 0 && (var0 & var0 - 1) == 0); - } - - public static int ceillog2(int var0) { - var0 = isPowerOfTwo(var0) ? var0 : smallestEncompassingPowerOfTwo(var0); - return MULTIPLY_DE_BRUIJN_BIT_POSITION[(int) (var0 * 125613361L >> 27L) & 0x1F]; - } - - public static int log2(int var0) { - return ceillog2(var0) - (isPowerOfTwo(var0) ? 0 : 1); - } - - public static int color(float var0, float var1, float var2) { - return color(floor(var0 * 255.0F), floor(var1 * 255.0F), floor(var2 * 255.0F)); - } - - public static int color(int var0, int var1, int var2) { - int var3 = var0; - var3 = (var3 << 8) + var1; - var3 = (var3 << 8) + var2; - return var3; - } - - public static int colorMultiply(int var0, int var1) { - int var2 = (var0 & 0xFF0000) >> 16; - int var3 = (var1 & 0xFF0000) >> 16; - int var4 = (var0 & 0xFF00) >> 8; - int var5 = (var1 & 0xFF00) >> 8; - int var6 = (var0 & 0xFF); - int var7 = (var1 & 0xFF); - int var8 = (int) (var2 * var3 / 255.0F); - int var9 = (int) (var4 * var5 / 255.0F); - int var10 = (int) (var6 * var7 / 255.0F); - return var0 & 0xFF000000 | var8 << 16 | var9 << 8 | var10; - } - - public static int colorMultiply(int var0, float var1, float var2, float var3) { - int var4 = (var0 & 0xFF0000) >> 16; - int var5 = (var0 & 0xFF00) >> 8; - int var6 = (var0 & 0xFF); - int var7 = (int) (var4 * var1); - int var8 = (int) (var5 * var2); - int var9 = (int) (var6 * var3); - return var0 & 0xFF000000 | var7 << 16 | var8 << 8 | var9; - } - - public static float frac(float var0) { - return var0 - floor(var0); - } - - public static double frac(double var0) { - return var0 - lfloor(var0); - } - - public static long getSeed(int var0, int var1, int var2) { - long var3 = (var0 * 3129871) ^ var2 * 116129781L ^ var1; - var3 = var3 * var3 * 42317861L + var3 * 11L; - return var3 >> 16L; - } - - public static UUID createInsecureUUID(Random var0) { - long var1 = var0.nextLong() & 0xFFFFFFFFFFFF0FFFL | 0x4000L; - long var3 = var0.nextLong() & 0x3FFFFFFFFFFFFFFFL | Long.MIN_VALUE; - return new UUID(var1, var3); - } - - public static UUID createInsecureUUID() { - return createInsecureUUID(RANDOM); - } - - public static double inverseLerp(double var0, double var2, double var4) { - return (var0 - var2) / (var4 - var2); - } - - public static double atan2(double var0, double var2) { - double var4 = var2 * var2 + var0 * var0; - if(Double.isNaN(var4)) - return Double.NaN; - boolean var6 = (var0 < 0.0D); - if(var6) - var0 = -var0; - boolean var7 = (var2 < 0.0D); - if(var7) - var2 = -var2; - boolean var8 = (var0 > var2); - if(var8) { - double d = var2; - var2 = var0; - var0 = d; - } - double var9 = fastInvSqrt(var4); - var2 *= var9; - var0 *= var9; - double var11 = FRAC_BIAS + var0; - int var13 = (int) Double.doubleToRawLongBits(var11); - double var14 = ASIN_TAB[var13]; - double var16 = COS_TAB[var13]; - double var18 = var11 - FRAC_BIAS; - double var20 = var0 * var16 - var2 * var18; - double var22 = (6.0D + var20 * var20) * var20 * 0.16666666666666666D; - double var24 = var14 + var22; - if(var8) - var24 = 1.5707963267948966D - var24; - if(var7) - var24 = Math.PI - var24; - if(var6) - var24 = -var24; - return var24; - } - - public static float fastInvSqrt(float var0) { - float var1 = 0.5F * var0; - int var2 = Float.floatToIntBits(var0); - var2 = 1597463007 - (var2 >> 1); - var0 = Float.intBitsToFloat(var2); - var0 *= 1.5F - var1 * var0 * var0; - return var0; - } - - public static double fastInvSqrt(double var0) { - double var2 = 0.5D * var0; - long var4 = Double.doubleToRawLongBits(var0); - var4 = 6910469410427058090L - (var4 >> 1L); - var0 = Double.longBitsToDouble(var4); - var0 *= 1.5D - var2 * var0 * var0; - return var0; - } - - public static float fastInvCubeRoot(float var0) { - int var1 = Float.floatToIntBits(var0); - var1 = 1419967116 - var1 / 3; - float var2 = Float.intBitsToFloat(var1); - var2 = 0.6666667F * var2 + 1.0F / 3.0F * var2 * var2 * var0; - var2 = 0.6666667F * var2 + 1.0F / 3.0F * var2 * var2 * var0; - return var2; - } - - public static int hsvToRgb(float var0, float var1, float var2) { - float var8, var9, var10; - int var11, var12, var13, var3 = (int) (var0 * 6.0F) % 6; - float var4 = var0 * 6.0F - var3; - float var5 = var2 * (1.0F - var1); - float var6 = var2 * (1.0F - var4 * var1); - float var7 = var2 * (1.0F - (1.0F - var4) * var1); - switch(var3) { - case 0: - var8 = var2; - var9 = var7; - var10 = var5; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 1: - var8 = var6; - var9 = var2; - var10 = var5; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 2: - var8 = var5; - var9 = var2; - var10 = var7; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 3: - var8 = var5; - var9 = var6; - var10 = var2; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 4: - var8 = var7; - var9 = var5; - var10 = var2; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - case 5: - var8 = var2; - var9 = var5; - var10 = var6; - var11 = clamp((int) (var8 * 255.0F), 0, 255); - var12 = clamp((int) (var9 * 255.0F), 0, 255); - var13 = clamp((int) (var10 * 255.0F), 0, 255); - return var11 << 16 | var12 << 8 | var13; - } - throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + var0 + ", " + var1 + ", " + var2); - } - - public static int murmurHash3Mixer(int var0) { - var0 ^= var0 >>> 16; - var0 *= -2048144789; - var0 ^= var0 >>> 13; - var0 *= -1028477387; - var0 ^= var0 >>> 16; - return var0; - } - - public static long murmurHash3Mixer(long var0) { - var0 ^= var0 >>> 33L; - var0 *= -49064778989728563L; - var0 ^= var0 >>> 33L; - var0 *= -4265267296055464877L; - var0 ^= var0 >>> 33L; - return var0; - } - - public static double[] cumulativeSum(double... var0) { - float var1 = 0.0F; - for(double var5 : var0) - var1 = (float) (var1 + var5); - int var2; - for(var2 = 0; var2 < var0.length; var2++) - var0[var2] = var0[var2] / var1; - for(var2 = 0; var2 < var0.length; var2++) - var0[var2] = ((var2 == 0) ? 0.0D : var0[var2 - 1]) + var0[var2]; - return var0; - } - - public static int getRandomForDistributionIntegral(Random var0, double[] var1) { - double var2 = var0.nextDouble(); - for(int var4 = 0; var4 < var1.length; var4++) { - if(var2 < var1[var4]) - return var4; - } - return var1.length; - } - - public static double[] binNormalDistribution(double var0, double var2, double var4, int var6, int var7) { - double[] var8 = new double[var7 - var6 + 1]; - int var9 = 0; - for(int var10 = var6; var10 <= var7; var10++) { - var8[var9] = Math.max(0.0D, var0 * - - StrictMath.exp(-(var10 - var4) * (var10 - var4) / 2.0D * var2 * var2)); - var9++; - } - return var8; - } - - public static double[] binBiModalNormalDistribution(double var0, double var2, double var4, double var6, double var8, double var10, int var12, int var13) { - double[] var14 = new double[var13 - var12 + 1]; - int var15 = 0; - for(int var16 = var12; var16 <= var13; var16++) { - var14[var15] = Math.max(0.0D, var0 * - - StrictMath.exp(-(var16 - var4) * (var16 - var4) / 2.0D * var2 * var2) + var6 * - StrictMath.exp(-(var16 - var10) * (var16 - var10) / 2.0D * var8 * var8)); - var15++; - } - return var14; - } - - public static double[] binLogDistribution(double var0, double var2, int var4, int var5) { - double[] var6 = new double[var5 - var4 + 1]; - int var7 = 0; - for(int var8 = var4; var8 <= var5; var8++) { - var6[var7] = Math.max(var0 * StrictMath.log(var8) + var2, 0.0D); - var7++; - } - return var6; - } - - public static float lerp(float var0, float var1, float var2) { - return var1 + var0 * (var2 - var1); - } - - public static double lerp(double var0, double var2, double var4) { - return var2 + var0 * (var4 - var2); - } - - public static double lerp2(double var0, double var2, double var4, double var6, double var8, double var10) { - return lerp(var2, - - lerp(var0, var4, var6), - lerp(var0, var8, var10)); - } - - public static double lerp3(double var0, double var2, double var4, double var6, double var8, double var10, double var12, double var14, double var16, double var18, double var20) { - return lerp(var4, - - lerp2(var0, var2, var6, var8, var10, var12), - lerp2(var0, var2, var14, var16, var18, var20)); - } - - public static double smoothstep(double var0) { - return var0 * var0 * var0 * (var0 * (var0 * 6.0D - 15.0D) + 10.0D); - } - - public static double smoothstepDerivative(double var0) { - return 30.0D * var0 * var0 * (var0 - 1.0D) * (var0 - 1.0D); - } - - public static int sign(double var0) { - if(var0 == 0.0D) - return 0; - return (var0 > 0.0D) ? 1 : -1; - } - - public static float rotLerp(float var0, float var1, float var2) { - return var1 + var0 * wrapDegrees(var2 - var1); - } - - public static float diffuseLight(float var0, float var1, float var2) { - return Math.min(var0 * var0 * 0.6F + var1 * var1 * (3.0F + var1) / 4.0F + var2 * var2 * 0.8F, 1.0F); - } - - @Deprecated - public static float rotlerp(float var0, float var1, float var2) { - float var3 = var1 - var0; - while(var3 < -180.0F) - var3 += 360.0F; - while(var3 >= 180.0F) - var3 -= 360.0F; - return var0 + var2 * var3; - } - - @Deprecated - public static float rotWrap(double var0) { - while(var0 >= 180.0D) - var0 -= 360.0D; - while(var0 < -180.0D) - var0 += 360.0D; - return (float) var0; - } - - public static float triangleWave(float var0, float var1) { - return (Math.abs(var0 % var1 - var1 * 0.5F) - var1 * 0.25F) / var1 * 0.25F; - } - - public static float square(float var0) { - return var0 * var0; - } - - public static double square(double var0) { - return var0 * var0; - } - - public static int square(int var0) { - return var0 * var0; - } - - public static double clampedMap(double var0, double var2, double var4, double var6, double var8) { - return clampedLerp(var6, var8, inverseLerp(var0, var2, var4)); - } - - public static double map(double var0, double var2, double var4, double var6, double var8) { - return lerp(inverseLerp(var0, var2, var4), var6, var8); - } - - public static double wobble(double var0) { - return var0 + (2.0D * (new Random(floor(var0 * 3000.0D))).nextDouble() - 1.0D) * 1.0E-7D / 2.0D; - } - - public static int roundToward(int var0, int var1) { - return (var0 + var1 - 1) / var1 * var1; - } - - public static int randomBetweenInclusive(Random var0, int var1, int var2) { - return var0.nextInt(var2 - var1 + 1) + var1; - } - - public static float randomBetween(Random var0, float var1, float var2) { - return var0.nextFloat() * (var2 - var1) + var1; - } - - public static float normal(Random var0, float var1, float var2) { - return var1 + (float) var0.nextGaussian() * var2; - } - - public static double length(int var0, double var1, int var3) { - return Math.sqrt((var0 * var0) + var1 * var1 + (var3 * var3)); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPalette.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPalette.java deleted file mode 100644 index 2c815141c..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPalette.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.volmit.iris.util.nbt.tag.ListTag; - -import java.util.function.Predicate; - -public interface MCAPalette { - int idFor(T paramT); - - boolean maybeHas(Predicate paramPredicate); - - T valueFor(int paramInt); - - int getSize(); - - void read(ListTag paramListTag); -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPaletteAccess.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPaletteAccess.java deleted file mode 100644 index e72a7d246..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPaletteAccess.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.volmit.iris.util.nbt.tag.CompoundTag; - -public interface MCAPaletteAccess { - void setBlock(int x, int y, int z, CompoundTag data); - - CompoundTag getBlock(int x, int y, int z); - - void writeToSection(CompoundTag tag); - - void readFromSection(CompoundTag tag); -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPaletteResize.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPaletteResize.java deleted file mode 100644 index d6ca278d5..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPaletteResize.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -interface MCAPaletteResize { - int onResize(int paramInt, T paramT); -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPalettedContainer.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPalettedContainer.java deleted file mode 100644 index 0dcf18ad3..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAPalettedContainer.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.volmit.iris.util.nbt.tag.CompoundTag; -import com.volmit.iris.util.nbt.tag.ListTag; -import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; - -import java.util.function.Function; -import java.util.function.Predicate; - -public class MCAPalettedContainer implements MCAPaletteResize { - public static final int GLOBAL_PALETTE_BITS = 9; - public static final int MIN_PALETTE_SIZE = 4; - private static final int SIZE = 4096; - private final MCAPalette globalPalette; - - private final MCAPaletteResize dummyPaletteResize = (var0, var1) -> 0; - - private final MCAIdMapper registry; - - private final Function reader; - - private final Function writer; - - private final T defaultValue; - - protected MCABitStorage storage; - - private MCAPalette palette; - - private int bits; - - public MCAPalettedContainer(MCAPalette var0, MCAIdMapper var1, Function var2, Function var3, T var4) { - this.globalPalette = var0; - this.registry = var1; - this.reader = var2; - this.writer = var3; - this.defaultValue = var4; - setBits(4); - } - - private static int getIndex(int var0, int var1, int var2) { - return var1 << 8 | var2 << 4 | var0; - } - - private void setBits(int var0) { - if(var0 == this.bits) - return; - this.bits = var0; - if(this.bits <= 4) { - this.bits = 4; - this.palette = new MCALinearPalette<>(this.registry, this.bits, this, this.reader); - } else if(this.bits < 9) { - this.palette = new MCAHashMapPalette<>(this.registry, this.bits, this, this.reader, this.writer); - } else { - this.palette = this.globalPalette; - this.bits = MCAMth.ceillog2(this.registry.size()); - } - this.palette.idFor(this.defaultValue); - this.storage = new MCABitStorage(this.bits, 4096); - } - - public int onResize(int var0, T var1) { - MCABitStorage var2 = this.storage; - MCAPalette var3 = this.palette; - setBits(var0); - for(int var4 = 0; var4 < var2.getSize(); var4++) { - T var5 = var3.valueFor(var2.get(var4)); - if(var5 != null) - set(var4, var5); - } - return this.palette.idFor(var1); - } - - public T getAndSet(int var0, int var1, int var2, T var3) { - return getAndSet(getIndex(var0, var1, var2), var3); - } - - public T getAndSetUnchecked(int var0, int var1, int var2, T var3) { - return getAndSet(getIndex(var0, var1, var2), var3); - } - - private T getAndSet(int var0, T var1) { - int var2 = this.palette.idFor(var1); - int var3 = this.storage.getAndSet(var0, var2); - T var4 = this.palette.valueFor(var3); - return (var4 == null) ? this.defaultValue : var4; - } - - public void set(int var0, int var1, int var2, T var3) { - set(getIndex(var0, var1, var2), var3); - } - - private void set(int var0, T var1) { - int var2 = this.palette.idFor(var1); - this.storage.set(var0, var2); - } - - public T get(int var0, int var1, int var2) { - return get(getIndex(var0, var1, var2)); - } - - protected T get(int var0) { - T var1 = this.palette.valueFor(this.storage.get(var0)); - return (var1 == null) ? this.defaultValue : var1; - } - - public void read(ListTag var0, long[] var1) { - int var2 = Math.max(4, MCAMth.ceillog2(var0.size())); - if(var2 != this.bits) - setBits(var2); - this.palette.read(var0); - int var3 = var1.length * 64 / 4096; - if(this.palette == this.globalPalette) { - MCAPalette var4 = new MCAHashMapPalette<>(this.registry, var2, this.dummyPaletteResize, this.reader, this.writer); - var4.read(var0); - MCABitStorage var5 = new MCABitStorage(var2, 4096, var1); - for(int var6 = 0; var6 < 4096; var6++) - this.storage.set(var6, this.globalPalette.idFor(var4.valueFor(var5.get(var6)))); - } else if(var3 == this.bits) { - System.arraycopy(var1, 0, this.storage.getRaw(), 0, var1.length); - } else { - MCABitStorage var4 = new MCABitStorage(var3, 4096, var1); - for(int var5 = 0; var5 < 4096; var5++) - this.storage.set(var5, var4.get(var5)); - } - } - - public void write(CompoundTag var0, String var1, String var2) { - MCAHashMapPalette var3 = new MCAHashMapPalette<>(this.registry, this.bits, this.dummyPaletteResize, this.reader, this.writer); - T var4 = this.defaultValue; - int var5 = var3.idFor(this.defaultValue); - int[] var6 = new int[4096]; - for(int i = 0; i < 4096; i++) { - T t = get(i); - if(t != var4) { - var4 = t; - var5 = var3.idFor(t); - } - var6[i] = var5; - } - ListTag paletteList = (ListTag) ListTag.createUnchecked(CompoundTag.class); - var3.write(paletteList); - var0.put(var1, paletteList); - int var8 = Math.max(4, MCAMth.ceillog2(paletteList.size())); - MCABitStorage var9 = new MCABitStorage(var8, 4096); - for(int var10 = 0; var10 < var6.length; var10++) { - var9.set(var10, var6[var10]); - } - var0.putLongArray(var2, var9.getRaw()); - } - - public boolean maybeHas(Predicate var0) { - return this.palette.maybeHas(var0); - } - - public void count(MCACountConsumer var0) { - Int2IntOpenHashMap int2IntOpenHashMap = new Int2IntOpenHashMap(); - this.storage.getAll(var1 -> int2IntOpenHashMap.put(var1, int2IntOpenHashMap.get(var1) + 1)); - int2IntOpenHashMap.int2IntEntrySet().forEach(var1 -> var0.accept(this.palette.valueFor(var1.getIntKey()), var1.getIntValue())); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAQuartPos.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAQuartPos.java deleted file mode 100644 index a98f4d976..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAQuartPos.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -public final class MCAQuartPos { - public static final int BITS = 2; - - public static final int SIZE = 4; - - private static final int SECTION_TO_QUARTS_BITS = 2; - - public static int fromBlock(int var0) { - return var0 >> 2; - } - - public static int toBlock(int var0) { - return var0 << 2; - } - - public static int fromSection(int var0) { - return var0 << 2; - } - - public static int toSection(int var0) { - return var0 >> 2; - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAWrappedPalettedContainer.java b/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAWrappedPalettedContainer.java deleted file mode 100644 index fcd7edd5c..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/mca/palette/MCAWrappedPalettedContainer.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.mca.palette; - -import com.volmit.iris.util.nbt.tag.CompoundTag; -import lombok.RequiredArgsConstructor; - -import java.util.function.Function; - -@RequiredArgsConstructor -public class MCAWrappedPalettedContainer implements MCAPaletteAccess { - private final MCAPalettedContainer container; - private final Function reader; - private final Function writer; - - public void setBlock(int x, int y, int z, CompoundTag data) { - container.set(x, y, z, writer.apply(data)); - } - - public CompoundTag getBlock(int x, int y, int z) { - return reader.apply(container.get(x, y, z)); - } - - public void writeToSection(CompoundTag tag) { - container.write(tag, "Palette", "BlockStates"); - } - - public void readFromSection(CompoundTag tag) { - container.read(tag.getListTag("Palette"), tag.getLongArrayTag("BlockStates").getValue()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/ArrayTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/ArrayTag.java deleted file mode 100644 index 721ea1083..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/ArrayTag.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -import java.lang.reflect.Array; - -/** - * ArrayTag is an abstract representation of any NBT array tag. - * For implementations see {@link ByteArrayTag}, {@link IntArrayTag}, {@link LongArrayTag}. - * - * @param - * The array type. - */ -public abstract class ArrayTag extends Tag { - - public ArrayTag(T value) { - super(value); - if(!value.getClass().isArray()) { - throw new UnsupportedOperationException("type of array tag must be an array"); - } - } - - public int length() { - return Array.getLength(getValue()); - } - - @Override - public T getValue() { - return super.getValue(); - } - - @Override - public void setValue(T value) { - super.setValue(value); - } - - @Override - public String valueToString(int maxDepth) { - return arrayToString("", ""); - } - - protected String arrayToString(@SuppressWarnings("SameParameterValue") String prefix, @SuppressWarnings("SameParameterValue") String suffix) { - StringBuilder sb = new StringBuilder("[").append(prefix).append("".equals(prefix) ? "" : ";"); - for(int i = 0; i < length(); i++) { - sb.append(i == 0 ? "" : ",").append(Array.get(getValue(), i)).append(suffix); - } - sb.append("]"); - return sb.toString(); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/ByteArrayTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/ByteArrayTag.java deleted file mode 100644 index 8b94784c3..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/ByteArrayTag.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -import java.util.Arrays; - -public class ByteArrayTag extends ArrayTag implements Comparable { - - public static final byte ID = 7; - public static final byte[] ZERO_VALUE = new byte[0]; - - public ByteArrayTag() { - super(ZERO_VALUE); - } - - public ByteArrayTag(byte[] value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(getValue(), ((ByteArrayTag) other).getValue()); - } - - @Override - public int hashCode() { - return Arrays.hashCode(getValue()); - } - - @Override - public int compareTo(ByteArrayTag other) { - return Integer.compare(length(), other.length()); - } - - @Override - public ByteArrayTag clone() { - return new ByteArrayTag(Arrays.copyOf(getValue(), length())); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/ByteTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/ByteTag.java deleted file mode 100644 index cabd9a107..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/ByteTag.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public class ByteTag extends NumberTag implements Comparable { - - public static final byte ID = 1; - public static final byte ZERO_VALUE = 0; - - public ByteTag() { - super(ZERO_VALUE); - } - - public ByteTag(byte value) { - super(value); - } - - public ByteTag(boolean value) { - super((byte) (value ? 1 : 0)); - } - - @Override - public byte getID() { - return ID; - } - - public boolean asBoolean() { - return getValue() > 0; - } - - public void setValue(byte value) { - super.setValue(value); - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && asByte() == ((ByteTag) other).asByte(); - } - - @Override - public int compareTo(ByteTag other) { - return getValue().compareTo(other.getValue()); - } - - @Override - public ByteTag clone() { - return new ByteTag(getValue()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/CompoundTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/CompoundTag.java deleted file mode 100644 index d610eab3a..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/CompoundTag.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -import com.volmit.iris.engine.data.io.MaxDepthIO; -import com.volmit.iris.util.collection.KMap; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.BiConsumer; - -@SuppressWarnings("ALL") -public class CompoundTag extends Tag>> implements Iterable>>, Comparable, MaxDepthIO { - - public static final byte ID = 10; - - public CompoundTag() { - super(createEmptyValue()); - } - - private static Map> createEmptyValue() { - return new KMap<>(); - } - - @Override - public byte getID() { - return ID; - } - - public int size() { - return getValue().size(); - } - - public Tag remove(String key) { - return getValue().remove(key); - } - - public void clear() { - getValue().clear(); - } - - public boolean containsKey(String key) { - return getValue().containsKey(key); - } - - public boolean containsValue(Tag value) { - return getValue().containsValue(value); - } - - public Collection> values() { - return getValue().values(); - } - - public Set keySet() { - return getValue().keySet(); - } - - public Set>> entrySet() { - return new NonNullEntrySet<>(getValue().entrySet()); - } - - @Override - public Iterator>> iterator() { - return entrySet().iterator(); - } - - public void forEach(BiConsumer> action) { - getValue().forEach(action); - } - - public > C get(String key, Class type) { - Tag t = getValue().get(key); - if(t != null) { - return type.cast(t); - } - return null; - } - - public Tag get(String key) { - return getValue().get(key); - } - - public ByteTag getByteTag(String key) { - return get(key, ByteTag.class); - } - - public ShortTag getShortTag(String key) { - return get(key, ShortTag.class); - } - - public IntTag getIntTag(String key) { - return get(key, IntTag.class); - } - - public LongTag getLongTag(String key) { - return get(key, LongTag.class); - } - - public FloatTag getFloatTag(String key) { - return get(key, FloatTag.class); - } - - public DoubleTag getDoubleTag(String key) { - return get(key, DoubleTag.class); - } - - public StringTag getStringTag(String key) { - return get(key, StringTag.class); - } - - public ByteArrayTag getByteArrayTag(String key) { - return get(key, ByteArrayTag.class); - } - - public IntArrayTag getIntArrayTag(String key) { - return get(key, IntArrayTag.class); - } - - public LongArrayTag getLongArrayTag(String key) { - return get(key, LongArrayTag.class); - } - - public ListTag getListTag(String key) { - return get(key, ListTag.class); - } - - public CompoundTag getCompoundTag(String key) { - return get(key, CompoundTag.class); - } - - public boolean getBoolean(String key) { - Tag t = get(key); - return t instanceof ByteTag && ((ByteTag) t).asByte() > 0; - } - - public byte getByte(String key) { - ByteTag t = getByteTag(key); - return t == null ? ByteTag.ZERO_VALUE : t.asByte(); - } - - public short getShort(String key) { - ShortTag t = getShortTag(key); - return t == null ? ShortTag.ZERO_VALUE : t.asShort(); - } - - public int getInt(String key) { - IntTag t = getIntTag(key); - return t == null ? IntTag.ZERO_VALUE : t.asInt(); - } - - public long getLong(String key) { - LongTag t = getLongTag(key); - return t == null ? LongTag.ZERO_VALUE : t.asLong(); - } - - public float getFloat(String key) { - FloatTag t = getFloatTag(key); - return t == null ? FloatTag.ZERO_VALUE : t.asFloat(); - } - - public double getDouble(String key) { - DoubleTag t = getDoubleTag(key); - return t == null ? DoubleTag.ZERO_VALUE : t.asDouble(); - } - - public String getString(String key) { - StringTag t = getStringTag(key); - return t == null ? StringTag.ZERO_VALUE : t.getValue(); - } - - public byte[] getByteArray(String key) { - ByteArrayTag t = getByteArrayTag(key); - return t == null ? ByteArrayTag.ZERO_VALUE : t.getValue(); - } - - public int[] getIntArray(String key) { - IntArrayTag t = getIntArrayTag(key); - return t == null ? IntArrayTag.ZERO_VALUE : t.getValue(); - } - - public long[] getLongArray(String key) { - LongArrayTag t = getLongArrayTag(key); - return t == null ? LongArrayTag.ZERO_VALUE : t.getValue(); - } - - public Tag put(String key, Tag tag) { - return getValue().put(Objects.requireNonNull(key), Objects.requireNonNull(tag)); - } - - public Tag putBoolean(String key, boolean value) { - return put(key, new ByteTag(value)); - } - - public Tag putByte(String key, byte value) { - return put(key, new ByteTag(value)); - } - - public Tag putShort(String key, short value) { - return put(key, new ShortTag(value)); - } - - public Tag putInt(String key, int value) { - return put(key, new IntTag(value)); - } - - public Tag putLong(String key, long value) { - return put(key, new LongTag(value)); - } - - public Tag putFloat(String key, float value) { - return put(key, new FloatTag(value)); - } - - public Tag putDouble(String key, double value) { - return put(key, new DoubleTag(value)); - } - - public Tag putString(String key, String value) { - return put(key, new StringTag(value)); - } - - public Tag putByteArray(String key, byte[] value) { - return put(key, new ByteArrayTag(value)); - } - - public Tag putIntArray(String key, int[] value) { - return put(key, new IntArrayTag(value)); - } - - public Tag putLongArray(String key, long[] value) { - return put(key, new LongArrayTag(value)); - } - - @Override - public String valueToString(int maxDepth) { - StringBuilder sb = new StringBuilder("{"); - boolean first = true; - for(Map.Entry> e : getValue().entrySet()) { - sb.append(first ? "" : ",") - .append(escapeString(e.getKey(), false)).append(":") - .append(e.getValue().toString(decrementMaxDepth(maxDepth))); - first = false; - } - sb.append("}"); - return sb.toString(); - } - - @Override - public boolean equals(Object other) { - if(this == other) { - return true; - } - if(!super.equals(other) || size() != ((CompoundTag) other).size()) { - return false; - } - for(Map.Entry> e : getValue().entrySet()) { - Tag v; - if((v = ((CompoundTag) other).get(e.getKey())) == null || !e.getValue().equals(v)) { - return false; - } - } - return true; - } - - @Override - public int compareTo(CompoundTag o) { - return Integer.compare(size(), o.getValue().size()); - } - - @Override - public CompoundTag clone() { - CompoundTag copy = new CompoundTag(); - for(Map.Entry> e : getValue().entrySet()) { - copy.put(e.getKey(), e.getValue().clone()); - } - return copy; - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/DoubleTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/DoubleTag.java deleted file mode 100644 index cc66c0d50..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/DoubleTag.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public class DoubleTag extends NumberTag implements Comparable { - - public static final byte ID = 6; - public static final double ZERO_VALUE = 0.0D; - - public DoubleTag() { - super(ZERO_VALUE); - } - - public DoubleTag(double value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - public void setValue(double value) { - super.setValue(value); - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && getValue().equals(((DoubleTag) other).getValue()); - } - - @Override - public int compareTo(DoubleTag other) { - return getValue().compareTo(other.getValue()); - } - - @Override - public DoubleTag clone() { - return new DoubleTag(getValue()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/EndTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/EndTag.java deleted file mode 100644 index 69bf51145..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/EndTag.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public final class EndTag extends Tag { - - public static final byte ID = 0; - public static final EndTag INSTANCE = new EndTag(); - - private EndTag() { - super(null); - } - - @Override - public byte getID() { - return ID; - } - - @Override - protected Void checkValue(Void value) { - return value; - } - - @Override - public String valueToString(int maxDepth) { - return "\"end\""; - } - - @Override - public EndTag clone() { - return INSTANCE; - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/FloatTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/FloatTag.java deleted file mode 100644 index 1f626de61..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/FloatTag.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public class FloatTag extends NumberTag implements Comparable { - - public static final byte ID = 5; - public static final float ZERO_VALUE = 0.0F; - - public FloatTag() { - super(ZERO_VALUE); - } - - public FloatTag(float value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - public void setValue(float value) { - super.setValue(value); - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && getValue().equals(((FloatTag) other).getValue()); - } - - @Override - public int compareTo(FloatTag other) { - return getValue().compareTo(other.getValue()); - } - - @Override - public FloatTag clone() { - return new FloatTag(getValue()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/IntArrayTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/IntArrayTag.java deleted file mode 100644 index 9fde7135b..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/IntArrayTag.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -import java.util.Arrays; - -public class IntArrayTag extends ArrayTag implements Comparable { - - public static final byte ID = 11; - public static final int[] ZERO_VALUE = new int[0]; - - public IntArrayTag() { - super(ZERO_VALUE); - } - - public IntArrayTag(int[] value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(getValue(), ((IntArrayTag) other).getValue()); - } - - @Override - public int hashCode() { - return Arrays.hashCode(getValue()); - } - - @Override - public int compareTo(IntArrayTag other) { - return Integer.compare(length(), other.length()); - } - - @Override - public IntArrayTag clone() { - return new IntArrayTag(Arrays.copyOf(getValue(), length())); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/IntTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/IntTag.java deleted file mode 100644 index 3949bb98e..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/IntTag.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public class IntTag extends NumberTag implements Comparable { - - public static final byte ID = 3; - public static final int ZERO_VALUE = 0; - - public IntTag() { - super(ZERO_VALUE); - } - - public IntTag(int value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - public void setValue(int value) { - super.setValue(value); - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && asInt() == ((IntTag) other).asInt(); - } - - @Override - public int compareTo(IntTag other) { - return getValue().compareTo(other.getValue()); - } - - @Override - public IntTag clone() { - return new IntTag(getValue()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/ListTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/ListTag.java deleted file mode 100644 index 8e71fc360..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/ListTag.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -import com.volmit.iris.engine.data.io.MaxDepthIO; -import com.volmit.iris.util.collection.KList; - -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.function.Consumer; - -/** - * ListTag represents a typed List in the nbt structure. - * An empty {@link ListTag} created using {@link ListTag#createUnchecked(Class)} will be of unknown type - * and returns an {@link EndTag}{@code .class} in {@link ListTag#getTypeClass()}. - * The type of an empty untyped {@link ListTag} can be set by using any of the {@code add()} - * methods or any of the {@code as...List()} methods. - */ -@SuppressWarnings("ALL") -public class ListTag> extends Tag> implements Iterable, Comparable>, MaxDepthIO { - - public static final byte ID = 9; - - private Class typeClass = null; - - private ListTag() { - super(createEmptyValue(3)); - } - - /** - * @param typeClass - * The exact class of the elements - * @throws IllegalArgumentException - * When {@code typeClass} is {@link EndTag}{@code .class} - * @throws NullPointerException - * When {@code typeClass} is {@code null} - */ - public ListTag(Class typeClass) throws IllegalArgumentException, NullPointerException { - super(createEmptyValue(3)); - if(typeClass == EndTag.class) { - throw new IllegalArgumentException("cannot create ListTag with EndTag elements"); - } - this.typeClass = Objects.requireNonNull(typeClass); - } - - /** - *

Creates a non-type-safe ListTag. Its element type will be set after the first - * element was added.

- * - *

This is an internal helper method for cases where the element type is not known - * at construction time. Use {@link #ListTag(Class)} when the type is known.

- * - * @return A new non-type-safe ListTag - */ - public static ListTag createUnchecked(Class typeClass) { - ListTag list = new ListTag<>(); - list.typeClass = typeClass; - return list; - } - - /** - *

Creates an empty mutable list to be used as empty value of ListTags.

- * - * @param - * Type of the list elements - * @param initialCapacity - * The initial capacity of the returned List - * @return An instance of {@link List} with an initial capacity of 3 - */ - private static List createEmptyValue(@SuppressWarnings("SameParameterValue") int initialCapacity) { - return new KList<>(initialCapacity); - } - - public ListTag makeAtomic() { - setValue(new CopyOnWriteArrayList<>(getValue())); - return this; - } - - @Override - public byte getID() { - return ID; - } - - public Class getTypeClass() { - return typeClass == null ? EndTag.class : typeClass; - } - - public int size() { - return getValue().size(); - } - - public T remove(int index) { - return getValue().remove(index); - } - - public void clear() { - getValue().clear(); - } - - public boolean contains(T t) { - return getValue().contains(t); - } - - public boolean containsAll(Collection> tags) { - return getValue().containsAll(tags); - } - - public void sort(Comparator comparator) { - getValue().sort(comparator); - } - - @Override - public Iterator iterator() { - return getValue().iterator(); - } - - @Override - public void forEach(Consumer action) { - getValue().forEach(action); - } - - public T set(int index, T t) { - return getValue().set(index, Objects.requireNonNull(t)); - } - - /** - * Adds a Tag to this ListTag after the last index. - * - * @param t - * The element to be added. - */ - public void add(T t) { - add(size(), t); - } - - public void add(int index, T t) { - Objects.requireNonNull(t); - if(typeClass == null || typeClass == EndTag.class) { - typeClass = t.getClass(); - } else if(typeClass != t.getClass()) { - throw new ClassCastException( - String.format("cannot add %s to ListTag<%s>", - t.getClass().getSimpleName(), - typeClass.getSimpleName())); - } - getValue().add(index, t); - } - - public void addAll(Collection t) { - for(T tt : t) { - add(tt); - } - } - - public void addAll(int index, Collection t) { - int i = 0; - for(T tt : t) { - add(index + i, tt); - i++; - } - } - - public void addBoolean(boolean value) { - addUnchecked(new ByteTag(value)); - } - - public void addByte(byte value) { - addUnchecked(new ByteTag(value)); - } - - public void addShort(short value) { - addUnchecked(new ShortTag(value)); - } - - public void addInt(int value) { - addUnchecked(new IntTag(value)); - } - - public void addLong(long value) { - addUnchecked(new LongTag(value)); - } - - public void addFloat(float value) { - addUnchecked(new FloatTag(value)); - } - - public void addDouble(double value) { - addUnchecked(new DoubleTag(value)); - } - - public void addString(String value) { - addUnchecked(new StringTag(value)); - } - - public void addByteArray(byte[] value) { - addUnchecked(new ByteArrayTag(value)); - } - - public void addIntArray(int[] value) { - addUnchecked(new IntArrayTag(value)); - } - - public void addLongArray(long[] value) { - addUnchecked(new LongArrayTag(value)); - } - - public T get(int index) { - return getValue().get(index); - } - - public int indexOf(T t) { - return getValue().indexOf(t); - } - - @SuppressWarnings("unchecked") - public > ListTag asTypedList(Class type) { - checkTypeClass(type); - typeClass = type; - return (ListTag) this; - } - - public ListTag asByteTagList() { - return asTypedList(ByteTag.class); - } - - public ListTag asShortTagList() { - return asTypedList(ShortTag.class); - } - - public ListTag asIntTagList() { - return asTypedList(IntTag.class); - } - - public ListTag asLongTagList() { - return asTypedList(LongTag.class); - } - - public ListTag asFloatTagList() { - return asTypedList(FloatTag.class); - } - - public ListTag asDoubleTagList() { - return asTypedList(DoubleTag.class); - } - - public ListTag asStringTagList() { - return asTypedList(StringTag.class); - } - - public ListTag asByteArrayTagList() { - return asTypedList(ByteArrayTag.class); - } - - public ListTag asIntArrayTagList() { - return asTypedList(IntArrayTag.class); - } - - public ListTag asLongArrayTagList() { - return asTypedList(LongArrayTag.class); - } - - @SuppressWarnings("unchecked") - public ListTag> asListTagList() { - checkTypeClass(ListTag.class); - typeClass = ListTag.class; - return (ListTag>) this; - } - - public ListTag asCompoundTagList() { - return asTypedList(CompoundTag.class); - } - - @Override - public String valueToString(int maxDepth) { - StringBuilder sb = new StringBuilder("{\"type\":\"").append(getTypeClass().getSimpleName()).append("\",\"list\":["); - for(int i = 0; i < size(); i++) { - sb.append(i > 0 ? "," : "").append(get(i).valueToString(decrementMaxDepth(maxDepth))); - } - sb.append("]}"); - return sb.toString(); - } - - @Override - public boolean equals(Object other) { - if(this == other) { - return true; - } - if(!super.equals(other) || size() != ((ListTag) other).size() || getTypeClass() != ((ListTag) other).getTypeClass()) { - return false; - } - for(int i = 0; i < size(); i++) { - if(!get(i).equals(((ListTag) other).get(i))) { - return false; - } - } - return true; - } - - @Override - public int hashCode() { - return Objects.hash(getValue().hashCode()); - } - - @Override - public int compareTo(ListTag o) { - return Integer.compare(size(), o.getValue().size()); - } - - @SuppressWarnings("unchecked") - @Override - public ListTag clone() { - ListTag copy = new ListTag<>(); - // assure type safety for clone - copy.typeClass = typeClass; - for(T t : getValue()) { - copy.add((T) t.clone()); - } - return copy; - } - - //TODO: make private - @SuppressWarnings("unchecked") - public void addUnchecked(Tag tag) { - if(typeClass != null && typeClass != tag.getClass() && typeClass != EndTag.class) { - throw new IllegalArgumentException(String.format( - "cannot add %s to ListTag<%s>", - tag.getClass().getSimpleName(), typeClass.getSimpleName())); - } - add(size(), (T) tag); - } - - private void checkTypeClass(Class clazz) { - if(typeClass != null && typeClass != EndTag.class && typeClass != clazz) { - throw new ClassCastException(String.format( - "cannot cast ListTag<%s> to ListTag<%s>", - typeClass.getSimpleName(), clazz.getSimpleName())); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/LongArrayTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/LongArrayTag.java deleted file mode 100644 index 4707b5f55..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/LongArrayTag.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -import java.util.Arrays; - -public class LongArrayTag extends ArrayTag implements Comparable { - - public static final byte ID = 12; - public static final long[] ZERO_VALUE = new long[0]; - - public LongArrayTag() { - super(ZERO_VALUE); - } - - public LongArrayTag(long[] value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(getValue(), ((LongArrayTag) other).getValue()); - } - - @Override - public int hashCode() { - return Arrays.hashCode(getValue()); - } - - @Override - public int compareTo(LongArrayTag other) { - return Integer.compare(length(), other.length()); - } - - @Override - public LongArrayTag clone() { - return new LongArrayTag(Arrays.copyOf(getValue(), length())); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/LongTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/LongTag.java deleted file mode 100644 index d240b158f..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/LongTag.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public class LongTag extends NumberTag implements Comparable { - - public static final byte ID = 4; - public static final long ZERO_VALUE = 0L; - - public LongTag() { - super(ZERO_VALUE); - } - - public LongTag(long value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - public void setValue(long value) { - super.setValue(value); - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && asLong() == ((LongTag) other).asLong(); - } - - @Override - public int compareTo(LongTag other) { - return getValue().compareTo(other.getValue()); - } - - @Override - public LongTag clone() { - return new LongTag(getValue()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/NonNullEntrySet.java b/src/main/java/com/volmit/iris/util/nbt/tag/NonNullEntrySet.java deleted file mode 100644 index 5640a53ff..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/NonNullEntrySet.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * A decorator for the Set returned by CompoundTag#entrySet() - * that disallows setting null values. - */ -@SuppressWarnings("ClassCanBeRecord") -class NonNullEntrySet implements Set> { - - private final Set> set; - - NonNullEntrySet(Set> set) { - this.set = set; - } - - @Override - public int size() { - return set.size(); - } - - @Override - public boolean isEmpty() { - return set.isEmpty(); - } - - @Override - public boolean contains(Object o) { - return set.contains(o); - } - - @Override - public Iterator> iterator() { - return new NonNullEntrySetIterator(set.iterator()); - } - - @Override - public Object[] toArray() { - return set.toArray(); - } - - @Override - public T[] toArray(T[] a) { - return set.toArray(a); - } - - @Override - public boolean add(Map.Entry kvEntry) { - return set.add(kvEntry); - } - - @Override - public boolean remove(Object o) { - return set.remove(o); - } - - @Override - public boolean containsAll(Collection c) { - return set.containsAll(c); - } - - @Override - public boolean addAll(Collection> c) { - return set.addAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return set.retainAll(c); - } - - @Override - public boolean removeAll(Collection c) { - return set.removeAll(c); - } - - @Override - public void clear() { - set.clear(); - } - - class NonNullEntrySetIterator implements Iterator> { - - private final Iterator> iterator; - - NonNullEntrySetIterator(Iterator> iterator) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Map.Entry next() { - return new NonNullEntry(iterator.next()); - } - } - - class NonNullEntry implements Map.Entry { - - private final Map.Entry entry; - - NonNullEntry(Map.Entry entry) { - this.entry = entry; - } - - @Override - public K getKey() { - return entry.getKey(); - } - - @Override - public V getValue() { - return entry.getValue(); - } - - @Override - public V setValue(V value) { - if(value == null) { - throw new NullPointerException(getClass().getSimpleName() + " does not allow setting null"); - } - return entry.setValue(value); - } - - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Override - public boolean equals(Object o) { - return entry.equals(o); - } - - @Override - public int hashCode() { - return entry.hashCode(); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/NumberTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/NumberTag.java deleted file mode 100644 index ca66a70f1..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/NumberTag.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public abstract class NumberTag> extends Tag { - - public NumberTag(T value) { - super(value); - } - - public byte asByte() { - return getValue().byteValue(); - } - - public short asShort() { - return getValue().shortValue(); - } - - public int asInt() { - return getValue().intValue(); - } - - public long asLong() { - return getValue().longValue(); - } - - public float asFloat() { - return getValue().floatValue(); - } - - public double asDouble() { - return getValue().doubleValue(); - } - - @Override - public String valueToString(int maxDepth) { - return getValue().toString(); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/ShortTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/ShortTag.java deleted file mode 100644 index b92e939fe..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/ShortTag.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public class ShortTag extends NumberTag implements Comparable { - - public static final byte ID = 2; - public static final short ZERO_VALUE = 0; - - public ShortTag() { - super(ZERO_VALUE); - } - - public ShortTag(short value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - public void setValue(short value) { - super.setValue(value); - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && asShort() == ((ShortTag) other).asShort(); - } - - @Override - public int compareTo(ShortTag other) { - return getValue().compareTo(other.getValue()); - } - - @Override - public ShortTag clone() { - return new ShortTag(getValue()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/StringTag.java b/src/main/java/com/volmit/iris/util/nbt/tag/StringTag.java deleted file mode 100644 index b135dc53d..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/StringTag.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -public class StringTag extends Tag implements Comparable { - - public static final byte ID = 8; - public static final String ZERO_VALUE = ""; - - public StringTag() { - super(ZERO_VALUE); - } - - public StringTag(String value) { - super(value); - } - - @Override - public byte getID() { - return ID; - } - - @Override - public String getValue() { - return super.getValue(); - } - - @Override - public void setValue(String value) { - super.setValue(value); - } - - @Override - public String valueToString(int maxDepth) { - return escapeString(getValue(), false); - } - - @Override - public boolean equals(Object other) { - return super.equals(other) && getValue().equals(((StringTag) other).getValue()); - } - - @Override - public int compareTo(StringTag o) { - return getValue().compareTo(o.getValue()); - } - - @Override - public StringTag clone() { - return new StringTag(getValue()); - } -} diff --git a/src/main/java/com/volmit/iris/util/nbt/tag/Tag.java b/src/main/java/com/volmit/iris/util/nbt/tag/Tag.java deleted file mode 100644 index a4e592797..000000000 --- a/src/main/java/com/volmit/iris/util/nbt/tag/Tag.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.nbt.tag; - -import com.volmit.iris.engine.data.io.MaxDepthReachedException; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Base class for all NBT tags. - * - *

Nesting

- *

All methods serializing instances or deserializing data track the nesting levels to prevent - * circular references or malicious data which could, when deserialized, result in thousands - * of instances causing a denial of service.

- * - *

These methods have a parameter for the maximum nesting depth they are allowed to traverse. A - * value of {@code 0} means that only the object itself, but no nested objects may be processed. - * If an instance is nested further than allowed, a {@link MaxDepthReachedException} will be thrown. - * Providing a negative maximum nesting depth will cause an {@code IllegalArgumentException} - * to be thrown.

- * - *

Some methods do not provide a parameter to specify the maximum nesting depth, but instead use - * {@link #DEFAULT_MAX_DEPTH}, which is also the maximum used by Minecraft. This is documented for - * the respective methods.

- * - *

If custom NBT tags contain objects other than NBT tags, which can be nested as well, then there - * is no guarantee that {@code MaxDepthReachedException}s are thrown for them. The respective class - * will document this behavior accordingly.

- * - * @param - * The type of the contained value - */ -public abstract class Tag implements Cloneable { - - /** - * The default maximum depth of the NBT structure. - */ - public static final int DEFAULT_MAX_DEPTH = 512; - - private static final Map ESCAPE_CHARACTERS; - private static final Pattern ESCAPE_PATTERN = Pattern.compile("[\\\\\n\t\r\"]"); - private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-+]+"); - - static { - final Map temp = new HashMap<>(); - temp.put("\\", "\\\\\\\\"); - temp.put("\n", "\\\\n"); - temp.put("\t", "\\\\t"); - temp.put("\r", "\\\\r"); - temp.put("\"", "\\\\\""); - //noinspection Java9CollectionFactory - ESCAPE_CHARACTERS = Collections.unmodifiableMap(temp); - } - - private T value; - - /** - * Initializes this Tag with some value. If the value is {@code null}, it will - * throw a {@code NullPointerException} - * - * @param value - * The value to be set for this Tag. - */ - public Tag(T value) { - setValue(value); - } - - /** - * Escapes a string to fit into a JSON-like string representation for Minecraft - * or to create the JSON string representation of a Tag returned from {@link Tag#toString()} - * - * @param s - * The string to be escaped. - * @param lenient - * {@code true} if it should force double quotes ({@code "}) at the start and - * the end of the string. - * @return The escaped string. - */ - @SuppressWarnings("StringBufferMayBeStringBuilder") - protected static String escapeString(String s, @SuppressWarnings("SameParameterValue") boolean lenient) { - StringBuffer sb = new StringBuffer(); - Matcher m = ESCAPE_PATTERN.matcher(s); - while(m.find()) { - m.appendReplacement(sb, ESCAPE_CHARACTERS.get(m.group())); - } - m.appendTail(sb); - m = NON_QUOTE_PATTERN.matcher(s); - if(!lenient || !m.matches()) { - sb.insert(0, "\"").append("\""); - } - return sb.toString(); - } - - /** - * @return This Tag's ID, usually used for serialization and deserialization. - */ - public abstract byte getID(); - - /** - * @return The value of this Tag. - */ - public T getValue() { - return value; - } - - /** - * Sets the value for this Tag directly. - * - * @param value - * The value to be set. - * @throws NullPointerException - * If the value is null - */ - protected void setValue(T value) { - this.value = checkValue(value); - } - - /** - * Checks if the value {@code value} is {@code null}. - * - * @param value - * The value to check - * @return The parameter {@code value} - * @throws NullPointerException - * If {@code value} was {@code null} - */ - protected T checkValue(T value) { - return Objects.requireNonNull(value); - } - - /** - * Calls {@link Tag#toString(int)} with an initial depth of {@code 0}. - * - * @throws MaxDepthReachedException - * If the maximum nesting depth is exceeded. - * @see Tag#toString(int) - */ - @Override - public final String toString() { - return toString(DEFAULT_MAX_DEPTH); - } - - /** - * Creates a string representation of this Tag in a valid JSON format. - * - * @param maxDepth - * The maximum nesting depth. - * @return The string representation of this Tag. - * @throws MaxDepthReachedException - * If the maximum nesting depth is exceeded. - */ - public String toString(int maxDepth) { - return "{\"type\":\"" + getClass().getSimpleName() + "\"," + - "\"value\":" + valueToString(maxDepth) + "}"; - } - - /** - * Calls {@link Tag#valueToString(int)} with {@link Tag#DEFAULT_MAX_DEPTH}. - * - * @return The string representation of the value of this Tag. - * @throws MaxDepthReachedException - * If the maximum nesting depth is exceeded. - */ - public String valueToString() { - return valueToString(DEFAULT_MAX_DEPTH); - } - - /** - * Returns a JSON representation of the value of this Tag. - * - * @param maxDepth - * The maximum nesting depth. - * @return The string representation of the value of this Tag. - * @throws MaxDepthReachedException - * If the maximum nesting depth is exceeded. - */ - public abstract String valueToString(int maxDepth); - - /** - * Returns whether this Tag and some other Tag are equal. - * They are equal if {@code other} is not {@code null} and they are of the same class. - * Custom Tag implementations should overwrite this but check the result - * of this {@code super}-method while comparing. - * - * @param other - * The Tag to compare to. - * @return {@code true} if they are equal based on the conditions mentioned above. - */ - @Override - public boolean equals(Object other) { - return other != null && getClass() == other.getClass(); - } - - /** - * Calculates the hash code of this Tag. Tags which are equal according to {@link Tag#equals(Object)} - * must return an equal hash code. - * - * @return The hash code of this Tag. - */ - @Override - public int hashCode() { - return value.hashCode(); - } - - /** - * Creates a clone of this Tag. - * - * @return A clone of this Tag. - */ - public abstract Tag clone(); -} diff --git a/src/main/java/com/volmit/iris/util/network/DL.java b/src/main/java/com/volmit/iris/util/network/DL.java deleted file mode 100644 index 7fb46f07f..000000000 --- a/src/main/java/com/volmit/iris/util/network/DL.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.network; - -import com.volmit.iris.util.collection.KSet; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.scheduling.ChronoLatch; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.util.Arrays; - -public abstract class DL { - protected File d; - protected URL u; - protected ChronoLatch latch; - protected KSet flags; - protected MeteredOutputStream o; - protected DownloadState state; - protected int timeout; - protected long size; - protected long start; - protected long downloaded; - protected long currentChunk; - protected long lastChunk; - protected long bps; - protected int bufferSize; - protected long lastPull; - protected DownloadMonitor m; - - public DL(URL u, File d, DownloadFlag... downloadFlags) { - this.d = d; - this.u = u; - size = -1; - lastPull = -1; - downloaded = 0; - bufferSize = 8192 * 32; - currentChunk = 0; - lastChunk = -1; - bps = -1; - start = -1; - timeout = 10000; - state = DownloadState.NEW; - flags = new KSet<>(); - latch = new ChronoLatch(500); - - flags.addAll(Arrays.asList(downloadFlags)); - } - - public void monitor(DownloadMonitor m) { - this.m = m; - } - - public void update() { - if(m != null) { - m.onUpdate(state, getProgress(), getElapsed(), getTimeLeft(), bps, getDiskBytesPerSecond(), size, downloaded, bufferSize, getBufferUse()); - } - } - - public boolean hasFlag(DownloadFlag f) { - return flags.contains(f); - } - - public boolean isState(DownloadState s) { - return state.equals(s); - } - - protected void state(DownloadState s) { - this.state = s; - update(); - } - - public int getBufferSize() { - return bufferSize; - } - - public void start() throws IOException { - if(!isState(DownloadState.NEW)) { - throw new DownloadException("Cannot start download while " + state.toString()); - } - - state(DownloadState.STARTING); - - if(hasFlag(DownloadFlag.CALCULATE_SIZE)) { - size = calculateSize(); - } - - start = System.currentTimeMillis(); - downloaded = 0; - bps = 0; - lastChunk = System.currentTimeMillis(); - o = new MeteredOutputStream(new FileOutputStream(d), 100); - openStream(); - state(DownloadState.DOWNLOADING); - } - - protected abstract long download() throws IOException; - - protected abstract void openStream() throws IOException; - - protected abstract void closeStream() throws IOException; - - public void downloadChunk() throws IOException { - if(!isState(DownloadState.DOWNLOADING)) { - throw new DownloadException("Cannot download while " + state.toString()); - } - - long d = download(); - lastPull = d; - - if(d < 0) { - finishDownload(); - return; - } - - downloaded += d; - currentChunk += d; - - double chunkTime = (double) (System.currentTimeMillis() - lastChunk) / 1000D; - bps = (long) ((double) currentChunk / chunkTime); - - if(latch.flip()) { - update(); - } - } - - public double getBufferUse() { - return (double) lastPull / (double) bufferSize; - } - - private void finishDownload() throws IOException { - if(!isState(DownloadState.NEW)) { - throw new DownloadException("Cannot finish download while " + state.toString()); - } - - closeStream(); - o.close(); - state(DownloadState.COMPLETE); - } - - public long getElapsed() { - return System.currentTimeMillis() - start; - } - - public long getRemaining() { - return size - downloaded; - } - - public long getTimeLeft() { - return (long) (((double) getRemaining() / (double) bps) * 1000D); - } - - public long getDiskBytesPerSecond() { - if(o == null) { - return -1; - } - - return o.getBps(); - } - - public long getBytesPerSecond() { - return bps; - } - - public double getProgress() { - return hasProgress() ? ((double) downloaded / (double) size) : -1D; - } - - public boolean hasProgress() { - return size > 0; - } - - private long calculateSize() throws IOException { - URLConnection c = u.openConnection(); - c.setConnectTimeout(timeout); - c.setReadTimeout(timeout); - c.connect(); - return c.getContentLengthLong(); - } - - public enum DownloadFlag { - CALCULATE_SIZE - } - - public enum DownloadState { - NEW, - STARTING, - DOWNLOADING, - FINALIZING, - COMPLETE, - FAILED - } - - public static class ThrottledDownload extends Download { - private final long mbps; - - public ThrottledDownload(URL u, File d, long mbps, DownloadFlag... downloadFlags) { - super(u, d, downloadFlags); - this.mbps = mbps; - } - - @Override - protected long download() throws IOException { - if(getBytesPerSecond() > mbps) { - try { - Thread.sleep(40); - } catch(InterruptedException e) { - e.printStackTrace(); - } - - return IO.transfer(in, o, 8192, mbps / 20); - } - - return IO.transfer(in, o, 8192, bufferSize); - } - } - - public static class DoubleBufferedDownload extends Download { - protected BufferedOutputStream os; - - public DoubleBufferedDownload(URL u, File d, DownloadFlag... downloadFlags) { - super(u, d, downloadFlags); - } - - @Override - protected void openStream() throws IOException { - os = new BufferedOutputStream(o, 8192 * 16); - in = new BufferedInputStream(u.openStream(), 8192 * 16); - buf = new byte[8192 * 2]; - } - } - - public static class Download extends DL { - protected InputStream in; - protected byte[] buf; - - public Download(URL u, File d, DownloadFlag... downloadFlags) { - super(u, d, downloadFlags); - } - - @Override - protected long download() throws IOException { - return IO.transfer(in, o, buf, bufferSize); - } - - @Override - protected void openStream() throws IOException { - in = u.openStream(); - buf = new byte[8192]; - } - - @Override - protected void closeStream() throws IOException { - in.close(); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/network/DownloadException.java b/src/main/java/com/volmit/iris/util/network/DownloadException.java deleted file mode 100644 index 970f6691e..000000000 --- a/src/main/java/com/volmit/iris/util/network/DownloadException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.network; - -import java.io.IOException; - -public class DownloadException extends IOException { - private static final long serialVersionUID = 5137918663903349839L; - - public DownloadException() { - super(); - } - - public DownloadException(String message, Throwable cause) { - super(message, cause); - } - - public DownloadException(String message) { - super(message); - } - - public DownloadException(Throwable cause) { - super(cause); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/network/DownloadMonitor.java b/src/main/java/com/volmit/iris/util/network/DownloadMonitor.java deleted file mode 100644 index 585ab84db..000000000 --- a/src/main/java/com/volmit/iris/util/network/DownloadMonitor.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.network; - -@FunctionalInterface -public interface DownloadMonitor { - void onUpdate(DL.DownloadState state, double progress, long elapsed, long estimated, long bps, long iobps, long size, long downloaded, long buffer, double bufferuse); -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/network/MeteredInputStream.java b/src/main/java/com/volmit/iris/util/network/MeteredInputStream.java deleted file mode 100644 index 4e3bf03f6..000000000 --- a/src/main/java/com/volmit/iris/util/network/MeteredInputStream.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.network; - -import java.io.IOException; -import java.io.InputStream; - -public class MeteredInputStream extends InputStream { - private final InputStream os; - private long written; - private long totalWritten; - private long since; - private boolean auto; - private long interval; - private long bps; - - public MeteredInputStream(InputStream os, long interval) { - this.os = os; - written = 0; - totalWritten = 0; - auto = true; - this.interval = interval; - bps = 0; - since = System.currentTimeMillis(); - } - - public MeteredInputStream(InputStream os) { - this(os, 100); - auto = false; - } - - @Override - public int read() throws IOException { - written++; - totalWritten++; - - if(auto && System.currentTimeMillis() - getSince() > interval) { - pollRead(); - } - - return os.read(); - } - - public long getSince() { - return since; - } - - public long getRead() { - return written; - } - - public long pollRead() { - long w = written; - written = 0; - double secondsElapsedSince = (double) (System.currentTimeMillis() - since) / 1000.0; - bps = (long) ((double) w / secondsElapsedSince); - since = System.currentTimeMillis(); - - return w; - } - - public void close() throws IOException { - os.close(); - } - - public boolean isAuto() { - return auto; - } - - public void setAuto(boolean auto) { - this.auto = auto; - } - - public long getInterval() { - return interval; - } - - public void setInterval(long interval) { - this.interval = interval; - } - - public long getTotalRead() { - return totalWritten; - } - - public long getBps() { - return bps; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/network/MeteredOutputStream.java b/src/main/java/com/volmit/iris/util/network/MeteredOutputStream.java deleted file mode 100644 index e3c2e1bbd..000000000 --- a/src/main/java/com/volmit/iris/util/network/MeteredOutputStream.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.network; - -import java.io.IOException; -import java.io.OutputStream; - -public class MeteredOutputStream extends OutputStream { - private final OutputStream os; - private long written; - private long totalWritten; - private long since; - private boolean auto; - private long interval; - private long bps; - - public MeteredOutputStream(OutputStream os, long interval) { - this.os = os; - written = 0; - totalWritten = 0; - auto = true; - this.interval = interval; - bps = 0; - since = System.currentTimeMillis(); - } - - public MeteredOutputStream(OutputStream os) { - this(os, 100); - auto = false; - } - - @Override - public void write(int b) throws IOException { - os.write(b); - written++; - totalWritten++; - - if(auto && System.currentTimeMillis() - getSince() > interval) { - pollWritten(); - } - } - - public long getSince() { - return since; - } - - public long getWritten() { - return written; - } - - public long pollWritten() { - long w = written; - written = 0; - double secondsElapsedSince = (double) (System.currentTimeMillis() - since) / 1000.0; - bps = (long) ((double) w / secondsElapsedSince); - since = System.currentTimeMillis(); - return w; - } - - public void close() throws IOException { - os.close(); - } - - public boolean isAuto() { - return auto; - } - - public void setAuto(boolean auto) { - this.auto = auto; - } - - public long getInterval() { - return interval; - } - - public void setInterval(long interval) { - this.interval = interval; - } - - public long getTotalWritten() { - return totalWritten; - } - - public long getBps() { - return bps; - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/noise/CNG.java b/src/main/java/com/volmit/iris/util/noise/CNG.java deleted file mode 100644 index 2c4b069b2..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CNG.java +++ /dev/null @@ -1,541 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.AtomicCache; -import com.volmit.iris.engine.object.IRare; -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.cache.FloatBitCache; -import com.volmit.iris.util.cache.FloatCache; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.function.NoiseInjector; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.stream.arithmetic.FittedStream; -import com.volmit.iris.util.stream.sources.CNGStream; -import lombok.Data; - -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; - -@Data -public class CNG { - public static final NoiseInjector ADD = (s, v) -> new double[] {s + v, 1}; - public static final NoiseInjector SRC_SUBTRACT = (s, v) -> new double[] {s - v < 0 ? 0 : s - v, -1}; - public static final NoiseInjector DST_SUBTRACT = (s, v) -> new double[] {v - s < 0 ? 0 : s - v, -1}; - public static final NoiseInjector MULTIPLY = (s, v) -> new double[] {s * v, 0}; - public static final NoiseInjector MAX = (s, v) -> new double[] {Math.max(s, v), 0}; - public static final NoiseInjector MIN = (s, v) -> new double[] {Math.min(s, v), 0}; - public static final NoiseInjector SRC_MOD = (s, v) -> new double[] {s % v, 0}; - public static final NoiseInjector SRC_POW = (s, v) -> new double[] {Math.pow(s, v), 0}; - public static final NoiseInjector DST_MOD = (s, v) -> new double[] {v % s, 0}; - public static final NoiseInjector DST_POW = (s, v) -> new double[] {Math.pow(v, s), 0}; - public static long hits = 0; - public static long creates = 0; - private final double opacity; - private double scale; - private double bakedScale; - private double fscale; - private boolean trueFracturing = false; - private KList children; - private CNG fracture; - private FloatCache cache; - private NoiseGenerator generator; - private NoiseInjector injector; - private RNG rng; - private boolean noscale; - private int oct; - private double patch; - private double up; - private double down; - private double power; - private NoiseStyle leakStyle; - private ProceduralStream customGenerator; - - public CNG(RNG random) { - this(random, 1); - } - - public CNG(RNG random, int octaves) { - this(random, 1D, octaves); - } - - public CNG(RNG random, double opacity, int octaves) { - this(random, NoiseType.SIMPLEX, opacity, octaves); - } - - public CNG(RNG random, NoiseType type, double opacity, int octaves) { - this(random, type.create(random.nextParallelRNG((long) ((1113334944L * opacity) + 12922 + octaves)).lmax()), opacity, octaves); - } - - public CNG(RNG random, NoiseGenerator generator, double opacity, int octaves) { - customGenerator = null; - creates++; - noscale = generator.isNoScale(); - this.oct = octaves; - this.rng = random; - power = 1; - scale = 1; - patch = 1; - bakedScale = 1; - fscale = 1; - down = 0; - up = 0; - fracture = null; - this.generator = generator; - this.opacity = opacity; - this.injector = ADD; - - if(generator instanceof OctaveNoise) { - ((OctaveNoise) generator).setOctaves(octaves); - } - } - - public CNG cellularize(RNG seed, double freq) { - FastNoise cellularFilter = new FastNoise(seed.imax()); - cellularFilter.SetNoiseType(FastNoise.NoiseType.Cellular); - cellularFilter.SetCellularReturnType(FastNoise.CellularReturnType.CellValue); - cellularFilter.SetCellularDistanceFunction(FastNoise.CellularDistanceFunction.Manhattan); - cellularFilter.SetFrequency((float) freq * 0.01f); - - ProceduralStream str = stream(); - - return new CNG(seed, new NoiseGenerator() { - @Override - public double noise(double x) { - return noise(x, 0); - } - - @Override - public double noise(double x, double z) { - return (cellularFilter.GetCellular((float) x, (float) z, str, 1) * 0.5) + 0.5D; - } - - @Override - public double noise(double x, double y, double z) { - return noise(x, y + z); - } - }, 1D, 1); - } - - public CNG cached(int size, String key, File cacheFolder) - { - if(size <= 0) - { - return this; - } - - cache = null; - - File f = new File(new File(cacheFolder, ".cache"), key + ".cnm"); - FloatCache fbc; - boolean cached = false; - if(f.exists()) - { - try { - fbc = new FloatCache(f); - cached = true; - } catch(IOException e) { - fbc = new FloatCache(size, size); - } - } - - else { - fbc = new FloatCache(size, size); - } - - if(!cached) - { - for(int i = 0; i < size; i++) - { - for(int j = 0; j < size; j++) - { - fbc.set(i, j, (float) noise(i, j)); - } - } - - try { - f.getParentFile().mkdirs(); - FileOutputStream fos = new FileOutputStream(f); - DataOutputStream dos = new DataOutputStream(fos); - fbc.writeCache(dos); - dos.close(); - Iris.info("Saved Noise Cache " + f.getName()); - } catch(IOException e) { - throw new RuntimeException(e); - } - } - - cache = fbc; - return this; - } - - public static CNG signature(RNG rng) { - return signature(rng, NoiseType.SIMPLEX); - } - - public static CNG signatureHalf(RNG rng) { - return signatureHalf(rng, NoiseType.SIMPLEX); - } - - public static CNG signatureThick(RNG rng) { - return signatureThick(rng, NoiseType.SIMPLEX); - } - - public static CNG signatureDouble(RNG rng) { - return signatureDouble(rng, NoiseType.SIMPLEX); - } - - public static CNG signatureDouble(RNG rng, NoiseType t) { - return signatureThick(rng, t).fractureWith(signature(rng.nextParallelRNG(4956)), 93); - } - - public static CNG signatureDoubleFast(RNG rng, NoiseType t, NoiseType f) { - return signatureThickFast(rng, t, f) - .fractureWith(signatureFast(rng.nextParallelRNG(4956), t, f), 93); - } - - public static CNG signature(RNG rng, NoiseType t) { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(17), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.9).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.21).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.9), 620), 145), 44).bake(); - // @done - } - - public static CNG signaturePerlin(RNG rng) { - return signaturePerlin(rng, NoiseType.PERLIN); - } - - public static CNG signaturePerlin(RNG rng, NoiseType t) { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(124996), t, 1D, 1) - .fractureWith(new CNG(rng.nextParallelRNG(18), NoiseType.PERLIN, 1, 1).scale(1.25), 250) - .bake(); - // @done - } - - public static CNG signatureFast(RNG rng, NoiseType t, NoiseType f) { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(17), t, 1D, 1) - .fractureWith(new CNG(rng.nextParallelRNG(18), f, 1, 1) - .scale(0.9) - .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) - .scale(0.21) - .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.9), 620), 145), 44) - .bake(); - // @done - } - - public static CNG signatureThick(RNG rng, NoiseType t) { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(133), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.5).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.11).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.4), 620), 145), 44).bake(); - // @done - } - - public static CNG signatureThickFast(RNG rng, NoiseType t, NoiseType f) { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(133), t, 1D, 1) - .fractureWith(new CNG(rng.nextParallelRNG(18), f, 1, 1) - .scale(0.5).fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) - .scale(0.11).fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) - .scale(0.4), 620), 145), 44).bake(); - // @done - } - - public static CNG signatureHalf(RNG rng, NoiseType t) { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(127), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.9).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.21).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.9), 420), 99), 22).bake(); - // @done - } - - public static CNG signatureHalfFast(RNG rng, NoiseType t, NoiseType f) { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(127), t, 1D, 1) - .fractureWith(new CNG(rng.nextParallelRNG(18), f, 1, 1).scale(0.9) - .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.21) - .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.9), 420), 99), 22).bake(); - // @done - } - - public NoiseGenerator getGen() { - return generator; - } - - public ProceduralStream stream() { - return new CNGStream(this); - } - - public ProceduralStream stream(double min, double max) { - return new FittedStream<>(stream(), min, max); - } - - public CNG bake() { - bakedScale *= scale; - scale = 1; - return this; - } - - public CNG child(CNG c) { - if(children == null) { - children = new KList<>(); - } - - children.add(c); - return this; - } - - public RNG getRNG() { - return rng; - } - - public CNG fractureWith(CNG c, double scale) { - fracture = c; - fscale = scale; - return this; - } - - public CNG scale(double c) { - scale = c; - return this; - } - - public CNG patch(double c) { - patch = c; - return this; - } - - public CNG up(double c) { - up = c; - return this; - } - - public CNG down(double c) { - down = c; - return this; - } - - public CNG injectWith(NoiseInjector i) { - injector = i; - return this; - } - - public T fitRarity(KList b, double... dim) { - if(b.size() == 0) { - return null; - } - - if(b.size() == 1) { - return b.get(0); - } - - KList rarityMapped = new KList<>(); - boolean o = false; - int max = 1; - for(T i : b) { - if(i.getRarity() > max) { - max = i.getRarity(); - } - } - - max++; - - for(T i : b) { - for(int j = 0; j < max - i.getRarity(); j++) { - //noinspection AssignmentUsedAsCondition - if(o = !o) { - rarityMapped.add(i); - } else { - rarityMapped.add(0, i); - } - } - } - - if(rarityMapped.size() == 1) { - return rarityMapped.get(0); - } - - if(rarityMapped.isEmpty()) { - throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); - } - - return fit(rarityMapped, dim); - } - - public T fit(T[] v, double... dim) { - if(v.length == 0) { - return null; - } - - if(v.length == 1) { - return v[0]; - } - - return v[fit(0, v.length - 1, dim)]; - } - - public T fit(List v, double... dim) { - if(v.size() == 0) { - return null; - } - - if(v.size() == 1) { - return v.get(0); - } - - try { - return v.get(fit(0, v.size() - 1, dim)); - } catch(Throwable e) { - Iris.reportError(e); - } - - return v.get(0); - } - - public int fit(int min, int max, double... dim) { - if(min == max) { - return min; - } - - double noise = noise(dim); - - return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); - } - - public int fit(double min, double max, double... dim) { - if(min == max) { - return (int) Math.round(min); - } - - double noise = noise(dim); - - return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); - } - - public double fitDouble(double min, double max, double... dim) { - if(min == max) { - return min; - } - - double noise = noise(dim); - - return IrisInterpolation.lerp(min, max, noise); - } - - private double getNoise(double... dim) { - double scale = noscale ? 1 : this.bakedScale * this.scale; - - if(fracture == null || noscale) { - return generator.noise( - (dim.length > 0 ? dim[0] : 0D) * scale, - (dim.length > 1 ? dim[1] : 0D) * scale, - (dim.length > 2 ? dim[2] : 0D) * scale) * opacity; - } - - if(fracture.isTrueFracturing()) { - double x = dim.length > 0 ? dim[0] + ((fracture.noise(dim) - 0.5) * fscale) : 0D; - double y = dim.length > 1 ? dim[1] + ((fracture.noise(dim[1], dim[0]) - 0.5) * fscale) : 0D; - double z = dim.length > 2 ? dim[2] + ((fracture.noise(dim[2], dim[0], dim[1]) - 0.5) * fscale) : 0D; - return generator.noise(x * scale, y * scale, z * scale) * opacity; - } - - double f = fracture.noise(dim) * fscale; - double x = dim.length > 0 ? dim[0] + f : 0D; - double y = dim.length > 1 ? dim[1] - f : 0D; - double z = dim.length > 2 ? dim[2] - f : 0D; - return generator.noise(x * scale, y * scale, z * scale) * opacity; - } - - public double invertNoise(double... dim) { - if(dim.length == 1) { - return noise(-dim[0]); - } else if(dim.length == 2) { - return noise(dim[1], dim[0]); - } else if(dim.length == 3) { - return noise(dim[1], dim[2], dim[0]); - } - - return noise(dim); - } - - public double noiseSym(double... dim) { - return (noise(dim) * 2) - 1; - } - - public double noise(double... dim) { - if(cache != null && dim.length == 2) - { - return cache.get((int)dim[0], (int)dim[1]); - } - - double n = getNoise(dim); - n = power != 1D ? (n < 0 ? -Math.pow(Math.abs(n), power) : Math.pow(n, power)) : n; - double m = 1; - hits += oct; - if(children == null) { - return (n - down + up) * patch; - } - - for(CNG i : children) { - double[] r = injector.combine(n, i.noise(dim)); - n = r[0]; - m += r[1]; - } - - return ((n / m) - down + up) * patch; - } - - public CNG pow(double power) { - this.power = power; - return this; - } - - public CNG oct(int octaves) { - oct = octaves; - return this; - } - - public double getScale() { - return scale; - } - - public boolean isStatic() { - return generator != null && generator.isStatic(); - } - - public static void main(String[] a) - { - CNG cng = NoiseStyle.SIMPLEX.create(new RNG(1234)); - PrecisionStopwatch p = PrecisionStopwatch.start(); - double r = 0; - - for(int i = 0; i < 30000000 * 10; i++) - { - r += cng.fit(-1000, 1000, i, i); - } - - System.out.println(Form.duration(p.getMilliseconds(), 10) + " merged = " + r); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/CNGFactory.java b/src/main/java/com/volmit/iris/util/noise/CNGFactory.java deleted file mode 100644 index ccb9f249e..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CNGFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; - -@FunctionalInterface -public interface CNGFactory { - CNG create(RNG seed); -} diff --git a/src/main/java/com/volmit/iris/util/noise/CachedNoise.java b/src/main/java/com/volmit/iris/util/noise/CachedNoise.java deleted file mode 100644 index e33ed2ccf..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CachedNoise.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; - -public class CachedNoise implements NoiseGenerator { - private final CachedNoiseMap n; - - public CachedNoise(NoiseGenerator generator, int size) { - n = new CachedNoiseMap(size, generator); - } - - @Override - public double noise(double x) { - return n.get((int)Math.round(x), 0); - } - - @Override - public double noise(double x, double z) { - return n.get((int)Math.round(x),(int)Math.round(z)); - } - - @Override - public double noise(double x, double y, double z) { - return n.get((int)Math.round(x),(int)Math.round(z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/CachedNoiseMap.java b/src/main/java/com/volmit/iris/util/noise/CachedNoiseMap.java deleted file mode 100644 index 8d9ca13a2..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CachedNoiseMap.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.hunk.bits.Writable; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.matter.IrisMatter; -import com.volmit.iris.util.matter.Matter; -import com.volmit.iris.util.matter.MatterSlice; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; - -public class CachedNoiseMap implements Writable { - private final Matter noise; - private final MatterSlice slice; - - public CachedNoiseMap(int size, NoiseGenerator cng) - { - noise = new IrisMatter(size, size, 1); - slice = noise.slice(Integer.class); - - for(int i = 0; i < slice.getWidth(); i++) - { - for(int j = 0; j < slice.getHeight(); j++) - { - set(i, j, cng.noise(i, j)); - } - } - } - - public CachedNoiseMap(File file) throws IOException, ClassNotFoundException { - noise = Matter.read(file); - slice = noise.slice(Integer.class); - } - - void write(File file) throws IOException { - noise.write(file); - } - - void set(int x, int y, double value) - { - slice.set(x%slice.getWidth(), y%slice.getHeight(), 0, Float.floatToIntBits((float)value)); - } - - double get(int x, int y) - { - Integer i = slice.get(x%slice.getWidth(), y%slice.getHeight(), 0); - - if(i == null) - { - return 0; - } - - return Float.intBitsToFloat(i); - } - - @Override - public Integer readNodeData(DataInputStream din) throws IOException { - return din.readInt(); - } - - @Override - public void writeNodeData(DataOutputStream dos, Integer integer) throws IOException { - dos.writeInt(integer); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/CellGenerator.java b/src/main/java/com/volmit/iris/util/noise/CellGenerator.java deleted file mode 100644 index ef4913f53..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CellGenerator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; -import lombok.Getter; -import lombok.Setter; - -public class CellGenerator { - private final FastNoiseDouble fn; - private final FastNoiseDouble fd; - private final CNG cng; - - @Getter - @Setter - private double cellScale; - - @Getter - @Setter - private double shuffle; - - public CellGenerator(RNG rng) { - shuffle = 128; - cellScale = 0.73; - cng = CNG.signature(rng.nextParallelRNG(3204)); - RNG rx = rng.nextParallelRNG(8735652); - long s = rx.lmax(); - fn = new FastNoiseDouble(s); - fn.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - fn.setCellularReturnType(FastNoiseDouble.CellularReturnType.CellValue); - fn.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - fd = new FastNoiseDouble(s); - fd.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - fd.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); - fd.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - } - - public double getDistance(double x, double z) { - return ((fd.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle)))) + 1f) / 2f; - } - - public double getDistance(double x, double y, double z) { - return ((fd.GetCellular(((x * cellScale) + (cng.noise(x, y, z) * shuffle)), ((y * cellScale) + (cng.noise(x, y, z) * shuffle)), ((z * cellScale) + (cng.noise(z, y, x) * shuffle)))) + 1f) / 2f; - } - - public double getValue(double x, double z, int possibilities) { - if(possibilities == 1) { - return 0; - } - - return ((fn.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle))) + 1f) / 2f) * (possibilities - 1); - } - - public double getValue(double x, double y, double z, int possibilities) { - if(possibilities == 1) { - return 0; - } - - return ((fn.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((y * 8 * cellScale) + (cng.noise(x, y * 8) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle))) + 1f) / 2f) * (possibilities - 1); - } - - public int getIndex(double x, double z, int possibilities) { - if(possibilities == 1) { - return 0; - } - - return (int) Math.round(getValue(x, z, possibilities)); - } - - public int getIndex(double x, double y, double z, int possibilities) { - if(possibilities == 1) { - return 0; - } - - return (int) Math.round(getValue(x, y, z, possibilities)); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/CellHeightNoise.java b/src/main/java/com/volmit/iris/util/noise/CellHeightNoise.java deleted file mode 100644 index 62e3d1761..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CellHeightNoise.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; - -public class CellHeightNoise implements NoiseGenerator { - private final FastNoiseDouble n; - - public CellHeightNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); - n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - } - - private double filter(double noise) { - return M.clip(1D - ((noise / 2D) + 0.5D), 0D, 1D); - } - - @Override - public double noise(double x) { - return filter(n.GetCellular(x, 0)); - } - - @Override - public double noise(double x, double z) { - return filter(n.GetCellular(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return filter(n.GetCellular(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/CellularNoise.java b/src/main/java/com/volmit/iris/util/noise/CellularNoise.java deleted file mode 100644 index 740c1c4c4..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CellularNoise.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; - -public class CellularNoise implements NoiseGenerator { - private final FastNoise n; - - public CellularNoise(long seed) { - this.n = new FastNoise(new RNG(seed).imax()); - n.SetNoiseType(FastNoise.NoiseType.Cellular); - n.SetCellularReturnType(FastNoise.CellularReturnType.CellValue); - n.SetCellularDistanceFunction(FastNoise.CellularDistanceFunction.Natural); - } - - @Override - public double noise(double x) { - return (n.GetCellular((float) x, 0) / 2D) + 0.5D; - } - - @Override - public double noise(double x, double z) { - return (n.GetCellular((float) x, (float) z) / 2D) + 0.5D; - } - - @Override - public double noise(double x, double y, double z) { - return (n.GetCellular((float) x, (float) y, (float) z) / 2D) + 0.5D; - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/CloverNoise.java b/src/main/java/com/volmit/iris/util/noise/CloverNoise.java deleted file mode 100644 index 8ed0e2be4..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CloverNoise.java +++ /dev/null @@ -1,1097 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -public class CloverNoise implements NoiseGenerator { - private final Noise2D n2; - private final Noise3D n3; - - public CloverNoise(long seed) { - n2 = new CloverNoise.Noise2D(seed); - n3 = new CloverNoise.Noise3D(seed); - } - - @Override - public double noise(double x) { - return n2.noise(x, 0); - } - - @Override - public double noise(double x, double z) { - return n2.noise(x, z); - } - - @Override - public double noise(double x, double y, double z) { - if(z == 0) { - return n2.noise(x, y); - } - - return n3.noise(x, y, z); - } - - /** - * Java implementation of 2D Clover Noise. See https://github.com/ValgoBoi/clover-noise - */ - public static class Noise2D { - private static final long HASH_A = 25214903917L; - private static final long HASH_C = 11L; - private static final long HASH_M = 0x1000000000000L; - private static final double POINT_SPREAD = 0.3; - private static final double CURL_DX = 0.0001; - private final long seed; - - /** - * Constructs a new 2D Clover Noise generator with a specific seed. - * - * @param seed - * The seed for the noise generator. - */ - public Noise2D(long seed) { - this.seed = seed; - } - - /** - * Constructs a new 2D Clover Noise generator, with the seed automatically set to the system time. - */ - public Noise2D() { - this(System.currentTimeMillis()); - } - - private long doHash(long input, long seed) { - input += seed; - - if(input < 0) { - input += HASH_M; - } - - input *= HASH_A; - input += HASH_C; - input %= HASH_M; - - return input; - } - - private double hash(Vector2 position) { - long hash = doHash(seed, (long) Math.floor(position.getX())); - hash = doHash(hash, (long) Math.floor(position.getY())); - hash = doHash(hash, hash * (long) Math.floor(position.getX() + position.getY())); - if(hash < 0) { - hash += HASH_M; - } - - return (double) hash / HASH_M; - } - - private Vector2 offset(Vector2 position) { - double hash = hash(position); - double scale = Math.floor(hash * 50 + 1) / 100; - Vector2 offset = new Vector2(Math.sin(hash * Math.PI * 100), Math.cos(hash * Math.PI * 100)).mult(scale).add(0.5); - return position.add(offset.mult(POINT_SPREAD * 2)).add(0.5 - POINT_SPREAD); - } - - /** - * Generates 2D Clover Noise at a specific point. - * - * @param p - * The point to generate noise at. - * @return The value of noise, from 0 to 1. - */ - public double noise(Vector2 p) { - Vector2 p_floor = p.floor(); - - Vector2 c_11 = offset(p_floor); - Vector2 c_10 = offset(p_floor.add(0, -1)); - Vector2 c_12 = offset(p_floor.add(0, 1)); - Vector2 c_01 = offset(p_floor.add(-1, 0)); - Vector2 c_21 = offset(p_floor.add(1, 0)); - - Vector2 d_p_c11 = p.sub(c_11).yx(); - Vector2 m_p_c11 = d_p_c11.mult(c_11); - - double side_nx = m_p_c11.sub(d_p_c11.mult(c_01)).ymx(); - double side_px = m_p_c11.sub(d_p_c11.mult(c_21)).ymx(); - - Vector2 a, c, d; - - if(side_nx < 0 && p.x < c_11.x || side_px > 0 && p.x > c_11.x) { - double side_py = m_p_c11.sub(d_p_c11.mult(c_12)).ymx(); - - if(side_py > 0) { - a = c_12; - c = c_01; - d = new Vector2(-1, 1); - } else { - a = c_21; - c = c_12; - d = new Vector2(1, 1); - } - } else { - double side_ny = m_p_c11.sub(d_p_c11.mult(c_10)).ymx(); - - if(side_ny > 0) { - a = c_10; - c = c_21; - d = new Vector2(1, -1); - } else { - a = c_01; - c = c_10; - d = new Vector2(-1, -1); - } - } - - d = offset(p_floor.add(d)); - - Vector2 f = a; - Vector2 g = c; - Vector2 h = d; - - Vector2 ac = a.sub(c); - Vector2 bd = c_11.sub(d); - - if(ac.x * ac.x + ac.y * ac.y < bd.x * bd.x + bd.y * bd.y) { - Vector2 pa = p.sub(a); - - if(pa.x * ac.y - pa.y * ac.x > 0.) { - h = c_11; - } - } else { - Vector2 pb = p.sub(c_11); - - if(pb.x * bd.y - pb.y * bd.x > 0) { - f = c_11; - } else { - g = c_11; - } - } - - Vector2 bc_v0 = g.sub(f); - Vector2 bc_v1 = h.sub(f); - Vector2 bc_v2 = p.sub(f); - double den = 1 / (bc_v0.x * bc_v1.y - bc_v1.x * bc_v0.y); - double v = (bc_v2.x * bc_v1.y - bc_v1.x * bc_v2.y) * den; - double w = (bc_v0.x * bc_v2.y - bc_v2.x * bc_v0.y) * den; - double u = 1 - v - w; - - v = v * v * v; - w = w * w * w; - u = u * u * u; - double s = 1 / (u + v + w); - v *= s; - w *= s; - u *= s; - - double fv = hash(f.floor()); - double gv = hash(g.floor()); - double hv = hash(h.floor()); - - return u * fv + v * gv + w * hv; - } - - /** - * Generates 2D Clover Noise at a specific point. - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @return The value of noise, from 0 to 1. - */ - public double noise(double x, double y) { - return noise(new Vector2(x, y)); - } - - /** - * Generates fractal 2D Clover Noise at a specific point. - * - * @param p - * The point to generate noise at. - * @param iterations - * The number of iterations for the fractal noise. - * @return The value of noise, from 0 to 1. - */ - public double fractalNoise(Vector2 p, int iterations) { - double total = 0; - double weight = 1; - double div = 0; - - for(int i = 0; i < iterations; i++) { - total += noise(p.mult(1 / weight)) * weight; - div += weight; - - weight *= 0.4; - } - - return total / div; - } - - /** - * Generates fractal 2D Clover Noise at a specific point. - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @param iterations - * The number of iterations for the fractal noise. - * @return The value of noise, from 0 to 1. - */ - public double fractalNoise(double x, double y, int iterations) { - return fractalNoise(new Vector2(x, y), iterations); - } - - /** - * Generates curl 2D Clover Noise at a specific point. - * - * @param p - * The point to generate noise at. - * @return The value of curl noise, a normalized 2D vector. - */ - public Vector2 curlNoise(Vector2 p) { - double v = noise(p); - double x = noise(p.add(CURL_DX, 0)); - double y = noise(p.add(0, CURL_DX)); - - return new Vector2(v - x, v - y).normalize(); - } - - /** - * Generates curl 2D Clover Noise at a specific point. - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @return The value of curl noise, a normalized 2D vector. - */ - public Vector2 curlNoise(double x, double y) { - return curlNoise(new Vector2(x, y)); - } - - /** - * Generates fractal curl 2D Clover Noise at a specific point. - * - * @param p - * The point to generate noise at. - * @param iterations - * The number of iterations for the fractal noise. - * @return The value of curl noise, a normalized 2D vector. - */ - public Vector2 fractalCurlNoise(Vector2 p, int iterations) { - double v = fractalNoise(p, iterations); - double x = fractalNoise(p.add(CURL_DX, 0), iterations); - double y = fractalNoise(p.add(0, CURL_DX), iterations); - - return new Vector2(v - x, v - y).normalize(); - } - - /** - * Generates fractal curl 2D Clover Noise at a specific point. - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @param iterations - * The number of iterations for the fractal noise. - * @return The value of curl noise, a normalized 2D vector. - */ - public Vector2 fractalCurlNoise(double x, double y, int iterations) { - return fractalCurlNoise(new Vector2(x, y), iterations); - } - - /** - * Generates 2D Frost Noise at a specific point. See https://github.com/ValgoBoi/clover-noise/blob/master/variations/frost.md - * - * @param p - * The point to generate noise at. - * @return The value of noise, from 0 to 1. - */ - public double frostNoise(Vector2 p) { - Vector2 curl_1 = fractalCurlNoise(p, 3).mult(fractalNoise(p, 2) * 0.4 + 0.3); - Vector2 p_1 = p.add(curl_1); - Vector2 curl_2 = fractalCurlNoise(p_1, 4).mult(fractalNoise(p_1, 3) * 0.1 + 0.05); - Vector2 p_2 = p_1.add(curl_2); - - return fractalNoise(p_2, 5) - fractalNoise(p_1, 3) * 0.5 + fractalNoise(p, 2) * 0.3; - } - - /** - * Generates 2D Frost Noise at a specific point. See https://github.com/ValgoBoi/clover-noise/blob/master/variations/frost.md - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @return The value of noise, from 0 to 1. - */ - public double frostNoise(double x, double y) { - return frostNoise(new Vector2(x, y)); - } - - /** - * Generates 2D Marble Noise at a specific point. See https://github.com/ValgoBoi/clover-noise/blob/master/variations/marble.md - * - * @param p - * The point to generate noise at. - * @return The value of noise, from 0 to 1. - */ - public double marbleNoise(Vector2 p) { - Vector2 p_2 = p.mult(0.6); - double d1 = Math.max(1 - Math.abs(fractalNoise(p_2.add(100), 4) - fractalNoise(p_2.add(200), 3)) * 3, 0); - d1 = d1 * d1 * d1; - d1 *= fractalNoise(p_2.add(300), 2) * 0.3; - - Vector2 curl_1 = fractalCurlNoise(p.add(400), 3).mult(fractalNoise(p.add(500), 2) * 0.05); - - Vector2 p_3 = p.mult(1.2); - double d2 = Math.max(1 - Math.abs(fractalNoise(p_3.add(curl_1).add(600), 4) - fractalNoise(p_3.add(curl_1).add(700), 3)) * 2, 0); - d2 = d2 * d2 * d2; - d2 *= fractalNoise(p_3.add(800), 2) * 0.5; - - double v = 1 - fractalNoise(p.add(900), 5); - v = 1 - v * v * v; - - return Math.min(Math.max(v - d1 - d2, 0), 1); - } - - /** - * Generates 2D Marble Noise at a specific point. See https://github.com/ValgoBoi/clover-noise/blob/master/variations/marble.md - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @return The value of noise, from 0 to 1. - */ - public double marbleNoise(double x, double y) { - return marbleNoise(new Vector2(x, y)); - } - } - - public static class Noise3D { - private static final long HASH_A = 25214903917L; - private static final long HASH_C = 11L; - private static final long HASH_M = 0x1000000000000L; - private static final double POINT_SPREAD = 0.2; - private static final double CURL_DX = 0.0001; - private final long seed; - - public Noise3D(long seed) { - this.seed = seed; - } - - public Noise3D() { - this(System.currentTimeMillis()); - } - - private long doHash(long input, long seed) { - input += seed; - - if(input < 0) { - input += HASH_M; - } - - input *= HASH_A; - input += HASH_C; - input %= HASH_M; - - return input; - } - - private double hash(Vector3 position) { - long hash = doHash(seed, (long) Math.floor(position.getX())); - hash = doHash(hash, (long) Math.floor(position.getY())); - hash = doHash(hash, (long) Math.floor(position.getZ())); - hash = doHash(hash, hash * (long) Math.floor(position.getX() + position.getY() + position.getZ())); - if(hash < 0) { - hash += HASH_M; - } - - return (double) hash / HASH_M; - } - - private Vector3 offset(Vector3 position) { - double hash = hash(position); - double theta = hash * Math.PI * 2000; - double height = (((Math.floor(hash * 1000) + 0.5) / 100) % 1 - 0.5) * Math.PI / 2; - double layer = Math.floor(hash * 10 + 1) / 10; - Vector3 offset = new Vector3(Math.sin(theta) * Math.cos(height), Math.sin(height), Math.cos(theta) * Math.cos(height)).mult(layer).add(0.5); - return position.add(offset.mult(POINT_SPREAD * 2).add(0.5 - POINT_SPREAD)); - } - - private boolean boundary(Vector3 p, Vector3 c_00, Vector3 c_10, Vector3 c_20, Vector3 c_01, Vector3 c_11, Vector3 c_21, Vector3 c_02, Vector3 c_12, Vector3 c_22) { - Vector2 d_p_c11 = p.yx().sub(c_11.yx()); - Vector2 m_p_c11 = d_p_c11.mult(c_11.xy()); - - double side_nx = m_p_c11.sub(d_p_c11.mult(c_01.xy())).ymx(); - double side_px = m_p_c11.sub(d_p_c11.mult(c_21.xy())).ymx(); - - Vector3 a, b, c, d; - - if(side_nx < 0 && p.x < c_11.x || side_px > 0 && p.x >= c_11.x) { - double side_py = m_p_c11.sub(d_p_c11.mult(c_12.xy())).ymx(); - - if(side_py > 0.) { - a = c_01; - b = c_02; - c = c_12; - d = c_11; - } else { - a = c_11; - b = c_12; - c = c_22; - d = c_21; - } - } else { - double side_ny = m_p_c11.sub(d_p_c11.mult(c_10.xy())).ymx(); - - if(side_ny > 0.) { - a = c_10; - b = c_11; - c = c_21; - d = c_20; - } else { - a = c_00; - b = c_01; - c = c_11; - d = c_10; - } - } - - Vector3 f = a; - Vector3 g = c; - Vector3 h = d; - - Vector3 ac = a.sub(c); - Vector3 pa = p.sub(a); - - if(pa.x * ac.y - pa.y * ac.x > 0) { - h = b; - } - - Vector2 bc_v0 = g.xy().sub(f.xy()); - Vector2 bc_v1 = h.xy().sub(f.xy()); - Vector2 bc_v2 = p.xy().sub(f.xy()); - double den = 1 / (bc_v0.x * bc_v1.y - bc_v1.x * bc_v0.y); - double v = (bc_v2.x * bc_v1.y - bc_v1.x * bc_v2.y) * den; - double w = (bc_v0.x * bc_v2.y - bc_v2.x * bc_v0.y) * den; - double u = 1 - v - w; - - return p.z < u * f.z + v * g.z + w * h.z; - } - - /** - * Generates 3D Clover Noise at a specific point. - * - * @param p - * The point to generate noise at. - * @return The value of noise, from 0 to 1. - */ - public double noise(Vector3 p) { - Vector3 p_floor = p.floor(); - - Vector3 c_111 = offset(p_floor); - Vector3 c_100 = offset(p_floor.add(0, -1, -1)); - Vector3 c_010 = offset(p_floor.add(-1, 0, -1)); - Vector3 c_110 = offset(p_floor.add(0, 0, -1)); - Vector3 c_210 = offset(p_floor.add(1, 0, -1)); - Vector3 c_120 = offset(p_floor.add(0, 1, -1)); - Vector3 c_001 = offset(p_floor.add(-1, -1, 0)); - Vector3 c_101 = offset(p_floor.add(0, -1, 0)); - Vector3 c_201 = offset(p_floor.add(1, -1, 0)); - Vector3 c_011 = offset(p_floor.add(-1, 0, 0)); - Vector3 c_211 = offset(p_floor.add(1, 0, 0)); - Vector3 c_021 = offset(p_floor.add(-1, 1, 0)); - Vector3 c_121 = offset(p_floor.add(0, 1, 0)); - Vector3 c_221 = offset(p_floor.add(1, 1, 0)); - Vector3 c_102 = offset(p_floor.add(0, -1, 1)); - Vector3 c_012 = offset(p_floor.add(-1, 0, 1)); - Vector3 c_112 = offset(p_floor.add(0, 0, 1)); - Vector3 c_212 = offset(p_floor.add(1, 0, 1)); - Vector3 c_122 = offset(p_floor.add(0, 1, 1)); - - boolean x_bound = boundary(p.yzx(), c_100.yzx(), c_110.yzx(), c_120.yzx(), c_101.yzx(), c_111.yzx(), c_121.yzx(), c_102.yzx(), c_112.yzx(), c_122.yzx()); - boolean y_bound = boundary(p.xzy(), c_010.xzy(), c_110.xzy(), c_210.xzy(), c_011.xzy(), c_111.xzy(), c_211.xzy(), c_012.xzy(), c_112.xzy(), c_212.xzy()); - boolean z_bound = boundary(p, c_001, c_101, c_201, c_011, c_111, c_211, c_021, c_121, c_221); - - Vector3 a, b, c, d, e, f, g, h; - - if(x_bound) { - if(y_bound) { - if(z_bound) { - a = offset(p_floor.add(-1, -1, -1)); - b = c_001; - c = c_010; - d = c_011; - e = c_100; - f = c_101; - g = c_110; - h = c_111; - } else { - a = c_001; - b = offset(p_floor.add(-1, -1, 1)); - c = c_011; - d = c_012; - e = c_101; - f = c_102; - g = c_111; - h = c_112; - } - } else { - if(z_bound) { - a = c_010; - b = c_011; - c = offset(p_floor.add(-1, 1, -1)); - d = c_021; - e = c_110; - f = c_111; - g = c_120; - h = c_121; - } else { - a = c_011; - b = c_012; - c = c_021; - d = offset(p_floor.add(-1, 1, 1)); - e = c_111; - f = c_112; - g = c_121; - h = c_122; - } - } - } else { - if(y_bound) { - if(z_bound) { - a = c_100; - b = c_101; - c = c_110; - d = c_111; - e = offset(p_floor.add(1, -1, -1)); - f = c_201; - g = c_210; - h = c_211; - } else { - a = c_101; - b = c_102; - c = c_111; - d = c_112; - e = c_201; - f = offset(p_floor.add(1, -1, 1)); - g = c_211; - h = c_212; - } - } else { - if(z_bound) { - a = c_110; - b = c_111; - c = c_120; - d = c_121; - e = c_210; - f = c_211; - g = offset(p_floor.add(1, 1, -1)); - h = c_221; - } else { - a = c_111; - b = c_112; - c = c_121; - d = c_122; - e = c_211; - f = c_212; - g = c_221; - h = offset(p_floor.add(1, 1, 1)); - } - } - } - - Vector3 ah = a.sub(h); - Vector3 pa = p.sub(a); - - double plane_b = ah.cross(b.sub(h)).mult(pa).xpypz(); - double plane_c = ah.cross(c.sub(h)).mult(pa).xpypz(); - double plane_d = ah.cross(d.sub(h)).mult(pa).xpypz(); - double plane_e = ah.cross(e.sub(h)).mult(pa).xpypz(); - double plane_f = ah.cross(f.sub(h)).mult(pa).xpypz(); - double plane_g = ah.cross(g.sub(h)).mult(pa).xpypz(); - - Vector3 i, j, k, l; - - i = a; - j = h; - - if(plane_b > 0 && plane_d <= 0) { - k = b; - l = d; - } else if(plane_d > 0 && plane_c <= 0) { - k = d; - l = c; - } else if(plane_c > 0 && plane_g <= 0) { - k = c; - l = g; - } else if(plane_g > 0 && plane_e <= 0) { - k = g; - l = e; - } else if(plane_e > 0 && plane_f <= 0) { - k = e; - l = f; - } else { - k = f; - l = b; - } - - Vector3 bc_ap = p.sub(i); - Vector3 bc_bp = p.sub(j); - - Vector3 bc_ab = j.sub(i); - Vector3 bc_ac = k.sub(i); - Vector3 bc_ad = l.sub(i); - - Vector3 bc_bc = k.sub(j); - Vector3 bc_bd = l.sub(j); - - double bc_va6 = bc_bp.mult(bc_bd.cross(bc_bc)).xpypz(); - double bc_vb6 = bc_ap.mult(bc_ac.cross(bc_ad)).xpypz(); - double bc_vc6 = bc_ap.mult(bc_ad.cross(bc_ab)).xpypz(); - double bc_vd6 = bc_ap.mult(bc_ab.cross(bc_ac)).xpypz(); - double bc_v6 = 1 / bc_ab.mult(bc_ac.cross(bc_ad)).xpypz(); - - double v = bc_va6 * bc_v6; - double w = bc_vb6 * bc_v6; - double t = bc_vc6 * bc_v6; - double u = bc_vd6 * bc_v6; - - double fiu = u * u * u * (1 - v * w * t); - double fiv = v * v * v * (1 - u * w * t); - double fiw = w * w * w * (1 - v * u * t); - double fit = t * t * t * (1 - v * w * u); - double s = fiu + fiv + fiw + fit; - fiu /= s; - fiv /= s; - fiw /= s; - fit /= s; - - double iv = hash(i.floor()); - double jv = hash(j.floor()); - double kv = hash(k.floor()); - double lv = hash(l.floor()); - - return fiv * iv + fiw * jv + fit * kv + fiu * lv; - } - - /** - * Generates 3D Clover Noise at a specific point. - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @param z - * The z coordinate of the point. - * @return The value of noise, from 0 to 1. - */ - public double noise(double x, double y, double z) { - return noise(new Vector3(x, y, z)); - } - - /** - * Generates fractal 3D Clover Noise at a specific point. - * - * @param p - * The point to generate noise at. - * @param iterations - * The number of iterations for the fractal noise. - * @return The value of noise, from 0 to 1. - */ - public double fractalNoise(Vector3 p, int iterations) { - double total = 0; - double weight = 1; - double div = 0; - - for(int i = 0; i < iterations; i++) { - total += noise(p.mult(1 / weight)) * weight; - div += weight; - - weight *= 0.4; - } - - return total / div; - } - - /** - * Generates fractal 3D Clover Noise at a specific point. - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @param z - * The z coordinate of the point. - * @param iterations - * The number of iterations for the fractal noise. - * @return The value of noise, from 0 to 1. - */ - public double fractalNoise(double x, double y, double z, int iterations) { - return fractalNoise(new Vector3(x, y, z), iterations); - } - - /** - * Generates curl 3D Clover Noise at a specific point. - * - * @param p - * The point to generate noise at. - * @return The value of curl noise, a normalized 3D vector. - */ - public Vector3 curlNoise(Vector3 p) { - double v = noise(p); - double x = noise(p.add(CURL_DX, 0, 0)); - double y = noise(p.add(0, CURL_DX, 0)); - double z = noise(p.add(0, 0, CURL_DX)); - - return new Vector3(v - x, v - y, v - z).normalize(); - } - - /** - * Generates curl 3D Clover Noise at a specific point. - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @param z - * The z coordinate of the point. - * @return The value of curl noise, a normalized 3D vector. - */ - public Vector3 curlNoise(double x, double y, double z) { - return curlNoise(new Vector3(x, y, z)); - } - - /** - * Generates fractal curl 3D Clover Noise at a specific point. - * - * @param p - * The point to generate noise at. - * @param iterations - * The number of iterations for the fractal noise. - * @return The value of curl noise, a normalized 3D vector. - */ - public Vector3 fractalCurlNoise(Vector3 p, int iterations) { - double v = fractalNoise(p, iterations); - double x = fractalNoise(p.add(CURL_DX, 0, 0), iterations); - double y = fractalNoise(p.add(0, CURL_DX, 0), iterations); - double z = fractalNoise(p.add(0, 0, CURL_DX), iterations); - - return new Vector3(v - x, v - y, v - z).normalize(); - } - - /** - * Generates fractal curl 3D Clover Noise at a specific point. - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @param z - * The z coordinate of the point. - * @param iterations - * The number of iterations for the fractal noise. - * @return The value of curl noise, a normalized 3D vector. - */ - public Vector3 fractalCurlNoise(double x, double y, double z, int iterations) { - return fractalCurlNoise(new Vector3(x, y, z), iterations); - } - - /** - * Generates 3D Frost Noise at a specific point. See https://github.com/ValgoBoi/clover-noise/blob/master/variations/frost.md - * - * @param p - * The point to generate noise at. - * @return The value of noise, from 0 to 1. - */ - public double frostNoise(Vector3 p) { - Vector3 curl_1 = fractalCurlNoise(p, 3).mult(fractalNoise(p, 2) * 0.4 + 0.3); - Vector3 p_1 = p.add(curl_1); - Vector3 curl_2 = fractalCurlNoise(p_1, 4).mult(fractalNoise(p_1, 3) * 0.1 + 0.05); - Vector3 p_2 = p_1.add(curl_2); - - return fractalNoise(p_2, 5) - fractalNoise(p_1, 3) * 0.5 + fractalNoise(p, 2) * 0.3; - } - - /** - * Generates 3D Frost Noise at a specific point. See https://github.com/ValgoBoi/clover-noise/blob/master/variations/frost.md - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @param z - * The z coordinate of the point. - * @return The value of noise, from 0 to 1. - */ - public double frostNoise(double x, double y, double z) { - return frostNoise(new Vector3(x, y, z)); - } - - /** - * Generates 3D Marble Noise at a specific point. See https://github.com/ValgoBoi/clover-noise/blob/master/variations/marble.md - * - * @param p - * The point to generate noise at. - * @return The value of noise, from 0 to 1. - */ - public double marbleNoise(Vector3 p) { - Vector3 p_2 = p.mult(0.6); - double d1 = Math.max(1 - Math.abs(fractalNoise(p_2.add(100), 4) - fractalNoise(p_2.add(200), 3)) * 3, 0); - d1 = d1 * d1 * d1; - d1 *= fractalNoise(p_2.add(300), 2) * 0.3; - - Vector3 curl_1 = fractalCurlNoise(p.add(400), 3).mult(fractalNoise(p.add(500), 2) * 0.05); - - Vector3 p_3 = p.mult(1.2); - double d2 = Math.max(1 - Math.abs(fractalNoise(p_3.add(curl_1).add(600), 4) - fractalNoise(p_3.add(curl_1).add(700), 3)) * 2, 0); - d2 = d2 * d2 * d2; - d2 *= fractalNoise(p_3.add(800), 2) * 0.5; - - double v = 1 - fractalNoise(p.add(900), 5); - v = 1 - v * v * v; - - return Math.min(Math.max(v - d1 - d2, 0), 1); - } - - /** - * Generates 3D Marble Noise at a specific point. See https://github.com/ValgoBoi/clover-noise/blob/master/variations/marble.md - * - * @param x - * The x coordinate of the point. - * @param y - * The y coordinate of the point. - * @param z - * The z coordinate of the point. - * @return The value of noise, from 0 to 1. - */ - public double marbleNoise(double x, double y, double z) { - return marbleNoise(new Vector3(x, y, z)); - } - } - - /** - * A 2-dimensional Vector, with methods relevant to the Clover Noise algorithm. - */ - public static class Vector2 { - private double x, y; - - public Vector2(double x, double y) { - this.x = x; - this.y = y; - } - - public Vector2() { - this(0, 0); - } - - public double getX() { - return x; - } - - public void setX(double x) { - this.x = x; - } - - public double getY() { - return y; - } - - public void setY(double y) { - this.y = y; - } - - public double ymx() { - return y - x; - } - - public Vector2 yx() { - return new Vector2(y, x); - } - - public Vector2 negate() { - return new Vector2(-x, -y); - } - - public Vector2 floor() { - return new Vector2(Math.floor(x), Math.floor(y)); - } - - public Vector2 normalize() { - double len2 = x * x + y * y; - double len = Math.sqrt(len2); - - return new Vector2(x / len, y / len); - } - - public Vector2 add(Vector2 a) { - return new Vector2(x + a.x, y + a.y); - } - - public Vector2 add(double xa, double ya) { - return add(new Vector2(xa, ya)); - } - - public Vector2 add(double a) { - return add(a, a); - } - - public Vector2 sub(Vector2 s) { - return add(s.negate()); - } - - public Vector2 sub(double xs, double ys) { - return sub(new Vector2(xs, ys)); - } - - public Vector2 sub(double s) { - return sub(s, s); - } - - public Vector2 mult(Vector2 m) { - return new Vector2(x * m.x, y * m.y); - } - - public Vector2 mult(double xm, double ym) { - return mult(new Vector2(xm, ym)); - } - - public Vector2 mult(double m) { - return mult(m, m); - } - } - - /** - * A 3-dimensional Vector, with methods relevant to the Clover Noise algorithm. - */ - public static class Vector3 { - double x, y, z; - - public Vector3(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - public Vector3() { - this(0, 0, 0); - } - - public double getX() { - return x; - } - - public void setX(double x) { - this.x = x; - } - - public double getY() { - return y; - } - - public void setY(double y) { - this.y = y; - } - - public double getZ() { - return z; - } - - public void setZ(double z) { - this.z = z; - } - - public Vector2 xy() { - return new Vector2(x, y); - } - - public Vector2 yx() { - return new Vector2(y, x); - } - - public Vector3 yzx() { - return new Vector3(y, z, x); - } - - public Vector3 xzy() { - return new Vector3(x, z, y); - } - - public double xpypz() { - return x + y + z; - } - - public Vector3 negate() { - return new Vector3(-x, -y, -z); - } - - public Vector3 floor() { - return new Vector3(Math.floor(x), Math.floor(y), Math.floor(z)); - } - - public Vector3 normalize() { - double len2 = x * x + y * y + z * z; - double len = Math.sqrt(len2); - - return new Vector3(x / len, y / len, z / len); - } - - public Vector3 add(Vector3 a) { - return new Vector3(x + a.x, y + a.y, z + a.z); - } - - public Vector3 add(double xa, double ya, double za) { - return add(new Vector3(xa, ya, za)); - } - - public Vector3 add(double a) { - return add(a, a, a); - } - - public Vector3 sub(Vector3 s) { - return add(s.negate()); - } - - public Vector3 sub(double xs, double ys, double zs) { - return sub(new Vector3(xs, ys, zs)); - } - - public Vector3 sub(double s) { - return sub(s, s, s); - } - - public Vector3 mult(Vector3 m) { - return new Vector3(x * m.x, y * m.y, z * m.z); - } - - public Vector3 mult(double mx, double my, double mz) { - return mult(new Vector3(mx, my, mz)); - } - - public Vector3 mult(double m) { - return mult(m, m, m); - } - - public Vector3 cross(Vector3 c) { - return new Vector3(y * c.z - z * c.y, z * c.x - x * c.z, x * c.y - y * c.x); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/noise/CubicNoise.java b/src/main/java/com/volmit/iris/util/noise/CubicNoise.java deleted file mode 100644 index 485ea08b8..000000000 --- a/src/main/java/com/volmit/iris/util/noise/CubicNoise.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; - -public class CubicNoise implements NoiseGenerator { - private final FastNoiseDouble n; - - public CubicNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - } - - private double f(double n) { - return (n / 2D) + 0.5D; - } - - @Override - public double noise(double x) { - return f(n.GetCubic(x, 0)); - } - - @Override - public double noise(double x, double z) { - return f(n.GetCubic(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return f(n.GetCubic(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/ExpressionNoise.java b/src/main/java/com/volmit/iris/util/noise/ExpressionNoise.java deleted file mode 100644 index 7052d9dd2..000000000 --- a/src/main/java/com/volmit/iris/util/noise/ExpressionNoise.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.engine.object.IrisExpression; -import com.volmit.iris.util.math.RNG; - -public class ExpressionNoise implements NoiseGenerator { - private final RNG rng; - private final IrisExpression expression; - - public ExpressionNoise(RNG rng, IrisExpression expression) { - this.rng = rng; - this.expression = expression; - } - - @Override - public double noise(double x) { - return expression.evaluate(rng, x, -1); - } - - @Override - public double noise(double x, double z) { - return expression.evaluate(rng, x, z); - } - - @Override - public double noise(double x, double y, double z) { - return expression.evaluate(rng, x, y, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/FastNoise.java b/src/main/java/com/volmit/iris/util/noise/FastNoise.java deleted file mode 100644 index 358085faf..000000000 --- a/src/main/java/com/volmit/iris/util/noise/FastNoise.java +++ /dev/null @@ -1,2198 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.Vector2f; -import com.volmit.iris.util.math.Vector3f; -import com.volmit.iris.util.stream.ProceduralStream; - -public class FastNoise { - private static final Float2[] GRAD_2D = {new Float2(-1, -1), new Float2(1, -1), new Float2(-1, 1), new Float2(1, 1), new Float2(0, -1), new Float2(-1, 0), new Float2(0, 1), new Float2(1, 0), - }; - private static final Float3[] GRAD_3D = {new Float3(1, 1, 0), new Float3(-1, 1, 0), new Float3(1, -1, 0), new Float3(-1, -1, 0), new Float3(1, 0, 1), new Float3(-1, 0, 1), new Float3(1, 0, -1), new Float3(-1, 0, -1), new Float3(0, 1, 1), new Float3(0, -1, 1), new Float3(0, 1, -1), new Float3(0, -1, -1), new Float3(1, 1, 0), new Float3(0, -1, 1), new Float3(-1, 1, 0), new Float3(0, -1, -1), - }; - private static final Float2[] CELL_2D = {new Float2(-0.4313539279f, 0.1281943404f), new Float2(-0.1733316799f, 0.415278375f), new Float2(-0.2821957395f, -0.3505218461f), new Float2(-0.2806473808f, 0.3517627718f), new Float2(0.3125508975f, -0.3237467165f), new Float2(0.3383018443f, -0.2967353402f), new Float2(-0.4393982022f, -0.09710417025f), new Float2(-0.4460443703f, -0.05953502905f), new Float2(-0.302223039f, 0.3334085102f), new Float2(-0.212681052f, -0.3965687458f), new Float2(-0.2991156529f, 0.3361990872f), new Float2(0.2293323691f, 0.3871778202f), new Float2(0.4475439151f, -0.04695150755f), new Float2(0.1777518f, 0.41340573f), new Float2(0.1688522499f, -0.4171197882f), new Float2(-0.0976597166f, 0.4392750616f), new Float2(0.08450188373f, 0.4419948321f), new Float2(-0.4098760448f, -0.1857461384f), new Float2(0.3476585782f, -0.2857157906f), new Float2(-0.3350670039f, -0.30038326f), new Float2(0.2298190031f, -0.3868891648f), new Float2(-0.01069924099f, 0.449872789f), new Float2(-0.4460141246f, -0.05976119672f), new Float2(0.3650293864f, 0.2631606867f), new Float2(-0.349479423f, 0.2834856838f), new Float2(-0.4122720642f, 0.1803655873f), new Float2(-0.267327811f, 0.3619887311f), new Float2(0.322124041f, -0.3142230135f), new Float2(0.2880445931f, -0.3457315612f), new Float2(0.3892170926f, -0.2258540565f), new Float2(0.4492085018f, -0.02667811596f), new Float2(-0.4497724772f, 0.01430799601f), new Float2(0.1278175387f, -0.4314657307f), new Float2(-0.03572100503f, 0.4485799926f), new Float2(-0.4297407068f, -0.1335025276f), new Float2(-0.3217817723f, 0.3145735065f), new Float2(-0.3057158873f, 0.3302087162f), new Float2(-0.414503978f, 0.1751754899f), new Float2(-0.3738139881f, 0.2505256519f), new Float2(0.2236891408f, -0.3904653228f), new Float2(0.002967775577f, -0.4499902136f), new Float2(0.1747128327f, -0.4146991995f), new Float2(-0.4423772489f, -0.08247647938f), new Float2(-0.2763960987f, -0.355112935f), new Float2(-0.4019385906f, -0.2023496216f), new Float2(0.3871414161f, -0.2293938184f), new Float2(-0.430008727f, 0.1326367019f), new Float2(-0.03037574274f, -0.4489736231f), new Float2(-0.3486181573f, 0.2845441624f), new Float2(0.04553517144f, -0.4476902368f), new Float2(-0.0375802926f, 0.4484280562f), new Float2(0.3266408905f, 0.3095250049f), new Float2(0.06540017593f, -0.4452222108f), new Float2(0.03409025829f, 0.448706869f), new Float2(-0.4449193635f, 0.06742966669f), new Float2(-0.4255936157f, -0.1461850686f), new Float2(0.449917292f, 0.008627302568f), new Float2(0.05242606404f, 0.4469356864f), new Float2(-0.4495305179f, -0.02055026661f), new Float2(-0.1204775703f, 0.4335725488f), new Float2(-0.341986385f, -0.2924813028f), new Float2(0.3865320182f, 0.2304191809f), new Float2(0.04506097811f, -0.447738214f), new Float2(-0.06283465979f, 0.4455915232f), new Float2(0.3932600341f, -0.2187385324f), new Float2(0.4472261803f, -0.04988730975f), new Float2(0.3753571011f, -0.2482076684f), new Float2(-0.273662295f, 0.357223947f), new Float2(0.1700461538f, 0.4166344988f), new Float2(0.4102692229f, 0.1848760794f), new Float2(0.323227187f, -0.3130881435f), new Float2(-0.2882310238f, -0.3455761521f), new Float2(0.2050972664f, 0.4005435199f), new Float2(0.4414085979f, -0.08751256895f), new Float2(-0.1684700334f, 0.4172743077f), new Float2(-0.003978032396f, 0.4499824166f), new Float2(-0.2055133639f, 0.4003301853f), new Float2(-0.006095674897f, -0.4499587123f), new Float2(-0.1196228124f, -0.4338091548f), new Float2(0.3901528491f, -0.2242337048f), new Float2(0.01723531752f, 0.4496698165f), new Float2(-0.3015070339f, 0.3340561458f), new Float2(-0.01514262423f, -0.4497451511f), new Float2(-0.4142574071f, -0.1757577897f), new Float2(-0.1916377265f, -0.4071547394f), new Float2(0.3749248747f, 0.2488600778f), new Float2(-0.2237774255f, 0.3904147331f), new Float2(-0.4166343106f, -0.1700466149f), new Float2(0.3619171625f, 0.267424695f), new Float2(0.1891126846f, -0.4083336779f), new Float2(-0.3127425077f, 0.323561623f), new Float2(-0.3281807787f, 0.307891826f), new Float2(-0.2294806661f, 0.3870899429f), new Float2(-0.3445266136f, 0.2894847362f), new Float2(-0.4167095422f, -0.1698621719f), new Float2(-0.257890321f, -0.3687717212f), new Float2(-0.3612037825f, 0.2683874578f), new Float2(0.2267996491f, 0.3886668486f), new Float2(0.207157062f, 0.3994821043f), new Float2(0.08355176718f, -0.4421754202f), new Float2(-0.4312233307f, 0.1286329626f), new Float2(0.3257055497f, 0.3105090899f), new Float2(0.177701095f, -0.4134275279f), new Float2(-0.445182522f, 0.06566979625f), new Float2(0.3955143435f, 0.2146355146f), new Float2(-0.4264613988f, 0.1436338239f), new Float2(-0.3793799665f, -0.2420141339f), new Float2(0.04617599081f, -0.4476245948f), new Float2(-0.371405428f, -0.2540826796f), new Float2(0.2563570295f, -0.3698392535f), new Float2(0.03476646309f, 0.4486549822f), new Float2(-0.3065454405f, 0.3294387544f), new Float2(-0.2256979823f, 0.3893076172f), new Float2(0.4116448463f, -0.1817925206f), new Float2(-0.2907745828f, -0.3434387019f), new Float2(0.2842278468f, -0.348876097f), new Float2(0.3114589359f, -0.3247973695f), new Float2(0.4464155859f, -0.0566844308f), new Float2(-0.3037334033f, -0.3320331606f), new Float2(0.4079607166f, 0.1899159123f), new Float2(-0.3486948919f, -0.2844501228f), new Float2(0.3264821436f, 0.3096924441f), new Float2(0.3211142406f, 0.3152548881f), new Float2(0.01183382662f, 0.4498443737f), new Float2(0.4333844092f, 0.1211526057f), new Float2(0.3118668416f, 0.324405723f), new Float2(-0.272753471f, 0.3579183483f), new Float2(-0.422228622f, -0.1556373694f), new Float2(-0.1009700099f, -0.4385260051f), new Float2(-0.2741171231f, -0.3568750521f), new Float2(-0.1465125133f, 0.4254810025f), new Float2(0.2302279044f, -0.3866459777f), new Float2(-0.3699435608f, 0.2562064828f), new Float2(0.105700352f, -0.4374099171f), new Float2(-0.2646713633f, 0.3639355292f), new Float2(0.3521828122f, 0.2801200935f), new Float2(-0.1864187807f, -0.4095705534f), new Float2(0.1994492955f, -0.4033856449f), new Float2(0.3937065066f, 0.2179339044f), new Float2(-0.3226158377f, 0.3137180602f), new Float2(0.3796235338f, 0.2416318948f), new Float2(0.1482921929f, 0.4248640083f), new Float2(-0.407400394f, 0.1911149365f), new Float2(0.4212853031f, 0.1581729856f), new Float2(-0.2621297173f, 0.3657704353f), new Float2(-0.2536986953f, -0.3716678248f), new Float2(-0.2100236383f, 0.3979825013f), new Float2(0.3624152444f, 0.2667493029f), new Float2(-0.3645038479f, -0.2638881295f), new Float2(0.2318486784f, 0.3856762766f), new Float2(-0.3260457004f, 0.3101519002f), new Float2(-0.2130045332f, -0.3963950918f), new Float2(0.3814998766f, -0.2386584257f), new Float2(-0.342977305f, 0.2913186713f), new Float2(-0.4355865605f, 0.1129794154f), new Float2(-0.2104679605f, 0.3977477059f), new Float2(0.3348364681f, -0.3006402163f), new Float2(0.3430468811f, 0.2912367377f), new Float2(-0.2291836801f, -0.3872658529f), new Float2(0.2547707298f, -0.3709337882f), new Float2(0.4236174945f, -0.151816397f), new Float2(-0.15387742f, 0.4228731957f), new Float2(-0.4407449312f, 0.09079595574f), new Float2(-0.06805276192f, -0.444824484f), new Float2(0.4453517192f, -0.06451237284f), new Float2(0.2562464609f, -0.3699158705f), new Float2(0.3278198355f, -0.3082761026f), new Float2(-0.4122774207f, -0.1803533432f), new Float2(0.3354090914f, -0.3000012356f), new Float2(0.446632869f, -0.05494615882f), new Float2(-0.1608953296f, 0.4202531296f), new Float2(-0.09463954939f, 0.4399356268f), new Float2(-0.02637688324f, -0.4492262904f), new Float2(0.447102804f, -0.05098119915f), new Float2(-0.4365670908f, 0.1091291678f), new Float2(-0.3959858651f, 0.2137643437f), new Float2(-0.4240048207f, -0.1507312575f), new Float2(-0.3882794568f, 0.2274622243f), new Float2(-0.4283652566f, -0.1378521198f), new Float2(0.3303888091f, 0.305521251f), new Float2(0.3321434919f, -0.3036127481f), new Float2(-0.413021046f, -0.1786438231f), new Float2(0.08403060337f, -0.4420846725f), new Float2(-0.3822882919f, 0.2373934748f), new Float2(-0.3712395594f, -0.2543249683f), new Float2(0.4472363971f, -0.04979563372f), new Float2(-0.4466591209f, 0.05473234629f), new Float2(0.0486272539f, -0.4473649407f), new Float2(-0.4203101295f, -0.1607463688f), new Float2(0.2205360833f, 0.39225481f), new Float2(-0.3624900666f, 0.2666476169f), new Float2(-0.4036086833f, -0.1989975647f), new Float2(0.2152727807f, 0.3951678503f), new Float2(-0.4359392962f, -0.1116106179f), new Float2(0.4178354266f, 0.1670735057f), new Float2(0.2007630161f, 0.4027334247f), new Float2(-0.07278067175f, -0.4440754146f), new Float2(0.3644748615f, -0.2639281632f), new Float2(-0.4317451775f, 0.126870413f), new Float2(-0.297436456f, 0.3376855855f), new Float2(-0.2998672222f, 0.3355289094f), new Float2(-0.2673674124f, 0.3619594822f), new Float2(0.2808423357f, 0.3516071423f), new Float2(0.3498946567f, 0.2829730186f), new Float2(-0.2229685561f, 0.390877248f), new Float2(0.3305823267f, 0.3053118493f), new Float2(-0.2436681211f, -0.3783197679f), new Float2(-0.03402776529f, 0.4487116125f), new Float2(-0.319358823f, 0.3170330301f), new Float2(0.4454633477f, -0.06373700535f), new Float2(0.4483504221f, 0.03849544189f), new Float2(-0.4427358436f, -0.08052932871f), new Float2(0.05452298565f, 0.4466847255f), new Float2(-0.2812560807f, 0.3512762688f), new Float2(0.1266696921f, 0.4318041097f), new Float2(-0.3735981243f, 0.2508474468f), new Float2(0.2959708351f, -0.3389708908f), new Float2(-0.3714377181f, 0.254035473f), new Float2(-0.404467102f, -0.1972469604f), new Float2(0.1636165687f, -0.419201167f), new Float2(0.3289185495f, -0.3071035458f), new Float2(-0.2494824991f, -0.3745109914f), new Float2(0.03283133272f, 0.4488007393f), new Float2(-0.166306057f, -0.4181414777f), new Float2(-0.106833179f, 0.4371346153f), new Float2(0.06440260376f, -0.4453676062f), new Float2(-0.4483230967f, 0.03881238203f), new Float2(-0.421377757f, -0.1579265206f), new Float2(0.05097920662f, -0.4471030312f), new Float2(0.2050584153f, -0.4005634111f), new Float2(0.4178098529f, -0.167137449f), new Float2(-0.3565189504f, -0.2745801121f), new Float2(0.4478398129f, 0.04403977727f), new Float2(-0.3399999602f, -0.2947881053f), new Float2(0.3767121994f, 0.2461461331f), new Float2(-0.3138934434f, 0.3224451987f), new Float2(-0.1462001792f, -0.4255884251f), new Float2(0.3970290489f, -0.2118205239f), new Float2(0.4459149305f, -0.06049689889f), new Float2(-0.4104889426f, -0.1843877112f), new Float2(0.1475103971f, -0.4251360756f), new Float2(0.09258030352f, 0.4403735771f), new Float2(-0.1589664637f, -0.4209865359f), new Float2(0.2482445008f, 0.3753327428f), new Float2(0.4383624232f, -0.1016778537f), new Float2(0.06242802956f, 0.4456486745f), new Float2(0.2846591015f, -0.3485243118f), new Float2(-0.344202744f, -0.2898697484f), new Float2(0.1198188883f, -0.4337550392f), new Float2(-0.243590703f, 0.3783696201f), new Float2(0.2958191174f, -0.3391033025f), new Float2(-0.1164007991f, 0.4346847754f), new Float2(0.1274037151f, -0.4315881062f), new Float2(0.368047306f, 0.2589231171f), new Float2(0.2451436949f, 0.3773652989f), new Float2(-0.4314509715f, 0.12786735f), - }; - private static final Float3[] CELL_3D = {new Float3(0.1453787434f, -0.4149781685f, -0.0956981749f), new Float3(-0.01242829687f, -0.1457918398f, -0.4255470325f), new Float3(0.2877979582f, -0.02606483451f, -0.3449535616f), new Float3(-0.07732986802f, 0.2377094325f, 0.3741848704f), new Float3(0.1107205875f, -0.3552302079f, -0.2530858567f), new Float3(0.2755209141f, 0.2640521179f, -0.238463215f), new Float3(0.294168941f, 0.1526064594f, 0.3044271714f), new Float3(0.4000921098f, -0.2034056362f, 0.03244149937f), new Float3(-0.1697304074f, 0.3970864695f, -0.1265461359f), new Float3(-0.1483224484f, -0.3859694688f, 0.1775613147f), new Float3(0.2623596946f, -0.2354852944f, 0.2796677792f), new Float3(-0.2709003183f, 0.3505271138f, -0.07901746678f), new Float3(-0.03516550699f, 0.3885234328f, 0.2243054374f), new Float3(-0.1267712655f, 0.1920044036f, 0.3867342179f), new Float3(0.02952021915f, 0.4409685861f, 0.08470692262f), new Float3(-0.2806854217f, -0.266996757f, 0.2289725438f), new Float3(-0.171159547f, 0.2141185563f, 0.3568720405f), new Float3(0.2113227183f, 0.3902405947f, -0.07453178509f), new Float3(-0.1024352839f, 0.2128044156f, -0.3830421561f), new Float3(-0.3304249877f, -0.1566986703f, 0.2622305365f), new Float3(0.2091111325f, 0.3133278055f, -0.2461670583f), new Float3(0.344678154f, -0.1944240454f, -0.2142341261f), new Float3(0.1984478035f, -0.3214342325f, -0.2445373252f), new Float3(-0.2929008603f, 0.2262915116f, 0.2559320961f), new Float3(-0.1617332831f, 0.006314769776f, -0.4198838754f), new Float3(-0.3582060271f, -0.148303178f, -0.2284613961f), new Float3(-0.1852067326f, -0.3454119342f, -0.2211087107f), new Float3(0.3046301062f, 0.1026310383f, 0.314908508f), new Float3(-0.03816768434f, -0.2551766358f, -0.3686842991f), new Float3(-0.4084952196f, 0.1805950793f, 0.05492788837f), new Float3(-0.02687443361f, -0.2749741471f, 0.3551999201f), new Float3(-0.03801098351f, 0.3277859044f, 0.3059600725f), new Float3(0.2371120802f, 0.2900386767f, -0.2493099024f), new Float3(0.4447660503f, 0.03946930643f, 0.05590469027f), new Float3(0.01985147278f, -0.01503183293f, -0.4493105419f), new Float3(0.4274339143f, 0.03345994256f, -0.1366772882f), new Float3(-0.2072988631f, 0.2871414597f, -0.2776273824f), new Float3(-0.3791240978f, 0.1281177671f, 0.2057929936f), new Float3(-0.2098721267f, -0.1007087278f, -0.3851122467f), new Float3(0.01582798878f, 0.4263894424f, 0.1429738373f), new Float3(-0.1888129464f, -0.3160996813f, -0.2587096108f), new Float3(0.1612988974f, -0.1974805082f, -0.3707885038f), new Float3(-0.08974491322f, 0.229148752f, -0.3767448739f), new Float3(0.07041229526f, 0.4150230285f, -0.1590534329f), new Float3(-0.1082925611f, -0.1586061639f, 0.4069604477f), new Float3(0.2474100658f, -0.3309414609f, 0.1782302128f), new Float3(-0.1068836661f, -0.2701644537f, -0.3436379634f), new Float3(0.2396452163f, 0.06803600538f, -0.3747549496f), new Float3(-0.3063886072f, 0.2597428179f, 0.2028785103f), new Float3(0.1593342891f, -0.3114350249f, -0.2830561951f), new Float3(0.2709690528f, 0.1412648683f, -0.3303331794f), new Float3(-0.1519780427f, 0.3623355133f, 0.2193527988f), new Float3(0.1699773681f, 0.3456012883f, 0.2327390037f), new Float3(-0.1986155616f, 0.3836276443f, -0.1260225743f), new Float3(-0.1887482106f, -0.2050154888f, -0.353330953f), new Float3(0.2659103394f, 0.3015631259f, -0.2021172246f), new Float3(-0.08838976154f, -0.4288819642f, -0.1036702021f), new Float3(-0.04201869311f, 0.3099592485f, 0.3235115047f), new Float3(-0.3230334656f, 0.201549922f, -0.2398478873f), new Float3(0.2612720941f, 0.2759854499f, -0.2409749453f), new Float3(0.385713046f, 0.2193460345f, 0.07491837764f), new Float3(0.07654967953f, 0.3721732183f, 0.241095919f), new Float3(0.4317038818f, -0.02577753072f, 0.1243675091f), new Float3(-0.2890436293f, -0.3418179959f, -0.04598084447f), new Float3(-0.2201947582f, 0.383023377f, -0.08548310451f), new Float3(0.4161322773f, -0.1669634289f, -0.03817251927f), new Float3(0.2204718095f, 0.02654238946f, -0.391391981f), new Float3(-0.1040307469f, 0.3890079625f, -0.2008741118f), new Float3(-0.1432122615f, 0.371614387f, -0.2095065525f), new Float3(0.3978380468f, -0.06206669342f, 0.2009293758f), new Float3(-0.2599274663f, 0.2616724959f, -0.2578084893f), new Float3(0.4032618332f, -0.1124593585f, 0.1650235939f), new Float3(-0.08953470255f, -0.3048244735f, 0.3186935478f), new Float3(0.118937202f, -0.2875221847f, 0.325092195f), new Float3(0.02167047076f, -0.03284630549f, -0.4482761547f), new Float3(-0.3411343612f, 0.2500031105f, 0.1537068389f), new Float3(0.3162964612f, 0.3082064153f, -0.08640228117f), new Float3(0.2355138889f, -0.3439334267f, -0.1695376245f), new Float3(-0.02874541518f, -0.3955933019f, 0.2125550295f), new Float3(-0.2461455173f, 0.02020282325f, -0.3761704803f), new Float3(0.04208029445f, -0.4470439576f, 0.02968078139f), new Float3(0.2727458746f, 0.2288471896f, -0.2752065618f), new Float3(-0.1347522818f, -0.02720848277f, -0.4284874806f), new Float3(0.3829624424f, 0.1231931484f, -0.2016512234f), new Float3(-0.3547613644f, 0.1271702173f, 0.2459107769f), new Float3(0.2305790207f, 0.3063895591f, 0.2354968222f), new Float3(-0.08323845599f, -0.1922245118f, 0.3982726409f), new Float3(0.2993663085f, -0.2619918095f, -0.2103333191f), new Float3(-0.2154865723f, 0.2706747713f, 0.287751117f), new Float3(0.01683355354f, -0.2680655787f, -0.3610505186f), new Float3(0.05240429123f, 0.4335128183f, -0.1087217856f), new Float3(0.00940104872f, -0.4472890582f, 0.04841609928f), new Float3(0.3465688735f, 0.01141914583f, -0.2868093776f), new Float3(-0.3706867948f, -0.2551104378f, 0.003156692623f), new Float3(0.2741169781f, 0.2139972417f, -0.2855959784f), new Float3(0.06413433865f, 0.1708718512f, 0.4113266307f), new Float3(-0.388187972f, -0.03973280434f, -0.2241236325f), new Float3(0.06419469312f, -0.2803682491f, 0.3460819069f), new Float3(-0.1986120739f, -0.3391173584f, 0.2192091725f), new Float3(-0.203203009f, -0.3871641506f, 0.1063600375f), new Float3(-0.1389736354f, -0.2775901578f, -0.3257760473f), new Float3(-0.06555641638f, 0.342253257f, -0.2847192729f), new Float3(-0.2529246486f, -0.2904227915f, 0.2327739768f), new Float3(0.1444476522f, 0.1069184044f, 0.4125570634f), new Float3(-0.3643780054f, -0.2447099973f, -0.09922543227f), new Float3(0.4286142488f, -0.1358496089f, -0.01829506817f), new Float3(0.165872923f, -0.3136808464f, -0.2767498872f), new Float3(0.2219610524f, -0.3658139958f, 0.1393320198f), new Float3(0.04322940318f, -0.3832730794f, 0.2318037215f), new Float3(-0.08481269795f, -0.4404869674f, -0.03574965489f), new Float3(0.1822082075f, -0.3953259299f, 0.1140946023f), new Float3(-0.3269323334f, 0.3036542563f, 0.05838957105f), new Float3(-0.4080485344f, 0.04227858267f, -0.184956522f), new Float3(0.2676025294f, -0.01299671652f, 0.36155217f), new Float3(0.3024892441f, -0.1009990293f, -0.3174892964f), new Float3(0.1448494052f, 0.425921681f, -0.0104580805f), new Float3(0.4198402157f, 0.08062320474f, 0.1404780841f), new Float3(-0.3008872161f, -0.333040905f, -0.03241355801f), new Float3(0.3639310428f, -0.1291284382f, -0.2310412139f), new Float3(0.3295806598f, 0.0184175994f, -0.3058388149f), new Float3(0.2776259487f, -0.2974929052f, -0.1921504723f), new Float3(0.4149000507f, -0.144793182f, -0.09691688386f), new Float3(0.145016715f, -0.0398992945f, 0.4241205002f), new Float3(0.09299023471f, -0.299732164f, -0.3225111565f), new Float3(0.1028907093f, -0.361266869f, 0.247789732f), new Float3(0.2683057049f, -0.07076041213f, -0.3542668666f), new Float3(-0.4227307273f, -0.07933161816f, -0.1323073187f), new Float3(-0.1781224702f, 0.1806857196f, -0.3716517945f), new Float3(0.4390788626f, -0.02841848598f, -0.09435116353f), new Float3(0.2972583585f, 0.2382799621f, -0.2394997452f), new Float3(-0.1707002821f, 0.2215845691f, 0.3525077196f), new Float3(0.3806686614f, 0.1471852559f, -0.1895464869f), new Float3(-0.1751445661f, -0.274887877f, 0.3102596268f), new Float3(-0.2227237566f, -0.2316778837f, 0.3149912482f), new Float3(0.1369633021f, 0.1341343041f, -0.4071228836f), new Float3(-0.3529503428f, -0.2472893463f, -0.129514612f), new Float3(-0.2590744185f, -0.2985577559f, -0.2150435121f), new Float3(-0.3784019401f, 0.2199816631f, -0.1044989934f), new Float3(-0.05635805671f, 0.1485737441f, 0.4210102279f), new Float3(0.3251428613f, 0.09666046873f, -0.2957006485f), new Float3(-0.4190995804f, 0.1406751354f, -0.08405978803f), new Float3(-0.3253150961f, -0.3080335042f, -0.04225456877f), new Float3(0.2857945863f, -0.05796152095f, 0.3427271751f), new Float3(-0.2733604046f, 0.1973770973f, -0.2980207554f), new Float3(0.219003657f, 0.2410037886f, -0.3105713639f), new Float3(0.3182767252f, -0.271342949f, 0.1660509868f), new Float3(-0.03222023115f, -0.3331161506f, -0.300824678f), new Float3(-0.3087780231f, 0.1992794134f, -0.2596995338f), new Float3(-0.06487611647f, -0.4311322747f, 0.1114273361f), new Float3(0.3921171432f, -0.06294284106f, -0.2116183942f), new Float3(-0.1606404506f, -0.358928121f, -0.2187812825f), new Float3(-0.03767771199f, -0.2290351443f, 0.3855169162f), new Float3(0.1394866832f, -0.3602213994f, 0.2308332918f), new Float3(-0.4345093872f, 0.005751117145f, 0.1169124335f), new Float3(-0.1044637494f, 0.4168128432f, -0.1336202785f), new Float3(0.2658727501f, 0.2551943237f, 0.2582393035f), new Float3(0.2051461999f, 0.1975390727f, 0.3484154868f), new Float3(-0.266085566f, 0.23483312f, 0.2766800993f), new Float3(0.07849405464f, -0.3300346342f, -0.2956616708f), new Float3(-0.2160686338f, 0.05376451292f, -0.3910546287f), new Float3(-0.185779186f, 0.2148499206f, 0.3490352499f), new Float3(0.02492421743f, -0.3229954284f, -0.3123343347f), new Float3(-0.120167831f, 0.4017266681f, 0.1633259825f), new Float3(-0.02160084693f, -0.06885389554f, 0.4441762538f), new Float3(0.2597670064f, 0.3096300784f, 0.1978643903f), new Float3(-0.1611553854f, -0.09823036005f, 0.4085091653f), new Float3(-0.3278896792f, 0.1461670309f, 0.2713366126f), new Float3(0.2822734956f, 0.03754421121f, -0.3484423997f), new Float3(0.03169341113f, 0.347405252f, -0.2842624114f), new Float3(0.2202613604f, -0.3460788041f, -0.1849713341f), new Float3(0.2933396046f, 0.3031973659f, 0.1565989581f), new Float3(-0.3194922995f, 0.2453752201f, -0.200538455f), new Float3(-0.3441586045f, -0.1698856132f, -0.2349334659f), new Float3(0.2703645948f, -0.3574277231f, 0.04060059933f), new Float3(0.2298568861f, 0.3744156221f, 0.0973588921f), new Float3(0.09326603877f, -0.3170108894f, 0.3054595587f), new Float3(-0.1116165319f, -0.2985018719f, 0.3177080142f), new Float3(0.2172907365f, -0.3460005203f, -0.1885958001f), new Float3(0.1991339479f, 0.3820341668f, -0.1299829458f), new Float3(-0.0541918155f, -0.2103145071f, 0.39412061f), new Float3(0.08871336998f, 0.2012117383f, 0.3926114802f), new Float3(0.2787673278f, 0.3505404674f, 0.04370535101f), new Float3(-0.322166438f, 0.3067213525f, 0.06804996813f), new Float3(-0.4277366384f, 0.132066775f, 0.04582286686f), new Float3(0.240131882f, -0.1612516055f, 0.344723946f), new Float3(0.1448607981f, -0.2387819045f, 0.3528435224f), new Float3(-0.3837065682f, -0.2206398454f, 0.08116235683f), new Float3(-0.4382627882f, -0.09082753406f, -0.04664855374f), new Float3(-0.37728353f, 0.05445141085f, 0.2391488697f), new Float3(0.1259579313f, 0.348394558f, 0.2554522098f), new Float3(-0.1406285511f, -0.270877371f, -0.3306796947f), new Float3(-0.1580694418f, 0.4162931958f, -0.06491553533f), new Float3(0.2477612106f, -0.2927867412f, -0.2353514536f), new Float3(0.2916132853f, 0.3312535401f, 0.08793624968f), new Float3(0.07365265219f, -0.1666159848f, 0.411478311f), new Float3(-0.26126526f, -0.2422237692f, 0.2748965434f), new Float3(-0.3721862032f, 0.252790166f, 0.008634938242f), new Float3(-0.3691191571f, -0.255281188f, 0.03290232422f), new Float3(0.2278441737f, -0.3358364886f, 0.1944244981f), new Float3(0.363398169f, -0.2310190248f, 0.1306597909f), new Float3(-0.304231482f, -0.2698452035f, 0.1926830856f), new Float3(-0.3199312232f, 0.316332536f, -0.008816977938f), new Float3(0.2874852279f, 0.1642275508f, -0.304764754f), new Float3(-0.1451096801f, 0.3277541114f, -0.2720669462f), new Float3(0.3220090754f, 0.0511344108f, 0.3101538769f), new Float3(-0.1247400865f, -0.04333605335f, -0.4301882115f), new Float3(-0.2829555867f, -0.3056190617f, -0.1703910946f), new Float3(0.1069384374f, 0.3491024667f, -0.2630430352f), new Float3(-0.1420661144f, -0.3055376754f, -0.2982682484f), new Float3(-0.250548338f, 0.3156466809f, -0.2002316239f), new Float3(0.3265787872f, 0.1871229129f, 0.2466400438f), new Float3(0.07646097258f, -0.3026690852f, 0.324106687f), new Float3(0.3451771584f, 0.2757120714f, -0.0856480183f), new Float3(0.298137964f, 0.2852657134f, 0.179547284f), new Float3(0.2812250376f, 0.3466716415f, 0.05684409612f), new Float3(0.4390345476f, -0.09790429955f, -0.01278335452f), new Float3(0.2148373234f, 0.1850172527f, 0.3494474791f), new Float3(0.2595421179f, -0.07946825393f, 0.3589187731f), new Float3(0.3182823114f, -0.307355516f, -0.08203022006f), new Float3(-0.4089859285f, -0.04647718411f, 0.1818526372f), new Float3(-0.2826749061f, 0.07417482322f, 0.3421885344f), new Float3(0.3483864637f, 0.225442246f, -0.1740766085f), new Float3(-0.3226415069f, -0.1420585388f, -0.2796816575f), new Float3(0.4330734858f, -0.118868561f, -0.02859407492f), new Float3(-0.08717822568f, -0.3909896417f, -0.2050050172f), new Float3(-0.2149678299f, 0.3939973956f, -0.03247898316f), new Float3(-0.2687330705f, 0.322686276f, -0.1617284888f), new Float3(0.2105665099f, -0.1961317136f, -0.3459683451f), new Float3(0.4361845915f, -0.1105517485f, 0.004616608544f), new Float3(0.05333333359f, -0.313639498f, -0.3182543336f), new Float3(-0.05986216652f, 0.1361029153f, -0.4247264031f), new Float3(0.3664988455f, 0.2550543014f, -0.05590974511f), new Float3(-0.2341015558f, -0.182405731f, 0.3382670703f), new Float3(-0.04730947785f, -0.4222150243f, -0.1483114513f), new Float3(-0.2391566239f, -0.2577696514f, -0.2808182972f), new Float3(-0.1242081035f, 0.4256953395f, -0.07652336246f), new Float3(0.2614832715f, -0.3650179274f, 0.02980623099f), new Float3(-0.2728794681f, -0.3499628774f, 0.07458404908f), new Float3(0.007892900508f, -0.1672771315f, 0.4176793787f), new Float3(-0.01730330376f, 0.2978486637f, -0.3368779738f), new Float3(0.2054835762f, -0.3252600376f, -0.2334146693f), new Float3(-0.3231994983f, 0.1564282844f, -0.2712420987f), new Float3(-0.2669545963f, 0.2599343665f, -0.2523278991f), new Float3(-0.05554372779f, 0.3170813944f, -0.3144428146f), new Float3(-0.2083935713f, -0.310922837f, -0.2497981362f), new Float3(0.06989323478f, -0.3156141536f, 0.3130537363f), new Float3(0.3847566193f, -0.1605309138f, -0.1693876312f), new Float3(-0.3026215288f, -0.3001537679f, -0.1443188342f), new Float3(0.3450735512f, 0.08611519592f, 0.2756962409f), new Float3(0.1814473292f, -0.2788782453f, -0.3029914042f), new Float3(-0.03855010448f, 0.09795110726f, 0.4375151083f), new Float3(0.3533670318f, 0.2665752752f, 0.08105160988f), new Float3(-0.007945601311f, 0.140359426f, -0.4274764309f), new Float3(0.4063099273f, -0.1491768253f, -0.1231199324f), new Float3(-0.2016773589f, 0.008816271194f, -0.4021797064f), new Float3(-0.07527055435f, -0.425643481f, -0.1251477955f), - }; - // Hashing - private final static int X_PRIME = 1619; - private final static int Y_PRIME = 31337; - private final static int Z_PRIME = 6971; - private final static int W_PRIME = 1013; - private final static float F3 = (float) (1.0 / 3.0); - private final static float G3 = (float) (1.0 / 6.0); - private final static float G33 = G3 * 3 - 1; - private final static float SQRT3 = (float) 1.7320508075688772935274463415059; - private final static float F2 = 0.5f * (SQRT3 - 1.0f); - private final static float G2 = (3.0f - SQRT3) / 6.0f; - private static final byte[] SIMPLEX_4D = {0, 1, 2, 3, 0, 1, 3, 2, 0, 0, 0, 0, 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 3, 1, 2, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 0, 1, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 1, 2, 3, 1, 0, 1, 0, 2, 3, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 1, 0, 0, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 2, 3, 0, 2, 1, 0, 0, 0, 0, 3, 1, 2, 0, 2, 1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 2, 0, 0, 0, 0, 3, 2, 0, 1, 3, 2, 1, 0 - }; - private final static float F4 = (float) ((2.23606797 - 1.0) / 4.0); - private final static float G4 = (float) ((5.0 - 2.23606797) / 20.0); - private final static float CUBIC_3D_BOUNDING = 1 / (float) (1.5 * 1.5 * 1.5); - private final static float CUBIC_2D_BOUNDING = 1 / (float) (1.5 * 1.5); - private int m_seed = 1337; - private float m_frequency = (float) 0.01; - private Interp m_interp = Interp.Quintic; - private NoiseType m_noiseType = NoiseType.Simplex; - private int m_octaves = 3; - private float m_lacunarity = (float) 2.0; - private float m_gain = (float) 0.5; - private FractalType m_fractalType = FractalType.FBM; - private float m_fractalBounding; - private CellularDistanceFunction m_cellularDistanceFunction = CellularDistanceFunction.Euclidean; - private CellularReturnType m_cellularReturnType = CellularReturnType.CellValue; - private FastNoise m_cellularNoiseLookup = null; - private float m_gradientPerturbAmp = (float) (1.0 / 0.45); - - public FastNoise() { - this(1337); - } - - public FastNoise(int seed) { - m_seed = seed; - CalculateFractalBounding(); - } - - // Returns a 0 float/double - public static float GetDecimalType() { - return 0; - } - - private static int FastFloor(float f) { - return (f >= 0 ? (int) f : (int) f - 1); - } - - private static int FastRound(float f) { - return (f >= 0) ? (int) (f + (float) 0.5) : (int) (f - (float) 0.5); - } - - private static float Lerp(float a, float b, float t) { - return a + t * (b - a); - } - - private static float InterpHermiteFunc(float t) { - return t * t * (3 - 2 * t); - } - - private static float InterpQuinticFunc(float t) { - return t * t * t * (t * (t * 6 - 15) + 10); - } - - private static float CubicLerp(float a, float b, float c, float d, float t) { - float p = (d - c) - (a - b); - return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; - } - - private static int Hash2D(int seed, int x, int y) { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - private static int Hash3D(int seed, int x, int y, int z) { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - public static int Hash4D(int seed, int x, int y, int z, int w) { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - hash ^= W_PRIME * w; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - private static float ValCoord2D(int seed, int x, int y) { - int n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - - return (n * n * n * 60493) / (float) 2147483648.0; - } - - private static float ValCoord3D(int seed, int x, int y, int z) { - int n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - n ^= Z_PRIME * z; - - return (n * n * n * 60493) / (float) 2147483648.0; - } - - private static float ValCoord4D(int seed, int x, int y, int z, int w) { - int n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - n ^= Z_PRIME * z; - n ^= W_PRIME * w; - - return (n * n * n * 60493) / (float) 2147483648.0; - } - - private static float GradCoord2D(int seed, int x, int y, float xd, float yd) { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - Float2 g = GRAD_2D[hash & 7]; - - return xd * g.x + yd * g.y; - } - - private static float GradCoord3D(int seed, int x, int y, int z, float xd, float yd, float zd) { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - Float3 g = GRAD_3D[hash & 15]; - - return xd * g.x + yd * g.y + zd * g.z; - } - - private static float GradCoord4D(int seed, int x, int y, int z, int w, float xd, float yd, float zd, float wd) { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - hash ^= W_PRIME * w; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - hash &= 31; - float a = yd, b = zd, c = wd; // X,Y,Z - switch(hash >> 3) { // OR, DEPENDING ON HIGH ORDER 2 BITS: - case 1: - a = wd; - b = xd; - c = yd; - break; // W,X,Y - case 2: - a = zd; - b = wd; - c = xd; - break; // Z,W,X - case 3: - a = yd; - b = zd; - c = wd; - break; // Y,Z,W - } - return ((hash & 4) == 0 ? -a : a) + ((hash & 2) == 0 ? -b : b) + ((hash & 1) == 0 ? -c : c); - } - - // Returns the seed used by this object - public int GetSeed() { - return m_seed; - } - - // Sets seed used for all noise types - // Default: 1337 - public void SetSeed(int seed) { - m_seed = seed; - } - - // Sets frequency for all noise types - // Default: 0.01 - public void SetFrequency(float frequency) { - m_frequency = frequency; - } - - // Changes the interpolation method used to smooth between noise values - // Possible interpolation methods (lowest to highest quality) : - // - Linear - // - Hermite - // - Quintic - // Used in Value, Gradient Noise and Position Perturbing - // Default: Quintic - public void SetInterp(Interp interp) { - m_interp = interp; - } - - // Sets noise return type of GetNoise(...) - // Default: Simplex - public void SetNoiseType(NoiseType noiseType) { - m_noiseType = noiseType; - } - - // Sets octave count for all fractal noise types - // Default: 3 - public void SetFractalOctaves(int octaves) { - m_octaves = octaves; - CalculateFractalBounding(); - } - - // Sets octave lacunarity for all fractal noise types - // Default: 2.0 - public void SetFractalLacunarity(float lacunarity) { - m_lacunarity = lacunarity; - } - - // Sets octave gain for all fractal noise types - // Default: 0.5 - public void SetFractalGain(float gain) { - m_gain = gain; - CalculateFractalBounding(); - } - - // Sets method for combining octaves in all fractal noise types - // Default: FBM - public void SetFractalType(FractalType fractalType) { - m_fractalType = fractalType; - } - - // Sets return type from cellular noise calculations - // Note: NoiseLookup requires another FastNoise object be set with - // SetCellularNoiseLookup() to function - // Default: CellValue - public void SetCellularDistanceFunction(CellularDistanceFunction cellularDistanceFunction) { - m_cellularDistanceFunction = cellularDistanceFunction; - } - - // Sets distance function used in cellular noise calculations - // Default: Euclidean - public void SetCellularReturnType(CellularReturnType cellularReturnType) { - m_cellularReturnType = cellularReturnType; - } - - // Noise used to calculate a cell value if cellular return type is NoiseLookup - // The lookup value is acquired through GetNoise() so ensure you SetNoiseType() - // on the noise lookup, value, gradient or simplex is recommended - public void SetCellularNoiseLookup(FastNoise noise) { - m_cellularNoiseLookup = noise; - } - - // White Noise - - // Sets the maximum perturb distance from original location when using - // GradientPerturb{Fractal}(...) - // Default: 1.0 - public void SetGradientPerturbAmp(float gradientPerturbAmp) { - m_gradientPerturbAmp = gradientPerturbAmp / (float) 0.45; - } - - private void CalculateFractalBounding() { - float amp = m_gain; - float ampFractal = 1; - for(int i = 1; i < m_octaves; i++) { - ampFractal += amp; - amp *= m_gain; - } - m_fractalBounding = 1 / ampFractal; - } - - public float GetNoise(float x, float y, float z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_noiseType) { - case Value: - return SingleValue(m_seed, x, y, z); - case ValueFractal: - switch(m_fractalType) { - case FBM: - return SingleValueFractalFBM(x, y, z); - case Billow: - return SingleValueFractalBillow(x, y, z); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y, z); - default: - return 0; - } - case Perlin: - return SinglePerlin(m_seed, x, y, z); - case PerlinFractal: - switch(m_fractalType) { - case FBM: - return SinglePerlinFractalFBM(x, y, z); - case Billow: - return SinglePerlinFractalBillow(x, y, z); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y, z); - default: - return 0; - } - case Simplex: - return SingleSimplex(m_seed, x, y, z); - case SimplexFractal: - switch(m_fractalType) { - case FBM: - return SingleSimplexFractalFBM(x, y, z); - case Billow: - return SingleSimplexFractalBillow(x, y, z); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y, z); - default: - return 0; - } - case Cellular: - switch(m_cellularReturnType) { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y, z); - default: - return SingleCellular2Edge(x, y, z); - } - case WhiteNoise: - return GetWhiteNoise(x, y, z); - case Cubic: - return SingleCubic(m_seed, x, y, z); - case CubicFractal: - switch(m_fractalType) { - case FBM: - return SingleCubicFractalFBM(x, y, z); - case Billow: - return SingleCubicFractalBillow(x, y, z); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y, z); - default: - return 0; - } - default: - return 0; - } - } - - public float GetNoise(float x, float y) { - x *= m_frequency; - y *= m_frequency; - - switch(m_noiseType) { - case Value: - return SingleValue(m_seed, x, y); - case ValueFractal: - switch(m_fractalType) { - case FBM: - return SingleValueFractalFBM(x, y); - case Billow: - return SingleValueFractalBillow(x, y); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y); - default: - return 0; - } - case Perlin: - return SinglePerlin(m_seed, x, y); - case PerlinFractal: - switch(m_fractalType) { - case FBM: - return SinglePerlinFractalFBM(x, y); - case Billow: - return SinglePerlinFractalBillow(x, y); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y); - default: - return 0; - } - case Simplex: - return SingleSimplex(m_seed, x, y); - case SimplexFractal: - switch(m_fractalType) { - case FBM: - return SingleSimplexFractalFBM(x, y); - case Billow: - return SingleSimplexFractalBillow(x, y); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y); - default: - return 0; - } - case Cellular: - switch(m_cellularReturnType) { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y); - default: - return SingleCellular2Edge(x, y); - } - case WhiteNoise: - return GetWhiteNoise(x, y); - case Cubic: - return SingleCubic(m_seed, x, y); - case CubicFractal: - switch(m_fractalType) { - case FBM: - return SingleCubicFractalFBM(x, y); - case Billow: - return SingleCubicFractalBillow(x, y); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y); - default: - return 0; - } - default: - return 0; - } - } - - private int FloatCast2Int(float f) { - int i = Float.floatToRawIntBits(f); - - return i ^ (i >> 16); - } - - public float GetWhiteNoise(float x, float y, float z, float w) { - int xi = FloatCast2Int(x); - int yi = FloatCast2Int(y); - int zi = FloatCast2Int(z); - int wi = FloatCast2Int(w); - - return ValCoord4D(m_seed, xi, yi, zi, wi); - } - - public float GetWhiteNoise(double x, double y, double z) { - int xi = FloatCast2Int((float) x); - int yi = FloatCast2Int((float) y); - int zi = FloatCast2Int((float) z); - - return ValCoord3D(m_seed, xi, yi, zi); - } - - public float GetWhiteNoise(double x, double y) { - int xi = FloatCast2Int((float) x); - int yi = FloatCast2Int((float) y); - - return ValCoord2D(m_seed, xi, yi); - } - - public float GetWhiteNoiseInt(int x, int y, int z, int w) { - return ValCoord4D(m_seed, x, y, z, w); - } - - public float GetWhiteNoiseInt(int x, int y, int z) { - return ValCoord3D(m_seed, x, y, z); - } - - public float GetWhiteNoiseInt(int x, int y) { - return ValCoord2D(m_seed, x, y); - } - - // Value Noise - public float GetValueFractal(float x, float y, float z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) { - case FBM: - return SingleValueFractalFBM(x, y, z); - case Billow: - return SingleValueFractalBillow(x, y, z); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private float SingleValueFractalFBM(float x, float y, float z) { - int seed = m_seed; - float sum = SingleValue(seed, x, y, z); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleValue(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleValueFractalBillow(float x, float y, float z) { - int seed = m_seed; - float sum = Math.abs(SingleValue(seed, x, y, z)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleValue(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleValueFractalRigidMulti(float x, float y, float z) { - int seed = m_seed; - float sum = 1 - Math.abs(SingleValue(seed, x, y, z)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleValue(++seed, x, y, z))) * amp; - } - - return sum; - } - - public float GetValue(float x, float y, float z) { - return SingleValue(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private float SingleValue(int seed, float x, float y, float z) { - int x0 = FastFloor(x); - int y0 = FastFloor(y); - int z0 = FastFloor(z); - int x1 = x0 + 1; - int y1 = y0 + 1; - int z1 = z0 + 1; - - float xs, ys, zs; - switch(m_interp) { - default: - case Linear: - xs = x - x0; - ys = y - y0; - zs = z - z0; - break; - case Hermite: - xs = InterpHermiteFunc(x - x0); - ys = InterpHermiteFunc(y - y0); - zs = InterpHermiteFunc(z - z0); - break; - case Quintic: - xs = InterpQuinticFunc(x - x0); - ys = InterpQuinticFunc(y - y0); - zs = InterpQuinticFunc(z - z0); - break; - } - - float xf00 = Lerp(ValCoord3D(seed, x0, y0, z0), ValCoord3D(seed, x1, y0, z0), xs); - float xf10 = Lerp(ValCoord3D(seed, x0, y1, z0), ValCoord3D(seed, x1, y1, z0), xs); - float xf01 = Lerp(ValCoord3D(seed, x0, y0, z1), ValCoord3D(seed, x1, y0, z1), xs); - float xf11 = Lerp(ValCoord3D(seed, x0, y1, z1), ValCoord3D(seed, x1, y1, z1), xs); - - float yf0 = Lerp(xf00, xf10, ys); - float yf1 = Lerp(xf01, xf11, ys); - - return Lerp(yf0, yf1, zs); - } - - public float GetValueFractal(float x, float y) { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) { - case FBM: - return SingleValueFractalFBM(x, y); - case Billow: - return SingleValueFractalBillow(x, y); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y); - default: - return 0; - } - } - - private float SingleValueFractalFBM(float x, float y) { - int seed = m_seed; - float sum = SingleValue(seed, x, y); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleValue(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleValueFractalBillow(float x, float y) { - int seed = m_seed; - float sum = Math.abs(SingleValue(seed, x, y)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - amp *= m_gain; - sum += (Math.abs(SingleValue(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleValueFractalRigidMulti(float x, float y) { - int seed = m_seed; - float sum = 1 - Math.abs(SingleValue(seed, x, y)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleValue(++seed, x, y))) * amp; - } - - return sum; - } - - public float GetValue(float x, float y) { - return SingleValue(m_seed, x * m_frequency, y * m_frequency); - } - - private float SingleValue(int seed, float x, float y) { - int x0 = FastFloor(x); - int y0 = FastFloor(y); - int x1 = x0 + 1; - int y1 = y0 + 1; - - float xs, ys; - switch(m_interp) { - default: - case Linear: - xs = x - x0; - ys = y - y0; - break; - case Hermite: - xs = InterpHermiteFunc(x - x0); - ys = InterpHermiteFunc(y - y0); - break; - case Quintic: - xs = InterpQuinticFunc(x - x0); - ys = InterpQuinticFunc(y - y0); - break; - } - - float xf0 = Lerp(ValCoord2D(seed, x0, y0), ValCoord2D(seed, x1, y0), xs); - float xf1 = Lerp(ValCoord2D(seed, x0, y1), ValCoord2D(seed, x1, y1), xs); - - return Lerp(xf0, xf1, ys); - } - - // Gradient Noise - public float GetPerlinFractal(float x, float y, float z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) { - case FBM: - return SinglePerlinFractalFBM(x, y, z); - case Billow: - return SinglePerlinFractalBillow(x, y, z); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private float SinglePerlinFractalFBM(float x, float y, float z) { - int seed = m_seed; - float sum = SinglePerlin(seed, x, y, z); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SinglePerlin(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private float SinglePerlinFractalBillow(float x, float y, float z) { - int seed = m_seed; - float sum = Math.abs(SinglePerlin(seed, x, y, z)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SinglePerlin(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SinglePerlinFractalRigidMulti(float x, float y, float z) { - int seed = m_seed; - float sum = 1 - Math.abs(SinglePerlin(seed, x, y, z)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SinglePerlin(++seed, x, y, z))) * amp; - } - - return sum; - } - - public float GetPerlin(float x, float y, float z) { - return SinglePerlin(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private float SinglePerlin(int seed, float x, float y, float z) { - int x0 = FastFloor(x); - int y0 = FastFloor(y); - int z0 = FastFloor(z); - int x1 = x0 + 1; - int y1 = y0 + 1; - int z1 = z0 + 1; - - float xs, ys, zs; - switch(m_interp) { - default: - case Linear: - xs = x - x0; - ys = y - y0; - zs = z - z0; - break; - case Hermite: - xs = InterpHermiteFunc(x - x0); - ys = InterpHermiteFunc(y - y0); - zs = InterpHermiteFunc(z - z0); - break; - case Quintic: - xs = InterpQuinticFunc(x - x0); - ys = InterpQuinticFunc(y - y0); - zs = InterpQuinticFunc(z - z0); - break; - } - - float xd0 = x - x0; - float yd0 = y - y0; - float zd0 = z - z0; - float xd1 = xd0 - 1; - float yd1 = yd0 - 1; - float zd1 = zd0 - 1; - - float xf00 = Lerp(GradCoord3D(seed, x0, y0, z0, xd0, yd0, zd0), GradCoord3D(seed, x1, y0, z0, xd1, yd0, zd0), xs); - float xf10 = Lerp(GradCoord3D(seed, x0, y1, z0, xd0, yd1, zd0), GradCoord3D(seed, x1, y1, z0, xd1, yd1, zd0), xs); - float xf01 = Lerp(GradCoord3D(seed, x0, y0, z1, xd0, yd0, zd1), GradCoord3D(seed, x1, y0, z1, xd1, yd0, zd1), xs); - float xf11 = Lerp(GradCoord3D(seed, x0, y1, z1, xd0, yd1, zd1), GradCoord3D(seed, x1, y1, z1, xd1, yd1, zd1), xs); - - float yf0 = Lerp(xf00, xf10, ys); - float yf1 = Lerp(xf01, xf11, ys); - - return Lerp(yf0, yf1, zs); - } - - public float GetPerlinFractal(float x, float y) { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) { - case FBM: - return SinglePerlinFractalFBM(x, y); - case Billow: - return SinglePerlinFractalBillow(x, y); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y); - default: - return 0; - } - } - - private float SinglePerlinFractalFBM(float x, float y) { - int seed = m_seed; - float sum = SinglePerlin(seed, x, y); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SinglePerlin(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private float SinglePerlinFractalBillow(float x, float y) { - int seed = m_seed; - float sum = Math.abs(SinglePerlin(seed, x, y)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SinglePerlin(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SinglePerlinFractalRigidMulti(float x, float y) { - int seed = m_seed; - float sum = 1 - Math.abs(SinglePerlin(seed, x, y)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SinglePerlin(++seed, x, y))) * amp; - } - - return sum; - } - - public float GetPerlin(float x, float y) { - return SinglePerlin(m_seed, x * m_frequency, y * m_frequency); - } - - private float SinglePerlin(int seed, float x, float y) { - int x0 = FastFloor(x); - int y0 = FastFloor(y); - int x1 = x0 + 1; - int y1 = y0 + 1; - - float xs, ys; - switch(m_interp) { - default: - case Linear: - xs = x - x0; - ys = y - y0; - break; - case Hermite: - xs = InterpHermiteFunc(x - x0); - ys = InterpHermiteFunc(y - y0); - break; - case Quintic: - xs = InterpQuinticFunc(x - x0); - ys = InterpQuinticFunc(y - y0); - break; - } - - float xd0 = x - x0; - float yd0 = y - y0; - float xd1 = xd0 - 1; - float yd1 = yd0 - 1; - - float xf0 = Lerp(GradCoord2D(seed, x0, y0, xd0, yd0), GradCoord2D(seed, x1, y0, xd1, yd0), xs); - float xf1 = Lerp(GradCoord2D(seed, x0, y1, xd0, yd1), GradCoord2D(seed, x1, y1, xd1, yd1), xs); - - return Lerp(xf0, xf1, ys); - } - - // Simplex Noise - public float GetSimplexFractal(float x, float y, float z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) { - case FBM: - return SingleSimplexFractalFBM(x, y, z); - case Billow: - return SingleSimplexFractalBillow(x, y, z); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private float SingleSimplexFractalFBM(float x, float y, float z) { - int seed = m_seed; - float sum = SingleSimplex(seed, x, y, z); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleSimplex(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleSimplexFractalBillow(float x, float y, float z) { - int seed = m_seed; - float sum = Math.abs(SingleSimplex(seed, x, y, z)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleSimplex(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleSimplexFractalRigidMulti(float x, float y, float z) { - int seed = m_seed; - float sum = 1 - Math.abs(SingleSimplex(seed, x, y, z)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleSimplex(++seed, x, y, z))) * amp; - } - - return sum; - } - - public float GetSimplex(float x, float y, float z) { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private float SingleSimplex(int seed, float x, float y, float z) { - float t = (x + y + z) * F3; - int i = FastFloor(x + t); - int j = FastFloor(y + t); - int k = FastFloor(z + t); - - t = (i + j + k) * G3; - float x0 = x - (i - t); - float y0 = y - (j - t); - float z0 = z - (k - t); - - int i1, j1, k1; - int i2, j2, k2; - - if(x0 >= y0) { - if(y0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } else if(x0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 0; - k2 = 1; - } else // x0 < z0 - { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 1; - j2 = 0; - k2 = 1; - } - } else // x0 < y0 - { - if(y0 < z0) { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 0; - j2 = 1; - k2 = 1; - } else if(x0 < z0) { - i1 = 0; - j1 = 1; - k1 = 0; - i2 = 0; - j2 = 1; - k2 = 1; - } else // x0 >= z0 - { - i1 = 0; - j1 = 1; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } - } - - float x1 = x0 - i1 + G3; - float y1 = y0 - j1 + G3; - float z1 = z0 - k1 + G3; - float x2 = x0 - i2 + F3; - float y2 = y0 - j2 + F3; - float z2 = z0 - k2 + F3; - float x3 = x0 + G33; - float y3 = y0 + G33; - float z3 = z0 + G33; - - float n0, n1, n2, n3; - - t = (float) 0.6 - x0 * x0 - y0 * y0 - z0 * z0; - if(t < 0) - n0 = 0; - else { - t *= t; - n0 = t * t * GradCoord3D(seed, i, j, k, x0, y0, z0); - } - - t = (float) 0.6 - x1 * x1 - y1 * y1 - z1 * z1; - if(t < 0) - n1 = 0; - else { - t *= t; - n1 = t * t * GradCoord3D(seed, i + i1, j + j1, k + k1, x1, y1, z1); - } - - t = (float) 0.6 - x2 * x2 - y2 * y2 - z2 * z2; - if(t < 0) - n2 = 0; - else { - t *= t; - n2 = t * t * GradCoord3D(seed, i + i2, j + j2, k + k2, x2, y2, z2); - } - - t = (float) 0.6 - x3 * x3 - y3 * y3 - z3 * z3; - if(t < 0) - n3 = 0; - else { - t *= t; - n3 = t * t * GradCoord3D(seed, i + 1, j + 1, k + 1, x3, y3, z3); - } - - return 32 * (n0 + n1 + n2 + n3); - } - - public float GetSimplexFractal(float x, float y) { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) { - case FBM: - return SingleSimplexFractalFBM(x, y); - case Billow: - return SingleSimplexFractalBillow(x, y); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y); - default: - return 0; - } - } - - private float SingleSimplexFractalFBM(float x, float y) { - int seed = m_seed; - float sum = SingleSimplex(seed, x, y); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleSimplex(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleSimplexFractalBillow(float x, float y) { - int seed = m_seed; - float sum = Math.abs(SingleSimplex(seed, x, y)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleSimplex(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleSimplexFractalRigidMulti(float x, float y) { - int seed = m_seed; - float sum = 1 - Math.abs(SingleSimplex(seed, x, y)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleSimplex(++seed, x, y))) * amp; - } - - return sum; - } - - public float GetSimplex(float x, float y) { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency); - } - - private float SingleSimplex(int seed, float x, float y) { - float t = (x + y) * F2; - int i = FastFloor(x + t); - int j = FastFloor(y + t); - - t = (i + j) * G2; - float X0 = i - t; - float Y0 = j - t; - - float x0 = x - X0; - float y0 = y - Y0; - - int i1, j1; - if(x0 > y0) { - i1 = 1; - j1 = 0; - } else { - i1 = 0; - j1 = 1; - } - - float x1 = x0 - i1 + G2; - float y1 = y0 - j1 + G2; - float x2 = x0 - 1 + 2 * G2; - float y2 = y0 - 1 + 2 * G2; - - float n0, n1, n2; - - t = (float) 0.5 - x0 * x0 - y0 * y0; - if(t < 0) - n0 = 0; - else { - t *= t; - n0 = t * t * GradCoord2D(seed, i, j, x0, y0); - } - - t = (float) 0.5 - x1 * x1 - y1 * y1; - if(t < 0) - n1 = 0; - else { - t *= t; - n1 = t * t * GradCoord2D(seed, i + i1, j + j1, x1, y1); - } - - t = (float) 0.5 - x2 * x2 - y2 * y2; - if(t < 0) - n2 = 0; - else { - t *= t; - n2 = t * t * GradCoord2D(seed, i + 1, j + 1, x2, y2); - } - - return 50 * (n0 + n1 + n2); - } - - public float GetSimplex(float x, float y, float z, float w) { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency, w * m_frequency); - } - - private float SingleSimplex(int seed, float x, float y, float z, float w) { - float n0, n1, n2, n3, n4; - float t = (x + y + z + w) * F4; - int i = FastFloor(x + t); - int j = FastFloor(y + t); - int k = FastFloor(z + t); - int l = FastFloor(w + t); - t = (i + j + k + l) * G4; - float X0 = i - t; - float Y0 = j - t; - float Z0 = k - t; - float W0 = l - t; - float x0 = x - X0; - float y0 = y - Y0; - float z0 = z - Z0; - float w0 = w - W0; - - int c = (x0 > y0) ? 32 : 0; - c += (x0 > z0) ? 16 : 0; - c += (y0 > z0) ? 8 : 0; - c += (x0 > w0) ? 4 : 0; - c += (y0 > w0) ? 2 : 0; - c += (z0 > w0) ? 1 : 0; - c <<= 2; - - int i1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - int i2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - int i3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - int j1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - int j2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - int j3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - int k1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - int k2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - int k3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - int l1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - int l2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - int l3 = SIMPLEX_4D[c] >= 1 ? 1 : 0; - - float x1 = x0 - i1 + G4; - float y1 = y0 - j1 + G4; - float z1 = z0 - k1 + G4; - float w1 = w0 - l1 + G4; - float x2 = x0 - i2 + 2 * G4; - float y2 = y0 - j2 + 2 * G4; - float z2 = z0 - k2 + 2 * G4; - float w2 = w0 - l2 + 2 * G4; - float x3 = x0 - i3 + 3 * G4; - float y3 = y0 - j3 + 3 * G4; - float z3 = z0 - k3 + 3 * G4; - float w3 = w0 - l3 + 3 * G4; - float x4 = x0 - 1 + 4 * G4; - float y4 = y0 - 1 + 4 * G4; - float z4 = z0 - 1 + 4 * G4; - float w4 = w0 - 1 + 4 * G4; - - t = (float) 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; - if(t < 0) - n0 = 0; - else { - t *= t; - n0 = t * t * GradCoord4D(seed, i, j, k, l, x0, y0, z0, w0); - } - t = (float) 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; - if(t < 0) - n1 = 0; - else { - t *= t; - n1 = t * t * GradCoord4D(seed, i + i1, j + j1, k + k1, l + l1, x1, y1, z1, w1); - } - t = (float) 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; - if(t < 0) - n2 = 0; - else { - t *= t; - n2 = t * t * GradCoord4D(seed, i + i2, j + j2, k + k2, l + l2, x2, y2, z2, w2); - } - t = (float) 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; - if(t < 0) - n3 = 0; - else { - t *= t; - n3 = t * t * GradCoord4D(seed, i + i3, j + j3, k + k3, l + l3, x3, y3, z3, w3); - } - t = (float) 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; - if(t < 0) - n4 = 0; - else { - t *= t; - n4 = t * t * GradCoord4D(seed, i + 1, j + 1, k + 1, l + 1, x4, y4, z4, w4); - } - - return 27 * (n0 + n1 + n2 + n3 + n4); - } - - // Cubic Noise - public float GetCubicFractal(float x, float y, float z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) { - case FBM: - return SingleCubicFractalFBM(x, y, z); - case Billow: - return SingleCubicFractalBillow(x, y, z); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private float SingleCubicFractalFBM(float x, float y, float z) { - int seed = m_seed; - float sum = SingleCubic(seed, x, y, z); - float amp = 1; - int i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleCubic(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleCubicFractalBillow(float x, float y, float z) { - int seed = m_seed; - float sum = Math.abs(SingleCubic(seed, x, y, z)) * 2 - 1; - float amp = 1; - int i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleCubic(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleCubicFractalRigidMulti(float x, float y, float z) { - int seed = m_seed; - float sum = 1 - Math.abs(SingleCubic(seed, x, y, z)); - float amp = 1; - int i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleCubic(++seed, x, y, z))) * amp; - } - - return sum; - } - - public float GetCubic(float x, float y, float z) { - return SingleCubic(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private float SingleCubic(int seed, float x, float y, float z) { - int x1 = FastFloor(x); - int y1 = FastFloor(y); - int z1 = FastFloor(z); - - int x0 = x1 - 1; - int y0 = y1 - 1; - int z0 = z1 - 1; - int x2 = x1 + 1; - int y2 = y1 + 1; - int z2 = z1 + 1; - int x3 = x1 + 2; - int y3 = y1 + 2; - int z3 = z1 + 2; - - float xs = x - (float) x1; - float ys = y - (float) y1; - float zs = z - (float) z1; - - return CubicLerp(CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z0), ValCoord3D(seed, x1, y0, z0), ValCoord3D(seed, x2, y0, z0), ValCoord3D(seed, x3, y0, z0), xs), CubicLerp(ValCoord3D(seed, x0, y1, z0), ValCoord3D(seed, x1, y1, z0), ValCoord3D(seed, x2, y1, z0), ValCoord3D(seed, x3, y1, z0), xs), CubicLerp(ValCoord3D(seed, x0, y2, z0), ValCoord3D(seed, x1, y2, z0), ValCoord3D(seed, x2, y2, z0), ValCoord3D(seed, x3, y2, z0), xs), CubicLerp(ValCoord3D(seed, x0, y3, z0), ValCoord3D(seed, x1, y3, z0), ValCoord3D(seed, x2, y3, z0), ValCoord3D(seed, x3, y3, z0), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z1), ValCoord3D(seed, x1, y0, z1), ValCoord3D(seed, x2, y0, z1), ValCoord3D(seed, x3, y0, z1), xs), CubicLerp(ValCoord3D(seed, x0, y1, z1), ValCoord3D(seed, x1, y1, z1), ValCoord3D(seed, x2, y1, z1), ValCoord3D(seed, x3, y1, z1), xs), CubicLerp(ValCoord3D(seed, x0, y2, z1), ValCoord3D(seed, x1, y2, z1), ValCoord3D(seed, x2, y2, z1), ValCoord3D(seed, x3, y2, z1), xs), CubicLerp(ValCoord3D(seed, x0, y3, z1), ValCoord3D(seed, x1, y3, z1), ValCoord3D(seed, x2, y3, z1), ValCoord3D(seed, x3, y3, z1), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z2), ValCoord3D(seed, x1, y0, z2), ValCoord3D(seed, x2, y0, z2), ValCoord3D(seed, x3, y0, z2), xs), CubicLerp(ValCoord3D(seed, x0, y1, z2), ValCoord3D(seed, x1, y1, z2), ValCoord3D(seed, x2, y1, z2), ValCoord3D(seed, x3, y1, z2), xs), CubicLerp(ValCoord3D(seed, x0, y2, z2), ValCoord3D(seed, x1, y2, z2), ValCoord3D(seed, x2, y2, z2), ValCoord3D(seed, x3, y2, z2), xs), CubicLerp(ValCoord3D(seed, x0, y3, z2), ValCoord3D(seed, x1, y3, z2), ValCoord3D(seed, x2, y3, z2), ValCoord3D(seed, x3, y3, z2), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z3), ValCoord3D(seed, x1, y0, z3), ValCoord3D(seed, x2, y0, z3), ValCoord3D(seed, x3, y0, z3), xs), CubicLerp(ValCoord3D(seed, x0, y1, z3), ValCoord3D(seed, x1, y1, z3), ValCoord3D(seed, x2, y1, z3), ValCoord3D(seed, x3, y1, z3), xs), CubicLerp(ValCoord3D(seed, x0, y2, z3), ValCoord3D(seed, x1, y2, z3), ValCoord3D(seed, x2, y2, z3), ValCoord3D(seed, x3, y2, z3), xs), CubicLerp(ValCoord3D(seed, x0, y3, z3), ValCoord3D(seed, x1, y3, z3), ValCoord3D(seed, x2, y3, z3), ValCoord3D(seed, x3, y3, z3), xs), ys), zs) * CUBIC_3D_BOUNDING; - } - - public float GetCubicFractal(float x, float y) { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) { - case FBM: - return SingleCubicFractalFBM(x, y); - case Billow: - return SingleCubicFractalBillow(x, y); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y); - default: - return 0; - } - } - - private float SingleCubicFractalFBM(float x, float y) { - int seed = m_seed; - float sum = SingleCubic(seed, x, y); - float amp = 1; - int i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleCubic(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleCubicFractalBillow(float x, float y) { - int seed = m_seed; - float sum = Math.abs(SingleCubic(seed, x, y)) * 2 - 1; - float amp = 1; - int i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleCubic(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleCubicFractalRigidMulti(float x, float y) { - int seed = m_seed; - float sum = 1 - Math.abs(SingleCubic(seed, x, y)); - float amp = 1; - int i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleCubic(++seed, x, y))) * amp; - } - - return sum; - } - - public float GetCubic(float x, float y) { - x *= m_frequency; - y *= m_frequency; - - return SingleCubic(0, x, y); - } - - private float SingleCubic(int seed, float x, float y) { - int x1 = FastFloor(x); - int y1 = FastFloor(y); - - int x0 = x1 - 1; - int y0 = y1 - 1; - int x2 = x1 + 1; - int y2 = y1 + 1; - int x3 = x1 + 2; - int y3 = y1 + 2; - - float xs = x - (float) x1; - float ys = y - (float) y1; - - return CubicLerp(CubicLerp(ValCoord2D(seed, x0, y0), ValCoord2D(seed, x1, y0), ValCoord2D(seed, x2, y0), ValCoord2D(seed, x3, y0), xs), CubicLerp(ValCoord2D(seed, x0, y1), ValCoord2D(seed, x1, y1), ValCoord2D(seed, x2, y1), ValCoord2D(seed, x3, y1), xs), CubicLerp(ValCoord2D(seed, x0, y2), ValCoord2D(seed, x1, y2), ValCoord2D(seed, x2, y2), ValCoord2D(seed, x3, y2), xs), CubicLerp(ValCoord2D(seed, x0, y3), ValCoord2D(seed, x1, y3), ValCoord2D(seed, x2, y3), ValCoord2D(seed, x3, y3), xs), ys) * CUBIC_2D_BOUNDING; - } - - // Cellular Noise - public float GetCellular(float x, float y, float z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_cellularReturnType) { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y, z); - default: - return SingleCellular2Edge(x, y, z); - } - } - - private float SingleCellular(float x, float y, float z) { - int xr = FastRound(x); - int yr = FastRound(y); - int zr = FastRound(z); - - float distance = 999999; - int xc = 0, yc = 0, zc = 0; - - switch(m_cellularDistanceFunction) { - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - for(int zi = zr - 1; zi <= zr + 1; zi++) { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - for(int zi = zr - 1; zi <= zr + 1; zi++) { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - for(int zi = zr - 1; zi <= zr + 1; zi++) { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - } - - switch(m_cellularReturnType) { - case CellValue: - return ValCoord3D(0, xc, yc, zc); - - case NoiseLookup: - Float3 vec = CELL_3D[Hash3D(m_seed, xc, yc, zc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y, zc + vec.z); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private float SingleCellular2Edge(float x, float y, float z) { - int xr = FastRound(x); - int yr = FastRound(y); - int zr = FastRound(z); - - float distance = 999999; - float distance2 = 999999; - - switch(m_cellularDistanceFunction) { - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - for(int zi = zr - 1; zi <= zr + 1; zi++) { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - for(int zi = zr - 1; zi <= zr + 1; zi++) { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - for(int zi = zr - 1; zi <= zr + 1; zi++) { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - default: - break; - } - - switch(m_cellularReturnType) { - case Distance2: - return distance2 - 1; - case Distance2Add: - return distance2 + distance - 1; - case Distance2Sub: - return distance2 - distance - 1; - case Distance2Mul: - return distance2 * distance - 1; - case Distance2Div: - return distance / distance2 - 1; - default: - return 0; - } - } - - public float GetCellular(float x, float y, ProceduralStream sourceNoise, double iscale) { - x *= m_frequency; - y *= m_frequency; - - switch(m_cellularReturnType) { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y, sourceNoise, iscale); - default: - return SingleCellular2Edge(x, y); - } - } - - public float GetCellular(float x, float y) { - x *= m_frequency; - y *= m_frequency; - - switch(m_cellularReturnType) { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y); - default: - return SingleCellular2Edge(x, y); - } - } - - private float SingleCellular(float x, float y) { - int xr = FastRound(x); - int yr = FastRound(y); - - float distance = 999999; - int xc = 0, yc = 0; - - switch(m_cellularDistanceFunction) { - default: - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = vecX * vecX + vecY * vecY; - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY)); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - } - - switch(m_cellularReturnType) { - case CellValue: - return ValCoord2D(0, xc, yc); - - case NoiseLookup: - Float2 vec = CELL_2D[Hash2D(m_seed, xc, yc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private float SingleCellular(float x, float y, ProceduralStream sourceNoise, double iscale) { - int xr = FastRound(x); - int yr = FastRound(y); - - float distance = 999999; - int xc = 0, yc = 0; - - switch(m_cellularDistanceFunction) { - default: - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = vecX * vecX + vecY * vecY; - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY)); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - } - - switch(m_cellularReturnType) { - case CellValue: - return sourceNoise.get(xc * iscale, yc * iscale).floatValue(); - - case NoiseLookup: - Float2 vec = CELL_2D[Hash2D(m_seed, xc, yc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private float SingleCellular2Edge(float x, float y) { - int xr = FastRound(x); - int yr = FastRound(y); - - float distance = 999999; - float distance2 = 999999; - - switch(m_cellularDistanceFunction) { - default: - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = vecX * vecX + vecY * vecY; - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = Math.abs(vecX) + Math.abs(vecY); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) { - for(int yi = yr - 1; yi <= yr + 1; yi++) { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - } - - switch(m_cellularReturnType) { - case Distance2: - return distance2 - 1; - case Distance2Add: - return distance2 + distance - 1; - case Distance2Sub: - return distance2 - distance - 1; - case Distance2Mul: - return distance2 * distance - 1; - case Distance2Div: - return distance / distance2 - 1; - default: - return 0; - } - } - - public void GradientPerturb(Vector3f v3) { - SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v3); - } - - public void GradientPerturbFractal(Vector3f v3) { - int seed = m_seed; - float amp = m_gradientPerturbAmp * m_fractalBounding; - float freq = m_frequency; - - SingleGradientPerturb(seed, amp, m_frequency, v3); - - for(int i = 1; i < m_octaves; i++) { - freq *= m_lacunarity; - amp *= m_gain; - SingleGradientPerturb(++seed, amp, freq, v3); - } - } - - private void SingleGradientPerturb(int seed, float perturbAmp, float frequency, Vector3f v3) { - float xf = v3.x * frequency; - float yf = v3.y * frequency; - float zf = v3.z * frequency; - - int x0 = FastFloor(xf); - int y0 = FastFloor(yf); - int z0 = FastFloor(zf); - int x1 = x0 + 1; - int y1 = y0 + 1; - int z1 = z0 + 1; - - float xs, ys, zs; - switch(m_interp) { - default: - case Linear: - xs = xf - x0; - ys = yf - y0; - zs = zf - z0; - break; - case Hermite: - xs = InterpHermiteFunc(xf - x0); - ys = InterpHermiteFunc(yf - y0); - zs = InterpHermiteFunc(zf - z0); - break; - case Quintic: - xs = InterpQuinticFunc(xf - x0); - ys = InterpQuinticFunc(yf - y0); - zs = InterpQuinticFunc(zf - z0); - break; - } - - Float3 vec0 = CELL_3D[Hash3D(seed, x0, y0, z0) & 255]; - Float3 vec1 = CELL_3D[Hash3D(seed, x1, y0, z0) & 255]; - - float lx0x = Lerp(vec0.x, vec1.x, xs); - float ly0x = Lerp(vec0.y, vec1.y, xs); - float lz0x = Lerp(vec0.z, vec1.z, xs); - - vec0 = CELL_3D[Hash3D(seed, x0, y1, z0) & 255]; - vec1 = CELL_3D[Hash3D(seed, x1, y1, z0) & 255]; - - float lx1x = Lerp(vec0.x, vec1.x, xs); - float ly1x = Lerp(vec0.y, vec1.y, xs); - float lz1x = Lerp(vec0.z, vec1.z, xs); - - float lx0y = Lerp(lx0x, lx1x, ys); - float ly0y = Lerp(ly0x, ly1x, ys); - float lz0y = Lerp(lz0x, lz1x, ys); - - vec0 = CELL_3D[Hash3D(seed, x0, y0, z1) & 255]; - vec1 = CELL_3D[Hash3D(seed, x1, y0, z1) & 255]; - - lx0x = Lerp(vec0.x, vec1.x, xs); - ly0x = Lerp(vec0.y, vec1.y, xs); - lz0x = Lerp(vec0.z, vec1.z, xs); - - vec0 = CELL_3D[Hash3D(seed, x0, y1, z1) & 255]; - vec1 = CELL_3D[Hash3D(seed, x1, y1, z1) & 255]; - - lx1x = Lerp(vec0.x, vec1.x, xs); - ly1x = Lerp(vec0.y, vec1.y, xs); - lz1x = Lerp(vec0.z, vec1.z, xs); - - v3.x += Lerp(lx0y, Lerp(lx0x, lx1x, ys), zs) * perturbAmp; - v3.y += Lerp(ly0y, Lerp(ly0x, ly1x, ys), zs) * perturbAmp; - v3.z += Lerp(lz0y, Lerp(lz0x, lz1x, ys), zs) * perturbAmp; - } - - public void GradientPerturb(Vector2f v2) { - SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v2); - } - - public void GradientPerturbFractal(Vector2f v2) { - int seed = m_seed; - float amp = m_gradientPerturbAmp * m_fractalBounding; - float freq = m_frequency; - - SingleGradientPerturb(seed, amp, m_frequency, v2); - - for(int i = 1; i < m_octaves; i++) { - freq *= m_lacunarity; - amp *= m_gain; - SingleGradientPerturb(++seed, amp, freq, v2); - } - } - - private void SingleGradientPerturb(int seed, float perturbAmp, float frequency, Vector2f v2) { - float xf = v2.x * frequency; - float yf = v2.y * frequency; - - int x0 = FastFloor(xf); - int y0 = FastFloor(yf); - int x1 = x0 + 1; - int y1 = y0 + 1; - - float xs, ys; - switch(m_interp) { - default: - case Linear: - xs = xf - x0; - ys = yf - y0; - break; - case Hermite: - xs = InterpHermiteFunc(xf - x0); - ys = InterpHermiteFunc(yf - y0); - break; - case Quintic: - xs = InterpQuinticFunc(xf - x0); - ys = InterpQuinticFunc(yf - y0); - break; - } - - Float2 vec0 = CELL_2D[Hash2D(seed, x0, y0) & 255]; - Float2 vec1 = CELL_2D[Hash2D(seed, x1, y0) & 255]; - - float lx0x = Lerp(vec0.x, vec1.x, xs); - float ly0x = Lerp(vec0.y, vec1.y, xs); - - vec0 = CELL_2D[Hash2D(seed, x0, y1) & 255]; - vec1 = CELL_2D[Hash2D(seed, x1, y1) & 255]; - - float lx1x = Lerp(vec0.x, vec1.x, xs); - float ly1x = Lerp(vec0.y, vec1.y, xs); - - v2.x += Lerp(lx0x, lx1x, ys) * perturbAmp; - v2.y += Lerp(ly0x, ly1x, ys) * perturbAmp; - } - - public enum NoiseType { - Value, - ValueFractal, - Perlin, - PerlinFractal, - Simplex, - SimplexFractal, - Cellular, - WhiteNoise, - Cubic, - CubicFractal - } - - public enum Interp { - Linear, - Hermite, - Quintic - } - - public enum FractalType { - FBM, - Billow, - RigidMulti - } - - public enum CellularDistanceFunction { - Euclidean, - Manhattan, - Natural - } - - public enum CellularReturnType { - CellValue, - NoiseLookup, - Distance, - Distance2, - Distance2Add, - Distance2Sub, - Distance2Mul, - Distance2Div - } - - private static class Float2 { - public final float x, y; - - public Float2(float x, float y) { - this.x = x; - this.y = y; - } - } - - private static class Float3 { - public final float x, y, z; - - public Float3(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/noise/FastNoiseDouble.java b/src/main/java/com/volmit/iris/util/noise/FastNoiseDouble.java deleted file mode 100644 index 96af95eb9..000000000 --- a/src/main/java/com/volmit/iris/util/noise/FastNoiseDouble.java +++ /dev/null @@ -1,1989 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.Vector2f; -import com.volmit.iris.util.math.Vector3f; - -public class FastNoiseDouble { - private static final Double2[] GRAD_2D = {new Double2(-1, -1), new Double2(1, -1), new Double2(-1, 1), new Double2(1, 1), new Double2(0, -1), new Double2(-1, 0), new Double2(0, 1), new Double2(1, 0), - }; - private static final Double3[] GRAD_3D = {new Double3(1, 1, 0), new Double3(-1, 1, 0), new Double3(1, -1, 0), new Double3(-1, -1, 0), new Double3(1, 0, 1), new Double3(-1, 0, 1), new Double3(1, 0, -1), new Double3(-1, 0, -1), new Double3(0, 1, 1), new Double3(0, -1, 1), new Double3(0, 1, -1), new Double3(0, -1, -1), new Double3(1, 1, 0), new Double3(0, -1, 1), new Double3(-1, 1, 0), new Double3(0, -1, -1), - }; - private static final Double2[] CELL_2D = {new Double2(-0.4313539279f, 0.1281943404f), new Double2(-0.1733316799f, 0.415278375f), new Double2(-0.2821957395f, -0.3505218461f), new Double2(-0.2806473808f, 0.3517627718f), new Double2(0.3125508975f, -0.3237467165f), new Double2(0.3383018443f, -0.2967353402f), new Double2(-0.4393982022f, -0.09710417025f), new Double2(-0.4460443703f, -0.05953502905f), new Double2(-0.302223039f, 0.3334085102f), new Double2(-0.212681052f, -0.3965687458f), new Double2(-0.2991156529f, 0.3361990872f), new Double2(0.2293323691f, 0.3871778202f), new Double2(0.4475439151f, -0.04695150755f), new Double2(0.1777518f, 0.41340573f), new Double2(0.1688522499f, -0.4171197882f), new Double2(-0.0976597166f, 0.4392750616f), new Double2(0.08450188373f, 0.4419948321f), new Double2(-0.4098760448f, -0.1857461384f), new Double2(0.3476585782f, -0.2857157906f), new Double2(-0.3350670039f, -0.30038326f), new Double2(0.2298190031f, -0.3868891648f), new Double2(-0.01069924099f, 0.449872789f), new Double2(-0.4460141246f, -0.05976119672f), new Double2(0.3650293864f, 0.2631606867f), new Double2(-0.349479423f, 0.2834856838f), new Double2(-0.4122720642f, 0.1803655873f), new Double2(-0.267327811f, 0.3619887311f), new Double2(0.322124041f, -0.3142230135f), new Double2(0.2880445931f, -0.3457315612f), new Double2(0.3892170926f, -0.2258540565f), new Double2(0.4492085018f, -0.02667811596f), new Double2(-0.4497724772f, 0.01430799601f), new Double2(0.1278175387f, -0.4314657307f), new Double2(-0.03572100503f, 0.4485799926f), new Double2(-0.4297407068f, -0.1335025276f), new Double2(-0.3217817723f, 0.3145735065f), new Double2(-0.3057158873f, 0.3302087162f), new Double2(-0.414503978f, 0.1751754899f), new Double2(-0.3738139881f, 0.2505256519f), new Double2(0.2236891408f, -0.3904653228f), new Double2(0.002967775577f, -0.4499902136f), new Double2(0.1747128327f, -0.4146991995f), new Double2(-0.4423772489f, -0.08247647938f), new Double2(-0.2763960987f, -0.355112935f), new Double2(-0.4019385906f, -0.2023496216f), new Double2(0.3871414161f, -0.2293938184f), new Double2(-0.430008727f, 0.1326367019f), new Double2(-0.03037574274f, -0.4489736231f), new Double2(-0.3486181573f, 0.2845441624f), new Double2(0.04553517144f, -0.4476902368f), new Double2(-0.0375802926f, 0.4484280562f), new Double2(0.3266408905f, 0.3095250049f), new Double2(0.06540017593f, -0.4452222108f), new Double2(0.03409025829f, 0.448706869f), new Double2(-0.4449193635f, 0.06742966669f), new Double2(-0.4255936157f, -0.1461850686f), new Double2(0.449917292f, 0.008627302568f), new Double2(0.05242606404f, 0.4469356864f), new Double2(-0.4495305179f, -0.02055026661f), new Double2(-0.1204775703f, 0.4335725488f), new Double2(-0.341986385f, -0.2924813028f), new Double2(0.3865320182f, 0.2304191809f), new Double2(0.04506097811f, -0.447738214f), new Double2(-0.06283465979f, 0.4455915232f), new Double2(0.3932600341f, -0.2187385324f), new Double2(0.4472261803f, -0.04988730975f), new Double2(0.3753571011f, -0.2482076684f), new Double2(-0.273662295f, 0.357223947f), new Double2(0.1700461538f, 0.4166344988f), new Double2(0.4102692229f, 0.1848760794f), new Double2(0.323227187f, -0.3130881435f), new Double2(-0.2882310238f, -0.3455761521f), new Double2(0.2050972664f, 0.4005435199f), new Double2(0.4414085979f, -0.08751256895f), new Double2(-0.1684700334f, 0.4172743077f), new Double2(-0.003978032396f, 0.4499824166f), new Double2(-0.2055133639f, 0.4003301853f), new Double2(-0.006095674897f, -0.4499587123f), new Double2(-0.1196228124f, -0.4338091548f), new Double2(0.3901528491f, -0.2242337048f), new Double2(0.01723531752f, 0.4496698165f), new Double2(-0.3015070339f, 0.3340561458f), new Double2(-0.01514262423f, -0.4497451511f), new Double2(-0.4142574071f, -0.1757577897f), new Double2(-0.1916377265f, -0.4071547394f), new Double2(0.3749248747f, 0.2488600778f), new Double2(-0.2237774255f, 0.3904147331f), new Double2(-0.4166343106f, -0.1700466149f), new Double2(0.3619171625f, 0.267424695f), new Double2(0.1891126846f, -0.4083336779f), new Double2(-0.3127425077f, 0.323561623f), new Double2(-0.3281807787f, 0.307891826f), new Double2(-0.2294806661f, 0.3870899429f), new Double2(-0.3445266136f, 0.2894847362f), new Double2(-0.4167095422f, -0.1698621719f), new Double2(-0.257890321f, -0.3687717212f), new Double2(-0.3612037825f, 0.2683874578f), new Double2(0.2267996491f, 0.3886668486f), new Double2(0.207157062f, 0.3994821043f), new Double2(0.08355176718f, -0.4421754202f), new Double2(-0.4312233307f, 0.1286329626f), new Double2(0.3257055497f, 0.3105090899f), new Double2(0.177701095f, -0.4134275279f), new Double2(-0.445182522f, 0.06566979625f), new Double2(0.3955143435f, 0.2146355146f), new Double2(-0.4264613988f, 0.1436338239f), new Double2(-0.3793799665f, -0.2420141339f), new Double2(0.04617599081f, -0.4476245948f), new Double2(-0.371405428f, -0.2540826796f), new Double2(0.2563570295f, -0.3698392535f), new Double2(0.03476646309f, 0.4486549822f), new Double2(-0.3065454405f, 0.3294387544f), new Double2(-0.2256979823f, 0.3893076172f), new Double2(0.4116448463f, -0.1817925206f), new Double2(-0.2907745828f, -0.3434387019f), new Double2(0.2842278468f, -0.348876097f), new Double2(0.3114589359f, -0.3247973695f), new Double2(0.4464155859f, -0.0566844308f), new Double2(-0.3037334033f, -0.3320331606f), new Double2(0.4079607166f, 0.1899159123f), new Double2(-0.3486948919f, -0.2844501228f), new Double2(0.3264821436f, 0.3096924441f), new Double2(0.3211142406f, 0.3152548881f), new Double2(0.01183382662f, 0.4498443737f), new Double2(0.4333844092f, 0.1211526057f), new Double2(0.3118668416f, 0.324405723f), new Double2(-0.272753471f, 0.3579183483f), new Double2(-0.422228622f, -0.1556373694f), new Double2(-0.1009700099f, -0.4385260051f), new Double2(-0.2741171231f, -0.3568750521f), new Double2(-0.1465125133f, 0.4254810025f), new Double2(0.2302279044f, -0.3866459777f), new Double2(-0.3699435608f, 0.2562064828f), new Double2(0.105700352f, -0.4374099171f), new Double2(-0.2646713633f, 0.3639355292f), new Double2(0.3521828122f, 0.2801200935f), new Double2(-0.1864187807f, -0.4095705534f), new Double2(0.1994492955f, -0.4033856449f), new Double2(0.3937065066f, 0.2179339044f), new Double2(-0.3226158377f, 0.3137180602f), new Double2(0.3796235338f, 0.2416318948f), new Double2(0.1482921929f, 0.4248640083f), new Double2(-0.407400394f, 0.1911149365f), new Double2(0.4212853031f, 0.1581729856f), new Double2(-0.2621297173f, 0.3657704353f), new Double2(-0.2536986953f, -0.3716678248f), new Double2(-0.2100236383f, 0.3979825013f), new Double2(0.3624152444f, 0.2667493029f), new Double2(-0.3645038479f, -0.2638881295f), new Double2(0.2318486784f, 0.3856762766f), new Double2(-0.3260457004f, 0.3101519002f), new Double2(-0.2130045332f, -0.3963950918f), new Double2(0.3814998766f, -0.2386584257f), new Double2(-0.342977305f, 0.2913186713f), new Double2(-0.4355865605f, 0.1129794154f), new Double2(-0.2104679605f, 0.3977477059f), new Double2(0.3348364681f, -0.3006402163f), new Double2(0.3430468811f, 0.2912367377f), new Double2(-0.2291836801f, -0.3872658529f), new Double2(0.2547707298f, -0.3709337882f), new Double2(0.4236174945f, -0.151816397f), new Double2(-0.15387742f, 0.4228731957f), new Double2(-0.4407449312f, 0.09079595574f), new Double2(-0.06805276192f, -0.444824484f), new Double2(0.4453517192f, -0.06451237284f), new Double2(0.2562464609f, -0.3699158705f), new Double2(0.3278198355f, -0.3082761026f), new Double2(-0.4122774207f, -0.1803533432f), new Double2(0.3354090914f, -0.3000012356f), new Double2(0.446632869f, -0.05494615882f), new Double2(-0.1608953296f, 0.4202531296f), new Double2(-0.09463954939f, 0.4399356268f), new Double2(-0.02637688324f, -0.4492262904f), new Double2(0.447102804f, -0.05098119915f), new Double2(-0.4365670908f, 0.1091291678f), new Double2(-0.3959858651f, 0.2137643437f), new Double2(-0.4240048207f, -0.1507312575f), new Double2(-0.3882794568f, 0.2274622243f), new Double2(-0.4283652566f, -0.1378521198f), new Double2(0.3303888091f, 0.305521251f), new Double2(0.3321434919f, -0.3036127481f), new Double2(-0.413021046f, -0.1786438231f), new Double2(0.08403060337f, -0.4420846725f), new Double2(-0.3822882919f, 0.2373934748f), new Double2(-0.3712395594f, -0.2543249683f), new Double2(0.4472363971f, -0.04979563372f), new Double2(-0.4466591209f, 0.05473234629f), new Double2(0.0486272539f, -0.4473649407f), new Double2(-0.4203101295f, -0.1607463688f), new Double2(0.2205360833f, 0.39225481f), new Double2(-0.3624900666f, 0.2666476169f), new Double2(-0.4036086833f, -0.1989975647f), new Double2(0.2152727807f, 0.3951678503f), new Double2(-0.4359392962f, -0.1116106179f), new Double2(0.4178354266f, 0.1670735057f), new Double2(0.2007630161f, 0.4027334247f), new Double2(-0.07278067175f, -0.4440754146f), new Double2(0.3644748615f, -0.2639281632f), new Double2(-0.4317451775f, 0.126870413f), new Double2(-0.297436456f, 0.3376855855f), new Double2(-0.2998672222f, 0.3355289094f), new Double2(-0.2673674124f, 0.3619594822f), new Double2(0.2808423357f, 0.3516071423f), new Double2(0.3498946567f, 0.2829730186f), new Double2(-0.2229685561f, 0.390877248f), new Double2(0.3305823267f, 0.3053118493f), new Double2(-0.2436681211f, -0.3783197679f), new Double2(-0.03402776529f, 0.4487116125f), new Double2(-0.319358823f, 0.3170330301f), new Double2(0.4454633477f, -0.06373700535f), new Double2(0.4483504221f, 0.03849544189f), new Double2(-0.4427358436f, -0.08052932871f), new Double2(0.05452298565f, 0.4466847255f), new Double2(-0.2812560807f, 0.3512762688f), new Double2(0.1266696921f, 0.4318041097f), new Double2(-0.3735981243f, 0.2508474468f), new Double2(0.2959708351f, -0.3389708908f), new Double2(-0.3714377181f, 0.254035473f), new Double2(-0.404467102f, -0.1972469604f), new Double2(0.1636165687f, -0.419201167f), new Double2(0.3289185495f, -0.3071035458f), new Double2(-0.2494824991f, -0.3745109914f), new Double2(0.03283133272f, 0.4488007393f), new Double2(-0.166306057f, -0.4181414777f), new Double2(-0.106833179f, 0.4371346153f), new Double2(0.06440260376f, -0.4453676062f), new Double2(-0.4483230967f, 0.03881238203f), new Double2(-0.421377757f, -0.1579265206f), new Double2(0.05097920662f, -0.4471030312f), new Double2(0.2050584153f, -0.4005634111f), new Double2(0.4178098529f, -0.167137449f), new Double2(-0.3565189504f, -0.2745801121f), new Double2(0.4478398129f, 0.04403977727f), new Double2(-0.3399999602f, -0.2947881053f), new Double2(0.3767121994f, 0.2461461331f), new Double2(-0.3138934434f, 0.3224451987f), new Double2(-0.1462001792f, -0.4255884251f), new Double2(0.3970290489f, -0.2118205239f), new Double2(0.4459149305f, -0.06049689889f), new Double2(-0.4104889426f, -0.1843877112f), new Double2(0.1475103971f, -0.4251360756f), new Double2(0.09258030352f, 0.4403735771f), new Double2(-0.1589664637f, -0.4209865359f), new Double2(0.2482445008f, 0.3753327428f), new Double2(0.4383624232f, -0.1016778537f), new Double2(0.06242802956f, 0.4456486745f), new Double2(0.2846591015f, -0.3485243118f), new Double2(-0.344202744f, -0.2898697484f), new Double2(0.1198188883f, -0.4337550392f), new Double2(-0.243590703f, 0.3783696201f), new Double2(0.2958191174f, -0.3391033025f), new Double2(-0.1164007991f, 0.4346847754f), new Double2(0.1274037151f, -0.4315881062f), new Double2(0.368047306f, 0.2589231171f), new Double2(0.2451436949f, 0.3773652989f), new Double2(-0.4314509715f, 0.12786735f), - }; - private static final Double3[] CELL_3D = {new Double3(0.1453787434f, -0.4149781685f, -0.0956981749f), new Double3(-0.01242829687f, -0.1457918398f, -0.4255470325f), new Double3(0.2877979582f, -0.02606483451f, -0.3449535616f), new Double3(-0.07732986802f, 0.2377094325f, 0.3741848704f), new Double3(0.1107205875f, -0.3552302079f, -0.2530858567f), new Double3(0.2755209141f, 0.2640521179f, -0.238463215f), new Double3(0.294168941f, 0.1526064594f, 0.3044271714f), new Double3(0.4000921098f, -0.2034056362f, 0.03244149937f), new Double3(-0.1697304074f, 0.3970864695f, -0.1265461359f), new Double3(-0.1483224484f, -0.3859694688f, 0.1775613147f), new Double3(0.2623596946f, -0.2354852944f, 0.2796677792f), new Double3(-0.2709003183f, 0.3505271138f, -0.07901746678f), new Double3(-0.03516550699f, 0.3885234328f, 0.2243054374f), new Double3(-0.1267712655f, 0.1920044036f, 0.3867342179f), new Double3(0.02952021915f, 0.4409685861f, 0.08470692262f), new Double3(-0.2806854217f, -0.266996757f, 0.2289725438f), new Double3(-0.171159547f, 0.2141185563f, 0.3568720405f), new Double3(0.2113227183f, 0.3902405947f, -0.07453178509f), new Double3(-0.1024352839f, 0.2128044156f, -0.3830421561f), new Double3(-0.3304249877f, -0.1566986703f, 0.2622305365f), new Double3(0.2091111325f, 0.3133278055f, -0.2461670583f), new Double3(0.344678154f, -0.1944240454f, -0.2142341261f), new Double3(0.1984478035f, -0.3214342325f, -0.2445373252f), new Double3(-0.2929008603f, 0.2262915116f, 0.2559320961f), new Double3(-0.1617332831f, 0.006314769776f, -0.4198838754f), new Double3(-0.3582060271f, -0.148303178f, -0.2284613961f), new Double3(-0.1852067326f, -0.3454119342f, -0.2211087107f), new Double3(0.3046301062f, 0.1026310383f, 0.314908508f), new Double3(-0.03816768434f, -0.2551766358f, -0.3686842991f), new Double3(-0.4084952196f, 0.1805950793f, 0.05492788837f), new Double3(-0.02687443361f, -0.2749741471f, 0.3551999201f), new Double3(-0.03801098351f, 0.3277859044f, 0.3059600725f), new Double3(0.2371120802f, 0.2900386767f, -0.2493099024f), new Double3(0.4447660503f, 0.03946930643f, 0.05590469027f), new Double3(0.01985147278f, -0.01503183293f, -0.4493105419f), new Double3(0.4274339143f, 0.03345994256f, -0.1366772882f), new Double3(-0.2072988631f, 0.2871414597f, -0.2776273824f), new Double3(-0.3791240978f, 0.1281177671f, 0.2057929936f), new Double3(-0.2098721267f, -0.1007087278f, -0.3851122467f), new Double3(0.01582798878f, 0.4263894424f, 0.1429738373f), new Double3(-0.1888129464f, -0.3160996813f, -0.2587096108f), new Double3(0.1612988974f, -0.1974805082f, -0.3707885038f), new Double3(-0.08974491322f, 0.229148752f, -0.3767448739f), new Double3(0.07041229526f, 0.4150230285f, -0.1590534329f), new Double3(-0.1082925611f, -0.1586061639f, 0.4069604477f), new Double3(0.2474100658f, -0.3309414609f, 0.1782302128f), new Double3(-0.1068836661f, -0.2701644537f, -0.3436379634f), new Double3(0.2396452163f, 0.06803600538f, -0.3747549496f), new Double3(-0.3063886072f, 0.2597428179f, 0.2028785103f), new Double3(0.1593342891f, -0.3114350249f, -0.2830561951f), new Double3(0.2709690528f, 0.1412648683f, -0.3303331794f), new Double3(-0.1519780427f, 0.3623355133f, 0.2193527988f), new Double3(0.1699773681f, 0.3456012883f, 0.2327390037f), new Double3(-0.1986155616f, 0.3836276443f, -0.1260225743f), new Double3(-0.1887482106f, -0.2050154888f, -0.353330953f), new Double3(0.2659103394f, 0.3015631259f, -0.2021172246f), new Double3(-0.08838976154f, -0.4288819642f, -0.1036702021f), new Double3(-0.04201869311f, 0.3099592485f, 0.3235115047f), new Double3(-0.3230334656f, 0.201549922f, -0.2398478873f), new Double3(0.2612720941f, 0.2759854499f, -0.2409749453f), new Double3(0.385713046f, 0.2193460345f, 0.07491837764f), new Double3(0.07654967953f, 0.3721732183f, 0.241095919f), new Double3(0.4317038818f, -0.02577753072f, 0.1243675091f), new Double3(-0.2890436293f, -0.3418179959f, -0.04598084447f), new Double3(-0.2201947582f, 0.383023377f, -0.08548310451f), new Double3(0.4161322773f, -0.1669634289f, -0.03817251927f), new Double3(0.2204718095f, 0.02654238946f, -0.391391981f), new Double3(-0.1040307469f, 0.3890079625f, -0.2008741118f), new Double3(-0.1432122615f, 0.371614387f, -0.2095065525f), new Double3(0.3978380468f, -0.06206669342f, 0.2009293758f), new Double3(-0.2599274663f, 0.2616724959f, -0.2578084893f), new Double3(0.4032618332f, -0.1124593585f, 0.1650235939f), new Double3(-0.08953470255f, -0.3048244735f, 0.3186935478f), new Double3(0.118937202f, -0.2875221847f, 0.325092195f), new Double3(0.02167047076f, -0.03284630549f, -0.4482761547f), new Double3(-0.3411343612f, 0.2500031105f, 0.1537068389f), new Double3(0.3162964612f, 0.3082064153f, -0.08640228117f), new Double3(0.2355138889f, -0.3439334267f, -0.1695376245f), new Double3(-0.02874541518f, -0.3955933019f, 0.2125550295f), new Double3(-0.2461455173f, 0.02020282325f, -0.3761704803f), new Double3(0.04208029445f, -0.4470439576f, 0.02968078139f), new Double3(0.2727458746f, 0.2288471896f, -0.2752065618f), new Double3(-0.1347522818f, -0.02720848277f, -0.4284874806f), new Double3(0.3829624424f, 0.1231931484f, -0.2016512234f), new Double3(-0.3547613644f, 0.1271702173f, 0.2459107769f), new Double3(0.2305790207f, 0.3063895591f, 0.2354968222f), new Double3(-0.08323845599f, -0.1922245118f, 0.3982726409f), new Double3(0.2993663085f, -0.2619918095f, -0.2103333191f), new Double3(-0.2154865723f, 0.2706747713f, 0.287751117f), new Double3(0.01683355354f, -0.2680655787f, -0.3610505186f), new Double3(0.05240429123f, 0.4335128183f, -0.1087217856f), new Double3(0.00940104872f, -0.4472890582f, 0.04841609928f), new Double3(0.3465688735f, 0.01141914583f, -0.2868093776f), new Double3(-0.3706867948f, -0.2551104378f, 0.003156692623f), new Double3(0.2741169781f, 0.2139972417f, -0.2855959784f), new Double3(0.06413433865f, 0.1708718512f, 0.4113266307f), new Double3(-0.388187972f, -0.03973280434f, -0.2241236325f), new Double3(0.06419469312f, -0.2803682491f, 0.3460819069f), new Double3(-0.1986120739f, -0.3391173584f, 0.2192091725f), new Double3(-0.203203009f, -0.3871641506f, 0.1063600375f), new Double3(-0.1389736354f, -0.2775901578f, -0.3257760473f), new Double3(-0.06555641638f, 0.342253257f, -0.2847192729f), new Double3(-0.2529246486f, -0.2904227915f, 0.2327739768f), new Double3(0.1444476522f, 0.1069184044f, 0.4125570634f), new Double3(-0.3643780054f, -0.2447099973f, -0.09922543227f), new Double3(0.4286142488f, -0.1358496089f, -0.01829506817f), new Double3(0.165872923f, -0.3136808464f, -0.2767498872f), new Double3(0.2219610524f, -0.3658139958f, 0.1393320198f), new Double3(0.04322940318f, -0.3832730794f, 0.2318037215f), new Double3(-0.08481269795f, -0.4404869674f, -0.03574965489f), new Double3(0.1822082075f, -0.3953259299f, 0.1140946023f), new Double3(-0.3269323334f, 0.3036542563f, 0.05838957105f), new Double3(-0.4080485344f, 0.04227858267f, -0.184956522f), new Double3(0.2676025294f, -0.01299671652f, 0.36155217f), new Double3(0.3024892441f, -0.1009990293f, -0.3174892964f), new Double3(0.1448494052f, 0.425921681f, -0.0104580805f), new Double3(0.4198402157f, 0.08062320474f, 0.1404780841f), new Double3(-0.3008872161f, -0.333040905f, -0.03241355801f), new Double3(0.3639310428f, -0.1291284382f, -0.2310412139f), new Double3(0.3295806598f, 0.0184175994f, -0.3058388149f), new Double3(0.2776259487f, -0.2974929052f, -0.1921504723f), new Double3(0.4149000507f, -0.144793182f, -0.09691688386f), new Double3(0.145016715f, -0.0398992945f, 0.4241205002f), new Double3(0.09299023471f, -0.299732164f, -0.3225111565f), new Double3(0.1028907093f, -0.361266869f, 0.247789732f), new Double3(0.2683057049f, -0.07076041213f, -0.3542668666f), new Double3(-0.4227307273f, -0.07933161816f, -0.1323073187f), new Double3(-0.1781224702f, 0.1806857196f, -0.3716517945f), new Double3(0.4390788626f, -0.02841848598f, -0.09435116353f), new Double3(0.2972583585f, 0.2382799621f, -0.2394997452f), new Double3(-0.1707002821f, 0.2215845691f, 0.3525077196f), new Double3(0.3806686614f, 0.1471852559f, -0.1895464869f), new Double3(-0.1751445661f, -0.274887877f, 0.3102596268f), new Double3(-0.2227237566f, -0.2316778837f, 0.3149912482f), new Double3(0.1369633021f, 0.1341343041f, -0.4071228836f), new Double3(-0.3529503428f, -0.2472893463f, -0.129514612f), new Double3(-0.2590744185f, -0.2985577559f, -0.2150435121f), new Double3(-0.3784019401f, 0.2199816631f, -0.1044989934f), new Double3(-0.05635805671f, 0.1485737441f, 0.4210102279f), new Double3(0.3251428613f, 0.09666046873f, -0.2957006485f), new Double3(-0.4190995804f, 0.1406751354f, -0.08405978803f), new Double3(-0.3253150961f, -0.3080335042f, -0.04225456877f), new Double3(0.2857945863f, -0.05796152095f, 0.3427271751f), new Double3(-0.2733604046f, 0.1973770973f, -0.2980207554f), new Double3(0.219003657f, 0.2410037886f, -0.3105713639f), new Double3(0.3182767252f, -0.271342949f, 0.1660509868f), new Double3(-0.03222023115f, -0.3331161506f, -0.300824678f), new Double3(-0.3087780231f, 0.1992794134f, -0.2596995338f), new Double3(-0.06487611647f, -0.4311322747f, 0.1114273361f), new Double3(0.3921171432f, -0.06294284106f, -0.2116183942f), new Double3(-0.1606404506f, -0.358928121f, -0.2187812825f), new Double3(-0.03767771199f, -0.2290351443f, 0.3855169162f), new Double3(0.1394866832f, -0.3602213994f, 0.2308332918f), new Double3(-0.4345093872f, 0.005751117145f, 0.1169124335f), new Double3(-0.1044637494f, 0.4168128432f, -0.1336202785f), new Double3(0.2658727501f, 0.2551943237f, 0.2582393035f), new Double3(0.2051461999f, 0.1975390727f, 0.3484154868f), new Double3(-0.266085566f, 0.23483312f, 0.2766800993f), new Double3(0.07849405464f, -0.3300346342f, -0.2956616708f), new Double3(-0.2160686338f, 0.05376451292f, -0.3910546287f), new Double3(-0.185779186f, 0.2148499206f, 0.3490352499f), new Double3(0.02492421743f, -0.3229954284f, -0.3123343347f), new Double3(-0.120167831f, 0.4017266681f, 0.1633259825f), new Double3(-0.02160084693f, -0.06885389554f, 0.4441762538f), new Double3(0.2597670064f, 0.3096300784f, 0.1978643903f), new Double3(-0.1611553854f, -0.09823036005f, 0.4085091653f), new Double3(-0.3278896792f, 0.1461670309f, 0.2713366126f), new Double3(0.2822734956f, 0.03754421121f, -0.3484423997f), new Double3(0.03169341113f, 0.347405252f, -0.2842624114f), new Double3(0.2202613604f, -0.3460788041f, -0.1849713341f), new Double3(0.2933396046f, 0.3031973659f, 0.1565989581f), new Double3(-0.3194922995f, 0.2453752201f, -0.200538455f), new Double3(-0.3441586045f, -0.1698856132f, -0.2349334659f), new Double3(0.2703645948f, -0.3574277231f, 0.04060059933f), new Double3(0.2298568861f, 0.3744156221f, 0.0973588921f), new Double3(0.09326603877f, -0.3170108894f, 0.3054595587f), new Double3(-0.1116165319f, -0.2985018719f, 0.3177080142f), new Double3(0.2172907365f, -0.3460005203f, -0.1885958001f), new Double3(0.1991339479f, 0.3820341668f, -0.1299829458f), new Double3(-0.0541918155f, -0.2103145071f, 0.39412061f), new Double3(0.08871336998f, 0.2012117383f, 0.3926114802f), new Double3(0.2787673278f, 0.3505404674f, 0.04370535101f), new Double3(-0.322166438f, 0.3067213525f, 0.06804996813f), new Double3(-0.4277366384f, 0.132066775f, 0.04582286686f), new Double3(0.240131882f, -0.1612516055f, 0.344723946f), new Double3(0.1448607981f, -0.2387819045f, 0.3528435224f), new Double3(-0.3837065682f, -0.2206398454f, 0.08116235683f), new Double3(-0.4382627882f, -0.09082753406f, -0.04664855374f), new Double3(-0.37728353f, 0.05445141085f, 0.2391488697f), new Double3(0.1259579313f, 0.348394558f, 0.2554522098f), new Double3(-0.1406285511f, -0.270877371f, -0.3306796947f), new Double3(-0.1580694418f, 0.4162931958f, -0.06491553533f), new Double3(0.2477612106f, -0.2927867412f, -0.2353514536f), new Double3(0.2916132853f, 0.3312535401f, 0.08793624968f), new Double3(0.07365265219f, -0.1666159848f, 0.411478311f), new Double3(-0.26126526f, -0.2422237692f, 0.2748965434f), new Double3(-0.3721862032f, 0.252790166f, 0.008634938242f), new Double3(-0.3691191571f, -0.255281188f, 0.03290232422f), new Double3(0.2278441737f, -0.3358364886f, 0.1944244981f), new Double3(0.363398169f, -0.2310190248f, 0.1306597909f), new Double3(-0.304231482f, -0.2698452035f, 0.1926830856f), new Double3(-0.3199312232f, 0.316332536f, -0.008816977938f), new Double3(0.2874852279f, 0.1642275508f, -0.304764754f), new Double3(-0.1451096801f, 0.3277541114f, -0.2720669462f), new Double3(0.3220090754f, 0.0511344108f, 0.3101538769f), new Double3(-0.1247400865f, -0.04333605335f, -0.4301882115f), new Double3(-0.2829555867f, -0.3056190617f, -0.1703910946f), new Double3(0.1069384374f, 0.3491024667f, -0.2630430352f), new Double3(-0.1420661144f, -0.3055376754f, -0.2982682484f), new Double3(-0.250548338f, 0.3156466809f, -0.2002316239f), new Double3(0.3265787872f, 0.1871229129f, 0.2466400438f), new Double3(0.07646097258f, -0.3026690852f, 0.324106687f), new Double3(0.3451771584f, 0.2757120714f, -0.0856480183f), new Double3(0.298137964f, 0.2852657134f, 0.179547284f), new Double3(0.2812250376f, 0.3466716415f, 0.05684409612f), new Double3(0.4390345476f, -0.09790429955f, -0.01278335452f), new Double3(0.2148373234f, 0.1850172527f, 0.3494474791f), new Double3(0.2595421179f, -0.07946825393f, 0.3589187731f), new Double3(0.3182823114f, -0.307355516f, -0.08203022006f), new Double3(-0.4089859285f, -0.04647718411f, 0.1818526372f), new Double3(-0.2826749061f, 0.07417482322f, 0.3421885344f), new Double3(0.3483864637f, 0.225442246f, -0.1740766085f), new Double3(-0.3226415069f, -0.1420585388f, -0.2796816575f), new Double3(0.4330734858f, -0.118868561f, -0.02859407492f), new Double3(-0.08717822568f, -0.3909896417f, -0.2050050172f), new Double3(-0.2149678299f, 0.3939973956f, -0.03247898316f), new Double3(-0.2687330705f, 0.322686276f, -0.1617284888f), new Double3(0.2105665099f, -0.1961317136f, -0.3459683451f), new Double3(0.4361845915f, -0.1105517485f, 0.004616608544f), new Double3(0.05333333359f, -0.313639498f, -0.3182543336f), new Double3(-0.05986216652f, 0.1361029153f, -0.4247264031f), new Double3(0.3664988455f, 0.2550543014f, -0.05590974511f), new Double3(-0.2341015558f, -0.182405731f, 0.3382670703f), new Double3(-0.04730947785f, -0.4222150243f, -0.1483114513f), new Double3(-0.2391566239f, -0.2577696514f, -0.2808182972f), new Double3(-0.1242081035f, 0.4256953395f, -0.07652336246f), new Double3(0.2614832715f, -0.3650179274f, 0.02980623099f), new Double3(-0.2728794681f, -0.3499628774f, 0.07458404908f), new Double3(0.007892900508f, -0.1672771315f, 0.4176793787f), new Double3(-0.01730330376f, 0.2978486637f, -0.3368779738f), new Double3(0.2054835762f, -0.3252600376f, -0.2334146693f), new Double3(-0.3231994983f, 0.1564282844f, -0.2712420987f), new Double3(-0.2669545963f, 0.2599343665f, -0.2523278991f), new Double3(-0.05554372779f, 0.3170813944f, -0.3144428146f), new Double3(-0.2083935713f, -0.310922837f, -0.2497981362f), new Double3(0.06989323478f, -0.3156141536f, 0.3130537363f), new Double3(0.3847566193f, -0.1605309138f, -0.1693876312f), new Double3(-0.3026215288f, -0.3001537679f, -0.1443188342f), new Double3(0.3450735512f, 0.08611519592f, 0.2756962409f), new Double3(0.1814473292f, -0.2788782453f, -0.3029914042f), new Double3(-0.03855010448f, 0.09795110726f, 0.4375151083f), new Double3(0.3533670318f, 0.2665752752f, 0.08105160988f), new Double3(-0.007945601311f, 0.140359426f, -0.4274764309f), new Double3(0.4063099273f, -0.1491768253f, -0.1231199324f), new Double3(-0.2016773589f, 0.008816271194f, -0.4021797064f), new Double3(-0.07527055435f, -0.425643481f, -0.1251477955f), - }; - // Hashing - private final static long X_PRIME = 1619; - private final static long Y_PRIME = 31337; - private final static long Z_PRIME = 6971; - private final static long W_PRIME = 1013; - private final static double F3 = 1.0 / 3.0; - private final static double G3 = 1.0 / 6.0; - private final static double G33 = G3 * 3 - 1; - private final static double F2 = 1.0 / 2.0; - private final static double G2 = 1.0 / 4.0; - private static final byte[] SIMPLEX_4D = {0, 1, 2, 3, 0, 1, 3, 2, 0, 0, 0, 0, 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 3, 1, 2, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 0, 1, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 1, 2, 3, 1, 0, 1, 0, 2, 3, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 1, 0, 0, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 2, 3, 0, 2, 1, 0, 0, 0, 0, 3, 1, 2, 0, 2, 1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 2, 0, 0, 0, 0, 3, 2, 0, 1, 3, 2, 1, 0 - }; - private final static double F4 = (2.23606797 - 1.0) / 4.0; - private final static double G4 = (5.0 - 2.23606797) / 20.0; - private final static double CUBIC_3D_BOUNDING = 1 / (1.5 * 1.5 * 1.5); - private final static double CUBIC_2D_BOUNDING = 1 / (1.5 * 1.5); - public Longerp m_longerp = Longerp.Linear; - private long m_seed = 1337; - private double m_frequency = 0.01; - private NoiseType m_noiseType = NoiseType.Simplex; - private long m_octaves = 3; - private double m_lacunarity = 2.0; - private double m_gain = 0.5; - private FractalType m_fractalType = FractalType.FBM; - private double m_fractalBounding; - private CellularDistanceFunction m_cellularDistanceFunction = CellularDistanceFunction.Euclidean; - private CellularReturnType m_cellularReturnType = CellularReturnType.CellValue; - private FastNoiseDouble m_cellularNoiseLookup = null; - private double m_gradientPerturbAmp = 1.0 / 0.45; - - public FastNoiseDouble() { - this(1337); - } - - public FastNoiseDouble(long seed) { - m_seed = seed; - calculateFractalBounding(); - } - - // Returns a 0 double/double - public static double getDecimalType() { - return 0; - } - - private static long fastFloor(double f) { - return (f >= 0 ? (long) f : (long) f - 1); - } - - private static long fastRound(double f) { - return (f >= 0) ? (long) (f + 0.5) : (long) (f - 0.5); - } - - private static double lerp(double a, double b, double t) { - return a + t * (b - a); - } - - private static double longerpHermiteFunc(double t) { - return t * t * (3 - 2 * t); - } - - private static double longerpQulongicFunc(double t) { - return t * t * t * (t * (t * 6 - 15) + 10); - } - - private static double cubicLerp(double a, double b, double c, double d, double t) { - double p = (d - c) - (a - b); - return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; - } - - private static long hash2D(long seed, long x, long y) { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - private static long hash3D(long seed, long x, long y, long z) { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - public static long hash4D(long seed, long x, long y, long z, long w) { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - hash ^= W_PRIME * w; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - private static double valCoord2D(long seed, long x, long y) { - long n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - - return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); - } - - private static double valCoord3D(long seed, long x, long y, long z) { - long n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - n ^= Z_PRIME * z; - - return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); - } - - private static double valCoord4D(long seed, long x, long y, long z, long w) { - long n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - n ^= Z_PRIME * z; - n ^= W_PRIME * w; - - return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); - } - - private static double GradCoord2D(long seed, long x, long y, double xd, double yd) { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - Double2 g = GRAD_2D[(int) hash & 7]; - - return xd * g.x + yd * g.y; - } - - private static double GradCoord3D(long seed, long x, long y, long z, double xd, double yd, double zd) { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - Double3 g = GRAD_3D[(int) (hash & 15)]; - - return xd * g.x + yd * g.y + zd * g.z; - } - - private static double GradCoord4D(long seed, long x, long y, long z, long w, double xd, double yd, double zd, double wd) { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - hash ^= W_PRIME * w; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - hash &= 31; - double a = yd, b = zd, c = wd; // X,Y,Z - switch((int) hash >> 3) { // OR, DEPENDING ON HIGH ORDER 2 BITS: - case 1 -> { - a = wd; - b = xd; - c = yd; - } // W,X,Y - case 2 -> { - a = zd; - b = wd; - c = xd; - } // Z,W,X - case 3 -> { - a = yd; - b = zd; - c = wd; - } // Y,Z,W - } - return ((hash & 4) == 0 ? -a : a) + ((hash & 2) == 0 ? -b : b) + ((hash & 1) == 0 ? -c : c); - } - - // Returns the seed used by this object - public long getSeed() { - return m_seed; - } - - // Sets seed used for all noise types - // Default: 1337 - public void setSeed(long seed) { - m_seed = seed; - } - - // Sets frequency for all noise types - // Default: 0.01 - public void setFrequency(double frequency) { - m_frequency = frequency; - } - - // Changes the longerpolation method used to smooth between noise values - // Possible longerpolation methods (lowest to highest quality) : - // - Linear - // - Hermite - // - Qulongic - // Used in Value, Gradient Noise and Position Perturbing - // Default: Qulongic - public void setLongerp(Longerp longerp) { - m_longerp = longerp; - } - - // Sets noise return type of GetNoise(...) - // Default: Simplex - public void setNoiseType(NoiseType noiseType) { - m_noiseType = noiseType; - } - - // Sets octave count for all fractal noise types - // Default: 3 - public void setFractalOctaves(long octaves) { - m_octaves = octaves; - calculateFractalBounding(); - } - - // Sets octave lacunarity for all fractal noise types - // Default: 2.0 - public void setFractalLacunarity(double lacunarity) { - m_lacunarity = lacunarity; - } - - // Sets octave gain for all fractal noise types - // Default: 0.5 - public void setFractalGain(double gain) { - m_gain = gain; - calculateFractalBounding(); - } - - // Sets method for combining octaves in all fractal noise types - // Default: FBM - public void setFractalType(FractalType fractalType) { - m_fractalType = fractalType; - } - - // Sets return type from cellular noise calculations - // Note: NoiseLookup requires another FastNoise object be set with - // SetCellularNoiseLookup() to function - // Default: CellValue - public void setCellularDistanceFunction(CellularDistanceFunction cellularDistanceFunction) { - m_cellularDistanceFunction = cellularDistanceFunction; - } - - // Sets distance function used in cellular noise calculations - // Default: Euclidean - public void setCellularReturnType(CellularReturnType cellularReturnType) { - m_cellularReturnType = cellularReturnType; - } - - // Noise used to calculate a cell value if cellular return type is NoiseLookup - // The lookup value is acquired through GetNoise() so ensure you SetNoiseType() - // on the noise lookup, value, gradient or simplex is recommended - public void setCellularNoiseLookup(FastNoiseDouble noise) { - m_cellularNoiseLookup = noise; - } - - // Sets the maximum perturb distance from original location when using - // GradientPerturb{Fractal}(...) - // Default: 1.0 - public void setGradientPerturbAmp(double gradientPerturbAmp) { - m_gradientPerturbAmp = gradientPerturbAmp / 0.45; - } - - // White Noise - - private void calculateFractalBounding() { - double amp = m_gain; - double ampFractal = 1; - for(long i = 1; i < m_octaves; i++) { - ampFractal += amp; - amp *= m_gain; - } - m_fractalBounding = 1 / ampFractal; - } - - public double GetNoise(double x, double y, double z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_noiseType) { - case Value: - return SingleValue(m_seed, x, y, z); - case ValueFractal: - return switch(m_fractalType) { - case FBM -> SingleValueFractalFBM(x, y, z); - case Billow -> SingleValueFractalBillow(x, y, z); - case RigidMulti -> SingleValueFractalRigidMulti(x, y, z); - }; - case Perlin: - return SinglePerlin(m_seed, x, y, z); - case PerlinFractal: - return switch(m_fractalType) { - case FBM -> SinglePerlinFractalFBM(x, y, z); - case Billow -> SinglePerlinFractalBillow(x, y, z); - case RigidMulti -> SinglePerlinFractalRigidMulti(x, y, z); - }; - case Simplex: - return SingleSimplex(m_seed, x, y, z); - case SimplexFractal: - return switch(m_fractalType) { - case FBM -> SingleSimplexFractalFBM(x, y, z); - case Billow -> SingleSimplexFractalBillow(x, y, z); - case RigidMulti -> SingleSimplexFractalRigidMulti(x, y, z); - }; - case Cellular: - return switch(m_cellularReturnType) { - case CellValue, NoiseLookup, Distance -> SingleCellular(x, y, z); - default -> SingleCellular2Edge(x, y, z); - }; - case WhiteNoise: - return GetWhiteNoise(x, y, z); - case Cubic: - return SingleCubic(m_seed, x, y, z); - case CubicFractal: - return switch(m_fractalType) { - case FBM -> SingleCubicFractalFBM(x, y, z); - case Billow -> SingleCubicFractalBillow(x, y, z); - case RigidMulti -> SingleCubicFractalRigidMulti(x, y, z); - }; - default: - return 0; - } - } - - public double GetNoise(double x, double y) { - x *= m_frequency; - y *= m_frequency; - - switch(m_noiseType) { - case Value: - return SingleValue(m_seed, x, y); - case ValueFractal: - return switch(m_fractalType) { - case FBM -> SingleValueFractalFBM(x, y); - case Billow -> SingleValueFractalBillow(x, y); - case RigidMulti -> SingleValueFractalRigidMulti(x, y); - }; - case Perlin: - return SinglePerlin(m_seed, x, y); - case PerlinFractal: - return switch(m_fractalType) { - case FBM -> SinglePerlinFractalFBM(x, y); - case Billow -> SinglePerlinFractalBillow(x, y); - case RigidMulti -> SinglePerlinFractalRigidMulti(x, y); - }; - case Simplex: - return SingleSimplex(m_seed, x, y); - case SimplexFractal: - return switch(m_fractalType) { - case FBM -> SingleSimplexFractalFBM(x, y); - case Billow -> SingleSimplexFractalBillow(x, y); - case RigidMulti -> SingleSimplexFractalRigidMulti(x, y); - }; - case Cellular: - return switch(m_cellularReturnType) { - case CellValue, NoiseLookup, Distance -> SingleCellular(x, y); - default -> SingleCellular2Edge(x, y); - }; - case WhiteNoise: - return GetWhiteNoise(x, y); - case Cubic: - return SingleCubic(m_seed, x, y); - case CubicFractal: - return switch(m_fractalType) { - case FBM -> SingleCubicFractalFBM(x, y); - case Billow -> SingleCubicFractalBillow(x, y); - case RigidMulti -> SingleCubicFractalRigidMulti(x, y); - }; - default: - return 0; - } - } - - private long DoubleCast2Long(double f) { - long i = Double.doubleToRawLongBits(f); - - return i ^ (i >> 16); - } - - public double GetWhiteNoise(double x, double y, double z, double w) { - long xi = DoubleCast2Long(x); - long yi = DoubleCast2Long(y); - long zi = DoubleCast2Long(z); - long wi = DoubleCast2Long(w); - - return valCoord4D(m_seed, xi, yi, zi, wi); - } - - public double GetWhiteNoise(double x, double y, double z) { - long xi = DoubleCast2Long(x); - long yi = DoubleCast2Long(y); - long zi = DoubleCast2Long(z); - - return valCoord3D(m_seed, xi, yi, zi); - } - - public double GetWhiteNoise(double x, double y) { - long xi = DoubleCast2Long(x); - long yi = DoubleCast2Long(y); - - return valCoord2D(m_seed, xi, yi); - } - - public double GetWhiteNoiseLong(long x, long y, long z, long w) { - return valCoord4D(m_seed, x, y, z, w); - } - - public double GetWhiteNoiseLong(long x, long y, long z) { - return valCoord3D(m_seed, x, y, z); - } - - public double GetWhiteNoiseLong(long x, long y) { - return valCoord2D(m_seed, x, y); - } - - // Value Noise - public double GetValueFractal(double x, double y, double z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - return switch(m_fractalType) { - case FBM -> SingleValueFractalFBM(x, y, z); - case Billow -> SingleValueFractalBillow(x, y, z); - case RigidMulti -> SingleValueFractalRigidMulti(x, y, z); - }; - } - - private double SingleValueFractalFBM(double x, double y, double z) { - long seed = m_seed; - double sum = SingleValue(seed, x, y, z); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleValue(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleValueFractalBillow(double x, double y, double z) { - long seed = m_seed; - double sum = Math.abs(SingleValue(seed, x, y, z)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleValue(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleValueFractalRigidMulti(double x, double y, double z) { - long seed = m_seed; - double sum = 1 - Math.abs(SingleValue(seed, x, y, z)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleValue(++seed, x, y, z))) * amp; - } - - return sum; - } - - public double GetValue(double x, double y, double z) { - return SingleValue(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private double SingleValue(long seed, double x, double y, double z) { - long x0 = fastFloor(x); - long y0 = fastFloor(y); - long z0 = fastFloor(z); - long x1 = x0 + 1; - long y1 = y0 + 1; - long z1 = z0 + 1; - - double xs = 0, ys = 0, zs = 0; - switch(m_longerp) { - case Linear -> { - xs = x - x0; - ys = y - y0; - zs = z - z0; - } - case Hermite -> { - xs = longerpHermiteFunc(x - x0); - ys = longerpHermiteFunc(y - y0); - zs = longerpHermiteFunc(z - z0); - } - case Qulongic -> { - xs = longerpQulongicFunc(x - x0); - ys = longerpQulongicFunc(y - y0); - zs = longerpQulongicFunc(z - z0); - } - } - - double xf00 = lerp(valCoord3D(seed, x0, y0, z0), valCoord3D(seed, x1, y0, z0), xs); - double xf10 = lerp(valCoord3D(seed, x0, y1, z0), valCoord3D(seed, x1, y1, z0), xs); - double xf01 = lerp(valCoord3D(seed, x0, y0, z1), valCoord3D(seed, x1, y0, z1), xs); - double xf11 = lerp(valCoord3D(seed, x0, y1, z1), valCoord3D(seed, x1, y1, z1), xs); - - double yf0 = lerp(xf00, xf10, ys); - double yf1 = lerp(xf01, xf11, ys); - - return lerp(yf0, yf1, zs); - } - - public double GetValueFractal(double x, double y) { - x *= m_frequency; - y *= m_frequency; - - return switch(m_fractalType) { - case FBM -> SingleValueFractalFBM(x, y); - case Billow -> SingleValueFractalBillow(x, y); - case RigidMulti -> SingleValueFractalRigidMulti(x, y); - }; - } - - private double SingleValueFractalFBM(double x, double y) { - long seed = m_seed; - double sum = SingleValue(seed, x, y); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleValue(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleValueFractalBillow(double x, double y) { - long seed = m_seed; - double sum = Math.abs(SingleValue(seed, x, y)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - amp *= m_gain; - sum += (Math.abs(SingleValue(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleValueFractalRigidMulti(double x, double y) { - long seed = m_seed; - double sum = 1 - Math.abs(SingleValue(seed, x, y)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleValue(++seed, x, y))) * amp; - } - - return sum; - } - - public double GetValue(double x, double y) { - return SingleValue(m_seed, x * m_frequency, y * m_frequency); - } - - private double SingleValue(long seed, double x, double y) { - long x0 = fastFloor(x); - long y0 = fastFloor(y); - long x1 = x0 + 1; - long y1 = y0 + 1; - - double xs = 0, ys = 0; - switch(m_longerp) { - case Linear -> { - xs = x - x0; - ys = y - y0; - } - case Hermite -> { - xs = longerpHermiteFunc(x - x0); - ys = longerpHermiteFunc(y - y0); - } - case Qulongic -> { - xs = longerpQulongicFunc(x - x0); - ys = longerpQulongicFunc(y - y0); - } - } - - double xf0 = lerp(valCoord2D(seed, x0, y0), valCoord2D(seed, x1, y0), xs); - double xf1 = lerp(valCoord2D(seed, x0, y1), valCoord2D(seed, x1, y1), xs); - - return lerp(xf0, xf1, ys); - } - - // Gradient Noise - public double GetPerlinFractal(double x, double y, double z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - return switch(m_fractalType) { - case FBM -> SinglePerlinFractalFBM(x, y, z); - case Billow -> SinglePerlinFractalBillow(x, y, z); - case RigidMulti -> SinglePerlinFractalRigidMulti(x, y, z); - }; - } - - private double SinglePerlinFractalFBM(double x, double y, double z) { - long seed = m_seed; - double sum = SinglePerlin(seed, x, y, z); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SinglePerlin(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private double SinglePerlinFractalBillow(double x, double y, double z) { - long seed = m_seed; - double sum = Math.abs(SinglePerlin(seed, x, y, z)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SinglePerlin(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SinglePerlinFractalRigidMulti(double x, double y, double z) { - long seed = m_seed; - double sum = 1 - Math.abs(SinglePerlin(seed, x, y, z)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SinglePerlin(++seed, x, y, z))) * amp; - } - - return sum; - } - - public double GetPerlin(double x, double y, double z) { - return SinglePerlin(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private double SinglePerlin(long seed, double x, double y, double z) { - long x0 = fastFloor(x); - long y0 = fastFloor(y); - long z0 = fastFloor(z); - long x1 = x0 + 1; - long y1 = y0 + 1; - long z1 = z0 + 1; - - double xs = 0, ys = 0, zs = 0; - switch(m_longerp) { - case Linear -> { - xs = x - x0; - ys = y - y0; - zs = z - z0; - } - case Hermite -> { - xs = longerpHermiteFunc(x - x0); - ys = longerpHermiteFunc(y - y0); - zs = longerpHermiteFunc(z - z0); - } - case Qulongic -> { - xs = longerpQulongicFunc(x - x0); - ys = longerpQulongicFunc(y - y0); - zs = longerpQulongicFunc(z - z0); - } - } - - double xd0 = x - x0; - double yd0 = y - y0; - double zd0 = z - z0; - double xd1 = xd0 - 1; - double yd1 = yd0 - 1; - double zd1 = zd0 - 1; - - double xf00 = lerp(GradCoord3D(seed, x0, y0, z0, xd0, yd0, zd0), GradCoord3D(seed, x1, y0, z0, xd1, yd0, zd0), xs); - double xf10 = lerp(GradCoord3D(seed, x0, y1, z0, xd0, yd1, zd0), GradCoord3D(seed, x1, y1, z0, xd1, yd1, zd0), xs); - double xf01 = lerp(GradCoord3D(seed, x0, y0, z1, xd0, yd0, zd1), GradCoord3D(seed, x1, y0, z1, xd1, yd0, zd1), xs); - double xf11 = lerp(GradCoord3D(seed, x0, y1, z1, xd0, yd1, zd1), GradCoord3D(seed, x1, y1, z1, xd1, yd1, zd1), xs); - - double yf0 = lerp(xf00, xf10, ys); - double yf1 = lerp(xf01, xf11, ys); - - return lerp(yf0, yf1, zs); - } - - public double GetPerlinFractal(double x, double y) { - x *= m_frequency; - y *= m_frequency; - - return switch(m_fractalType) { - case FBM -> SinglePerlinFractalFBM(x, y); - case Billow -> SinglePerlinFractalBillow(x, y); - case RigidMulti -> SinglePerlinFractalRigidMulti(x, y); - }; - } - - private double SinglePerlinFractalFBM(double x, double y) { - long seed = m_seed; - double sum = SinglePerlin(seed, x, y); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SinglePerlin(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private double SinglePerlinFractalBillow(double x, double y) { - long seed = m_seed; - double sum = Math.abs(SinglePerlin(seed, x, y)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SinglePerlin(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SinglePerlinFractalRigidMulti(double x, double y) { - long seed = m_seed; - double sum = 1 - Math.abs(SinglePerlin(seed, x, y)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SinglePerlin(++seed, x, y))) * amp; - } - - return sum; - } - - public double GetPerlin(double x, double y) { - return SinglePerlin(m_seed, x * m_frequency, y * m_frequency); - } - - private double SinglePerlin(long seed, double x, double y) { - long x0 = fastFloor(x); - long y0 = fastFloor(y); - long x1 = x0 + 1; - long y1 = y0 + 1; - - double xs = 0, ys = 0; - switch(m_longerp) { - case Linear -> { - xs = x - x0; - ys = y - y0; - } - case Hermite -> { - xs = longerpHermiteFunc(x - x0); - ys = longerpHermiteFunc(y - y0); - } - case Qulongic -> { - xs = longerpQulongicFunc(x - x0); - ys = longerpQulongicFunc(y - y0); - } - } - - double xd0 = x - x0; - double yd0 = y - y0; - double xd1 = xd0 - 1; - double yd1 = yd0 - 1; - - double xf0 = lerp(GradCoord2D(seed, x0, y0, xd0, yd0), GradCoord2D(seed, x1, y0, xd1, yd0), xs); - double xf1 = lerp(GradCoord2D(seed, x0, y1, xd0, yd1), GradCoord2D(seed, x1, y1, xd1, yd1), xs); - - return lerp(xf0, xf1, ys); - } - - // Simplex Noise - public double GetSimplexFractal(double x, double y, double z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - return switch(m_fractalType) { - case FBM -> SingleSimplexFractalFBM(x, y, z); - case Billow -> SingleSimplexFractalBillow(x, y, z); - case RigidMulti -> SingleSimplexFractalRigidMulti(x, y, z); - }; - } - - private double SingleSimplexFractalFBM(double x, double y, double z) { - long seed = m_seed; - double sum = SingleSimplex(seed, x, y, z); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleSimplex(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleSimplexFractalBillow(double x, double y, double z) { - long seed = m_seed; - double sum = Math.abs(SingleSimplex(seed, x, y, z)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleSimplex(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleSimplexFractalRigidMulti(double x, double y, double z) { - long seed = m_seed; - double sum = 1 - Math.abs(SingleSimplex(seed, x, y, z)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleSimplex(++seed, x, y, z))) * amp; - } - - return sum; - } - - public double GetSimplex(double x, double y, double z) { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private double SingleSimplex(long seed, double x, double y, double z) { - double t = (x + y + z) * F3; - long i = fastFloor(x + t); - long j = fastFloor(y + t); - long k = fastFloor(z + t); - - t = (i + j + k) * G3; - double x0 = x - (i - t); - double y0 = y - (j - t); - double z0 = z - (k - t); - - long i1, j1, k1; - long i2, j2, k2; - - if(x0 >= y0) { - if(y0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } else if(x0 >= z0) { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 0; - k2 = 1; - } else // x0 < z0 - { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 1; - j2 = 0; - k2 = 1; - } - } else // x0 < y0 - { - if(y0 < z0) { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 0; - j2 = 1; - k2 = 1; - } else if(x0 < z0) { - i1 = 0; - j1 = 1; - k1 = 0; - i2 = 0; - j2 = 1; - k2 = 1; - } else // x0 >= z0 - { - i1 = 0; - j1 = 1; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } - } - - double x1 = x0 - i1 + G3; - double y1 = y0 - j1 + G3; - double z1 = z0 - k1 + G3; - double x2 = x0 - i2 + F3; - double y2 = y0 - j2 + F3; - double z2 = z0 - k2 + F3; - double x3 = x0 + G33; - double y3 = y0 + G33; - double z3 = z0 + G33; - - double n0, n1, n2, n3; - - t = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; - if(t < 0) - n0 = 0; - else { - t *= t; - n0 = t * t * GradCoord3D(seed, i, j, k, x0, y0, z0); - } - - t = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; - if(t < 0) - n1 = 0; - else { - t *= t; - n1 = t * t * GradCoord3D(seed, i + i1, j + j1, k + k1, x1, y1, z1); - } - - t = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; - if(t < 0) - n2 = 0; - else { - t *= t; - n2 = t * t * GradCoord3D(seed, i + i2, j + j2, k + k2, x2, y2, z2); - } - - t = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; - if(t < 0) - n3 = 0; - else { - t *= t; - n3 = t * t * GradCoord3D(seed, i + 1, j + 1, k + 1, x3, y3, z3); - } - - return 32 * (n0 + n1 + n2 + n3); - } - - public double GetSimplexFractal(double x, double y) { - x *= m_frequency; - y *= m_frequency; - - return switch(m_fractalType) { - case FBM -> SingleSimplexFractalFBM(x, y); - case Billow -> SingleSimplexFractalBillow(x, y); - case RigidMulti -> SingleSimplexFractalRigidMulti(x, y); - }; - } - - private double SingleSimplexFractalFBM(double x, double y) { - long seed = m_seed; - double sum = SingleSimplex(seed, x, y); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleSimplex(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleSimplexFractalBillow(double x, double y) { - long seed = m_seed; - double sum = Math.abs(SingleSimplex(seed, x, y)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleSimplex(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleSimplexFractalRigidMulti(double x, double y) { - long seed = m_seed; - double sum = 1 - Math.abs(SingleSimplex(seed, x, y)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleSimplex(++seed, x, y))) * amp; - } - - return sum; - } - - public double GetSimplex(double x, double y) { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency); - } - - private double SingleSimplex(long seed, double x, double y) { - double t = (x + y) * F2; - long i = fastFloor(x + t); - long j = fastFloor(y + t); - - t = (i + j) * G2; - double X0 = i - t; - double Y0 = j - t; - - double x0 = x - X0; - double y0 = y - Y0; - - long i1, j1; - if(x0 > y0) { - i1 = 1; - j1 = 0; - } else { - i1 = 0; - j1 = 1; - } - - double x1 = x0 - i1 + G2; - double y1 = y0 - j1 + G2; - double x2 = x0 - 1 + F2; - double y2 = y0 - 1 + F2; - - double n0, n1, n2; - - t = 0.5 - x0 * x0 - y0 * y0; - if(t < 0) - n0 = 0; - else { - t *= t; - n0 = t * t * GradCoord2D(seed, i, j, x0, y0); - } - - t = 0.5 - x1 * x1 - y1 * y1; - if(t < 0) - n1 = 0; - else { - t *= t; - n1 = t * t * GradCoord2D(seed, i + i1, j + j1, x1, y1); - } - - t = 0.5 - x2 * x2 - y2 * y2; - if(t < 0) - n2 = 0; - else { - t *= t; - n2 = t * t * GradCoord2D(seed, i + 1, j + 1, x2, y2); - } - - return 50 * (n0 + n1 + n2); - } - - public double GetSimplex(double x, double y, double z, double w) { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency, w * m_frequency); - } - - private double SingleSimplex(long seed, double x, double y, double z, double w) { - double n0, n1, n2, n3, n4; - double t = (x + y + z + w) * F4; - long i = fastFloor(x + t); - long j = fastFloor(y + t); - long k = fastFloor(z + t); - long l = fastFloor(w + t); - t = (i + j + k + l) * G4; - double X0 = i - t; - double Y0 = j - t; - double Z0 = k - t; - double W0 = l - t; - double x0 = x - X0; - double y0 = y - Y0; - double z0 = z - Z0; - double w0 = w - W0; - - int c = (x0 > y0) ? 32 : 0; - c += (x0 > z0) ? 16 : 0; - c += (y0 > z0) ? 8 : 0; - c += (x0 > w0) ? 4 : 0; - c += (y0 > w0) ? 2 : 0; - c += (z0 > w0) ? 1 : 0; - c <<= 2; - - long i1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - long i2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - long i3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - long j1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - long j2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - long j3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - long k1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - long k2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - long k3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - long l1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - long l2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - long l3 = SIMPLEX_4D[c] >= 1 ? 1 : 0; - - double x1 = x0 - i1 + G4; - double y1 = y0 - j1 + G4; - double z1 = z0 - k1 + G4; - double w1 = w0 - l1 + G4; - double x2 = x0 - i2 + 2 * G4; - double y2 = y0 - j2 + 2 * G4; - double z2 = z0 - k2 + 2 * G4; - double w2 = w0 - l2 + 2 * G4; - double x3 = x0 - i3 + 3 * G4; - double y3 = y0 - j3 + 3 * G4; - double z3 = z0 - k3 + 3 * G4; - double w3 = w0 - l3 + 3 * G4; - double x4 = x0 - 1 + 4 * G4; - double y4 = y0 - 1 + 4 * G4; - double z4 = z0 - 1 + 4 * G4; - double w4 = w0 - 1 + 4 * G4; - - t = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; - if(t < 0) - n0 = 0; - else { - t *= t; - n0 = t * t * GradCoord4D(seed, i, j, k, l, x0, y0, z0, w0); - } - t = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; - if(t < 0) - n1 = 0; - else { - t *= t; - n1 = t * t * GradCoord4D(seed, i + i1, j + j1, k + k1, l + l1, x1, y1, z1, w1); - } - t = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; - if(t < 0) - n2 = 0; - else { - t *= t; - n2 = t * t * GradCoord4D(seed, i + i2, j + j2, k + k2, l + l2, x2, y2, z2, w2); - } - t = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; - if(t < 0) - n3 = 0; - else { - t *= t; - n3 = t * t * GradCoord4D(seed, i + i3, j + j3, k + k3, l + l3, x3, y3, z3, w3); - } - t = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; - if(t < 0) - n4 = 0; - else { - t *= t; - n4 = t * t * GradCoord4D(seed, i + 1, j + 1, k + 1, l + 1, x4, y4, z4, w4); - } - - return 27 * (n0 + n1 + n2 + n3 + n4); - } - - // Cubic Noise - public double GetCubicFractal(double x, double y, double z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - return switch(m_fractalType) { - case FBM -> SingleCubicFractalFBM(x, y, z); - case Billow -> SingleCubicFractalBillow(x, y, z); - case RigidMulti -> SingleCubicFractalRigidMulti(x, y, z); - }; - } - - private double SingleCubicFractalFBM(double x, double y, double z) { - long seed = m_seed; - double sum = SingleCubic(seed, x, y, z); - double amp = 1; - long i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleCubic(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleCubicFractalBillow(double x, double y, double z) { - long seed = m_seed; - double sum = Math.abs(SingleCubic(seed, x, y, z)) * 2 - 1; - double amp = 1; - long i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleCubic(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleCubicFractalRigidMulti(double x, double y, double z) { - long seed = m_seed; - double sum = 1 - Math.abs(SingleCubic(seed, x, y, z)); - double amp = 1; - long i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleCubic(++seed, x, y, z))) * amp; - } - - return sum; - } - - public double GetCubic(double x, double y, double z) { - return SingleCubic(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private double SingleCubic(long seed, double x, double y, double z) { - long x1 = fastFloor(x); - long y1 = fastFloor(y); - long z1 = fastFloor(z); - - long x0 = x1 - 1; - long y0 = y1 - 1; - long z0 = z1 - 1; - long x2 = x1 + 1; - long y2 = y1 + 1; - long z2 = z1 + 1; - long x3 = x1 + 2; - long y3 = y1 + 2; - long z3 = z1 + 2; - - double xs = x - (double) x1; - double ys = y - (double) y1; - double zs = z - (double) z1; - - return cubicLerp(cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z0), valCoord3D(seed, x1, y0, z0), valCoord3D(seed, x2, y0, z0), valCoord3D(seed, x3, y0, z0), xs), cubicLerp(valCoord3D(seed, x0, y1, z0), valCoord3D(seed, x1, y1, z0), valCoord3D(seed, x2, y1, z0), valCoord3D(seed, x3, y1, z0), xs), cubicLerp(valCoord3D(seed, x0, y2, z0), valCoord3D(seed, x1, y2, z0), valCoord3D(seed, x2, y2, z0), valCoord3D(seed, x3, y2, z0), xs), cubicLerp(valCoord3D(seed, x0, y3, z0), valCoord3D(seed, x1, y3, z0), valCoord3D(seed, x2, y3, z0), valCoord3D(seed, x3, y3, z0), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z1), valCoord3D(seed, x1, y0, z1), valCoord3D(seed, x2, y0, z1), valCoord3D(seed, x3, y0, z1), xs), cubicLerp(valCoord3D(seed, x0, y1, z1), valCoord3D(seed, x1, y1, z1), valCoord3D(seed, x2, y1, z1), valCoord3D(seed, x3, y1, z1), xs), cubicLerp(valCoord3D(seed, x0, y2, z1), valCoord3D(seed, x1, y2, z1), valCoord3D(seed, x2, y2, z1), valCoord3D(seed, x3, y2, z1), xs), cubicLerp(valCoord3D(seed, x0, y3, z1), valCoord3D(seed, x1, y3, z1), valCoord3D(seed, x2, y3, z1), valCoord3D(seed, x3, y3, z1), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z2), valCoord3D(seed, x1, y0, z2), valCoord3D(seed, x2, y0, z2), valCoord3D(seed, x3, y0, z2), xs), cubicLerp(valCoord3D(seed, x0, y1, z2), valCoord3D(seed, x1, y1, z2), valCoord3D(seed, x2, y1, z2), valCoord3D(seed, x3, y1, z2), xs), cubicLerp(valCoord3D(seed, x0, y2, z2), valCoord3D(seed, x1, y2, z2), valCoord3D(seed, x2, y2, z2), valCoord3D(seed, x3, y2, z2), xs), cubicLerp(valCoord3D(seed, x0, y3, z2), valCoord3D(seed, x1, y3, z2), valCoord3D(seed, x2, y3, z2), valCoord3D(seed, x3, y3, z2), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z3), valCoord3D(seed, x1, y0, z3), valCoord3D(seed, x2, y0, z3), valCoord3D(seed, x3, y0, z3), xs), cubicLerp(valCoord3D(seed, x0, y1, z3), valCoord3D(seed, x1, y1, z3), valCoord3D(seed, x2, y1, z3), valCoord3D(seed, x3, y1, z3), xs), cubicLerp(valCoord3D(seed, x0, y2, z3), valCoord3D(seed, x1, y2, z3), valCoord3D(seed, x2, y2, z3), valCoord3D(seed, x3, y2, z3), xs), cubicLerp(valCoord3D(seed, x0, y3, z3), valCoord3D(seed, x1, y3, z3), valCoord3D(seed, x2, y3, z3), valCoord3D(seed, x3, y3, z3), xs), ys), zs) * CUBIC_3D_BOUNDING; - } - - public double GetCubicFractal(double x, double y) { - x *= m_frequency; - y *= m_frequency; - - return switch(m_fractalType) { - case FBM -> SingleCubicFractalFBM(x, y); - case Billow -> SingleCubicFractalBillow(x, y); - case RigidMulti -> SingleCubicFractalRigidMulti(x, y); - }; - } - - private double SingleCubicFractalFBM(double x, double y) { - long seed = m_seed; - double sum = SingleCubic(seed, x, y); - double amp = 1; - long i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleCubic(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleCubicFractalBillow(double x, double y) { - long seed = m_seed; - double sum = Math.abs(SingleCubic(seed, x, y)) * 2 - 1; - double amp = 1; - long i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleCubic(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleCubicFractalRigidMulti(double x, double y) { - long seed = m_seed; - double sum = 1 - Math.abs(SingleCubic(seed, x, y)); - double amp = 1; - long i = 0; - - while(++i < m_octaves) { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleCubic(++seed, x, y))) * amp; - } - - return sum; - } - - public double GetCubic(double x, double y) { - x *= m_frequency; - y *= m_frequency; - - return SingleCubic(0, x, y); - } - - private double SingleCubic(long seed, double x, double y) { - long x1 = fastFloor(x); - long y1 = fastFloor(y); - - long x0 = x1 - 1; - long y0 = y1 - 1; - long x2 = x1 + 1; - long y2 = y1 + 1; - long x3 = x1 + 2; - long y3 = y1 + 2; - - double xs = x - (double) x1; - double ys = y - (double) y1; - - return cubicLerp(cubicLerp(valCoord2D(seed, x0, y0), valCoord2D(seed, x1, y0), valCoord2D(seed, x2, y0), valCoord2D(seed, x3, y0), xs), cubicLerp(valCoord2D(seed, x0, y1), valCoord2D(seed, x1, y1), valCoord2D(seed, x2, y1), valCoord2D(seed, x3, y1), xs), cubicLerp(valCoord2D(seed, x0, y2), valCoord2D(seed, x1, y2), valCoord2D(seed, x2, y2), valCoord2D(seed, x3, y2), xs), cubicLerp(valCoord2D(seed, x0, y3), valCoord2D(seed, x1, y3), valCoord2D(seed, x2, y3), valCoord2D(seed, x3, y3), xs), ys) * CUBIC_2D_BOUNDING; - } - - // Cellular Noise - public double GetCellular(double x, double y, double z) { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - return switch(m_cellularReturnType) { - case CellValue, NoiseLookup, Distance -> SingleCellular(x, y, z); - default -> SingleCellular2Edge(x, y, z); - }; - } - - private double SingleCellular(double x, double y, double z) { - long xr = fastRound(x); - long yr = fastRound(y); - long zr = fastRound(z); - - double distance = 999999; - long xc = 0, yc = 0, zc = 0; - - switch(m_cellularDistanceFunction) { - case Euclidean: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - for(long zi = zr - 1; zi <= zr + 1; zi++) { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - case Manhattan: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - for(long zi = zr - 1; zi <= zr + 1; zi++) { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - case Natural: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - for(long zi = zr - 1; zi <= zr + 1; zi++) { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - } - - switch(m_cellularReturnType) { - case CellValue: - return valCoord3D(0, xc, yc, zc); - - case NoiseLookup: - Double3 vec = CELL_3D[(int) hash3D(m_seed, xc, yc, zc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y, zc + vec.z); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private double SingleCellular2Edge(double x, double y, double z) { - long xr = fastRound(x); - long yr = fastRound(y); - long zr = fastRound(z); - - double distance = 999999; - double distance2 = 999999; - - switch(m_cellularDistanceFunction) { - case Euclidean: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - for(long zi = zr - 1; zi <= zr + 1; zi++) { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - case Manhattan: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - for(long zi = zr - 1; zi <= zr + 1; zi++) { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - case Natural: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - for(long zi = zr - 1; zi <= zr + 1; zi++) { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - default: - break; - } - - return switch(m_cellularReturnType) { - case Distance2 -> distance2 - 1; - case Distance2Add -> distance2 + distance - 1; - case Distance2Sub -> distance2 - distance - 1; - case Distance2Mul -> distance2 * distance - 1; - case Distance2Div -> distance / distance2 - 1; - default -> 0; - }; - } - - public double GetCellular(double x, double y) { - x *= m_frequency; - y *= m_frequency; - - return switch(m_cellularReturnType) { - case CellValue, NoiseLookup, Distance -> SingleCellular(x, y); - default -> SingleCellular2Edge(x, y); - }; - } - - private double SingleCellular(double x, double y) { - long xr = fastRound(x); - long yr = fastRound(y); - - double distance = 999999; - long xc = 0, yc = 0; - - switch(m_cellularDistanceFunction) { - default: - case Euclidean: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = vecX * vecX + vecY * vecY; - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Manhattan: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY)); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Natural: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - if(newDistance < distance) { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - } - - switch(m_cellularReturnType) { - case CellValue: - return valCoord2D(0, xc, yc); - - case NoiseLookup: - Double2 vec = CELL_2D[(int) hash2D(m_seed, xc, yc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private double SingleCellular2Edge(double x, double y) { - long xr = fastRound(x); - long yr = fastRound(y); - - double distance = 999999; - double distance2 = 999999; - - switch(m_cellularDistanceFunction) { - default: - case Euclidean: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = vecX * vecX + vecY * vecY; - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - case Manhattan: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = Math.abs(vecX) + Math.abs(vecY); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - case Natural: - for(long xi = xr - 1; xi <= xr + 1; xi++) { - for(long yi = yr - 1; yi <= yr + 1; yi++) { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - } - - return switch(m_cellularReturnType) { - case Distance2 -> distance2 - 1; - case Distance2Add -> distance2 + distance - 1; - case Distance2Sub -> distance2 - distance - 1; - case Distance2Mul -> distance2 * distance - 1; - case Distance2Div -> distance / distance2 - 1; - default -> 0; - }; - } - - public void GradientPerturb(Vector3f v3) { - SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v3); - } - - public void GradientPerturbFractal(Vector3f v3) { - long seed = m_seed; - double amp = m_gradientPerturbAmp * m_fractalBounding; - double freq = m_frequency; - - SingleGradientPerturb(seed, amp, m_frequency, v3); - - for(long i = 1; i < m_octaves; i++) { - freq *= m_lacunarity; - amp *= m_gain; - SingleGradientPerturb(++seed, amp, freq, v3); - } - } - - private void SingleGradientPerturb(long seed, double perturbAmp, double frequency, Vector3f v3) { - double xf = v3.x * frequency; - double yf = v3.y * frequency; - double zf = v3.z * frequency; - - long x0 = fastFloor(xf); - long y0 = fastFloor(yf); - long z0 = fastFloor(zf); - long x1 = x0 + 1; - long y1 = y0 + 1; - long z1 = z0 + 1; - - double xs = 0, ys = 0, zs = 0; - switch(m_longerp) { - case Linear -> { - xs = xf - x0; - ys = yf - y0; - zs = zf - z0; - } - case Hermite -> { - xs = longerpHermiteFunc(xf - x0); - ys = longerpHermiteFunc(yf - y0); - zs = longerpHermiteFunc(zf - z0); - } - case Qulongic -> { - xs = longerpQulongicFunc(xf - x0); - ys = longerpQulongicFunc(yf - y0); - zs = longerpQulongicFunc(zf - z0); - } - } - - Double3 vec0 = CELL_3D[(int) hash3D(seed, x0, y0, z0) & 255]; - Double3 vec1 = CELL_3D[(int) hash3D(seed, x1, y0, z0) & 255]; - - double lx0x = lerp(vec0.x, vec1.x, xs); - double ly0x = lerp(vec0.y, vec1.y, xs); - double lz0x = lerp(vec0.z, vec1.z, xs); - - vec0 = CELL_3D[(int) hash3D(seed, x0, y1, z0) & 255]; - vec1 = CELL_3D[(int) hash3D(seed, x1, y1, z0) & 255]; - - double lx1x = lerp(vec0.x, vec1.x, xs); - double ly1x = lerp(vec0.y, vec1.y, xs); - double lz1x = lerp(vec0.z, vec1.z, xs); - - double lx0y = lerp(lx0x, lx1x, ys); - double ly0y = lerp(ly0x, ly1x, ys); - double lz0y = lerp(lz0x, lz1x, ys); - - vec0 = CELL_3D[(int) hash3D(seed, x0, y0, z1) & 255]; - vec1 = CELL_3D[(int) hash3D(seed, x1, y0, z1) & 255]; - - lx0x = lerp(vec0.x, vec1.x, xs); - ly0x = lerp(vec0.y, vec1.y, xs); - lz0x = lerp(vec0.z, vec1.z, xs); - - vec0 = CELL_3D[(int) hash3D(seed, x0, y1, z1) & 255]; - vec1 = CELL_3D[(int) hash3D(seed, x1, y1, z1) & 255]; - - lx1x = lerp(vec0.x, vec1.x, xs); - ly1x = lerp(vec0.y, vec1.y, xs); - lz1x = lerp(vec0.z, vec1.z, xs); - - v3.x += lerp(lx0y, lerp(lx0x, lx1x, ys), zs) * perturbAmp; - v3.y += lerp(ly0y, lerp(ly0x, ly1x, ys), zs) * perturbAmp; - v3.z += lerp(lz0y, lerp(lz0x, lz1x, ys), zs) * perturbAmp; - } - - public void GradientPerturb(Vector2f v2) { - SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v2); - } - - public void GradientPerturbFractal(Vector2f v2) { - long seed = m_seed; - double amp = m_gradientPerturbAmp * m_fractalBounding; - double freq = m_frequency; - - SingleGradientPerturb(seed, amp, m_frequency, v2); - - for(long i = 1; i < m_octaves; i++) { - freq *= m_lacunarity; - amp *= m_gain; - SingleGradientPerturb(++seed, amp, freq, v2); - } - } - - private void SingleGradientPerturb(long seed, double perturbAmp, double frequency, Vector2f v2) { - double xf = v2.x * frequency; - double yf = v2.y * frequency; - - long x0 = fastFloor(xf); - long y0 = fastFloor(yf); - long x1 = x0 + 1; - long y1 = y0 + 1; - - double xs = 0, ys = 0; - switch(m_longerp) { - case Linear -> { - xs = xf - x0; - ys = yf - y0; - } - case Hermite -> { - xs = longerpHermiteFunc(xf - x0); - ys = longerpHermiteFunc(yf - y0); - } - case Qulongic -> { - xs = longerpQulongicFunc(xf - x0); - ys = longerpQulongicFunc(yf - y0); - } - } - - Double2 vec0 = CELL_2D[(int) hash2D(seed, x0, y0) & 255]; - Double2 vec1 = CELL_2D[(int) hash2D(seed, x1, y0) & 255]; - - double lx0x = lerp(vec0.x, vec1.x, xs); - double ly0x = lerp(vec0.y, vec1.y, xs); - - vec0 = CELL_2D[(int) hash2D(seed, x0, y1) & 255]; - vec1 = CELL_2D[(int) hash2D(seed, x1, y1) & 255]; - - double lx1x = lerp(vec0.x, vec1.x, xs); - double ly1x = lerp(vec0.y, vec1.y, xs); - - v2.x += lerp(lx0x, lx1x, ys) * perturbAmp; - v2.y += lerp(ly0x, ly1x, ys) * perturbAmp; - } - - public enum NoiseType { - Value, - ValueFractal, - Perlin, - PerlinFractal, - Simplex, - SimplexFractal, - Cellular, - WhiteNoise, - Cubic, - CubicFractal - } - - public enum Longerp { - Linear, - Hermite, - Qulongic - } - - public enum FractalType { - FBM, - Billow, - RigidMulti - } - - public enum CellularDistanceFunction { - Euclidean, - Manhattan, - Natural - } - - public enum CellularReturnType { - CellValue, - NoiseLookup, - Distance, - Distance2, - Distance2Add, - Distance2Sub, - Distance2Mul, - Distance2Div - } - - @SuppressWarnings("ClassCanBeRecord") - private static class Double2 { - public final double x, y; - - public Double2(double x, double y) { - this.x = x; - this.y = y; - } - } - - @SuppressWarnings("ClassCanBeRecord") - private static class Double3 { - public final double x, y, z; - - public Double3(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/noise/FlatNoise.java b/src/main/java/com/volmit/iris/util/noise/FlatNoise.java deleted file mode 100644 index e7a92b8d8..000000000 --- a/src/main/java/com/volmit/iris/util/noise/FlatNoise.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -public class FlatNoise implements NoiseGenerator { - public FlatNoise(long seed) { - - } - - @Override - public double noise(double x) { - return 1D; - } - - @Override - public double noise(double x, double z) { - return 1D; - } - - @Override - public double noise(double x, double y, double z) { - return 1D; - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/FractalBillowPerlinNoise.java b/src/main/java/com/volmit/iris/util/noise/FractalBillowPerlinNoise.java deleted file mode 100644 index 06c92b12f..000000000 --- a/src/main/java/com/volmit/iris/util/noise/FractalBillowPerlinNoise.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.FastNoiseDouble.FractalType; - -public class FractalBillowPerlinNoise implements NoiseGenerator, OctaveNoise { - private final FastNoiseDouble n; - - public FractalBillowPerlinNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalOctaves(1); - n.setFractalType(FractalType.Billow); - } - - public double f(double v) { - return (v / 2D) + 0.5D; - } - - @Override - public double noise(double x) { - return f(n.GetPerlinFractal(x, 0f)); - } - - @Override - public double noise(double x, double z) { - return f(n.GetPerlinFractal(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return f(n.GetPerlinFractal(x, y, z)); - } - - @Override - public void setOctaves(int o) { - n.setFractalOctaves(o); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/FractalBillowSimplexNoise.java b/src/main/java/com/volmit/iris/util/noise/FractalBillowSimplexNoise.java deleted file mode 100644 index 1641bb4b7..000000000 --- a/src/main/java/com/volmit/iris/util/noise/FractalBillowSimplexNoise.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.FastNoiseDouble.FractalType; - -public class FractalBillowSimplexNoise implements NoiseGenerator, OctaveNoise { - private final FastNoiseDouble n; - - public FractalBillowSimplexNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalOctaves(1); - n.setFractalType(FractalType.Billow); - } - - public double f(double v) { - return (v / 2D) + 0.5D; - } - - @Override - public double noise(double x) { - return f(n.GetSimplexFractal(x, 0d)); - } - - @Override - public double noise(double x, double z) { - return f(n.GetSimplexFractal(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return f(n.GetSimplexFractal(x, y, z)); - } - - @Override - public void setOctaves(int o) { - n.setFractalOctaves(o); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/FractalCubicNoise.java b/src/main/java/com/volmit/iris/util/noise/FractalCubicNoise.java deleted file mode 100644 index 76db22118..000000000 --- a/src/main/java/com/volmit/iris/util/noise/FractalCubicNoise.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.FastNoiseDouble.FractalType; - -public class FractalCubicNoise implements NoiseGenerator { - private final FastNoiseDouble n; - - public FractalCubicNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalType(FractalType.Billow); - } - - private double f(double n) { - return (n / 2D) + 0.5D; - } - - @Override - public double noise(double x) { - return f(n.GetCubicFractal(x, 0)); - } - - @Override - public double noise(double x, double z) { - return f(n.GetCubicFractal(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return f(n.GetCubicFractal(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/FractalFBMSimplexNoise.java b/src/main/java/com/volmit/iris/util/noise/FractalFBMSimplexNoise.java deleted file mode 100644 index af3e68d64..000000000 --- a/src/main/java/com/volmit/iris/util/noise/FractalFBMSimplexNoise.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.FastNoiseDouble.FractalType; - -public class FractalFBMSimplexNoise implements NoiseGenerator, OctaveNoise { - private final FastNoiseDouble n; - - public FractalFBMSimplexNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalOctaves(1); - n.setFractalType(FractalType.FBM); - } - - public double f(double v) { - return (v / 2D) + 0.5D; - } - - @Override - public double noise(double x) { - return f(n.GetSimplexFractal(x, 0d)); - } - - @Override - public double noise(double x, double z) { - return f(n.GetSimplexFractal(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return f(n.GetSimplexFractal(x, y, z)); - } - - @Override - public void setOctaves(int o) { - n.setFractalOctaves(o); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/FractalRigidMultiSimplexNoise.java b/src/main/java/com/volmit/iris/util/noise/FractalRigidMultiSimplexNoise.java deleted file mode 100644 index 150975da2..000000000 --- a/src/main/java/com/volmit/iris/util/noise/FractalRigidMultiSimplexNoise.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.FastNoiseDouble.FractalType; - -public class FractalRigidMultiSimplexNoise implements NoiseGenerator, OctaveNoise { - private final FastNoiseDouble n; - - public FractalRigidMultiSimplexNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalOctaves(1); - n.setFractalType(FractalType.RigidMulti); - } - - public double f(double v) { - return (v / 2D) + 0.5D; - } - - @Override - public double noise(double x) { - return f(n.GetSimplexFractal(x, 0d)); - } - - @Override - public double noise(double x, double z) { - return f(n.GetSimplexFractal(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return f(n.GetSimplexFractal(x, y, z)); - } - - @Override - public void setOctaves(int o) { - n.setFractalOctaves(o); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/GlobNoise.java b/src/main/java/com/volmit/iris/util/noise/GlobNoise.java deleted file mode 100644 index 0443f51c1..000000000 --- a/src/main/java/com/volmit/iris/util/noise/GlobNoise.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; - -public class GlobNoise implements NoiseGenerator { - private final FastNoiseDouble n; - - public GlobNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Div); - n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - } - - private double f(double n) { - return n + 1D; - } - - @Override - public double noise(double x) { - return f(n.GetCellular(x, 0)); - } - - @Override - public double noise(double x, double z) { - return f(n.GetCellular(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return f(n.GetCellular(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/ImageNoise.java b/src/main/java/com/volmit/iris/util/noise/ImageNoise.java deleted file mode 100644 index 2bd790fd5..000000000 --- a/src/main/java/com/volmit/iris/util/noise/ImageNoise.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.object.IrisImageMap; - -public class ImageNoise implements NoiseGenerator { - private final IrisImageMap expression; - private final IrisData data; - - public ImageNoise(IrisData data, IrisImageMap expression) { - this.data = data; - this.expression = expression; - } - - @Override - public double noise(double x) { - return noise(x, 0); - } - - @Override - public double noise(double x, double z) { - return expression.getNoise(data, (int) x, (int) z); - } - - @Override - public double noise(double x, double y, double z) { - return noise(x, z + y); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/InterpolatedNoise.java b/src/main/java/com/volmit/iris/util/noise/InterpolatedNoise.java deleted file mode 100644 index a4d7d10fe..000000000 --- a/src/main/java/com/volmit/iris/util/noise/InterpolatedNoise.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.function.NoiseProvider; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.interpolation.IrisInterpolation; - -public class InterpolatedNoise implements NoiseGenerator { - private final InterpolationMethod method; - private final NoiseProvider p; - - public InterpolatedNoise(long seed, NoiseType type, InterpolationMethod method) { - this.method = method; - NoiseGenerator g = type.create(seed); - p = g::noise; - } - - @Override - public double noise(double x) { - return noise(x, 0); - } - - @Override - public double noise(double x, double z) { - return IrisInterpolation.getNoise(method, (int) x, (int) z, 32, p); - } - - @Override - public double noise(double x, double y, double z) { - if(z == 0) { - return noise(x, y); - } - - return IrisInterpolation.getNoise(method, (int) x, (int) z, 32, p); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/NoiseFactory.java b/src/main/java/com/volmit/iris/util/noise/NoiseFactory.java deleted file mode 100644 index fac5399d4..000000000 --- a/src/main/java/com/volmit/iris/util/noise/NoiseFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -@FunctionalInterface -public interface NoiseFactory { - NoiseGenerator create(long seed); -} diff --git a/src/main/java/com/volmit/iris/util/noise/NoiseGenerator.java b/src/main/java/com/volmit/iris/util/noise/NoiseGenerator.java deleted file mode 100644 index 6ad166239..000000000 --- a/src/main/java/com/volmit/iris/util/noise/NoiseGenerator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.stream.interpolation.Interpolated; - -public interface NoiseGenerator { - double noise(double x); - - double noise(double x, double z); - - double noise(double x, double y, double z); - - default boolean isStatic() { - return false; - } - - default boolean isNoScale() { - return false; - } - - default ProceduralStream stream() { - return ProceduralStream.of(this::noise, this::noise, Interpolated.DOUBLE); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/NoiseType.java b/src/main/java/com/volmit/iris/util/noise/NoiseType.java deleted file mode 100644 index b2d26b2c8..000000000 --- a/src/main/java/com/volmit/iris/util/noise/NoiseType.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.interpolation.InterpolationMethod; - -public enum NoiseType { - WHITE(WhiteNoise::new), - WHITE_BILINEAR((s) -> new InterpolatedNoise(s, WHITE, InterpolationMethod.BILINEAR)), - WHITE_BICUBIC((s) -> new InterpolatedNoise(s, WHITE, InterpolationMethod.BICUBIC)), - WHITE_HERMITE((s) -> new InterpolatedNoise(s, WHITE, InterpolationMethod.HERMITE)), - SIMPLEX(SimplexNoise::new), - PERLIN(seed -> new PerlinNoise(seed).hermite()), - FRACTAL_BILLOW_SIMPLEX(FractalBillowSimplexNoise::new), - FRACTAL_BILLOW_PERLIN(FractalBillowPerlinNoise::new), - FRACTAL_FBM_SIMPLEX(FractalFBMSimplexNoise::new), - FRACTAL_RIGID_MULTI_SIMPLEX(FractalRigidMultiSimplexNoise::new), - FLAT(FlatNoise::new), - CELLULAR(CellularNoise::new), - CELLULAR_BILINEAR((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.BILINEAR)), - CELLULAR_BILINEAR_STARCAST_3((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.BILINEAR_STARCAST_3)), - CELLULAR_BILINEAR_STARCAST_6((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.BILINEAR_STARCAST_6)), - CELLULAR_BILINEAR_STARCAST_9((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.BILINEAR_STARCAST_9)), - CELLULAR_BILINEAR_STARCAST_12((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.BILINEAR_STARCAST_12)), - CELLULAR_BICUBIC((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.BICUBIC)), - CELLULAR_HERMITE((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.HERMITE)), - CELLULAR_STARCAST_3((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.STARCAST_3)), - CELLULAR_STARCAST_6((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.STARCAST_6)), - CELLULAR_STARCAST_9((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.STARCAST_9)), - CELLULAR_STARCAST_12((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.STARCAST_12)), - CELLULAR_HERMITE_STARCAST_3((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.HERMITE_STARCAST_3)), - CELLULAR_HERMITE_STARCAST_6((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.HERMITE_STARCAST_6)), - CELLULAR_HERMITE_STARCAST_9((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.HERMITE_STARCAST_9)), - CELLULAR_HERMITE_STARCAST_12((s) -> new InterpolatedNoise(s, CELLULAR, InterpolationMethod.HERMITE_STARCAST_12)), - GLOB(GlobNoise::new), - CUBIC(CubicNoise::new), - FRACTAL_CUBIC(FractalCubicNoise::new), - CELLULAR_HEIGHT(CellHeightNoise::new), - CLOVER(CloverNoise::new), - CLOVER_BILINEAR((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.BILINEAR)), - CLOVER_BILINEAR_STARCAST_3((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.BILINEAR_STARCAST_3)), - CLOVER_BILINEAR_STARCAST_6((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.BILINEAR_STARCAST_6)), - CLOVER_BILINEAR_STARCAST_9((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.BILINEAR_STARCAST_9)), - CLOVER_BILINEAR_STARCAST_12((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.BILINEAR_STARCAST_12)), - CLOVER_BICUBIC((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.BICUBIC)), - CLOVER_HERMITE((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.HERMITE)), - CLOVER_STARCAST_3((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.STARCAST_3)), - CLOVER_STARCAST_6((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.STARCAST_6)), - CLOVER_STARCAST_9((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.STARCAST_9)), - CLOVER_STARCAST_12((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.STARCAST_12)), - CLOVER_HERMITE_STARCAST_3((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.HERMITE_STARCAST_3)), - CLOVER_HERMITE_STARCAST_6((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.HERMITE_STARCAST_6)), - CLOVER_HERMITE_STARCAST_9((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.HERMITE_STARCAST_9)), - CLOVER_HERMITE_STARCAST_12((s) -> new InterpolatedNoise(s, CLOVER, InterpolationMethod.HERMITE_STARCAST_12)), - VASCULAR(VascularNoise::new); - - private final NoiseFactory f; - - NoiseType(NoiseFactory f) { - this.f = f; - } - - public NoiseGenerator create(long seed) { - return f.create(seed); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/OctaveNoise.java b/src/main/java/com/volmit/iris/util/noise/OctaveNoise.java deleted file mode 100644 index a868f0738..000000000 --- a/src/main/java/com/volmit/iris/util/noise/OctaveNoise.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -public interface OctaveNoise { - void setOctaves(int o); -} diff --git a/src/main/java/com/volmit/iris/util/noise/PerlinNoise.java b/src/main/java/com/volmit/iris/util/noise/PerlinNoise.java deleted file mode 100644 index aca2e1efd..000000000 --- a/src/main/java/com/volmit/iris/util/noise/PerlinNoise.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; - -public class PerlinNoise implements NoiseGenerator, OctaveNoise { - private final FastNoiseDouble n; - private int octaves; - - public PerlinNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - octaves = 1; - } - - public double f(double v) { - return (v / 2D) + 0.5D; - } - - @Override - public double noise(double x) { - if(octaves <= 1) { - return f(n.GetPerlin(x, 0)); - } - - double f = 1; - double m = 0; - double v = 0; - - for(int i = 0; i < octaves; i++) { - v += n.GetPerlin((x * (f == 1 ? f++ : (f *= 2))), 0) * f; - m += f; - } - - return f(v / m); - } - - @Override - public double noise(double x, double z) { - if(octaves <= 1) { - return f(n.GetPerlin(x, z)); - } - double f = 1; - double m = 0; - double v = 0; - - for(int i = 0; i < octaves; i++) { - f = f == 1 ? f + 1 : f * 2; - v += n.GetPerlin((x * f), (z * f)) * f; - m += f; - } - - return f(v / m); - } - - @Override - public double noise(double x, double y, double z) { - if(octaves <= 1) { - return f(n.GetPerlin(x, y, z)); - } - double f = 1; - double m = 0; - double v = 0; - - for(int i = 0; i < octaves; i++) { - f = f == 1 ? f + 1 : f * 2; - v += n.GetPerlin((x * f), (y * f), (z * f)) * f; - m += f; - } - - return f(v / m); - } - - @Override - public void setOctaves(int o) { - octaves = o; - } - - public NoiseGenerator hermite() { - n.m_longerp = FastNoiseDouble.Longerp.Hermite; - return this; - } - - public NoiseGenerator quad() { - n.m_longerp = FastNoiseDouble.Longerp.Qulongic; - return this; - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/RarityCellGenerator.java b/src/main/java/com/volmit/iris/util/noise/RarityCellGenerator.java deleted file mode 100644 index 42f631e69..000000000 --- a/src/main/java/com/volmit/iris/util/noise/RarityCellGenerator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.engine.object.IRare; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; - -public class RarityCellGenerator extends CellGenerator { - public RarityCellGenerator(RNG rng) { - super(rng); - } - - public T get(double x, double z, KList b) { - if(b.size() == 0) { - return null; - } - - if(b.size() == 1) { - return b.get(0); - } - - KList rarityMapped = new KList<>(); - boolean o = false; - int max = 1; - for(T i : b) { - if(i.getRarity() > max) { - max = i.getRarity(); - } - } - - max++; - - for(T i : b) { - for(int j = 0; j < max - i.getRarity(); j++) { - //noinspection AssignmentUsedAsCondition - if(o = !o) { - rarityMapped.add(i); - } else { - rarityMapped.add(0, i); - } - } - } - - if(rarityMapped.size() == 1) { - return rarityMapped.get(0); - } - - if(rarityMapped.isEmpty()) { - throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); - } - - return rarityMapped.get(getIndex(x, z, rarityMapped.size())); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/SimplexNoise.java b/src/main/java/com/volmit/iris/util/noise/SimplexNoise.java deleted file mode 100644 index 71f39b89f..000000000 --- a/src/main/java/com/volmit/iris/util/noise/SimplexNoise.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; - -public class SimplexNoise implements NoiseGenerator, OctaveNoise { - private final FastNoiseDouble n; - private int octaves; - - public SimplexNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - octaves = 1; - } - - public double f(double v) { - return (v / 2D) + 0.5D; - } - - @Override - public double noise(double x) { - if(octaves <= 1) { - return f(n.GetSimplex(x, 0d)); - } - - double f = 1; - double m = 0; - double v = 0; - - for(int i = 0; i < octaves; i++) { - v += n.GetSimplex((x * (f == 1 ? f++ : (f *= 2))), 0d) * f; - m += f; - } - - return f(v / m); - } - - @Override - public double noise(double x, double z) { - if(octaves <= 1) { - return f(n.GetSimplex(x, z)); - } - double f = 1; - double m = 0; - double v = 0; - - for(int i = 0; i < octaves; i++) { - f = f == 1 ? f + 1 : f * 2; - v += n.GetSimplex((x * f), (z * f)) * f; - m += f; - } - - return f(v / m); - } - - @Override - public double noise(double x, double y, double z) { - if(octaves <= 1) { - return f(n.GetSimplex(x, y, z)); - } - double f = 1; - double m = 0; - double v = 0; - - for(int i = 0; i < octaves; i++) { - f = f == 1 ? f + 1 : f * 2; - v += n.GetSimplex((x * f), (y * f), (z * f)) * f; - m += f; - } - - return f(v / m); - } - - @Override - public void setOctaves(int o) { - octaves = o; - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/VascularNoise.java b/src/main/java/com/volmit/iris/util/noise/VascularNoise.java deleted file mode 100644 index 6a979d08c..000000000 --- a/src/main/java/com/volmit/iris/util/noise/VascularNoise.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; - -public class VascularNoise implements NoiseGenerator { - private final FastNoiseDouble n; - - public VascularNoise(long seed) { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); - n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - } - - private double filter(double noise) { - return M.clip((noise / 2D) + 0.5D, 0D, 1D); - } - - @Override - public double noise(double x) { - return filter(n.GetCellular(x, 0)); - } - - @Override - public double noise(double x, double z) { - return filter(n.GetCellular(x, z)); - } - - @Override - public double noise(double x, double y, double z) { - return filter(n.GetCellular(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/noise/WhiteNoise.java b/src/main/java/com/volmit/iris/util/noise/WhiteNoise.java deleted file mode 100644 index 3ce0bccc4..000000000 --- a/src/main/java/com/volmit/iris/util/noise/WhiteNoise.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.noise; - -import com.volmit.iris.util.math.RNG; - -public class WhiteNoise implements NoiseGenerator { - private final FastNoise n; - - public WhiteNoise(long seed) { - n = new FastNoise(new RNG(seed).imax()); - } - - public boolean isStatic() { - return true; - } - - public boolean isNoScale() { - return true; - } - - private double f(double m) { - return (m % 8192) * 1024; - } - - @Override - public double noise(double x) { - return (n.GetWhiteNoise(f(x), 0d) / 2D) + 0.5D; - } - - @Override - public double noise(double x, double z) { - return (n.GetWhiteNoise(f(x), f(z)) / 2D) + 0.5D; - } - - @Override - public double noise(double x, double y, double z) { - return (n.GetWhiteNoise(f(x), f(y), f(z)) / 2D) + 0.5D; - } -} diff --git a/src/main/java/com/volmit/iris/util/parallel/BurstExecutor.java b/src/main/java/com/volmit/iris/util/parallel/BurstExecutor.java deleted file mode 100644 index ffb4cf5ad..000000000 --- a/src/main/java/com/volmit/iris/util/parallel/BurstExecutor.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.parallel; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import lombok.Getter; -import lombok.Setter; - -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -@SuppressWarnings("ALL") -public class BurstExecutor { - private final ExecutorService executor; - @Getter - private final KList> futures; - @Setter - private boolean multicore = true; - - public BurstExecutor(ExecutorService executor, int burstSizeEstimate) { - this.executor = executor; - futures = new KList>(burstSizeEstimate); - } - - @SuppressWarnings("UnusedReturnValue") - public Future queue(Runnable r) { - if(!multicore) { - r.run(); - return CompletableFuture.completedFuture(null); - } - - synchronized(futures) { - - Future c = executor.submit(r); - futures.add(c); - return c; - } - } - - public BurstExecutor queue(List r) { - if(!multicore) { - for(Runnable i : new KList<>(r)) { - i.run(); - } - - return this; - } - - synchronized(futures) { - for(Runnable i : new KList<>(r)) { - queue(i); - } - } - - return this; - } - - public BurstExecutor queue(Runnable[] r) { - if(!multicore) { - for(Runnable i : new KList<>(r)) { - i.run(); - } - - return this; - } - - synchronized(futures) { - for(Runnable i : r) { - queue(i); - } - } - - return this; - } - - public void complete() { - if(!multicore) { - return; - } - - synchronized(futures) { - if(futures.isEmpty()) { - return; - } - - try { - for(Future i : futures) { - i.get(); - } - - futures.clear(); - } catch(InterruptedException | ExecutionException e) { - Iris.reportError(e); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/parallel/BurstedHunk.java b/src/main/java/com/volmit/iris/util/parallel/BurstedHunk.java deleted file mode 100644 index abe41466c..000000000 --- a/src/main/java/com/volmit/iris/util/parallel/BurstedHunk.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.parallel; - - -import com.volmit.iris.util.hunk.Hunk; - -public interface BurstedHunk extends Hunk { - int getOffsetX(); - - int getOffsetY(); - - int getOffsetZ(); -} diff --git a/src/main/java/com/volmit/iris/util/parallel/GridLock.java b/src/main/java/com/volmit/iris/util/parallel/GridLock.java deleted file mode 100644 index 46735c2b4..000000000 --- a/src/main/java/com/volmit/iris/util/parallel/GridLock.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.parallel; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.function.NastyRunnable; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.io.IORunnable; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Supplier; - -public class GridLock { - private final Hunk locks; - - public GridLock(int x, int z) { - this.locks = Hunk.newAtomicHunk(x, 1, z); - locks.iterateSync((a, b, c) -> locks.set(a, b, c, new ReentrantLock())); - } - - public void with(int x, int z, Runnable r) { - lock(x, z); - r.run(); - unlock(x, z); - } - - public void withNasty(int x, int z, NastyRunnable r) throws Throwable { - lock(x, z); - r.run(); - unlock(x, z); - } - - public void withIO(int x, int z, IORunnable r) throws IOException { - lock(x, z); - r.run(); - unlock(x, z); - } - - public T withResult(int x, int z, Supplier r) { - lock(x, z); - T t = r.get(); - unlock(x, z); - return t; - } - - public void withAll(Runnable r) { - locks.iterateSync((a, b, c, d) -> d.lock()); - r.run(); - locks.iterateSync((a, b, c, d) -> d.unlock()); - } - - public T withAllResult(Supplier r) { - locks.iterateSync((a, b, c, d) -> d.lock()); - T t = r.get(); - locks.iterateSync((a, b, c, d) -> d.unlock()); - - return t; - } - - public boolean tryLock(int x, int z) { - return locks.get(x, 0, z).tryLock(); - } - - public boolean tryLock(int x, int z, long timeout) { - try { - return locks.get(x, 0, z).tryLock(timeout, TimeUnit.MILLISECONDS); - } catch(InterruptedException e) { - Iris.reportError(e); - } - - return false; - } - - public void lock(int x, int z) { - locks.get(x, 0, z).lock(); - } - - public void unlock(int x, int z) { - locks.get(x, 0, z).unlock(); - } -} diff --git a/src/main/java/com/volmit/iris/util/parallel/HyperLock.java b/src/main/java/com/volmit/iris/util/parallel/HyperLock.java deleted file mode 100644 index ac7d62cdf..000000000 --- a/src/main/java/com/volmit/iris/util/parallel/HyperLock.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.parallel; - -import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap; -import com.volmit.iris.Iris; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.util.function.NastyRunnable; -import com.volmit.iris.util.io.IORunnable; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Supplier; - -public class HyperLock { - private final ConcurrentLinkedHashMap locks; - private boolean enabled = true; - private boolean fair = false; - - public HyperLock() { - this(1024, false); - } - - public HyperLock(int capacity) { - this(capacity, false); - } - - public HyperLock(int capacity, boolean fair) { - this.fair = fair; - locks = new ConcurrentLinkedHashMap.Builder() - .initialCapacity(capacity) - .maximumWeightedCapacity(capacity) - .listener((k, v) -> { - if(v.isLocked() || v.isHeldByCurrentThread()) { - Iris.warn("InfiniLock Eviction of " + k + " still has locks on it!"); - } - }) - .concurrencyLevel(32) - .build(); - } - - public void with(int x, int z, Runnable r) { - lock(x, z); - r.run(); - unlock(x, z); - } - - public void withLong(long k, Runnable r) { - lock(Cache.keyX(k), Cache.keyZ(k)); - r.run(); - unlock(Cache.keyX(k), Cache.keyZ(k)); - } - - public void withNasty(int x, int z, NastyRunnable r) throws Throwable { - lock(x, z); - Throwable ee = null; - try { - r.run(); - } catch(Throwable e) { - ee = e; - } finally { - unlock(x, z); - - if(ee != null) { - throw ee; - } - } - } - - public void withIO(int x, int z, IORunnable r) throws IOException { - lock(x, z); - IOException ee = null; - try { - r.run(); - } catch(IOException e) { - ee = e; - } finally { - unlock(x, z); - - if(ee != null) { - throw ee; - } - } - } - - public T withResult(int x, int z, Supplier r) { - lock(x, z); - T t = r.get(); - unlock(x, z); - return t; - } - - public boolean tryLock(int x, int z) { - return getLock(x, z).tryLock(); - } - - public boolean tryLock(int x, int z, long timeout) { - try { - return getLock(x, z).tryLock(timeout, TimeUnit.MILLISECONDS); - } catch(InterruptedException e) { - Iris.reportError(e); - } - - return false; - } - - private ReentrantLock getLock(int x, int z) { - return locks.computeIfAbsent(Cache.key(x, z), k -> new ReentrantLock(fair)); - } - - public void lock(int x, int z) { - if(!enabled) { - return; - } - - getLock(x, z).lock(); - } - - public void unlock(int x, int z) { - if(!enabled) { - return; - } - - getLock(x, z).unlock(); - } - - public void disable() { - enabled = false; - } -} diff --git a/src/main/java/com/volmit/iris/util/parallel/MultiBurst.java b/src/main/java/com/volmit/iris/util/parallel/MultiBurst.java deleted file mode 100644 index 4280f8aed..000000000 --- a/src/main/java/com/volmit/iris/util/parallel/MultiBurst.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.parallel; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.core.service.PreservationSVC; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; - -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinWorkerThread; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -public class MultiBurst { - public static final MultiBurst burst = new MultiBurst(); - private final AtomicLong last; - private final String name; - private final int priority; - private ExecutorService service; - - public MultiBurst() { - this("Iris", Thread.MIN_PRIORITY); - } - - public MultiBurst(String name, int priority) { - this.name = name; - this.priority = priority; - last = new AtomicLong(M.ms()); - Iris.service(PreservationSVC.class).register(this); - } - - private synchronized ExecutorService getService() { - last.set(M.ms()); - if(service == null || service.isShutdown()) { - service = new ForkJoinPool(IrisSettings.getThreadCount(IrisSettings.get().getConcurrency().getParallelism()), - new ForkJoinPool.ForkJoinWorkerThreadFactory() { - int m = 0; - - @Override - public ForkJoinWorkerThread newThread(ForkJoinPool pool) { - final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); - worker.setPriority(priority); - worker.setName(name + " " + ++m); - return worker; - } - }, - (t, e) -> e.printStackTrace(), true); - } - - return service; - } - - public void burst(Runnable... r) { - burst(r.length).queue(r).complete(); - } - - public void burst(boolean multicore, Runnable... r) { - if(multicore) { - burst(r); - } else { - sync(r); - } - } - - public void burst(List r) { - burst(r.size()).queue(r).complete(); - } - - public void burst(boolean multicore, List r) { - if(multicore) { - burst(r); - } else { - sync(r); - } - } - - private void sync(List r) { - for(Runnable i : new KList<>(r)) { - i.run(); - } - } - - public void sync(Runnable... r) { - for(Runnable i : r) { - i.run(); - } - } - - public void sync(KList r) { - for(Runnable i : r) { - i.run(); - } - } - - public BurstExecutor burst(int estimate) { - return new BurstExecutor(getService(), estimate); - } - - public BurstExecutor burst() { - return burst(16); - } - - public BurstExecutor burst(boolean multicore) { - BurstExecutor b = burst(); - b.setMulticore(multicore); - return b; - } - - public Future lazySubmit(Callable o) { - return getService().submit(o); - } - - public void lazy(Runnable o) { - getService().execute(o); - } - - public Future future(Runnable o) { - return getService().submit(o); - } - - public Future complete(Runnable o) { - return getService().submit(o); - } - - public Future completeValue(Callable o) { - return getService().submit(o); - } - - public void close() { - if(service != null) { - service.shutdown(); - PrecisionStopwatch p = PrecisionStopwatch.start(); - try { - while(!service.awaitTermination(1, TimeUnit.SECONDS)) { - Iris.info("Still waiting to shutdown burster..."); - if(p.getMilliseconds() > 7000) { - Iris.warn("Forcing Shutdown..."); - - try { - service.shutdownNow(); - } catch(Throwable e) { - - } - - break; - } - } - } catch(Throwable e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/parallel/NOOPGridLock.java b/src/main/java/com/volmit/iris/util/parallel/NOOPGridLock.java deleted file mode 100644 index bc6ee8f2b..000000000 --- a/src/main/java/com/volmit/iris/util/parallel/NOOPGridLock.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.parallel; - -import com.volmit.iris.util.function.NastyRunnable; -import com.volmit.iris.util.io.IORunnable; - -import java.io.IOException; -import java.util.function.Supplier; - -public class NOOPGridLock extends GridLock { - public NOOPGridLock(int x, int z) { - super(x, z); - } - - @Override - public void with(int x, int z, Runnable r) { - r.run(); - } - - @Override - public void withNasty(int x, int z, NastyRunnable r) throws Throwable { - r.run(); - } - - @Override - public void withIO(int x, int z, IORunnable r) throws IOException { - r.run(); - } - - @Override - public T withResult(int x, int z, Supplier r) { - return r.get(); - } - - @Override - public void withAll(Runnable r) { - r.run(); - } - - @Override - public T withAllResult(Supplier r) { - return r.get(); - } - - @Override - public boolean tryLock(int x, int z) { - return true; - } - - @Override - public boolean tryLock(int x, int z, long timeout) { - return true; - } - - @Override - public void lock(int x, int z) { - - } - - @Override - public void unlock(int x, int z) { - - } -} diff --git a/src/main/java/com/volmit/iris/util/particle/FastParticle.java b/src/main/java/com/volmit/iris/util/particle/FastParticle.java deleted file mode 100644 index c05a08035..000000000 --- a/src/main/java/com/volmit/iris/util/particle/FastParticle.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.particle; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; - -/** - * Simple Bukkit Particles API with 1.7 to 1.13.2 support ! - *

- * You can find the project on GitHub - * - * @author MrMicky - */ -public final class FastParticle { - - private static final ParticleSender PARTICLE_SENDER; - - static { - if(FastReflection.optionalClass("org.bukkit.Particle$DustOptions").isPresent()) { - PARTICLE_SENDER = new ParticleSender.ParticleSender1_13(); - } else if(FastReflection.optionalClass("org.bukkit.Particle").isPresent()) { - PARTICLE_SENDER = new ParticleSender.ParticleSenderImpl(); - } else { - PARTICLE_SENDER = new ParticleSenderLegacy(); - } - } - - private FastParticle() { - throw new UnsupportedOperationException(); - } - - /* - * Worlds methods - */ - public static void spawnParticle(World world, ParticleType particle, Location location, int count) { - spawnParticle(world, particle, location.getX(), location.getY(), location.getZ(), count); - } - - public static void spawnParticle(World world, ParticleType particle, double x, double y, double z, int count) { - spawnParticle(world, particle, x, y, z, count, null); - } - - public static void spawnParticle(World world, ParticleType particle, Location location, int count, T data) { - spawnParticle(world, particle, location.getX(), location.getY(), location.getZ(), count, data); - } - - public static void spawnParticle(World world, ParticleType particle, double x, double y, double z, int count, - T data) { - spawnParticle(world, particle, x, y, z, count, 0.0D, 0.0D, 0.0D, data); - } - - public static void spawnParticle(World world, ParticleType particle, Location location, int count, double offsetX, - double offsetY, double offsetZ) { - spawnParticle(world, particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ); - } - - public static void spawnParticle(World world, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ) { - spawnParticle(world, particle, x, y, z, count, offsetX, offsetY, offsetZ, null); - } - - public static void spawnParticle(World world, ParticleType particle, Location location, int count, - double offsetX, double offsetY, double offsetZ, T data) { - spawnParticle(world, particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, - offsetZ, data); - } - - public static void spawnParticle(World world, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ, T data) { - spawnParticle(world, particle, x, y, z, count, offsetX, offsetY, offsetZ, 1.0D, data); - } - - public static void spawnParticle(World world, ParticleType particle, Location location, int count, double offsetX, - double offsetY, double offsetZ, double extra) { - spawnParticle(world, particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra); - } - - public static void spawnParticle(World world, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ, double extra) { - spawnParticle(world, particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, null); - } - - public static void spawnParticle(World world, ParticleType particle, Location location, int count, - double offsetX, double offsetY, double offsetZ, double extra, T data) { - spawnParticle(world, particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data); - } - - public static void spawnParticle(World world, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ, double extra, T data) { - sendParticle(world, particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } - - /* - * Player methods - */ - public static void spawnParticle(Player player, ParticleType particle, Location location, int count) { - spawnParticle(player, particle, location.getX(), location.getY(), location.getZ(), count); - } - - public static void spawnParticle(Player player, ParticleType particle, double x, double y, double z, int count) { - spawnParticle(player, particle, x, y, z, count, null); - } - - public static void spawnParticle(Player player, ParticleType particle, Location location, int count, T data) { - spawnParticle(player, particle, location.getX(), location.getY(), location.getZ(), count, data); - } - - public static void spawnParticle(Player player, ParticleType particle, double x, double y, double z, int count, - T data) { - spawnParticle(player, particle, x, y, z, count, 0.0D, 0.0D, 0.0D, data); - } - - public static void spawnParticle(Player player, ParticleType particle, Location location, int count, double offsetX, - double offsetY, double offsetZ) { - spawnParticle(player, particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ); - } - - public static void spawnParticle(Player player, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ) { - spawnParticle(player, particle, x, y, z, count, offsetX, offsetY, offsetZ, null); - } - - public static void spawnParticle(Player player, ParticleType particle, Location location, int count, - double offsetX, double offsetY, double offsetZ, T data) { - spawnParticle(player, particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, data); - } - - public static void spawnParticle(Player player, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ, T data) { - spawnParticle(player, particle, x, y, z, count, offsetX, offsetY, offsetZ, 1.0D, data); - } - - public static void spawnParticle(Player player, ParticleType particle, Location location, int count, double offsetX, - double offsetY, double offsetZ, double extra) { - spawnParticle(player, particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra); - } - - public static void spawnParticle(Player player, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ, double extra) { - spawnParticle(player, particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, null); - } - - public static void spawnParticle(Player player, ParticleType particle, Location location, int count, - double offsetX, double offsetY, double offsetZ, double extra, T data) { - spawnParticle(player, particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data); - } - - public static void spawnParticle(Player player, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ, double extra, T data) { - sendParticle(player, particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } - - private static void sendParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, - double offsetX, double offsetY, double offsetZ, double extra, Object data) { - if(!particle.isSupported()) { - throw new IllegalArgumentException("The particle '" + particle + "' is not compatible with your server version"); - } - - PARTICLE_SENDER.spawnParticle(receiver, particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } -} diff --git a/src/main/java/com/volmit/iris/util/particle/FastReflection.java b/src/main/java/com/volmit/iris/util/particle/FastReflection.java deleted file mode 100644 index e95f21cf6..000000000 --- a/src/main/java/com/volmit/iris/util/particle/FastReflection.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.particle; - -import com.volmit.iris.Iris; -import org.bukkit.Bukkit; - -import java.util.Optional; - -/** - * Small reflection class to use CraftBukkit and NMS - * - * @author MrMicky - */ -public final class FastReflection { - - public static final String OBC_PACKAGE = "org.bukkit.craftbukkit"; - public static final String NMS_PACKAGE = "net.minecraft.server"; - - public static final String VERSION = Bukkit.getServer().getClass().getPackage().getName().substring(OBC_PACKAGE.length() + 1); - - private FastReflection() { - throw new UnsupportedOperationException(); - } - - public static String nmsClassName(String className) { - return NMS_PACKAGE + '.' + VERSION + '.' + className; - } - - public static Class nmsClass(String className) throws ClassNotFoundException { - return Class.forName(nmsClassName(className)); - } - - public static Optional> nmsOptionalClass(String className) { - return optionalClass(nmsClassName(className)); - } - - public static String obcClassName(String className) { - return OBC_PACKAGE + '.' + VERSION + '.' + className; - } - - public static Class obcClass(String className) throws ClassNotFoundException { - return Class.forName(obcClassName(className)); - } - - public static Optional> obcOptionalClass(String className) { - return optionalClass(obcClassName(className)); - } - - public static Optional> optionalClass(String className) { - try { - return Optional.of(Class.forName(className)); - } catch(ClassNotFoundException e) { - Iris.reportError(e); - return Optional.empty(); - } - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public static Object enumValueOf(Class enumClass, String enumName) { - return Enum.valueOf((Class) enumClass, enumName.toUpperCase()); - } -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/particle/ParticleSender.java b/src/main/java/com/volmit/iris/util/particle/ParticleSender.java deleted file mode 100644 index 31e43c6a7..000000000 --- a/src/main/java/com/volmit/iris/util/particle/ParticleSender.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.particle; - -import com.volmit.iris.Iris; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Particle; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Player; -import org.bukkit.material.MaterialData; - -/** - * Particle sender using the Bukkit particles API for 1.9+ servers - * - * @author MrMicky - */ -@SuppressWarnings("deprecation") -interface ParticleSender { - - void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data); - - Object getParticle(ParticleType particle); - - boolean isValidData(Object particle, Object data); - - default double color(double color) { - return color / 255.0; - } - - class ParticleSenderImpl implements ParticleSender { - - @Override - public void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data) { - Particle bukkitParticle = Particle.valueOf(particle.toString()); - - if(data instanceof Color) { - if(particle.getDataType() == Color.class) { - Color color = (Color) data; - count = 0; - offsetX = color(color.getRed()); - offsetY = color(color.getGreen()); - offsetZ = color(color.getBlue()); - extra = 1.0; - } - data = null; - } - - if(receiver instanceof World) { - ((World) receiver).spawnParticle(bukkitParticle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } else if(receiver instanceof Player) { - ((Player) receiver).spawnParticle(bukkitParticle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } - } - - @Override - public Particle getParticle(ParticleType particle) { - try { - return Particle.valueOf(particle.toString()); - } catch(IllegalArgumentException e) { - Iris.reportError(e); - return null; - } - } - - @Override - public boolean isValidData(Object particle, Object data) { - return isValidDataBukkit((Particle) particle, data); - } - - public boolean isValidDataBukkit(Particle particle, Object data) { - return particle.getDataType() == Void.class || particle.getDataType().isInstance(data); - } - } - - class ParticleSender1_13 extends ParticleSenderImpl { - @Override - public void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data) { - Particle bukkitParticle = Particle.valueOf(particle.toString()); - - if(bukkitParticle.getDataType() == Particle.DustOptions.class) { - if(data instanceof Color) { - data = new Particle.DustOptions((Color) data, 1); - } else if(data == null) { - data = new Particle.DustOptions(Color.RED, 1); - } - } else if(bukkitParticle.getDataType() == BlockData.class && data instanceof MaterialData) { - data = Bukkit.createBlockData(((MaterialData) data).getItemType()); - } - - super.spawnParticle(receiver, particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } - - @Override - public boolean isValidDataBukkit(Particle particle, Object data) { - if(particle.getDataType() == Particle.DustOptions.class && data instanceof Color) { - return true; - } - - if(particle.getDataType() == BlockData.class && data instanceof MaterialData) { - return true; - } - - return super.isValidDataBukkit(particle, data); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/particle/ParticleSenderLegacy.java b/src/main/java/com/volmit/iris/util/particle/ParticleSenderLegacy.java deleted file mode 100644 index 3b46f1e3c..000000000 --- a/src/main/java/com/volmit/iris/util/particle/ParticleSenderLegacy.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.particle; - -import com.volmit.iris.Iris; -import org.bukkit.Color; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -/** - * Legacy particle sender with NMS for 1.7/1.8 servers - * - * @author MrMicky - */ -@SuppressWarnings({"deprecation", "JavaReflectionInvocation"}) -class ParticleSenderLegacy implements ParticleSender { - - private static final boolean SERVER_IS_1_8; - - private static final Constructor PACKET_PARTICLE; - private static final Class ENUM_PARTICLE; - - private static final Method WORLD_GET_HANDLE; - private static final Method WORLD_SEND_PARTICLE; - - private static final Method PLAYER_GET_HANDLE; - private static final Field PLAYER_CONNECTION; - private static final Method SEND_PACKET; - private static final int[] EMPTY = new int[0]; - - static { - ENUM_PARTICLE = FastReflection.nmsOptionalClass("EnumParticle").orElse(null); - SERVER_IS_1_8 = ENUM_PARTICLE != null; - - try { - Class packetParticleClass = FastReflection.nmsClass("PacketPlayOutWorldParticles"); - Class playerClass = FastReflection.nmsClass("EntityPlayer"); - Class playerConnectionClass = FastReflection.nmsClass("PlayerConnection"); - Class worldClass = FastReflection.nmsClass("WorldServer"); - Class entityPlayerClass = FastReflection.nmsClass("EntityPlayer"); - - Class craftPlayerClass = FastReflection.obcClass("entity.CraftPlayer"); - Class craftWorldClass = FastReflection.obcClass("CraftWorld"); - - if(SERVER_IS_1_8) { - PACKET_PARTICLE = packetParticleClass.getConstructor(ENUM_PARTICLE, boolean.class, float.class, - float.class, float.class, float.class, float.class, float.class, float.class, int.class, - int[].class); - WORLD_SEND_PARTICLE = worldClass.getDeclaredMethod("sendParticles", entityPlayerClass, ENUM_PARTICLE, - boolean.class, double.class, double.class, double.class, int.class, double.class, double.class, - double.class, double.class, int[].class); - } else { - PACKET_PARTICLE = packetParticleClass.getConstructor(String.class, float.class, float.class, float.class, - float.class, float.class, float.class, float.class, int.class); - WORLD_SEND_PARTICLE = worldClass.getDeclaredMethod("a", String.class, double.class, double.class, - double.class, int.class, double.class, double.class, double.class, double.class); - } - - WORLD_GET_HANDLE = craftWorldClass.getDeclaredMethod("getHandle"); - PLAYER_GET_HANDLE = craftPlayerClass.getDeclaredMethod("getHandle"); - PLAYER_CONNECTION = playerClass.getField("playerConnection"); - SEND_PACKET = playerConnectionClass.getMethod("sendPacket", FastReflection.nmsClass("Packet")); - } catch(ReflectiveOperationException e) { - throw new ExceptionInInitializerError(e); - } - } - - @Override - public void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, - double offsetZ, double extra, Object data) { - try { - int[] datas = toData(particle, data); - - if(data instanceof Color) { - if(particle.getDataType() == Color.class) { - Color color = (Color) data; - count = 0; - offsetX = color(color.getRed()); - offsetY = color(color.getGreen()); - offsetZ = color(color.getBlue()); - extra = 1.0; - } - } - - if(receiver instanceof World) { - Object worldServer = WORLD_GET_HANDLE.invoke(receiver); - - if(SERVER_IS_1_8) { - WORLD_SEND_PARTICLE.invoke(worldServer, null, getEnumParticle(particle), true, x, y, z, count, offsetX, offsetY, offsetZ, extra, datas); - } else { - String particleName = particle.getLegacyName() + (datas.length != 2 ? "" : "_" + datas[0] + "_" + datas[1]); - WORLD_SEND_PARTICLE.invoke(worldServer, particleName, x, y, z, count, offsetX, offsetY, offsetZ, extra); - } - } else if(receiver instanceof Player) { - Object packet; - - if(SERVER_IS_1_8) { - packet = PACKET_PARTICLE.newInstance(getEnumParticle(particle), true, (float) x, (float) y, - (float) z, (float) offsetX, (float) offsetY, (float) offsetZ, (float) extra, count, datas); - } else { - String particleName = particle.getLegacyName() + (datas.length != 2 ? "" : "_" + datas[0] + "_" + datas[1]); - packet = PACKET_PARTICLE.newInstance(particleName, (float) x, (float) y, (float) z, - (float) offsetX, (float) offsetY, (float) offsetZ, (float) extra, count); - } - - Object entityPlayer = PLAYER_GET_HANDLE.invoke(receiver); - Object playerConnection = PLAYER_CONNECTION.get(entityPlayer); - SEND_PACKET.invoke(playerConnection, packet); - } - } catch(ReflectiveOperationException e) { - Iris.reportError(e); - throw new RuntimeException(e); - } - } - - @Override - public boolean isValidData(Object particle, Object data) { - return true; - } - - @Override - public Object getParticle(ParticleType particle) { - if(!SERVER_IS_1_8) { - return particle.getLegacyName(); - } - - try { - return getEnumParticle(particle); - } catch(IllegalArgumentException e) { - Iris.reportError(e); - return null; - } - } - - private Object getEnumParticle(ParticleType particleType) { - return FastReflection.enumValueOf(ENUM_PARTICLE, particleType.toString()); - } - - private int[] toData(ParticleType particle, Object data) { - Class dataType = particle.getDataType(); - if(dataType == ItemStack.class) { - if(!(data instanceof ItemStack itemStack)) { - return SERVER_IS_1_8 ? new int[2] : new int[] {1, 0}; - } - - return new int[] {itemStack.getType().getId(), itemStack.getDurability()}; - } - - if(dataType == MaterialData.class) { - if(!(data instanceof MaterialData materialData)) { - return SERVER_IS_1_8 ? new int[1] : new int[] {1, 0}; - } - - if(SERVER_IS_1_8) { - return new int[] {materialData.getItemType().getId() + (materialData.getData() << 12)}; - } else { - return new int[] {materialData.getItemType().getId(), materialData.getData()}; - } - } - - return EMPTY; - } -} diff --git a/src/main/java/com/volmit/iris/util/particle/ParticleType.java b/src/main/java/com/volmit/iris/util/particle/ParticleType.java deleted file mode 100644 index 0cf8425f2..000000000 --- a/src/main/java/com/volmit/iris/util/particle/ParticleType.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.particle; - -import com.volmit.iris.Iris; -import org.bukkit.Color; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; - -/** - * @author MrMicky - */ -@SuppressWarnings("deprecation") -public enum ParticleType { - - // 1.7+ - EXPLOSION_NORMAL("explode", "poof"), - EXPLOSION_LARGE("largeexplode", "explosion"), - EXPLOSION_HUGE("hugeexplosion", "explosion_emitter"), - FIREWORKS_SPARK("fireworksSpark", "firework"), - WATER_BUBBLE("bubble", "bubble"), - WATER_SPLASH("splash", "splash"), - WATER_WAKE("wake", "fishing"), - SUSPENDED("suspended", "underwater"), - SUSPENDED_DEPTH("depthsuspend", "underwater"), - CRIT("crit", "crit"), - CRIT_MAGIC("magicCrit", "enchanted_hit"), - SMOKE_NORMAL("smoke", "smoke"), - SMOKE_LARGE("largesmoke", "large_smoke"), - SPELL("spell", "effect"), - SPELL_INSTANT("instantSpell", "instant_effect"), - SPELL_MOB("mobSpell", "entity_effect"), - SPELL_MOB_AMBIENT("mobSpellAmbient", "ambient_entity_effect"), - SPELL_WITCH("witchMagic", "witch"), - DRIP_WATER("dripWater", "dripping_water"), - DRIP_LAVA("dripLava", "dripping_lava"), - VILLAGER_ANGRY("angryVillager", "angry_villager"), - VILLAGER_HAPPY("happyVillager", "happy_villager"), - TOWN_AURA("townaura", "mycelium"), - NOTE("note", "note"), - PORTAL("portal", "portal"), - ENCHANTMENT_TABLE("enchantmenttable", "enchant"), - FLAME("flame", "flame"), - LAVA("lava", "lava"), - // FOOTSTEP("footstep", null), - CLOUD("cloud", "cloud"), - REDSTONE("reddust", "dust"), - SNOWBALL("snowballpoof", "item_snowball"), - SNOW_SHOVEL("snowshovel", "item_snowball"), - SLIME("slime", "item_slime"), - HEART("heart", "heart"), - ITEM_CRACK("iconcrack", "item"), - BLOCK_CRACK("blockcrack", "block"), - BLOCK_DUST("blockdust", "block"), - - // 1.8+ - BARRIER("barrier", "barrier", 8), - WATER_DROP("droplet", "rain", 8), - MOB_APPEARANCE("mobappearance", "elder_guardian", 8), - // ITEM_TAKE("take", null, 8), - - // 1.9+ - DRAGON_BREATH("dragonbreath", "dragon_breath", 9), - END_ROD("endRod", "end_rod", 9), - DAMAGE_INDICATOR("damageIndicator", "damage_indicator", 9), - SWEEP_ATTACK("sweepAttack", "sweep_attack", 9), - - // 1.10+ - FALLING_DUST("fallingdust", "falling_dust", 10), - - // 1.11+ - TOTEM("totem", "totem_of_undying", 11), - SPIT("spit", "spit", 11), - - // 1.13+ - SQUID_INK(13), - BUBBLE_POP(13), - CURRENT_DOWN(13), - BUBBLE_COLUMN_UP(13), - NAUTILUS(13), - DOLPHIN(13), - - // 1.14+ - SNEEZE(14), - CAMPFIRE_COSY_SMOKE(14), - CAMPFIRE_SIGNAL_SMOKE(14), - COMPOSTER(14), - FLASH(14), - FALLING_LAVA(14), - LANDING_LAVA(14), - FALLING_WATER(14), - - // 1.15+ - DRIPPING_HONEY(15), - FALLING_HONEY(15), - LANDING_HONEY(15), - FALLING_NECTAR(15); - - private static final int SERVER_VERSION_ID; - - static { - String ver = FastReflection.VERSION; - SERVER_VERSION_ID = ver.charAt(4) == '_' ? Character.getNumericValue(ver.charAt(3)) : Integer.parseInt(ver.substring(3, 5)); - } - - private final String legacyName; - private final String name; - private final int minimumVersion; - - // 1.7 particles - ParticleType(String legacyName, String name) { - this(legacyName, name, -1); - } - - // 1.13+ particles - ParticleType(int minimumVersion) { - this.legacyName = null; - this.name = name().toLowerCase(); - this.minimumVersion = minimumVersion; - } - - // 1.8-1.12 particles - ParticleType(String legacyName, String name, int minimumVersion) { - this.legacyName = legacyName; - this.name = name; - this.minimumVersion = minimumVersion; - } - - public static ParticleType getParticle(String particleName) { - try { - return ParticleType.valueOf(particleName.toUpperCase()); - } catch(IllegalArgumentException e) { - Iris.reportError(e); - for(ParticleType particle : values()) { - if(particle.getName().equalsIgnoreCase(particleName)) { - return particle; - } - - if(particle.hasLegacyName() && particle.getLegacyName().equalsIgnoreCase(particleName)) { - return particle; - } - } - } - return null; - } - - public boolean hasLegacyName() { - return legacyName != null; - } - - public String getLegacyName() { - if(!hasLegacyName()) { - throw new IllegalStateException("Particle " + name() + " don't have legacy name"); - } - return legacyName; - } - - public String getName() { - return name; - } - - public boolean isSupported() { - return minimumVersion <= 0 || SERVER_VERSION_ID >= minimumVersion; - } - - public Class getDataType() { - return switch(this) { - case ITEM_CRACK -> ItemStack.class; - case BLOCK_CRACK, BLOCK_DUST, FALLING_DUST -> - //noinspection deprecation - MaterialData.class; - case REDSTONE -> Color.class; - default -> Void.class; - }; - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/CancellableTask.java b/src/main/java/com/volmit/iris/util/plugin/CancellableTask.java deleted file mode 100644 index 2889b8758..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/CancellableTask.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -public interface CancellableTask { - void cancel(); -} diff --git a/src/main/java/com/volmit/iris/util/plugin/Chunks.java b/src/main/java/com/volmit/iris/util/plugin/Chunks.java deleted file mode 100644 index 41322880e..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/Chunks.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; - -public class Chunks { - public static boolean isSafe(World w, int x, int z) { - return w.isChunkLoaded(x, z) - && w.isChunkLoaded(x + 1, z) - && w.isChunkLoaded(x, z + 1) - && w.isChunkLoaded(x - 1, z) - && w.isChunkLoaded(x, z - 1) - && w.isChunkLoaded(x - 1, z - 1) - && w.isChunkLoaded(x + 1, z + 1) - && w.isChunkLoaded(x + 1, z - 1) - && w.isChunkLoaded(x - 1, z + 1); - } - - public static boolean isSafe(Location l) { - return isSafe(l.getWorld(), l.getBlockX() >> 4, l.getBlockZ() >> 4); - } - - public static boolean hasPlayersNearby(Location at) { - try { - return !at.getWorld().getNearbyEntities(at, 32, 32, 32, (i) -> i instanceof Player).isEmpty(); - } catch(Throwable ignored) { - return false; - } - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/Command.java b/src/main/java/com/volmit/iris/util/plugin/Command.java deleted file mode 100644 index 4698693c4..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/Command.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target(FIELD) -public @interface Command { - String value() default ""; -} diff --git a/src/main/java/com/volmit/iris/util/plugin/CommandDummy.java b/src/main/java/com/volmit/iris/util/plugin/CommandDummy.java deleted file mode 100644 index c46289bf6..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/CommandDummy.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import org.bukkit.Server; -import org.bukkit.command.CommandSender; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionAttachment; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Set; -import java.util.UUID; - -public class CommandDummy implements CommandSender { - @Override - public void sendMessage(@NotNull String message) { - - } - - @Override - public void sendMessage(@NotNull String... messages) { - - } - - @Override - public void sendMessage(@Nullable UUID sender, @NotNull String message) { - - } - - @Override - public void sendMessage(@Nullable UUID sender, @NotNull String... messages) { - - } - - @NotNull - @Override - public Server getServer() { - return null; - } - - @NotNull - @Override - public String getName() { - return null; - } - - @NotNull - @Override - public Spigot spigot() { - return null; - } - - @Override - public boolean isPermissionSet(@NotNull String name) { - return false; - } - - @Override - public boolean isPermissionSet(@NotNull Permission perm) { - return false; - } - - @Override - public boolean hasPermission(@NotNull String name) { - return false; - } - - @Override - public boolean hasPermission(@NotNull Permission perm) { - return false; - } - - @NotNull - @Override - public PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value) { - return null; - } - - @NotNull - @Override - public PermissionAttachment addAttachment(@NotNull Plugin plugin) { - return null; - } - - @Nullable - @Override - public PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value, int ticks) { - return null; - } - - @Nullable - @Override - public PermissionAttachment addAttachment(@NotNull Plugin plugin, int ticks) { - return null; - } - - @Override - public void removeAttachment(@NotNull PermissionAttachment attachment) { - - } - - @Override - public void recalculatePermissions() { - - } - - @NotNull - @Override - public Set getEffectivePermissions() { - return null; - } - - @Override - public boolean isOp() { - return false; - } - - @Override - public void setOp(boolean value) { - - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/Control.java b/src/main/java/com/volmit/iris/util/plugin/Control.java deleted file mode 100644 index d78e8cd83..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/Control.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target(FIELD) -public @interface Control { - -} diff --git a/src/main/java/com/volmit/iris/util/plugin/Controller.java b/src/main/java/com/volmit/iris/util/plugin/Controller.java deleted file mode 100644 index 0aa777552..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/Controller.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.Iris; - -public abstract class Controller implements IController { - private final String name; - private int tickRate; - - public Controller() { - name = getClass().getSimpleName().replaceAll("Controller", "") + " Controller"; - tickRate = -1; - } - - protected void setTickRate(@SuppressWarnings("SameParameterValue") int rate) { - this.tickRate = rate; - } - - protected void disableTicking() { - setTickRate(-1); - } - - @Override - public void l(Object l) { - Iris.info("[" + getName() + "]: " + l); - } - - @Override - public void w(Object l) { - Iris.warn("[" + getName() + "]: " + l); - } - - @Override - public void f(Object l) { - Iris.error("[" + getName() + "]: " + l); - } - - @Override - public void v(Object l) { - Iris.verbose("[" + getName() + "]: " + l); - } - - @Override - public String getName() { - return name; - } - - @Override - public abstract void start(); - - @Override - public abstract void stop(); - - @Override - public abstract void tick(); - - @Override - public int getTickInterval() { - return tickRate; - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/ICommand.java b/src/main/java/com/volmit/iris/util/plugin/ICommand.java deleted file mode 100644 index 3314ac380..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/ICommand.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.util.collection.KList; - -/** - * Represents a pawn command - * - * @author cyberpwn - */ -public interface ICommand { - KList getRequiredPermissions(); - - /** - * Get the name of this command (node) - * - * @return the node - */ - String getNode(); - - /** - * Get all (realized) nodes of this command - * - * @return the nodes - */ - KList getNodes(); - - /** - * Get all (every) node in this command - * - * @return all nodes - */ - KList getAllNodes(); - - /** - * Add a node to this command - * - * @param node - * the node - */ - void addNode(String node); - - /** - * Handle a command. If this is a subcommand, parameters after the subcommand - * will be adapted in args for you - * - * @param sender - * the volume sender (pre-tagged) - * @param args - * the arguments after this command node - * @return return true to mark it as handled - */ - boolean handle(VolmitSender sender, String[] args); - - KList handleTab(VolmitSender sender, String[] args); -} diff --git a/src/main/java/com/volmit/iris/util/plugin/IController.java b/src/main/java/com/volmit/iris/util/plugin/IController.java deleted file mode 100644 index 401780733..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/IController.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import org.bukkit.event.Listener; - -@SuppressWarnings("EmptyMethod") -public interface IController extends Listener { - String getName(); - - void start(); - - void stop(); - - void tick(); - - int getTickInterval(); - - void l(Object l); - - void w(Object l); - - void f(Object l); - - void v(Object l); -} diff --git a/src/main/java/com/volmit/iris/util/plugin/Instance.java b/src/main/java/com/volmit/iris/util/plugin/Instance.java deleted file mode 100644 index 824cf6f8c..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/Instance.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target(FIELD) -public @interface Instance { - -} diff --git a/src/main/java/com/volmit/iris/util/plugin/IrisService.java b/src/main/java/com/volmit/iris/util/plugin/IrisService.java deleted file mode 100644 index a0850418c..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/IrisService.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.Iris; -import org.bukkit.event.Listener; - -public interface IrisService extends Listener { - void onEnable(); - - void onDisable(); - - default void postShutdown(Runnable r) { - Iris.instance.postShutdown(r); - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/Metrics.java b/src/main/java/com/volmit/iris/util/plugin/Metrics.java deleted file mode 100644 index 551a63660..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/Metrics.java +++ /dev/null @@ -1,781 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonPrimitive; -import com.volmit.iris.Iris; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.ServicePriority; - -import javax.net.ssl.HttpsURLConnection; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -/** - * bStats collects some data for plugin authors. - *

- * Check out https://bStats.org/ to learn more about bStats! - */ -@SuppressWarnings({"WeakerAccess", "unused"}) -public class Metrics { - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - // Should failed requests be logged? - private static boolean logFailedRequests; - // Should the sent data be logged? - private static boolean logSentData; - // Should the response text be logged? - private static boolean logResponseStatusText; - // The uuid of the server - private static String serverUUID; - - static { - // You can use the property to disable the check in your test environment - if(System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D - final String defaultPackage = new String( - new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong package names - if(Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - // Is bStats enabled on this server? - private final boolean enabled; - // The plugin - private final Plugin plugin; - - // The plugin id - private final int pluginId; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin - * The plugin which stats should be submitted. - * @param pluginId - * The id of the plugin. - * It can be found at What is my plugin id? - */ - public Metrics(Plugin plugin, int pluginId) { - if(plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - this.pluginId = pluginId; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if(!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - // Should the sent data be logged? - config.addDefault("logSentData", false); - // Should the response text be logged? - config.addDefault("logResponseStatusText", false); - - // Inform the server owners about bStats - config.options().header( - """ - bStats collects some data for plugin authors like how many servers are using their plugins. - To honor their work, you should not disable it. - This has nearly no effect on the server performance! - Check out https://bStats.org/ to learn more :)""" - ).copyDefaults(true); - try { - config.save(configFile); - } catch(IOException e) { - Iris.reportError(e); - } - } - - // Load the data - enabled = true; - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - logSentData = config.getBoolean("logSentData", false); - logResponseStatusText = config.getBoolean("logResponseStatusText", false); - - if(enabled) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for(Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch(NoSuchFieldException e) { - Iris.reportError(e); - } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if(!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Sends the data to the bStats server. - * - * @param plugin - * Any plugin. It's just used to get a logger instance. - * @param data - * The data to send. - * @throws Exception - * If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception { - if(data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if(Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if(logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - try(DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - - StringBuilder builder = new StringBuilder(); - try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - - if(logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder); - } - } - - /** - * Gzips the given String. - * - * @param str - * The string to gzip. - * @return The gzipped String. - * @throws IOException - * If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if(str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try(GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - - /** - * Checks if bStats is enabled. - * - * @return Whether bStats is enabled or not. - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Adds a custom chart. - * - * @param chart - * The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if(chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if(!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() { - JsonObject data = new JsonObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.addProperty("pluginName", pluginName); // Append the name of the plugin - data.addProperty("id", pluginId); // Append the id of the plugin - data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin - JsonArray customCharts = new JsonArray(); - for(CustomChart customChart : charts) { - // Add the data of the custom charts - JsonObject chart = customChart.getRequestJsonObject(); - if(chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.add("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch(Exception e) { - Iris.reportError(e); - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - String bukkitName = Bukkit.getName(); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JsonObject data = new JsonObject(); - - data.addProperty("serverUUID", serverUUID); - - data.addProperty("playerAmount", playerAmount); - data.addProperty("onlineMode", onlineMode); - data.addProperty("bukkitVersion", bukkitVersion); - data.addProperty("bukkitName", bukkitName); - - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JsonObject data = getServerData(); - - JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for(Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - - for(RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); - if(plugin instanceof JsonObject) { - pluginData.add((JsonObject) plugin); - } else { // old bstats version compatibility - try { - Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); - if(plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { - Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); - jsonStringGetter.setAccessible(true); - String jsonString = (String) jsonStringGetter.invoke(plugin); - JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); - pluginData.add(object); - } - } catch(ClassNotFoundException e) { - Iris.reportError(e); - // minecraft version 1.14+ - - if(logFailedRequests) { - this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); - } - } - } - } catch(NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { - Iris.reportError(ignored); - } - } - } catch(NoSuchFieldException e) { - Iris.reportError(e); - } - } - - data.add("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(() -> { - try { - // Send the data - sendData(plugin, data); - } catch(Exception e) { - Iris.reportError(e); - // Something went wrong! :( - if(logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - }).start(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - final String chartId; - - /** - * Class constructor. - * - * @param chartId - * The id of the chart. - */ - CustomChart(String chartId) { - if(chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - private JsonObject getRequestJsonObject() { - JsonObject chart = new JsonObject(); - chart.addProperty("chartId", chartId); - try { - JsonObject data = getChartData(); - if(data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.add("data", data); - } catch(Throwable t) { - Iris.reportError(t); - if(logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JsonObject getChartData() throws Exception; - - } - - /** - * Represents a custom simple pie. - */ - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId - * The id of the chart. - * @param callable - * The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - String value = callable.call(); - if(value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId - * The id of the chart. - * @param callable - * The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if(map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for(Map.Entry entry : map.entrySet()) { - if(entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if(allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom drilldown pie. - */ - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId - * The id of the chart. - * @param callable - * The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map> map = callable.call(); - if(map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for(Map.Entry> entryValues : map.entrySet()) { - JsonObject value = new JsonObject(); - boolean allSkipped = true; - for(Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - value.addProperty(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if(!allSkipped) { - reallyAllSkipped = false; - values.add(entryValues.getKey(), value); - } - } - if(reallyAllSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId - * The id of the chart. - * @param callable - * The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - int value = callable.call(); - if(value == 0) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId - * The id of the chart. - * @param callable - * The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if(map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for(Map.Entry entry : map.entrySet()) { - if(entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if(allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId - * The id of the chart. - * @param callable - * The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if(map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for(Map.Entry entry : map.entrySet()) { - JsonArray categoryValues = new JsonArray(); - categoryValues.add(new JsonPrimitive(entry.getValue())); - values.add(entry.getKey(), categoryValues); - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId - * The id of the chart. - * @param callable - * The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if(map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for(Map.Entry entry : map.entrySet()) { - if(entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JsonArray categoryValues = new JsonArray(); - for(int categoryValue : entry.getValue()) { - categoryValues.add(new JsonPrimitive(categoryValue)); - } - values.add(entry.getKey(), categoryValues); - } - if(allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/plugin/MetricsLite.java b/src/main/java/com/volmit/iris/util/plugin/MetricsLite.java deleted file mode 100644 index 2eaf4e5c9..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/MetricsLite.java +++ /dev/null @@ -1,405 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.volmit.iris.Iris; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.ServicePriority; - -import javax.net.ssl.HttpsURLConnection; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -/** - * bStats collects some data for plugin authors. - *

- * Check out https://bStats.org/ to learn more about bStats! - */ -public class MetricsLite { - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - // Should failed requests be logged? - private static boolean logFailedRequests; - // Should the sent data be logged? - private static boolean logSentData; - // Should the response text be logged? - private static boolean logResponseStatusText; - // The uuid of the server - private static String serverUUID; - - static { - // You can use the property to disable the check in your test environment - if(System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this - // little "trick" ... :D - final String defaultPackage = new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong - // package names - if(MetricsLite.class.getPackage().getName().equals(defaultPackage) || MetricsLite.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - // Is bStats enabled on this server? - private final boolean enabled; - // The plugin - private final Plugin plugin; - - // The plugin id - private final int pluginId; - - /** - * Class constructor. - * - * @param plugin - * The plugin which stats should be submitted. - * @param pluginId - * The id of the plugin. It can be found at - * What is my - * plugin id? - */ - public MetricsLite(Plugin plugin, int pluginId) { - if(plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - this.pluginId = pluginId; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if(!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - // Should the sent data be logged? - config.addDefault("logSentData", false); - // Should the response text be logged? - config.addDefault("logResponseStatusText", false); - - // Inform the server owners about bStats - config.options().header(""" - bStats collects some data for plugin authors like how many servers are using their plugins. - To honor their work, you should not disable it. - This has nearly no effect on the server performance! - Check out https://bStats.org/ to learn more :)""").copyDefaults(true); - try { - config.save(configFile); - } catch(IOException e) { - Iris.reportError(e); - } - } - - // Load the data - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - enabled = config.getBoolean("enabled", true); - logSentData = config.getBoolean("logSentData", false); - logResponseStatusText = config.getBoolean("logResponseStatusText", false); - if(enabled) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for(Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch(NoSuchFieldException e) { - Iris.reportError(e); - } - } - // Register our service - Bukkit.getServicesManager().register(MetricsLite.class, this, plugin, ServicePriority.Normal); - if(!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Sends the data to the bStats server. - * - * @param plugin - * Any plugin. It's just used to get a logger instance. - * @param data - * The data to send. - * @throws Exception - * If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception { - if(data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if(Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if(logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - try(DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - - StringBuilder builder = new StringBuilder(); - try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - - if(logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder); - } - } - - /** - * Gzips the given String. - * - * @param str - * The string to gzip. - * @return The gzipped String. - * @throws IOException - * If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if(str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try(GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - - /** - * Checks if bStats is enabled. - * - * @return Whether bStats is enabled or not. - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if(!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to - // use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the - // stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other - // plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be - // blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() { - JsonObject data = new JsonObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.addProperty("pluginName", pluginName); // Append the name of the plugin - data.addProperty("id", pluginId); // Append the id of the plugin - data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin - data.add("customCharts", new JsonArray()); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: - // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch(Exception e) { - Iris.reportError(e); - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - String bukkitName = Bukkit.getName(); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JsonObject data = new JsonObject(); - - data.addProperty("serverUUID", serverUUID); - - data.addProperty("playerAmount", playerAmount); - data.addProperty("onlineMode", onlineMode); - data.addProperty("bukkitVersion", bukkitVersion); - data.addProperty("bukkitName", bukkitName); - - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JsonObject data = getServerData(); - - JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for(Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - - for(RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); - if(plugin instanceof JsonObject) { - pluginData.add((JsonObject) plugin); - } else { // old bstats version compatibility - try { - Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); - if(plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { - Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); - jsonStringGetter.setAccessible(true); - String jsonString = (String) jsonStringGetter.invoke(plugin); - JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); - pluginData.add(object); - } - } catch(ClassNotFoundException e) { - Iris.reportError(e); - // minecraft version 1.14+ - if(logFailedRequests) { - this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception ", e); - } - } - } - } catch(NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { - Iris.reportError(ignored); - } - } - } catch(NoSuchFieldException e) { - Iris.reportError(e); - } - } - - data.add("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(() -> - { - try { - // Send the data - sendData(plugin, data); - } catch(Exception e) { - Iris.reportError(e); - // Something went wrong! :( - if(logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - }).start(); - } - -} \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/plugin/MortarCommand.java b/src/main/java/com/volmit/iris/util/plugin/MortarCommand.java deleted file mode 100644 index b7c0c03f1..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/MortarCommand.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.format.C; -import org.bukkit.Sound; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.util.Comparator; - -/** - * Represents a pawn command - * - * @author cyberpwn - */ -public abstract class MortarCommand implements ICommand { - private final KList children; - private final KList nodes; - private final KList requiredPermissions; - private final String node; - private String category; - private String description; - - /** - * Override this with a super constructor as most commands shouldn't change - * these parameters - * - * @param node - * the node (primary node) i.e. volume - * @param nodes - * the aliases. i.e. v, vol, bile - */ - public MortarCommand(String node, String... nodes) { - category = ""; - this.node = node; - this.nodes = new KList<>(nodes); - requiredPermissions = new KList<>(); - children = buildChildren(); - description = "No Description"; - } - - @Override - public KList handleTab(VolmitSender sender, String[] args) { - KList v = new KList<>(); - if(args.length == 0) { - for(MortarCommand i : getChildren()) { - v.add(i.getNode()); - } - } - - addTabOptions(sender, args, v); - - if(v.isEmpty()) { - return null; - } - - if(sender.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) { - sender.playSound(Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 0.25f, 1.7f); - } - - return v; - } - - public abstract void addTabOptions(VolmitSender sender, String[] args, KList list); - - public void printHelp(VolmitSender sender) { - boolean b = false; - - for(MortarCommand i : getChildren()) { - for(String j : i.getRequiredPermissions()) { - if(!sender.hasPermission(j)) { - } - } - - b = true; - - sender.sendMessage("" + C.GREEN + i.getNode() + " " + "" + (getArgsUsage().trim().isEmpty() ? "" : (C.WHITE + i.getArgsUsage())) + C.GRAY + " - " + i.getDescription()); - } - - if(!b) { - sender.sendMessage("There are either no sub-commands or you do not have permission to use them."); - } - - if(sender.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) { - sender.playSound(Sound.ITEM_BOOK_PAGE_TURN, 0.28f, 1.4f); - sender.playSound(Sound.ITEM_AXE_STRIP, 0.35f, 1.7f); - } - } - - protected abstract String getArgsUsage(); - - public String getDescription() { - return description; - } - - protected void setDescription(String description) { - this.description = description; - } - - protected void requiresPermission(MortarPermission node) { - if(node == null) { - return; - } - - requiresPermission(node.toString()); - } - - protected void requiresPermission(String node) { - if(node == null) { - return; - } - - requiredPermissions.add(node); - } - - public void rejectAny(int past, VolmitSender sender, String[] a) { - if(a.length > past) { - int p = past; - - StringBuilder m = new StringBuilder(); - - for(String i : a) { - p--; - if(p < 0) { - m.append(i).append(", "); - } - } - - if(!m.toString().trim().isEmpty()) { - sender.sendMessage("Parameters Ignored: " + m); - } - } - } - - @Override - public String getNode() { - return node; - } - - @Override - public KList getNodes() { - return nodes; - } - - @Override - public KList getAllNodes() { - return getNodes().copy().qadd(getNode()); - } - - @Override - public void addNode(String node) { - getNodes().add(node); - } - - public KList getChildren() { - return children; - } - - private KList buildChildren() { - KList p = new KList<>(); - - for(Field i : getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(Command.class)) { - try { - i.setAccessible(true); - MortarCommand pc = (MortarCommand) i.getType().getConstructor().newInstance(); - Command c = i.getAnnotation(Command.class); - - if(!c.value().trim().isEmpty()) { - pc.setCategory(c.value().trim()); - } else { - pc.setCategory(getCategory()); - } - - p.add(pc); - } catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - } - - p.sort(Comparator.comparing(MortarCommand::getNode)); - - return p; - } - - @Override - public KList getRequiredPermissions() { - return requiredPermissions; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/MortarPermission.java b/src/main/java/com/volmit/iris/util/plugin/MortarPermission.java deleted file mode 100644 index 3789663f5..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/MortarPermission.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import org.bukkit.command.CommandSender; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; - -public abstract class MortarPermission { - private MortarPermission parent; - - public MortarPermission() { - for(Field i : getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(Permission.class)) { - try { - MortarPermission px = (MortarPermission) i.getType().getConstructor().newInstance(); - px.setParent(this); - i.set(Modifier.isStatic(i.getModifiers()) ? null : this, px); - } catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - } - } - - public KList getChildren() { - KList p = new KList<>(); - - for(Field i : getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(Permission.class)) { - try { - p.add((MortarPermission) i.get(Modifier.isStatic(i.getModifiers()) ? null : this)); - } catch(IllegalArgumentException | IllegalAccessException | SecurityException e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - } - - return p; - } - - public String getFullNode() { - if(hasParent()) { - return getParent().getFullNode() + "." + getNode(); - } - - return getNode(); - } - - protected abstract String getNode(); - - public abstract String getDescription(); - - public abstract boolean isDefault(); - - @Override - public String toString() { - return getFullNode(); - } - - public boolean hasParent() { - return getParent() != null; - } - - public MortarPermission getParent() { - return parent; - } - - public void setParent(MortarPermission parent) { - this.parent = parent; - } - - public boolean has(CommandSender sender) { - return sender.hasPermission(getFullNode()); - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/Permission.java b/src/main/java/com/volmit/iris/util/plugin/Permission.java deleted file mode 100644 index ef5dcbcd2..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/Permission.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - -@Retention(RUNTIME) -@Target(FIELD) -public @interface Permission { - -} diff --git a/src/main/java/com/volmit/iris/util/plugin/PluginRegistry.java b/src/main/java/com/volmit/iris/util/plugin/PluginRegistry.java deleted file mode 100644 index f2336a306..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/PluginRegistry.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -public class PluginRegistry { - private final KMap registry = new KMap<>(); - @Getter - private final String namespace; - - public void unregisterAll() { - registry.clear(); - } - - public KList getRegistries() { - return registry.k(); - } - - public T get(String s) { - if(!registry.containsKey(s)) { - return null; - } - - return registry.get(s); - } - - public void register(String s, T t) { - registry.put(s, t); - } - - public void unregister(String s) { - registry.remove(s); - } - - public T resolve(String id) { - if(registry.isEmpty()) { - return null; - } - - return registry.get(id); - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/PluginRegistryGroup.java b/src/main/java/com/volmit/iris/util/plugin/PluginRegistryGroup.java deleted file mode 100644 index 9ecbe60b2..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/PluginRegistryGroup.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; - -public class PluginRegistryGroup { - private final KMap> registries = new KMap<>(); - - public T resolve(String namespace, String id) { - if(registries.isEmpty()) { - return null; - } - - PluginRegistry r = registries.get(namespace); - if(r == null) { - return null; - } - - return r.resolve(id); - } - - public void clearRegistries() { - registries.clear(); - } - - public void removeRegistry(String namespace) { - registries.remove(namespace); - } - - public PluginRegistry getRegistry(String namespace) { - return registries.computeIfAbsent(namespace, PluginRegistry::new); - } - - public KList compile() { - KList l = new KList<>(); - registries.values().forEach((i) - -> i.getRegistries().forEach((j) - -> l.add(i.getNamespace() + ":" + j))); - return l; - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/RouterCommand.java b/src/main/java/com/volmit/iris/util/plugin/RouterCommand.java deleted file mode 100644 index 91c71b6db..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/RouterCommand.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -/** - * Assistive command router - * - * @author cyberpwn - */ -public class RouterCommand extends org.bukkit.command.Command { - private final CommandExecutor ex; - private String usage; - - /** - * The router command routes commands to bukkit executors - * - * @param realCommand - * the real command - * @param ex - * the executor - */ - public RouterCommand(ICommand realCommand, CommandExecutor ex) { - super(realCommand.getNode().toLowerCase()); - setAliases(realCommand.getNodes()); - - this.ex = ex; - } - - - @Override - public Command setUsage(String u) { - this.usage = u; - return this; - } - - - @Override - public String getUsage() { - return usage; - } - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - return ex.onCommand(sender, this, commandLabel, args); - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/VirtualCommand.java b/src/main/java/com/volmit/iris/util/plugin/VirtualCommand.java deleted file mode 100644 index 187f75661..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/VirtualCommand.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.reflect.V; -import org.bukkit.Bukkit; -import org.bukkit.Sound; -import org.bukkit.command.CommandSender; - -import java.lang.reflect.Field; - -/** - * Represents a virtual command. A chain of iterative processing through - * subcommands. - * - * @author cyberpwn - */ -public class VirtualCommand { - private final ICommand command; - private final String tag; - - private final KMap, VirtualCommand> children; - - public VirtualCommand(ICommand command) { - this(command, ""); - } - - public VirtualCommand(ICommand command, String tag) { - this.command = command; - children = new KMap<>(); - this.tag = tag; - - for(Field i : command.getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(Command.class)) { - try { - Command cc = i.getAnnotation(Command.class); - ICommand cmd = (ICommand) i.getType().getConstructor().newInstance(); - new V(command, true, true).set(i.getName(), cmd); - children.put(cmd.getAllNodes(), new VirtualCommand(cmd, cc.value().trim().isEmpty() ? tag : cc.value().trim())); - } catch(Exception e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - } - } - - public String getTag() { - return tag; - } - - public ICommand getCommand() { - return command; - } - - public KMap, VirtualCommand> getChildren() { - return children; - } - - public boolean hit(CommandSender sender, KList chain) { - return hit(sender, chain, null); - } - - public boolean hit(CommandSender sender, KList chain, String label) { - VolmitSender vs = new VolmitSender(sender); - vs.setTag(tag); - - if(label != null) { - vs.setCommand(label); - } - - if(chain.isEmpty()) { - if(!checkPermissions(sender, command)) { - return true; - } - - return command.handle(vs, new String[0]); - } - - String nl = chain.get(0); - - for(KList i : children.k()) { - for(String j : i) { - if(j.equalsIgnoreCase(nl)) { - vs.setCommand(chain.get(0)); - VirtualCommand cmd = children.get(i); - KList c = chain.copy(); - c.remove(0); - if(cmd.hit(sender, c, vs.getCommand())) { - if(vs.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) { - vs.player().getWorld().playSound(vs.player().getLocation(), Sound.ITEM_AXE_STRIP, 0.35f, 1.8f); - } - - return true; - } - } - } - } - - if(!checkPermissions(sender, command)) { - return true; - } - - return command.handle(vs, chain.toArray(new String[0])); - } - - public KList hitTab(CommandSender sender, KList chain, String label) { - VolmitSender vs = new VolmitSender(sender); - vs.setTag(tag); - - if(label != null) - vs.setCommand(label); - - if(chain.isEmpty()) { - if(!checkPermissions(sender, command)) { - return null; - } - - return command.handleTab(vs, new String[0]); - } - - String nl = chain.get(0); - - for(KList i : children.k()) { - for(String j : i) { - if(j.equalsIgnoreCase(nl)) { - vs.setCommand(chain.get(0)); - VirtualCommand cmd = children.get(i); - KList c = chain.copy(); - c.remove(0); - KList v = cmd.hitTab(sender, c, vs.getCommand()); - if(v != null) { - return v; - } - } - } - } - - if(!checkPermissions(sender, command)) { - return null; - } - - return command.handleTab(vs, chain.toArray(new String[0])); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - private boolean checkPermissions(CommandSender sender, ICommand command2) { - boolean failed = false; - - for(String i : command.getRequiredPermissions()) { - if(!sender.hasPermission(i)) { - failed = true; - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> sender.sendMessage("- " + C.WHITE + i), 0); - } - } - - if(failed) { - sender.sendMessage("Insufficient Permissions"); - return false; - } - - return true; - } -} diff --git a/src/main/java/com/volmit/iris/util/plugin/VolmitPlugin.java b/src/main/java/com/volmit/iris/util/plugin/VolmitPlugin.java deleted file mode 100644 index 0044a8e38..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/VolmitPlugin.java +++ /dev/null @@ -1,546 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.reflect.V; -import com.volmit.iris.util.scheduling.J; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandMap; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.command.SimpleCommandMap; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.permissions.PermissionDefault; -import org.bukkit.plugin.java.JavaPlugin; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -@SuppressWarnings("EmptyMethod") -public abstract class VolmitPlugin extends JavaPlugin implements Listener { - public static final boolean bad = false; - private KMap, VirtualCommand> commands; - private KList commandCache; - private KList permissionCache; - - public File getJarFile() { - return getFile(); - } - - public void l(Object l) { - Iris.info("[" + getName() + "]: " + l); - } - - public void w(Object l) { - Iris.warn("[" + getName() + "]: " + l); - } - - public void f(Object l) { - Iris.error("[" + getName() + "]: " + l); - } - - public void v(Object l) { - Iris.verbose("[" + getName() + "]: " + l); - } - - public void onEnable() { - registerInstance(); - registerPermissions(); - registerCommands(); - J.a(this::outputInfo); - registerListener(this); - start(); - } - - public void unregisterAll() { - unregisterListeners(); - unregisterCommands(); - unregisterPermissions(); - unregisterInstance(); - } - - private void outputInfo() { - try { - IO.delete(getDataFolder("info")); - getDataFolder("info").mkdirs(); - outputPluginInfo(); - outputCommandInfo(); - outputPermissionInfo(); - } catch(Throwable e) { - Iris.reportError(e); - - } - } - - private void outputPermissionInfo() throws IOException { - FileConfiguration fc = new YamlConfiguration(); - - for(MortarPermission i : permissionCache) { - chain(i, fc); - } - - fc.save(getDataFile("info", "permissions.yml")); - } - - private void chain(MortarPermission i, FileConfiguration fc) { - KList ff = new KList<>(); - - for(MortarPermission j : i.getChildren()) { - ff.add(j.getFullNode()); - } - - fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "description", i.getDescription()); - fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "default", i.isDefault()); - fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "children", ff); - - for(MortarPermission j : i.getChildren()) { - chain(j, fc); - } - } - - private void outputCommandInfo() throws IOException { - FileConfiguration fc = new YamlConfiguration(); - - for(MortarCommand i : commandCache) { - chain(i, "/", fc); - } - - fc.save(getDataFile("info", "commands.yml")); - } - - private void chain(MortarCommand i, String c, FileConfiguration fc) { - String n = c + (c.length() == 1 ? "" : " ") + i.getNode(); - fc.set(n + "." + "description", i.getDescription()); - fc.set(n + "." + "required-permissions", i.getRequiredPermissions()); - fc.set(n + "." + "aliases", i.getAllNodes()); - - for(MortarCommand j : i.getChildren()) { - chain(j, n, fc); - } - } - - private void outputPluginInfo() throws IOException { - FileConfiguration fc = new YamlConfiguration(); - fc.set("version", getDescription().getVersion()); - fc.set("name", getDescription().getName()); - fc.save(getDataFile("info", "plugin.yml")); - } - - private void registerPermissions() { - permissionCache = new KList<>(); - - for(Field i : getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(Permission.class)) { - try { - i.setAccessible(true); - MortarPermission pc = (MortarPermission) i.getType().getConstructor().newInstance(); - i.set(Modifier.isStatic(i.getModifiers()) ? null : this, pc); - registerPermission(pc); - permissionCache.add(pc); - v("Registered Permissions " + pc.getFullNode() + " (" + i.getName() + ")"); - } catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - Iris.reportError(e); - w("Failed to register permission (field " + i.getName() + ")"); - e.printStackTrace(); - } - } - } - - for(org.bukkit.permissions.Permission i : computePermissions()) { - try { - Bukkit.getPluginManager().addPermission(i); - } catch(Throwable e) { - Iris.reportError(e); - - } - } - } - - private KList computePermissions() { - KList g = new KList<>(); - for(Field i : getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(Permission.class)) { - try { - MortarPermission x = (MortarPermission) i.get(Modifier.isStatic(i.getModifiers()) ? null : this); - g.add(toPermission(x)); - g.addAll(computePermissions(x)); - } catch(IllegalArgumentException | IllegalAccessException | SecurityException e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - } - - return g.removeDuplicates(); - } - - private KList computePermissions(MortarPermission p) { - KList g = new KList<>(); - - if(p == null) { - return g; - } - - for(MortarPermission i : p.getChildren()) { - if(i == null) { - continue; - } - - g.add(toPermission(i)); - g.addAll(computePermissions(i)); - } - - return g; - } - - private org.bukkit.permissions.Permission toPermission(MortarPermission p) { - if(p == null) { - return null; - } - - org.bukkit.permissions.Permission perm = new org.bukkit.permissions.Permission(p.getFullNode() + (p.hasParent() ? "" : ".*")); - perm.setDescription(p.getDescription() == null ? "" : p.getDescription()); - perm.setDefault(p.isDefault() ? PermissionDefault.TRUE : PermissionDefault.OP); - - for(MortarPermission i : p.getChildren()) { - perm.getChildren().put(i.getFullNode(), true); - } - - return perm; - } - - private void registerPermission(MortarPermission pc) { - - } - - @Override - public void onDisable() { - stop(); - Bukkit.getScheduler().cancelTasks(this); - unregisterListener(this); - unregisterAll(); - } - - private void tickController(IController i) { - if(bad) { - return; - } - - if(i.getTickInterval() < 0) { - return; - } - - M.tick++; - if(M.interval(i.getTickInterval())) { - try { - i.tick(); - } catch(Throwable e) { - w("Failed to tick controller " + i.getName()); - e.printStackTrace(); - Iris.reportError(e); - } - } - } - - private void registerInstance() { - if(bad) { - return; - } - for(Field i : getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(Instance.class)) { - try { - i.setAccessible(true); - i.set(Modifier.isStatic(i.getModifiers()) ? null : this, this); - v("Registered Instance " + i.getName()); - } catch(IllegalArgumentException | IllegalAccessException | SecurityException e) { - w("Failed to register instance (field " + i.getName() + ")"); - e.printStackTrace(); - Iris.reportError(e); - } - } - } - } - - private void unregisterInstance() { - if(bad) { - return; - } - for(Field i : getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(Instance.class)) { - try { - i.setAccessible(true); - i.set(Modifier.isStatic(i.getModifiers()) ? null : this, null); - v("Unregistered Instance " + i.getName()); - } catch(IllegalArgumentException | IllegalAccessException | SecurityException e) { - w("Failed to unregister instance (field " + i.getName() + ")"); - e.printStackTrace(); - Iris.reportError(e); - } - } - } - } - - private void registerCommands() { - if(bad) { - return; - } - commands = new KMap<>(); - commandCache = new KList<>(); - - for(Field i : getClass().getDeclaredFields()) { - if(i.isAnnotationPresent(com.volmit.iris.util.plugin.Command.class)) { - try { - i.setAccessible(true); - MortarCommand pc = (MortarCommand) i.getType().getConstructor().newInstance(); - com.volmit.iris.util.plugin.Command c = i.getAnnotation(com.volmit.iris.util.plugin.Command.class); - registerCommand(pc, c.value()); - commandCache.add(pc); - v("Registered Commands /" + pc.getNode() + " (" + i.getName() + ")"); - } catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - w("Failed to register command (field " + i.getName() + ")"); - e.printStackTrace(); - Iris.reportError(e); - } - } - } - } - - - @Override - public List onTabComplete(CommandSender sender, Command command, - String alias, String[] args) { - KList chain = new KList<>(); - - for(String i : args) { - if(i.trim().isEmpty()) { - continue; - } - - chain.add(i.trim()); - } - - for(KList i : commands.k()) { - for(String j : i) { - if(j.equalsIgnoreCase(alias)) { - VirtualCommand cmd = commands.get(i); - - List v = cmd.hitTab(sender, chain.copy(), alias); - if(v != null) { - return v; - } - } - } - } - - return super.onTabComplete(sender, command, alias, args); - } - - @Override - public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) { - if(bad) { - return false; - } - - KList chain = new KList<>(); - chain.add(args); - - for(KList i : commands.k()) { - for(String j : i) { - if(j.equalsIgnoreCase(label)) { - VirtualCommand cmd = commands.get(i); - - if(cmd.hit(sender, chain.copy(), label)) { - return true; - } - } - } - } - - return false; - } - - public void registerCommand(ICommand cmd) { - registerCommand(cmd, ""); - } - - public void registerCommand(ICommand cmd, String subTag) { - if(bad) { - return; - } - - commands.put(cmd.getAllNodes(), new VirtualCommand(cmd, subTag.trim().isEmpty() ? getTag() : getTag(subTag.trim()))); - PluginCommand cc = getCommand(cmd.getNode().toLowerCase()); - - if(cc != null) { - cc.setExecutor(this); - cc.setUsage(getName() + ":" + getClass().toString() + ":" + cmd.getNode()); - } else { - RouterCommand r = new RouterCommand(cmd, this); - r.setUsage(getName() + ":" + getClass().toString()); - ((CommandMap) new V(Bukkit.getServer()).get("commandMap")).register("", r); - } - } - - public void unregisterCommand(ICommand cmd) { - if(bad) { - return; - } - try { - SimpleCommandMap m = new V(Bukkit.getServer()).get("commandMap"); - - Map k = new V(m).get("knownCommands"); - - for(Iterator> it = k.entrySet().iterator(); it.hasNext(); ) { - Map.Entry entry = it.next(); - if(entry.getValue() instanceof Command) { - org.bukkit.command.Command c = entry.getValue(); - String u = c.getUsage(); - - if(u != null && u.equals(getName() + ":" + getClass().toString() + ":" + cmd.getNode())) { - if(c.unregister(m)) { - it.remove(); - v("Unregistered Command /" + cmd.getNode()); - } else { - Bukkit.getConsoleSender().sendMessage(getTag() + "Failed to unregister command " + c.getName()); - } - } - } - } - } catch(Throwable e) { - e.printStackTrace(); - Iris.reportError(e); - } - } - - public String getTag() { - if(bad) { - return ""; - } - return getTag(""); - } - - public void registerListener(Listener l) { - Iris.debug("Register Listener " + l.getClass().getSimpleName()); - Bukkit.getPluginManager().registerEvents(l, this); - } - - public void unregisterListener(Listener l) { - Iris.debug("Register Listener " + l.getClass().getSimpleName()); - HandlerList.unregisterAll(l); - } - - public void unregisterListeners() { - if(bad) { - return; - } - HandlerList.unregisterAll((Listener) this); - } - - public void unregisterCommands() { - if(bad) { - return; - } - for(VirtualCommand i : commands.v()) { - try { - unregisterCommand(i.getCommand()); - } catch(Throwable e) { - Iris.reportError(e); - - } - } - } - - private void unregisterPermissions() { - if(bad) { - return; - } - for(org.bukkit.permissions.Permission i : computePermissions()) { - Bukkit.getPluginManager().removePermission(i); - v("Unregistered Permission " + i.getName()); - } - } - - public File getDataFile(String... strings) { - File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator)); - f.getParentFile().mkdirs(); - return f; - } - - public File getDataFileList(String pre, String[] strings) { - KList v = new KList<>(strings); - v.add(0, pre); - File f = new File(getDataFolder(), v.toString(File.separator)); - f.getParentFile().mkdirs(); - return f; - } - - public File getDataFolder(String... strings) { - if(strings.length == 0) { - return super.getDataFolder(); - } - - File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator)); - f.mkdirs(); - - return f; - } - - public File getDataFolderNoCreate(String... strings) { - if(strings.length == 0) { - return super.getDataFolder(); - } - - File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator)); - - return f; - } - - public File getDataFolderList(String pre, String[] strings) { - KList v = new KList<>(strings); - v.add(0, pre); - if(v.size() == 0) { - return super.getDataFolder(); - } - File f = new File(getDataFolder(), v.toString(File.separator)); - f.mkdirs(); - - return f; - } - - public abstract void start(); - - public abstract void stop(); - - public abstract String getTag(String subTag); -} diff --git a/src/main/java/com/volmit/iris/util/plugin/VolmitSender.java b/src/main/java/com/volmit/iris/util/plugin/VolmitSender.java deleted file mode 100644 index 51864039a..000000000 --- a/src/main/java/com/volmit/iris/util/plugin/VolmitSender.java +++ /dev/null @@ -1,607 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.plugin; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.IrisSettings; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.decree.DecreeParameter; -import com.volmit.iris.util.decree.virtual.VirtualDecreeCommand; -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.scheduling.J; -import lombok.Getter; -import lombok.Setter; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.title.Title; -import org.bukkit.Server; -import org.bukkit.Sound; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionAttachment; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.Plugin; - -import java.time.Duration; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; - -/** - * Represents a volume sender. A command sender with extra crap in it - * - * @author cyberpwn - */ -public class VolmitSender implements CommandSender { - @Getter - private static final KMap helpCache = new KMap<>(); - private final CommandSender s; - private String tag; - @Getter - @Setter - private String command; - - /** - * Wrap a command sender - * - * @param s - * the command sender - */ - public VolmitSender(CommandSender s) { - tag = ""; - this.s = s; - } - - public VolmitSender(CommandSender s, String tag) { - this.tag = tag; - this.s = s; - } - - public static long getTick() { - return M.ms() / 16; - } - - public static String pulse(String colorA, String colorB, double speed) { - return ""; - } - - public static String pulse(double speed) { - return Form.f(invertSpread((((getTick() * 15D * speed) % 1000D) / 1000D)), 3).replaceAll("\\Q,\\E", ".").replaceAll("\\Q?\\E", "-"); - } - - public static double invertSpread(double v) { - return ((1D - v) * 2D) - 1D; - } - - public static KList paginate(KList all, int linesPerPage, int page, AtomicBoolean hasNext) { - int totalPages = (int) Math.ceil((double) all.size() / linesPerPage); - page = page < 0 ? 0 : page >= totalPages ? totalPages - 1 : page; - hasNext.set(page < totalPages - 1); - KList d = new KList<>(); - - for(int i = linesPerPage * page; i < Math.min(all.size(), linesPerPage * (page + 1)); i++) { - d.add(all.get(i)); - } - - return d; - } - - /** - * Get the command tag - * - * @return the command tag - */ - public String getTag() { - return tag; - } - - /** - * Set a command tag (prefix for sendMessage) - * - * @param tag - * the tag - */ - public void setTag(String tag) { - this.tag = tag; - } - - /** - * Is this sender a player? - * - * @return true if it is - */ - public boolean isPlayer() { - return getS() instanceof Player; - } - - /** - * Force cast to player (be sure to check first) - * - * @return a casted player - */ - public Player player() { - return (Player) getS(); - } - - /** - * Get the origin sender this object is wrapping - * - * @return the command sender - */ - public CommandSender getS() { - return s; - } - - @Override - public boolean isPermissionSet(String name) { - return s.isPermissionSet(name); - } - - @Override - public boolean isPermissionSet(Permission perm) { - return s.isPermissionSet(perm); - } - - @Override - public boolean hasPermission(String name) { - return s.hasPermission(name); - } - - @Override - public boolean hasPermission(Permission perm) { - return s.hasPermission(perm); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return s.addAttachment(plugin, name, value); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin) { - return s.addAttachment(plugin); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { - return s.addAttachment(plugin, name, value, ticks); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return s.addAttachment(plugin, ticks); - } - - @Override - public void removeAttachment(PermissionAttachment attachment) { - s.removeAttachment(attachment); - } - - @Override - public void recalculatePermissions() { - s.recalculatePermissions(); - } - - @Override - public Set getEffectivePermissions() { - return s.getEffectivePermissions(); - } - - @Override - public boolean isOp() { - return s.isOp(); - } - - @Override - public void setOp(boolean value) { - s.setOp(value); - } - - public void hr() { - s.sendMessage("========================================================"); - } - - public void sendTitle(String title, String subtitle, int i, int s, int o) { - Iris.audiences.player(player()).showTitle(Title.title( - createComponent(title), - createComponent(subtitle), - Title.Times.times(Duration.ofMillis(i), Duration.ofMillis(s), Duration.ofMillis(o)))); - } - - public void sendProgress(double percent, String thing) { - //noinspection IfStatementWithIdenticalBranches - if(percent < 0) { - int l = 44; - int g = (int) (1D * l); - sendTitle(C.IRIS + thing + " ", 0, 500, 250); - sendActionNoProcessing("" + "" + pulse("#00ff80", "#00373d", 1D) + " " + Form.repeat(" ", g) + "" + Form.repeat(" ", l - g)); - } else { - int l = 44; - int g = (int) (percent * l); - sendTitle(C.IRIS + thing + " " + C.BLUE + "" + Form.pc(percent, 0), 0, 500, 250); - sendActionNoProcessing("" + "" + pulse("#00ff80", "#00373d", 1D) + " " + Form.repeat(" ", g) + "" + Form.repeat(" ", l - g)); - } - } - - public void sendAction(String action) { - Iris.audiences.player(player()).sendActionBar(createNoPrefixComponent(action)); - } - - public void sendActionNoProcessing(String action) { - Iris.audiences.player(player()).sendActionBar(createNoPrefixComponentNoProcessing(action)); - } - - public void sendTitle(String subtitle, int i, int s, int o) { - Iris.audiences.player(player()).showTitle(Title.title( - createNoPrefixComponent(" "), - createNoPrefixComponent(subtitle), - Title.Times.times(Duration.ofMillis(i), Duration.ofMillis(s), Duration.ofMillis(o)))); - } - - private Component createNoPrefixComponent(String message) { - if(!IrisSettings.get().getGeneral().canUseCustomColors(this)) { - String t = C.translateAlternateColorCodes('&', MiniMessage.miniMessage().stripTags(message)); - return MiniMessage.miniMessage().deserialize(t); - } - - String t = C.translateAlternateColorCodes('&', message); - String a = C.aura(t, IrisSettings.get().getGeneral().getSpinh(), IrisSettings.get().getGeneral().getSpins(), IrisSettings.get().getGeneral().getSpinb(), 0.36); - return MiniMessage.miniMessage().deserialize(a); - } - - private Component createNoPrefixComponentNoProcessing(String message) { - return MiniMessage.builder().postProcessor(c -> c).build().deserialize(message); - } - - private Component createComponent(String message) { - if(!IrisSettings.get().getGeneral().canUseCustomColors(this)) { - String t = C.translateAlternateColorCodes('&', MiniMessage.miniMessage().stripTags(getTag() + message)); - return MiniMessage.miniMessage().deserialize(t); - } - - String t = C.translateAlternateColorCodes('&', getTag() + message); - String a = C.aura(t, IrisSettings.get().getGeneral().getSpinh(), IrisSettings.get().getGeneral().getSpins(), IrisSettings.get().getGeneral().getSpinb()); - return MiniMessage.miniMessage().deserialize(a); - } - - private Component createComponentRaw(String message) { - if(!IrisSettings.get().getGeneral().canUseCustomColors(this)) { - String t = C.translateAlternateColorCodes('&', MiniMessage.miniMessage().stripTags(getTag() + message)); - return MiniMessage.miniMessage().deserialize(t); - } - - String t = C.translateAlternateColorCodes('&', getTag() + message); - return MiniMessage.miniMessage().deserialize(t); - } - - public void showWaiting(String passive, CompletableFuture f) { - AtomicInteger v = new AtomicInteger(); - AtomicReference g = new AtomicReference<>(); - v.set(J.ar(() -> { - if(f.isDone() && g.get() != null) { - J.car(v.get()); - sendAction(" "); - return; - } - - sendProgress(-1, passive); - }, 0)); - J.a(() -> { - try { - g.set(f.get()); - } catch(InterruptedException e) { - e.printStackTrace(); - } catch(ExecutionException e) { - e.printStackTrace(); - } - }); - - } - - @Override - public void sendMessage(String message) { - if(s instanceof CommandDummy) { - return; - } - - if((!IrisSettings.get().getGeneral().isUseCustomColorsIngame() && s instanceof Player) || !IrisSettings.get().getGeneral().isUseConsoleCustomColors()) { - s.sendMessage(C.translateAlternateColorCodes('&', getTag() + message)); - return; - } - - if(message.contains("")) { - s.sendMessage(C.translateAlternateColorCodes('&', getTag() + message.replaceAll("\\Q\\E", ""))); - return; - } - - try { - Iris.audiences.sender(s).sendMessage(createComponent(message)); - } catch(Throwable e) { - String t = C.translateAlternateColorCodes('&', getTag() + message); - String a = C.aura(t, IrisSettings.get().getGeneral().getSpinh(), IrisSettings.get().getGeneral().getSpins(), IrisSettings.get().getGeneral().getSpinb()); - - Iris.debug("Failure to parse " + a); - s.sendMessage(C.translateAlternateColorCodes('&', getTag() + message)); - } - } - - public void sendMessageBasic(String message) { - s.sendMessage(C.translateAlternateColorCodes('&', getTag() + message)); - } - - public void sendMessageRaw(String message) { - if(s instanceof CommandDummy) { - return; - } - - if((!IrisSettings.get().getGeneral().isUseCustomColorsIngame() && s instanceof Player) || !IrisSettings.get().getGeneral().isUseConsoleCustomColors()) { - s.sendMessage(C.translateAlternateColorCodes('&', message)); - return; - } - - if(message.contains("")) { - s.sendMessage(message.replaceAll("\\Q\\E", "")); - return; - } - - try { - Iris.audiences.sender(s).sendMessage(createComponentRaw(message)); - } catch(Throwable e) { - String t = C.translateAlternateColorCodes('&', getTag() + message); - String a = C.aura(t, IrisSettings.get().getGeneral().getSpinh(), IrisSettings.get().getGeneral().getSpins(), IrisSettings.get().getGeneral().getSpinb()); - - Iris.debug("Failure to parse " + a); - s.sendMessage(C.translateAlternateColorCodes('&', getTag() + message)); - } - } - - @Override - public void sendMessage(String[] messages) { - for(String str : messages) - sendMessage(str); - } - - @Override - public void sendMessage(UUID uuid, String message) { - sendMessage(message); - } - - @Override - public void sendMessage(UUID uuid, String[] messages) { - sendMessage(messages); - } - - @Override - public Server getServer() { - return s.getServer(); - } - - @Override - public String getName() { - return s.getName(); - } - - @Override - public Spigot spigot() { - return s.spigot(); - } - - private String pickRandoms(int max, VirtualDecreeCommand i) { - KList m = new KList<>(); - for(int ix = 0; ix < max; ix++) { - m.add((i.isNode() - ? (i.getNode().getParameters().isNotEmpty()) - ? "<#aebef2>✦ <#5ef288>" - + i.getParentPath() - + " <#42ecf5>" - + i.getName() + " " - + i.getNode().getParameters().shuffleCopy(RNG.r).convert((f) - -> (f.isRequired() || RNG.r.b(0.5) - ? "<#f2e15e>" + f.getNames().getRandom() + "=" - + "<#d665f0>" + f.example() - : "")) - .toString(" ") - : "" - : "")); - } - - return m.removeDuplicates().convert((iff) -> iff.replaceAll("\\Q \\E", " ")).toString("\n"); - } - - public void sendHeader(String name, int overrideLength) { - int len = overrideLength; - int h = name.length() + 2; - String s = Form.repeat(" ", len - h - 4); - String si = Form.repeat("(", 3); - String so = Form.repeat(")", 3); - String sf = "["; - String se = "]"; - - if(name.trim().isEmpty()) { - sendMessageRaw("" + sf + s + "" + s + se); - } else { - sendMessageRaw("" + sf + s + si + " " + name + " " + so + s + se); - } - } - - public void sendHeader(String name) { - sendHeader(name, 44); - } - - public void sendDecreeHelp(VirtualDecreeCommand v) { - sendDecreeHelp(v, 0); - } - - public void sendDecreeHelp(VirtualDecreeCommand v, int page) { - if(!isPlayer()) { - for(VirtualDecreeCommand i : v.getNodes()) { - sendDecreeHelpNode(i); - } - - return; - } - - int m = v.getNodes().size(); - - sendMessageRaw("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); - - if(v.getNodes().isNotEmpty()) { - sendHeader(v.getPath() + (page > 0 ? (" {" + (page + 1) + "}") : "")); - if(isPlayer() && v.getParent() != null) { - sendMessageRaw("Click to go back to <#3299bf>" + Form.capitalize(v.getParent().getName()) + " Help" + "'><#f58571>〈 Back"); - } - - AtomicBoolean next = new AtomicBoolean(false); - for(VirtualDecreeCommand i : paginate(v.getNodes(), 17, page, next)) { - sendDecreeHelpNode(i); - } - - String s = ""; - int l = 75 - (page > 0 ? 10 : 0) - (next.get() ? 10 : 0); - - if(page > 0) { - s += "Click to go back to page " + page + "'>〈 Page " + page + " "; - } - - s += "" + Form.repeat(" ", l) + ""; - - if(next.get()) { - s += " Click to go to back to page " + (page + 2) + "'>Page " + (page + 2) + " ❭"; - } - - sendMessageRaw(s); - } else { - sendMessage(C.RED + "There are no subcommands in this group! Contact support, this is a command design issue!"); - } - } - - public void sendDecreeHelpNode(VirtualDecreeCommand i) { - if(isPlayer() || s instanceof CommandDummy) { - sendMessageRaw(helpCache.computeIfAbsent(i.getPath(), (k) -> { - String newline = "\n"; - - /// Command - // Contains main command & aliases - String realText = i.getPath() + " >" + "<#46826a>⇀ " + i.getName(); - String hoverTitle = i.getNames().copy().reverse().convert((f) -> "<#42ecf5>" + f).toString(", "); - String description = "<#3fe05a>✎ <#6ad97d>" + i.getDescription(); - String usage = "<#bbe03f>✒ <#a8e0a2>"; - String onClick; - if(i.isNode()) { - if(i.getNode().getParameters().isEmpty()) { - usage += "There are no parameters. Click to type command."; - onClick = "suggest_command"; - } else { - usage += "Hover over all of the parameters to learn more."; - onClick = "suggest_command"; - } - } else { - usage += "This is a command category. Click to run."; - onClick = "run_command"; - } - - String suggestion = ""; - String suggestions = ""; - if(i.isNode() && i.getNode().getParameters().isNotEmpty()) { - suggestion += newline + "<#aebef2>✦ <#5ef288>" + i.getParentPath() + " <#42ecf5>" + i.getName() + " " - + i.getNode().getParameters().convert((f) -> "<#d665f0>" + f.example()).toString(" "); - suggestions += newline + "" + pickRandoms(Math.min(i.getNode().getParameters().size() + 1, 5), i); - } - - /// Params - StringBuilder nodes = new StringBuilder(); - if(i.isNode()) { - for(DecreeParameter p : i.getNode().getParameters()) { - - String nTitle = "" + p.getName(); - String nHoverTitle = p.getNames().convert((ff) -> "<#d665f0>" + ff).toString(", "); - String nDescription = "<#3fe05a>✎ <#6ad97d>" + p.getDescription(); - String nUsage; - String fullTitle; - Iris.debug("Contextual: " + p.isContextual() + " / player: " + isPlayer()); - if(p.isContextual() && (isPlayer() || s instanceof CommandDummy)) { - fullTitle = "<#ffcc00>[" + nTitle + "<#ffcc00>] "; - nUsage = "<#ff9900>➱ <#ffcc00>The value may be derived from environment context."; - } else if(p.isRequired()) { - fullTitle = "[" + nTitle + "] "; - nUsage = "<#db4321>⚠ <#faa796>This parameter is required."; - } else if(p.hasDefault()) { - fullTitle = "<#4f4f4f>⊰" + nTitle + "<#4f4f4f>⊱"; - nUsage = "<#2181db>✔ <#78dcf0>Defaults to \"" + p.getParam().defaultValue() + "\" if undefined."; - } else { - fullTitle = "<#4f4f4f>⊰" + nTitle + "<#4f4f4f>⊱"; - nUsage = "<#a73abd>✔ <#78dcf0>This parameter is optional."; - } - String type = "<#cc00ff>✢ <#ff33cc>This parameter is of type " + p.getType().getSimpleName() + "."; - - nodes - .append("") - .append(fullTitle) - .append(""); - } - } else { - nodes = new StringBuilder(" - Category of Commands"); - } - - /// Wrapper - String wrapper = - "" + - "" + - "" + - " " + - nodes; - - return wrapper; - })); - } else { - sendMessage(i.getPath()); - } - } - - public void playSound(Sound sound, float volume, float pitch) { - if(isPlayer()) { - player().playSound(player().getLocation(), sound, volume, pitch); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/reflect/ShadeFix.java b/src/main/java/com/volmit/iris/util/reflect/ShadeFix.java deleted file mode 100644 index 204b1f8be..000000000 --- a/src/main/java/com/volmit/iris/util/reflect/ShadeFix.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.reflect; - -public class ShadeFix { - public static void fix(Class c) { - c.getCanonicalName(); - } -} diff --git a/src/main/java/com/volmit/iris/util/reflect/V.java b/src/main/java/com/volmit/iris/util/reflect/V.java deleted file mode 100644 index 7e6f7296a..000000000 --- a/src/main/java/com/volmit/iris/util/reflect/V.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.reflect; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; - -import java.lang.annotation.Annotation; - -public class V { - private final Object o; - private boolean local; - private boolean suppress = false; - - public V(Class c, Object... parameters) { - this.o = Violator.construct(c, parameters); - this.local = true; - } - - public V(Object o) { - this.o = o; - this.local = true; - } - - public V(Object o, boolean local, boolean suppress) { - this(o); - this.local = local; - this.suppress = suppress; - } - - public V(Object o, boolean local) { - this(o); - this.local = local; - } - - public T get(Class t) { - try { - return local ? Violator.getDeclaredAnnotation(o.getClass(), t) : Violator.getAnnotation(o.getClass(), t); - } catch(Throwable e) { - Iris.reportError(e); - if(!suppress) { - e.printStackTrace(); - } - } - - return null; - } - - public T get(Class t, String mn, Class... pars) { - try { - return local ? Violator.getDeclaredAnnotation(Violator.getDeclaredMethod(o.getClass(), mn, pars), t) : Violator.getAnnotation(Violator.getMethod(o.getClass(), mn, pars), t); - } catch(Throwable e) { - Iris.reportError(e); - if(!suppress) { - e.printStackTrace(); - } - } - - return null; - } - - public T get(Class t, String mn) { - try { - return local ? Violator.getDeclaredAnnotation(Violator.getDeclaredField(o.getClass(), mn), t) : Violator.getAnnotation(Violator.getField(o.getClass(), mn), t); - } catch(Throwable e) { - Iris.reportError(e); - if(!suppress) { - e.printStackTrace(); - } - } - - return null; - } - - @SuppressWarnings("unchecked") - public T get(String field) { - try { - return (T) (local ? Violator.getDeclaredField(o.getClass(), field) : Violator.getField(o.getClass(), field)).get(o); - } catch(Throwable e) { - Iris.reportError(e); - if(!suppress) { - e.printStackTrace(); - } - } - - return null; - } - - public Object getSelf() { - return o; - } - - public Object invoke(String method, Object... parameters) { - KList> par = new KList<>(); - - for(Object i : parameters) { - par.add(i.getClass()); - } - - try { - return (local ? Violator.getDeclaredMethod(o.getClass(), method, par.toArray(new Class[0])) : Violator.getMethod(o.getClass(), method, par.toArray(new Class[0]))).invoke(o, parameters); - } catch(Throwable e) { - Iris.reportError(e); - if(!suppress) { - e.printStackTrace(); - } - } - - return null; - } - - public void set(String field, Object value) { - try { - // https://github.com/VolmitSoftware/Mortar/issues/5 - (local ? Violator.getDeclaredField(o.getClass(), field) : Violator.getField(o.getClass(), field)).set(o, value); - } catch(Throwable e) { - Iris.reportError(e); - if(!suppress) { - e.printStackTrace(); - } - } - } -} diff --git a/src/main/java/com/volmit/iris/util/reflect/Violator.java b/src/main/java/com/volmit/iris/util/reflect/Violator.java deleted file mode 100644 index 639c275b7..000000000 --- a/src/main/java/com/volmit/iris/util/reflect/Violator.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.reflect; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.concurrent.ConcurrentSkipListMap; - -public class Violator { - protected static final ConcurrentSkipListMap nodes = new ConcurrentSkipListMap<>(); - - private static String id(Object o, Object h) { - if(o instanceof Field) { - return id(((Field) o).getDeclaringClass(), null) + "." + ((Field) o).getName(); - } - - if(o instanceof String) { - return (String) o; - } - - if(o instanceof Class) { - return ((Class) o).getCanonicalName(); - } - - if(o instanceof Constructor co) { - - StringBuilder mx = new StringBuilder(); - - for(Class i : co.getParameterTypes()) { - mx.append(",").append(i.getCanonicalName()); - } - - mx = new StringBuilder(mx.length() >= 1 ? mx.substring(1) : mx.toString()); - - return id(co.getDeclaringClass(), null) + "(" + mx + ")"; - } - - if(o instanceof Method) { - StringBuilder mx = new StringBuilder(); - - for(Class i : ((Method) o).getParameterTypes()) { - mx.append(",").append(i.getCanonicalName()); - } - - mx = new StringBuilder(mx.length() >= 1 ? mx.substring(1) : mx.toString()); - - return id(((Method) o).getDeclaringClass(), null) + "." + ((Method) o).getName() + "(" + mx + ")"; - } - - if(o instanceof Annotation a) { - return "@" + a.annotationType().getCanonicalName() + "[" + id(h, null) + "]"; - } - - return o.hashCode() + o.toString(); - } - - private static void p(String n, Object o) { - nodes.put(n, o); - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - private static boolean h(String n) { - return nodes.containsKey(n); - } - - private static Object g(String n) { - return nodes.get(n); - } - - public static Constructor getConstructor(Class c, Class... params) throws NoSuchMethodException, SecurityException { - StringBuilder mx = new StringBuilder(); - - for(Class i : params) { - mx.append(",").append(i.getCanonicalName()); - } - - mx = new StringBuilder(mx.length() >= 1 ? mx.substring(1) : mx.toString()); - - if(!h(id(c, null) + "(" + mx + ")")) { - Constructor co = c.getConstructor(params); - co.setAccessible(true); - p(id(co, null), co); - } - - return (Constructor) g(id(c, null) + "(" + mx + ")"); - } - - @SuppressWarnings("rawtypes") - public static Field getField(Class c, String name) throws Throwable { - if(!h(id(c, null) + "." + name)) { - try { - Field f = c.getField(name); - f.setAccessible(true); - p(id(c, null) + "." + name, f); - } catch(NoSuchFieldException e) { - Iris.reportError(e); - Class s = c.getSuperclass(); - if(null == s) { - throw e; - } - Field f = s.getField(name); - f.setAccessible(true); - p(id(c, null) + "." + name, f); - } - } - - return (Field) g(id(c, null) + "." + name); - } - - @SuppressWarnings("rawtypes") - public static Field getDeclaredField(Class c, String name) throws Throwable { - if(!h(id(c, null) + "." + name)) { - try { - Field f = c.getDeclaredField(name); - f.setAccessible(true); - p(id(c, null) + "." + name, f); - } catch(NoSuchFieldException e) { - Iris.reportError(e); - Class s = c.getSuperclass(); - if(null == s) { - throw e; - } - Field f = s.getDeclaredField(name); - f.setAccessible(true); - p(id(c, null) + "." + name, f); - } - } - - return (Field) g(id(c, null) + "." + name); - } - - public static Method getMethod(Class c, String name, Class... pars) throws Throwable { - String iv = ""; - StringBuilder mx = new StringBuilder(); - - for(Class i : pars) { - mx.append(",").append(i.getCanonicalName()); - } - - mx = new StringBuilder(mx.length() >= 1 ? mx.substring(1) : mx.toString()); - iv = id(c, null) + "." + name + "(" + mx + ")"; - - if(!h(iv)) { - Method f = c.getMethod(name, pars); - f.setAccessible(true); - p(iv, f); - } - - return (Method) g(iv); - } - - @SuppressWarnings("unchecked") - public static T construct(Class c, Object... parameters) { - KList> cv = new KList<>(); - - for(Object i : parameters) { - cv.add(i.getClass()); - } - - try { - Constructor co = getConstructor(c, cv.toArray(new Class[0])); - return (T) co.newInstance(parameters); - } catch(Exception e) { - Iris.reportError(e); - e.printStackTrace(); - } - - return null; - } - - public static Method getDeclaredMethod(Class c, String name, Class... pars) throws Throwable { - String iv = ""; - StringBuilder mx = new StringBuilder(); - - for(Class i : pars) { - mx.append(",").append(i.getCanonicalName()); - } - - mx = new StringBuilder(mx.length() >= 1 ? mx.substring(1) : mx.toString()); - iv = id(c, null) + "." + name + "(" + mx + ")"; - - if(!h(iv)) { - Method f = c.getDeclaredMethod(name, pars); - f.setAccessible(true); - p(iv, f); - } - - return (Method) g(iv); - } - - @SuppressWarnings("unchecked") - public static T getAnnotation(Class c, Class a) { - if(!h("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]")) { - T f = c.getAnnotation(a); - p(id(f, c), f); - } - - return (T) g("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]"); - } - - @SuppressWarnings("unchecked") - public static T getDeclaredAnnotation(Class c, Class a) { - if(!h("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]")) { - T f = c.getDeclaredAnnotation(a); - p(id(f, c), f); - } - - return (T) g("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]"); - } - - @SuppressWarnings("unchecked") - public static T getAnnotation(Field c, Class a) { - if(!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) { - T f = c.getAnnotation(a); - p(id(f, c), f); - } - - return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); - } - - @SuppressWarnings("unchecked") - public static T getDeclaredAnnotation(Field c, Class a) { - if(!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) { - T f = c.getDeclaredAnnotation(a); - p(id(f, c), f); - } - - return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); - } - - @SuppressWarnings("unchecked") - public static T getAnnotation(Method c, Class a) { - if(!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) { - T f = c.getAnnotation(a); - p(id(f, c), f); - } - - return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); - } - - @SuppressWarnings("unchecked") - public static T getDeclaredAnnotation(Method c, Class a) { - if(!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) { - T f = c.getDeclaredAnnotation(a); - p(id(f, c), f); - - Iris.debug("Set as " + id(f, c) + " as " + ("@" + a.getCanonicalName() + "[" + id(c, null) + "]")); - } - - return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/AR.java b/src/main/java/com/volmit/iris/util/scheduling/AR.java deleted file mode 100644 index b5fda2c52..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/AR.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.util.plugin.CancellableTask; - -public abstract class AR implements Runnable, CancellableTask { - private int id = 0; - - public AR() { - this(0); - } - - public AR(int interval) { - id = J.ar(this, interval); - } - - @Override - public void cancel() { - J.car(id); - } - - public int getId() { - return id; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/Callback.java b/src/main/java/com/volmit/iris/util/scheduling/Callback.java deleted file mode 100644 index cb816e354..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/Callback.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -/** - * Callback for async workers - * - * @param - * the type of object to be returned in the runnable - * @author cyberpwn - */ -@FunctionalInterface -public interface Callback { - /** - * Called when the callback calls back... - * - * @param t - * the object to be called back - */ - void run(T t); -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/ChronoLatch.java b/src/main/java/com/volmit/iris/util/scheduling/ChronoLatch.java deleted file mode 100644 index 629221de5..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/ChronoLatch.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -public class ChronoLatch { - private final long interval; - private long since; - - public ChronoLatch(long interval, boolean openedAtStart) { - this.interval = interval; - since = System.currentTimeMillis() - (openedAtStart ? interval * 2 : 0); - } - - public ChronoLatch(long interval) { - this(interval, true); - } - - public void flipDown() { - since = System.currentTimeMillis(); - } - - public boolean couldFlip() { - return System.currentTimeMillis() - since > interval; - } - - public boolean flip() { - if(System.currentTimeMillis() - since > interval) { - since = System.currentTimeMillis(); - return true; - } - - return false; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/Contained.java b/src/main/java/com/volmit/iris/util/scheduling/Contained.java deleted file mode 100644 index a010dd1f0..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/Contained.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import java.util.function.Function; - -public class Contained { - private T t; - - public void mod(Function x) { - set(x.apply(t)); - } - - public T get() { - return t; - } - - public void set(T t) { - this.t = t; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/GroupedExecutor.java b/src/main/java/com/volmit/iris/util/scheduling/GroupedExecutor.java deleted file mode 100644 index 2c951f66c..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/GroupedExecutor.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.function.NastyRunnable; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory; -import java.util.concurrent.ForkJoinWorkerThread; - -public class GroupedExecutor { - private final ExecutorService service; - private final KMap mirror; - private int xc; - - public GroupedExecutor(int threadLimit, int priority, String name) { - xc = 1; - mirror = new KMap<>(); - - if(threadLimit == 1) { - service = Executors.newSingleThreadExecutor((r) -> - { - Thread t = new Thread(r); - t.setName(name); - t.setPriority(priority); - - return t; - }); - } else if(threadLimit > 1) { - final ForkJoinWorkerThreadFactory factory = pool -> { - final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); - worker.setName(name + " " + xc++); - worker.setPriority(priority); - return worker; - }; - - service = new ForkJoinPool(threadLimit, factory, null, false); - } else { - service = Executors.newCachedThreadPool((r) -> - { - Thread t = new Thread(r); - t.setName(name + " " + xc++); - t.setPriority(priority); - - return t; - }); - } - } - - public void waitFor(String g) { - if(g == null) { - return; - } - - if(!mirror.containsKey(g)) { - return; - } - - while(true) { - if(mirror.get(g) == 0) { - break; - } - } - } - - public void queue(String q, NastyRunnable r) { - mirror.compute(q, (k, v) -> k == null || v == null ? 1 : v + 1); - service.execute(() -> - { - try { - r.run(); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - - mirror.computeIfPresent(q, (k, v) -> v - 1); - }); - } - - public void close() { - J.a(() -> - { - J.sleep(100); - service.shutdown(); - }); - } - - public void closeNow() { - service.shutdown(); - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/IrisLock.java b/src/main/java/com/volmit/iris/util/scheduling/IrisLock.java deleted file mode 100644 index 6a84d654b..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/IrisLock.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.Iris; -import lombok.Data; -import lombok.experimental.Accessors; - -import java.util.concurrent.locks.ReentrantLock; - -@Data -@Accessors( - chain = true -) -public class IrisLock { - private transient final ReentrantLock lock; - private transient final String name; - private transient boolean disabled = false; - - public IrisLock(String name) { - this.name = name; - lock = new ReentrantLock(false); - } - - public void lock() { - if(disabled) { - return; - } - - lock.lock(); - } - - public void unlock() { - if(disabled) { - return; - } - try { - lock.unlock(); - } catch(Throwable e) { - Iris.reportError(e); - - } - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/J.java b/src/main/java/com/volmit/iris/util/scheduling/J.java deleted file mode 100644 index 2b865d29e..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/J.java +++ /dev/null @@ -1,406 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.function.NastyFunction; -import com.volmit.iris.util.function.NastyFuture; -import com.volmit.iris.util.function.NastyRunnable; -import com.volmit.iris.util.function.NastySupplier; -import com.volmit.iris.util.math.FinalInteger; -import com.volmit.iris.util.parallel.MultiBurst; -import org.bukkit.Bukkit; - -import java.util.concurrent.Callable; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Future; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -@SuppressWarnings("ALL") -public class J { - private static int tid = 0; - private static KList afterStartup = new KList<>(); - private static KList afterStartupAsync = new KList<>(); - private static boolean started = false; - - public static void dofor(int a, Function c, int ch, Consumer d) { - for(int i = a; c.apply(i); i += ch) { - c.apply(i); - } - } - - public static boolean doif(Supplier c, Runnable g) { - try { - if(c.get()) { - g.run(); - return true; - } - } catch(NullPointerException e) { - Iris.reportError(e); - // TODO: Fix this because this is just a suppression for an NPE on g - return false; - } - - return false; - } - - public static void arun(Runnable a) { - MultiBurst.burst.lazy(() -> { - try { - a.run(); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Failed to run async task"); - e.printStackTrace(); - } - }); - } - - public static void a(Runnable a) { - MultiBurst.burst.lazy(() -> { - try { - a.run(); - } catch(Throwable e) { - Iris.reportError(e); - Iris.error("Failed to run async task"); - e.printStackTrace(); - } - }); - } - - public static void aBukkit(Runnable a) { - if(!Bukkit.getPluginManager().isPluginEnabled(Iris.instance)) { - return; - } - Bukkit.getScheduler().scheduleAsyncDelayedTask(Iris.instance, a); - } - - public static Future a(Callable a) { - return MultiBurst.burst.lazySubmit(a); - } - - public static void attemptAsync(NastyRunnable r) { - J.a(() -> J.attempt(r)); - } - - public static R attemptResult(NastyFuture r, R onError) { - try { - return r.run(); - } catch(Throwable e) { - Iris.reportError(e); - - } - - return onError; - } - - public static R attemptFunction(NastyFunction r, T param, R onError) { - try { - return r.run(param); - } catch(Throwable e) { - Iris.reportError(e); - - } - - return onError; - } - - public static boolean sleep(long ms) { - return J.attempt(() -> Thread.sleep(ms)); - } - - public static boolean attempt(NastyRunnable r) { - return attemptCatch(r) == null; - } - - public static T attemptResult(NastySupplier r) { - try { - return r.get(); - } catch(Throwable e) { - return null; - } - } - - public static Throwable attemptCatch(NastyRunnable r) { - try { - r.run(); - } catch(Throwable e) { - return e; - } - - return null; - } - - public static T attempt(Supplier t, T i) { - try { - return t.get(); - } catch(Throwable e) { - Iris.reportError(e); - return i; - } - } - - /** - * Dont call this unless you know what you are doing! - */ - public static void executeAfterStartupQueue() { - if(started) { - return; - } - - started = true; - - for(Runnable r : afterStartup) { - s(r); - } - - for(Runnable r : afterStartupAsync) { - a(r); - } - - afterStartup = null; - afterStartupAsync = null; - } - - /** - * Schedule a sync task to be run right after startup. If the server has already - * started ticking, it will simply run it in a sync task. - *

- * If you dont know if you should queue this or not, do so, it's pretty - * forgiving. - * - * @param r - * the runnable - */ - public static void ass(Runnable r) { - if(started) { - s(r); - } else { - afterStartup.add(r); - } - } - - /** - * Schedule an async task to be run right after startup. If the server has - * already started ticking, it will simply run it in an async task. - *

- * If you dont know if you should queue this or not, do so, it's pretty - * forgiving. - * - * @param r - * the runnable - */ - public static void asa(Runnable r) { - if(started) { - a(r); - } else { - afterStartupAsync.add(r); - } - } - - /** - * Queue a sync task - * - * @param r - * the runnable - */ - public static void s(Runnable r) { - if(!Bukkit.getPluginManager().isPluginEnabled(Iris.instance)) { - return; - } - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, r); - } - - public static CompletableFuture sfut(Runnable r) { - CompletableFuture f = new CompletableFuture(); - - if(!Bukkit.getPluginManager().isPluginEnabled(Iris.instance)) { - return null; - } - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> { - r.run(); - f.complete(null); - }); - return f; - } - - public static CompletableFuture sfut(Runnable r, int delay) { - CompletableFuture f = new CompletableFuture(); - - if(!Bukkit.getPluginManager().isPluginEnabled(Iris.instance)) { - return null; - } - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> { - r.run(); - f.complete(null); - }, delay); - return f; - } - - public static CompletableFuture afut(Runnable r) { - CompletableFuture f = new CompletableFuture(); - J.a(() -> { - r.run(); - f.complete(null); - }); - return f; - } - - /** - * Queue a sync task - * - * @param r - * the runnable - * @param delay - * the delay to wait in ticks before running - */ - public static void s(Runnable r, int delay) { - try { - if(!Bukkit.getPluginManager().isPluginEnabled(Iris.instance)) { - return; - } - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, r, delay); - } catch(Throwable e) { - Iris.reportError(e); - } - } - - /** - * Cancel a sync repeating task - * - * @param id - * the task id - */ - public static void csr(int id) { - Bukkit.getScheduler().cancelTask(id); - } - - /** - * Start a sync repeating task - * - * @param r - * the runnable - * @param interval - * the interval - * @return the task id - */ - public static int sr(Runnable r, int interval) { - if(!Bukkit.getPluginManager().isPluginEnabled(Iris.instance)) { - return -1; - } - return Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, r, 0, interval); - } - - /** - * Start a sync repeating task for a limited amount of ticks - * - * @param r - * the runnable - * @param interval - * the interval in ticks - * @param intervals - * the maximum amount of intervals to run - */ - public static void sr(Runnable r, int interval, int intervals) { - FinalInteger fi = new FinalInteger(0); - - new SR() { - @Override - public void run() { - fi.add(1); - r.run(); - - if(fi.get() >= intervals) { - cancel(); - } - } - }; - } - - /** - * Call an async task dealyed - * - * @param r - * the runnable - * @param delay - * the delay to wait before running - */ - @SuppressWarnings("deprecation") - public static void a(Runnable r, int delay) { - if(Bukkit.getPluginManager().isPluginEnabled(Iris.instance)) { - Bukkit.getScheduler().scheduleAsyncDelayedTask(Iris.instance, r, delay); - } - } - - /** - * Cancel an async repeat task - * - * @param id - * the id - */ - public static void car(int id) { - Bukkit.getScheduler().cancelTask(id); - } - - /** - * Start an async repeat task - * - * @param r - * the runnable - * @param interval - * the interval in ticks - * @return the task id - */ - @SuppressWarnings("deprecation") - public static int ar(Runnable r, int interval) { - if(!Bukkit.getPluginManager().isPluginEnabled(Iris.instance)) { - return -1; - } - return Bukkit.getScheduler().scheduleAsyncRepeatingTask(Iris.instance, r, 0, interval); - } - - /** - * Start an async repeating task for a limited time - * - * @param r - * the runnable - * @param interval - * the interval - * @param intervals - * the intervals to run - */ - public static void ar(Runnable r, int interval, int intervals) { - FinalInteger fi = new FinalInteger(0); - - new AR() { - @Override - public void run() { - fi.add(1); - r.run(); - - if(fi.get() >= intervals) { - cancel(); - } - } - }; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/Looper.java b/src/main/java/com/volmit/iris/util/scheduling/Looper.java deleted file mode 100644 index 11e080a36..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/Looper.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.PreservationSVC; - -public abstract class Looper extends Thread { - @SuppressWarnings("BusyWait") - public void run() { - Iris.service(PreservationSVC.class).register(this); - while(!interrupted()) { - try { - long m = loop(); - - if(m < 0) { - break; - } - - //noinspection BusyWait - Thread.sleep(m); - } catch(InterruptedException e) { - Iris.reportError(e); - break; - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - Iris.debug("Iris Thread " + getName() + " Shutdown."); - } - - protected abstract long loop(); -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/O.java b/src/main/java/com/volmit/iris/util/scheduling/O.java deleted file mode 100644 index 7218bc214..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/O.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.util.collection.KList; - -public class O implements Observable { - private T t = null; - private KList> observers; - - @Override - public T get() { - return t; - } - - @Override - public O set(T t) { - this.t = t; - - if(observers != null && observers.hasElements()) { - observers.forEach((o) -> o.onChanged(t, t)); - } - - return this; - } - - @Override - public boolean has() { - return t != null; - } - - @Override - public O clearObservers() { - observers.clear(); - return this; - } - - @Override - public O observe(Observer t) { - if(observers == null) { - observers = new KList<>(); - } - - observers.add(t); - - return this; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/Observable.java b/src/main/java/com/volmit/iris/util/scheduling/Observable.java deleted file mode 100644 index 3fbd672cc..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/Observable.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -public interface Observable { - T get(); - - Observable set(T t); - - boolean has(); - - Observable clearObservers(); - - Observable observe(Observer t); -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/Observer.java b/src/main/java/com/volmit/iris/util/scheduling/Observer.java deleted file mode 100644 index 49a378a54..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/Observer.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -@FunctionalInterface -public interface Observer { - void onChanged(T from, T to); -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/PrecisionStopwatch.java b/src/main/java/com/volmit/iris/util/scheduling/PrecisionStopwatch.java deleted file mode 100644 index ffe47a10e..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/PrecisionStopwatch.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -public class PrecisionStopwatch { - private long nanos; - private long startNano; - private long millis; - private long startMillis; - private double time; - private boolean profiling; - - public PrecisionStopwatch() { - reset(); - profiling = false; - } - - public static PrecisionStopwatch start() { - PrecisionStopwatch p = new PrecisionStopwatch(); - p.begin(); - - return p; - } - - public void begin() { - profiling = true; - startNano = System.nanoTime(); - startMillis = System.currentTimeMillis(); - } - - public void end() { - if(!profiling) { - return; - } - - profiling = false; - nanos = System.nanoTime() - startNano; - millis = System.currentTimeMillis() - startMillis; - time = (double) nanos / 1000000.0; - time = (double) millis - time > 1.01 ? millis : time; - } - - public void reset() { - nanos = -1; - millis = -1; - startNano = -1; - startMillis = -1; - time = -0; - profiling = false; - } - - public double getTicks() { - return getMilliseconds() / 50.0; - } - - public double getSeconds() { - return getMilliseconds() / 1000.0; - } - - public double getMinutes() { - return getSeconds() / 60.0; - } - - public double getHours() { - return getMinutes() / 60.0; - } - - public double getMilliseconds() { - nanos = System.nanoTime() - startNano; - millis = System.currentTimeMillis() - startMillis; - time = (double) nanos / 1000000.0; - time = (double) millis - time > 1.01 ? millis : time; - return time; - } - - public long getNanoseconds() { - return (long) (time * 1000000.0); - } - - public long getNanos() { - return nanos; - } - - public long getStartNano() { - return startNano; - } - - public long getMillis() { - return millis; - } - - public long getStartMillis() { - return startMillis; - } - - public double getTime() { - return time; - } - - public boolean isProfiling() { - return profiling; - } - - public void rewind(long l) { - startMillis -= l; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/Queue.java b/src/main/java/com/volmit/iris/util/scheduling/Queue.java deleted file mode 100644 index c25bb715d..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/Queue.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.util.collection.KList; - -@SuppressWarnings("ALL") -public interface Queue { - static Queue create(KList t) { - return new ShurikenQueue().queue(t); - } - - @SuppressWarnings("unchecked") - static Queue create(T... t) { - return new ShurikenQueue().queue(new KList().add(t)); - } - - Queue queue(T t); - - Queue queue(KList t); - - boolean hasNext(int amt); - - boolean hasNext(); - - T next(); - - KList next(int amt); - - Queue clear(); - - int size(); - - boolean contains(T p); -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/QueueExecutor.java b/src/main/java/com/volmit/iris/util/scheduling/QueueExecutor.java deleted file mode 100644 index 93215eeaf..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/QueueExecutor.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.Iris; - -public class QueueExecutor extends Looper { - private final Queue queue; - private boolean shutdown; - - public QueueExecutor() { - queue = new ShurikenQueue<>(); - shutdown = false; - } - - public Queue queue() { - return queue; - } - - @Override - protected long loop() { - while(queue.hasNext()) { - try { - queue.next().run(); - } catch(Throwable e) { - Iris.reportError(e); - e.printStackTrace(); - } - } - - if(shutdown && !queue.hasNext()) { - interrupt(); - return -1; - } - - return Math.max(500, (long) getRunTime() * 10); - } - - public double getRunTime() { - return 0; - } - - public void shutdown() { - shutdown = true; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/S.java b/src/main/java/com/volmit/iris/util/scheduling/S.java deleted file mode 100644 index a6d37809f..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/S.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -public abstract class S implements Runnable { - public S() { - J.s(this); - } - - public S(int delay) { - J.s(this, delay); - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/SR.java b/src/main/java/com/volmit/iris/util/scheduling/SR.java deleted file mode 100644 index bbb41cd85..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/SR.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.util.plugin.CancellableTask; - -public abstract class SR implements Runnable, CancellableTask { - private int id = 0; - - public SR() { - this(0); - } - - public SR(int interval) { - id = J.sr(this, interval); - } - - @Override - public void cancel() { - J.csr(id); - } - - public int getId() { - return id; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/ShurikenQueue.java b/src/main/java/com/volmit/iris/util/scheduling/ShurikenQueue.java deleted file mode 100644 index c8968e50b..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/ShurikenQueue.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.util.collection.KList; - -public class ShurikenQueue implements Queue { - private KList queue; - private boolean randomPop; - private boolean reversePop; - - public ShurikenQueue() { - clear(); - } - - public ShurikenQueue responsiveMode() { - reversePop = true; - return this; - } - - public ShurikenQueue randomMode() { - randomPop = true; - return this; - } - - @Override - public ShurikenQueue queue(T t) { - queue.add(t); - return this; - } - - @Override - public ShurikenQueue queue(KList t) { - queue.add(t); - return this; - } - - @Override - public boolean hasNext(int amt) { - return queue.size() >= amt; - } - - @Override - public boolean hasNext() { - return !queue.isEmpty(); - } - - @Override - public T next() { - return reversePop ? queue.popLast() : randomPop ? queue.popRandom() : queue.pop(); - } - - @Override - public KList next(int amt) { - KList t = new KList<>(); - - for(int i = 0; i < amt; i++) { - if(!hasNext()) { - break; - } - - t.add(next()); - } - - return t; - } - - @Override - public ShurikenQueue clear() { - queue = new KList<>(); - return this; - } - - @Override - public int size() { - return queue.size(); - } - - @Override - public boolean contains(T p) { - return queue.contains(p); - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/Switch.java b/src/main/java/com/volmit/iris/util/scheduling/Switch.java deleted file mode 100644 index a4e25e8a2..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/Switch.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -public class Switch { - private volatile boolean b; - - /** - * Defaulted off - */ - public Switch() { - b = false; - } - - public void flip() { - b = true; - } - - public boolean isFlipped() { - return b; - } - - public void reset() { - b = false; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/TaskExecutor.java b/src/main/java/com/volmit/iris/util/scheduling/TaskExecutor.java deleted file mode 100644 index 617c2a067..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/TaskExecutor.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.function.NastyRunnable; -import com.volmit.iris.util.math.M; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory; -import java.util.concurrent.ForkJoinWorkerThread; - -public class TaskExecutor { - private final ExecutorService service; - private int xc; - - public TaskExecutor(int threadLimit, int priority, String name) { - xc = 1; - - if(threadLimit == 1) { - service = Executors.newSingleThreadExecutor((r) -> - { - Thread t = new Thread(r); - t.setName(name); - t.setPriority(priority); - - return t; - }); - } else if(threadLimit > 1) { - final ForkJoinWorkerThreadFactory factory = pool -> { - final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); - worker.setName(name + " " + xc++); - worker.setPriority(priority); - return worker; - }; - - service = new ForkJoinPool(threadLimit, factory, null, false); - } else { - service = Executors.newCachedThreadPool((r) -> - { - Thread t = new Thread(r); - t.setName(name + " " + xc++); - t.setPriority(priority); - - return t; - }); - } - } - - public TaskGroup startWork() { - return new TaskGroup(this); - } - - public void close() { - J.a(() -> - { - J.sleep(10000); - service.shutdown(); - }); - } - - public void closeNow() { - service.shutdown(); - } - - public enum TaskState { - QUEUED, - RUNNING, - COMPLETED, - FAILED - } - - public static class TaskGroup { - private final KList tasks; - private final TaskExecutor e; - - public TaskGroup(TaskExecutor e) { - tasks = new KList<>(); - this.e = e; - } - - public TaskGroup queue(NastyRunnable... r) { - for(NastyRunnable i : r) { - tasks.add(new AssignedTask(i)); - } - - return this; - } - - public TaskGroup queue(KList r) { - for(NastyRunnable i : r) { - tasks.add(new AssignedTask(i)); - } - - return this; - } - - public TaskResult execute() { - double timeElapsed = 0; - int tasksExecuted = 0; - int tasksFailed = 0; - int tasksCompleted = 0; - tasks.forEach((t) -> t.go(e)); - long msv = M.ns(); - - waiting: - while(true) { - try { - //noinspection BusyWait - Thread.sleep(0); - } catch(InterruptedException ignored) { - - } - - for(AssignedTask i : tasks) { - if(i.state.equals(TaskState.QUEUED) || i.state.equals(TaskState.RUNNING)) { - continue waiting; - } - } - - timeElapsed = (double) (M.ns() - msv) / 1000000D; - - for(AssignedTask i : tasks) { - if(i.state.equals(TaskState.COMPLETED)) { - tasksCompleted++; - } else { - tasksFailed++; - } - - tasksExecuted++; - } - - break; - } - - return new TaskResult(timeElapsed, tasksExecuted, tasksFailed, tasksCompleted); - } - } - - @SuppressWarnings("ClassCanBeRecord") - @ToString - public static class TaskResult { - public final double timeElapsed; - public final int tasksExecuted; - public final int tasksFailed; - public final int tasksCompleted; - - public TaskResult(double timeElapsed, int tasksExecuted, int tasksFailed, int tasksCompleted) { - this.timeElapsed = timeElapsed; - this.tasksExecuted = tasksExecuted; - this.tasksFailed = tasksFailed; - this.tasksCompleted = tasksCompleted; - } - } - - public static class AssignedTask { - @Getter - private final NastyRunnable task; - @Getter - @Setter - private TaskState state; - - public AssignedTask(NastyRunnable task) { - this.task = task; - state = TaskState.QUEUED; - } - - public void go(TaskExecutor e) { - e.service.execute(() -> - { - state = TaskState.RUNNING; - try { - task.run(); - state = TaskState.COMPLETED; - } catch(Throwable ex) { - Iris.reportError(ex); - ex.printStackTrace(); - Iris.reportError(ex); - state = TaskState.FAILED; - } - }); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/ThreadMonitor.java b/src/main/java/com/volmit/iris/util/scheduling/ThreadMonitor.java deleted file mode 100644 index fec26599d..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/ThreadMonitor.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.RollingSequence; - -/** - * Not particularly efficient or perfectly accurate but is great at fast thread - * switching detection - * - * @author dan - */ -public class ThreadMonitor extends Thread { - private final Thread monitor; - private final ChronoLatch cl; - private final RollingSequence sq = new RollingSequence(3); - int cycles = 0; - private boolean running; - private State lastState; - private PrecisionStopwatch st; - - private ThreadMonitor(Thread monitor) { - running = true; - st = PrecisionStopwatch.start(); - this.monitor = monitor; - lastState = State.NEW; - cl = new ChronoLatch(1000); - start(); - } - - public static ThreadMonitor bind(Thread monitor) { - return new ThreadMonitor(monitor); - } - - public void run() { - while(running) { - try { - //noinspection BusyWait - Thread.sleep(0); - State s = monitor.getState(); - if(lastState != s) { - cycles++; - pushState(s); - } - - lastState = s; - - if(cl.flip()) { - Iris.info("Cycles: " + Form.f(cycles) + " (" + Form.duration(sq.getAverage(), 2) + ")"); - } - } catch(Throwable e) { - Iris.reportError(e); - running = false; - break; - } - } - } - - public void pushState(State s) { - if(s != State.RUNNABLE) { - if(st != null) { - sq.put(st.getMilliseconds()); - } - } else { - - st = PrecisionStopwatch.start(); - } - } - - public void unbind() { - running = false; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/Wrapper.java b/src/main/java/com/volmit/iris/util/scheduling/Wrapper.java deleted file mode 100644 index 4eb9dc27d..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/Wrapper.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling; - -public class Wrapper { - private T t; - - public Wrapper(T t) { - set(t); - } - - public void set(T t) { - this.t = t; - } - - public T get() { - return t; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((t == null) ? 0 : t.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if(this == obj) { - return true; - } - if(obj == null) { - return false; - } - if(!(obj instanceof Wrapper other)) { - return false; - } - - if(t == null) { - return other.t == null; - } else return t.equals(other.t); - } - - @Override - public String toString() { - if(t != null) { - return get().toString(); - } - - return super.toString() + " (null)"; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/jobs/DownloadJob.java b/src/main/java/com/volmit/iris/util/scheduling/jobs/DownloadJob.java deleted file mode 100644 index e74e41f58..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/jobs/DownloadJob.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling.jobs; - -import com.volmit.iris.util.network.DL; -import com.volmit.iris.util.network.DownloadMonitor; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - -public class DownloadJob implements Job { - private final DL.Download download; - private int tw; - private int cw; - - public DownloadJob(String url, File destination) throws MalformedURLException { - tw = 1; - cw = 0; - download = new DL.Download(new URL(url), destination, DL.DownloadFlag.CALCULATE_SIZE); - download.monitor(new DownloadMonitor() { - @Override - public void onUpdate(DL.DownloadState state, double progress, long elapsed, long estimated, long bps, long iobps, long size, long downloaded, long buffer, double bufferuse) { - if(size == -1) { - tw = 1; - } else { - tw = (int) (size / 100); - cw = (int) (downloaded / 100); - } - } - }); - } - - @Override - public String getName() { - return "Downloading"; - } - - @Override - public void execute() { - try { - download.start(); - while(download.isState(DL.DownloadState.DOWNLOADING)) { - download.downloadChunk(); - } - } catch(IOException e) { - e.printStackTrace(); - } - - cw = tw; - } - - @Override - public void completeWork() { - - } - - @Override - public int getTotalWork() { - return tw; - } - - @Override - public int getWorkCompleted() { - return cw; - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/jobs/Job.java b/src/main/java/com/volmit/iris/util/scheduling/jobs/Job.java deleted file mode 100644 index 471dddde4..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/jobs/Job.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling.jobs; - -import com.volmit.iris.util.format.C; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.plugin.VolmitSender; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; - -import java.util.concurrent.CompletableFuture; - -public interface Job { - String getName(); - - void execute(); - - void completeWork(); - - int getTotalWork(); - - default int getWorkRemaining() { - return getTotalWork() - getWorkCompleted(); - } - - int getWorkCompleted(); - - default String getProgressString() { - return Form.pc(getProgress(), 0); - } - - default double getProgress() { - return (double) getWorkCompleted() / (double) getTotalWork(); - } - - - default void execute(VolmitSender sender) { - execute(sender, () -> { - }); - } - - - default void execute(VolmitSender sender, Runnable whenComplete) { - execute(sender, false, whenComplete); - } - - default void execute(VolmitSender sender, boolean silentMsg, Runnable whenComplete) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - CompletableFuture f = J.afut(this::execute); - int c = J.ar(() -> { - if(sender.isPlayer()) { - sender.sendProgress(getProgress(), getName()); - } else { - sender.sendMessage(getName() + ": " + getProgressString()); - } - }, sender.isPlayer() ? 0 : 20); - f.whenComplete((fs, ff) -> { - J.car(c); - if(!silentMsg) { - sender.sendMessage(C.AQUA + "Completed " + getName() + " in " + Form.duration(p.getMilliseconds(), 1)); - } - whenComplete.run(); - }); - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/jobs/JobCollection.java b/src/main/java/com/volmit/iris/util/scheduling/jobs/JobCollection.java deleted file mode 100644 index 52704b982..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/jobs/JobCollection.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling.jobs; - -import com.volmit.iris.util.collection.KList; - -public class JobCollection implements Job { - private final String name; - private final KList jobs; - private String status; - - public JobCollection(String name, Job... jobs) { - this(name, new KList<>(jobs)); - } - - public JobCollection(String name, KList jobs) { - this.name = name; - status = null; - this.jobs = new KList<>(jobs); - } - - @Override - public String getName() { - return status == null ? name : (name + " 》" + status); - } - - @Override - public void execute() { - for(Job i : jobs) { - status = i.getName(); - i.execute(); - } - - status = null; - } - - @Override - public void completeWork() { - - } - - @Override - public int getTotalWork() { - return jobs.stream().mapToInt(Job::getTotalWork).sum(); - } - - @Override - public int getWorkCompleted() { - return jobs.stream().mapToInt(Job::getWorkCompleted).sum(); - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/jobs/ParallelQueueJob.java b/src/main/java/com/volmit/iris/util/scheduling/jobs/ParallelQueueJob.java deleted file mode 100644 index 3d0c724c0..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/jobs/ParallelQueueJob.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling.jobs; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; - -public abstract class ParallelQueueJob extends QueueJob { - @Override - public void execute() { - while(queue.isNotEmpty()) { - BurstExecutor b = MultiBurst.burst.burst(queue.size()); - KList q = queue.copy(); - queue.clear(); - for(T i : q) { - b.queue(() -> { - execute(i); - completeWork(); - }); - } - b.complete(); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/jobs/QueueJob.java b/src/main/java/com/volmit/iris/util/scheduling/jobs/QueueJob.java deleted file mode 100644 index 481994ad7..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/jobs/QueueJob.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling.jobs; - -import com.volmit.iris.util.collection.KList; - -import java.util.concurrent.atomic.AtomicInteger; - -public abstract class QueueJob implements Job { - final KList queue; - private final AtomicInteger completed; - protected int totalWork; - - public QueueJob() { - totalWork = 0; - completed = new AtomicInteger(0); - queue = new KList<>(); - } - - public QueueJob queue(T t) { - queue.add(t); - totalWork++; - return this; - } - - public QueueJob queue(KList f) { - queue.addAll(f); - totalWork += f.size(); - return this; - } - - public abstract void execute(T t); - - @Override - public void execute() { - totalWork = queue.size(); - while(queue.isNotEmpty()) { - execute(queue.pop()); - completeWork(); - } - } - - @Override - public void completeWork() { - completed.incrementAndGet(); - } - - @Override - public int getTotalWork() { - return totalWork; - } - - @Override - public int getWorkCompleted() { - return completed.get(); - } -} diff --git a/src/main/java/com/volmit/iris/util/scheduling/jobs/SingleJob.java b/src/main/java/com/volmit/iris/util/scheduling/jobs/SingleJob.java deleted file mode 100644 index 43c4c2d81..000000000 --- a/src/main/java/com/volmit/iris/util/scheduling/jobs/SingleJob.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.scheduling.jobs; - -public class SingleJob implements Job { - private final String name; - private final Runnable runnable; - private boolean done; - - public SingleJob(String name, Runnable runnable) { - this.name = name; - done = false; - this.runnable = runnable; - } - - @Override - public String getName() { - return name; - } - - @Override - public void execute() { - runnable.run(); - completeWork(); - } - - @Override - public void completeWork() { - done = true; - } - - @Override - public int getTotalWork() { - return 1; - } - - @Override - public int getWorkCompleted() { - return done ? 1 : 0; - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/ArraySignificance.java b/src/main/java/com/volmit/iris/util/stream/ArraySignificance.java deleted file mode 100644 index 5d718d25d..000000000 --- a/src/main/java/com/volmit/iris/util/stream/ArraySignificance.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream; - -import com.volmit.iris.util.collection.KList; - -public class ArraySignificance implements Significance { - private final KList types; - private final KList significance; - private final T significant; - - public ArraySignificance(KList types, KList significance, T significant) { - this.types = types; - this.significance = significance; - this.significant = significant; - } - - public ArraySignificance(KList types, KList significance) { - this.types = types; - this.significance = significance; - double s = 0; - int v = 0; - for(int i = 0; i < significance.size(); i++) { - if(significance.get(i) > s) { - s = significance.get(i); - v = i; - } - } - - significant = types.get(v); - } - - @Override - public KList getFactorTypes() { - return types; - } - - @Override - public double getSignificance(T t) { - for(int i = 0; i < types.size(); i++) { - if(types.get(i).equals(t)) { - return significance.get(i); - } - } - - return 0; - } - - @Override - public T getMostSignificantType() { - return significant; - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/BasicLayer.java b/src/main/java/com/volmit/iris/util/stream/BasicLayer.java deleted file mode 100644 index cffdd2fdf..000000000 --- a/src/main/java/com/volmit/iris/util/stream/BasicLayer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class BasicLayer implements ProceduralLayer { - private final long seed; - private final double zoom; - private final double offsetX; - private final double offsetY; - private final double offsetZ; - - public BasicLayer(long seed, double zoom) { - this(seed, zoom, 0D, 0D, 0D); - } - - public BasicLayer(long seed) { - this(seed, 1D); - } - - public BasicLayer() { - this(1337); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/BasicStream.java b/src/main/java/com/volmit/iris/util/stream/BasicStream.java deleted file mode 100644 index b23ba9801..000000000 --- a/src/main/java/com/volmit/iris/util/stream/BasicStream.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream; - -public abstract class BasicStream extends BasicLayer implements ProceduralStream { - private final ProceduralStream source; - - public BasicStream(ProceduralStream source) { - super(); - this.source = source; - } - - public BasicStream() { - this(null); - } - - - @Override - public ProceduralStream getTypedSource() { - return source; - } - - @Override - public ProceduralStream getSource() { - return getTypedSource(); - } - - @Override - public abstract T get(double x, double z); - - @Override - public abstract T get(double x, double y, double z); - - @Override - public abstract double toDouble(T t); - - @Override - public abstract T fromDouble(double d); -} diff --git a/src/main/java/com/volmit/iris/util/stream/ProceduralLayer.java b/src/main/java/com/volmit/iris/util/stream/ProceduralLayer.java deleted file mode 100644 index 5ae3f9c23..000000000 --- a/src/main/java/com/volmit/iris/util/stream/ProceduralLayer.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream; - -public interface ProceduralLayer { - long getSeed(); - - double getOffsetX(); - - double getOffsetY(); - - double getOffsetZ(); - - double getZoom(); -} diff --git a/src/main/java/com/volmit/iris/util/stream/ProceduralStream.java b/src/main/java/com/volmit/iris/util/stream/ProceduralStream.java deleted file mode 100644 index 6f6ba5d0c..000000000 --- a/src/main/java/com/volmit/iris/util/stream/ProceduralStream.java +++ /dev/null @@ -1,537 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.loader.IrisData; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.object.IRare; -import com.volmit.iris.engine.object.IrisStyledRange; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.function.Function4; -import com.volmit.iris.util.hunk.Hunk; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.stream.arithmetic.AddingStream; -import com.volmit.iris.util.stream.arithmetic.ClampedStream; -import com.volmit.iris.util.stream.arithmetic.CoordinateBitShiftLeftStream; -import com.volmit.iris.util.stream.arithmetic.CoordinateBitShiftRightStream; -import com.volmit.iris.util.stream.arithmetic.DividingStream; -import com.volmit.iris.util.stream.arithmetic.FittedStream; -import com.volmit.iris.util.stream.arithmetic.MaxingStream; -import com.volmit.iris.util.stream.arithmetic.MinningStream; -import com.volmit.iris.util.stream.arithmetic.ModuloStream; -import com.volmit.iris.util.stream.arithmetic.MultiplyingStream; -import com.volmit.iris.util.stream.arithmetic.OffsetStream; -import com.volmit.iris.util.stream.arithmetic.RadialStream; -import com.volmit.iris.util.stream.arithmetic.RoundingDoubleStream; -import com.volmit.iris.util.stream.arithmetic.SlopeStream; -import com.volmit.iris.util.stream.arithmetic.SubtractingStream; -import com.volmit.iris.util.stream.arithmetic.ZoomStream; -import com.volmit.iris.util.stream.convert.AwareConversionStream2D; -import com.volmit.iris.util.stream.convert.AwareConversionStream3D; -import com.volmit.iris.util.stream.convert.CachedConversionStream; -import com.volmit.iris.util.stream.convert.ConversionStream; -import com.volmit.iris.util.stream.convert.ForceDoubleStream; -import com.volmit.iris.util.stream.convert.RoundingStream; -import com.volmit.iris.util.stream.convert.SelectionStream; -import com.volmit.iris.util.stream.convert.SignificanceStream; -import com.volmit.iris.util.stream.convert.To3DStream; -import com.volmit.iris.util.stream.interpolation.Interpolated; -import com.volmit.iris.util.stream.sources.FunctionStream; -import com.volmit.iris.util.stream.utility.CachedStream2D; -import com.volmit.iris.util.stream.utility.CachedStream3D; -import com.volmit.iris.util.stream.utility.NullSafeStream; -import com.volmit.iris.util.stream.utility.ProfiledStream; -import com.volmit.iris.util.stream.utility.SemaphoreStream; -import com.volmit.iris.util.stream.utility.SynchronizedStream; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Function; - -@SuppressWarnings("ALL") -public interface ProceduralStream extends ProceduralLayer, Interpolated { - static ProceduralStream ofDouble(Function2 f) { - try { - return of(f, Interpolated.DOUBLE); - } catch(IncompatibleClassChangeError e) { - Iris.warn(f.toString()); - Iris.reportError(e); - e.printStackTrace(); - return null; - } - } - - static ProceduralStream ofDouble(Function3 f) { - return of(f, Interpolated.DOUBLE); - } - - static ProceduralStream of(Function2 f, Interpolated helper) { - return of(f, (x, y, z) -> f.apply(x, z), helper); - } - - static ProceduralStream of(Function3 f, Interpolated helper) { - return of((x, z) -> f.apply(x, 0D, z), f, helper); - } - - static ProceduralStream of(Function2 f, Function3 f2, Interpolated helper) { - return new FunctionStream<>(f, f2, helper); - } - - default ProceduralStream chance(double chance) { - return of((x, z) -> getDouble(x, z) < chance, Interpolated.BOOLEAN); - } - - default ProceduralStream seededChance(RNG brng, long rootSeed, double chance) { - RNG rng = brng.nextParallelRNG(rootSeed - 3995L); - return of((x, z) -> { - double ch = getDouble(x, z); - rng.setSeed((long) (ch * Long.MAX_VALUE)); - return rng.chance(chance); - }, Interpolated.BOOLEAN); - } - - default ProceduralStream profile() { - return profile(10); - } - - default ProceduralStream profile(int memory) { - return new ProfiledStream<>(this, memory); - } - - default ProceduralStream onNull(T v) { - return new NullSafeStream<>(this, v); - } - - default ProceduralStream add(Function3 a) { - return new AddingStream<>(this, a); - } - - default ProceduralStream add(Function2 a) { - return new AddingStream<>(this, a); - } - - default ProceduralStream add(ProceduralStream a) { - return add2D((x, z) -> a.get(x, z)); - } - - default ProceduralStream subtract(ProceduralStream a) { - return subtract2D((x, z) -> a.get(x, z)); - } - - default ProceduralStream add2D(Function2 a) { - return new AddingStream<>(this, a); - } - - default ProceduralStream subtract2D(Function2 a) { - return new SubtractingStream(this, a); - } - - default ProceduralStream add(double a) { - return new AddingStream<>(this, a); - } - - default ProceduralStream blockToChunkCoords() { - return bitShiftCoordsRight(4); - } - - default ProceduralStream chunkToRegionCoords() { - return bitShiftCoordsRight(5); - } - - default ProceduralStream blockToRegionCoords() { - return blockToChunkCoords().chunkToRegionCoords(); - } - - default ProceduralStream regionToBlockCoords() { - return regionToChunkCoords().chunkToBlockCoords(); - } - - default ProceduralStream regionToChunkCoords() { - return bitShiftCoordsLeft(5); - } - - default ProceduralStream chunkToBlockCoords() { - return bitShiftCoordsLeft(4); - } - - default ProceduralStream bitShiftCoordsRight(int a) { - return new CoordinateBitShiftRightStream<>(this, a); - } - - default ProceduralStream synchronize() { - return new SynchronizedStream<>(this); - } - - default ProceduralStream semaphore(int permits) { - return new SemaphoreStream<>(this, permits); - } - - default ProceduralStream bitShiftCoordsLeft(int a) { - return new CoordinateBitShiftLeftStream<>(this, a); - } - - default ProceduralStream max(Function3 a) { - return new MaxingStream<>(this, a); - } - - default ProceduralStream max(Function2 a) { - return new MaxingStream<>(this, a); - } - - default ProceduralStream slope() { - return slope(1); - } - - default ProceduralStream slope(int range) { - return new SlopeStream<>(this, range); - } - - default ProceduralStream max(double a) { - return new MaxingStream<>(this, a); - } - - default ProceduralStream min(Function3 a) { - return new MinningStream<>(this, a); - } - - default ProceduralStream min(Function2 a) { - return new MinningStream<>(this, a); - } - - default ProceduralStream min(double a) { - return new MinningStream<>(this, a); - } - - default ProceduralStream subtract(Function3 a) { - return new SubtractingStream<>(this, a); - } - - default ProceduralStream subtract(Function2 a) { - return new SubtractingStream<>(this, a); - } - - default ProceduralStream subtract(double a) { - return new SubtractingStream<>(this, a); - } - - default ProceduralStream multiply(Function3 a) { - return new MultiplyingStream<>(this, a); - } - - default ProceduralStream multiply(Function2 a) { - return new MultiplyingStream<>(this, a); - } - - default ProceduralStream multiply(double a) { - return new MultiplyingStream<>(this, a); - } - - default ProceduralStream divide(Function3 a) { - return new DividingStream<>(this, a); - } - - default ProceduralStream divide(Function2 a) { - return new DividingStream<>(this, a); - } - - default ProceduralStream divide(double a) { - return new DividingStream<>(this, a); - } - - default ProceduralStream modulo(Function3 a) { - return new ModuloStream<>(this, a); - } - - default ProceduralStream modulo(Function2 a) { - return new ModuloStream<>(this, a); - } - - default ProceduralStream modulo(double a) { - return new ModuloStream<>(this, a); - } - - default ProceduralStream round() { - return new RoundingStream(this); - } - - default ProceduralStream roundDouble() { - return new RoundingDoubleStream(this); - } - - default ProceduralStream forceDouble() { - return new ForceDoubleStream(this); - } - - default ProceduralStream> significance(double radius, int checks) { - return new SignificanceStream, T>(this, radius, checks); - } - - default ProceduralStream to3D() { - return new To3DStream(this); - } - - default ProceduralStream cache2D(String name, Engine engine, int size) { - return new CachedStream2D(name, engine, this, size); - } - - default ProceduralStream cache3D(String name, Engine engine, int maxSize) { - return new CachedStream3D(name, engine, this, maxSize); - } - - default ProceduralStream convert(Function converter) { - return new ConversionStream(this, converter); - } - - default ProceduralStream convertAware2D(Function3 converter) { - return new AwareConversionStream2D(this, converter); - } - - default ProceduralStream convertAware3D(Function4 converter) { - return new AwareConversionStream3D(this, converter); - } - - default ProceduralStream convertCached(Function converter) { - return new CachedConversionStream(this, converter); - } - - default ProceduralStream offset(double x, double y, double z) { - return new OffsetStream(this, x, y, z); - } - - default ProceduralStream offset(double x, double z) { - return new OffsetStream(this, x, 0, z); - } - - default ProceduralStream zoom(double x, double y, double z) { - return new ZoomStream(this, x, y, z); - } - - default ProceduralStream zoom(double x, double z) { - return new ZoomStream(this, x, 1, z); - } - - default ProceduralStream zoom(double all) { - return new ZoomStream(this, all, all, all); - } - - default ProceduralStream radial(double scale) { - return new RadialStream<>(this, scale); - } - - default ProceduralStream radial() { - return radial(1D); - } - - default ProceduralStream select(V... types) { - return new SelectionStream(this, types); - } - - default ProceduralStream select(List types) { - return new SelectionStream(this, types); - } - - @SuppressWarnings("unchecked") - default ProceduralStream selectRarity(V... types) { - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for(V i : types) { - totalRarity += IRare.get(i); - } - - for(V i : types) { - rarityTypes.addMultiple(i, totalRarity / IRare.get(i)); - } - - return new SelectionStream(this, rarityTypes); - } - - default ProceduralStream selectRarity(List types) { - return IRare.stream(this.forceDouble(), types); - } - - default ProceduralStream selectRarity(List types, Function loader) { - List r = new ArrayList<>(); - for(V f : types) { - r.add(loader.apply(f)); - } - return selectRarity(r); - } - - default int countPossibilities(List types, Function loader) { - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for(V i : types) { - totalRarity += IRare.get(loader.apply(i)); - } - - for(V i : types) { - rarityTypes.addMultiple(i, totalRarity / IRare.get(loader.apply(i))); - } - - return rarityTypes.size(); - } - - default ProceduralStream clamp(double min, double max) { - return new ClampedStream(this, min, max); - } - - default ProceduralStream fit(double min, double max) { - return new FittedStream(this, min, max); - } - - default ProceduralStream style(RNG rng, IrisStyledRange range, IrisData data) { - return ProceduralStream.of((x, z) -> { - double d = getDouble(x, z); - return range.get(rng, d, -d, data); - }, Interpolated.DOUBLE); - } - - default ProceduralStream fit(double inMin, double inMax, double min, double max) { - return new FittedStream(this, inMin, inMax, min, max); - } - - default void fill(Hunk h, double x, double y, double z, int parallelism) { - h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> hh.set(xv, yv, zv, get(xx + xv + x, yy + yv + y, zz + zv + z)))); - } - - default void fill2D(Hunk h, double x, double z, V v, int parallelism) { - h.compute2D(parallelism, (xx, __, zz, hh) -> - { - for(int i = 0; i < hh.getWidth(); i++) { - for(int k = 0; k < hh.getDepth(); k++) { - double n = getDouble(i + x + xx, k + z + zz); - - for(int j = 0; j < Math.min(h.getHeight(), n); j++) { - hh.set(i, j, k, v); - } - } - } - }); - } - - default void fill2D(Hunk h, double x, double z, ProceduralStream v, int parallelism) { - h.compute2D(parallelism, (xx, yy, zz, hh) -> - { - for(int i = 0; i < hh.getWidth(); i++) { - for(int k = 0; k < hh.getDepth(); k++) { - double n = getDouble(i + x + xx, k + z + zz); - - for(int j = 0; j < Math.min(h.getHeight(), n); j++) { - hh.set(i, j, k, v.get(i + x + xx, j + yy, k + z + zz)); - } - } - } - }); - } - - default void fill2DYLocked(Hunk h, double x, double z, V v, int parallelism) { - h.compute2D(parallelism, (xx, yy, zz, hh) -> - { - for(int i = 0; i < hh.getWidth(); i++) { - for(int k = 0; k < hh.getDepth(); k++) { - double n = getDouble(i + x + xx, k + z + zz); - - for(int j = 0; j < Math.min(h.getHeight(), n); j++) { - hh.set(i, j, k, v); - } - } - } - }); - } - - default void fill2DYLocked(Hunk h, double x, double z, ProceduralStream v, int parallelism) { - h.compute2D(parallelism, (xx, yy, zz, hh) -> - { - for(int i = 0; i < hh.getWidth(); i++) { - for(int k = 0; k < hh.getDepth(); k++) { - double n = getDouble(i + x + xx, k + z + zz); - - for(int j = 0; j < Math.min(h.getHeight(), n); j++) { - hh.set(i, j, k, v.get(i + x + xx, k + z + zz)); - } - } - } - }); - } - - default void fill3D(Hunk h, double x, int y, double z, V v, int parallelism) { - h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> - { - if(getDouble(xx + xv + x, yy + yv + y, zz + zv + z) > 0.5) { - hh.set(xv, yv, zv, v); - } - })); - } - - default void fill3D(Hunk h, double x, int y, double z, ProceduralStream v, int parallelism) { - h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> - { - if(getDouble(xx + xv + x, yy + yv + y, zz + zv + z) > 0.5) { - hh.set(xv, yv, zv, v.get(xx + xv + x, yy + yv + y, zz + zv + z)); - } - })); - } - - default void fill(Hunk h, double x, double y, double z) { - fill(h, x, z, 4); - } - - default void fill2D(Hunk h, double x, double z, V v) { - fill2D(h, x, z, v, 4); - } - - default void fill2D(Hunk h, double x, double z, ProceduralStream v) { - fill2D(h, x, z, v, 4); - } - - default void fill2DYLocked(Hunk h, double x, double z, V v) { - fill2DYLocked(h, x, z, v, 4); - } - - default void fill2DYLocked(Hunk h, double x, double z, ProceduralStream v) { - fill2DYLocked(h, x, z, v, 4); - } - - default void fill3D(Hunk h, double x, int y, double z, V v) { - fill3D(h, x, y, z, v, 4); - } - - default void fill3D(Hunk h, double x, int y, double z, ProceduralStream v) { - fill3D(h, x, y, z, v, 4); - } - - default double getDouble(double x, double z) { - return toDouble(get(x, z)); - } - - default double getDouble(double x, double y, double z) { - return toDouble(get(x, y, z)); - } - - ProceduralStream getTypedSource(); - - ProceduralStream getSource(); - - T get(double x, double z); - - T get(double x, double y, double z); -} diff --git a/src/main/java/com/volmit/iris/util/stream/Significance.java b/src/main/java/com/volmit/iris/util/stream/Significance.java deleted file mode 100644 index 28937a641..000000000 --- a/src/main/java/com/volmit/iris/util/stream/Significance.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream; - -import com.volmit.iris.util.collection.KList; - -public interface Significance { - KList getFactorTypes(); - - double getSignificance(T t); - - T getMostSignificantType(); -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/AddingStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/AddingStream.java deleted file mode 100644 index 273e107ca..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/AddingStream.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class AddingStream extends BasicStream { - private final Function3 add; - - public AddingStream(ProceduralStream stream, Function3 add) { - super(stream); - this.add = add; - } - - public AddingStream(ProceduralStream stream, Function2 add) { - this(stream, (x, y, z) -> add.apply(x, z)); - } - - public AddingStream(ProceduralStream stream, double add) { - this(stream, (x, y, z) -> add); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return fromDouble(add.apply(x, 0D, z) + getTypedSource().getDouble(x, z)); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(add.apply(x, y, z) + getTypedSource().getDouble(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/ClampedStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/ClampedStream.java deleted file mode 100644 index 34f5a5f8a..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/ClampedStream.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class ClampedStream extends BasicStream implements ProceduralStream { - private final double min; - private final double max; - - public ClampedStream(ProceduralStream stream, double min, double max) { - super(stream); - this.min = min; - this.max = max; - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - private double clamp(double v) { - return Math.max(Math.min(v, max), min); - } - - @Override - public T get(double x, double z) { - return fromDouble(clamp(getTypedSource().getDouble(x, z))); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(clamp(getTypedSource().getDouble(x, y, z))); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/CoordinateBitShiftLeftStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/CoordinateBitShiftLeftStream.java deleted file mode 100644 index 14925fe75..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/CoordinateBitShiftLeftStream.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class CoordinateBitShiftLeftStream extends BasicStream implements ProceduralStream { - private final int amount; - - public CoordinateBitShiftLeftStream(ProceduralStream stream, int amount) { - super(stream); - this.amount = amount; - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return getTypedSource().get((int) x << amount, (int) z << amount); - } - - @Override - public T get(double x, double y, double z) { - return getTypedSource().get((int) x << amount, (int) y << amount, (int) z << amount); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/CoordinateBitShiftRightStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/CoordinateBitShiftRightStream.java deleted file mode 100644 index 948a690e8..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/CoordinateBitShiftRightStream.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class CoordinateBitShiftRightStream extends BasicStream implements ProceduralStream { - private final int amount; - - public CoordinateBitShiftRightStream(ProceduralStream stream, int amount) { - super(stream); - this.amount = amount; - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return getTypedSource().get((int) x >> amount, (int) z >> amount); - } - - @Override - public T get(double x, double y, double z) { - return getTypedSource().get((int) x >> amount, (int) y >> amount, (int) z >> amount); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/DividingStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/DividingStream.java deleted file mode 100644 index 881af02e8..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/DividingStream.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class DividingStream extends BasicStream implements ProceduralStream { - private final Function3 add; - - public DividingStream(ProceduralStream stream, Function3 add) { - super(stream); - this.add = add; - } - - public DividingStream(ProceduralStream stream, Function2 add) { - this(stream, (x, y, z) -> add.apply(x, z)); - } - - public DividingStream(ProceduralStream stream, double add) { - this(stream, (x, y, z) -> add); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return fromDouble(getTypedSource().getDouble(x, z) / add.apply(x, 0D, z)); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(getTypedSource().getDouble(x, y, z) / add.apply(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/FittedStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/FittedStream.java deleted file mode 100644 index 045039e9f..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/FittedStream.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class FittedStream extends BasicStream implements ProceduralStream { - private final double min; - private final double max; - private final double inMin; - private final double inMax; - - public FittedStream(ProceduralStream stream, double inMin, double inMax, double min, double max) { - super(stream); - this.inMin = inMin; - this.inMax = inMax; - this.min = min; - this.max = max; - } - - public FittedStream(ProceduralStream stream, double min, double max) { - this(stream, 0, 1, min, max); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - private double dlerp(double v) { - return min + ((max - min) * ((v - inMin) / (inMax - inMin))); - } - - @Override - public T get(double x, double z) { - return fromDouble(dlerp(getTypedSource().getDouble(x, z))); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(dlerp(getTypedSource().getDouble(x, y, z))); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/MaxingStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/MaxingStream.java deleted file mode 100644 index 513f09ea2..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/MaxingStream.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class MaxingStream extends BasicStream { - private final Function3 add; - - public MaxingStream(ProceduralStream stream, Function3 add) { - super(stream); - this.add = add; - } - - public MaxingStream(ProceduralStream stream, Function2 add) { - this(stream, (x, y, z) -> add.apply(x, z)); - } - - public MaxingStream(ProceduralStream stream, double add) { - this(stream, (x, y, z) -> add); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return fromDouble(Math.max(add.apply(x, 0D, z), getTypedSource().getDouble(x, z))); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(Math.max(add.apply(x, y, z), getTypedSource().getDouble(x, y, z))); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/MinningStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/MinningStream.java deleted file mode 100644 index 369856432..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/MinningStream.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class MinningStream extends BasicStream { - private final Function3 add; - - public MinningStream(ProceduralStream stream, Function3 add) { - super(stream); - this.add = add; - } - - public MinningStream(ProceduralStream stream, Function2 add) { - this(stream, (x, y, z) -> add.apply(x, z)); - } - - public MinningStream(ProceduralStream stream, double add) { - this(stream, (x, y, z) -> add); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return fromDouble(Math.min(add.apply(x, 0D, z), getTypedSource().getDouble(x, z))); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(Math.min(add.apply(x, y, z), getTypedSource().getDouble(x, y, z))); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/ModuloStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/ModuloStream.java deleted file mode 100644 index c8c0664b5..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/ModuloStream.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class ModuloStream extends BasicStream { - private final Function3 add; - - public ModuloStream(ProceduralStream stream, Function3 add) { - super(stream); - this.add = add; - } - - public ModuloStream(ProceduralStream stream, Function2 add) { - this(stream, (x, y, z) -> add.apply(x, z)); - } - - public ModuloStream(ProceduralStream stream, double add) { - this(stream, (x, y, z) -> add); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return fromDouble(getTypedSource().getDouble(x, z) % add.apply(x, 0D, z)); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(getTypedSource().getDouble(x, y, z) % add.apply(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/MultiplyingStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/MultiplyingStream.java deleted file mode 100644 index 4e1a8e4fc..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/MultiplyingStream.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class MultiplyingStream extends BasicStream { - private final Function3 add; - - public MultiplyingStream(ProceduralStream stream, Function3 add) { - super(stream); - this.add = add; - } - - public MultiplyingStream(ProceduralStream stream, Function2 add) { - this(stream, (x, y, z) -> add.apply(x, z)); - } - - public MultiplyingStream(ProceduralStream stream, double add) { - this(stream, (x, y, z) -> add); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return fromDouble(getTypedSource().getDouble(x, z) * add.apply(x, 0D, z)); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(getTypedSource().getDouble(x, y, z) * add.apply(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/OffsetStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/OffsetStream.java deleted file mode 100644 index ace5be403..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/OffsetStream.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class OffsetStream extends BasicStream implements ProceduralStream { - private final double ox; - private final double oy; - private final double oz; - - public OffsetStream(ProceduralStream stream, double x, double y, double z) { - super(stream); - this.ox = x; - this.oy = y; - this.oz = z; - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return getTypedSource().get(x + ox, z + oz); - } - - @Override - public T get(double x, double y, double z) { - return getTypedSource().get(x + ox, y + oy, z + oz); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/RadialStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/RadialStream.java deleted file mode 100644 index be20cdc40..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/RadialStream.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class RadialStream extends BasicStream implements ProceduralStream { - private final double scale; - - public RadialStream(ProceduralStream stream) { - this(stream, 1D); - } - - public RadialStream(ProceduralStream stream, double scale) { - super(stream); - this.scale = scale; - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - private double radii(double v) { - return (v / (360D * scale)) % 360D; - } - - @Override - public T get(double x, double z) { - return fromDouble(radii(getTypedSource().getDouble(x, z))); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(radii(getTypedSource().getDouble(x, y, z))); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/RoundingDoubleStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/RoundingDoubleStream.java deleted file mode 100644 index 7b24faf0e..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/RoundingDoubleStream.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class RoundingDoubleStream extends BasicStream { - private final ProceduralStream stream; - - public RoundingDoubleStream(ProceduralStream stream) { - super(); - this.stream = stream; - } - - @Override - public double toDouble(Double t) { - return t; - } - - @Override - public Double fromDouble(double d) { - return (double) Math.round(d); - } - - private double round(double v) { - return Math.round(v); - } - - @Override - public Double get(double x, double z) { - return round(stream.getDouble(x, z)); - } - - @Override - public Double get(double x, double y, double z) { - return round(stream.getDouble(x, y, z)); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/SlopeStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/SlopeStream.java deleted file mode 100644 index eb60f804b..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/SlopeStream.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class SlopeStream extends BasicStream { - private final int range; - - public SlopeStream(ProceduralStream stream, int range) { - super(stream); - this.range = range; - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - double height = getTypedSource().getDouble(x, z); - double dx = getTypedSource().getDouble(x + range, z) - height; - double dy = getTypedSource().getDouble(x, z + range) - height; - - return fromDouble(Math.sqrt(dx * dx + dy * dy)); - } - - @Override - public T get(double x, double y, double z) { - double height = getTypedSource().getDouble(x, y, z); - double dx = getTypedSource().getDouble(x + range, y, z) - height; - double dy = getTypedSource().getDouble(x, y + range, z) - height; - double dz = getTypedSource().getDouble(x, y, z + range) - height; - - return fromDouble(Math.cbrt((dx * dx) + (dy * dy) + (dz * dz))); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/SubtractingStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/SubtractingStream.java deleted file mode 100644 index 8dd76be80..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/SubtractingStream.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class SubtractingStream extends BasicStream { - private final Function3 add; - - public SubtractingStream(ProceduralStream stream, Function3 add) { - super(stream); - this.add = add; - } - - public SubtractingStream(ProceduralStream stream, Function2 add) { - this(stream, (x, y, z) -> add.apply(x, z)); - } - - public SubtractingStream(ProceduralStream stream, double add) { - this(stream, (x, y, z) -> add); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return fromDouble(getTypedSource().getDouble(x, z) - add.apply(x, 0D, z)); - } - - @Override - public T get(double x, double y, double z) { - return fromDouble(getTypedSource().getDouble(x, y, z) - add.apply(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/arithmetic/ZoomStream.java b/src/main/java/com/volmit/iris/util/stream/arithmetic/ZoomStream.java deleted file mode 100644 index ea2e5c5b0..000000000 --- a/src/main/java/com/volmit/iris/util/stream/arithmetic/ZoomStream.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.arithmetic; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class ZoomStream extends BasicStream { - private final double ox; - private final double oy; - private final double oz; - - public ZoomStream(ProceduralStream stream, double x, double y, double z) { - super(stream); - this.ox = x; - this.oy = y; - this.oz = z; - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return getTypedSource().get(x / ox, z / oz); - } - - @Override - public T get(double x, double y, double z) { - return getTypedSource().get(x / ox, y / oy, z / oz); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/AwareConversionStream2D.java b/src/main/java/com/volmit/iris/util/stream/convert/AwareConversionStream2D.java deleted file mode 100644 index 6fd4c3775..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/AwareConversionStream2D.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class AwareConversionStream2D extends BasicStream { - private final ProceduralStream stream; - private final Function3 converter; - - public AwareConversionStream2D(ProceduralStream stream, Function3 converter) { - super(null); - this.stream = stream; - this.converter = converter; - } - - @Override - public double toDouble(V t) { - if(t instanceof Double) { - return (Double) t; - } - - return 0; - } - - @Override - public V fromDouble(double d) { - return null; - } - - @Override - public ProceduralStream getSource() { - return stream; - } - - @Override - public V get(double x, double z) { - return converter.apply(stream.get(x, z), x, z); - } - - @Override - public V get(double x, double y, double z) { - return converter.apply(stream.get(x, y, z), x, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/AwareConversionStream3D.java b/src/main/java/com/volmit/iris/util/stream/convert/AwareConversionStream3D.java deleted file mode 100644 index f6420a9bf..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/AwareConversionStream3D.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.function.Function4; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class AwareConversionStream3D extends BasicStream { - private final ProceduralStream stream; - private final Function4 converter; - - public AwareConversionStream3D(ProceduralStream stream, Function4 converter) { - super(null); - this.stream = stream; - this.converter = converter; - } - - @Override - public double toDouble(V t) { - if(t instanceof Double) { - return (Double) t; - } - - return 0; - } - - @Override - public V fromDouble(double d) { - return null; - - - } - - @Override - public ProceduralStream getSource() { - return stream; - } - - @Override - public V get(double x, double z) { - return converter.apply(stream.get(x, z), x, 0D, z); - } - - @Override - public V get(double x, double y, double z) { - return converter.apply(stream.get(x, y, z), x, y, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/CachedConversionStream.java b/src/main/java/com/volmit/iris/util/stream/convert/CachedConversionStream.java deleted file mode 100644 index b056a9cce..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/CachedConversionStream.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.stream.BasicLayer; -import com.volmit.iris.util.stream.ProceduralStream; - -import java.util.function.Function; - -public class CachedConversionStream extends BasicLayer implements ProceduralStream { - private final ProceduralStream stream; - private final Function converter; - private final KMap cache; - - public CachedConversionStream(ProceduralStream stream, Function converter) { - super(); - this.stream = stream; - this.converter = converter; - cache = new KMap<>(); - } - - @Override - public double toDouble(V t) { - return 0; - } - - @Override - public V fromDouble(double d) { - return null; - } - - @Override - public ProceduralStream getTypedSource() { - return null; - } - - @Override - public ProceduralStream getSource() { - return stream; - } - - @Override - public V get(double x, double z) { - return cache.computeIfAbsent(stream.get(x, z), converter); - } - - @Override - public V get(double x, double y, double z) { - return cache.computeIfAbsent(stream.get(x, y, z), converter); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/ConversionStream.java b/src/main/java/com/volmit/iris/util/stream/convert/ConversionStream.java deleted file mode 100644 index 0625b51df..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/ConversionStream.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.stream.BasicLayer; -import com.volmit.iris.util.stream.ProceduralStream; - -import java.util.function.Function; - -public class ConversionStream extends BasicLayer implements ProceduralStream { - private final ProceduralStream stream; - private final Function converter; - - public ConversionStream(ProceduralStream stream, Function converter) { - super(); - this.stream = stream; - this.converter = converter; - } - - @Override - public double toDouble(V t) { - if(t instanceof Double) { - return (Double) t; - } - - return 0; - } - - @Override - public V fromDouble(double d) { - return null; - } - - @Override - public ProceduralStream getTypedSource() { - return null; - } - - @Override - public ProceduralStream getSource() { - return null; - } - - @Override - public V get(double x, double z) { - return converter.apply(stream.get(x, z)); - } - - @Override - public V get(double x, double y, double z) { - return converter.apply(stream.get(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/ForceDoubleStream.java b/src/main/java/com/volmit/iris/util/stream/convert/ForceDoubleStream.java deleted file mode 100644 index f9c28cb10..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/ForceDoubleStream.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class ForceDoubleStream extends BasicStream { - private final ProceduralStream stream; - - public ForceDoubleStream(ProceduralStream stream) { - super(null); - this.stream = stream; - } - - @Override - public double toDouble(Double t) { - return t; - } - - @Override - public Double fromDouble(double d) { - return d; - } - - @Override - public Double get(double x, double z) { - return stream.getDouble(x, z); - } - - @Override - public Double get(double x, double y, double z) { - return stream.getDouble(x, y, z); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/RoundingStream.java b/src/main/java/com/volmit/iris/util/stream/convert/RoundingStream.java deleted file mode 100644 index 272a3d691..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/RoundingStream.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class RoundingStream extends BasicStream { - private final ProceduralStream stream; - - public RoundingStream(ProceduralStream stream) { - super(); - this.stream = stream; - } - - @Override - public double toDouble(Integer t) { - return t.doubleValue(); - } - - @Override - public Integer fromDouble(double d) { - return (int) Math.round(d); - } - - private int round(double v) { - return (int) Math.round(v); - } - - @Override - public Integer get(double x, double z) { - return round(stream.getDouble(x, z)); - } - - @Override - public Integer get(double x, double y, double z) { - return round(stream.getDouble(x, y, z)); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/SelectionStream.java b/src/main/java/com/volmit/iris/util/stream/convert/SelectionStream.java deleted file mode 100644 index 83c9df4d8..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/SelectionStream.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -import java.util.List; - -public class SelectionStream extends BasicStream { - private final ProceduralStream stream; - private final T[] options; - - public SelectionStream(ProceduralStream stream, T[] options) { - super(); - this.stream = stream.fit(0, options.length - 1).round(); - this.options = options; - } - - @SuppressWarnings("unchecked") - public SelectionStream(ProceduralStream stream, List options) { - this(stream, (T[]) options.toArray()); - } - - @Override - public double toDouble(T t) { - throw new UnsupportedOperationException(); - } - - @Override - public T fromDouble(double d) { - throw new UnsupportedOperationException(); - } - - @Override - public T get(double x, double z) { - if(options.length == 0) { - return null; - } - - return options[stream.get(x, z)]; - } - - @Override - public T get(double x, double y, double z) { - if(options.length == 0) { - return null; - } - - return options[stream.get(x, y, z)]; - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/SignificanceStream.java b/src/main/java/com/volmit/iris/util/stream/convert/SignificanceStream.java deleted file mode 100644 index b2a13d7b9..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/SignificanceStream.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.stream.ArraySignificance; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.stream.Significance; - -public class SignificanceStream, T> extends BasicStream { - private final ProceduralStream stream; - private final double radius; - private final int checks; - - public SignificanceStream(ProceduralStream stream, double radius, int checks) { - super(); - this.stream = stream; - this.radius = radius; - this.checks = checks; - } - - @Override - public double toDouble(K t) { - return 0; - } - - @Override - public K fromDouble(double d) { - return null; - } - - @SuppressWarnings("unchecked") - @Override - public K get(double x, double z) { - KList ke = new KList<>(8); - KList va = new KList<>(8); - - double m = (360d / checks); - double v = 0; - - for(int i = 0; i < 360; i += m) { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - double cx = x + ((radius * cos) - (radius * sin)); - double cz = z + ((radius * sin) + (radius * cos)); - T t = stream.get(cx, cz); - - if(ke.addIfMissing(t)) { - va.add(1D); - v++; - } else { - int ind = ke.indexOf(t); - va.set(ind, va.get(ind) + 1D); - } - } - - for(int i = 0; i < va.size(); i++) { - va.set(i, va.get(i) / v); - } - - return (K) new ArraySignificance<>(ke, va); - } - - @Override - public K get(double x, double y, double z) { - return get(x, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/convert/To3DStream.java b/src/main/java/com/volmit/iris/util/stream/convert/To3DStream.java deleted file mode 100644 index 969211ae4..000000000 --- a/src/main/java/com/volmit/iris/util/stream/convert/To3DStream.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.convert; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class To3DStream extends BasicStream { - public To3DStream(ProceduralStream stream) { - super(stream); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return getTypedSource().get(x, z); - } - - @Override - public T get(double x, double y, double z) { - return getTypedSource().fromDouble(getTypedSource().getDouble(x, z) >= y ? 1D : 0D); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/BiHermiteStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/BiHermiteStream.java deleted file mode 100644 index e0604eb03..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/BiHermiteStream.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class BiHermiteStream extends BasicStream implements Interpolator { - private final int rx; - private final int ry; - private final double tension; - private final double bias; - - public BiHermiteStream(ProceduralStream stream, int rx, int ry, double tension, double bias) { - super(stream); - this.rx = rx; - this.ry = ry; - this.tension = tension; - this.bias = bias; - } - - public BiHermiteStream(ProceduralStream stream, int rx, int ry) { - this(stream, rx, ry, 0.5, 0); - } - - public T interpolate(double x, double y) { - int fx = (int) Math.floor(x / rx); - int fz = (int) Math.floor(y / ry); - int x0 = Math.round((fx - 1) * rx); - int z0 = Math.round((fz - 1) * ry); - int x1 = Math.round(fx * rx); - int z1 = Math.round(fz * ry); - int x2 = Math.round((fx + 1) * rx); - int z2 = Math.round((fz + 1) * ry); - int x3 = Math.round((fx + 2) * rx); - int z3 = Math.round((fz + 2) * ry); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); - - //@builder - return getTypedSource().fromDouble(IrisInterpolation.bihermite( - getTypedSource().getDouble(x0, z0), - getTypedSource().getDouble(x0, z1), - getTypedSource().getDouble(x0, z2), - getTypedSource().getDouble(x0, z3), - getTypedSource().getDouble(x1, z0), - getTypedSource().getDouble(x1, z1), - getTypedSource().getDouble(x1, z2), - getTypedSource().getDouble(x1, z3), - getTypedSource().getDouble(x2, z0), - getTypedSource().getDouble(x2, z1), - getTypedSource().getDouble(x2, z2), - getTypedSource().getDouble(x2, z3), - getTypedSource().getDouble(x3, z0), - getTypedSource().getDouble(x3, z1), - getTypedSource().getDouble(x3, z2), - getTypedSource().getDouble(x3, z3), - px, pz, tension, bias)); - //@done - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/BiStarcastStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/BiStarcastStream.java deleted file mode 100644 index 05d696d67..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/BiStarcastStream.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class BiStarcastStream extends BasicStream implements Interpolator { - private final int rad; - private final int checks; - - public BiStarcastStream(ProceduralStream stream, int rad, int checks) { - super(stream); - this.rad = rad; - this.checks = checks; - } - - public T interpolate(double x, double y) { - double m = (360D / checks); - double v = 0; - - for(int i = 0; i < 360; i += m) { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - double cx = x + ((rad * cos) - (rad * sin)); - double cz = y + ((rad * sin) + (rad * cos)); - v += getTypedSource().getDouble(cx, cz); - } - - return getTypedSource().fromDouble(v / checks); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/BicubicStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/BicubicStream.java deleted file mode 100644 index 288b46122..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/BicubicStream.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class BicubicStream extends BasicStream implements Interpolator { - private final int rx; - private final int ry; - - public BicubicStream(ProceduralStream stream, int rx, int ry) { - super(stream); - this.rx = rx; - this.ry = ry; - } - - public T interpolate(double x, double y) { - int fx = (int) Math.floor(x / rx); - int fz = (int) Math.floor(y / ry); - int x0 = Math.round((fx - 1) * rx); - int z0 = Math.round((fz - 1) * ry); - int x1 = Math.round(fx * rx); - int z1 = Math.round(fz * ry); - int x2 = Math.round((fx + 1) * rx); - int z2 = Math.round((fz + 1) * ry); - int x3 = Math.round((fx + 2) * rx); - int z3 = Math.round((fz + 2) * ry); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); - - //@builder - return getTypedSource().fromDouble(IrisInterpolation.bicubic( - getTypedSource().getDouble(x0, z0), - getTypedSource().getDouble(x0, z1), - getTypedSource().getDouble(x0, z2), - getTypedSource().getDouble(x0, z3), - getTypedSource().getDouble(x1, z0), - getTypedSource().getDouble(x1, z1), - getTypedSource().getDouble(x1, z2), - getTypedSource().getDouble(x1, z3), - getTypedSource().getDouble(x2, z0), - getTypedSource().getDouble(x2, z1), - getTypedSource().getDouble(x2, z2), - getTypedSource().getDouble(x2, z3), - getTypedSource().getDouble(x3, z0), - getTypedSource().getDouble(x3, z1), - getTypedSource().getDouble(x3, z2), - getTypedSource().getDouble(x3, z3), - px, pz)); - //@done - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/BilinearStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/BilinearStream.java deleted file mode 100644 index a7e0cf373..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/BilinearStream.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class BilinearStream extends BasicStream implements Interpolator { - private final int rx; - private final int ry; - - public BilinearStream(ProceduralStream stream, int rx, int ry) { - super(stream); - this.rx = rx; - this.ry = ry; - } - - public T interpolate(double x, double y) { - int fx = (int) Math.floor(x / rx); - int fz = (int) Math.floor(y / ry); - int x1 = Math.round(fx * rx); - int z1 = Math.round(fz * ry); - int x2 = Math.round((fx + 1) * rx); - int z2 = Math.round((fz + 1) * ry); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); - - //@builder - return getTypedSource().fromDouble(IrisInterpolation.blerp( - getTypedSource().getDouble(x1, z1), - getTypedSource().getDouble(x2, z1), - getTypedSource().getDouble(x1, z2), - getTypedSource().getDouble(x2, z2), - px, pz)); - //@done - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/Interpolated.java b/src/main/java/com/volmit/iris/util/stream/interpolation/Interpolated.java deleted file mode 100644 index b61fb2acb..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/Interpolated.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.CaveResult; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.stream.ProceduralStream; -import org.bukkit.block.data.BlockData; - -import java.util.UUID; -import java.util.function.Function; - -public interface Interpolated { - Interpolated BLOCK_DATA = of((t) -> 0D, (t) -> null); - Interpolated> CAVE_RESULTS = of((t) -> 0D, (t) -> null); - Interpolated RNG = of((t) -> 0D, (t) -> null); - Interpolated DOUBLE = of((t) -> t, (t) -> t); - Interpolated DOUBLE_ARRAY = of((t) -> 0D, (t) -> new Double[2]); - Interpolated BOOLEAN = of((t) -> 0D, (t) -> false); - Interpolated INT = of(Double::valueOf, Double::intValue); - Interpolated LONG = of(Double::valueOf, Double::longValue); - Interpolated UUID = of((i) -> Double.longBitsToDouble(i.getMostSignificantBits()), (i) -> new UUID(Double.doubleToLongBits(i), i.longValue())); - - static Interpolated of(Function a, Function b) { - return new Interpolated<>() { - @Override - public double toDouble(T t) { - return a.apply(t); - } - - @Override - public T fromDouble(double d) { - return b.apply(d); - } - }; - } - - double toDouble(T t); - - T fromDouble(double d); - - default InterpolatorFactory interpolate() { - if(this instanceof ProceduralStream) { - return new InterpolatorFactory<>((ProceduralStream) this); - } - - Iris.warn("Cannot interpolate " + this.getClass().getCanonicalName() + "!"); - return null; - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/InterpolatingStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/InterpolatingStream.java deleted file mode 100644 index 12ef7a078..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/InterpolatingStream.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.function.NoiseProvider; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class InterpolatingStream extends BasicStream implements Interpolator { - private final InterpolationMethod type; - private final NoiseProvider np; - private final int rx; - - public InterpolatingStream(ProceduralStream stream, int rx, InterpolationMethod type) { - super(stream); - this.type = type; - this.rx = rx; - this.np = (xf, zf) -> getTypedSource().getDouble(xf, zf); - } - - public T interpolate(double x, double y) { - return fromDouble(IrisInterpolation.getNoise(type, (int) x, (int) y, rx, np)); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/Interpolator.java b/src/main/java/com/volmit/iris/util/stream/interpolation/Interpolator.java deleted file mode 100644 index 6df5068b0..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/Interpolator.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.stream.ProceduralStream; - -public interface Interpolator { - @SuppressWarnings("unchecked") - default InterpolatorFactory into() { - if(this instanceof ProceduralStream) { - return new InterpolatorFactory<>((ProceduralStream) this); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/InterpolatorFactory.java b/src/main/java/com/volmit/iris/util/stream/interpolation/InterpolatorFactory.java deleted file mode 100644 index 8ed1ee315..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/InterpolatorFactory.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.stream.ProceduralStream; - -@SuppressWarnings("ClassCanBeRecord") -public class InterpolatorFactory { - private final ProceduralStream stream; - - public InterpolatorFactory(ProceduralStream stream) { - this.stream = stream; - } - - public InterpolatingStream with(InterpolationMethod t, int rx) { - return new InterpolatingStream<>(stream, rx, t); - } - - public TrilinearStream trilinear(int rx, int ry, int rz) { - return new TrilinearStream<>(stream, rx, ry, rz); - } - - public TricubicStream tricubic(int rx, int ry, int rz) { - return new TricubicStream<>(stream, rx, ry, rz); - } - - public BicubicStream bicubic(int rx, int ry) { - return new BicubicStream<>(stream, rx, ry); - } - - public BicubicStream bicubic(int r) { - return bicubic(r, r); - } - - public BilinearStream bilinear(int rx, int ry) { - return new BilinearStream<>(stream, rx, ry); - } - - public BilinearStream bilinear(int r) { - return bilinear(r, r); - } - - public TriStarcastStream tristarcast(int radius, int checks) { - return new TriStarcastStream<>(stream, radius, checks); - } - - public TriStarcastStream tristarcast3(int radius) { - return tristarcast(radius, 3); - } - - public TriStarcastStream tristarcast6(int radius) { - return tristarcast(radius, 6); - } - - public TriStarcastStream tristarcast9(int radius) { - return tristarcast(radius, 9); - } - - public BiStarcastStream bistarcast(int radius, int checks) { - return new BiStarcastStream<>(stream, radius, checks); - } - - public BiStarcastStream bistarcast3(int radius) { - return bistarcast(radius, 3); - } - - public BiStarcastStream bistarcast6(int radius) { - return bistarcast(radius, 6); - } - - public BiStarcastStream bistarcast9(int radius) { - return bistarcast(radius, 9); - } - - public BiHermiteStream bihermite(int rx, int ry, double tension, double bias) { - return new BiHermiteStream<>(stream, rx, ry, tension, bias); - } - - public BiHermiteStream bihermite(int rx, int ry) { - return new BiHermiteStream<>(stream, rx, ry); - } - - public BiHermiteStream bihermite(int r) { - return bihermite(r, r); - } - - public BiHermiteStream bihermite(int r, double tension, double bias) { - return bihermite(r, r, tension, bias); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/TriHermiteStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/TriHermiteStream.java deleted file mode 100644 index 0688599a4..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/TriHermiteStream.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class TriHermiteStream extends BasicStream implements Interpolator { - private final int rx; - private final int ry; - private final int rz; - private final double tension; - private final double bias; - - public TriHermiteStream(ProceduralStream stream, int rx, int ry, int rz, double tension, double bias) { - super(stream); - this.rx = rx; - this.ry = ry; - this.rz = rz; - this.tension = tension; - this.bias = bias; - } - - public T interpolate(double x, double y, double z) { - int fx = (int) Math.floor(x / rx); - int fy = (int) Math.floor(y / ry); - int fz = (int) Math.floor(z / rz); - int x0 = Math.round((fx - 1) * rx); - int y0 = Math.round((fy - 1) * ry); - int z0 = Math.round((fz - 1) * rz); - int x1 = Math.round(fx * rx); - int y1 = Math.round(fy * ry); - int z1 = Math.round(fz * rz); - int x2 = Math.round((fx + 1) * rx); - int y2 = Math.round((fy + 1) * ry); - int z2 = Math.round((fz + 1) * rz); - int x3 = Math.round((fx + 2) * rx); - int y3 = Math.round((fy + 2) * ry); - int z3 = Math.round((fz + 2) * rz); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); - - //@builder - return getTypedSource().fromDouble(IrisInterpolation.trihermite( - getTypedSource().getDouble(x0, y0, z0), - getTypedSource().getDouble(x0, y0, z1), - getTypedSource().getDouble(x0, y0, z2), - getTypedSource().getDouble(x0, y0, z3), - getTypedSource().getDouble(x1, y0, z0), - getTypedSource().getDouble(x1, y0, z1), - getTypedSource().getDouble(x1, y0, z2), - getTypedSource().getDouble(x1, y0, z3), - getTypedSource().getDouble(x2, y0, z0), - getTypedSource().getDouble(x2, y0, z1), - getTypedSource().getDouble(x2, y0, z2), - getTypedSource().getDouble(x2, y0, z3), - getTypedSource().getDouble(x3, y0, z0), - getTypedSource().getDouble(x3, y0, z1), - getTypedSource().getDouble(x3, y0, z2), - getTypedSource().getDouble(x3, y0, z3), - getTypedSource().getDouble(x0, y1, z0), - getTypedSource().getDouble(x0, y1, z1), - getTypedSource().getDouble(x0, y1, z2), - getTypedSource().getDouble(x0, y1, z3), - getTypedSource().getDouble(x1, y1, z0), - getTypedSource().getDouble(x1, y1, z1), - getTypedSource().getDouble(x1, y1, z2), - getTypedSource().getDouble(x1, y1, z3), - getTypedSource().getDouble(x2, y1, z0), - getTypedSource().getDouble(x2, y1, z1), - getTypedSource().getDouble(x2, y1, z2), - getTypedSource().getDouble(x2, y1, z3), - getTypedSource().getDouble(x3, y1, z0), - getTypedSource().getDouble(x3, y1, z1), - getTypedSource().getDouble(x3, y1, z2), - getTypedSource().getDouble(x3, y1, z3), - getTypedSource().getDouble(x0, y2, z0), - getTypedSource().getDouble(x0, y2, z1), - getTypedSource().getDouble(x0, y2, z2), - getTypedSource().getDouble(x0, y2, z3), - getTypedSource().getDouble(x1, y2, z0), - getTypedSource().getDouble(x1, y2, z1), - getTypedSource().getDouble(x1, y2, z2), - getTypedSource().getDouble(x1, y2, z3), - getTypedSource().getDouble(x2, y2, z0), - getTypedSource().getDouble(x2, y2, z1), - getTypedSource().getDouble(x2, y2, z2), - getTypedSource().getDouble(x2, y2, z3), - getTypedSource().getDouble(x3, y2, z0), - getTypedSource().getDouble(x3, y2, z1), - getTypedSource().getDouble(x3, y2, z2), - getTypedSource().getDouble(x3, y2, z3), - getTypedSource().getDouble(x0, y3, z0), - getTypedSource().getDouble(x0, y3, z1), - getTypedSource().getDouble(x0, y3, z2), - getTypedSource().getDouble(x0, y3, z3), - getTypedSource().getDouble(x1, y3, z0), - getTypedSource().getDouble(x1, y3, z1), - getTypedSource().getDouble(x1, y3, z2), - getTypedSource().getDouble(x1, y3, z3), - getTypedSource().getDouble(x2, y3, z0), - getTypedSource().getDouble(x2, y3, z1), - getTypedSource().getDouble(x2, y3, z2), - getTypedSource().getDouble(x2, y3, z3), - getTypedSource().getDouble(x3, y3, z0), - getTypedSource().getDouble(x3, y3, z1), - getTypedSource().getDouble(x3, y3, z2), - getTypedSource().getDouble(x3, y3, z3), - px, pz, py, tension, bias)); - //@done - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, 0, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, y, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/TriStarcastStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/TriStarcastStream.java deleted file mode 100644 index 1c8db4b91..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/TriStarcastStream.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class TriStarcastStream extends BasicStream implements Interpolator { - private final int rad; - private final int checks; - - public TriStarcastStream(ProceduralStream stream, int rad, int checks) { - super(stream); - this.rad = rad; - this.checks = checks; - } - - public T interpolate(double x, double y, double z) { - double m = (360D / checks); - double v = 0; - - for(int i = 0; i < 360; i += m) { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - double cx = x + ((rad * cos) - (rad * sin)); - double cy = y + ((rad * sin) + (rad * cos)); - double cz = z + ((rad * cos) - (rad * sin)); - v += getTypedSource().getDouble(cx, cy, cz); - } - - return getTypedSource().fromDouble(v / checks); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, 0, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, y, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/TricubicStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/TricubicStream.java deleted file mode 100644 index 4ad809a27..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/TricubicStream.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class TricubicStream extends BasicStream implements Interpolator { - private final int rx; - private final int ry; - private final int rz; - - public TricubicStream(ProceduralStream stream, int rx, int ry, int rz) { - super(stream); - this.rx = rx; - this.ry = ry; - this.rz = rz; - } - - public T interpolate(double x, double y, double z) { - int fx = (int) Math.floor(x / rx); - int fy = (int) Math.floor(y / ry); - int fz = (int) Math.floor(z / rz); - int x0 = Math.round((fx - 1) * rx); - int y0 = Math.round((fy - 1) * ry); - int z0 = Math.round((fz - 1) * rz); - int x1 = Math.round(fx * rx); - int y1 = Math.round(fy * ry); - int z1 = Math.round(fz * rz); - int x2 = Math.round((fx + 1) * rx); - int y2 = Math.round((fy + 1) * ry); - int z2 = Math.round((fz + 1) * rz); - int x3 = Math.round((fx + 2) * rx); - int y3 = Math.round((fy + 2) * ry); - int z3 = Math.round((fz + 2) * rz); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); - - //@builder - return getTypedSource().fromDouble(IrisInterpolation.tricubic( - getTypedSource().getDouble(x0, y0, z0), - getTypedSource().getDouble(x0, y0, z1), - getTypedSource().getDouble(x0, y0, z2), - getTypedSource().getDouble(x0, y0, z3), - getTypedSource().getDouble(x1, y0, z0), - getTypedSource().getDouble(x1, y0, z1), - getTypedSource().getDouble(x1, y0, z2), - getTypedSource().getDouble(x1, y0, z3), - getTypedSource().getDouble(x2, y0, z0), - getTypedSource().getDouble(x2, y0, z1), - getTypedSource().getDouble(x2, y0, z2), - getTypedSource().getDouble(x2, y0, z3), - getTypedSource().getDouble(x3, y0, z0), - getTypedSource().getDouble(x3, y0, z1), - getTypedSource().getDouble(x3, y0, z2), - getTypedSource().getDouble(x3, y0, z3), - - getTypedSource().getDouble(x0, y1, z0), - getTypedSource().getDouble(x0, y1, z1), - getTypedSource().getDouble(x0, y1, z2), - getTypedSource().getDouble(x0, y1, z3), - getTypedSource().getDouble(x1, y1, z0), - getTypedSource().getDouble(x1, y1, z1), - getTypedSource().getDouble(x1, y1, z2), - getTypedSource().getDouble(x1, y1, z3), - getTypedSource().getDouble(x2, y1, z0), - getTypedSource().getDouble(x2, y1, z1), - getTypedSource().getDouble(x2, y1, z2), - getTypedSource().getDouble(x2, y1, z3), - getTypedSource().getDouble(x3, y1, z0), - getTypedSource().getDouble(x3, y1, z1), - getTypedSource().getDouble(x3, y1, z2), - getTypedSource().getDouble(x3, y1, z3), - - getTypedSource().getDouble(x0, y2, z0), - getTypedSource().getDouble(x0, y2, z1), - getTypedSource().getDouble(x0, y2, z2), - getTypedSource().getDouble(x0, y2, z3), - getTypedSource().getDouble(x1, y2, z0), - getTypedSource().getDouble(x1, y2, z1), - getTypedSource().getDouble(x1, y2, z2), - getTypedSource().getDouble(x1, y2, z3), - getTypedSource().getDouble(x2, y2, z0), - getTypedSource().getDouble(x2, y2, z1), - getTypedSource().getDouble(x2, y2, z2), - getTypedSource().getDouble(x2, y2, z3), - getTypedSource().getDouble(x3, y2, z0), - getTypedSource().getDouble(x3, y2, z1), - getTypedSource().getDouble(x3, y2, z2), - getTypedSource().getDouble(x3, y2, z3), - - getTypedSource().getDouble(x0, y3, z0), - getTypedSource().getDouble(x0, y3, z1), - getTypedSource().getDouble(x0, y3, z2), - getTypedSource().getDouble(x0, y3, z3), - getTypedSource().getDouble(x1, y3, z0), - getTypedSource().getDouble(x1, y3, z1), - getTypedSource().getDouble(x1, y3, z2), - getTypedSource().getDouble(x1, y3, z3), - getTypedSource().getDouble(x2, y3, z0), - getTypedSource().getDouble(x2, y3, z1), - getTypedSource().getDouble(x2, y3, z2), - getTypedSource().getDouble(x2, y3, z3), - getTypedSource().getDouble(x3, y3, z0), - getTypedSource().getDouble(x3, y3, z1), - getTypedSource().getDouble(x3, y3, z2), - getTypedSource().getDouble(x3, y3, z3), - px, pz, py)); - //@done - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, 0, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, y, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/interpolation/TrilinearStream.java b/src/main/java/com/volmit/iris/util/stream/interpolation/TrilinearStream.java deleted file mode 100644 index 4be5f5d9f..000000000 --- a/src/main/java/com/volmit/iris/util/stream/interpolation/TrilinearStream.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.interpolation; - -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class TrilinearStream extends BasicStream implements Interpolator { - private final int rx; - private final int ry; - private final int rz; - - public TrilinearStream(ProceduralStream stream, int rx, int ry, int rz) { - super(stream); - this.rx = rx; - this.ry = ry; - this.rz = rz; - } - - public T interpolate(double x, double y, double z) { - int fx = (int) Math.floor(x / rx); - int fy = (int) Math.floor(y / ry); - int fz = (int) Math.floor(z / rz); - int x1 = Math.round(fx * rx); - int y1 = Math.round(fy * ry); - int z1 = Math.round(fz * rz); - int x2 = Math.round((fx + 1) * rx); - int y2 = Math.round((fy + 1) * ry); - int z2 = Math.round((fz + 1) * rz); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); - - //@builder - return getTypedSource().fromDouble(IrisInterpolation.trilerp( - getTypedSource().getDouble(x1, y1, z1), - getTypedSource().getDouble(x2, y1, z1), - getTypedSource().getDouble(x1, y1, z2), - getTypedSource().getDouble(x2, y1, z2), - getTypedSource().getDouble(x1, y2, z1), - getTypedSource().getDouble(x2, y2, z1), - getTypedSource().getDouble(x1, y2, z2), - getTypedSource().getDouble(x2, y2, z2), - px, pz, py)); - //@done - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - return interpolate(x, 0, z); - } - - @Override - public T get(double x, double y, double z) { - return interpolate(x, y, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/sources/CNGStream.java b/src/main/java/com/volmit/iris/util/stream/sources/CNGStream.java deleted file mode 100644 index 4878a5e58..000000000 --- a/src/main/java/com/volmit/iris/util/stream/sources/CNGStream.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.sources; - -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.stream.BasicLayer; -import com.volmit.iris.util.stream.ProceduralStream; - -public class CNGStream extends BasicLayer implements ProceduralStream { - private final CNG cng; - - public CNGStream(CNG cng) { - this.cng = cng; - } - - public CNGStream(CNG cng, double zoom, double offsetX, double offsetY, double offsetZ) { - super(1337, zoom, offsetX, offsetY, offsetZ); - this.cng = cng; - } - - public CNGStream(CNG cng, double zoom) { - super(1337, zoom); - this.cng = cng; - } - - @Override - public double toDouble(Double t) { - return t; - } - - @Override - public Double fromDouble(double d) { - return d; - } - - @Override - public ProceduralStream getTypedSource() { - return null; - } - - @Override - public ProceduralStream getSource() { - return null; - } - - @Override - public Double get(double x, double z) { - return cng.noise((x + getOffsetX()) / getZoom(), (z + getOffsetZ()) / getZoom()); - } - - @Override - public Double get(double x, double y, double z) { - return cng.noise((x + getOffsetX()) / getZoom(), (y + getOffsetY()) / getZoom(), (z + getOffsetZ()) * getZoom()); - } - -} diff --git a/src/main/java/com/volmit/iris/util/stream/sources/FunctionStream.java b/src/main/java/com/volmit/iris/util/stream/sources/FunctionStream.java deleted file mode 100644 index 66a1ce506..000000000 --- a/src/main/java/com/volmit/iris/util/stream/sources/FunctionStream.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.sources; - -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.Function3; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.interpolation.Interpolated; - -public class FunctionStream extends BasicStream { - private final Function2 f2; - private final Function3 f3; - private final Interpolated helper; - - public FunctionStream(Function2 f2, Function3 f3, Interpolated helper) { - super(); - this.f2 = f2; - this.f3 = f3; - this.helper = helper; - } - - @Override - public double toDouble(T t) { - return helper.toDouble(t); - } - - @Override - public T fromDouble(double d) { - return helper.fromDouble(d); - } - - @Override - public T get(double x, double z) { - return f2.apply(x, z); - } - - @Override - public T get(double x, double y, double z) { - return f3.apply(x, y, z); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/utility/CachedStream2D.java b/src/main/java/com/volmit/iris/util/stream/utility/CachedStream2D.java deleted file mode 100644 index 5bfda4b23..000000000 --- a/src/main/java/com/volmit/iris/util/stream/utility/CachedStream2D.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.utility; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.PreservationSVC; -import com.volmit.iris.engine.data.cache.Cache; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.MeteredCache; -import com.volmit.iris.util.data.KCache; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class CachedStream2D extends BasicStream implements ProceduralStream, MeteredCache { - private final ProceduralStream stream; - private final KCache cache; - private final Engine engine; - - public CachedStream2D(String name, Engine engine, ProceduralStream stream, int size) { - super(); - this.stream = stream; - this.engine = engine; - cache = new KCache<>(k -> stream.get(Cache.keyX(k), Cache.keyZ(k)), size); - Iris.service(PreservationSVC.class).registerCache(this); - } - - @Override - public double toDouble(T t) { - return stream.toDouble(t); - } - - @Override - public T fromDouble(double d) { - return stream.fromDouble(d); - } - - @Override - public T get(double x, double z) { - return cache.get(Cache.key((int) x, (int) z)); - } - - @Override - public T get(double x, double y, double z) { - return stream.get(x, y, z); - } - - @Override - public long getSize() { - return cache.getSize(); - } - - @Override - public KCache getRawCache() { - return cache; - } - - @Override - public long getMaxSize() { - return cache.getMaxSize(); - } - - @Override - public boolean isClosed() { - return engine.isClosed(); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/utility/CachedStream3D.java b/src/main/java/com/volmit/iris/util/stream/utility/CachedStream3D.java deleted file mode 100644 index 7c1b66407..000000000 --- a/src/main/java/com/volmit/iris/util/stream/utility/CachedStream3D.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.utility; - -import com.volmit.iris.Iris; -import com.volmit.iris.core.service.PreservationSVC; -import com.volmit.iris.engine.framework.Engine; -import com.volmit.iris.engine.framework.MeteredCache; -import com.volmit.iris.util.data.KCache; -import com.volmit.iris.util.math.BlockPosition; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class CachedStream3D extends BasicStream implements ProceduralStream, MeteredCache { - private final ProceduralStream stream; - private final KCache cache; - private final Engine engine; - - public CachedStream3D(String name, Engine engine, ProceduralStream stream, int size) { - super(); - this.stream = stream; - this.engine = engine; - cache = new KCache<>((k) -> stream.get(k.getX(), k.getY(), k.getZ()), size); - Iris.service(PreservationSVC.class).registerCache(this); - } - - @Override - public double toDouble(T t) { - return stream.toDouble(t); - } - - @Override - public T fromDouble(double d) { - return stream.fromDouble(d); - } - - @Override - public T get(double x, double z) { - return cache.get(new BlockPosition((int) x, 0, (int) z)); - } - - @Override - public T get(double x, double y, double z) { - return cache.get(new BlockPosition((int) x, (int) y, (int) z)); - } - - @Override - public long getSize() { - return cache.getSize(); - } - - @Override - public KCache getRawCache() { - return cache; - } - - @Override - public long getMaxSize() { - return cache.getMaxSize(); - } - - @Override - public boolean isClosed() { - return engine.isClosed(); - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/utility/NullSafeStream.java b/src/main/java/com/volmit/iris/util/stream/utility/NullSafeStream.java deleted file mode 100644 index 864c9d3d3..000000000 --- a/src/main/java/com/volmit/iris/util/stream/utility/NullSafeStream.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.utility; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class NullSafeStream extends BasicStream implements ProceduralStream { - private final ProceduralStream stream; - private final T ifNull; - - public NullSafeStream(ProceduralStream stream, T ifNull) { - super(); - this.stream = stream; - this.ifNull = ifNull; - } - - @Override - public double toDouble(T t) { - return stream.toDouble(t); - } - - @Override - public T fromDouble(double d) { - return stream.fromDouble(d); - } - - @Override - public T get(double x, double z) { - T t = stream.get(x, z); - - if(t == null) { - return ifNull; - } - - return t; - } - - @Override - public T get(double x, double y, double z) { - T t = stream.get(x, y, z); - - if(t == null) { - return ifNull; - } - - return t; - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/utility/ProfiledStream.java b/src/main/java/com/volmit/iris/util/stream/utility/ProfiledStream.java deleted file mode 100644 index 7309cfc67..000000000 --- a/src/main/java/com/volmit/iris/util/stream/utility/ProfiledStream.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.utility; - -import com.volmit.iris.Iris; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.math.RollingSequence; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; -import lombok.Data; - -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; - -public class ProfiledStream extends BasicStream { - public static final AtomicInteger ids = new AtomicInteger(); - private final int id; - private final RollingSequence metrics; - - public ProfiledStream(ProceduralStream stream, int memory) { - super(stream); - this.metrics = new RollingSequence(memory); - this.id = ids.getAndAdd(1); - } - - public static void print(Consumer printer, ProceduralStream stream) { - KList tails = getTails(stream); - int ind = tails.size(); - for(ProfiledTail i : tails) { - printer.accept(Form.repeat(" ", ind) + i); - ind--; - } - } - - private static KList> getAllChildren(ProceduralStream s) { - KList> v = new KList<>(); - ProceduralStream cursor = s; - - for(int i = 0; i < 32; i++) { - v.add(cursor); - cursor = nextChuld(cursor); - - if(cursor == null) { - break; - } - } - - return v; - } - - private static ProceduralStream nextChuld(ProceduralStream s) { - ProceduralStream v = s.getTypedSource(); - return v == null ? s.getSource() : v; - } - - private static ProfiledTail getTail(ProceduralStream t) { - if(t instanceof ProfiledStream s) { - - return new ProfiledTail(s.getId(), s.getMetrics(), s.getClass().getSimpleName().replaceAll("\\QStream\\E", "")); - } - - return null; - } - - private static KList getTails(ProceduralStream t) { - KList tails = new KList<>(); - - for(ProceduralStream v : getAllChildren(t)) { - ProfiledTail p = getTail(v); - - if(p != null) { - tails.add(p); - } - } - - if(tails.isEmpty()) { - return null; - } - - ProfiledTail cursor = tails.popLast(); - KList tailx = new KList<>(); - tailx.add(cursor); - - while(tails.isNotEmpty()) { - tailx.add(cursor); - ProfiledTail parent = tails.popLast(); - parent.setChild(cursor); - cursor = parent; - tailx.add(cursor); - } - - return tailx; - } - - public int getId() { - return id; - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - T t = getTypedSource().get(x, z); - try { - metrics.put(p.getMilliseconds()); - } catch(Throwable e) { - Iris.reportError(e); - } - - return t; - } - - @Override - public T get(double x, double y, double z) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - T t = getTypedSource().get(x, y, z); - try { - metrics.put(p.getMilliseconds()); - } catch(Throwable e) { - Iris.reportError(e); - } - - return t; - } - - public RollingSequence getMetrics() { - return metrics; - } - - @Data - private static class ProfiledTail { - private final int id; - private final RollingSequence metrics; - private final String name; - private ProfiledTail child; - - public ProfiledTail(int id, RollingSequence metrics, String name) { - this.id = id; - this.metrics = metrics; - this.name = name; - } - - public String toString() { - return id + "-" + name + ": " + Form.duration(metrics.getAverage(), 2); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/utility/SemaphoreStream.java b/src/main/java/com/volmit/iris/util/stream/utility/SemaphoreStream.java deleted file mode 100644 index 94b7f9aa9..000000000 --- a/src/main/java/com/volmit/iris/util/stream/utility/SemaphoreStream.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.utility; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -import java.util.concurrent.Semaphore; - -public class SemaphoreStream extends BasicStream { - private final Semaphore semaphore; - - public SemaphoreStream(ProceduralStream stream, int permits) { - super(stream); - this.semaphore = new Semaphore(permits); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - try { - semaphore.acquire(); - T t = getTypedSource().get(x, z); - semaphore.release(); - return t; - } catch(InterruptedException e) { - e.printStackTrace(); - } - - return null; - } - - @Override - public T get(double x, double y, double z) { - try { - semaphore.acquire(); - T t = getTypedSource().get(x, y, z); - semaphore.release(); - return t; - } catch(InterruptedException e) { - e.printStackTrace(); - } - - return null; - } -} diff --git a/src/main/java/com/volmit/iris/util/stream/utility/SynchronizedStream.java b/src/main/java/com/volmit/iris/util/stream/utility/SynchronizedStream.java deleted file mode 100644 index 95f3137aa..000000000 --- a/src/main/java/com/volmit/iris/util/stream/utility/SynchronizedStream.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * 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 . - */ - -package com.volmit.iris.util.stream.utility; - -import com.volmit.iris.util.stream.BasicStream; -import com.volmit.iris.util.stream.ProceduralStream; - -public class SynchronizedStream extends BasicStream { - public SynchronizedStream(ProceduralStream stream) { - super(stream); - } - - @Override - public double toDouble(T t) { - return getTypedSource().toDouble(t); - } - - @Override - public T fromDouble(double d) { - return getTypedSource().fromDouble(d); - } - - @Override - public T get(double x, double z) { - synchronized(getTypedSource()) { - return getTypedSource().get(x, z); - } - } - - @Override - public T get(double x, double y, double z) { - synchronized(getTypedSource()) { - return getTypedSource().get(x, y, z); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/U.java b/src/main/java/com/volmit/iris/util/uniques/U.java deleted file mode 100644 index 97f559104..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/U.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.volmit.iris.util.uniques; - -import java.io.File; - -public class U { - public static void main(String[] a) - { - UniqueRenderer r = new UniqueRenderer("helloworld", 2560 , 1440); - - r.writeCollectionFrames(new File("collection"), 1, 1024); - - System.exit(0); - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/UBufferedImage.java b/src/main/java/com/volmit/iris/util/uniques/UBufferedImage.java deleted file mode 100644 index 3211d49a2..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/UBufferedImage.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.volmit.iris.util.uniques; - -import java.awt.*; -import java.awt.image.BufferedImage; -import java.awt.image.ColorModel; -import java.awt.image.WritableRaster; - -public class UBufferedImage implements UImage { - private final BufferedImage buf; - - public UBufferedImage(BufferedImage buf) - { - this.buf = buf; - } - - @Override - public int getWidth() { - return buf.getWidth(); - } - - @Override - public int getHeight() { - return buf.getHeight(); - } - - @Override - public UImage copy() { - ColorModel cm = buf.getColorModel(); - boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); - WritableRaster raster = buf.copyData(null); - return new UBufferedImage(new BufferedImage(cm, raster, isAlphaPremultiplied, null)); - } - - @Override - public Color get(int x, int y) { - return new Color(buf.getRGB(x, y)); - } - - @Override - public void set(int x, int y, Color color) { - try - { - buf.setRGB(x, y, color.getRGB()); - } - - catch(Throwable e) - { - - } - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/UFeature.java b/src/main/java/com/volmit/iris/util/uniques/UFeature.java deleted file mode 100644 index a06ccd00b..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/UFeature.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.volmit.iris.util.uniques; - -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.function.Function2; -import com.volmit.iris.util.function.NoiseInjector; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.stream.interpolation.Interpolated; - -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.List; -import java.util.function.Consumer; - -public interface UFeature { - List injectors = List.of( - CNG.ADD, - CNG.DST_MOD, - CNG.DST_POW, - CNG.DST_SUBTRACT, - CNG.MAX, - CNG.MIN, - CNG.SRC_MOD, - CNG.SRC_POW, - CNG.SRC_SUBTRACT, - CNG.MULTIPLY - ); - - void render(UImage image, RNG rng, double time, Consumer progressor, UFeatureMeta meta); - - default Color color(CNG hue, CNG saturation, CNG brightness, double x, double y, double t) - { - return Color.getHSBColor((float)hue.fitDouble(0, 1, x + t, y + t), - (float)saturation.fitDouble(0, 1, x + t, y + t), - (float)brightness.fitDouble(0, 1, x + t, y + t)); - } - - default InterpolationMethod interpolator(RNG rng) - { - return rng.pick( - UniqueRenderer.renderer.getInterpolators() - ); - } - - default CNG generator(String key, RNG rng, double scaleMod, long salt, UFeatureMeta meta) - { - return generator(key, rng, scaleMod, rng.i(1, 3), rng.i(1, 5), salt, meta); - } - - default CNG generator(String key, RNG rng, double scaleMod, int fractures, int composites, long salt, UFeatureMeta meta) - { - RNG rngg = rng.nextParallelRNG(salt); - CNG cng = rng.pick(UniqueRenderer.renderer.getStyles()).create(rngg).oct(rng.i(1, 5)); - RNG rngf = rngg.nextParallelRNG(-salt); - cng.scale(rngf.d(0.33 * scaleMod, 1.66 * scaleMod)); - - if(fractures > 0) - { - cng.fractureWith(generator(null, rngf.nextParallelRNG(salt + fractures), scaleMod / rng.d(4, 17), fractures-1, composites, salt + fractures + 55, null), scaleMod * rngf.nextDouble(16, 256)); - } - - for(int i = 0; i < composites; i++) - { - CNG sub = generator(null, rngf.nextParallelRNG(salt + fractures), scaleMod * rngf.d(0.4, 3.3), fractures / 3, 0, salt + fractures + composites + 78, null); - sub.setInjector(rng.pick(injectors)); - cng.child(sub); - } - - if(key != null && meta != null) - { - meta.registerGenerator(key, cng); - } - return cng; - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/UFeatureMeta.java b/src/main/java/com/volmit/iris/util/uniques/UFeatureMeta.java deleted file mode 100644 index faa87fef1..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/UFeatureMeta.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.volmit.iris.util.uniques; - -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.function.NoiseInjector; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@NoArgsConstructor -public class UFeatureMeta { - private KMap interpolators; - private KMap generators; - private String feature; - - public void registerInterpolator(String key, InterpolationMethod method, double radius) - { - if(interpolators == null) - { - interpolators = new KMap<>(); - } - interpolators.put(key, new UFeatureMetaInterpolator(method, radius)); - } - - public void registerGenerator(String key, CNG cng) - { - if(generators == null) - { - generators = new KMap<>(); - } - generators.put(key, buildGenerator(cng)); - } - - public UFeatureMetaGenerator buildGenerator(CNG cng) - { - UFeatureMetaGenerator g = new UFeatureMetaGenerator(); - g.setScale(cng.getScale()); - g.setOctaves(cng.getOct()); - - if(cng.getFracture() != null) - { - g.setFracture(buildGenerator(cng.getFracture())); - g.setFractureMultiplier(cng.getFscale()); - } - - if(cng.getChildren() != null && cng.getChildren().isNotEmpty()) - { - g.setChildren(new KList<>()); - - for(CNG i : cng.getChildren()) - { - g.getChildren().add(buildGenerator(i)); - } - } - - if(cng.getInjector() == CNG.ADD){g.setParentInject("add");} - else if(cng.getInjector() == CNG.SRC_SUBTRACT){g.setParentInject("src_subtract");} - else if(cng.getInjector() == CNG.DST_SUBTRACT){g.setParentInject("dst_subtract");} - else if(cng.getInjector() == CNG.MULTIPLY ){g.setParentInject("multiply");} - else if(cng.getInjector() == CNG.MAX){g.setParentInject("max");} - else if(cng.getInjector() == CNG.MIN){g.setParentInject("min");} - else if(cng.getInjector() == CNG.SRC_MOD ){g.setParentInject("src_mod");} - else if(cng.getInjector() == CNG.SRC_POW ){g.setParentInject("src_pow");} - else if(cng.getInjector() == CNG.DST_MOD ){g.setParentInject("dst_mod");} - else if(cng.getInjector() == CNG.DST_POW){g.setParentInject("dst_pow");} - - return g; - } - - public boolean isEmpty() { - return (interpolators == null || interpolators.isEmpty()) && (generators == null || generators.isEmpty()); - } - - @Data - @NoArgsConstructor - @AllArgsConstructor - static class UFeatureMetaInterpolator - { - private InterpolationMethod interpolator; - private double radius; - } - - @Data - @NoArgsConstructor - static class UFeatureMetaGenerator - { - private NoiseStyle style; - private int octaves = 1; - private double scale = 1; - private String parentInject; - private UFeatureMetaGenerator fracture; - private Double fractureMultiplier; - private List children; - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/UImage.java b/src/main/java/com/volmit/iris/util/uniques/UImage.java deleted file mode 100644 index 821584a64..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/UImage.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.volmit.iris.util.uniques; - -import java.awt.*; - -public interface UImage { - int getWidth(); - - int getHeight(); - - default boolean isInBounds(int x, int y) - { - return x >= 0 && x < getWidth() && y >= 0 && y < getHeight(); - } - - UImage copy(); - - Color get(int x, int y); - - void set(int x, int y, Color color); -} diff --git a/src/main/java/com/volmit/iris/util/uniques/UMeta.java b/src/main/java/com/volmit/iris/util/uniques/UMeta.java deleted file mode 100644 index f5ba9aae6..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/UMeta.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.volmit.iris.util.uniques; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.io.IO; -import com.volmit.iris.util.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.List; - -@Data -@NoArgsConstructor -public class UMeta { - private transient BufferedImage image; - private KMap features; - private long id; - private double time; - private int width; - private int height; - - public void registerFeature(String key, UFeatureMeta feature) - { - if(features == null) - { - features = new KMap<>(); - } - - features.put(key, feature); - } - - public void export(File destination) throws IOException { - - for(String i : features.k()) - { - if(features.get(i).isEmpty()) - { - features.remove(i); - } - } - - width = image.getWidth(); - height = image.getHeight(); - ImageIO.write(image, "PNG", destination); - IO.writeAll(new File(destination.getParentFile(), destination.getName() + ".json"), new GsonBuilder().setPrettyPrinting().create().toJson(this)); - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/UniqueRenderer.java b/src/main/java/com/volmit/iris/util/uniques/UniqueRenderer.java deleted file mode 100644 index a8b80e3fe..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/UniqueRenderer.java +++ /dev/null @@ -1,338 +0,0 @@ -package com.volmit.iris.util.uniques; - -import com.volmit.iris.Iris; -import com.volmit.iris.engine.object.NoiseStyle; -import com.volmit.iris.util.collection.KList; -import com.volmit.iris.util.collection.KMap; -import com.volmit.iris.util.format.Form; -import com.volmit.iris.util.function.NoiseProvider; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.parallel.BurstExecutor; -import com.volmit.iris.util.parallel.MultiBurst; -import com.volmit.iris.util.scheduling.ChronoLatch; -import com.volmit.iris.util.scheduling.J; -import com.volmit.iris.util.scheduling.PrecisionStopwatch; -import com.volmit.iris.util.stream.ProceduralStream; -import com.volmit.iris.util.uniques.features.*; - -import javax.imageio.ImageIO; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.io.File; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - -public class UniqueRenderer { - static UniqueRenderer renderer; - - static final List backgrounds = List.of(new UFWarpedBackground()); - static final List interpolators = List.of(new UFInterpolator(), new UFNOOP()); - static final List features = List.of(new UFWarpedLines(), new UFWarpedDisc(), new UFWarpedDots(), new UFWarpedCircle()); - private final String seed; - private final ProceduralStream spatialSeed; - private final int width; - private final int height; - private final KMap writing = new KMap<>(); - private KList sortedStyles = new KList(); - private KList sortedInterpolators = new KList(); - int cores = Runtime.getRuntime().availableProcessors(); - private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); - - public UniqueRenderer(String seed, int width, int height) - { - renderer = this; - computeNoiseStyles(3000, 2); - computeInterpolationMethods(3000, 2); - this.seed = seed; - this.width = width; - this.height = height; - spatialSeed = NoiseStyle.FRACTAL_WATER.stream(new RNG(seed)).convert((d) -> new RNG(Math.round(seed.hashCode() + (d * 934321234D)))); - new Thread(() -> { - while(true) - { - J.sleep(5000); - - if(!writing.isEmpty()) - { - System.out.println(Form.repeat("\n", 60)); - System.out.println(Form.memSize(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(), 2) + " of " + Form.memSize(Runtime.getRuntime().totalMemory(), 2)); - KMap c = writing.copy(); - - for(String i : writing.k().sort()) - { - String prog = ""; - String f = writing.get(i); - - if(f.contains("%")) - { - String v = f.split("\\Q%\\E")[0]; - try - { - prog = drawProgress(Double.valueOf(Integer.parseInt(v.substring(v.length() - 2))) / 100D, 30); - } - - catch(Throwable e) - { - try - { - prog = drawProgress(Double.valueOf(Integer.parseInt(v.substring(v.length() - 1))) / 100D, 30); - } - - catch(Throwable ee) - { - try - { - prog = drawProgress(Double.valueOf(Integer.parseInt(v.substring(v.length() - 3))) / 100D, 30); - } - - catch(Throwable eee) - { - - } - } - } - } - - System.out.println(prog + " " + i + " => " + f); - } - } - } - }).start(); - } - - public UMeta renderFrameBuffer(long id, double t) - { - UMeta meta = new UMeta(); - meta.setId(id); - meta.setTime(t); - RNG rng = spatialSeed.get(id, id + ((id * id) % (id / 3D))); - RNG rngbg = spatialSeed.get(id, -id + ((id * id) % (id / 4D))); - BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - BufferedImage bufFG = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - UImage image = new UBufferedImage(buf); - UImage imageFG = new UBufferedImage(bufFG); - ChronoLatch cl = new ChronoLatch(250); - UFeature background = rng.pick(backgrounds); - UFeature interpolator = rng.pick(interpolators); - UFeature foreground = rng.pick(features); - UFeature foregroundInterpolator = rng.pick(interpolators); - UFeatureMeta backgroundMeta = new UFeatureMeta(); - UFeatureMeta foregroundMeta = new UFeatureMeta(); - UFeatureMeta backgroundInterpolatorMeta = new UFeatureMeta(); - UFeatureMeta foregroundInterpolatorMeta = new UFeatureMeta(); - background.render(image, rngbg, t, (p) -> { - if(cl.flip()) - { - writing.put("#" + id + ":" + t, Form.pc(p / 4D) + " [" + background.getClass().getSimpleName() + " " + Form.pc(p) + "]"); - } - }, backgroundMeta); - backgroundMeta.setFeature(background.getClass().getSimpleName()); - meta.registerFeature("background", backgroundMeta); - interpolator.render(image, rng, t, (p) -> { - if(cl.flip()) - { - writing.put("#" + id + ":" + t, Form.pc(0.25 + (p / 4d)) + " [" + interpolator.getClass().getSimpleName() + " " + Form.pc(p) + "]"); - } - }, backgroundInterpolatorMeta); - backgroundInterpolatorMeta.setFeature(interpolator.getClass().getSimpleName()); - meta.registerFeature("backgroundInterpolator", backgroundInterpolatorMeta); - foreground.render(imageFG, rng, t, (p) -> { - if(cl.flip()) - { - writing.put("#" + id + ":" + t, Form.pc(0.5 + (p / 4d)) + " [" + foreground.getClass().getSimpleName() + " " + Form.pc(p) + "]"); - } - }, foregroundMeta); - foregroundMeta.setFeature(foreground.getClass().getSimpleName()); - meta.registerFeature("foreground", foregroundMeta); - overlay(imageFG, bufFG, image); - foregroundInterpolator.render(image, rng, t, (p) -> { - if(cl.flip()) - { - writing.put("#" + id + ":" + t, Form.pc(0.75 + (p / 4d)) + " [" + interpolator.getClass().getSimpleName() + " " + Form.pc(p) + "]"); - } - }, foregroundInterpolatorMeta); - foregroundInterpolatorMeta.setFeature(foregroundInterpolator.getClass().getSimpleName()); - meta.registerFeature("foregroundInterpolator", foregroundInterpolatorMeta); - overlay(imageFG, bufFG, image); - meta.setImage(buf); - writing.remove("#" + id + ":" + t); - return meta; - } - -private void overlay(UImage layer, BufferedImage layerBuf, UImage onto) -{ - for(int i = 0; i < onto.getWidth(); i++) - { - for(int j = 0; j < onto.getHeight(); j++) - { - if(layerBuf.getRGB(i, j) != 0) - { - onto.set(i, j, layer.get(i, j)); - } - } - } -} - - private String drawProgress(double progress, int len) - { - int max = len; - int in = (int) Math.round(progress * max); - max -= in; - - return "[" + Form.repeat("=", in) + Form.repeat(" ", max)+ "]"; - } - - private void computeNoiseStyles(double time, double scope) { - List allowedStyles = new KList<>(NoiseStyle.values()); - allowedStyles.remove(NoiseStyle.FLAT); - KMap speeds = new KMap<>(); - double allocateMS = time; - double maxTestDuration = allocateMS / allowedStyles.size(); - System.out.println("Running Noise Style Benchmark for " + Form.duration(allocateMS, 0) + "."); - System.out.println("Benchmarking " + allowedStyles.size() + " + Noise Styles for " + Form.duration(maxTestDuration, 1) + " each."); - System.out.println(); - - for(NoiseStyle i : allowedStyles) - { - int score = 0; - CNG cng = i.create(new RNG("renderspeedtest")); - PrecisionStopwatch p = PrecisionStopwatch.start(); - double g = 0; - while(p.getMilliseconds() < maxTestDuration) - { - cng.noise(g, -g * 2); - g+= 0.1; - g *= 1.25; - score++; - } - - speeds.put(i, score); - } - - for(NoiseStyle i : speeds.sortKNumber()) - { - System.out.println(Form.capitalizeWords(i.name().toLowerCase(Locale.ROOT).replaceAll("\\Q_\\E", " ")) + " => " + Form.f(speeds.get(i))); - } - System.out.println(); - int takeUpTo = (int) Math.max(1, scope * speeds.size()); - System.out.println("Choosing the fastest " + Form.pc(scope) + " styles (" + takeUpTo + ")"); - - for(NoiseStyle i : speeds.sortKNumber().reverse()) - { - if(takeUpTo-- <= 0) - { - break; - } - - sortedStyles.add(i); - System.out.println("- " + Form.capitalizeWords(i.name().toLowerCase(Locale.ROOT).replaceAll("\\Q_\\E", " "))); - } - } - - private void computeInterpolationMethods(double time, double scope) { - List allowedStyles = new KList<>(InterpolationMethod.values()); - allowedStyles.remove(InterpolationMethod.NONE); - KMap speeds = new KMap<>(); - double allocateMS = time; - double maxTestDuration = allocateMS / allowedStyles.size(); - System.out.println("Running Interpolation Method Benchmark for " + Form.duration(allocateMS, 0) + "."); - System.out.println("Benchmarking " + allowedStyles.size() + " + Interpolation Methods for " + Form.duration(maxTestDuration, 1) + " each."); - System.out.println(); - - RNG r = new RNG("renderspeedtestinterpolation"); - CNG cng = NoiseStyle.SIMPLEX.create(r); - NoiseProvider np = (x, z) -> cng.noise(x, z); - - for(InterpolationMethod i : allowedStyles) - { - int score = 0; - - PrecisionStopwatch p = PrecisionStopwatch.start(); - double g = 0; - while(p.getMilliseconds() < maxTestDuration) - { - IrisInterpolation.getNoise(i, (int) g, (int) (-g * 2.225), r.d(4, 64), np); - cng.noise(g, -g * 2); - g+= 1.1; - g *= 1.25; - score++; - } - - speeds.put(i, score); - } - - for(InterpolationMethod i : speeds.sortKNumber()) - { - System.out.println(Form.capitalizeWords(i.name().toLowerCase(Locale.ROOT).replaceAll("\\Q_\\E", " ")) + " => " + Form.f(speeds.get(i))); - } - System.out.println(); - int takeUpTo = (int) Math.max(1, scope * speeds.size()); - System.out.println("Choosing the fastest " + Form.pc(scope) + " interpolators (" + takeUpTo + ")"); - - for(InterpolationMethod i : speeds.sortKNumber().reverse()) - { - if(takeUpTo-- <= 0) - { - break; - } - - sortedInterpolators.add(i); - System.out.println("- " + Form.capitalizeWords(i.name().toLowerCase(Locale.ROOT).replaceAll("\\Q_\\E", " "))); - } - } - - public void writeCollectionFrames(File folder, int fromId, int toId) - { - folder.mkdirs(); - BurstExecutor burst = new BurstExecutor(executor, Math.min(toId - fromId, 1000)); - burst.setMulticore(true); - AtomicInteger ai = new AtomicInteger(0); - int max = toId - fromId; - - for(int i = fromId; i <= toId; i++) - { - int ii = i; - burst.queue(() -> { - - writing.put("!#[" + fromId + "-" + toId + "] Collection", ai.get() + " of " + max + " (" + Form.pc(ai.get() / (double)max, 0) + ")"); - writeFrame(new File(folder, ii + ".png"), ii, 0); - ai.incrementAndGet(); - writing.put("!#[" + fromId + "-" + toId + "] Collection", ai.get() + " of " + max + " (" + Form.pc(ai.get() /(double) max, 0) + ")"); - }); - } - - burst.complete(); - writing.remove("!#[" + fromId + "-" + toId + "] Collection"); - } - - public void writeFrame(File destination, long id, double t) { - try - { - renderFrameBuffer(id, t).export(destination); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - public void report(String s) - { - System.out.println(s); - } - - public KList getStyles() { - return sortedStyles; - } - - public List getInterpolators() { - return sortedInterpolators; - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/features/UFInterpolator.java b/src/main/java/com/volmit/iris/util/uniques/features/UFInterpolator.java deleted file mode 100644 index e2cfecf8f..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/features/UFInterpolator.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.volmit.iris.util.uniques.features; - -import com.volmit.iris.util.function.NoiseProvider; -import com.volmit.iris.util.interpolation.InterpolationMethod; -import com.volmit.iris.util.interpolation.IrisInterpolation; -import com.volmit.iris.util.math.M; -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.uniques.UFeature; -import com.volmit.iris.util.uniques.UFeatureMeta; -import com.volmit.iris.util.uniques.UImage; -import com.volmit.iris.util.uniques.UniqueRenderer; - -import java.awt.*; -import java.util.function.Consumer; - -public class UFInterpolator implements UFeature { - @Override - public void render(UImage image, RNG rng, double t, Consumer progressor, UFeatureMeta meta) { - UImage ref = image.copy(); - CNG rmod = generator("interpolator_radius", rng, 1, 33004, meta); - - NoiseProvider nHue = (x, y) -> { - int ix = Math.abs(((int)x)%ref.getWidth()); - int iy = Math.abs(((int)y)%ref.getHeight()); - Color color = ref.get(ix, iy); - float[] hsv = new float[3]; - Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getGreen(), hsv); - return hsv[0]; - }; - NoiseProvider nSat = (x, y) -> { - int ix = Math.abs(((int)x)%ref.getWidth()); - int iy = Math.abs(((int)y)%ref.getHeight()); - Color color = ref.get(ix, iy); - float[] hsv = new float[3]; - Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getGreen(), hsv); - return hsv[1]; - }; - NoiseProvider nBri = (x, y) -> { - int ix = Math.abs(((int)x)%ref.getWidth()); - int iy = Math.abs(((int)y)%ref.getHeight()); - Color color = ref.get(ix, iy); - float[] hsv = new float[3]; - Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getGreen(), hsv); - return hsv[2]; - }; - InterpolationMethod method = interpolator(rng); - int sizeMin = Math.min(image.getWidth(), image.getHeight()); - double radius = Math.max(4, rmod.fit(sizeMin / 256, sizeMin / 4, t * rng.d(0.03, 1.25), t * rng.d(0.01, 2.225))); - for(int i = 0; i < image.getWidth(); i++) - { - for(int j = 0; j < image.getHeight(); j++) - { - image.set(i, j, Color.getHSBColor( - (float)Math.max(Math.min(1D, IrisInterpolation.getNoise(method, i, j, radius, nHue)), 0D), - (float)Math.max(Math.min(1D, IrisInterpolation.getNoise(method, i, j, radius, nSat)), 0D), - (float)Math.max(Math.min(1D, IrisInterpolation.getNoise(method, i, j, radius, nBri)), 0D) - )); - } - - progressor.accept(i / (double)image.getWidth()); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/features/UFNOOP.java b/src/main/java/com/volmit/iris/util/uniques/features/UFNOOP.java deleted file mode 100644 index 76c4db56b..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/features/UFNOOP.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.volmit.iris.util.uniques.features; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.uniques.UFeature; -import com.volmit.iris.util.uniques.UFeatureMeta; -import com.volmit.iris.util.uniques.UImage; - -import java.awt.*; -import java.util.function.Consumer; - -public class UFNOOP implements UFeature { - @Override - public void render(UImage image, RNG rng, double t, Consumer progressor, UFeatureMeta meta) { - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedBackground.java b/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedBackground.java deleted file mode 100644 index da5f0e411..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedBackground.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.volmit.iris.util.uniques.features; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.uniques.UFeature; -import com.volmit.iris.util.uniques.UFeatureMeta; -import com.volmit.iris.util.uniques.UImage; - -import java.awt.*; -import java.util.function.Consumer; - -public class UFWarpedBackground implements UFeature { - @Override - public void render(UImage image, RNG rng, double t, Consumer progressor, UFeatureMeta meta) { - CNG hue = generator("color_hue", rng, rng.d(0.001, rng.d(2, 5)), rng.i(0, 3) ,rng.i(0, 3), 31007, meta); - CNG sat = generator("color_sat", rng, rng.d(0.001, rng.d(2, 5)), rng.i(0, 2) ,rng.i(0, 2), 33004, meta); - CNG bri = generator("color_bri", rng, rng.d(0.001, rng.d(2, 5)), rng.i(0, 1) ,rng.i(0, 1), 32005, meta).patch(0.145); - double tcf = rng.d(0.15, 0.55); - - for(int i = 0; i < image.getWidth(); i++) - { - for(int j = 0; j < image.getHeight(); j++) - { - image.set(i, j, color(hue, sat, bri, i, j, tcf * t)); - } - - progressor.accept(i / (double)image.getWidth()); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedCircle.java b/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedCircle.java deleted file mode 100644 index 2d73ee01b..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedCircle.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.volmit.iris.util.uniques.features; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.uniques.UFeature; -import com.volmit.iris.util.uniques.UFeatureMeta; -import com.volmit.iris.util.uniques.UImage; - -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.function.Consumer; - -public class UFWarpedCircle implements UFeature { - @Override - public void render(UImage image, RNG rng, double t, Consumer progressor, UFeatureMeta meta) { - double r = Math.min(image.getWidth(), image.getHeight()) / 2.5D; - double i, angle, x1, y1; - CNG xShift = generator("x_warp", rng, 0.6, 1001, meta); - CNG yShift = generator("y_warp", rng, 0.6, 1002, meta); - CNG hue = generator("color_hue", rng, rng.d(0.25, 2.5), 1003, meta); - CNG sat = generator("color_sat",rng, rng.d(0.25, 2.5), 1004, meta); - CNG bri = generator("color_bri",rng, rng.d(0.25, 2.5), 1005, meta); - double tcf = rng.d(0.75, 11.25); - double rcf = rng.d(7.75, 16.25); - int x = image.getWidth()/2; - int y = image.getHeight()/2; - - for(int d = 0; d < 256; d++) - { - r -= Math.min(image.getWidth(), image.getHeight()) / 300D; - - if(r <= 0) - { - return; - } - - for(i = 0; i < 360; i += 0.1) - { - angle = i; - x1 = r * Math.cos(angle * Math.PI / 180); - y1 = r * Math.sin(angle * Math.PI / 180); - image.set((int)Math.round(x + x1 + xShift.fit(-r/2, r/2, x1 + (t+ (d * 8)), -y1 + (t+ (d * 8)))), - (int)Math.round(y + y1 + yShift.fit(-r/2, r/2, y1 + (t+ (d * 8)), -x1 + (t+ (d * 8)))), - color(hue, sat, bri, x1, y1, (t * tcf) + (d * rcf))); - } - - progressor.accept(d / 256D); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedDisc.java b/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedDisc.java deleted file mode 100644 index b394f2c7c..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedDisc.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.volmit.iris.util.uniques.features; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.uniques.UFeature; -import com.volmit.iris.util.uniques.UFeatureMeta; -import com.volmit.iris.util.uniques.UImage; - -import java.util.function.Consumer; - -public class UFWarpedDisc implements UFeature { - @Override - public void render(UImage image, RNG rng, double t, Consumer progressor, UFeatureMeta meta) { - double r = Math.min(image.getWidth(), image.getHeight()) / 3D; - CNG xShift = generator("x_warp", rng, 0.6, 1001, meta); - CNG yShift = generator("y_warp",rng, 0.6, 1002, meta); - CNG hue = generator("color_hue",rng, rng.d(0.25, 2.5), 1003, meta); - CNG sat = generator("color_sat",rng, rng.d(0.25, 2.5), 1004, meta); - CNG bri = generator("color_bri",rng, rng.d(0.25, 2.5), 1005, meta); - double tcf = rng.d(0.75, 11.25); - int x = image.getWidth()/2; - int y = image.getHeight()/2; - - for(int i = (int)( x - r); i < x+r; i++) - { - for(int j =(int)( y - r); j < y+r; j++) - { - if(image.isInBounds(i, j) && Math.pow(x - i, 2) + Math.pow(y - j, 2) <= r*r) - { - image.set(Math.round(i + xShift.fit(-r/2, r/2, i+t, -j+t)), - Math.round(j + yShift.fit(-r/2, r/2, j+t, -i+t)), - color(hue, sat, bri, i, j, tcf * t)); - } - } - - progressor.accept(i / (x + r)); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedDots.java b/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedDots.java deleted file mode 100644 index a9670600e..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedDots.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.volmit.iris.util.uniques.features; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.uniques.UFeature; -import com.volmit.iris.util.uniques.UFeatureMeta; -import com.volmit.iris.util.uniques.UImage; - -import java.awt.*; -import java.util.function.Consumer; - -public class UFWarpedDots implements UFeature { - @Override - public void render(UImage image, RNG rng, double t, Consumer progressor, UFeatureMeta meta) { - CNG genX = generator("x_pos", rng, 4, 2000, meta); - CNG genY = generator("y_pos", rng, 4, 2001, meta); - - double tcf = rng.d(0.75, 11.25); - - for(int i = 1; i <= 8; i++) - { - CNG xShift = generator("x_warp_" + i, rng, 2, 2006+i, meta); - CNG yShift = generator("y_warp_" + i,rng, 2, 2007+i, meta); - CNG hue = generator("color_hue_" + i,rng, rng.d(0.55, 3.5), 2003+i, meta); - CNG sat = generator("color_sat_" + i,rng, rng.d(0.55, 3.5), 2004+i, meta); - CNG bri = generator("color_bri_" + i,rng, rng.d(0.55, 3.5), 2005+i, meta); - int x = genX.fit(0, image.getWidth(), i * 128, i * 5855); - int y = genY.fit(0, image.getHeight(), i * 128, i * 5855); - Color color = color(hue, sat, bri, x, y, t); - double r = Math.max(genX.fit(image.getWidth() / 10, image.getWidth() / 6, x, y), genY.fit(image.getHeight() / 10, image.getHeight() / 6, x, y)); - - for(int j = (int)(x - r); j < x + r; j++) - { - for(int k = (int)(y - r); k < y + r; k++) - { - if(image.isInBounds(j, k) && Math.pow(x - j, 2) + Math.pow(y - k, 2) <= r*r) - { - image.set(Math.round(j + xShift.fit(-r/2, r/2, j+t, -k+t)), - Math.round(k + yShift.fit(-r/2, r/2, k+t, -j+t)), - color(hue, sat, bri, j, k, tcf * t)); - } - } - } - - progressor.accept(i / 32D); - } - } -} diff --git a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedLines.java b/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedLines.java deleted file mode 100644 index badfdb79e..000000000 --- a/src/main/java/com/volmit/iris/util/uniques/features/UFWarpedLines.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.volmit.iris.util.uniques.features; - -import com.volmit.iris.util.math.RNG; -import com.volmit.iris.util.noise.CNG; -import com.volmit.iris.util.uniques.UFeature; -import com.volmit.iris.util.uniques.UFeatureMeta; -import com.volmit.iris.util.uniques.UImage; - -import java.util.function.Consumer; - -public class UFWarpedLines implements UFeature { - @Override - public void render(UImage image, RNG rng, double t, Consumer progressor, UFeatureMeta meta) { - for(int g = 1; g < 5; g++) - { - CNG xShift = generator("x_warp_"+g, rng, 0.6, 1001 * g, meta); - CNG yShift = generator("y_warp_"+g, rng, 0.6, 1002 * g, meta); - CNG cX = generator("x_clip_"+g, rng, rng.d(0.035, 0.6), 77001 * g, meta); - CNG cY = generator("y_clip"+g, rng, rng.d(0.035, 0.6), 77002, meta); - CNG hue = generator("color_hue_"+g, rng, rng.d(0.25, 2.5), 1003 * g, meta); - CNG sat = generator("color_sat_"+g, rng, rng.d(0.25, 2.5), 1004 * g, meta); - CNG bri = generator("color_bri_"+g, rng, rng.d(0.25, 2.5), 1005 * g, meta); - double tcf = rng.d(0.75, 11.25 + (g * 4)); - double rcf = rng.d(7.75, 16.25 + (g * 5)); - double xcf = rng.d(0.15, 0.55 + (g * 0.645)); - double w = rng.d(64, 186 + (g * 8)); - double ww = image.getWidth() / rng.d(3, 9); - double hh = image.getHeight() / rng.d(3, 9); - boolean wh = rng.nextBoolean(); - double sa = rng.d(0.35, 0.66); - double sb = rng.d(0.35, 0.66); - - for(int i = 0; i < image.getWidth(); i+= (wh ? image.getWidth() / w : 1)) - { - for(int j = 0; j < image.getHeight(); j+= (!wh ? image.getHeight() / w : 1)) - { - if(cX.fitDouble(0, 1, i, -j, t * xcf) > sa && cY.fitDouble(0, 1, -j, i, t * xcf) > sb) - { - image.set(Math.round(i + xShift.fit(-ww, ww, i, j, (t * rcf))), - Math.round(j + yShift.fit(-hh, hh, -j, i, (t * rcf))), - color(hue, sat, bri, i, j, (t * tcf))); - } - } - } - } - } -} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml deleted file mode 100644 index bdc0fb9c9..000000000 --- a/src/main/resources/plugin.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: ${name} -version: ${version} -main: ${main} -load: STARTUP -authors: [ cyberpwn, NextdoorPsycho ] -website: volmit.com -description: More than a Dimension! -libraries: - - com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2 - - com.github.ben-manes.caffeine:caffeine:3.0.5 - - org.apache.commons:commons-lang3:3.12.0 - - io.timeandspace:smoothie-map:2.0.2 - - com.google.guava:guava:31.0.1-jre - - com.google.code.gson:gson:2.8.9 - - org.zeroturnaround:zt-zip:1.14 - - it.unimi.dsi:fastutil:8.5.6 - - org.ow2.asm:asm:9.2 - - rhino:js:1.7R2 - - bsf:bsf:2.4.0 -commands: - iris: - aliases: [ ir, irs ] -api-version: ${apiversion} -hotload-dependencies: false -softdepend: [ "Oraxen", "ItemsAdder", "IrisFeller", "WorldEdit"] \ No newline at end of file diff --git a/wad.png b/wad.png deleted file mode 100644 index 637f00509..000000000 Binary files a/wad.png and /dev/null differ

- * Character encoding names can be found at - * IANA. - *