diff --git a/gource.bat b/gource.bat new file mode 100644 index 000000000..6786239d7 --- /dev/null +++ b/gource.bat @@ -0,0 +1,3 @@ +@echo off +cd gource +gource -f -a 1 -s 0.5 --colour-images --max-file-lag 10 --title MyGuide --user-scale 1.67 --max-user-speed 725 --filename-time 2 \ No newline at end of file diff --git a/gource/COPYING.txt b/gource/COPYING.txt new file mode 100644 index 000000000..94a9ed024 --- /dev/null +++ b/gource/COPYING.txt @@ -0,0 +1,674 @@ + 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/gource/ChangeLog.txt b/gource/ChangeLog.txt new file mode 100644 index 000000000..eed47ea16 --- /dev/null +++ b/gource/ChangeLog.txt @@ -0,0 +1,298 @@ +0.51: + * Fixed --font-file relative path handling. + * Fixed a bug in resolving the repository root directory from a relative path. + +0.50: + * Right mouse button rotation now pivots around the camera. + * Added --font-file option. + * Added --enable-font-file option to configure. + * Added --no-time-travel option (Lars Schmertmann). + * Added --dir-name-position option (Lars Schmertmann). + * Added --file-extension-fallback option (Lars Schmertmann). + * Added --user-show-filter option (Victor Lopez). + * Added --disable-input option (Joey Parrish). + * Added --loop-delay-seconds option (Joey Parrish). + * Added --font-scale option. + * Added filename, dirname and user font size options (Carl Colena). + * Added workaround for FFMpeg error parsing Gource PPM video output. + * Fixed a bug in the Mercurial log parser that caused changes to be missed. + * Fixed file removal being cancelled by an action with an earlier timestamp. + * Fixed a bug in the log file format detection that could result in the wrong + first entry being displayed for a custom log. + * Fixed a bug where automatically cycling through a config with multiple + repositories reset settings to their defaults. + +0.49: + * Fixed compatibility with GLM 0.9.9.0. + +0.48: + * Can now generate logs from git sub module directories. + +0.47: + * Fixed low mouse movement speed with some mice while repositioning camera. + +0.46: + * Added --screen option. + +0.45: + * Added --window-position XxY option. + * Added --frameless option. + * Added --file-show-filter REGEX option (swoogles). + * Added --filename-time and filename-colour options (gh2k). + * Improved handling of very low seconds-per-day values (malengrin). + * Fixed crash when SVN log lacks author information (obarthel). + * Additional git log command validation (cym13). + * Allow lower case hex colours in custom logs (HSorensen). + * Enabled STDOUT support with --output-stream '-' on Windows (circulosmeos). + * Now requires SDL 2 to build (deprecated SDL 1.2 support removed). + +0.44: + * Fixed crash when taking a screenshot with an odd resolution. + * Fixed type deduction compilation error with newer versions of GCC. + * Documentation improvements. + +0.43: + * Updated boost autoconf macros to fix multi-arch detection. + +0.42: + * Fixed bzr log command when no start date was specified (chrisf). + * Fixed hg log commit order when date range specified. + * Fixed hg log command line on Windows. + * Fixed parser bug in date range filtering code. + +0.41: + * Multi-monitor support using SDL 2.0 when available. + * SDL 1.2 support is deprecated. + * Full screen mode now uses desktop resolution by default. + * Added --start-date, --stop-date 'YYYY-MM-DD hh:mm:ss' options. + * Added --dir-name-depth option. + * Changed --file-idle-time default value to 0. + * Changed screenshot format to PNG. + +0.40: + * Added caption support. + * Improved command line interoperability on Windows. + * Fixed directory deletion short circuiting processing the rest of a commit. + * Fixed issue loading non-ascii user image filenames on windows. + * Ignore UTF-8 byte order mark at the start of lines in custom log files. + * Fix to boost macros for Macs and non-GNU systems (mistydemeo). + * Autotools improvements (flameeyes). + +0.39: + * Fixed blurry non power of 2 logos. + * File colour changes now supported in custom logs (rmyorston). + * Fixed building against Boost 1.50 (svenstaro). + * Updated boost autoconf macros (flameeyes). + * Autogen script (matthiaskrgr). + +0.38: + * New high quality sprites. + * Fullscreen toggle with alt + enter. + * Window is now resizable. -WIDTHxHEIGHT! creates a non-resizable window. + * Lowered minimum zoom distance. + * Use AM_CPPFLAGS in Makefile.am to allow passing custom CPPFLAGS. + * Don't add files that match the path of a known directory. + * Fixed divide by zero in text shader causing artifacts on some video cards. + * Recursively search for repository directory when log-format not specified + (thanks to Jörg Bachmann for original concept / prototype). + * New dependency on Boost Filesystem. + * Doubled the maximum zoom out distance. + * Allow negative timestamps before 1970 in custom log (artzub). + * Fix for UTF8-CPP checked.h compilation issue (vszakats). + * Fixed bug causing missing characters in text. + * Fixed --highlight-users option not using highlight-colour. + * highlight-colour default changed to white. + * Added --selection-colour option (applied to selected users and files). + * Added --dir-colour option (applied to directories). + +0.37: + * Made SVN log GMT timestamp conversion fix portable. + +0.36: + * Fixed SVN log GMT timestamp conversion. + * Fixed issue with sub-dirs of deleted dir not being removed in some cases. + +0.35: + * Added long file extension truncation handling to file key (--key). + * Treat changes in Mercurial log files with the same time/user as one commit. + * Fixed handling of spaces in directory names with Mercurial. + * Fixed --font-colour option. + +0.34: + * Now using VBOs and shaders for faster rendering when OpenGL 2.0 is available. + * Eliminated bloom colour banding artifacts (requires OpenGL 2.0). + * New font rendering library derived from FTGL (FTGL no longer required). + * Single pass font/shadow rendering (with lots of help from Chris Forbes). + * Added --no-vsync option. + * Fixed bug where tree is out of alignment with object positions in windowed + mode due to using the wrong display dimensions internally. + * Removed default max-files limit. + +0.33: + * Added --hide root option to not draw branches from the root directory. + * Fixed log parsing of Bazaar merges and tagged commits. + * --output-custom-log now skips unparsed log entries instead of exiting. + +0.32: + * Fixed behaviour of user camera tracking. + +0.31: + * Added --with-tinyxml option to configure (use the system TinyXML library). + +0.30: + * Fixed crash when SVN log entry contains no 'paths' element. + * Handle directory deletion (happens in SVN logs). + +0.29: + * SVN built-in support. + * cvs2cl log support (cvs-exp support is now deprecated). + * Made camera behaviour when zooming and selecting objects more intuitive. + * Improved interactive performance. + * Added file extension key (--key or toggled with 'K'). + * Added mouse-over tool tips. + * Added --highlight-colour option. + * Added --hash-seed option. The S key now randomizes colours. + * Added --output-custom-log option. + * Exposed --time-scale option (previously only available interactively). + * Removed arbitrary 1024 maximum length limit for log lines. + * Fixed two file colouring bugs (quoted files from git, period in file path). + * Fix handling of avatars for UTF-8 usernames on MACOSX (Christian Köstlin). + * Recover from video mode failing to set due to multi-sampling (Siddhesh Poyarekar). + +0.28: + * Bazaar support for merged commits (Nick Moffit). + * C++ efficiency improvements (Oliver Smith). + * Improved cvs-exp log compatibility. + * Re-show name of user when adding a new action if user is idle. + * Added --padding option to control camera view padding. + * More accurate camera tracking (tracks the bounding boxes of objects). + * Improved automatic rotation logic. + +0.27: + * Display time stops at the time of the last commit. + * Users fade out when end reached rather than ending abruptly. + * Position slider is now hidden by default if recording a video. + * Automatic camera rotation for better use of screen space. + * Support international keyboards (Peter Kjellerstedt). + * C++ efficiency improvements (Jacob Metcalfe). + * Fixed crash when reading from STDIN. + * Fixed intermittent crash closing Gource when using --output-ppm-stream. + * Added ini style config file support (see --load/save-config). + * Added screenshot button (F12). Screenshots respect the alpha channel. + * Added --transparent to make the background see-through (for screenshots). + * Added --logo and --background-image options. + * Added --dont-stop option for manual exiting when recording videos. + * Added --stop-at-time option to stop Gource after a number of seconds. + * Added --hide 'mouse' option. + * Added --highlight-dirs option. + * Added --file-extensions to show filename extensions only. + * Added --user-filter REGEX option. + * Allow --file-idle-time 0 (files will never expire). + * Allow --start-position 'random' to set a random start position. + * --log-command VCS replaces multiple --log-command-VCS options. + * Replaced --disable-progress and --disable-bloom with arguments to --hide. + +0.26a: + * Updated to latest version of GL autoconf macros. + +0.26: + * Improved mouse dragging. + * Holding right mouse button and moving the mouse rotates the view. + * The middle mouse button now toggles the camera mode. + * Username positions now scale correctly. + * Simulation time no longer incremented while paused, counting towards file time lag. + * M key now toggles mouse visibility. + * Added --hide option to use instead of multiple --hide-ELEMENT options. + +0.25: + * Bazaar support (John Arbash Meinel). + * Dragging the mouse on the background moves the camera. + * Added --camera-mode option (track,overview). + * Support DOS line endings in logs. + * Improved compatibility of hg log command (Brendan Cully). + * Fixed PPM exporter producing blank images on some video cards. + * Fixed parsing of negative timezones from cvs-exp.pl logs. + * Fixed various gdb and compiler warnings. + +0.24: + * PPM output speed improvements, including using a second thread (HighlandSun). + * Now using standard autotools (Flameeyes). + * Fixed --max-file-lag not working with some custom log files. + * Gource will stop at the end of the log by default when recording a video. + * Fixed STDIN stopping working after the first lot of records with tail -f. + * Added proper exception handling. + * Print errors to stderr. + +0.23: + * Hiding filenames no longer hides directory names. + * Fixed --stop-on-idle option. + * Added --stop-at-end option (more intuitive than --stop-position 1.0). + +0.22: + * Fixed Mercurial log order. + +0.21b: + * Fixed windows build. + +0.21: + * Some documentation fixes. + +0.20: + * Added bloom effect (turn off with --disable-bloom). + * Added support for Mercurial (thanks to Justin Love for gource.style). + * --start-position option now works in combination with --disable-progress. + +0.19: + * Use time_t instead of long for timestamps. + +0.18: + * Fixed camera movement while the simulation is paused. + +0.17: + * Show correct month for CVS logs. + * Added time scaling (Bitshifter). + +0.16: + * Added --hide-dirnames option. + * Added --user-scale option. + * Added --date-format option (Pat Notz). + * Fix bug when encountering long log lines. + * Fixed incorrect parsing of trivial merges. + * Fixed building issues on OSX. + +0.15: + * Added PPM output support for creating videos (Johannes Schindelin). + * Added experimental Apache combined access log support (--log-format apache). + * Added --stop-position and --stop-on-idle options (useful for making videos). + * Added --max-file-lag option to limit how long after a commit file changes can take to appear. + * Added --no-renames to the git log command as they don't display correctly. + * Added --max-user-speed and --user-friction as options. + * Now builds on OSX Leopard (with the required libaries installed). + * Caught raw exception from replace_invalid(). + * Added CXXFLAGS. You may want to override the default (eg CXXFLAGS=-O3 ./configure). + +0.14: + * Updated SVN instructions. + +0.13: + * Removed single quotes from log command (fixes running gource --git-log-command in back ticks) + * Added SVN instructions. + * Fixed manpage hyphens. + +0.12: + * Added --enable-ttf-font-dir=DIR option to configure (to specify the ttf-freefont directory). + * UTF-8 support using UTF8-CPP (http://utfcpp.sourceforge.net/). + * Changed the git log command (see --git-log-command) to require less work to parse. + Log files generated with the previous git-log command used by gource should continue to work. + * Allow --seconds-per-day value less than 1.0. + * Added --git-branch command. + * Added --loop command. + * Added --crop command. + +0.11: + * Made N key skip to next entry. + * Documented --user-image-dir flag. + * temp file name now uses uid instead of time + +0.1: + * First release. diff --git a/gource/README.txt b/gource/README.txt new file mode 100644 index 000000000..9eeb62485 --- /dev/null +++ b/gource/README.txt @@ -0,0 +1,469 @@ + + Gource + + software version control visualization + + Copyright (C) 2009 Andrew Caudwell + + http://gource.io + +Contents +======== + +1. Description +2. Requirements +3. Using Gource +4. Copyright + +1. Description +============== + +OpenGL-based 3D visualisation tool for source control repositories. + +The repository is displayed as a tree where the root of the repository is the +centre, directories are branches and files are leaves. Contributors to the +source code appear and disappear as they contribute to specific files and +directories. + +2. Requirements +=============== + +Gource's display is rendered using OpenGL and requires a 3D accelerated video +card to run. + +3. Using Gource +=============== + +gource [options] [path] + +options: + + -h, --help + Help ('-H' for extended help). + + -WIDTHxHEIGHT, --viewport WIDTHxHEIGHT + Set the viewport size. If -f is also supplied, will attempt to set + the video mode to this also. Add ! to make the window non-resizable. + + --screen SCREEN + Set the number of the screen to display on. + + --window-position XxY + Initial window position on your desktop which may be made up of + multiple monitors. + + This will override the screen setting so don't specify both. + + --frameless + Frameless window. + + -f, --fullscreen + Fullscreen. + + -w, --windowed + Windowed. + + --transparent + Make the background transparent. Only really useful for screenshots. + + --start-date "YYYY-MM-DD hh:mm:ss +tz" + Start with the first entry after the supplied date and optional time. + + If a time zone offset isn't specified the local time zone is used. + + Example accepted formats: + + "2012-06-30" + "2012-06-30 12:00" + "2012-06-30 12:00:00 +12" + + --stop-date "YYYY-MM-DD hh:mm:ss +tz" + Stop after the last entry prior to the supplied date and optional time. + + Uses the same format as --start-date. + + -p, --start-position POSITION + Begin at some position in the log (between 0.0 and 1.0 or 'random'). + + --stop-position POSITION + Stop (exit) at some position in the log (does not work with STDIN). + + -t, --stop-at-time SECONDS + Stop (exit) after a specified number of seconds. + + --stop-at-end + Stop (exit) at the end of the log / stream. + + --loop + Loop back to the start of the log when the end is reached. + + --loop-delay-seconds + Seconds to delay before looping. + + -a, --auto-skip-seconds SECONDS + Skip to next entry if nothing happens for a number of seconds. + + -s, --seconds-per-day SECONDS + Speed of simulation in seconds per day. + + --realtime + Realtime playback speed. + + --no-time-travel + Use the time of the last commit if the time of a commit is in the past. + + -c, --time-scale SCALE + Change simulation time scale. + + -i, --file-idle-time SECONDS + Time in seconds files remain idle before they are removed or 0 + for no limit. + + -e, --elasticity FLOAT + Elasticity of nodes. + + -b, --background-colour FFFFFF + Background colour in hex. + + --background-image IMAGE + Set a background image. + + --logo IMAGE + Logo to display in the foreground. + + --logo-offset XxY + Offset position of the logo. + + --title TITLE + Set a title. + + --font-file FILE + Specify the font. Should work with most font file formats supported by FreeType, such as TTF and OTF, among others. + + --font-scale SCALE + Scale the size of all fonts. + + --font-size SIZE + Font size used by the date and title. + + --file-font-size SIZE + Font size of filenames. + + --dir-font-size SIZE + Font size of directory names + + --user-font-size SIZE + Font size of user names. + + --font-colour FFFFFF + Font colour used by the date and title in hex. + + --key + Show file extension key. + + --date-format FORMAT + Specify display date string (strftime format). + + --log-command VCS + Show the VCS log command used by gource (git,svn,hg,bzr,cvs2cl). + + --log-format VCS + Specify the log format (git,svn,hg,bzr,cvs2cl,custom). + + Required when reading from STDIN. + + --git-branch + Get the git log of a branch other than the current one. + + --follow-user USER + Have the camera automatically follow a particular user. + + --highlight-dirs + Highlight the names of all directories. + + --highlight-user USER + Highlight the names of a particular user. + + --highlight-users + Highlight the names of all users. + + --highlight-colour FFFFFF + Font colour for highlighted users in hex. + + --selection-colour FFFFFF + Font colour for selected users and files. + + --filename-colour FFFFFF + Font colour for filenames. + + --dir-colour FFFFFF + Font colour for directories. + + --dir-name-depth DEPTH + Draw names of directories down to a specific depth in the tree. + + --dir-name-position FLOAT + Position along edge of the directory name + (between 0.1 and 1.0, default is 0.5). + + --filename-time SECONDS + Duration to keep filenames on screen (>= 2.0). + + --file-extensions + Show filename extensions only. + + --file-extension-fallback + Use filename as extension if the extension is missing or empty. + + --file-filter REGEX + Filter out file paths matching the specified regular expression. + + --file-show-filter REGEX + Show only file paths matching the specified regular expression. + + --user-filter REGEX + Filter usernames matching the specified regular expression. + + --user-show-filter REGEX + Show only usernames matching the specified regular expression. + + --user-image-dir DIRECTORY + Directory containing .jpg or .png images of users + (eg "Full Name.png") to use as avatars. + + --default-user-image IMAGE + Path of .jpg or .png to use as the default user image. + + --colour-images + Colourize user images. + + --crop AXIS + Crop view on an axis (vertical,horizontal). + + --padding FLOAT + Camera view padding. + + --multi-sampling + Enable multi-sampling. + + --no-vsync + Disable vsync. + + --bloom-multiplier FLOAT + Adjust the amount of bloom. + + --bloom-intensity FLOAT + Adjust the intensity of the bloom. + + --max-files NUMBER + Set the maximum number of files or 0 for no limit. + + Excess files will be discarded. + + --max-file-lag SECONDS + Max time files of a commit can take to appear. + + Use -1 for no limit. + + --max-user-speed UNITS + Max speed users can travel per second. + + --user-friction SECONDS + Time users take to come to a halt. + + --user-scale SCALE + Change scale of user avatars. + + --camera-mode MODE + Camera mode (overview,track). + + --disable-auto-rotate + Disable automatic camera rotation. + + --disable-input + Disable keyboard and mouse input. + + --hide DISPLAY_ELEMENT + Hide one or more display elements from the list below: + + bloom - bloom effect + date - current date + dirnames - names of directories + files - file icons + filenames - names of files + mouse - mouse cursor + progress - progress bar widget + root - root directory of tree + tree - animated tree structure + users - user avatars + usernames - names of users + + Separate multiple elements with commas (eg "mouse,progress") + + --hash-seed SEED + Change the seed of hash function. + + --caption-file FILE + Caption file (see Caption Log Format). + + --caption-size SIZE + Caption size. + + --caption-colour FFFFFF + Caption colour in hex. + + --caption-duration SECONDS + Caption duration. + + --caption-offset X + Caption horizontal offset (0 to centre captions). + + -o, --output-ppm-stream FILE + Output a PPM image stream to a file ('-' for STDOUT). + + This will automatically hide the progress bar initially and + enable 'stop-at-end' unless other behaviour is specified. + + -r, --output-framerate FPS + Framerate of output (25,30,60). Used with --output-ppm-stream. + + --output-custom-log FILE + Output a custom format log file ('-' for STDOUT). + + --load-config CONFIG_FILE + Load a gource conf file. + + --save-config CONFIG_FILE + Save a gource conf file with the current options. + + --path PATH + + path Either a supported version control directory, a pre-generated log + file (see log commands or the custom log format), a Gource conf + file or '-' to read STDIN. + + If path is omitted, gource will attempt to read a log from the + current directory. + +Git, Bazaar, Mercurial and SVN Examples: + +View the log of the repository in the current path: + + gource + +View the log of a project in the specified directory: + + gource my-project-dir + +For large projects, generating a log of the project history may take a long +time. For centralized VCS like SVN, generating the log may also put load on +the central VCS server. + +In these cases, you may like to save a copy of the log for later use. + +You can generate a log in the VCS specific log format using +the --log-command VCS option: + + cd my-svn-project + `gource --log-command svn` > my-svn-project.log + gource my-svn-project.log + +You can also have Gource write a copy of the log file in its own format: + + gource --output-custom-log my-project-custom.log + +CVS Support: + +Use 'cvs2cl' to generate the log and then pass it to Gource: + + cvs2cl --chrono --stdout --xml -g-q > my-cvs-project.log + gource my-cvs-project.log + +Custom Log Format: + +If you want to use Gource with something other than the supported systems, +there is a pipe ('|') delimited custom log format: + + timestamp - A unix timestamp of when the update occured. + username - The name of the user who made the update. + type - initial for the update type - (A)dded, (M)odified or (D)eleted. + file - Path of the file updated. + colour - A colour for the file in hex (FFFFFF) format. Optional. + +Caption Log Format: + +Gource can display captions along the timeline by specifying a caption file +(using --caption-file) in the pipe ('|') delimited format below: + + timestamp - A unix timestamp of when to display the caption. + caption - The caption + +Recording Videos: + +See the guide on the homepage for examples of recording videos with Gource: + + https://github.com/acaudwell/Gource/wiki/Videos + +More Information: + +Visit the Gource homepage for guides and examples of using Gource with various +version control systems: + + http://gource.io + +Interface: + +The time shown in the top left of the screen is set initially from the first +log entry read and is incremented according to the simulation speed +(--seconds-per-day). + +Pressing SPACE at any time will pause/resume the simulation. While paused you +may use the mouse to inspect the detail of individual files and users. + +TAB cycles through selecting the current visible users. + +The camera mode, either tracking activity or showing the entire code tree, can +be toggled using the Middle mouse button. + +You can drag the left mouse button to manually control the camera. The right +mouse button rotates the view. + +Interactive keyboard commands: + + (V) Toggle camera mode + (C) Displays Gource logo + (K) Toggle file extension key + (M) Toggle mouse visibility + (N) Jump forward in time to next log entry + (S) Randomize colours + (D) Toggle directory name display mode + (F) Toggle file name display mode + (U) Toggle user name display mode + (G) Toggle display of users + (T) Toggle display of directory tree edges + (R) Toggle display of root directory edges + (+-) Adjust simulation speed + (<>) Adjust time scale + (TAB) Cycle through visible users + (F12) Screenshot + (Alt+Enter) Fullscreen toggle + (ESC) Quit + +4. Copyright +============ + +Gource - software version control visualization +Copyright (C) 2009 Andrew Caudwell + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . diff --git a/gource/SDL2.dll b/gource/SDL2.dll new file mode 100644 index 000000000..b4b67c0e7 Binary files /dev/null and b/gource/SDL2.dll differ diff --git a/gource/SDL2_image.dll b/gource/SDL2_image.dll new file mode 100644 index 000000000..290bb6b0e Binary files /dev/null and b/gource/SDL2_image.dll differ diff --git a/gource/THANKS.txt b/gource/THANKS.txt new file mode 100644 index 000000000..0636814af --- /dev/null +++ b/gource/THANKS.txt @@ -0,0 +1 @@ +Cheers to everyone at Catalyst IT for their support and encouragement. diff --git a/gource/cmd/gource b/gource/cmd/gource new file mode 100644 index 000000000..1bab330a4 --- /dev/null +++ b/gource/cmd/gource @@ -0,0 +1,3 @@ +#!/bin/sh +GOURCE_CMD_DIR=`dirname "$0"` +"$GOURCE_CMD_DIR/../gource.exe" "$@" diff --git a/gource/cmd/gource.cmd b/gource/cmd/gource.cmd new file mode 100644 index 000000000..31b2f7e22 --- /dev/null +++ b/gource/cmd/gource.cmd @@ -0,0 +1,2 @@ +@echo off +"%~dp0\..\gource.exe" %* diff --git a/gource/data/beam.png b/gource/data/beam.png new file mode 100644 index 000000000..1250c53b6 Binary files /dev/null and b/gource/data/beam.png differ diff --git a/gource/data/bloom.tga b/gource/data/bloom.tga new file mode 100644 index 000000000..f7812c396 Binary files /dev/null and b/gource/data/bloom.tga differ diff --git a/gource/data/bloom_alpha.tga b/gource/data/bloom_alpha.tga new file mode 100644 index 000000000..a1b79947c Binary files /dev/null and b/gource/data/bloom_alpha.tga differ diff --git a/gource/data/file.png b/gource/data/file.png new file mode 100644 index 000000000..739882596 Binary files /dev/null and b/gource/data/file.png differ diff --git a/gource/data/fonts/FreeSans.ttf b/gource/data/fonts/FreeSans.ttf new file mode 100644 index 000000000..9db958532 Binary files /dev/null and b/gource/data/fonts/FreeSans.ttf differ diff --git a/gource/data/fonts/README.txt b/gource/data/fonts/README.txt new file mode 100644 index 000000000..8c970cbcf --- /dev/null +++ b/gource/data/fonts/README.txt @@ -0,0 +1,108 @@ +-*-text-*- + GNU FreeFont + +The GNU FreeFont project aims to provide a useful set of free scalable +(i.e., OpenType) fonts covering as much as possible of the ISO 10646/Unicode +UCS (Universal Character Set). + +Statement of Purpose +-------------------- + +The practical reason for putting glyphs together in a single font face is +to conveniently mix symbols and characters from different writing systems, +without having to switch fonts. + +Coverage +-------- + +FreeFont covers the following character sets + +* ISO 8859 parts 1-15 +* CEN MES-3 European Unicode Subset + http://www.evertype.com/standards/iso10646/pdf/cwa13873.pdf +* IBM/Microsoft code pages 437, 850, 852, 1250, 1252 and more +* Microsoft/Adobe Windows Glyph List 4 (WGL4) + http://www.microsoft.com/typography/otspec/WGL4.htm +* KOI8-R and KOI8-RU +* DEC VT100 graphics symbols +* International Phonetic Alphabet +* Arabic, Hebrew, Armenian, Georgian, Ethiopian and Thai alphabets, + including Arabic presentation forms A/B +* mathematical symbols, including the whole TeX repertoire of symbols +* APL symbols + etc. + +Editing +------- + +The free outline font editor, George Williams's FontForge + is used for editing the fonts. + +Design Issues +------------- + +Which font shapes should be made? Historical style terms like Renaissance +or Baroque letterforms cannot be applied beyond Latin/Cyrillic/Greek +scripts to any greater extent than Kufi or Nashki can be applied beyond +Arabic script; "italic" is really only meaningful for Latin letters. + +However, most modern writing systems have typographic formulations for +contrasting uniform and modulated character stroke widths, and have some +history with "oblique", faces. Since the advent of the typewriter, most +have developed a typographic style with uniform-width characters. + +Accordingly, the FreeFont family has one monospaced - FreeMono - and two +proportional faces (one with uniform stroke - FreeSans - and one with +modulated stroke - FreeSerif). + +To make text from different writing systems look good side-by-side, each +FreeFont face is meant to contain characters of similar style and weight. + +Licensing +--------- + +Free UCS scalable fonts is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License as published +by the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. + +The fonts are distributed in the hope that they will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +As a special exception, if you create a document which uses this font, and +embed this font or unaltered portions of this font into the document, this +font does not by itself cause the resulting document to be covered by the +GNU General Public License. This exception does not however invalidate any +other reasons why the document might be covered by the GNU General Public +License. If you modify this font, you may extend this exception to your +version of the font, but you are not obligated to do so. If you do not +wish to do so, delete this exception statement from your version. + + +Files and their suffixes +------------------------ + +The files with .sfd (Spline Font Database) are in FontForge's native format. +Please use these if you plan to modify the font files. + +TrueType fonts for immediate consumption are the files with the .ttf +(TrueType Font) suffix. These are ready to use in Xwindows based +systems using FreeType, on Mac OS, and on older Windows systems. + +OpenType fonts (with suffix .otf) are for use in Windows Vista. +Note that although they can be installed on Linux, but many applications +in Linux still don't support them. + + +-------------------------------------------------------------------------- +Primoz Peterlin, +Steve White + +Free UCS scalable fonts: http://savannah.gnu.org/projects/freefont/ +$Id: README,v 1.7 2009/01/13 08:43:23 Stevan_White Exp $ diff --git a/gource/data/gource.style b/gource/data/gource.style new file mode 100644 index 000000000..333e03245 --- /dev/null +++ b/gource/data/gource.style @@ -0,0 +1,5 @@ +changeset = '{file_adds}{file_copies}{file_mods}{file_dels}' +file_mod = "{date|hgdate}|{author|person}|M|{file_mod}\n" +file_add = "{date|hgdate}|{author|person}|A|{file_add}\n" +file_del = "{date|hgdate}|{author|person}|D|{file_del}\n" +file_copy = "{date|hgdate}|{author|person}|A|{name}\n" diff --git a/gource/data/shaders/bloom.frag b/gource/data/shaders/bloom.frag new file mode 100644 index 000000000..81960feb0 --- /dev/null +++ b/gource/data/shaders/bloom.frag @@ -0,0 +1,16 @@ + +varying vec3 pos; + +void main() +{ + float r = fract(sin(dot(pos.xy ,vec2(11.3713,67.3219))) * 2351.3718); + + float offset = (0.5 - r) * gl_TexCoord[0].x * 0.045; + + float intensity = min(1.0, cos((length(pos*2.0)+offset)/gl_TexCoord[0].x)); + float gradient = intensity * smoothstep(0.0, 2.0, intensity); + + gradient *= smoothstep(1.0,0.67+r*0.33, 1.0-intensity); + + gl_FragColor = gl_Color * gradient; +} diff --git a/gource/data/shaders/bloom.vert b/gource/data/shaders/bloom.vert new file mode 100644 index 000000000..7274540e5 --- /dev/null +++ b/gource/data/shaders/bloom.vert @@ -0,0 +1,10 @@ + +varying vec3 pos; + +void main() +{ + pos = gl_Vertex.xyz - gl_MultiTexCoord0.yzw; + gl_TexCoord[0] = gl_MultiTexCoord0; + gl_FrontColor = gl_Color; + gl_Position = ftransform(); +} diff --git a/gource/data/shaders/shadow.frag b/gource/data/shaders/shadow.frag new file mode 100644 index 000000000..6235f7f36 --- /dev/null +++ b/gource/data/shaders/shadow.frag @@ -0,0 +1,9 @@ +uniform sampler2D tex; +uniform float shadow_strength; + +void main(void) +{ + vec4 colour = texture2D(tex,gl_TexCoord[0].st); + + gl_FragColor = vec4(0.0, 0.0, 0.0, gl_Color.w * colour.w * shadow_strength); +} diff --git a/gource/data/shaders/shadow.vert b/gource/data/shaders/shadow.vert new file mode 100644 index 000000000..061b80424 --- /dev/null +++ b/gource/data/shaders/shadow.vert @@ -0,0 +1,6 @@ +void main(void) +{ + gl_TexCoord[0] = gl_MultiTexCoord0; + gl_FrontColor = gl_Color; + gl_Position = ftransform(); +} diff --git a/gource/data/shaders/text.frag b/gource/data/shaders/text.frag new file mode 100644 index 000000000..5bed3c20d --- /dev/null +++ b/gource/data/shaders/text.frag @@ -0,0 +1,15 @@ +uniform sampler2D tex; +uniform float shadow_strength; +uniform float texel_size; + +void main(void) +{ + float colour_alpha = texture2D(tex,gl_TexCoord[0].xy).w; + float shadow_alpha = texture2D(tex,gl_TexCoord[0].xy - vec2(texel_size)).w * shadow_strength; + + float combined_alpha = 1.0 - (1.0-shadow_alpha)*(1.0-colour_alpha); + + if(combined_alpha > 0.0) colour_alpha /= combined_alpha; + + gl_FragColor = gl_Color * vec4(vec3(colour_alpha), combined_alpha); +} diff --git a/gource/data/shaders/text.vert b/gource/data/shaders/text.vert new file mode 100644 index 000000000..061b80424 --- /dev/null +++ b/gource/data/shaders/text.vert @@ -0,0 +1,6 @@ +void main(void) +{ + gl_TexCoord[0] = gl_MultiTexCoord0; + gl_FrontColor = gl_Color; + gl_Position = ftransform(); +} diff --git a/gource/data/user.png b/gource/data/user.png new file mode 100644 index 000000000..23b53ebb9 Binary files /dev/null and b/gource/data/user.png differ diff --git a/gource/glew32.dll b/gource/glew32.dll new file mode 100644 index 000000000..37a65a112 Binary files /dev/null and b/gource/glew32.dll differ diff --git a/gource/gource.exe b/gource/gource.exe new file mode 100644 index 000000000..9f781abc0 Binary files /dev/null and b/gource/gource.exe differ diff --git a/gource/libboost_filesystem-mt.dll b/gource/libboost_filesystem-mt.dll new file mode 100644 index 000000000..25c119769 Binary files /dev/null and b/gource/libboost_filesystem-mt.dll differ diff --git a/gource/libbz2-1.dll b/gource/libbz2-1.dll new file mode 100644 index 000000000..e22f01e27 Binary files /dev/null and b/gource/libbz2-1.dll differ diff --git a/gource/libfreetype-6.dll b/gource/libfreetype-6.dll new file mode 100644 index 000000000..9ab4da486 Binary files /dev/null and b/gource/libfreetype-6.dll differ diff --git a/gource/libgcc_s_seh-1.dll b/gource/libgcc_s_seh-1.dll new file mode 100644 index 000000000..929d55b5b Binary files /dev/null and b/gource/libgcc_s_seh-1.dll differ diff --git a/gource/libglib-2.0-0.dll b/gource/libglib-2.0-0.dll new file mode 100644 index 000000000..38b06a6a2 Binary files /dev/null and b/gource/libglib-2.0-0.dll differ diff --git a/gource/libgraphite2.dll b/gource/libgraphite2.dll new file mode 100644 index 000000000..556106bbf Binary files /dev/null and b/gource/libgraphite2.dll differ diff --git a/gource/libharfbuzz-0.dll b/gource/libharfbuzz-0.dll new file mode 100644 index 000000000..b23c3ad56 Binary files /dev/null and b/gource/libharfbuzz-0.dll differ diff --git a/gource/libiconv-2.dll b/gource/libiconv-2.dll new file mode 100644 index 000000000..d28ee1d74 Binary files /dev/null and b/gource/libiconv-2.dll differ diff --git a/gource/libintl-8.dll b/gource/libintl-8.dll new file mode 100644 index 000000000..41580ba2f Binary files /dev/null and b/gource/libintl-8.dll differ diff --git a/gource/libjpeg-8.dll b/gource/libjpeg-8.dll new file mode 100644 index 000000000..cfeb9356d Binary files /dev/null and b/gource/libjpeg-8.dll differ diff --git a/gource/liblzma-5.dll b/gource/liblzma-5.dll new file mode 100644 index 000000000..468f0a3a7 Binary files /dev/null and b/gource/liblzma-5.dll differ diff --git a/gource/libpcre-1.dll b/gource/libpcre-1.dll new file mode 100644 index 000000000..3b8707113 Binary files /dev/null and b/gource/libpcre-1.dll differ diff --git a/gource/libpng16-16.dll b/gource/libpng16-16.dll new file mode 100644 index 000000000..3c9163ebe Binary files /dev/null and b/gource/libpng16-16.dll differ diff --git a/gource/libstdc++-6.dll b/gource/libstdc++-6.dll new file mode 100644 index 000000000..305b81b4a Binary files /dev/null and b/gource/libstdc++-6.dll differ diff --git a/gource/libtiff-5.dll b/gource/libtiff-5.dll new file mode 100644 index 000000000..bb0a959bc Binary files /dev/null and b/gource/libtiff-5.dll differ diff --git a/gource/libwebp-7.dll b/gource/libwebp-7.dll new file mode 100644 index 000000000..71b632fe8 Binary files /dev/null and b/gource/libwebp-7.dll differ diff --git a/gource/libwinpthread-1.dll b/gource/libwinpthread-1.dll new file mode 100644 index 000000000..5820e18b8 Binary files /dev/null and b/gource/libwinpthread-1.dll differ diff --git a/gource/libzstd.dll b/gource/libzstd.dll new file mode 100644 index 000000000..e201b97c7 Binary files /dev/null and b/gource/libzstd.dll differ diff --git a/gource/zlib1.dll b/gource/zlib1.dll new file mode 100644 index 000000000..7e8e6fda9 Binary files /dev/null and b/gource/zlib1.dll differ diff --git a/plains.json b/plains.json new file mode 100644 index 000000000..960520677 --- /dev/null +++ b/plains.json @@ -0,0 +1,69 @@ +{ + "children": [], + "decorators": [], + "objects": [], + "name": "Plains", + "layers": [ + { + "minHeight": 1, + "terrainZoom": 5, + "maxHeight": 3, + "palette": [ + "GRASS_BLOCK" + ], + "dispersion": "SCATTER" + }, + { + "minHeight": 1, + "terrainZoom": 5, + "maxHeight": 1, + "palette": [ + "DIRT" + ], + "dispersion": "SCATTER" + }, + { + "minHeight": 1, + "terrainZoom": 5, + "maxHeight": 3, + "palette": [ + "DIRT", + "COARSE_DIRT" + ], + "dispersion": "SCATTER" + }, + { + "minHeight": 6, + "terrainZoom": 5, + "maxHeight": 2341, + "palette": [ + "STONE", + "ANDESITE", + "STONE" + ], + "dispersion": "SCATTER" + } + ], + "childShrinkFactor": 1.55, + "derivative": "THE_VOID", + "auxiliaryGenerators": [ + { + "offsetX": 0, + "offsetZ": 0.01, + "min": 1, + "seed": 1336, + "max": 5, + "zoom": 3.065 + }, + { + "offsetX": 0, + "offsetZ": 0, + "min": 1.01, + "seed": 1339, + "max": 2, + "zoom": 1.6 + } + ], + "highHeight": 3.66669, + "lowHeight": 31.5 +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 52035c6d0..496bb387f 100644 --- a/pom.xml +++ b/pom.xml @@ -44,7 +44,7 @@ shade - false + true @@ -144,26 +144,43 @@ - - ninja.bytecode - Shuriken - 1.1.14 - - - com.volmit - Mortar - 1.0.76 - org.spigotmc spigot-api - 1.12.2-R0.1-SNAPSHOT + 1.16.1-R0.1-SNAPSHOT + provided + + + javax.vecmath + vecmath + 1.5.2 + + + com.google.code.gson + gson + 2.8.5 + + + org.projectlombok + lombok + 1.18.10 + provided + + + ninja.bytecode + Shuriken + 1.1.24 + + + org.bukkit + bukkit + 1.16.1-R0.1-SNAPSHOT provided org.bukkit.craftbukkit - cb-1.12.2 - 1.12.2 + cb-1.16.1 + 1.16.1 provided diff --git a/src/main/java/ninja/bytecode/iris/GeneratedChunk.java b/src/main/java/ninja/bytecode/iris/GeneratedChunk.java new file mode 100644 index 000000000..03c064dea --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/GeneratedChunk.java @@ -0,0 +1,20 @@ +package ninja.bytecode.iris; + +import org.bukkit.generator.ChunkGenerator.BiomeGrid; +import org.bukkit.generator.ChunkGenerator.ChunkData; + +import lombok.Data; +import ninja.bytecode.iris.util.ChunkPosition; + +@Data +public class GeneratedChunk +{ + private ChunkPosition pos; + private ChunkData data; + private BiomeGrid grid; + + public GeneratedChunk(ChunkPosition pos) + { + this.pos = pos; + } +} diff --git a/src/main/java/ninja/bytecode/iris/Iris.java b/src/main/java/ninja/bytecode/iris/Iris.java index e31c4f619..3364a036e 100644 --- a/src/main/java/ninja/bytecode/iris/Iris.java +++ b/src/main/java/ninja/bytecode/iris/Iris.java @@ -1,200 +1,688 @@ package ninja.bytecode.iris; import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import java.util.UUID; import org.bukkit.Bukkit; -import org.bukkit.Difficulty; +import org.bukkit.ChatColor; +import org.bukkit.FluidCollisionMode; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; import org.bukkit.World; -import org.bukkit.World.Environment; +import org.bukkit.WorldCreator; +import org.bukkit.block.data.BlockData; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.generator.ChunkGenerator; +import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.util.Vector; -import mortar.api.rift.PhantomRift; -import mortar.api.rift.Rift; -import mortar.api.rift.RiftException; -import mortar.bukkit.command.Command; -import mortar.bukkit.plugin.Control; -import mortar.bukkit.plugin.MortarPlugin; -import mortar.util.text.C; -import ninja.bytecode.iris.command.CommandIris; -import ninja.bytecode.iris.controller.ExecutionController; -import ninja.bytecode.iris.controller.PackController; -import ninja.bytecode.iris.controller.WandController; -import ninja.bytecode.iris.generator.IrisGenerator; +import com.google.gson.Gson; + +import ninja.bytecode.iris.generator.IrisChunkGenerator; +import ninja.bytecode.iris.object.IrisBiome; +import ninja.bytecode.iris.object.IrisDimension; +import ninja.bytecode.iris.object.IrisObject; +import ninja.bytecode.iris.util.BiomeResult; +import ninja.bytecode.iris.util.BlockDataTools; +import ninja.bytecode.iris.util.BoardManager; +import ninja.bytecode.iris.util.BoardProvider; +import ninja.bytecode.iris.util.BoardSettings; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.Cuboid; +import ninja.bytecode.iris.util.Cuboid.CuboidDirection; +import ninja.bytecode.iris.util.Desc; import ninja.bytecode.iris.util.Direction; -import ninja.bytecode.iris.util.HotswapGenerator; -import ninja.bytecode.iris.util.IrisMetrics; +import ninja.bytecode.iris.util.GroupedExecutor; +import ninja.bytecode.iris.util.IO; +import ninja.bytecode.iris.util.ScoreDirection; +import ninja.bytecode.iris.wand.WandController; +import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.collections.KMap; +import ninja.bytecode.shuriken.execution.J; +import ninja.bytecode.shuriken.format.Form; +import ninja.bytecode.shuriken.json.JSONException; +import ninja.bytecode.shuriken.json.JSONObject; import ninja.bytecode.shuriken.logging.L; +import ninja.bytecode.shuriken.math.RollingSequence; +import ninja.bytecode.shuriken.reaction.O; +import ninja.bytecode.shuriken.tools.JarScanner; -public class Iris extends MortarPlugin +public class Iris extends JavaPlugin implements BoardProvider { - public static Thread primaryThread; - public static Settings settings; - public static IrisMetrics metrics; - private static ExecutionController executionController; - + public static KList executors = new KList<>(); public static Iris instance; + public static IrisDataManager data; + public static IrisHotloadManager hotloader; + public static WandController wand; + private static String last = ""; + private BoardManager manager; + private RollingSequence hits = new RollingSequence(20); - @Control - private PackController packController; + public Iris() + { + IO.delete(new File("iris")); + } - @Control - private WandController wandController; - - @Command - private CommandIris commandIris; - - private Rift r; - - @Override public void onEnable() { instance = this; - executionController = new ExecutionController(); - executionController.start(); - primaryThread = Thread.currentThread(); - L.consoleConsumer = (s) -> Bukkit.getConsoleSender().sendMessage(s); - Direction.calculatePermutations(); - settings = new Settings(); - getServer().getPluginManager().registerEvents((Listener) this, this); - super.onEnable(); - } - - public File getObjectCacheFolder() - { - return getDataFolder("cache", "object"); - } - - public static boolean isGen(World world) - { - IrisGenerator g = getGen(world); - return g != null; - } - - public static IrisGenerator getGen(World world) - { - try - { - return (IrisGenerator) ((HotswapGenerator) world.getGenerator()).getGenerator(); - } - - catch(Throwable e) - { - - } - - return null; - } - - @Override - public void start() - { - instance = this; - packController.compile(); - - if(Iris.settings.performance.debugMode) + hotloader = new IrisHotloadManager(); + data = new IrisDataManager(getDataFolder()); + wand = new WandController(); + manager = new BoardManager(this, BoardSettings.builder().boardProvider(this).scoreDirection(ScoreDirection.UP).build()); + J.a(() -> { try { - //@builder - r = new PhantomRift("Iris-Debug/" + UUID.randomUUID().toString()) - .setTileTickLimit(0.1) - .setEntityTickLimit(0.1) - .setAllowBosses(false) - .setEnvironment(Environment.NORMAL) - .setDifficulty(Difficulty.PEACEFUL) - .setRandomLightUpdates(false) - .setViewDistance(32) - .setHangingTickRate(2000) - .setGenerator(IrisGenerator.class) - .load(); - - for(Player i : Bukkit.getOnlinePlayers()) - { - r.send(i); - } - //@done + writeDocs(); } - - catch(RiftException e) + catch(JSONException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | IOException e) { e.printStackTrace(); } - } + }); } @Override - public void stop() + public String getTitle(Player player) { - if(settings.performance.debugMode && r != null) + return ChatColor.GREEN + "Iris"; + } + + @Override + public List getLines(Player player) + { + World world = player.getWorld(); + List lines = new ArrayList<>(); + + if(world.getGenerator() instanceof IrisChunkGenerator) { - r.colapse(); + IrisChunkGenerator g = (IrisChunkGenerator) world.getGenerator(); + int x = player.getLocation().getBlockX(); + int z = player.getLocation().getBlockZ(); + BiomeResult er = g.sampleTrueBiome(x, z); + BiomeResult erx = g.sampleBiome(x, z); + IrisBiome b = er != null ? er.getBiome() : null; + IrisBiome bx = erx != null ? erx.getBiome() : null; + lines.add("&7&m-----------------"); + lines.add(ChatColor.GREEN + "Speed" + ChatColor.GRAY + ": " + ChatColor.BOLD + "" + ChatColor.GRAY + Form.f(g.getMetrics().getPerSecond().getAverage(), 0) + "/s " + Form.duration(g.getMetrics().getTotal().getAverage(), 1) + ""); + lines.add(ChatColor.GREEN + "Loss" + ChatColor.GRAY + ": " + ChatColor.BOLD + "" + ChatColor.GRAY + Form.duration(g.getMetrics().getLoss().getAverage(), 4) + ""); + lines.add(ChatColor.GREEN + "Generators" + ChatColor.GRAY + ": " + Form.f(CNG.creates)); + lines.add(ChatColor.GREEN + "Noise" + ChatColor.GRAY + ": " + Form.f((int) hits.getAverage())); + lines.add(ChatColor.GREEN + "Parallax Regions" + ChatColor.GRAY + ": " + Form.f((int) g.getParallaxMap().getLoadedRegions().size())); + lines.add(ChatColor.GREEN + "Parallax Chunks" + ChatColor.GRAY + ": " + Form.f((int) g.getParallaxMap().getLoadedChunks().size())); + + if(er != null && b != null) + { + lines.add(ChatColor.GREEN + "Biome" + ChatColor.GRAY + ": " + b.getName()); + lines.add(ChatColor.GREEN + "Real" + ChatColor.GRAY + ": " + bx.getName()); + lines.add(ChatColor.GREEN + "File" + ChatColor.GRAY + ": " + b.getLoadKey() + ".json"); + } + + lines.add("&7&m-----------------"); } - HandlerList.unregisterAll((Plugin) this); + else + { + lines.add(ChatColor.GREEN + "Join an Iris World!"); + } + + return lines; + } + + public void writeDocs() throws IOException, JSONException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException + { + JarScanner j = new JarScanner(getFile(), "ninja.bytecode.iris.object"); + j.scan(); + File of = new File(getDataFolder(), "packs"); + of.mkdirs(); + KMap files = new KMap<>(); + + for(Class i : j.getClasses()) + { + if(i.isAnnotationPresent(Desc.class)) + { + Desc d = i.getAnnotation(Desc.class); + KList page = new KList<>(); + page.add("# " + i.getSimpleName()); + page.add("> " + d.value()); + + page.add("```json"); + page.add(new JSONObject(new Gson().toJson(i.getConstructor().newInstance())).toString(4)); + page.add("```"); + + page.add(""); + for(java.lang.reflect.Field k : i.getDeclaredFields()) + { + if(k.isAnnotationPresent(Desc.class)) + { + page.add("## " + k.getName()); + page.add("> " + k.getAnnotation(Desc.class).value()); + page.add(""); + } + } + + String pge = page.toString("\n"); + files.put(i.getSimpleName(), pge); + } + } + + for(String i : files.k()) + { + IO.writeAll(new File(of, i + ".md"), files.get(i)); + } + } + + public void onDisable() + { + for(GroupedExecutor i : executors) + { + i.close(); + } + + executors.clear(); + manager.onDisable(); Bukkit.getScheduler().cancelTasks(this); - executionController.stop(); + HandlerList.unregisterAll((Plugin) this); } - @EventHandler - public void on(PlayerJoinEvent e) + @SuppressWarnings("deprecation") + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if(settings.performance.debugMode && r != null) + if(command.getName().equals("iris")) { - e.getPlayer().teleport(r.getSpawn()); + if(args.length == 0) + { + imsg(sender, "/iris dev [dimension] - Create a new dev world"); + imsg(sender, "/iris what - Data about items & blocks"); + imsg(sender, "/iris wand [?] - Get a wand / help"); + imsg(sender, "/iris save - Save object"); + imsg(sender, "/iris load - Load & place object"); + } + + if(args.length >= 1) + { + if(args[0].equalsIgnoreCase("what")) + { + if(args.length != 2) + { + imsg(sender, "/iris what - Data about items & blocks"); + return true; + } + + BlockData bd = null; + + try + { + if(args[1].toLowerCase().startsWith("h")) + { + bd = BlockDataTools.getBlockData(((Player) sender).getInventory().getItemInMainHand().getType().name()); + } + + else + { + bd = ((Player) sender).getTargetBlockExact(128, FluidCollisionMode.NEVER).getBlockData(); + } + + } + + catch(Throwable e) + { + + } + + if(bd == null) + { + imsg(sender, "No data found."); + return true; + } + + imsg(sender, "Material: " + ChatColor.GREEN + bd.getMaterial().name()); + imsg(sender, "Full: " + ChatColor.WHITE + bd.getAsString(true)); + + return true; + } + + if(args[0].equalsIgnoreCase("wand")) + { + if(args.length == 1) + { + ((Player) sender).getInventory().addItem(WandController.createWand()); + } + + else if(args[1].equalsIgnoreCase("x+y")) + { + Player p = (Player) sender; + + if(!WandController.isWand(p)) + { + sender.sendMessage("Ready your Wand."); + return true; + } + Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); + 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(CuboidDirection.North); + cursor = cursor.contract(CuboidDirection.South); + cursor = cursor.contract(CuboidDirection.East); + cursor = cursor.contract(CuboidDirection.West); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + } + + else if(args[1].equalsIgnoreCase("x&y")) + { + Player p = (Player) sender; + + if(!WandController.isWand(p)) + { + sender.sendMessage("Ready your Wand."); + return true; + } + + Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); + 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 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)); + + while(!cursorx.containsOnly(Material.AIR)) + { + a1x.add(new Vector(0, -1, 0)); + a2x.add(new Vector(0, -1, 0)); + cursorx = new Cuboid(a1x, a2x); + } + + a1x.add(new 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(CuboidDirection.North); + cursor = cursor.contract(CuboidDirection.South); + cursor = cursor.contract(CuboidDirection.East); + cursor = cursor.contract(CuboidDirection.West); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + } + + else if(args[1].equalsIgnoreCase(">") && args.length > 2) + { + Player p = (Player) sender; + + if(!WandController.isWand(p)) + { + sender.sendMessage("Ready your Wand."); + return true; + } + + int amt = Integer.valueOf(args[2]); + Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); + Location a1 = b[0].clone(); + Location a2 = b[1].clone(); + Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); + a1.add(d.toVector().multiply(amt)); + a2.add(d.toVector().multiply(amt)); + Cuboid cursor = new Cuboid(a1, a2); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + } + + else if(args[1].equalsIgnoreCase("+") && args.length > 2) + { + Player p = (Player) sender; + + if(!WandController.isWand(p)) + { + sender.sendMessage("Ready your Wand."); + return true; + } + + int amt = Integer.valueOf(args[2]); + Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); + Location a1 = b[0].clone(); + Location a2 = b[1].clone(); + Cuboid cursor = new Cuboid(a1, a2); + Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); + cursor = cursor.expand(d, amt); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + } + + else if(args[1].equalsIgnoreCase("-") && args.length > 2) + { + Player p = (Player) sender; + + if(!WandController.isWand(p)) + { + sender.sendMessage("Ready your Wand."); + return true; + } + + int amt = Integer.valueOf(args[2]); + Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); + Location a1 = b[0].clone(); + Location a2 = b[1].clone(); + Cuboid cursor = new Cuboid(a1, a2); + Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); + cursor = cursor.expand(d, -amt); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + } + + else if(args[1].equalsIgnoreCase("p1")) + { + ItemStack wand = ((Player) sender).getInventory().getItemInMainHand(); + if(WandController.isWand(wand)) + { + Location[] g = WandController.getCuboid(wand); + g[0] = ((Player) sender).getLocation().getBlock().getLocation().clone().add(0, -1, 0); + ((Player) sender).setItemInHand(WandController.createWand(g[0], g[1])); + } + } + + else if(args[1].equalsIgnoreCase("p2")) + { + ItemStack wand = ((Player) sender).getInventory().getItemInMainHand(); + if(WandController.isWand(wand)) + { + Location[] g = WandController.getCuboid(wand); + g[1] = ((Player) sender).getLocation().getBlock().getLocation().clone().add(0, -1, 0); + ((Player) sender).setItemInHand(WandController.createWand(g[0], g[1])); + } + } + + else if(args[1].equalsIgnoreCase("l1")) + { + ItemStack wand = ((Player) sender).getInventory().getItemInMainHand(); + if(WandController.isWand(wand)) + { + Location[] g = WandController.getCuboid(wand); + g[0] = ((Player) sender).getTargetBlock((Set) null, 256).getLocation().clone(); + ((Player) sender).setItemInHand(WandController.createWand(g[0], g[1])); + } + } + + else if(args[1].equalsIgnoreCase("l2")) + { + ItemStack wand = ((Player) sender).getInventory().getItemInMainHand(); + if(WandController.isWand(wand)) + { + Location[] g = WandController.getCuboid(wand); + g[1] = ((Player) sender).getTargetBlock((Set) null, 256).getLocation().clone(); + ((Player) sender).setItemInHand(WandController.createWand(g[0], g[1])); + } + } + + else + { + imsg(sender, "/iris wand x+y - Expand up and out"); + imsg(sender, "/iris wand x&y - Expand up and down and out"); + imsg(sender, "/iris wand > - Shift in looking direction"); + imsg(sender, "/iris wand + - Expand in looking direction"); + imsg(sender, "/iris wand - - Contract in looking direction"); + imsg(sender, "/iris wand p1 - Set wand pos 1 where standing"); + imsg(sender, "/iris wand p2 - Set wand pos 2 where standing"); + imsg(sender, "/iris wand l1 - Set wand pos 1 where looking"); + imsg(sender, "/iris wand l2 - Set wand pos 2 where looking"); + } + + } + + if(args[0].equalsIgnoreCase("save") && args.length >= 2) + { + ItemStack wand = ((Player) sender).getInventory().getItemInMainHand(); + IrisObject o = WandController.createSchematic(wand); + try + { + o.write(new File(getDataFolder(), "objects/" + args[1] + ".iob")); + imsg(sender, "Saved " + "objects/" + args[1] + ".iob"); + } + + catch(IOException e) + { + imsg(sender, "Failed to save " + "objects/" + args[1] + ".iob"); + + e.printStackTrace(); + } + } + + if(args[0].equalsIgnoreCase("load") && args.length >= 2) + { + File file = new File(getDataFolder(), "objects/" + args[1] + ".iob"); + boolean intoWand = false; + + for(String i : args) + { + if(i.equalsIgnoreCase("-edit")) + { + intoWand = true; + } + } + + if(!file.exists()) + { + imsg(sender, "Can't find " + "objects/" + args[1] + ".iob"); + } + + ItemStack wand = ((Player) sender).getInventory().getItemInMainHand(); + IrisObject o = new IrisObject(0, 0, 0); + + try + { + o.read(new File(getDataFolder(), "objects/" + args[1] + ".iob")); + imsg(sender, "Loaded " + "objects/" + args[1] + ".iob"); + Location block = ((Player) sender).getTargetBlock((Set) null, 256).getLocation().clone().add(0, 1, 0); + + if(intoWand && WandController.isWand(wand)) + { + wand = WandController.createWand(block.clone().subtract(o.getCenter()).add(o.getW() - 1, o.getH(), o.getD() - 1), block.clone().subtract(o.getCenter())); + ((Player) sender).getInventory().setItemInMainHand(wand); + imsg(sender, "Updated wand for " + "objects/" + args[1] + ".iob"); + } + + WandController.pasteSchematic(o, block); + imsg(sender, "Placed " + "objects/" + args[1] + ".iob"); + } + + catch(IOException e) + { + imsg(sender, "Failed to load " + "objects/" + args[1] + ".iob"); + e.printStackTrace(); + } + } + + if(args[0].equalsIgnoreCase("dev")) + { + String dim = "overworld"; + + if(args.length > 1) + { + dim = args[1]; + } + + String dimm = dim; + + Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> + { + for(World i : Bukkit.getWorlds()) + { + if(i.getName().startsWith("iris/")) + { + for(Player j : Bukkit.getOnlinePlayers()) + { + imsg(j, "Unloading " + i.getName()); + } + + Bukkit.unloadWorld(i, false); + } + } + + IrisDimension d = data.getDimensionLoader().load(dimm); + + if(d == null) + { + imsg(sender, "Can't find dimension: " + dimm); + return; + } + + for(Player i : Bukkit.getOnlinePlayers()) + { + imsg(i, "Creating Iris " + dimm + "..."); + } + + IrisChunkGenerator gx = new IrisChunkGenerator(dimm, 16); + O done = new O(); + done.set(false); + + J.a(() -> + { + int req = 740; + while(!done.get()) + { + for(Player i : Bukkit.getOnlinePlayers()) + { + imsg(i, "Generating " + Form.pc((double) gx.getGenerated() / (double) req)); + } + J.sleep(3000); + } + }); + World world = Bukkit.createWorld(new WorldCreator("iris/" + UUID.randomUUID()).generator(gx)); + done.set(true); + + for(Player i : Bukkit.getOnlinePlayers()) + { + imsg(i, "Generating 100%"); + } + + for(Player i : Bukkit.getOnlinePlayers()) + { + i.teleport(new Location(world, 0, 100, 0)); + + Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> + { + imsg(i, "Have Fun!"); + i.setGameMode(GameMode.SPECTATOR); + }, 5); + } + }); + } + } + + return true; } + + return false; } - public void reload() + public void imsg(CommandSender s, String msg) { - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> - { - onDisable(); - onEnable(); - }); + s.sendMessage(ChatColor.GREEN + "[" + ChatColor.DARK_GRAY + "Iris" + ChatColor.GREEN + "]" + ChatColor.GRAY + ": " + msg); } @Override public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { - return new HotswapGenerator(new IrisGenerator()); + return new IrisChunkGenerator("overworld", 16); } - @Override - public String getTag(String arg0) + public static void msg(String string) { - return makeTag(C.GREEN, C.DARK_GRAY, C.GRAY, C.BOLD + "Iris" + C.RESET); - } + String msg = ChatColor.GREEN + "[Iris]: " + ChatColor.GRAY + string; - public static String makeTag(C brace, C tag, C text, String tagName) - { - return brace + "\u3008" + tag + tagName + brace + "\u3009" + " " + text; - } - - public static PackController pack() - { - return instance.packController; - } - - public static ExecutionController exec() - { - if(executionController == null) + if(last.equals(msg)) { - executionController = new ExecutionController(); - executionController.start(); + return; } - return executionController; + last = msg; + + Bukkit.getConsoleSender().sendMessage(msg); } - public static WandController wand() + public static void warn(String string) { - return instance.wandController; + msg(ChatColor.YELLOW + string); + } + + public static void error(String string) + { + msg(ChatColor.RED + string); + } + + public static void verbose(String string) + { + msg(ChatColor.GRAY + string); + } + + public static void success(String string) + { + msg(ChatColor.GREEN + string); + } + + public static void info(String string) + { + msg(ChatColor.WHITE + string); + } + + public void hit(long hits2) + { + hits.put(hits2); } } diff --git a/src/main/java/ninja/bytecode/iris/IrisContext.java b/src/main/java/ninja/bytecode/iris/IrisContext.java new file mode 100644 index 000000000..b855bd1c9 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/IrisContext.java @@ -0,0 +1,37 @@ +package ninja.bytecode.iris; + +import org.bukkit.World; + +import ninja.bytecode.iris.object.IrisDimension; +import ninja.bytecode.iris.object.IrisRegion; +import ninja.bytecode.iris.util.BiomeResult; +import ninja.bytecode.shuriken.collections.KMap; + +public interface IrisContext +{ + static KMap contexts = new KMap<>(); + + public static void pushContext(IrisContext context) + { + contexts.put(context.getWorld(), context); + } + + public static IrisContext of(World world) + { + return contexts.get(world); + } + + public BiomeResult getBiome(int x, int z); + + public IrisDimension getDimension(); + + public IrisRegion getRegion(int x, int z); + + public IrisMetrics getMetrics(); + + public int getHeight(int x, int z); + + public World getWorld(); + + public void onHotloaded(); +} diff --git a/src/main/java/ninja/bytecode/iris/IrisDataManager.java b/src/main/java/ninja/bytecode/iris/IrisDataManager.java new file mode 100644 index 000000000..10b1b51cc --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/IrisDataManager.java @@ -0,0 +1,127 @@ +package ninja.bytecode.iris; + +import java.io.File; + +import org.bukkit.World.Environment; +import org.bukkit.block.Biome; + +import com.google.gson.Gson; + +import lombok.Data; +import ninja.bytecode.iris.object.IrisBiome; +import ninja.bytecode.iris.object.IrisBiomeDecorator; +import ninja.bytecode.iris.object.IrisDimension; +import ninja.bytecode.iris.object.IrisGenerator; +import ninja.bytecode.iris.object.IrisNoiseGenerator; +import ninja.bytecode.iris.object.IrisObjectPlacement; +import ninja.bytecode.iris.object.IrisRegion; +import ninja.bytecode.iris.util.IO; +import ninja.bytecode.iris.util.ObjectResourceLoader; +import ninja.bytecode.iris.util.ResourceLoader; +import ninja.bytecode.shuriken.json.JSONObject; + +@Data +public class IrisDataManager +{ + private File dataFolder; + private File packs; + private ResourceLoader biomeLoader; + private ResourceLoader regionLoader; + private ResourceLoader dimensionLoader; + private ResourceLoader generatorLoader; + private ObjectResourceLoader objectLoader; + + public void hotloaded() + { + packs.mkdirs(); + this.regionLoader = new ResourceLoader<>(packs, "regions", "Region", IrisRegion.class); + this.biomeLoader = new ResourceLoader<>(packs, "biomes", "Biome", IrisBiome.class); + this.dimensionLoader = new ResourceLoader<>(packs, "dimensions", "Dimension", IrisDimension.class); + this.generatorLoader = new ResourceLoader<>(packs, "generators", "Generator", IrisGenerator.class); + this.objectLoader = new ObjectResourceLoader(packs, "objects", "Object"); + writeExamples(); + } + + public IrisDataManager(File dataFolder) + { + this.dataFolder = dataFolder; + this.packs = new File(dataFolder, "packs"); + hotloaded(); + } + + private void writeExamples() + { + File examples = new File(dataFolder, "example"); + examples.mkdirs(); + String biomes = ""; + String envs = ""; + + for(Biome i : Biome.values()) + { + biomes += i.name() + "\n"; + } + + for(Environment i : Environment.values()) + { + envs += i.name() + "\n"; + } + + try + { + new File(examples, "example-pack/regions").mkdirs(); + new File(examples, "example-pack/biomes").mkdirs(); + new File(examples, "example-pack/dimensions").mkdirs(); + new File(examples, "example-pack/generators").mkdirs(); + IO.writeAll(new File(examples, "biome-list.txt"), biomes); + IO.writeAll(new File(examples, "environment-list.txt"), envs); + + IrisGenerator gen = new IrisGenerator(); + IrisNoiseGenerator n = new IrisNoiseGenerator(); + n.setSeed(1000); + IrisNoiseGenerator nf = new IrisNoiseGenerator(); + nf.setIrisBased(false); + nf.setOctaves(3); + nf.setOpacity(16); + nf.setZoom(24); + nf.setSeed(44); + n.getFracture().add(nf); + IrisNoiseGenerator nf2 = new IrisNoiseGenerator(); + nf2.setIrisBased(false); + nf2.setOctaves(8); + nf2.setOpacity(24); + nf2.setZoom(64); + nf2.setSeed(55); + n.getFracture().add(nf2); + gen.getComposite().add(n); + + IrisDimension dim = new IrisDimension(); + + IrisRegion region = new IrisRegion(); + region.getLandBiomes().add("plains"); + region.getLandBiomes().add("desert"); + region.getLandBiomes().add("forest"); + region.getLandBiomes().add("mountains"); + region.getSeaBiomes().add("ocean"); + region.getShoreBiomes().add("beach"); + + IrisObjectPlacement o = new IrisObjectPlacement(); + o.getPlace().add("schematic1"); + o.getPlace().add("schematic2"); + + IrisBiome biome = new IrisBiome(); + biome.getChildren().add("another_biome"); + biome.getDecorators().add(new IrisBiomeDecorator()); + biome.getObjects().add(o); + + IO.writeAll(new File(examples, "example-pack/biomes/example-biome.json"), new JSONObject(new Gson().toJson(biome)).toString(4)); + IO.writeAll(new File(examples, "example-pack/regions/example-region.json"), new JSONObject(new Gson().toJson(region)).toString(4)); + IO.writeAll(new File(examples, "example-pack/dimensions/example-dimension.json"), new JSONObject(new Gson().toJson(dim)).toString(4)); + IO.writeAll(new File(examples, "example-pack/generators/example-generator.json"), new JSONObject(new Gson().toJson(gen)).toString(4)); + } + + catch(Throwable e) + { + + } + } +} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/IrisHotloadManager.java b/src/main/java/ninja/bytecode/iris/IrisHotloadManager.java new file mode 100644 index 000000000..12fbd538e --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/IrisHotloadManager.java @@ -0,0 +1,58 @@ +package ninja.bytecode.iris; + +import java.io.File; + +import org.bukkit.Bukkit; + +import ninja.bytecode.iris.util.ChronoLatch; +import ninja.bytecode.iris.util.FileWatcher; +import ninja.bytecode.shuriken.collections.KSet; + +public class IrisHotloadManager +{ + private ChronoLatch latch; + private KSet watchers; + + public IrisHotloadManager() + { + watchers = new KSet<>(); + latch = new ChronoLatch(3000); + } + + public void check(IrisContext ch) + { + if(!latch.flip()) + { + return; + } + + Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> + { + boolean modified = false; + int c = 0; + + for(FileWatcher i : watchers) + { + if(i.checkModified()) + { + c++; + Iris.info("File Modified: " + i.getFile().getPath()); + modified = true; + } + } + + if(modified) + { + watchers.clear(); + Iris.success("Hotloading Iris (" + c + " File" + (c == 1 ? "" : "s") + " changed)"); + Iris.data.hotloaded(); + ch.onHotloaded(); + } + }); + } + + public void track(File file) + { + watchers.add(new FileWatcher(file)); + } +} diff --git a/src/main/java/ninja/bytecode/iris/IrisMetrics.java b/src/main/java/ninja/bytecode/iris/IrisMetrics.java new file mode 100644 index 000000000..9c57fae0d --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/IrisMetrics.java @@ -0,0 +1,21 @@ +package ninja.bytecode.iris; + +import lombok.Data; +import ninja.bytecode.shuriken.math.RollingSequence; + +@Data +public class IrisMetrics +{ + private final RollingSequence total; + private final RollingSequence perSecond; + private final RollingSequence loss; + public int generators = 0; + public int noiseHits = 0; + + public IrisMetrics(int memory) + { + total = new RollingSequence(memory); + perSecond = new RollingSequence(5); + loss = new RollingSequence(memory); + } +} diff --git a/src/main/java/ninja/bytecode/iris/IrisSettings.java b/src/main/java/ninja/bytecode/iris/IrisSettings.java new file mode 100644 index 000000000..7d58f403a --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/IrisSettings.java @@ -0,0 +1,9 @@ +package ninja.bytecode.iris; + +import lombok.Data; + +@Data +public class IrisSettings +{ + private int threads = 8; +} diff --git a/src/main/java/ninja/bytecode/iris/Settings.java b/src/main/java/ninja/bytecode/iris/Settings.java deleted file mode 100644 index 893034845..000000000 --- a/src/main/java/ninja/bytecode/iris/Settings.java +++ /dev/null @@ -1,87 +0,0 @@ -package ninja.bytecode.iris; - -import ninja.bytecode.iris.util.InterpolationMode; -import ninja.bytecode.iris.util.ObjectMode; -import ninja.bytecode.iris.util.PerformanceMode; - -public class Settings -{ - public PerformanceSettings performance = new PerformanceSettings(); - public GeneratorSettings gen = new GeneratorSettings(); - public OreSettings ore = new OreSettings(); - - public static class PerformanceSettings - { - public PerformanceMode performanceMode = PerformanceMode.EXPLICIT; - public ObjectMode objectMode = ObjectMode.PARALLAX; - public int threadPriority = Thread.MAX_PRIORITY; - public int threadCount = 32; - public boolean debugMode = true; - public int decorationAccuracy = 1; - public boolean noObjectFail = false; - public boolean verbose = false; - public int placeHistoryLimit = 8192; - } - - public static class GeneratorSettings - { - public InterpolationMode interpolationMode = InterpolationMode.BILINEAR; - public int interpolationRadius = 53; - public int blockSmoothing = 1; - public double objectDensity = 1D; - public double horizontalZoom = 2; - public double heightFracture = 155; - public double landScale = 0.44; - public double landChance = 0.56; - public double roughness = 1.25; - public double biomeEdgeFuzzScale = 1.75; - public double biomeEdgeScrambleScale = 0.2; - public double biomeEdgeScrambleRange = 2.5; - public double heightMultiplier = 0.806; - public double heightExponentBase = 1; - public double heightExponentMultiplier = 1.41; - public double heightScale = 0.56; - public double baseHeight = 0.065; - public int seaLevel = 63; - public double biomeScale = 0.8; - public boolean flatBedrock = false; - } - - public static class OreSettings - { - public int ironMinHeight = 5; - public int ironMaxHeight = 65; - public double ironMaxDispersion = 0.02; - public double ironMinDispersion = 0.26; - - public int coalMinHeight = 5; - public int coalMaxHeight = 100; - public double coalMaxDispersion = 0.02; - public double coalMinDispersion = 0.29; - - public int goldMinHeight = 5; - public int goldMaxHeight = 34; - public double goldMaxDispersion = 0.01; - public double goldMinDispersion = 0.13; - - public int redstoneMinHeight = 5; - public int redstoneMaxHeight = 15; - public double redstoneMaxDispersion = 0.05; - public double redstoneMinDispersion = 0.17; - - public int lapisMinHeight = 13; - public int lapisMaxHeight = 33; - public double lapisMaxDispersion = 0.05; - public double lapisMinDispersion = 0.12; - - public int diamondMinHeight = 5; - public int diamondMaxHeight = 16; - public double diamondMaxDispersion = 0.05; - public double diamondMinDispersion = 0.1; - - public int emeraldMinHeight = 5; - public int emeraldMaxHeight = 16; - public double emeraldMaxDispersion = 0.005; - public double emeraldMinDispersion = 0.07; - } -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandFind.java b/src/main/java/ninja/bytecode/iris/command/CommandFind.java deleted file mode 100644 index 7a47f0f61..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandFind.java +++ /dev/null @@ -1,33 +0,0 @@ -package ninja.bytecode.iris.command; - -import mortar.bukkit.command.Command; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; - -public class CommandFind extends MortarCommand -{ - @Command - private CommandFindBiome fBiome; - - @Command - private CommandFindObject fObject; - - public CommandFind() - { - super("find", "f"); - setDescription("Teleport to a specific biome / object"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - for(MortarCommand i : getChildren()) - { - sender.sendMessage("/iris find " + C.WHITE + i.getNode() + C.GRAY + (!i.getNodes().isEmpty() ? "," : "") + i.getNodes().toString(",") + " - " + C.DARK_GREEN + i.getDescription()); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandFindBiome.java b/src/main/java/ninja/bytecode/iris/command/CommandFindBiome.java deleted file mode 100644 index c158ce1bd..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandFindBiome.java +++ /dev/null @@ -1,93 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.World; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.pack.IrisBiome; - -public class CommandFindBiome extends MortarCommand -{ - public CommandFindBiome() - { - super("biome", "b"); - setDescription("Teleport to a biome by name"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - World w = null; - - if(sender.isPlayer() && Iris.isGen(sender.player().getWorld())) - { - w = sender.player().getWorld(); - } - - else - { - if(sender.isPlayer()) - { - sender.sendMessage(sender.player().getWorld().getGenerator().getClass().getCanonicalName()); - } - - sender.sendMessage("Console / Non-Iris World."); - return true; - } - - Player p = sender.player(); - IrisGenerator g = Iris.getGen(p.getWorld()); - if(args.length > 0) - { - IrisBiome b = null; - for(IrisBiome i : g.getDimension().getBiomes()) - { - if(args[0].toLowerCase().equals(i.getName().toLowerCase().replaceAll("\\Q \\E", "_"))) - { - b = i; - break; - } - } - - if(b == null) - { - sender.sendMessage("Couldn't find any biomes containing '" + args[0] + "'."); - } - - else - { - sender.sendMessage("Looking for Biome " + b.getName() + "..."); - boolean f = false; - - for(int i = 0; i < 10000; i++) - { - int x = (int) ((int) (29999983 / 1.2) * Math.random()); - int z = (int) ((int) (29999983 / 1.2) * Math.random()); - - if(g.getBiome((int) g.getOffsetX(x, z), (int) g.getOffsetZ(x, z)).equals(b)) - { - f = true; - p.teleport(w.getHighestBlockAt(x, z).getLocation()); - break; - } - } - - if(!f) - { - sender.sendMessage("Couldn't for " + b.getName() + " in 10,000 different locations and could not find it. Try again!"); - } - } - } - - else - { - sender.sendMessage("/iris find biome "); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandFindObject.java b/src/main/java/ninja/bytecode/iris/command/CommandFindObject.java deleted file mode 100644 index 387f964f2..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandFindObject.java +++ /dev/null @@ -1,64 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.genobject.PlacedObject; - -public class CommandFindObject extends MortarCommand -{ - public CommandFindObject() - { - super("object", "o"); - setDescription("Teleport to an object by name"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - World w = null; - - if(sender.isPlayer() && Iris.isGen(sender.player().getWorld())) - { - w = sender.player().getWorld(); - } - - else - { - sender.sendMessage("Console / Non-Iris World."); - return true; - } - - Player p = sender.player(); - - if(args.length > 0) - { - PlacedObject o = Iris.getGen(w).randomObject(args[0]); - - if(o != null) - { - Location l = new Location(w, o.getX(), o.getY(), o.getZ()); - p.teleport(l); - sender.sendMessage("Found Object " + C.DARK_GREEN + o.getF().replace(":", "/" + C.WHITE)); - } - - else - { - sender.sendMessage("Couldn't find any objects containing '" + args[0] + "' Either"); - } - } - - else - { - sender.sendMessage("/iris find object "); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandIris.java b/src/main/java/ninja/bytecode/iris/command/CommandIris.java deleted file mode 100644 index a7907abb8..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandIris.java +++ /dev/null @@ -1,44 +0,0 @@ -package ninja.bytecode.iris.command; - -import mortar.bukkit.command.Command; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; - -public class CommandIris extends MortarCommand -{ - @Command - private CommandTimings timings; - - @Command - private CommandWhat what; - - @Command - private CommandFind find; - - @Command - private CommandObject object; - - @Command - private CommandSelection selection; - - @Command - private CommandReload reload; - - public CommandIris() - { - super("iris", "irs", "ir"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - for(MortarCommand i : getChildren()) - { - sender.sendMessage("/iris " + C.WHITE + i.getNode() + C.GRAY + (!i.getNodes().isEmpty() ? "," : "") + i.getNodes().toString(",") + " - " + C.DARK_GREEN + i.getDescription()); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandObject.java b/src/main/java/ninja/bytecode/iris/command/CommandObject.java deleted file mode 100644 index 1c44cabfe..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandObject.java +++ /dev/null @@ -1,36 +0,0 @@ -package ninja.bytecode.iris.command; - -import mortar.bukkit.command.Command; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; - -public class CommandObject extends MortarCommand -{ - @Command - private CommandObjectWand oWand; - - @Command - private CommandObjectLoad oLoad; - - @Command - private CommandObjectSave oSave; - - public CommandObject() - { - super("object", "o"); - setDescription("Object Subcommands"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - for(MortarCommand i : getChildren()) - { - sender.sendMessage("/iris object " + C.WHITE + i.getNode() + C.GRAY + (!i.getNodes().isEmpty() ? "," : "") + i.getNodes().toString(",") + " - " + C.DARK_GREEN + i.getDescription()); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandObjectLoad.java b/src/main/java/ninja/bytecode/iris/command/CommandObjectLoad.java deleted file mode 100644 index db4ddcb18..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandObjectLoad.java +++ /dev/null @@ -1,166 +0,0 @@ -package ninja.bytecode.iris.command; - -import java.io.File; -import java.io.FileInputStream; - -import org.bukkit.Location; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.controller.WandController; -import ninja.bytecode.iris.generator.genobject.GenObject; -import ninja.bytecode.iris.util.Direction; -import ninja.bytecode.shuriken.format.Form; - -public class CommandObjectLoad extends MortarCommand -{ - public CommandObjectLoad() - { - super("load", "l"); - setDescription("Load & Paste an object"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Players Only"); - return true; - } - - if(args.length < 1) - { - sender.sendMessage("/iris object load "); - sender.sendMessage("Use -c to place at cursor"); - sender.sendMessage("Use -g to place with gravity"); - sender.sendMessage("Use -w to set hydrophilic"); - sender.sendMessage("Use -u to set submerged"); - sender.sendMessage("Use -h: to shift vertically"); - sender.sendMessage("Use -m: to set max slope"); - sender.sendMessage("Use -b: to set base slope"); - sender.sendMessage("Use -f:N -t:S to rotate north to south (180 deg)"); - return true; - } - - Player p = sender.player(); - - GenObject s = new GenObject(1, 1, 1); - File f = new File(Iris.instance.getDataFolder(), "schematics/" + args[0] + ".ish"); - - if(!f.exists()) - { - sender.sendMessage("Can't find " + args[0]); - return true; - } - - try - { - FileInputStream fin = new FileInputStream(f); - s.read(fin, true); - - boolean cursor = false; - boolean gravity = false; - Direction df = null; - Direction dt = null; - int shift = 0; - - for(String i : args) - { - if(i.equalsIgnoreCase("-c")) - { - sender.sendMessage("Placing @ Cursor"); - cursor = true; - continue; - } - - if(i.equalsIgnoreCase("-u")) - { - sender.sendMessage("Placing Submerged"); - s.setSubmerged(true); - continue; - } - - if(i.equalsIgnoreCase("-w")) - { - sender.sendMessage("Placing with Hydrophilia"); - s.setHydrophilic(true); - continue; - } - - if(i.equalsIgnoreCase("-g")) - { - sender.sendMessage("Placing with Gravity"); - gravity = true; - continue; - } - - if(i.startsWith("-m:")) - { - shift = Integer.valueOf(i.split("\\Q:\\E")[1]); - sender.sendMessage("Max Slope set to " + shift); - s.setMaxslope(shift); - continue; - } - - if(i.startsWith("-b:")) - { - shift = Integer.valueOf(i.split("\\Q:\\E")[1]); - sender.sendMessage("Base Slope set to " + shift); - s.setBaseslope(shift); - continue; - } - - if(i.startsWith("-h:")) - { - shift = Integer.valueOf(i.split("\\Q:\\E")[1]); - sender.sendMessage("Shifting Placement by 0," + shift + ",0"); - continue; - } - - if(i.startsWith("-f:")) - { - df = Direction.valueOf(i.split("\\Q:\\E")[1].toUpperCase().substring(0, 1)); - continue; - } - - if(i.startsWith("-t:")) - { - dt = Direction.valueOf(i.split("\\Q:\\E")[1].toUpperCase().substring(0, 1)); - continue; - } - } - - if(dt != null && df != null) - { - sender.sendMessage("Rotating " + C.WHITE + df + C.GRAY + " to " + C.WHITE + dt); - s.rotate(df, dt); - } - - Location at = p.getLocation(); - - if(cursor) - { - at = p.getTargetBlock(null, 64).getLocation(); - } - - s.setShift(0, shift, 0); - s.setGravity(gravity); - WandController.pasteSchematic(s, at); - p.playSound(p.getLocation(), Sound.BLOCK_ENCHANTMENT_TABLE_USE, 1f, 1.25f); - sender.sendMessage("Pasted " + args[0] + " (" + Form.f(s.getSchematic().size()) + " Blocks Modified)"); - } - - catch(Throwable e1) - { - e1.printStackTrace(); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandObjectSave.java b/src/main/java/ninja/bytecode/iris/command/CommandObjectSave.java deleted file mode 100644 index f0a36430e..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandObjectSave.java +++ /dev/null @@ -1,67 +0,0 @@ -package ninja.bytecode.iris.command; - -import java.io.File; -import java.io.FileOutputStream; - -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.controller.WandController; -import ninja.bytecode.iris.generator.genobject.GenObject; -import ninja.bytecode.shuriken.format.Form; - -public class CommandObjectSave extends MortarCommand -{ - public CommandObjectSave() - { - super("save", "s"); - setDescription("Save an object"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Players Only"); - return true; - } - - if(args.length < 1) - { - sender.sendMessage("/iris object save "); - return true; - } - - Player p = sender.player(); - GenObject s = WandController.createSchematic(p.getInventory().getItemInMainHand(), p.getLocation()); - - if(s == null) - { - sender.sendMessage("Hold your wand while using this command."); - return true; - } - - File f = new File(Iris.instance.getDataFolder(), "schematics/" + args[0] + ".ish"); - f.getParentFile().mkdirs(); - try - { - FileOutputStream fos = new FileOutputStream(f); - s.write(fos, true); - p.sendMessage("Saved " + args[0] + " (" + Form.f(s.getSchematic().size()) + " Entries)"); - p.playSound(p.getLocation(), Sound.BLOCK_ENCHANTMENT_TABLE_USE, 1f, 0.45f); - } - - catch(Throwable e1) - { - p.sendMessage("Failed. Check the console!"); - e1.printStackTrace(); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandObjectWand.java b/src/main/java/ninja/bytecode/iris/command/CommandObjectWand.java deleted file mode 100644 index b98f2166b..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandObjectWand.java +++ /dev/null @@ -1,32 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Sound; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.controller.WandController; - -public class CommandObjectWand extends MortarCommand -{ - public CommandObjectWand() - { - super("wand", "w"); - setDescription("Obtain Iris Wand"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Players Only"); - return true; - } - - sender.player().getInventory().addItem(WandController.createWand()); - sender.player().playSound(sender.player().getLocation(), Sound.ITEM_ARMOR_EQUIP_DIAMOND, 1f, 1.55f); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandReload.java b/src/main/java/ninja/bytecode/iris/command/CommandReload.java deleted file mode 100644 index 45d2a2afc..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandReload.java +++ /dev/null @@ -1,36 +0,0 @@ -package ninja.bytecode.iris.command; - -import mortar.bukkit.command.Command; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; - -public class CommandReload extends MortarCommand -{ - @Command - private CommandReloadPack rThis; - - @Command - private CommandReloadChunks rChunks; - - @Command - private CommandReloadIris rIris; - - public CommandReload() - { - super("reload", "r"); - setDescription("Reload Chunks / Pack / Iris"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - for(MortarCommand i : getChildren()) - { - sender.sendMessage("/iris reload " + C.WHITE + i.getNode() + C.GRAY + (!i.getNodes().isEmpty() ? "," : "") + i.getNodes().toString(",") + " - " + C.DARK_GREEN + i.getDescription()); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandReloadChunks.java b/src/main/java/ninja/bytecode/iris/command/CommandReloadChunks.java deleted file mode 100644 index 2bfc5e9c0..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandReloadChunks.java +++ /dev/null @@ -1,38 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Chunk; -import org.bukkit.entity.Player; - -import mortar.api.nms.NMP; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; - -public class CommandReloadChunks extends MortarCommand -{ - public CommandReloadChunks() - { - super("chunks", "c"); - setDescription("Resends chunk packets."); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - - if(!sender.isPlayer()) - { - sender.sendMessage("Again, You don't have a position. Stop it."); - } - - sender.sendMessage("Resending Chunks in your view distance."); - Player p = sender.player(); - - for(Chunk i : p.getWorld().getLoadedChunks()) - { - NMP.CHUNK.refreshIgnorePosition(p, i); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandReloadIris.java b/src/main/java/ninja/bytecode/iris/command/CommandReloadIris.java deleted file mode 100644 index 892c06388..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandReloadIris.java +++ /dev/null @@ -1,23 +0,0 @@ -package ninja.bytecode.iris.command; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.Iris; - -public class CommandReloadIris extends MortarCommand -{ - public CommandReloadIris() - { - super("iris", "i"); - setDescription("Reloads Iris"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - Iris.instance.reload(); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandReloadPack.java b/src/main/java/ninja/bytecode/iris/command/CommandReloadPack.java deleted file mode 100644 index 63bc8c350..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandReloadPack.java +++ /dev/null @@ -1,142 +0,0 @@ -package ninja.bytecode.iris.command; - -import java.util.function.Consumer; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import mortar.api.sched.J; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.logic.queue.ChronoLatch; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.controller.PackController; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.WorldReactor; -import ninja.bytecode.iris.pack.CompiledDimension; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.format.Form; -import ninja.bytecode.shuriken.logging.L; - -public class CommandReloadPack extends MortarCommand -{ - public CommandReloadPack() - { - super("pack", "p"); - setDescription("Reloads the pack + regen"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - sender.sendMessage("=== Hotloading Pack ==="); - PackController c = Iris.pack(); - KMap f = new KMap<>(); - - for(World i : Bukkit.getWorlds()) - { - if(i.getGenerator() instanceof IrisGenerator) - { - String n = ((IrisGenerator) i.getGenerator()).getDimension().getName(); - sender.sendMessage("Preparing " + n); - f.put(i.getName(), n); - } - } - - if(f.isEmpty()) - { - sender.sendMessage("No Worlds to inject!"); - return true; - } - - J.a(() -> - { - try - { - Consumer m = (msg) -> - { - J.s(() -> - { - String mm = msg; - - if(msg.contains("|")) - { - KList fx = new KList<>(); - fx.add(msg.split("\\Q|\\E")); - fx.remove(0); - fx.remove(0); - mm = fx.toString(""); - } - - sender.sendMessage(mm.replaceAll("\\Q \\E", "")); - }); - }; - - L.addLogConsumer(m); - c.compile(); - L.logConsumers.remove(m); - - J.s(() -> - { - if(sender.isPlayer()) - { - ChronoLatch cl = new ChronoLatch(3000); - Player p = sender.player(); - World ww = sender.player().getWorld(); - - sender.sendMessage("Regenerating View Distance"); - - WorldReactor r = new WorldReactor(ww); - r.generateRegionNormal(p, true, 200, (pct) -> - { - if(cl.flip()) - { - sender.sendMessage("Regenerating " + Form.pc(pct)); - } - }, () -> - { - sender.sendMessage("Done! Use F3 + A"); - }); - } - }, 5); - - for(String fi : f.k()) - { - J.s(() -> - { - World i = Bukkit.getWorld(fi); - CompiledDimension dim = c.getDimension(f.get(fi)); - - for(String k : c.getDimensions().k()) - { - if(c.getDimension(k).getName().equals(f.get(fi))) - { - dim = c.getDimension(k); - break; - } - } - - if(dim == null) - { - J.s(() -> sender.sendMessage("Cannot find dimnension: " + f.get(fi))); - return; - } - sender.sendMessage("Hotloaded " + i.getName()); - IrisGenerator g = ((IrisGenerator) i.getGenerator()); - g.inject(dim); - }); - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } - }); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandSelection.java b/src/main/java/ninja/bytecode/iris/command/CommandSelection.java deleted file mode 100644 index 041da0bd2..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandSelection.java +++ /dev/null @@ -1,42 +0,0 @@ -package ninja.bytecode.iris.command; - -import mortar.bukkit.command.Command; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; - -public class CommandSelection extends MortarCommand -{ - @Command - private CommandSelectionExpand expand; - - @Command - private CommandSelectionShift shift; - - @Command - private CommandSelectionShrink shr; - - @Command - private CommandSelectionXUp xip; - - @Command - private CommandSelectionXVert xvc; - - public CommandSelection() - { - super("selection", "sel", "s"); - setDescription("Wand Selection Subcommands"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - for(MortarCommand i : getChildren()) - { - sender.sendMessage("/iris sel " + C.WHITE + i.getNode() + C.GRAY + (!i.getNodes().isEmpty() ? "," : "") + i.getNodes().toString(",") + " - " + C.DARK_GREEN + i.getDescription()); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandSelectionExpand.java b/src/main/java/ninja/bytecode/iris/command/CommandSelectionExpand.java deleted file mode 100644 index d5345dc22..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandSelectionExpand.java +++ /dev/null @@ -1,60 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Location; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.controller.WandController; -import ninja.bytecode.iris.util.Cuboid; -import ninja.bytecode.iris.util.Direction; - -public class CommandSelectionExpand extends MortarCommand -{ - public CommandSelectionExpand() - { - super("expand", "+"); - setDescription("Expand in looking direction"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Players Only"); - return true; - } - - Player p = sender.player(); - - if(!WandController.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } - - if(args.length == 0) - { - sender.sendMessage("/iris selection expand "); - return true; - } - - int amt = Integer.valueOf(args[0]); - Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); - Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); - cursor = cursor.expand(d, amt); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEMFRAME_ROTATE_ITEM, 1f, 0.55f); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandSelectionShift.java b/src/main/java/ninja/bytecode/iris/command/CommandSelectionShift.java deleted file mode 100644 index d0e60ba4b..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandSelectionShift.java +++ /dev/null @@ -1,61 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Location; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.controller.WandController; -import ninja.bytecode.iris.util.Cuboid; -import ninja.bytecode.iris.util.Direction; - -public class CommandSelectionShift extends MortarCommand -{ - public CommandSelectionShift() - { - super("shift", ">"); - setDescription("Shift looking direction"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Players Only"); - return true; - } - - Player p = sender.player(); - - if(!WandController.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } - - if(args.length == 0) - { - sender.sendMessage("/iris selection shift "); - return true; - } - - int amt = Integer.valueOf(args[0]); - Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); - a1.add(d.toVector().multiply(amt)); - a2.add(d.toVector().multiply(amt)); - Cuboid cursor = new Cuboid(a1, a2); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEMFRAME_ROTATE_ITEM, 1f, 0.55f); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandSelectionShrink.java b/src/main/java/ninja/bytecode/iris/command/CommandSelectionShrink.java deleted file mode 100644 index 762939d4c..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandSelectionShrink.java +++ /dev/null @@ -1,57 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Location; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.controller.WandController; -import ninja.bytecode.iris.util.Cuboid; -import ninja.bytecode.iris.util.Cuboid.CuboidDirection; - -public class CommandSelectionShrink extends MortarCommand -{ - public CommandSelectionShrink() - { - super("shrinkwrap", "shrink"); - setDescription("Match blocks boundary"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Players Only"); - return true; - } - - Player p = sender.player(); - - if(!WandController.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } - - Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); - cursor = cursor.contract(CuboidDirection.North); - cursor = cursor.contract(CuboidDirection.South); - cursor = cursor.contract(CuboidDirection.East); - cursor = cursor.contract(CuboidDirection.West); - cursor = cursor.contract(CuboidDirection.Up); - cursor = cursor.contract(CuboidDirection.Down); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEMFRAME_ROTATE_ITEM, 1f, 0.55f); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandSelectionXUp.java b/src/main/java/ninja/bytecode/iris/command/CommandSelectionXUp.java deleted file mode 100644 index 62d500a69..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandSelectionXUp.java +++ /dev/null @@ -1,72 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.controller.WandController; -import ninja.bytecode.iris.util.Cuboid; -import ninja.bytecode.iris.util.Cuboid.CuboidDirection; - -public class CommandSelectionXUp extends MortarCommand -{ - public CommandSelectionXUp() - { - super("expandup", "xup"); - setDescription("Expand Up & Trim In"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Players Only"); - return true; - } - - Player p = sender.player(); - - if(!WandController.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } - - Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); - 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(CuboidDirection.North); - cursor = cursor.contract(CuboidDirection.South); - cursor = cursor.contract(CuboidDirection.East); - cursor = cursor.contract(CuboidDirection.West); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEMFRAME_ROTATE_ITEM, 1f, 0.55f); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandSelectionXVert.java b/src/main/java/ninja/bytecode/iris/command/CommandSelectionXVert.java deleted file mode 100644 index 9d97047b9..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandSelectionXVert.java +++ /dev/null @@ -1,83 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import ninja.bytecode.iris.controller.WandController; -import ninja.bytecode.iris.util.Cuboid; -import ninja.bytecode.iris.util.Cuboid.CuboidDirection; - -public class CommandSelectionXVert extends MortarCommand -{ - public CommandSelectionXVert() - { - super("expandvertical", "xvert"); - setDescription("Expand Up + Down & Trim In"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Players Only"); - return true; - } - - Player p = sender.player(); - - if(!WandController.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } - - Location[] b = WandController.getCuboid(p.getInventory().getItemInMainHand()); - 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 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)); - - while(!cursorx.containsOnly(Material.AIR)) - { - a1x.add(new Vector(0, -1, 0)); - a2x.add(new Vector(0, -1, 0)); - cursorx = new Cuboid(a1x, a2x); - } - - a1x.add(new 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(CuboidDirection.North); - cursor = cursor.contract(CuboidDirection.South); - cursor = cursor.contract(CuboidDirection.East); - cursor = cursor.contract(CuboidDirection.West); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandController.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEMFRAME_ROTATE_ITEM, 1f, 0.55f); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandTimings.java b/src/main/java/ninja/bytecode/iris/command/CommandTimings.java deleted file mode 100644 index 901cdded0..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandTimings.java +++ /dev/null @@ -1,57 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Bukkit; -import org.bukkit.World; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.IrisGenerator; - -public class CommandTimings extends MortarCommand -{ - public CommandTimings() - { - super("timings", "t"); - setDescription("Tick use on a per chunk basis"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - World world = null; - - if(sender.isPlayer() && Iris.isGen(sender.player().getWorld())) - { - world = sender.player().getWorld(); - } - - else if(args.length >= 1) - { - World t = Bukkit.getWorld(args[0]); - - if(t == null) - { - sender.sendMessage("Unknown world " + args[0]); - return true; - } - - else if(t.getGenerator() instanceof IrisGenerator) - { - world = t; - } - } - - else - { - sender.sendMessage("Console / Non-Iris World. " + C.WHITE + "Use /iris timings "); - return true; - } - - Iris.getGen(world).getMetrics().send(sender, (m) -> sender.sendMessage(m)); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandWhat.java b/src/main/java/ninja/bytecode/iris/command/CommandWhat.java deleted file mode 100644 index a6ff4f350..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandWhat.java +++ /dev/null @@ -1,36 +0,0 @@ -package ninja.bytecode.iris.command; - -import mortar.bukkit.command.Command; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; - -public class CommandWhat extends MortarCommand -{ - @Command - private CommandWhatBiome wBiome; - - @Command - private CommandWhatObject wObject; - - @Command - private CommandWhatBlock wBlock; - - public CommandWhat() - { - super("what", "w"); - setDescription("Identify what you are looking at."); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - for(MortarCommand i : getChildren()) - { - sender.sendMessage("/iris what " + C.WHITE + i.getNode() + C.GRAY + (!i.getNodes().isEmpty() ? "," : "") + i.getNodes().toString(",") + " - " + C.DARK_GREEN + i.getDescription()); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandWhatBiome.java b/src/main/java/ninja/bytecode/iris/command/CommandWhatBiome.java deleted file mode 100644 index c40c71e19..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandWhatBiome.java +++ /dev/null @@ -1,66 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.World; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.iris.util.BiomeLayer; -import ninja.bytecode.shuriken.format.Form; - -public class CommandWhatBiome extends MortarCommand -{ - public CommandWhatBiome() - { - super("biome", "b"); - setDescription("Identify Current Biome"); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - World world = null; - - if(sender.isPlayer() && Iris.isGen(sender.player().getWorld())) - { - world = sender.player().getWorld(); - } - - else - { - sender.sendMessage("Console / Non-Iris World."); - return true; - } - - Player p = sender.player(); - IrisGenerator g = Iris.getGen(world); - IrisBiome biome = g.getBiome((int) g.getOffsetX(p.getLocation().getX(), p.getLocation().getZ()), (int) g.getOffsetZ(p.getLocation().getX(), p.getLocation().getZ())); - BiomeLayer l = new BiomeLayer(g, biome); - sender.sendMessage("Biome: " + C.BOLD + C.WHITE + biome.getName() + C.RESET + C.GRAY + " (" + C.GOLD + l.getBiome().getRarityString() + C.GRAY + ")"); - - for(String i : biome.getSchematicGroups().k()) - { - String f = ""; - double percent = biome.getSchematicGroups().get(i); - - if(percent > 1D) - { - f = (int) percent + " + " + Form.pc(percent - (int) percent, percent - (int) percent >= 0.01 ? 0 : 3); - } - - else - { - f = Form.pc(percent, percent >= 0.01 ? 0 : 3); - } - - sender.sendMessage("* " + C.DARK_GREEN + i + ": " + C.BOLD + C.WHITE + f + C.RESET + C.GRAY + " (" + Form.f(g.getDimension().getObjectGroup(i).size()) + " variants)"); - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandWhatBlock.java b/src/main/java/ninja/bytecode/iris/command/CommandWhatBlock.java deleted file mode 100644 index 28bba5856..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandWhatBlock.java +++ /dev/null @@ -1,33 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; - -public class CommandWhatBlock extends MortarCommand -{ - public CommandWhatBlock() - { - super("block", "id", "i"); - setDescription("Identify Current Block Looking at"); - } - - @SuppressWarnings("deprecation") - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!sender.isPlayer()) - { - sender.sendMessage("Not sure where you are looking."); - } - - Player p = sender.player(); - Block b = p.getTargetBlock(null, 64); - sender.sendMessage(b.getType().getId() + ":" + b.getData() + " (" + b.getType().toString() + ":" + b.getData() + ")"); - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/command/CommandWhatObject.java b/src/main/java/ninja/bytecode/iris/command/CommandWhatObject.java deleted file mode 100644 index d847c6658..000000000 --- a/src/main/java/ninja/bytecode/iris/command/CommandWhatObject.java +++ /dev/null @@ -1,165 +0,0 @@ -package ninja.bytecode.iris.command; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import mortar.api.sched.SR; -import mortar.bukkit.command.MortarCommand; -import mortar.bukkit.command.MortarSender; -import mortar.lang.collection.FinalInteger; -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.genobject.GenObject; -import ninja.bytecode.iris.generator.genobject.GenObjectGroup; -import ninja.bytecode.iris.generator.genobject.PlacedObject; -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.format.Form; - -public class CommandWhatObject extends MortarCommand -{ - private KMap goc; - private KMap gog; - - public CommandWhatObject() - { - super("object", "o"); - setDescription("WAYLA For Objects"); - goc = new KMap<>(); - gog = new KMap<>(); - } - - @Override - public boolean handle(MortarSender sender, String[] args) - { - World world = null; - - if(sender.isPlayer() && Iris.isGen(sender.player().getWorld())) - { - world = sender.player().getWorld(); - } - - else - { - sender.sendMessage("Console / Non-Iris World."); - return true; - } - - Player p = sender.player(); - IrisGenerator generator = Iris.getGen(world); - Location l = p.getTargetBlock(null, 32).getLocation(); - PlacedObject po = generator.nearest(l, 12); - - if(po != null) - { - if(!goc.containsKey(po.getF())) - { - String root = po.getF().split("\\Q:\\E")[0]; - String n = po.getF().split("\\Q:\\E")[1]; - GenObjectGroup gg = generator.getDimension().getObjectGroup(root); - gog.put(root, gg); - - for(GenObject i : gg.getSchematics()) - { - if(i.getName().equals(n)) - { - goc.put(po.getF(), i); - break; - } - } - - if(!goc.containsKey(po.getF())) - { - goc.put(po.getF(), new GenObject(0, 0, 0)); - } - } - - GenObjectGroup ggg = gog.get(po.getF().split("\\Q:\\E")[0]); - GenObject g = goc.get(po.getF()); - - if(g != null) - { - Location point = new Location(l.getWorld(), po.getX(), po.getY(), po.getZ()); - IrisBiome biome = generator.getBiome((int) generator.getOffsetX(po.getX(), po.getZ()), (int) generator.getOffsetZ(po.getX(), po.getZ())); - String gg = po.getF().split("\\Q:\\E")[0]; - - p.sendMessage(C.DARK_GREEN + C.BOLD.toString() + gg + C.GRAY + "/" + C.RESET + C.ITALIC + C.GRAY + g.getName() + C.RESET + C.WHITE + " (1 of " + Form.f(generator.getDimension().getObjectGroup(gg).size()) + " variants)"); - - if(biome.getSchematicGroups().containsKey(gg)) - { - String f = ""; - double percent = biome.getSchematicGroups().get(gg); - - if(percent > 1D) - { - f = (int) percent + " + " + Form.pc(percent - (int) percent, percent - (int) percent >= 0.01 ? 0 : 3); - } - - else - { - f = Form.pc(percent, percent >= 0.01 ? 0 : 3); - } - - p.sendMessage(C.GOLD + "Spawn Chance in " + C.YELLOW + biome.getName() + C.RESET + ": " + C.BOLD + C.WHITE + f); - } - - try - { - int a = 0; - int b = 0; - double c = 0; - - for(GenObject i : ggg.getSchematics()) - { - a += i.getSuccesses(); - b += i.getPlaces(); - } - - c = ((double) a / (double) b); - p.sendMessage(C.GRAY + "Grp: " + C.DARK_AQUA + Form.f(a) + C.GRAY + " of " + C.AQUA + Form.f(b) + C.GRAY + " placements (" + C.DARK_AQUA + Form.pc(c, 0) + C.GRAY + ")"); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - - p.sendMessage(C.GRAY + "Var: " + C.DARK_AQUA + Form.f(g.getSuccesses()) + C.GRAY + " of " + C.AQUA + Form.f(g.getPlaces()) + C.GRAY + " placements (" + C.DARK_AQUA + Form.pc(g.getSuccess(), 0) + C.GRAY + ")"); - - for(String i : ggg.getFlags()) - { - p.sendMessage(C.GRAY + "- " + C.DARK_PURPLE + i); - } - - FinalInteger fi = new FinalInteger(125); - - new SR() - { - @Override - public void run() - { - if(point.distanceSquared(p.getLocation()) > 64 * 64) - { - cancel(); - } - - fi.sub(1); - Iris.wand().draw(new Location[] {point.clone().add(g.getW() / 2, g.getH() / 2, g.getD() / 2), point.clone().subtract(g.getW() / 2, g.getH() / 2, g.getD() / 2) - }, p); - - if(fi.get() <= 0) - { - cancel(); - } - } - }; - - } - } - - return true; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/controller/ExecutionController.java b/src/main/java/ninja/bytecode/iris/controller/ExecutionController.java deleted file mode 100644 index da8e95f33..000000000 --- a/src/main/java/ninja/bytecode/iris/controller/ExecutionController.java +++ /dev/null @@ -1,64 +0,0 @@ -package ninja.bytecode.iris.controller; - -import org.bukkit.World; - -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.execution.TaskExecutor; - -public class ExecutionController -{ - KMap executors; - - public void start() - { - executors = new KMap<>(); - } - - public void stop() - { - for(TaskExecutor i : executors.v()) - { - i.close(); - } - - executors.clear(); - } - - public TaskExecutor getExecutor(World world, String f) - { - String k = world.getWorldFolder().getAbsolutePath() + " (" + world + ") " + f; - - if(executors.containsKey(k)) - { - return executors.get(k); - } - - TaskExecutor x = new TaskExecutor(getTC(), Iris.settings.performance.threadPriority, "Iris " + f); - executors.put(k, x); - return x; - } - - public int getTC() - { - switch(Iris.settings.performance.performanceMode) - { - case HALF_CPU: - return Math.max(Runtime.getRuntime().availableProcessors() / 2, 1); - case MATCH_CPU: - return Runtime.getRuntime().availableProcessors(); - case SINGLE_THREADED: - return 1; - case DOUBLE_CPU: - return Runtime.getRuntime().availableProcessors() * 2; - case UNLIMITED: - return -1; - case EXPLICIT: - return Iris.settings.performance.threadCount; - default: - break; - } - - return Math.max(Runtime.getRuntime().availableProcessors() / 2, 1); - } -} diff --git a/src/main/java/ninja/bytecode/iris/controller/PackController.java b/src/main/java/ninja/bytecode/iris/controller/PackController.java deleted file mode 100644 index 68401f1bb..000000000 --- a/src/main/java/ninja/bytecode/iris/controller/PackController.java +++ /dev/null @@ -1,358 +0,0 @@ -package ninja.bytecode.iris.controller; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import mortar.bukkit.plugin.Controller; -import net.md_5.bungee.api.ChatColor; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.genobject.GenObject; -import ninja.bytecode.iris.generator.genobject.GenObjectGroup; -import ninja.bytecode.iris.pack.CompiledDimension; -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.iris.pack.IrisDimension; -import ninja.bytecode.iris.pack.IrisPack; -import ninja.bytecode.shuriken.bench.PrecisionStopwatch; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.execution.J; -import ninja.bytecode.shuriken.format.Form; -import ninja.bytecode.shuriken.io.IO; -import ninja.bytecode.shuriken.json.JSONException; -import ninja.bytecode.shuriken.json.JSONObject; -import ninja.bytecode.shuriken.logging.L; - -public class PackController extends Controller -{ - private KMap compiledDimensions; - private KMap dimensions; - private KMap biomes; - private KMap genObjectGroups; - private boolean ready; - - @Override - public void start() - { - compiledDimensions = new KMap<>(); - dimensions = new KMap<>(); - biomes = new KMap<>(); - genObjectGroups = new KMap<>(); - ready = false; - } - - @Override - public void stop() - { - - } - - @Override - public void tick() - { - - } - - public boolean isReady() - { - return ready; - } - - public KList getFiles(File folder) - { - KList buf = new KList(); - - if(!folder.exists()) - { - return buf; - } - - if(folder.isDirectory()) - { - for(File i : folder.listFiles()) - { - if(i.isFile()) - { - buf.add(i); - } - - else if(i.isDirectory()) - { - buf.addAll(getFiles(folder)); - } - } - } - - return buf; - } - - public void compile() - { - dimensions = new KMap<>(); - biomes = new KMap<>(); - genObjectGroups = new KMap<>(); - ready = false; - PrecisionStopwatch p = PrecisionStopwatch.start(); - File dims = new File(Iris.instance.getDataFolder(), "dimensions"); - dims.mkdirs(); - - try - { - IrisPack master = new IrisPack(loadJSON("pack/manifest.json")); - master.load(); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - - L.v(ChatColor.LIGHT_PURPLE + "Processing Content"); - - for(GenObjectGroup i : genObjectGroups.v()) - { - i.processVariants(); - } - - for(String i : dimensions.k()) - { - IrisDimension id = dimensions.get(i); - CompiledDimension d = new CompiledDimension(id); - - for(IrisBiome j : id.getBiomes()) - { - d.registerBiome(j); - KList g = j.getSchematicGroups().k(); - g.sort(); - - for(String k : g) - { - d.registerObject(genObjectGroups.get(k)); - - if(j.isLush()) - { - try - { - GenObjectGroup ggx = genObjectGroups.get(k).copy("-lush-" + j.getLush()); - ggx.applyLushFilter(j.getLush()); - d.registerObject(ggx); - j.getSchematicGroups().put(ggx.getName(), j.getSchematicGroups().get(k)); - j.getSchematicGroups().remove(k); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - if(j.isSnowy()) - { - try - { - GenObjectGroup ggx = genObjectGroups.get(k).copy("-snow-" + j.getSnow()); - ggx.applySnowFilter((int) (j.getSnow() * 4)); - d.registerObject(ggx); - j.getSchematicGroups().put(ggx.getName(), j.getSchematicGroups().get(k)); - j.getSchematicGroups().remove(k); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - } - } - - d.sort(); - compiledDimensions.put(i, d); - } - - for(String i : compiledDimensions.k()) - { - CompiledDimension d = compiledDimensions.get(i); - d.computeObjectSize(); - L.i(ChatColor.GREEN + i + ChatColor.WHITE + " (" + d.getEnvironment().toString().toLowerCase() + ")"); - L.i(ChatColor.DARK_GREEN + " Biomes: " + ChatColor.GRAY + Form.f(d.getBiomes().size())); - L.i(ChatColor.DARK_GREEN + " Objects: " + ChatColor.GRAY + Form.f(d.countObjects())); - L.flush(); - } - - L.i(""); - L.i(ChatColor.LIGHT_PURPLE + "Compilation Time: " + ChatColor.WHITE + Form.duration(p.getMilliseconds(), 2)); - L.i(ChatColor.GREEN + "Iris Dimensions Successfully Compiled!"); - L.i(""); - L.flush(); - - ready = true; - } - - public KMap getCompiledDimensions() - { - return compiledDimensions; - } - - public KMap getDimensions() - { - return dimensions; - } - - public KMap getBiomes() - { - return biomes; - } - - public KMap getGenObjectGroups() - { - return genObjectGroups; - } - - public CompiledDimension getDimension(String name) - { - return compiledDimensions.get(name); - } - - public IrisDimension loadDimension(String s) throws JSONException, IOException - { - L.v(ChatColor.GOLD + "Loading Dimension: " + ChatColor.GRAY + "pack/dimensions/" + s + ".json"); - return new IrisDimension(loadJSON("pack/dimensions/" + s + ".json")); - } - - public IrisBiome loadBiome(String s) throws JSONException, IOException - { - L.v(ChatColor.DARK_GREEN + "Loading Biome: " + ChatColor.GRAY + "pack/biomes/" + s + ".json"); - return new IrisBiome(loadJSON("pack/biomes/" + s + ".json")); - } - - public GenObjectGroup loadSchematicGroup(String s) - { - GenObjectGroup g = GenObjectGroup.load("pack/objects/" + s); - L.v(ChatColor.DARK_AQUA + "Loading Objects: " + ChatColor.GRAY + "pack/objects/" + s + ".ish"); - - if(g != null) - { - genObjectGroups.put(s, g); - return g; - } - - L.i("Cannot load Object Group: " + s); - - return null; - } - - public GenObject loadSchematic(String s) throws IOException - { - return GenObject.load(loadResource("pack/objects/" + s + ".ish")); - } - - public JSONObject loadJSON(String s) throws JSONException, IOException - { - return new JSONObject(IO.readAll(loadResource(s))); - } - - public File loadFolder(String string) - { - File internal = internalResource(string); - - if(internal.exists()) - { - return internal; - } - - L.f(ChatColor.RED + "Cannot find folder: " + internal.getAbsolutePath()); - return null; - } - - public InputStream loadResource(String string) throws IOException - { - File internal = internalResource(string); - - if(internal.exists()) - { - L.flush(); - return new FileInputStream(internal); - } - - else - { - L.f(ChatColor.RED + "Cannot find Resource: " + ChatColor.YELLOW + internal.getAbsolutePath()); - - if(internal.getName().equals("manifest.json")) - { - L.f(ChatColor.RED + "Reloading Iris to fix manifest jar issues"); - Iris.instance.reload(); - } - - return null; - } - } - - private static File internalResource(String resource) - { - if(new File(Iris.instance.getDataFolder(), "pack").exists()) - { - return new File(Iris.instance.getDataFolder(), resource); - } - - return new File(System.getProperty("java.io.tmpdir") + "/Iris/" + resource); - } - - public void registerBiome(String name, IrisBiome biome) - { - biomes.put(name, biome); - } - - public void registerDimension(String i, IrisDimension d) - { - dimensions.put(i, d); - } - - public void invalidate() - { - J.attempt(() -> new File(Iris.instance.getDataFolder(), "dimensions").delete()); - compiledDimensions.clear(); - } - - public IrisBiome getBiomeById(String id) - { - if(!biomes.containsKey(id)) - { - try - { - biomes.put(id, ((PackController) Iris.instance.getController(PackController.class)).loadBiome(id)); - } - - catch(JSONException | IOException e) - { - e.printStackTrace(); - } - } - - return biomes.get(id); - } - - public void dispose() - { - for(GenObjectGroup i : genObjectGroups.values()) - { - i.dispose(); - } - - for(IrisDimension i : dimensions.values()) - { - i.dispose(); - } - - for(CompiledDimension i : compiledDimensions.values()) - { - i.dispose(); - } - - compiledDimensions.clear(); - dimensions.clear(); - biomes.clear(); - genObjectGroups.clear(); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/BiomeChunkGenerator.java b/src/main/java/ninja/bytecode/iris/generator/BiomeChunkGenerator.java new file mode 100644 index 000000000..820b6d5c2 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/generator/BiomeChunkGenerator.java @@ -0,0 +1,204 @@ +package ninja.bytecode.iris.generator; + +import java.util.concurrent.locks.ReentrantLock; + +import org.bukkit.World; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.layer.GenLayerBiome; +import ninja.bytecode.iris.object.InferredType; +import ninja.bytecode.iris.object.IrisBiome; +import ninja.bytecode.iris.object.IrisBiomeGeneratorLink; +import ninja.bytecode.iris.object.IrisGenerator; +import ninja.bytecode.iris.object.IrisRegion; +import ninja.bytecode.iris.util.BiomeResult; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.ChronoLatch; +import ninja.bytecode.iris.util.ChunkPosition; +import ninja.bytecode.iris.util.IrisInterpolation; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.collections.KMap; +import ninja.bytecode.shuriken.math.M; + +@Data +@EqualsAndHashCode(callSuper = false) +public abstract class BiomeChunkGenerator extends DimensionChunkGenerator +{ + protected ReentrantLock regLock; + protected KMap generators; + protected GenLayerBiome glBiome; + protected CNG masterFracture; + protected KMap biomeHitCache; + protected ChronoLatch cwarn = new ChronoLatch(1000); + + public BiomeChunkGenerator(String dimensionName) + { + super(dimensionName); + generators = new KMap<>(); + regLock = new ReentrantLock(); + biomeHitCache = new KMap<>(); + } + + public void onInit(World world, RNG rng) + { + loadGenerators(); + glBiome = new GenLayerBiome(this, masterRandom.nextParallelRNG(1)); + masterFracture = CNG.signature(rng.nextParallelRNG(13)).scale(0.12); + } + + public void onHotloaded() + { + biomeHitCache = new KMap<>(); + generators.clear(); + loadGenerators(); + } + + public void registerGenerator(IrisGenerator g) + { + regLock.lock(); + if(g.getLoadKey() == null || generators.containsKey(g.getLoadKey())) + { + regLock.unlock(); + return; + } + + regLock.unlock(); + generators.put(g.getLoadKey(), g); + } + + protected double getBiomeHeight(double rx, double rz) + { + double h = 0; + + for(IrisGenerator i : generators.values()) + { + h += interpolateGenerator(rx, rz, i); + } + + return h; + } + + protected double interpolateGenerator(double rx, double rz, IrisGenerator gen) + { + double hi = IrisInterpolation.getNoise(gen.getInterpolationFunction(), (int) Math.round(rx), (int) Math.round(rz), gen.getInterpolationScale(), (xx, zz) -> + { + IrisBiome b = sampleBiome((int) xx, (int) zz).getBiome(); + + for(IrisBiomeGeneratorLink i : b.getGenerators()) + { + if(i.getGenerator().equals(gen.getLoadKey())) + { + return i.getMax(); + } + } + + return 0; + }); + + double lo = IrisInterpolation.getNoise(gen.getInterpolationFunction(), (int) Math.round(rx), (int) Math.round(rz), gen.getInterpolationScale(), (xx, zz) -> + { + IrisBiome b = sampleBiome((int) xx, (int) zz).getBiome(); + + for(IrisBiomeGeneratorLink i : b.getGenerators()) + { + if(i.getGenerator().equals(gen.getLoadKey())) + { + return i.getMin(); + } + } + + return 0; + }); + + return M.lerp(lo, hi, gen.getHeight(rx, rz, world.getSeed() + 239945)); + } + + protected void loadGenerators() + { + KList touch = new KList<>(); + KList loadQueue = new KList<>(); + + for(String i : getDimension().getRegions()) + { + IrisRegion r = Iris.data.getRegionLoader().load(i); + + if(r != null) + { + loadQueue.addAll(r.getLandBiomes()); + loadQueue.addAll(r.getSeaBiomes()); + loadQueue.addAll(r.getShoreBiomes()); + } + } + + while(!loadQueue.isEmpty()) + { + String next = loadQueue.pop(); + + if(!touch.contains(next)) + { + touch.add(next); + IrisBiome biome = Iris.data.getBiomeLoader().load(next); + biome.getGenerators().forEach((i) -> registerGenerator(i.getCachedGenerator())); + loadQueue.addAll(biome.getChildren()); + } + } + } + + public IrisRegion sampleRegion(int x, int z) + { + double wx = getModifiedX(x, z); + double wz = getModifiedZ(x, z); + return glBiome.getRegion(wx, wz); + } + + public BiomeResult sampleBiome(int x, int z) + { + if(!getDimension().getFocus().equals("")) + { + IrisBiome biome = Iris.data.getBiomeLoader().load(getDimension().getFocus()); + + for(String i : getDimension().getRegions()) + { + IrisRegion reg = Iris.data.getRegionLoader().load(i); + + if(reg.getLandBiomes().contains(biome.getLoadKey())) + { + biome.setInferredType(InferredType.LAND); + break; + } + + if(reg.getSeaBiomes().contains(biome.getLoadKey())) + { + biome.setInferredType(InferredType.SEA); + break; + } + + if(reg.getShoreBiomes().contains(biome.getLoadKey())) + { + biome.setInferredType(InferredType.SHORE); + break; + } + } + + return new BiomeResult(biome, 0); + } + + ChunkPosition pos = new ChunkPosition(x, z); + + if(biomeHitCache.containsKey(pos)) + { + return biomeHitCache.get(pos); + } + + double wx = getModifiedX(x, z); + double wz = getModifiedZ(x, z); + IrisRegion region = glBiome.getRegion(wx, wz); + BiomeResult res = glBiome.generateRegionData(wx, wz, x, z, region); + biomeHitCache.put(pos, res); + + return res; + } +} diff --git a/src/main/java/ninja/bytecode/iris/generator/ContextualChunkGenerator.java b/src/main/java/ninja/bytecode/iris/generator/ContextualChunkGenerator.java new file mode 100644 index 000000000..7bdc889f9 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/generator/ContextualChunkGenerator.java @@ -0,0 +1,302 @@ +package ninja.bytecode.iris.generator; + +import java.util.List; +import java.util.Random; + +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.ChunkUnloadEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import net.md_5.bungee.api.ChatColor; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.IrisContext; +import ninja.bytecode.iris.IrisMetrics; +import ninja.bytecode.iris.util.BlockDataTools; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.ChronoLatch; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.bench.PrecisionStopwatch; +import ninja.bytecode.shuriken.logging.L; + +@Data +@EqualsAndHashCode(callSuper = false) +public abstract class ContextualChunkGenerator extends ChunkGenerator implements Listener +{ + protected boolean failing; + protected int task; + protected boolean initialized; + protected RNG masterRandom; + protected ChronoLatch perSecond; + protected ChronoLatch pushLatch; + protected IrisMetrics metrics; + protected World world; + protected int generated; + protected int ticks; + protected boolean pregenDone; + + public ContextualChunkGenerator() + { + pushLatch = new ChronoLatch(3000); + perSecond = new ChronoLatch(1000); + CNG.creates = 0; + generated = 0; + ticks = 0; + task = -1; + initialized = false; + failing = false; + pregenDone = false; + } + + protected abstract void onGenerate(RNG masterRandom, int x, int z, ChunkData data, BiomeGrid grid); + + protected abstract void onInit(World world, RNG masterRandom); + + protected abstract void onTick(int ticks); + + protected abstract void onClose(); + + protected abstract void onFailure(Throwable e); + + protected abstract void onChunkLoaded(Chunk c); + + protected abstract void onChunkUnloaded(Chunk c); + + protected abstract void onPlayerJoin(Player p); + + protected abstract void onPlayerLeft(Player p); + + private void init(World world, RNG rng) + { + if(initialized) + { + return; + } + + this.world = world; + this.masterRandom = new RNG(world.getSeed()); + metrics = new IrisMetrics(128); + initialized = true; + Bukkit.getServer().getPluginManager().registerEvents(this, Iris.instance); + task = Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, this::tick, 0, 0); + onInit(world, masterRandom); + } + + private void tick() + { + if(perSecond.flip()) + { + if(generated > 770) + { + pregenDone = true; + } + + if(pregenDone) + { + metrics.getPerSecond().put(generated); + generated = 0; + } + } + + onTick(ticks++); + } + + @EventHandler + public void on(PlayerTeleportEvent e) + { + if(e.getFrom().getWorld().equals(world) && !e.getTo().getWorld().equals(world)) + { + onPlayerLeft(e.getPlayer()); + } + + if(!e.getFrom().getWorld().equals(world) && e.getTo().getWorld().equals(world)) + { + onPlayerJoin(e.getPlayer()); + } + } + + @EventHandler + public void on(PlayerQuitEvent e) + { + if(e.getPlayer().getWorld().equals(world)) + { + onPlayerLeft(e.getPlayer()); + } + } + + @EventHandler + public void on(PlayerJoinEvent e) + { + if(e.getPlayer().getWorld().equals(world)) + { + onPlayerJoin(e.getPlayer()); + } + } + + @EventHandler + public void on(ChunkLoadEvent e) + { + if(e.getWorld().equals(world)) + { + onChunkLoaded(e.getChunk()); + } + } + + @EventHandler + public void on(ChunkUnloadEvent e) + { + if(e.getWorld().equals(world)) + { + onChunkUnloaded(e.getChunk()); + } + } + + @EventHandler + public void on(WorldUnloadEvent e) + { + if(world != null && e.getWorld().equals(world)) + { + close(); + } + } + + protected void close() + { + HandlerList.unregisterAll(this); + Bukkit.getScheduler().cancelTask(getTask()); + onClose(); + } + + @Override + public boolean canSpawn(World world, int x, int z) + { + return super.canSpawn(world, x, z); + } + + protected ChunkData generateChunkDataFailure(World world, Random no, int x, int z, BiomeGrid biomeGrid) + { + ChunkData c = Bukkit.createChunkData(world); + + for(int i = 0; i < 16; i++) + { + for(int j = 0; j < 16; j++) + { + int h = 0; + + if(j == i || j + i == 16) + { + c.setBlock(i, h, j, BlockDataTools.getBlockData("RED_TERRACOTTA")); + } + + else + { + c.setBlock(i, h, j, BlockDataTools.getBlockData("BLACK_TERRACOTTA")); + } + } + } + + return c; + } + + @Override + public ChunkData generateChunkData(World world, Random no, int x, int z, BiomeGrid biomeGrid) + { + PrecisionStopwatch sx = PrecisionStopwatch.start(); + + if(failing) + { + return generateChunkDataFailure(world, no, x, z, biomeGrid); + } + + try + { + if(pushLatch.flip()) + { + if(this.world == null) + { + this.world = world; + } + + Iris.hotloader.check((IrisContext) this); + + if(this instanceof IrisContext) + { + IrisContext.pushContext((IrisContext) this); + } + } + + PrecisionStopwatch s = PrecisionStopwatch.start(); + RNG random = new RNG(world.getSeed()); + init(world, random.nextParallelRNG(0)); + ChunkData c = Bukkit.createChunkData(world); + onGenerate(random, x, z, c, biomeGrid); + metrics.getTotal().put(s.getMilliseconds()); + generated++; + long hits = CNG.hits; + CNG.hits = 0; + Iris.instance.hit(hits); + metrics.getLoss().put(sx.getMilliseconds() - s.getMilliseconds()); + return c; + } + + catch(Throwable e) + { + fail(e); + } + + return generateChunkDataFailure(world, no, x, z, biomeGrid); + } + + public void onHotloaded() + { + + } + + protected void fail(Throwable e) + { + failing = true; + Iris.error("ERROR! Failed to generate chunk! Iris has entered a failed state!"); + + for(Player i : world.getPlayers()) + { + Iris.instance.imsg(i, ChatColor.DARK_RED + "Iris Generator has entered a failed state!"); + Iris.instance.imsg(i, ChatColor.RED + "- Check the console for the error."); + Iris.instance.imsg(i, ChatColor.RED + "- Then simply run /iris dev"); + } + + L.ex(e); + onFailure(e); + } + + @Override + public List getDefaultPopulators(World world) + { + return super.getDefaultPopulators(world); + } + + @Override + public Location getFixedSpawnLocation(World world, Random random) + { + return super.getFixedSpawnLocation(world, random); + } + + @Override + public boolean isParallelCapable() + { + return true; + } +} diff --git a/src/main/java/ninja/bytecode/iris/generator/DimensionChunkGenerator.java b/src/main/java/ninja/bytecode/iris/generator/DimensionChunkGenerator.java new file mode 100644 index 000000000..7dbb4c4c7 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/generator/DimensionChunkGenerator.java @@ -0,0 +1,89 @@ +package ninja.bytecode.iris.generator; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.object.InferredType; +import ninja.bytecode.iris.object.IrisBiome; +import ninja.bytecode.iris.object.IrisDimension; +import ninja.bytecode.iris.object.IrisRegion; +import ninja.bytecode.iris.util.BiomeResult; + +@Data +@EqualsAndHashCode(callSuper = false) +public abstract class DimensionChunkGenerator extends ContextualChunkGenerator +{ + protected final String dimensionName; + + public DimensionChunkGenerator(String dimensionName) + { + super(); + this.dimensionName = dimensionName; + } + + public IrisDimension getDimension() + { + IrisDimension d = Iris.data.getDimensionLoader().load(dimensionName); + + if(d == null) + { + Iris.error("Can't find dimension: " + dimensionName); + } + + return d; + } + + protected BiomeResult focus() + { + IrisBiome biome = Iris.data.getBiomeLoader().load(getDimension().getFocus()); + + for(String i : getDimension().getRegions()) + { + IrisRegion reg = Iris.data.getRegionLoader().load(i); + + if(reg.getLandBiomes().contains(biome.getLoadKey())) + { + biome.setInferredType(InferredType.LAND); + break; + } + + if(reg.getSeaBiomes().contains(biome.getLoadKey())) + { + biome.setInferredType(InferredType.SEA); + break; + } + + if(reg.getShoreBiomes().contains(biome.getLoadKey())) + { + biome.setInferredType(InferredType.SHORE); + break; + } + } + + return new BiomeResult(biome, 0); + } + + public double getModifiedX(int rx, int rz) + { + return (getDimension().cosRotate() * rx) + (-getDimension().sinRotate() * rz) + + + getDimension().getCoordFracture(masterRandom, 39392).fitDoubleD(-getDimension().getCoordFractureDistance() / 2, getDimension().getCoordFractureDistance() / 2, rx, rz); + } + + public double getModifiedZ(int rx, int rz) + { + return (getDimension().sinRotate() * rx) + (getDimension().cosRotate() * rz) + + + getDimension().getCoordFracture(masterRandom, 39392).fitDoubleD(-getDimension().getCoordFractureDistance() / 2, getDimension().getCoordFractureDistance() / 2, rx, rz); + } + + public double getZoomed(double modified) + { + return (double) (modified) / getDimension().getTerrainZoom(); + } + + public double getUnzoomed(double modified) + { + return (double) (modified) * getDimension().getTerrainZoom(); + } +} diff --git a/src/main/java/ninja/bytecode/iris/generator/IrisChunkGenerator.java b/src/main/java/ninja/bytecode/iris/generator/IrisChunkGenerator.java new file mode 100644 index 000000000..46150f10a --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/generator/IrisChunkGenerator.java @@ -0,0 +1,86 @@ +package ninja.bytecode.iris.generator; + +import java.lang.reflect.Method; + +import org.bukkit.Chunk; +import org.bukkit.entity.Player; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.IrisContext; +import ninja.bytecode.iris.object.IrisRegion; +import ninja.bytecode.iris.util.BiomeResult; + +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisChunkGenerator extends ParallaxChunkGenerator implements IrisContext +{ + private Method initLighting; + + public IrisChunkGenerator(String dimensionName, int threads) + { + super(dimensionName, threads); + } + + @Override + public BiomeResult getBiome(int x, int z) + { + return sampleBiome(x, z); + } + + @Override + public IrisRegion getRegion(int x, int z) + { + return sampleRegion(x, z); + } + + @Override + public int getHeight(int x, int z) + { + return sampleHeight(x, z); + } + + @Override + protected void onTick(int ticks) + { + + } + + @Override + protected void onClose() + { + super.onClose(); + Iris.info("Closing Iris Dimension " + getWorld().getName()); + } + + @Override + protected void onFailure(Throwable e) + { + + } + + @Override + protected void onChunkLoaded(Chunk c) + { + // TODO: updateLights(); better + } + + @Override + protected void onChunkUnloaded(Chunk c) + { + + } + + @Override + protected void onPlayerJoin(Player p) + { + + } + + @Override + protected void onPlayerLeft(Player p) + { + + } +} diff --git a/src/main/java/ninja/bytecode/iris/generator/IrisGenerator.java b/src/main/java/ninja/bytecode/iris/generator/IrisGenerator.java deleted file mode 100644 index 299f89101..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/IrisGenerator.java +++ /dev/null @@ -1,728 +0,0 @@ -package ninja.bytecode.iris.generator; - -import java.util.List; -import java.util.Random; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.TreeSpecies; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.generator.BlockPopulator; -import org.bukkit.material.Leaves; -import org.bukkit.util.NumberConversions; - -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.generator.genobject.GenObjectDecorator; -import ninja.bytecode.iris.generator.genobject.PlacedObject; -import ninja.bytecode.iris.generator.layer.GenLayerBiome; -import ninja.bytecode.iris.generator.layer.GenLayerCarving; -import ninja.bytecode.iris.generator.layer.GenLayerCaves; -import ninja.bytecode.iris.generator.layer.GenLayerCliffs; -import ninja.bytecode.iris.generator.layer.GenLayerLayeredNoise; -import ninja.bytecode.iris.generator.layer.GenLayerOres; -import ninja.bytecode.iris.generator.layer.GenLayerSnow; -import ninja.bytecode.iris.generator.parallax.ParallaxWorldGenerator; -import ninja.bytecode.iris.pack.BiomeType; -import ninja.bytecode.iris.pack.CompiledDimension; -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.iris.pack.IrisRegion; -import ninja.bytecode.iris.util.ChunkPlan; -import ninja.bytecode.iris.util.InterpolationMode; -import ninja.bytecode.iris.util.IrisInterpolation; -import ninja.bytecode.iris.util.IrisMetrics; -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.NoiseProvider; -import ninja.bytecode.iris.util.ObjectMode; -import ninja.bytecode.iris.util.SChunkVector; -import ninja.bytecode.shuriken.bench.PrecisionStopwatch; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.M; -import ninja.bytecode.shuriken.math.RNG; - -public class IrisGenerator extends ParallaxWorldGenerator -{ - //@builder - public static final KList ROCK = new KList().add(new MB[] { - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5) - }); - //@done - private boolean disposed; - private CNG scatter; - private CNG beach; - private CNG swirl; - private MB BEDROCK = new MB(Material.BEDROCK); - private GenObjectDecorator god; - private GenLayerLayeredNoise glLNoise; - private GenLayerBiome glBiome; - private GenLayerSnow glSnow; - private GenLayerCliffs glCliffs; - private GenLayerCaves glCaves; - private GenLayerCarving glCarving; - private GenLayerOres glOres; - private RNG rTerrain; - private CompiledDimension dim; - private IrisMetrics metrics = new IrisMetrics(0, 512); - private int objectHits; - - public IrisGenerator() - { - this(Iris.pack().getDimension("overworld")); - } - - public void hitObject() - { - objectHits++; - } - - public IrisGenerator(CompiledDimension dim) - { - objectHits = 0; - CNG.hits = 0; - CNG.creates = 0; - this.dim = dim; - disposed = false; - L.i("Preparing Dimension: " + dim.getName() + " With " + dim.getBiomes().size() + " Biomes..."); - } - - public int scatterInt(int x, int y, int z, int bound) - { - return (int) (scatter(x, y, z) * (double) (bound - 1)); - } - - public double scatter(int x, int y, int z) - { - return scatter.noise(x, y, z); - } - - public boolean scatterChance(int x, int y, int z, double chance) - { - return scatter(x, y, z) > chance; - } - - @Override - public void onInit(World world, Random random) - { - if(disposed) - { - return; - } - - random = new Random(world.getSeed()); - rTerrain = new RNG(world.getSeed()); - swirl = new CNG(rTerrain.nextParallelRNG(0), 40, 1).scale(0.007); - beach = new CNG(rTerrain.nextParallelRNG(0), 3, 1).scale(0.15); - glLNoise = new GenLayerLayeredNoise(this, world, random, rTerrain.nextParallelRNG(2)); - glBiome = new GenLayerBiome(this, world, random, rTerrain.nextParallelRNG(4), dim.getBiomes()); - glSnow = new GenLayerSnow(this, world, random, rTerrain.nextParallelRNG(5)); - glCliffs = new GenLayerCliffs(this, world, random, rTerrain.nextParallelRNG(9)); - glCaves = new GenLayerCaves(this, world, random, rTerrain.nextParallelRNG(10)); - glCarving = new GenLayerCarving(this, world, random, rTerrain.nextParallelRNG(11)); - glOres = new GenLayerOres(this, world, random, rTerrain.nextParallelRNG(12)); - scatter = new CNG(rTerrain.nextParallelRNG(52), 1, 1).scale(10); - - if(Iris.settings.performance.objectMode.equals(ObjectMode.PARALLAX)) - { - god = new GenObjectDecorator(this); - } - } - - @Override - public ChunkPlan onInitChunk(World world, int x, int z, Random random) - { - return new ChunkPlan(); - } - - public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome) - { - random = new Random(world.getSeed()); - PrecisionStopwatch s = getMetrics().start(); - ChunkData d = super.generateChunkData(world, random, x, z, biome); - getMetrics().stop("chunk:ms", s); - getMetrics().put("noise-hits", CNG.hits); - metrics.setGenerators((int) CNG.creates); - CNG.hits = 0; - return d; - } - - public IrisBiome biome(String name) - { - return getDimension().getBiomeByName(name); - } - - public double getOffsetX(double x, double z) - { - return Math.round((double) x * (Iris.settings.gen.horizontalZoom / 1.90476190476)) + swirl.noise(x, z); - } - - public double getOffsetZ(double x, double z) - { - return Math.round((double) z * (Iris.settings.gen.horizontalZoom / 1.90476190476)) - swirl.noise(z, x); - } - - public IrisMetrics getMetrics() - { - return metrics; - } - - public IrisBiome getBeach(IrisBiome biome) - { - IrisBiome beach = null; - IrisRegion region = glBiome.getRegion(biome.getRegionID()); - - if(region != null) - { - beach = region.getBeach(); - } - - if(beach == null) - { - beach = biome("Beach"); - } - - return beach; - } - - public int computeHeight(int x, int z, ChunkPlan plan, IrisBiome biome) - { - return (int) Math.round(M.clip(getANoise((int) x, (int) z, plan, biome), 0D, 1D) * 253); - } - - public double getInterpolation(int x, int z, double opacity, ChunkPlan plan) - { - PrecisionStopwatch s = getMetrics().start(); - NoiseProvider n = (xf, zf) -> getBiomedHeight((int) Math.round(xf), (int) Math.round(zf), plan); - double d = 0; - double rad = Iris.settings.gen.interpolationRadius; - - InterpolationMode m = Iris.settings.gen.interpolationMode; - - if(m.equals(InterpolationMode.BILINEAR)) - { - d = IrisInterpolation.getBilinearNoise(x, z, rad, n); - } - - else if(m.equals(InterpolationMode.BICUBIC)) - { - d = IrisInterpolation.getBicubicNoise(x, z, rad, n); - } - - else if(m.equals(InterpolationMode.HERMITE_BICUBIC)) - { - d = IrisInterpolation.getHermiteNoise(x, z, rad, n); - } - - else - { - d = n.noise(x, z); - } - - getMetrics().stop("interpolation:ms:x256:/biome:.", s); - - return d; - } - - public double getANoise(int x, int z, ChunkPlan plan, IrisBiome biome) - { - double hv = getInterpolation((int) x, (int) z, 1D, plan); - hv += glLNoise.generateLayer(hv * Iris.settings.gen.roughness * 215, (double) x * Iris.settings.gen.roughness * 0.82, (double) z * Iris.settings.gen.roughness * 0.82) * (1.6918 * (hv * 2.35)); - - if(biome.hasCliffs()) - { - hv = glCliffs.generateLayer(hv, x, z, biome.getCliffScale(), biome.getCliffChance()); - } - - return hv; - } - - public IrisRegion getRegion(IrisBiome biome) - { - return glBiome.getRegion(biome.getRegionID()); - } - - @Override - public List getDefaultPopulators(World world) - { - KList p = new KList<>(); - - if(Iris.settings.performance.objectMode.equals(ObjectMode.QUICK_N_DIRTY) || Iris.settings.performance.objectMode.equals(ObjectMode.LIGHTING)) - { - p.add(god = new GenObjectDecorator(this)); - } - - return p; - } - - @Override - public void onGenParallax(int x, int z, Random random) - { - try - { - PrecisionStopwatch s = getMetrics().start(); - god.populateParallax(x, z, random); - String xx = "x" + getParallaxSize().getX() * getParallaxSize().getZ(); - getMetrics().stop("object:" + xx + ":.:ms:/parallax", s); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - private double getObjectHits() - { - int hits = objectHits; - objectHits = 0; - return hits; - } - - public IrisBiome getBiome(int x, int z) - { - IrisBiome biome = glBiome.getBiome(x, z); - int height = computeHeight((int) x, (int) z, new ChunkPlan(), biome); - biome = getBiome((int) x, height, (int) z); - - return biome; - } - - private IrisBiome getBiome(int x, int y, int z) - { - int seaLevel = Iris.settings.gen.seaLevel; - boolean land = y >= seaLevel; - int beachHeight = land ? 1 + (int) Math.round(seaLevel + beach.noise(x, z) + 1) : seaLevel; - boolean beach = y <= beachHeight && land; - IrisBiome biome = glBiome.getBiome(x, z); - IrisBiome realBiome = glBiome.getBiome(x, z, true); - boolean nearAquatic = glBiome.isNearAquatic(x, z); - IrisRegion region = getRegion(realBiome); - - // Remove Oceans from biomes above sea level - if(land && biome.getType().equals(BiomeType.FLUID)) - { - biome = realBiome; - } - - // Add Beaches & Shores - if(beach && biome.getType().equals(BiomeType.LAND)) - { - biome = nearAquatic ? region.getBeach() : region.getShore(); - } - - // // Replace biomes under sea level with lakes - if(!land && biome.getType().equals(BiomeType.LAND)) - { - biome = region.getLake(); - } - - return biome; - } - - @Override - public Biome onGenColumn(int wxxf, int wzxf, int x, int z, ChunkPlan plan, AtomicChunkData data, boolean surfaceOnly) - { - PrecisionStopwatch s = getMetrics().start(); - if(disposed) - { - data.setBlock(x, 0, z, Material.MAGENTA_GLAZED_TERRACOTTA); - return Biome.VOID; - } - - double wx = getOffsetX(wxxf, wzxf); - double wz = getOffsetZ(wxxf, wzxf); - int wxx = (int) wx; - int wzx = (int) wz; - int highest = 0; - int seaLevel = Iris.settings.gen.seaLevel; - IrisBiome biome = glBiome.getBiome(wxx, wzx); - int height = computeHeight(wxx, wzx, plan, biome); - int max = Math.max(height, seaLevel); - biome = getBiome(wxx, height, wzx); - MB FLUID = biome.getFluid(); - - for(int i = surfaceOnly ? max > seaLevel ? max - 2 : height - 2 : 0; i < max; i++) - { - MB mb = ROCK.get(scatterInt(wzx, i, wxx, ROCK.size())); - boolean carved = surfaceOnly ? false : glCarving.isCarved(wzx, wxx, x, z, i, data, plan); - boolean underwater = i >= height && i < seaLevel; - boolean underground = i < height; - int dheight = biome.getDirtDepth(); - int rheight = biome.getRockDepth(); - boolean dirt = (height - 1) - i < (dheight > 0 ? scatterInt(x, i, z, 4) : 0) + dheight; - boolean rocky = i > height - rheight && !dirt; - boolean bedrock = i == 0 || !Iris.settings.gen.flatBedrock ? i <= 2 : i < scatterInt(x, i, z, 3); - - if(!carved) - { - mb = underwater ? FLUID : mb; - mb = underground && dirt ? biome.getSubSurface(wxx, i, wzx, rTerrain) : mb; - mb = underground && rocky ? biome.getRock(wxx, i, wzx, rTerrain) : mb; - mb = bedrock ? BEDROCK : mb; - - if(i == height - 1) - { - mb = biome.getSurface(wx, wz, rTerrain); - } - - highest = i > highest ? i : highest; - } - - else - { - mb = MB.of(Material.AIR); - } - data.setBlock(x, i, z, mb.material, mb.data); - } - - getMetrics().stop("terrain:ms:x256:/chunk:..", s); - - int hw = 0; - int hl = 0; - - for(int i = highest; i > 0; i--) - { - Material t = data.getType(x, i, z); - hw = i > seaLevel && hw == 0 && (t.equals(Material.WATER) || t.equals(Material.STATIONARY_WATER)) ? i : hw; - hl = hl == 0 && !t.equals(Material.AIR) ? i : hl; - } - - plan.setRealHeight(x, z, hl); - plan.setRealWaterHeight(x, z, hw == 0 ? seaLevel : hw); - plan.setBiome(x, z, biome); - - if(!surfaceOnly) - { - glCaves.genCaves(wxxf, wzxf, x, z, data, plan); - glOres.genOres(wxxf, wzxf, x, z, hl, data, plan); - } - - for(int i = highest; i > 0; i--) - { - Material t = data.getType(x, i, z); - hw = i > seaLevel && hw == 0 && (t.equals(Material.WATER) || t.equals(Material.STATIONARY_WATER)) ? i : hw; - hl = hl == 0 && !t.equals(Material.AIR) ? i : hl; - } - - plan.setRealHeight(x, z, hl); - plan.setRealWaterHeight(x, z, hw == 0 ? seaLevel : hw); - plan.setBiome(x, z, biome); - double time = s.getMilliseconds() * 256D; - double atime = getMetrics().get("chunk:ms").getAverage(); - getMetrics().setParScale(time / atime); - getMetrics().put("objects:,:/parallax", getObjectHits()); - - return biome.getRealBiome(); - } - - @Override - protected void onDecorateChunk(World world, int cx, int cz, AtomicChunkData data, ChunkPlan plan) - { - PrecisionStopwatch p = PrecisionStopwatch.start(); - int x = 0; - int z = 0; - int hhx = 0; - int v = 0; - int borderh = 0; - int above = 0; - int below = 0; - - for(int f = 0; f < Iris.settings.gen.blockSmoothing; f++) - { - for(x = 0; x < 16; x++) - { - for(z = 0; z < 16; z++) - { - hhx = plan.getRealHeight(x, z); - borderh = 0; - - if(x == 0 || x == 15) - { - borderh++; - } - - if(z == 0 || z == 15) - { - borderh++; - } - - if(hhx > Iris.settings.gen.seaLevel - 2) - { - above = 0; - below = 0; - - if(x + 1 <= 15) - { - v = plan.getRealHeight(x + 1, z); - - if(v > hhx) - { - above++; - } - - else if(v < hhx) - { - below++; - } - } - - if(x - 1 >= 0) - { - v = plan.getRealHeight(x - 1, z); - - if(v > hhx) - { - above++; - } - - else if(v < hhx) - { - below++; - } - } - - if(z + 1 <= 15) - { - v = plan.getRealHeight(x, z + 1); - - if(v > hhx) - { - above++; - } - - else if(v < hhx) - { - below++; - } - } - - if(z - 1 >= 0) - { - v = plan.getRealHeight(x, z - 1); - - if(v > hhx) - { - above++; - } - - else if(v < hhx) - { - below++; - } - } - - // Patch Hole - if(above >= 4 - borderh) - { - data.setBlock(x, hhx + 1, z, data.getMB(x, hhx, z)); - plan.setRealHeight(x, z, hhx + 1); - } - - // Remove Nipple - else if(below >= 4 - borderh) - { - data.setBlock(x, hhx - 1, z, data.getMB(x, hhx, z)); - data.setBlock(x, hhx, z, Material.AIR); - plan.setRealHeight(x, z, hhx - 1); - } - } - } - } - } - - getMetrics().stop("decoration:ms:/chunk:..", p); - } - - @SuppressWarnings("deprecation") - @Override - protected void onDecorateColumn(World world, int x, int z, int wx, int wz, AtomicChunkData data, ChunkPlan plan) - { - PrecisionStopwatch p = PrecisionStopwatch.start(); - int h = plan.getRealHeight(x, z); - - if(h < 63) - { - return; - } - - IrisBiome biome = plan.getBiome(x, z); - - if(biome == null) - { - return; - } - - if(biome.getSnow() > 0) - { - double level = glSnow.getHeight(wx, wz) * biome.getSnow(); - int blocks = (int) level; - level -= blocks; - int layers = (int) (level * 7D); - int snowHeight = blocks + (layers > 0 ? 1 : 0); - - for(int j = 0; j < snowHeight; j++) - { - data.setBlock(x, h + j + 1, z, j == snowHeight - 1 ? Material.SNOW : Material.SNOW_BLOCK, j == snowHeight - 1 ? (byte) layers : (byte) 0); - } - } - - else - { - MB mbx = biome.getScatterChanceSingle(scatter(wx, h, wz), scatter(wz, h, wx)); - - if(!mbx.material.equals(Material.AIR)) - { - data.setBlock(x, h + 1, z, mbx.material, mbx.data); - - if(mbx.material.equals(Material.DOUBLE_PLANT)) - { - data.setBlock(x, h + 2, z, mbx.material, (byte) 10); - } - } - } - - if(biome.getLush() > 0.33) - { - double lx = (biome.getLush() > 1 ? 1 : biome.getLush()) - 0.33; - double g = glSnow.getHeight(wz, wx); - - if(lx / 1.18D > g) - { - double gx = glSnow.getHeight(wx * 2.25, wz * 2.25); - double gf = glSnow.getHeight(wx * 6.25, wz * 6.25); - - if(gf > gx) - { - Leaves l = new Leaves(TreeSpecies.values()[(int) (gx * (TreeSpecies.values().length - 1))]); - l.setDecaying(false); - l.setDecayable(false); - data.setBlock(x, h - 1, z, data.getMB(x, h, z)); - data.setBlock(x, h, z, l.getItemType(), l.getData()); - - if(gf - gx > 0.2) - { - l = new Leaves(TreeSpecies.values()[(int) (gf * (TreeSpecies.values().length - 1))]); - l.setDecaying(false); - l.setDecayable(false); - data.setBlock(x, h + 1, z, l.getItemType(), l.getData()); - } - } - } - } - - getMetrics().stop("pardecoration:ms:x256:/chunk:..", p); - } - - @Override - public void onPostChunk(World world, int cx, int cz, Random random, AtomicChunkData data, ChunkPlan plan) - { - - } - - private double getBiomedHeight(int x, int z, ChunkPlan plan) - { - double xh = plan.getHeight(x, z); - - if(xh == -1) - { - IrisBiome biome = glBiome.getBiome(x, z); - double h = Iris.settings.gen.baseHeight + biome.getHeight(); - h += biome.getGenerator().getHeight(x, z) / 2D; - plan.setHeight(x, z, h); - return h; - } - - return xh; - } - - public RNG getRTerrain() - { - return rTerrain; - } - - public CompiledDimension getDimension() - { - return dim; - } - - public void dispose() - { - if(disposed) - { - return; - } - L.w(C.YELLOW + "Disposed Iris World " + C.RED + getWorld().getName()); - disposed = true; - dim = null; - glLNoise = null; - glSnow = null; - glCliffs = null; - god.dispose(); - } - - public boolean isDisposed() - { - return disposed; - } - - public PlacedObject nearest(Location o, int i) - { - PlacedObject f = null; - double d = Integer.MAX_VALUE; - if(god != null) - { - for(PlacedObject j : god.getHistory()) - { - double dx = Math.abs(NumberConversions.square(j.getX() - o.getX()) + NumberConversions.square(j.getY() - o.getY()) + NumberConversions.square(j.getZ() - o.getZ())); - - if(dx < d) - { - d = dx; - f = j; - } - } - } - - return f; - } - - public PlacedObject randomObject(String string) - { - return god.randomObject(string); - } - - @Override - protected SChunkVector getParallaxSize() - { - return dim.getMaxChunkSize(); - } - - @Override - protected void onUnload() - { - dispose(); - } - - public void inject(CompiledDimension dimension) - { - this.dim = dimension; - onInit(getWorld(), rTerrain); - } -} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/generator/IrisSample.java b/src/main/java/ninja/bytecode/iris/generator/IrisSample.java deleted file mode 100644 index 40afbc7bb..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/IrisSample.java +++ /dev/null @@ -1,81 +0,0 @@ -package ninja.bytecode.iris.generator; - -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.iris.util.MB; - -public class IrisSample -{ - public MB surface; - public int height; - public IrisBiome biome; - - public MB getSurface() - { - return surface; - } - - public void setSurface(MB surface) - { - this.surface = surface; - } - - public int getHeight() - { - return height; - } - - public void setHeight(int height) - { - this.height = height; - } - - public IrisBiome getBiome() - { - return biome; - } - - public void setBiome(IrisBiome biome) - { - this.biome = biome; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((biome == null) ? 0 : biome.hashCode()); - result = prime * result + height; - result = prime * result + ((surface == null) ? 0 : surface.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; - IrisSample other = (IrisSample) obj; - if(biome == null) - { - if(other.biome != null) - return false; - } - else if(!biome.equals(other.biome)) - return false; - if(height != other.height) - return false; - if(surface == null) - { - if(other.surface != null) - return false; - } - else if(!surface.equals(other.surface)) - return false; - return true; - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/ParallaxChunkGenerator.java b/src/main/java/ninja/bytecode/iris/generator/ParallaxChunkGenerator.java new file mode 100644 index 000000000..c62be1ab4 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/generator/ParallaxChunkGenerator.java @@ -0,0 +1,202 @@ +package ninja.bytecode.iris.generator; + +import java.io.IOException; + +import org.bukkit.World; +import org.bukkit.block.data.BlockData; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.object.IrisBiome; +import ninja.bytecode.iris.object.IrisObjectPlacement; +import ninja.bytecode.iris.object.atomics.AtomicSliver; +import ninja.bytecode.iris.object.atomics.AtomicSliverMap; +import ninja.bytecode.iris.object.atomics.AtomicWorldData; +import ninja.bytecode.iris.object.atomics.MasterLock; +import ninja.bytecode.iris.util.BiomeMap; +import ninja.bytecode.iris.util.ChunkPosition; +import ninja.bytecode.iris.util.HeightMap; +import ninja.bytecode.iris.util.IObjectPlacer; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KMap; + +@Data +@EqualsAndHashCode(callSuper = false) +public abstract class ParallaxChunkGenerator extends TerrainChunkGenerator implements IObjectPlacer +{ + private KMap sliverCache; + protected AtomicWorldData parallaxMap; + private MasterLock masterLock; + private int sliverBuffer; + + public ParallaxChunkGenerator(String dimensionName, int threads) + { + super(dimensionName, threads); + sliverCache = new KMap<>(); + sliverBuffer = 0; + masterLock = new MasterLock(); + } + + public void onInit(World world, RNG rng) + { + super.onInit(world, rng); + parallaxMap = new AtomicWorldData(world); + } + + protected void onClose() + { + super.onClose(); + + try + { + parallaxMap.unloadAll(true); + } + + catch(IOException e) + { + e.printStackTrace(); + } + } + + @Override + public int getHighest(int x, int z) + { + return sampleSliver(x, z).getHighestBlock(); + } + + @Override + public void set(int x, int y, int z, BlockData d) + { + getMasterLock().lock((x >> 4) + "." + (z >> 4)); + getParallaxSliver(x, z).set(y, d); + getMasterLock().unlock((x >> 4) + "." + (z >> 4)); + } + + @Override + public BlockData get(int x, int y, int z) + { + BlockData b = sampleSliver(x, z).getBlock().get(y); + return b == null ? AIR : b; + } + + public AtomicSliver getParallaxSliver(int wx, int wz) + { + getMasterLock().lock("gpc"); + getMasterLock().lock((wx >> 4) + "." + (wz >> 4)); + AtomicSliverMap map = getParallaxChunk(wx >> 4, wz >> 4); + getMasterLock().unlock("gpc"); + AtomicSliver sliver = map.getSliver(wx & 15, wz & 15); + getMasterLock().unlock((wx >> 4) + "." + (wz >> 4)); + + return sliver; + } + + public boolean isParallaxGenerated(int x, int z) + { + return getParallaxChunk(x, z).isParallaxGenerated(); + } + + public boolean isWorldGenerated(int x, int z) + { + return getParallaxChunk(x, z).isWorldGenerated(); + } + + public AtomicSliverMap getParallaxChunk(int x, int z) + { + try + { + return getParallaxMap().loadChunk(x, z); + } + + catch(IOException e) + { + fail(e); + } + + return new AtomicSliverMap(); + } + + @Override + protected void onPostGenerate(RNG random, int x, int z, ChunkData data, BiomeGrid grid, HeightMap height, BiomeMap biomeMap) + { + biomeHitCache.clear(); + + if(getDimension().isPlaceObjects()) + { + onGenerateParallax(random, x, z); + getParallaxChunk(x, z).inject(data); + setSliverBuffer(getSliverCache().size()); + getParallaxChunk(x, z).setWorldGenerated(true); + getParallaxMap().clean(x + z); + getSliverCache().clear(); + getMasterLock().clear(); + } + } + + protected void onGenerateParallax(RNG random, int x, int z) + { + String key = "par." + x + "." + "z"; + ChunkPosition rad = Iris.data.getObjectLoader().getParallaxSize(); + + for(int ii = x - (rad.getX() / 2); ii <= x + (rad.getX() / 2); ii++) + { + int i = ii; + + for(int jj = z - (rad.getZ() / 2); jj <= z + (rad.getZ() / 2); jj++) + { + int j = jj; + + if(isParallaxGenerated(ii, jj)) + { + continue; + } + + if(isWorldGenerated(ii, jj)) + { + continue; + } + + getTx().queue(key, () -> + { + IrisBiome b = sampleTrueBiome((i * 16) + 7, (j * 16) + 7).getBiome(); + int g = 1; + + for(IrisObjectPlacement k : b.getObjects()) + { + placeObject(k, i, j, random.nextParallelRNG((34 * ((i * 30) + (j * 30) + g++) * i * j) + i - j + 3569222)); + } + }); + + getParallaxChunk(ii, jj).setParallaxGenerated(true); + } + } + + getTx().waitFor(key); + } + + protected void placeObject(IrisObjectPlacement o, int x, int z, RNG rng) + { + for(int i = 0; i < o.getTriesForChunk(rng); i++) + { + rng = rng.nextParallelRNG((i * 3 + 8) - 23040); + o.getSchematic(rng).place((x * 16) + rng.nextInt(16), (z * 16) + rng.nextInt(16), this, o, rng); + } + } + + public AtomicSliver sampleSliver(int x, int z) + { + ChunkPosition key = new ChunkPosition(x, z); + + if(sliverCache.containsKey(key)) + { + return sliverCache.get(key); + } + + AtomicSliver s = new AtomicSliver(x & 15, z & 15); + onGenerateColumn(x >> 4, z >> 4, x, z, x & 15, z & 15, s, null); + sliverCache.put(key, s); + + return s; + } +} diff --git a/src/main/java/ninja/bytecode/iris/generator/ParallelChunkGenerator.java b/src/main/java/ninja/bytecode/iris/generator/ParallelChunkGenerator.java new file mode 100644 index 000000000..d0cca8b24 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/generator/ParallelChunkGenerator.java @@ -0,0 +1,99 @@ +package ninja.bytecode.iris.generator; + +import org.bukkit.World; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.object.atomics.AtomicSliver; +import ninja.bytecode.iris.object.atomics.AtomicSliverMap; +import ninja.bytecode.iris.util.BiomeMap; +import ninja.bytecode.iris.util.GroupedExecutor; +import ninja.bytecode.iris.util.HeightMap; +import ninja.bytecode.iris.util.RNG; + +@Data +@EqualsAndHashCode(callSuper = false) +public abstract class ParallelChunkGenerator extends BiomeChunkGenerator +{ + private GroupedExecutor tx; + private int threads; + + public ParallelChunkGenerator(String dimensionName, int threads) + { + super(dimensionName); + this.threads = threads; + } + + public void changeThreadCount(int tc) + { + threads = tc; + GroupedExecutor e = tx; + tx = new GroupedExecutor(threads, Thread.NORM_PRIORITY, "Iris Generator - " + world.getName()); + Iris.executors.add(tx); + + if(e != null) + { + e.close(); + } + } + + protected abstract void onGenerateColumn(int cx, int cz, int wx, int wz, int x, int z, AtomicSliver sliver, BiomeMap biomeMap); + + protected abstract int onSampleColumnHeight(int cx, int cz, int wx, int wz, int x, int z); + + protected abstract void onPostGenerate(RNG random, int x, int z, ChunkData data, BiomeGrid grid, HeightMap height, BiomeMap biomeMap); + + protected int sampleHeight(int x, int z) + { + return onSampleColumnHeight(x >> 4, z >> 4, x, z, x & 15, z & 15); + } + + protected void onGenerate(RNG random, int x, int z, ChunkData data, BiomeGrid grid) + { + AtomicSliverMap map = new AtomicSliverMap(); + HeightMap height = new HeightMap(); + String key = "c" + x + "," + z; + BiomeMap biomeMap = new BiomeMap(); + int ii, jj; + + for(ii = 0; ii < 16; ii++) + { + int i = ii; + int wx = (x * 16) + i; + + for(jj = 0; jj < 16; jj++) + { + int j = jj; + int wz = (z * 16) + j; + AtomicSliver sliver = map.getSliver(i, j); + + tx.queue(key, () -> + { + onGenerateColumn(x, z, wx, wz, i, j, sliver, biomeMap); + }); + } + } + + tx.waitFor(key); + map.write(data, grid, height); + onPostGenerate(random, x, z, data, grid, height, biomeMap); + } + + protected void onClose() + { + tx.close(); + } + + public void onInit(World world, RNG rng) + { + super.onInit(world, rng); + changeThreadCount(threads); + } + + @Override + public boolean isParallelCapable() + { + return false; + } +} diff --git a/src/main/java/ninja/bytecode/iris/generator/TerrainChunkGenerator.java b/src/main/java/ninja/bytecode/iris/generator/TerrainChunkGenerator.java new file mode 100644 index 000000000..2e4545c22 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/generator/TerrainChunkGenerator.java @@ -0,0 +1,306 @@ +package ninja.bytecode.iris.generator; + +import java.util.concurrent.locks.ReentrantLock; + +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.data.Bisected; +import org.bukkit.block.data.Bisected.Half; +import org.bukkit.block.data.BlockData; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.object.IrisBiome; +import ninja.bytecode.iris.object.IrisBiomeDecorator; +import ninja.bytecode.iris.object.IrisRegion; +import ninja.bytecode.iris.object.atomics.AtomicSliver; +import ninja.bytecode.iris.util.BiomeMap; +import ninja.bytecode.iris.util.BiomeResult; +import ninja.bytecode.iris.util.BlockPosition; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.math.M; + +@Data +@EqualsAndHashCode(callSuper = false) +public abstract class TerrainChunkGenerator extends ParallelChunkGenerator +{ + protected static final BlockData AIR = Material.AIR.createBlockData(); + protected static final BlockData STONE = Material.STONE.createBlockData(); + protected static final BlockData WATER = Material.WATER.createBlockData(); + private KList updateBlocks = new KList<>(); + private ReentrantLock relightLock = new ReentrantLock(); + private long lastUpdateRequest = M.ms(); + private long lastChunkLoad = M.ms(); + + public TerrainChunkGenerator(String dimensionName, int threads) + { + super(dimensionName, threads); + } + + public void onInit(World world, RNG rng) + { + super.onInit(world, rng); + } + + public void queueUpdate(int x, int y, int z) + { + if(M.ms() - lastUpdateRequest > 3000 && M.ms() - lastChunkLoad > 3000) + { + updateBlocks.clear(); + } + + updateBlocks.add(new BlockPosition(x, y, z)); + lastUpdateRequest = M.ms(); + } + + public void updateLights() + { + if(M.ms() - lastUpdateRequest > 3000 && M.ms() - lastChunkLoad > 3000) + { + updateBlocks.clear(); + } + + for(BlockPosition i : updateBlocks.copy()) + { + if(getWorld().isChunkLoaded(i.getChunkX(), i.getChunkZ())) + { + updateBlocks.remove(i); + Block b = getWorld().getBlockAt(i.getX(), i.getY(), i.getZ()); + BlockData bd = b.getBlockData(); + b.setBlockData(AIR, false); + b.setBlockData(bd, true); + } + } + + while(updateBlocks.size() > 5000) + { + updateBlocks.remove(0); + } + + lastChunkLoad = M.ms(); + } + + public void checkUnderwater(int x, int y, int z, BlockData d) + { + if(d.getMaterial().equals(Material.SEA_PICKLE) || d.getMaterial().equals(Material.SOUL_SAND) || d.getMaterial().equals(Material.MAGMA_BLOCK)) + { + queueUpdate(x, y, z); + } + } + + public void checkSurface(int x, int y, int z, BlockData d) + { + if(d.getMaterial().equals(Material.SEA_PICKLE) || d.getMaterial().equals(Material.TORCH) || d.getMaterial().equals(Material.REDSTONE_TORCH) || d.getMaterial().equals(Material.TORCH)) + { + queueUpdate(x, y, z); + } + } + + @Override + protected void onGenerateColumn(int cx, int cz, int rx, int rz, int x, int z, AtomicSliver sliver, BiomeMap biomeMap) + { + try + { + BlockData block; + int fluidHeight = getDimension().getFluidHeight(); + double ox = getModifiedX(rx, rz); + double oz = getModifiedZ(rx, rz); + double wx = getZoomed(ox); + double wz = getZoomed(oz); + int depth = 0; + double noise = getNoiseHeight(rx, rz); + int height = (int) Math.round(noise) + fluidHeight; + IrisBiome biome = sampleTrueBiome(rx, rz).getBiome(); + KList layers = biome.generateLayers(wx, wz, masterRandom, height); + + for(int k = Math.max(height, fluidHeight); k < 255; k++) + { + if(k < Math.max(height, fluidHeight) + 3) + { + if(biomeMap != null) + { + sliver.set(k, biome.getGroundBiome(masterRandom, rz, k, rx)); + } + } + + else + { + if(biomeMap != null) + { + sliver.set(k, biome.getSkyBiome(masterRandom, rx, k, rz)); + } + } + } + + for(int k = Math.max(height, fluidHeight); k >= 0; k--) + { + boolean underwater = k > height && k <= fluidHeight; + + if(biomeMap != null) + { + sliver.set(k, biome.getGroundBiome(masterRandom, rz, k, rx)); + biomeMap.setBiome(x, z, biome); + } + + if(underwater) + { + block = WATER; + } + + else + { + block = layers.hasIndex(depth) ? layers.get(depth) : STONE; + depth++; + } + + sliver.set(k, block); + + if(k == height && block.getMaterial().isSolid() && k < fluidHeight && biome.isSea()) + { + int j = 0; + + for(IrisBiomeDecorator i : biome.getDecorators()) + { + BlockData d = i.getBlockData(getMasterRandom().nextParallelRNG(biome.hashCode() + j++), wx, wz); + + if(d != null) + { + int stack = i.getHeight(getMasterRandom().nextParallelRNG(39456 + i.hashCode()), wx, wz); + + if(stack == 1) + { + sliver.set(k + 1, d); + checkUnderwater(rx, k + 1, rz, d); + } + + else if(k < fluidHeight - stack) + { + for(int l = 0; l < stack; l++) + { + sliver.set(k + l + 1, d); + checkUnderwater(rx, k + l + 1, rz, d); + } + } + + break; + } + } + } + + if(k == Math.max(height, fluidHeight) && block.getMaterial().isSolid() && k < 255 && !biome.isSea()) + { + int j = 0; + + for(IrisBiomeDecorator i : biome.getDecorators()) + { + BlockData d = i.getBlockData(getMasterRandom().nextParallelRNG(biome.hashCode() + j++), wx, wz); + + if(d != null) + { + if(d instanceof Bisected && k < 254) + { + Bisected t = ((Bisected) d.clone()); + t.setHalf(Half.TOP); + Bisected b = ((Bisected) d.clone()); + b.setHalf(Half.BOTTOM); + sliver.set(k + 1, b); + sliver.set(k + 2, t); + } + + else + { + int stack = i.getHeight(getMasterRandom().nextParallelRNG(39456 + i.hashCode()), wx, wz); + + if(stack == 1) + { + sliver.set(k + 1, d); + } + + else if(k < 255 - stack) + { + for(int l = 0; l < stack; l++) + { + sliver.set(k + l + 1, d); + } + } + } + + break; + } + } + } + } + } + + catch(Throwable e) + { + fail(e); + } + } + + protected double getNoiseHeight(int rx, int rz) + { + double wx = getZoomed(rx); + double wz = getZoomed(rz); + + return getBiomeHeight(wx, wz); + } + + public BiomeResult sampleTrueBiome(int x, int z) + { + if(!getDimension().getFocus().equals("")) + { + return focus(); + } + + double wx = getModifiedX(x, z); + double wz = getModifiedZ(x, z); + IrisRegion region = sampleRegion(x, z); + int height = sampleHeight(x, z); + double sh = region.getShoreHeight(wx, wz); + IrisBiome current = sampleBiome(x, z).getBiome(); + + // Stop shores from spawning on land + if(current.isShore() && height > sh) + { + return glBiome.generateLandData(wx, wz, x, z, region); + } + + // Stop land & shore from spawning underwater + if(current.isShore() || current.isLand() && height <= getDimension().getFluidHeight()) + { + return glBiome.generateSeaData(wx, wz, x, z, region); + } + + // Stop oceans from spawning on land + if(current.isSea() && height > getDimension().getFluidHeight()) + { + return glBiome.generateLandData(wx, wz, x, z, region); + } + + // Stop land from spawning underwater + if(height <= getDimension().getFluidHeight()) + { + return glBiome.generateSeaData(wx, wz, x, z, region); + } + + // Stop land from spawning where shores go + if(height <= getDimension().getFluidHeight() + sh) + { + return glBiome.generateShoreData(wx, wz, x, z, region); + } + + return glBiome.generateRegionData(wx, wz, x, z, region); + } + + @Override + protected int onSampleColumnHeight(int cx, int cz, int rx, int rz, int x, int z) + { + int fluidHeight = getDimension().getFluidHeight(); + double noise = getNoiseHeight(rx, rz); + + return (int) Math.round(noise) + fluidHeight; + } +} diff --git a/src/main/java/ninja/bytecode/iris/generator/WorldReactor.java b/src/main/java/ninja/bytecode/iris/generator/WorldReactor.java deleted file mode 100644 index a1acca8fa..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/WorldReactor.java +++ /dev/null @@ -1,105 +0,0 @@ -package ninja.bytecode.iris.generator; - -import java.util.Collections; -import java.util.function.Consumer; - -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import mortar.api.nms.NMP; -import mortar.api.sched.J; -import mortar.compute.math.M; -import mortar.lang.collection.FinalDouble; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.util.ChronoQueue; -import ninja.bytecode.iris.util.ObjectMode; -import ninja.bytecode.iris.util.SMCAVector; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; - -public class WorldReactor -{ - private static KList q = new KList<>(); - private final World world; - - public WorldReactor(World world) - { - this.world = world; - } - - public void generateRegionNormal(Player p, boolean force, double mst, Consumer progress, Runnable done) - { - for(ChronoQueue i : WorldReactor.q) - { - i.close(); - } - - WorldReactor.q.clear(); - - ChronoQueue q = new ChronoQueue(mst, 10240); - WorldReactor.q.add(q); - FinalDouble of = new FinalDouble(0D); - FinalDouble max = new FinalDouble(0D); - KMap d = new KMap<>(); - int mx = p.getLocation().getChunk().getX(); - int mz = p.getLocation().getChunk().getZ(); - for(int xx = p.getLocation().getChunk().getX() - 32; xx < p.getLocation().getChunk().getX() + 32; xx++) - { - int x = xx; - - for(int zz = p.getLocation().getChunk().getZ() - 32; zz < p.getLocation().getChunk().getZ() + 32; zz++) - { - int z = zz; - - if(world.isChunkLoaded(x, z) || world.loadChunk(x, z, false)) - { - d.put(new SMCAVector(x, z), Math.sqrt(Math.pow(x - mx, 2) + Math.pow(z - mz, 2))); - } - } - } - - KList v = d.k(); - Collections.sort(v, (a, b) -> (int) (10000 * (d.get(a) - d.get(b)))); - - for(SMCAVector i : v) - { - int x = i.getX(); - int z = i.getZ(); - - if(Iris.settings.performance.objectMode.equals(ObjectMode.PARALLAX) && world.getGenerator() instanceof IrisGenerator) - { - IrisGenerator gg = ((IrisGenerator) world.getGenerator()); - gg.getWorldData().deleteChunk(x, z); - } - - max.add(1); - q.queue(() -> - { - world.regenerateChunk(x, z); - - Chunk cc = world.getChunkAt(x, z); - NMP.host.relight(cc); - of.add(1); - - if(of.get() == max.get()) - { - progress.accept(1D); - q.dieSlowly(); - done.run(); - } - - else - { - progress.accept(M.clip(of.get() / max.get(), 0D, 1D)); - } - - }); - } - - J.s(() -> - { - q.dieSlowly(); - }, 20); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicCharArray.java b/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicCharArray.java deleted file mode 100644 index 7f032167e..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicCharArray.java +++ /dev/null @@ -1,83 +0,0 @@ -package ninja.bytecode.iris.generator.atomics; - -import java.io.Serializable; -import java.lang.reflect.Field; - -import sun.misc.Unsafe; - -@SuppressWarnings("restriction") -public class AtomicCharArray implements Serializable -{ - private static final long serialVersionUID = 2862133569453604235L; - private static final Unsafe unsafe; - private static final int base; - private static final int shift; - volatile char[] array; - - public AtomicCharArray(int var1) - { - this.array = new char[var1]; - } - - private long checkedByteOffset(int var1) - { - if(var1 >= 0 && var1 < this.array.length) - { - return byteOffset(var1); - } - else - { - throw new IndexOutOfBoundsException("index " + var1); - } - } - - public final char get(int var1) - { - return this.getRaw(this.checkedByteOffset(var1)); - } - - private char getRaw(long var1) - { - return unsafe.getCharVolatile(this.array, var1); - } - - public final void set(int var1, char var2) - { - unsafe.putCharVolatile(this.array, this.checkedByteOffset(var1), var2); - } - - private static long byteOffset(int var0) - { - return ((long) var0 << shift) + (long) base; - } - - static - { - Field f; - Unsafe o = null; - - try - { - f = Unsafe.class.getDeclaredField("theUnsafe"); - f.setAccessible(true); - o = (Unsafe) f.get(null); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - - unsafe = o; - base = unsafe.arrayBaseOffset(int[].class); - int var0 = unsafe.arrayIndexScale(int[].class); - if((var0 & var0 - 1) != 0) - { - throw new Error("data type scale not a power of two"); - } - else - { - shift = 31 - Integer.numberOfLeadingZeros(var0); - } - } -} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicChunkData.java b/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicChunkData.java deleted file mode 100644 index e6af21880..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicChunkData.java +++ /dev/null @@ -1,456 +0,0 @@ -package ninja.bytecode.iris.generator.atomics; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.util.concurrent.locks.ReentrantLock; - -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.craftbukkit.v1_12_R1.generator.CraftChunkData; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.generator.ChunkGenerator.ChunkData; -import org.bukkit.material.MaterialData; - -import mortar.compute.math.M; -import ninja.bytecode.iris.util.MB; - -public final class AtomicChunkData implements ChunkGenerator.ChunkData -{ - private static final Field t; - private static final Field[] sections; - private static final int h = 0x1000; - private final int maxHeight; - private static ReentrantLock[] locks; - private char[] s0; - private char[] s1; - private char[] s2; - private char[] s3; - private char[] s4; - private char[] s5; - private char[] s6; - private char[] s7; - private char[] s8; - private char[] s9; - private char[] s10; - private char[] s11; - private char[] s12; - private char[] s13; - private char[] s14; - private char[] s15; - private char[][] m; - private World w; - private long lastUse; - private int bits; - - public AtomicChunkData(World world) - { - this.maxHeight = world.getMaxHeight(); - this.w = world; - bits = 0; - lastUse = M.ms(); - } - - public long getTimeSinceLastUse() - { - return M.ms() - lastUse; - } - - public void read(InputStream in) throws IOException - { - read(in, true); - } - - public void read(InputStream in, boolean ignoreAir) throws IOException - { - DataInputStream din = new DataInputStream(in); - int bits = din.readInt(); - - for(int i = 0; i < 16; i++) - { - int bit = getBit(i); - if((bits & bit) == bit) - { - char[] section = getChunkSection(i << 4, true); - - for(int j = 0; j < section.length; j++) - { - char c = din.readChar(); - - if(c == 0 && ignoreAir) - { - continue; - } - - section[j] = c; - } - } - } - - din.close(); - } - - public void write(OutputStream out) throws IOException - { - DataOutputStream dos = new DataOutputStream(out); - dos.writeInt(getDataBits()); - - for(int i = 0; i < 16; i++) - { - if(hasDataBit(i)) - { - char[] section = getChunkSection(i << 4, false); - for(int j = 0; j < section.length; j++) - { - dos.writeChar(section[j]); - } - } - } - - dos.close(); - } - - public boolean hasDataBit(int section) - { - int b = getBit(section); - return (bits & b) == b; - } - - public void clearDataBits() - { - bits = 0; - } - - public void addDataBit(int section) - { - bits |= getBit(section); - } - - public void removeDataBit(int section) - { - bits ^= getBit(section); - } - - public int getDataBits() - { - return bits; - } - - public int getBit(int index) - { - return (int) (index < 0 ? -1 : Math.pow(2, index)); - } - - public int computeDataBits() - { - int bits = 0; - - for(int i = 0; i < 16; i++) - { - try - { - bits |= sections[i].get(this) != null ? getBit(i) : 0; - } - - catch(Throwable e) - { - - } - } - - return bits; - } - - @Override - public int getMaxHeight() - { - return maxHeight; - } - - @SuppressWarnings("deprecation") - @Override - public void setBlock(int x, int y, int z, Material material) - { - setBlock(x, y, z, material.getId()); - } - - @SuppressWarnings("deprecation") - @Override - public void setBlock(int x, int y, int z, MaterialData material) - { - setBlock(x, y, z, material.getItemTypeId(), material.getData()); - } - - @SuppressWarnings("deprecation") - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material) - { - setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material.getId()); - } - - @SuppressWarnings("deprecation") - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material) - { - setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material.getItemTypeId(), material.getData()); - } - - @SuppressWarnings("deprecation") - @Override - public Material getType(int x, int y, int z) - { - lastUse = M.ms(); - return Material.getMaterial(getTypeId(x, y, z)); - } - - @SuppressWarnings("deprecation") - @Override - public MaterialData getTypeAndData(int x, int y, int z) - { - lastUse = M.ms(); - return getType(x, y, z).getNewData(getData(x, y, z)); - } - - @SuppressWarnings("deprecation") - public void setBlock(int x, int y, int z, Material blockId, byte data) - { - setBlock(x, y, z, blockId.getId(), data); - } - - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, int blockId) - { - lastUse = M.ms(); - setRegion(xMin, yMin, zMin, xMax, yMax, zMax, blockId, (byte) 0); - } - - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, int blockId, int data) - { - lastUse = M.ms(); - throw new UnsupportedOperationException("AtomicChunkData does not support setting regions"); - } - - @Override - public void setBlock(int x, int y, int z, int blockId) - { - setBlock(x, y, z, blockId, (byte) 0); - } - - @Override - public void setBlock(int x, int y, int z, int blockId, byte data) - { - setBlock(x, y, z, (char) (blockId << 4 | data)); - } - - @SuppressWarnings("deprecation") - public MB getMB(int x, int y, int z) - { - if(x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) - { - lastUse = M.ms(); - return MB.of(Material.AIR); - } - - char[] section = getChunkSection(y, false); - - if(section == null) - { - lastUse = M.ms(); - return MB.of(Material.AIR); - } - - else - { - lastUse = M.ms(); - char xf = section[(y & 0xf) << 8 | z << 4 | x]; - return MB.of(Material.getMaterial(xf >> 4), xf & 0xf); - } - } - - @Override - public int getTypeId(int x, int y, int z) - { - if(x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) - { - return 0; - } - - char[] section = getChunkSection(y, false); - - if(section == null) - { - return 0; - } - - else - { - lastUse = M.ms(); - return section[(y & 0xf) << 8 | z << 4 | x] >> 4; - } - } - - @Override - public byte getData(int x, int y, int z) - { - if(x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) - { - lastUse = M.ms(); - return (byte) 0; - } - - char[] section = getChunkSection(y, false); - - if(section == null) - { - lastUse = M.ms(); - return (byte) 0; - } - - else - { - lastUse = M.ms(); - return (byte) (section[(y & 0xf) << 8 | z << 4 | x] & 0xf); - } - } - - private void setBlock(int x, int y, int z, char type) - { - if(x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) - { - return; - } - - lastUse = M.ms(); - ReentrantLock l = locks[y >> 4]; - l.lock(); - getChunkSection(y, true)[(y & 0xf) << 8 | z << 4 | x] = type; - l.unlock(); - } - - private char[] getChunkSection(int y, boolean c) - { - try - { - int s = y >> 4; - Field sf = sections[s]; - char[] section = (char[]) sf.get(this); - - if(section == null && c) - { - sf.set(this, new char[h]); - section = (char[]) sf.get(this); - addDataBit(s); - } - - return section; - } - - catch(Throwable e) - { - e.printStackTrace(); - } - - return null; - } - - public ChunkData toChunkData() - { - ChunkData c = new CraftChunkData(w); - - try - { - m = (char[][]) t.get(c); - m[0] = s0; - m[1] = s1; - m[2] = s2; - m[3] = s3; - m[4] = s4; - m[5] = s5; - m[6] = s6; - m[7] = s7; - m[8] = s8; - m[9] = s9; - m[10] = s10; - m[11] = s11; - m[12] = s12; - m[13] = s13; - m[14] = s14; - m[15] = s15; - } - - catch(IllegalArgumentException | IllegalAccessException e) - { - e.printStackTrace(); - } - - return c; - } - - static - { - locks = new ReentrantLock[16]; - Field[] s = new Field[16]; - - for(int i = 0; i < 16; i++) - { - try - { - s[i] = AtomicChunkData.class.getDeclaredField("s" + i); - locks[i] = new ReentrantLock(); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - sections = s; - - Field x = null; - - try - { - x = CraftChunkData.class.getDeclaredField("sections"); - x.setAccessible(true); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - - t = x; - } - - public void inject(AtomicChunkData data) - { - for(int i = 0; i < 16; i++) - { - if(hasDataBit(i)) - { - char[] fromSection = getChunkSection(i << 4, false); - char[] toSection = data.getChunkSection(i << 4, true); - - for(int j = 0; j < fromSection.length; j++) - { - char x = fromSection[j]; - - if(x != 0) - { - toSection[j] = x; - } - } - } - } - } - - public void setBlock(int x, int y, int z, MB mb) - { - setBlock(x, y, z, mb.material, mb.data); - } -} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicWorldData.java b/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicWorldData.java deleted file mode 100644 index d6e7e3e0e..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicWorldData.java +++ /dev/null @@ -1,158 +0,0 @@ -package ninja.bytecode.iris.generator.atomics; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.bukkit.World; - -import ninja.bytecode.iris.util.SMCAVector; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; - -public class AtomicWorldData -{ - private World world; - private KMap loadedSections; - - public AtomicWorldData(World world) - { - this.world = world; - loadedSections = new KMap<>(); - getSubregionFolder().mkdirs(); - } - - public KList getLoadedRegions() - { - return loadedSections.k(); - } - - public AtomicRegionData getSubregion(int x, int z) throws IOException - { - if(!isSectionLoaded(x, z)) - { - loadedSections.put(new SMCAVector(x, z), loadSection(x, z)); - } - - AtomicRegionData f = loadedSections.get(new SMCAVector(x, z)); - - return f; - } - - public void saveAll() throws IOException - { - for(SMCAVector i : loadedSections.keySet()) - { - saveSection(i); - } - } - - public void unloadAll(boolean save) throws IOException - { - for(SMCAVector i : loadedSections.keySet()) - { - unloadSection(i, save); - } - } - - public void deleteSection(int x, int z) throws IOException - { - unloadSection(x, z, false); - getSubregionFile(x, z).delete(); - } - - public boolean isSectionLoaded(int x, int z) - { - return isSectionLoaded(new SMCAVector(x, z)); - } - - public boolean isSectionLoaded(SMCAVector s) - { - return loadedSections.containsKey(s); - } - - public boolean unloadSection(int x, int z, boolean save) throws IOException - { - return unloadSection(new SMCAVector(x, z), save); - } - - public boolean unloadSection(SMCAVector s, boolean save) throws IOException - { - if(!isSectionLoaded(s)) - { - return false; - } - - if(save) - { - saveSection(s); - } - - loadedSections.remove(s); - return true; - } - - public boolean saveSection(int x, int z) throws IOException - { - return saveSection(new SMCAVector(x, z)); - } - - public boolean saveSection(SMCAVector s) throws IOException - { - if(!isSectionLoaded(s.getX(), s.getZ())) - { - return false; - } - - AtomicRegionData data = loadedSections.get(s); - FileOutputStream fos = new FileOutputStream(getSubregionFile(s.getX(), s.getZ())); - data.write(fos); - fos.close(); - return true; - } - - public AtomicRegionData loadSection(int x, int z) throws IOException - { - if(isSectionLoaded(x, z)) - { - return loadedSections.get(new SMCAVector(x, z)); - } - - File file = getSubregionFile(x, z); - - if(!file.exists()) - { - return createSection(x, z); - } - - FileInputStream fin = new FileInputStream(file); - AtomicRegionData data = new AtomicRegionData(world); - data.read(fin); - fin.close(); - return data; - } - - public AtomicRegionData createSection(int x, int z) - { - if(isSectionLoaded(x, z)) - { - return loadedSections.get(new SMCAVector(x, z)); - } - - AtomicRegionData data = new AtomicRegionData(world); - loadedSections.put(new SMCAVector(x, z), data); - - return data; - } - - public File getSubregionFile(int x, int z) - { - return new File(getSubregionFolder(), "sr." + x + "." + z + ".smca"); - } - - public File getSubregionFolder() - { - return new File(world.getWorldFolder(), "subregion"); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/genobject/GenObject.java b/src/main/java/ninja/bytecode/iris/generator/genobject/GenObject.java deleted file mode 100644 index a884a7658..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/genobject/GenObject.java +++ /dev/null @@ -1,1110 +0,0 @@ -package ninja.bytecode.iris.generator.genobject; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.zip.GZIPInputStream; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.material.Directional; -import org.bukkit.material.Ladder; -import org.bukkit.material.Leaves; -import org.bukkit.material.MaterialData; -import org.bukkit.material.Stairs; -import org.bukkit.material.Vine; -import org.bukkit.util.BlockVector; -import org.bukkit.util.Vector; - -import mortar.compute.math.M; -import mortar.logic.format.F; -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.placer.NMSPlacer; -import ninja.bytecode.iris.util.Direction; -import ninja.bytecode.iris.util.IPlacer; -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.SBlockVector; -import ninja.bytecode.iris.util.SChunkVectorShort; -import ninja.bytecode.iris.util.VectorMath; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.io.CustomOutputStream; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.math.RNG; - -public class GenObject -{ - private boolean centeredHeight; - private int w; - private int h; - private int d; - private int failures; - private int successes; - private boolean gravity; - private boolean oversized; - private String name = "?"; - private KMap s; - private KMap slopeCache; - private KMap gravityCache; - private BlockVector mount; - private int maxslope; - private int baseslope; - private boolean hydrophilic; - private boolean submerged; - private int mountHeight; - private BlockVector shift; - - public GenObject(int w, int h, int d) - { - this.w = w; - oversized = false; - this.h = h; - this.d = d; - shift = new BlockVector(); - s = new KMap<>(); - centeredHeight = false; - gravity = false; - maxslope = -1; - baseslope = 0; - hydrophilic = false; - submerged = false; - } - - public void recalculateMountShift() - { - int ly = Integer.MAX_VALUE; - - for(SBlockVector i : s.keySet()) - { - if(i.getY() < ly) - { - ly = (int) i.getY(); - } - } - - KList fmount = new KList<>(); - - for(SBlockVector i : s.keySet()) - { - if(i.getY() == ly) - { - fmount.add(i); - } - } - - double avx[] = new double[fmount.size()]; - double avy[] = new double[fmount.size()]; - double avz[] = new double[fmount.size()]; - int c = 0; - - for(SBlockVector i : fmount) - { - avx[c] = i.getX(); - avy[c] = i.getY(); - avz[c] = i.getZ(); - c++; - } - - mountHeight = avg(avy); - mount = new BlockVector(0, 0, 0); - } - - private KMap getSlopeCache() - { - if(slopeCache == null) - { - computeSlopeCache(); - } - - return slopeCache; - } - - private KMap getGravityCache() - { - if(gravityCache == null) - { - computeGravityCache(); - } - - return gravityCache; - } - - private void computeGravityCache() - { - gravityCache = new KMap<>(); - - for(SBlockVector i : s.keySet()) - { - SChunkVectorShort v = new SChunkVectorShort(i.getX(), i.getZ()); - - if(!gravityCache.containsKey(v) || gravityCache.get(v).getY() > i.getY()) - { - gravityCache.put(v, i); - } - } - } - - private void computeSlopeCache() - { - slopeCache = new KMap<>(); - int low = Integer.MAX_VALUE; - - for(SBlockVector i : s.keySet()) - { - SChunkVectorShort v = new SChunkVectorShort(i.getX(), i.getZ()); - - if(!slopeCache.containsKey(v) || slopeCache.get(v).getY() > i.getY()) - { - slopeCache.put(v, i); - } - } - - for(SChunkVectorShort i : slopeCache.keySet()) - { - int f = (int) slopeCache.get(i).getY(); - - if(f < low) - { - low = f; - } - } - - for(SChunkVectorShort i : slopeCache.k()) - { - int f = (int) slopeCache.get(i).getY(); - - if(f > low - baseslope) - { - slopeCache.remove(i); - } - } - } - - private int avg(double[] v) - { - double g = 0; - - for(int i = 0; i < v.length; i++) - { - g += v[i]; - } - - return (int) Math.round(g / (double) v.length); - } - - public void setCenteredHeight() - { - this.centeredHeight = true; - } - - public int getW() - { - return w; - } - - public int getH() - { - return h; - } - - public int getD() - { - return d; - } - - public KMap getSchematic() - { - return s; - } - - public int getWidth() - { - return w; - } - - public int getDepth() - { - return d; - } - - public void read(InputStream in, boolean gzip) throws IOException - { - @SuppressWarnings("resource") - GZIPInputStream gzi = gzip ? new GZIPInputStream(in) : null; - DataInputStream din = new DataInputStream(gzip ? gzi : in); - readDirect(din); - din.close(); - } - - @SuppressWarnings("deprecation") - public void readDirect(DataInputStream din) throws IOException - { - w = din.readInt(); - h = din.readInt(); - d = din.readInt(); - int l = din.readInt(); - clear(); - - for(int i = 0; i < l; i++) - { - s.put(new SBlockVector(din.readInt(), din.readInt(), din.readInt()), new MB(Material.getMaterial((int) din.readInt()), din.readInt())); - } - } - - @SuppressWarnings("deprecation") - public void writeDirect(DataOutputStream dos) throws IOException - { - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(d); - dos.writeInt(s.size()); - - for(SBlockVector i : s.keySet()) - { - dos.writeInt((int) i.getX()); - dos.writeInt((int) i.getY()); - dos.writeInt((int) i.getZ()); - dos.writeInt(s.get(i).material.getId()); - dos.writeInt(s.get(i).data); - } - } - - public void write(OutputStream out, boolean gzip) throws IOException - { - CustomOutputStream cos = gzip ? new CustomOutputStream(out, 9) : null; - DataOutputStream dos = new DataOutputStream(gzip ? cos : out); - writeDirect(dos); - dos.close(); - } - - public MB get(int x, int y, int z) - { - return s.get(new SBlockVector(x, y, z)); - } - - public boolean has(int x, int y, int z) - { - return s.containsKey(new SBlockVector(x, y, z)); - } - - public void put(int x, int y, int z, MB mb) - { - s.put(new SBlockVector(x, y, z), mb); - } - - public GenObject copy() - { - GenObject s = new GenObject(w, h, d); - s.fill(this.s); - s.centeredHeight = centeredHeight; - s.name = name; - s.oversized = oversized; - return s; - } - - public void clear() - { - s.clear(); - } - - public void fill(KMap b) - { - clear(); - s.putAll(b); - } - - public int sh(int g) - { - int m = (g / 2); - return g % 2 == 0 ? m : m + 1; - } - - public Location place(Location l) - { - NMSPlacer p; - Location ll = place(l, p = new NMSPlacer(l.getWorld())); - p.flush(); - - return ll; - } - - public Location place(Location l, IPlacer placer) - { - return place(l.getBlockX(), l.getBlockY(), l.getBlockZ(), placer); - } - - @SuppressWarnings("deprecation") - public Location place(int wx, int wy, int wz, IPlacer placer) - { - Location start = new Location(placer.getWorld(), wx, wy, wz).clone().add(0, sh(h) + 1, 0); - - if(mount == null) - { - recalculateMountShift(); - } - - start.subtract(mount); - - int highestY = submerged ? placer.getHighestYUnderwater(start) : placer.getHighestY(start); - - if(start.getBlockY() + mountHeight > highestY) - { - start.subtract(0, start.getBlockY() + mountHeight - highestY, 0); - } - - start.add(shift); - KMap undo = new KMap<>(); - - for(SBlockVector i : s.keySet()) - { - MB b = getSchematic().get(i); - - if(b.material.equals(Material.LEAVES) || b.material.equals(Material.LEAVES_2)) - { - Leaves l = new Leaves(b.material, b.data); - l.setDecayable(false); - l.setDecaying(false); - b = new MB(l.getItemType(), l.getData()); - } - - Location f = start.clone().add(i.toBlockVector()); - - if(gravity) - { - SChunkVectorShort v = new SChunkVectorShort(i.getX(), i.getZ()); - int offset = (int) i.getY() - (int) getGravityCache().get(v).getY(); - f.setY(f.getBlockY() - ((f.getBlockY() - offset) - (submerged ? placer.getHighestYUnderwater(f) : placer.getHighestY(f)))); - } - - else if(maxslope >= 0) - { - SChunkVectorShort v = new SChunkVectorShort(i.getX(), i.getZ()); - SBlockVector m = getSlopeCache().get(v); - - if(m == null) - { - continue; - } - - int offset = (int) i.getY() - (int) m.getY(); - int shift = ((f.getBlockY() - offset) - (submerged ? placer.getHighestYUnderwater(f) : placer.getHighestY(f))); - - if(Math.abs(shift) > maxslope) - { - for(Location j : undo.k()) - { - placer.set(j, undo.get(j)); - } - - if(Iris.settings.performance.verbose) - { - L.w(C.WHITE + "Object " + C.YELLOW + getName() + C.WHITE + " failed to place on slope " + C.YELLOW + Math.abs(shift) + C.WHITE + " at " + C.YELLOW + F.f(f.getBlockX()) + " " + F.f(f.getBlockY()) + " " + F.f(f.getBlockZ())); - } - - failures++; - return null; - } - } - - if(!hydrophilic && !Iris.settings.performance.noObjectFail) - { - if(f.getBlockY() == 63 && i.getY() == mountHeight) - { - Material m = placer.get(f.clone().subtract(0, 1, 0)).material; - - if(m.equals(Material.WATER) || m.equals(Material.STATIONARY_WATER) || m.equals(Material.LAVA) || m.equals(Material.STATIONARY_LAVA)) - { - for(Location j : undo.k()) - { - placer.set(j, undo.get(j)); - } - - if(Iris.settings.performance.verbose) - { - L.w(C.WHITE + "Object " + C.YELLOW + getName() + C.WHITE + " (hydrophobic) failed to place in " + C.YELLOW + m.toString().toLowerCase() + C.WHITE + " at " + C.YELLOW + F.f(f.getBlockX()) + " " + F.f(f.getBlockY()) + " " + F.f(f.getBlockZ())); - } - - failures++; - return null; - } - } - } - - try - { - undo.put(f, placer.get(f)); - placer.set(f, b); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - successes++; - return start; - } - - public static GenObject load(InputStream in) throws IOException - { - GenObject s = new GenObject(1, 1, 1); - s.read(in, true); - - return s; - } - - public static GenObject load(File f) throws IOException - { - GenObject s = new GenObject(1, 1, 1); - s.name = f.getName().replaceAll("\\Q.ish\\E", ""); - FileInputStream fin = new FileInputStream(f); - s.read(fin, true); - - return s; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public void rotate(Direction from, Direction to) - { - KMap g = new KMap<>(); - g.putAll(s); - s.clear(); - - for(SBlockVector i : g.keySet()) - { - MB mb = rotate(from, to, g.get(i)); - s.put(new SBlockVector(VectorMath.rotate(from, to, i.toBlockVector()).toBlockVector()), mb); - } - - name = name + "-rt" + to.name(); - } - - @SuppressWarnings("deprecation") - private MB rotate(Direction from, Direction to, MB mb) - { - try - { - Material t = mb.material; - int i = t.getId(); - byte d = mb.data; - MaterialData data = t.getData().getConstructor(int.class, byte.class).newInstance(i, d); - - if(data instanceof Directional) - { - Directional dir = (Directional) data; - Supplier get = dir::getFacing; - Consumer set = dir::setFacingDirection; - - if(dir instanceof Ladder) - { - get = ((Ladder) dir)::getAttachedFace; - set = ((Ladder) dir)::setFacingDirection; - } - - if(dir instanceof Stairs) - { - get = ((Stairs) dir)::getAscendingDirection; - set = ((Stairs) dir)::setFacingDirection; - } - - BlockFace fac = get.get(); - set.accept(rotate(from, to, fac)); - d = data.getData(); - t = data.getItemType(); - return MB.of(t, d); - } - - else if(data instanceof Vine) - { - Vine vin = (Vine) data; - Vine vif = new Vine(); - - for(Direction j : Direction.news()) - { - if(vin.isOnFace(j.getFace())) - { - vif.putOnFace(rotate(from, to, j.getFace())); - } - } - - d = vif.getData(); - t = vif.getItemType(); - return MB.of(t, d); - } - - else if(i >= 235 && i <= 250) - { - BlockFace fac = getGlazedTCDir(d); - d = toGlazedTCDir(Direction.getDirection(rotate(from, to, fac)).getFace()); - t = data.getItemType(); - return MB.of(t, d); - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } - - return mb; - } - - private byte toGlazedTCDir(BlockFace b) - { - switch(b) - { - case NORTH: - return 0; - case EAST: - return 1; - case SOUTH: - return 2; - case WEST: - return 3; - default: - break; - } - - return 0; - } - - private BlockFace getGlazedTCDir(byte d2) - { - switch(d2) - { - case 0: - return BlockFace.NORTH; - case 1: - return BlockFace.EAST; - case 2: - return BlockFace.SOUTH; - case 3: - return BlockFace.WEST; - } - - return BlockFace.NORTH; - } - - private BlockFace rotate(Direction from, Direction to, BlockFace face) - { - return Direction.getDirection(from.angle(Direction.getDirection(face).toVector(), to)).getFace(); - } - - public void computeFlag(String j) - { - try - { - if(j.equals("gravity")) - { - gravity = true; - } - - if(j.equals("hydrophilic")) - { - hydrophilic = true; - } - - if(j.equals("submerged")) - { - submerged = true; - hydrophilic = true; - } - - if(j.startsWith("maxslope ")) - { - maxslope = Integer.valueOf(j.split("\\Q \\E")[1]); - } - - if(j.startsWith("baseslope ")) - { - baseslope = Integer.valueOf(j.split("\\Q \\E")[1]); - } - - if(j.startsWith("replace ")) - { - String[] g = j.split("\\Q \\E"); - MB a = MB.of(g[1]); - boolean specific = g[1].contains(":"); - MB b = MB.of(g[2]); - - for(SBlockVector i : s.k()) - { - MB c = s.get(i); - - if((specific && c.equals(a)) || c.material.equals(a.material)) - { - s.put(i, b); - } - } - } - - if(j.startsWith("sink ")) - { - int downshift = Integer.valueOf(j.split("\\Q \\E")[1]); - shift.subtract(new Vector(0, downshift, 0)); - } - - if(j.startsWith("raise ")) - { - int downshift = Integer.valueOf(j.split("\\Q \\E")[1]); - shift.add(new Vector(0, downshift, 0)); - } - } - - catch(Throwable e) - { - L.f("Failed to compute flag '" + j + "'"); - L.ex(e); - } - } - - public void applySnowFilter(int factor) - { - int minX = 0; - int maxX = 0; - int minY = 0; - int maxY = 0; - int minZ = 0; - int maxZ = 0; - boolean added = false; - - for(SBlockVector i : getSchematic().keySet()) - { - if(i.getX() > maxX) - { - maxX = (int) i.getX(); - } - - if(i.getY() > maxY) - { - maxY = (int) i.getY(); - } - - if(i.getZ() > maxZ) - { - maxZ = (int) i.getZ(); - } - - if(i.getX() < minX) - { - minX = (int) i.getX(); - } - - if(i.getY() < minY) - { - minY = (int) i.getY(); - } - - if(i.getZ() < minZ) - { - minZ = (int) i.getZ(); - } - } - - for(int i = minX; i <= maxX; i++) - { - for(int j = minZ; j <= maxZ; j++) - { - SBlockVector highest = null; - - for(SBlockVector k : getSchematic().keySet()) - { - if(k.getX() == i && k.getZ() == j) - { - if(highest == null) - { - highest = k; - } - - else if(highest.getY() < k.getY()) - { - highest = k; - } - } - } - - if(highest != null) - { - BlockVector mbv = highest.toBlockVector().add(new Vector(0, 1, 0)).toBlockVector(); - added = true; - getSchematic().put(new SBlockVector(mbv), MB.of(Material.SNOW, RNG.r.nextInt((int) M.clip(factor, 1, 8)))); - } - } - } - - if(added) - { - h++; - recalculateMountShift(); - } - } - - @SuppressWarnings("deprecation") - public void applyLushFilter(double factor) - { - int minX = 0; - int maxX = 0; - int minY = 0; - int maxY = 0; - int minZ = 0; - int maxZ = 0; - boolean added = false; - - for(SBlockVector i : getSchematic().keySet()) - { - if(i.getX() > maxX) - { - maxX = (int) i.getX(); - } - - if(i.getY() > maxY) - { - maxY = (int) i.getY(); - } - - if(i.getZ() > maxZ) - { - maxZ = (int) i.getZ(); - } - - if(i.getX() < minX) - { - minX = (int) i.getX(); - } - - if(i.getY() < minY) - { - minY = (int) i.getY(); - } - - if(i.getZ() < minZ) - { - minZ = (int) i.getZ(); - } - } - - for(int i = minX; i <= maxX; i++) - { - for(int j = minY; j <= maxY; j++) - { - for(int k = minZ; k <= maxZ; k++) - { - SBlockVector at = new SBlockVector(i, j, k); - - if(M.r(factor / 25D) && getSchematic().containsKey(at) && !getSchematic().get(at).material.equals(Material.VINE)) - { - SBlockVector a = new SBlockVector(i + 1, j, k); - SBlockVector b = new SBlockVector(i - 1, j, k); - SBlockVector c = new SBlockVector(i, j, k + 1); - SBlockVector d = new SBlockVector(i, j, k - 1); - Vine v = null; - KMap e = new KMap<>(); - - if(!getSchematic().containsKey(a)) - { - v = new Vine(BlockFace.WEST); - SBlockVector ma = new SBlockVector(a.getX(), a.getY(), a.getZ() + 1); - SBlockVector mb = new SBlockVector(a.getX(), a.getY(), a.getZ() - 1); - - if(getSchematic().containsKey(ma) && !getSchematic().get(ma).material.equals(Material.VINE)) - { - v = new Vine(BlockFace.SOUTH, BlockFace.WEST); - } - - else if(getSchematic().containsKey(mb) && !getSchematic().get(mb).material.equals(Material.VINE)) - { - v = new Vine(BlockFace.NORTH, BlockFace.WEST); - } - - e.put(a, MB.of(Material.VINE, v.getData())); - } - - if(!getSchematic().containsKey(b)) - { - v = new Vine(BlockFace.EAST); - SBlockVector ma = new SBlockVector(b.getX(), b.getY(), b.getZ() + 1); - SBlockVector mb = new SBlockVector(b.getX(), b.getY(), b.getZ() - 1); - - if(getSchematic().containsKey(ma) && !getSchematic().get(ma).material.equals(Material.VINE)) - { - v = new Vine(BlockFace.SOUTH, BlockFace.EAST); - } - - else if(getSchematic().containsKey(mb) && !getSchematic().get(mb).material.equals(Material.VINE)) - { - v = new Vine(BlockFace.NORTH, BlockFace.EAST); - } - - e.put(b, MB.of(Material.VINE, v.getData())); - } - - if(!getSchematic().containsKey(c)) - { - v = new Vine(BlockFace.NORTH); - SBlockVector ma = new SBlockVector(c.getX() + 1, c.getY(), c.getZ()); - SBlockVector mb = new SBlockVector(c.getX() - 1, c.getY(), c.getZ()); - - if(getSchematic().containsKey(ma) && !getSchematic().get(ma).material.equals(Material.VINE)) - { - v = new Vine(BlockFace.NORTH, BlockFace.EAST); - } - - else if(getSchematic().containsKey(mb) && !getSchematic().get(mb).material.equals(Material.VINE)) - { - v = new Vine(BlockFace.NORTH, BlockFace.WEST); - } - - e.put(c, MB.of(Material.VINE, v.getData())); - } - - if(!getSchematic().containsKey(d)) - { - v = new Vine(BlockFace.SOUTH); - SBlockVector ma = new SBlockVector(d.getX() + 1, d.getY(), d.getZ()); - SBlockVector mb = new SBlockVector(d.getX() - 1, d.getY(), d.getZ()); - - if(getSchematic().containsKey(ma) && !getSchematic().get(ma).material.equals(Material.VINE)) - { - v = new Vine(BlockFace.SOUTH, BlockFace.EAST); - } - - else if(getSchematic().containsKey(mb) && !getSchematic().get(mb).material.equals(Material.VINE)) - { - v = new Vine(BlockFace.SOUTH, BlockFace.WEST); - } - - e.put(d, MB.of(Material.VINE, v.getData())); - } - - if(!e.isEmpty()) - { - added = true; - } - - for(SBlockVector n : e.k()) - { - for(int g = 0; g < (factor * 2) * RNG.r.nextDouble(); g++) - { - if(n.getY() - (g + 1) < minY) - { - break; - } - - SBlockVector p = new SBlockVector(n.getX(), n.getY() - g, n.getZ()); - - if(e.containsKey(p) || getSchematic().containsKey(p)) - { - break; - } - - e.put(p, e.get(n)); - } - } - - getSchematic().putAll(e); - } - } - } - } - - if(added) - { - w++; - d++; - recalculateMountShift(); - } - } - - public double getSuccess() - { - return (double) successes / ((double) successes + (double) failures); - } - - public int getFailures() - { - return failures; - } - - public int getSuccesses() - { - return successes; - } - - public int getPlaces() - { - return successes + failures; - } - - public void dispose() - { - s.clear(); - } - - public void setGravity(boolean gravity) - { - this.gravity = gravity; - } - - public void setShift(int x, int y, int z) - { - shift = new BlockVector(x, y, z); - } - - public boolean isCenteredHeight() - { - return centeredHeight; - } - - public boolean isGravity() - { - return gravity; - } - - public KMap getS() - { - return s; - } - - public BlockVector getMount() - { - return mount; - } - - public int getMaxslope() - { - return maxslope; - } - - public int getBaseslope() - { - return baseslope; - } - - public boolean isHydrophilic() - { - return hydrophilic; - } - - public boolean isSubmerged() - { - return submerged; - } - - public int getMountHeight() - { - return mountHeight; - } - - public BlockVector getShift() - { - return shift; - } - - public void setCenteredHeight(boolean centeredHeight) - { - this.centeredHeight = centeredHeight; - } - - public void setW(int w) - { - this.w = w; - } - - public void setH(int h) - { - this.h = h; - } - - public void setD(int d) - { - this.d = d; - } - - public void setFailures(int failures) - { - this.failures = failures; - } - - public void setSuccesses(int successes) - { - this.successes = successes; - } - - public void setS(KMap s) - { - this.s = s; - } - - public void setSlopeCache(KMap slopeCache) - { - this.slopeCache = slopeCache; - } - - public void setGravityCache(KMap gravityCache) - { - this.gravityCache = gravityCache; - } - - public void setMount(BlockVector mount) - { - this.mount = mount; - } - - public void setMaxslope(int maxslope) - { - this.maxslope = maxslope; - } - - public void setBaseslope(int baseslope) - { - this.baseslope = baseslope; - } - - public void setHydrophilic(boolean hydrophilic) - { - this.hydrophilic = hydrophilic; - } - - public void setSubmerged(boolean submerged) - { - this.submerged = submerged; - } - - public void setMountHeight(int mountHeight) - { - this.mountHeight = mountHeight; - } - - public void setShift(BlockVector shift) - { - this.shift = shift; - } - - public boolean isOversized() - { - return oversized; - } - - public void setOversized(boolean oversized) - { - this.oversized = oversized; - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/genobject/GenObjectDecorator.java b/src/main/java/ninja/bytecode/iris/generator/genobject/GenObjectDecorator.java deleted file mode 100644 index b65309260..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/genobject/GenObjectDecorator.java +++ /dev/null @@ -1,463 +0,0 @@ -package ninja.bytecode.iris.generator.genobject; - -import java.util.Collections; -import java.util.Random; - -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.generator.BlockPopulator; - -import mortar.api.sched.S; -import mortar.logic.format.F; -import mortar.util.text.C; -import net.md_5.bungee.api.ChatColor; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.parallax.ParallaxCache; -import ninja.bytecode.iris.generator.placer.AtomicParallaxPlacer; -import ninja.bytecode.iris.generator.placer.BukkitPlacer; -import ninja.bytecode.iris.generator.placer.NMSPlacer; -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.iris.util.IPlacer; -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.ObjectMode; -import ninja.bytecode.iris.util.SMCAVector; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.collections.KSet; -import ninja.bytecode.shuriken.execution.ChronoLatch; -import ninja.bytecode.shuriken.execution.J; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.math.M; -import ninja.bytecode.shuriken.math.RNG; - -public class GenObjectDecorator extends BlockPopulator -{ - private KList placeHistory; - private KMap> orderCache; - private KMap> populationCache; - private IPlacer placer; - private IrisGenerator g; - private ChronoLatch cl = new ChronoLatch(250); - - public GenObjectDecorator(IrisGenerator generator) - { - this.g = generator; - placeHistory = new KList<>(); - populationCache = new KMap<>(); - orderCache = new KMap<>(); - - for(IrisBiome i : generator.getDimension().getBiomes()) - { - KMap gc = new KMap<>(); - KMap> or = new KMap<>(); - int ff = 0; - for(String j : i.getSchematicGroups().k()) - { - double c = i.getSchematicGroups().get(j); - - try - { - GenObjectGroup g = generator.getDimension().getObjectGroup(j); - ff += g.size(); - gc.put(g, c); - - if(!or.containsKey(g.getPiority())) - { - or.put(g.getPiority(), new KList<>()); - } - - or.get(g.getPiority()).add(g); - } - - catch(Throwable e) - { - L.f(ChatColor.RED + "Failed to inject " + j + " into GenObjectDecorator"); - L.ex(e); - } - } - - if(!gc.isEmpty()) - { - KList g = new KList<>(); - for(KList j : or.v()) - { - g.addAll(j); - } - - Collections.sort(g, (a, b) -> a.getPiority() - b.getPiority()); - orderCache.put(i, g); - populationCache.put(i, gc); - - if(Iris.settings.performance.verbose) - { - L.v(C.DARK_GREEN + i.getName() + ": " + C.DARK_AQUA + F.f(ff) + " Objects"); - } - } - } - - L.i("Population Cache is " + populationCache.size()); - } - - @Override - public void populate(World world, Random random, Chunk source) - { - Runnable m = () -> - { - try - { - if(g.isDisposed()) - { - placeHistory.clear(); - return; - } - - KSet hits = new KSet<>(); - int cx = source.getX(); - int cz = source.getZ(); - - for(int i = 0; i < Iris.settings.performance.decorationAccuracy; i++) - { - int x = (cx << 4) + random.nextInt(16); - int z = (cz << 4) + random.nextInt(16); - IrisBiome biome = g.getBiome((int) g.getOffsetX(x, z), (int) g.getOffsetZ(x, z)); - - if(hits.contains(biome)) - { - continue; - } - - KMap objects = populationCache.get(biome); - - if(objects == null) - { - continue; - } - - hits.add(biome); - populate(world, cx, cz, random, biome); - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } - }; - - if(Iris.settings.performance.objectMode.equals(ObjectMode.QUICK_N_DIRTY)) - { - J.a(m); - } - - else - { - m.run(); - } - } - - @SuppressWarnings("deprecation") - private void populate(World world, int cx, int cz, Random random, IrisBiome biome) - { - for(GenObjectGroup i : orderCache.get(biome)) - { - if(biome.getSchematicGroups().get(i.getName()) == null) - { - L.w(C.YELLOW + "Cannot find chance for " + C.RED + i.getName() + C.YELLOW + " in Biome " + C.RED + biome.getName()); - continue; - } - - for(int j = 0; j < getTries(biome.getSchematicGroups().get(i.getName())); j++) - { - if(M.r(Iris.settings.gen.objectDensity)) - { - GenObject go = i.getSchematics().get(random.nextInt(i.getSchematics().size())); - int x = (cx << 4) + random.nextInt(16); - int z = (cz << 4) + random.nextInt(16); - - if(i.getWorldChance() >= 0D) - { - int rngx = (int) Math.floor(x / (double) (i.getWorldRadius() == 0 ? 32 : i.getWorldRadius())); - int rngz = (int) Math.floor(z / (double) (i.getWorldRadius() == 0 ? 32 : i.getWorldRadius())); - - if(new RNG(new SMCAVector(rngx, rngz).hashCode()).nextDouble() < i.getWorldChance()) - { - if(Iris.settings.performance.verbose) - { - L.w(C.WHITE + "Object " + C.YELLOW + i.getName() + "/*" + C.WHITE + " failed to place due to a world chance."); - } - - break; - } - } - - int by = world.getHighestBlockYAt(x, z); - Block b = world.getBlockAt(x, by - 1, z); - MB mb = MB.of(b.getType(), b.getData()); - - if(!Iris.settings.performance.noObjectFail) - { - if(!mb.material.isSolid() || !biome.isSurface(mb.material)) - { - if(Iris.settings.performance.verbose) - { - L.w(C.WHITE + "Object " + C.YELLOW + i.getName() + "/*" + C.WHITE + " failed to place in " + C.YELLOW + mb.material.toString().toLowerCase() + C.WHITE + " at " + C.YELLOW + F.f(x) + " " + F.f(by) + " " + F.f(z)); - } - - return; - } - } - - if(Iris.settings.performance.objectMode.equals(ObjectMode.QUICK_N_DIRTY)) - { - placer = new NMSPlacer(world); - } - - else if(Iris.settings.performance.objectMode.equals(ObjectMode.LIGHTING_PHYSICS)) - { - placer = new BukkitPlacer(world, true); - } - - else if(Iris.settings.performance.objectMode.equals(ObjectMode.LIGHTING)) - { - placer = new BukkitPlacer(world, false); - } - - Runnable rx = () -> - { - Location start = go.place(x, by, z, placer); - - if(start != null) - { - g.hitObject(); - if(Iris.settings.performance.verbose) - { - L.v(C.GRAY + "Placed " + C.DARK_GREEN + i.getName() + C.WHITE + "/" + C.DARK_GREEN + go.getName() + C.GRAY + " at " + C.DARK_GREEN + F.f(start.getBlockX()) + " " + F.f(start.getBlockY()) + " " + F.f(start.getBlockZ())); - } - - if(Iris.settings.performance.debugMode) - { - placeHistory.add(new PlacedObject(start.getBlockX(), start.getBlockY(), start.getBlockZ(), i.getName() + ":" + go.getName())); - - if(placeHistory.size() > Iris.settings.performance.placeHistoryLimit) - { - while(placeHistory.size() > Iris.settings.performance.placeHistoryLimit) - { - placeHistory.remove(0); - } - } - } - } - }; - - if(Iris.settings.performance.objectMode.equals(ObjectMode.QUICK_N_DIRTY)) - { - new S(20) - { - @Override - public void run() - { - rx.run(); - } - }; - } - - else - { - rx.run(); - } - } - } - } - - if(placer != null && cl.flip()) - { - placer.flush(); - } - } - - public void populateParallax(int cx, int cz, Random random) - { - try - { - if(g.isDisposed()) - { - placeHistory.clear(); - return; - } - - ParallaxCache cache = new ParallaxCache(g); - KSet hits = new KSet<>(); - - for(int i = 0; i < Iris.settings.performance.decorationAccuracy; i++) - { - int x = (cx << 4) + random.nextInt(16); - int z = (cz << 4) + random.nextInt(16); - IrisBiome biome = cache.getBiome(x, z); - - if(hits.contains(biome)) - { - continue; - } - - KMap objects = populationCache.get(biome); - - if(objects == null) - { - continue; - } - - hits.add(biome); - populateParallax(cx, cz, random, biome, cache); - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - private void populateParallax(int cx, int cz, Random random, IrisBiome biome, ParallaxCache cache) - { - for(GenObjectGroup i : orderCache.get(biome)) - { - if(biome.getSchematicGroups().get(i.getName()) == null) - { - L.w(C.YELLOW + "Cannot find chance for " + C.RED + i.getName() + C.YELLOW + " in Biome " + C.RED + biome.getName()); - continue; - } - - for(int j = 0; j < getTries(biome.getSchematicGroups().get(i.getName())); j++) - { - if(M.r(Iris.settings.gen.objectDensity)) - { - if(i.getSchematics().isEmpty()) - { - continue; - } - - GenObject go = i.getSchematics().get(random.nextInt(i.getSchematics().size())); - int x = (cx << 4) + random.nextInt(16); - int z = (cz << 4) + random.nextInt(16); - - if(i.getWorldChance() >= 0D) - { - int rngx = (int) Math.floor(x / (double) (i.getWorldRadius() == 0 ? 32 : i.getWorldRadius())); - int rngz = (int) Math.floor(z / (double) (i.getWorldRadius() == 0 ? 32 : i.getWorldRadius())); - - if(new RNG(new SMCAVector(rngx, rngz).hashCode()).nextDouble() < i.getWorldChance()) - { - if(Iris.settings.performance.verbose) - { - L.w(C.WHITE + "Object " + C.YELLOW + i.getName() + "/*" + C.WHITE + " failed to place due to a world chance."); - } - - break; - } - } - - int by = cache.getHeight(x, z); - MB mb = cache.get(x, by, z); - - if(!Iris.settings.performance.noObjectFail) - { - if(!mb.material.isSolid() || !biome.isSurface(mb.material)) - { - if(Iris.settings.performance.verbose) - { - L.w(C.WHITE + "Object " + C.YELLOW + i.getName() + "/*" + C.WHITE + " failed to place in " + C.YELLOW + mb.material.toString().toLowerCase() + C.WHITE + " at " + C.YELLOW + F.f(x) + " " + F.f(by) + " " + F.f(z)); - } - - return; - } - } - - placer = new AtomicParallaxPlacer(g, cache); - Location start = go.place(x, by, z, placer); - - if(start != null) - { - g.hitObject(); - if(Iris.settings.performance.verbose) - { - L.v(C.GRAY + "Placed " + C.DARK_GREEN + i.getName() + C.WHITE + "/" + C.DARK_GREEN + go.getName() + C.GRAY + " at " + C.DARK_GREEN + F.f(start.getBlockX()) + " " + F.f(start.getBlockY()) + " " + F.f(start.getBlockZ())); - } - - if(Iris.settings.performance.debugMode) - { - placeHistory.add(new PlacedObject(start.getBlockX(), start.getBlockY(), start.getBlockZ(), i.getName() + ":" + go.getName())); - - if(placeHistory.size() > Iris.settings.performance.placeHistoryLimit) - { - while(placeHistory.size() > Iris.settings.performance.placeHistoryLimit) - { - placeHistory.remove(0); - } - } - } - } - } - } - } - - if(placer != null && cl.flip()) - { - placer.flush(); - } - } - - public int getTries(double chance) - { - if(chance <= 0) - { - return 0; - } - - if(Math.floor(chance) == chance) - { - return (int) chance; - } - - int floor = (int) Math.floor(chance); - - if(chance - floor > 0 && M.r(chance - floor)) - { - floor++; - } - - return floor; - } - - public KList getHistory() - { - return placeHistory; - } - - public void dispose() - { - - } - - public PlacedObject randomObject(String string) - { - KList v = new KList<>(); - - for(PlacedObject i : placeHistory) - { - if(i.getF().toLowerCase().replaceAll("\\Q:\\E", "/").startsWith(string.toLowerCase())) - { - v.add(i); - } - } - - if(v.isEmpty()) - { - return null; - } - - return v.getRandom(); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/genobject/GenObjectGroup.java b/src/main/java/ninja/bytecode/iris/generator/genobject/GenObjectGroup.java deleted file mode 100644 index f2b1dc40a..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/genobject/GenObjectGroup.java +++ /dev/null @@ -1,387 +0,0 @@ -package ninja.bytecode.iris.generator.genobject; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.function.Consumer; - -import net.md_5.bungee.api.ChatColor; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.util.Direction; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.format.Form; -import ninja.bytecode.shuriken.io.IO; -import ninja.bytecode.shuriken.logging.L; - -public class GenObjectGroup -{ - private KList schematics; - private KList osSchematics; - private KList pxSchematics; - private KList flags; - private String name; - private int priority; - private double worldChance; - private int worldRad; - - public GenObjectGroup(String name) - { - this.schematics = new KList<>(); - this.flags = new KList<>(); - this.name = name; - priority = Integer.MIN_VALUE; - worldChance = Integer.MIN_VALUE; - worldRad = 32; - } - - public void read(DataInputStream din) throws IOException - { - flags.clear(); - schematics.clear(); - name = din.readUTF(); - int fl = din.readInt(); - int sc = din.readInt(); - - for(int i = 0; i < fl; i++) - { - flags.add(din.readUTF()); - } - - for(int i = 0; i < sc; i++) - { - GenObject g = new GenObject(0, 0, 0); - g.readDirect(din); - schematics.add(g); - } - } - - public void write(DataOutputStream dos, Consumer progress) throws IOException - { - dos.writeUTF(name); - dos.writeInt(flags.size()); - dos.writeInt(schematics.size()); - - for(String i : flags) - { - dos.writeUTF(i); - } - - int of = 0; - - if(progress != null) - { - progress.accept((double) of / (double) schematics.size()); - } - - for(GenObject i : schematics) - { - i.writeDirect(dos); - of++; - - if(progress != null) - { - progress.accept((double) of / (double) schematics.size()); - } - } - } - - public void applyLushFilter(double factor) - { - if(flags.contains("no lush")) - { - L.i(ChatColor.DARK_GREEN + "Skipping Lush Filter for " + ChatColor.GRAY + getName()); - return; - } - - L.i(ChatColor.GREEN + "Applying Lush Filter to " + ChatColor.WHITE + getName()); - - for(GenObject i : schematics) - { - i.applyLushFilter(factor); - } - } - - public void applySnowFilter(int factor) - { - if(flags.contains("no snow")) - { - L.i(ChatColor.DARK_AQUA + "Skipping Snow Filter for " + ChatColor.GRAY + getName()); - return; - } - - L.i(ChatColor.AQUA + "Applying Snow Filter to " + ChatColor.WHITE + getName()); - - for(GenObject i : schematics) - { - i.applySnowFilter(factor); - } - } - - public GenObjectGroup copy(String suffix) - { - GenObjectGroup gog = new GenObjectGroup(name + suffix); - gog.schematics = new KList<>(); - gog.flags = flags.copy(); - - for(GenObject i : schematics) - { - GenObject g = i.copy(); - g.setName(i.getName() + suffix); - gog.schematics.add(g); - } - - return gog; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public KList getSchematics() - { - return schematics; - } - - public KList getPXSchematics() - { - if(pxSchematics == null) - { - pxSchematics = new KList<>(); - - for(GenObject i : schematics) - { - if(!i.isOversized()) - { - pxSchematics.add(i); - } - } - } - - return pxSchematics; - } - - public KList getOSSchematics() - { - if(osSchematics == null) - { - osSchematics = new KList<>(); - - for(GenObject i : schematics) - { - if(i.isOversized()) - { - osSchematics.add(i); - } - } - } - - return pxSchematics; - } - - public void setSchematics(KList schematics) - { - this.schematics = schematics; - } - - public KList getFlags() - { - return flags; - } - - public void setFlags(KList flags) - { - this.flags = flags; - } - - public int size() - { - return getSchematics().size(); - } - - public int getPiority() - { - if(priority == Integer.MIN_VALUE) - { - for(String i : flags) - { - if(i.startsWith("priority ")) - { - priority = Integer.valueOf(i.split("\\Q \\E")[1]); - break; - } - } - } - - return priority; - } - - public static GenObjectGroup load(String string) - { - File folder = Iris.pack().loadFolder(string); - - if(folder != null) - { - GenObjectGroup g = new GenObjectGroup(string); - - for(File i : folder.listFiles()) - { - if(i.getName().endsWith(".ifl")) - { - try - { - g.flags.add(IO.readAll(i).split("\\Q\n\\E")); - } - - catch(IOException e) - { - L.ex(e); - } - } - - if(i.getName().endsWith(".ish")) - { - try - { - GenObject s = GenObject.load(i); - g.getSchematics().add(s); - } - - catch(IOException e) - { - L.f("Cannot load Schematic: " + string + "/" + i.getName()); - L.ex(e); - } - } - } - - return g; - } - - return null; - } - - public void processVariants() - { - for(GenObject i : getSchematics()) - { - i.recalculateMountShift(); - - for(String j : flags) - { - i.computeFlag(j); - } - } - - if(!flags.contains("no rotation")) - { - KList inject = new KList<>(); - for(GenObject i : getSchematics()) - { - for(Direction j : new Direction[] {Direction.S, Direction.E, Direction.W}) - { - GenObject cp = i.copy(); - GenObject f = cp; - f.rotate(Direction.N, j); - f.recalculateMountShift(); - inject.add(f); - } - } - - getSchematics().add(inject); - } - - L.i(ChatColor.LIGHT_PURPLE + "Processed " + ChatColor.WHITE + Form.f(schematics.size()) + ChatColor.LIGHT_PURPLE + " Schematics in " + ChatColor.WHITE + name); - } - - public void dispose() - { - for(GenObject i : schematics) - { - i.dispose(); - } - - schematics.clear(); - flags.clear(); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((flags == null) ? 0 : flags.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + priority; - return result; - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - return true; - if(obj == null) - return false; - if(getClass() != obj.getClass()) - return false; - GenObjectGroup other = (GenObjectGroup) obj; - if(flags == null) - { - if(other.flags != null) - return false; - } - else if(!flags.equals(other.flags)) - return false; - if(name == null) - { - if(other.name != null) - return false; - } - else if(!name.equals(other.name)) - return false; - if(priority != other.priority) - return false; - - return true; - } - - public double getWorldChance() - { - if(worldChance == Integer.MIN_VALUE) - { - for(String i : flags) - { - if(i.startsWith("world chance ")) - { - worldChance = Double.valueOf(i.split("\\Q \\E")[2]); - } - } - } - - return worldChance; - } - - public double getWorldRadius() - { - if(worldRad == Integer.MIN_VALUE) - { - for(String i : flags) - { - if(i.startsWith("world radius ")) - { - worldRad = Integer.valueOf(i.split("\\Q \\E")[2]); - } - } - } - - return worldRad; - } - -} diff --git a/src/main/java/ninja/bytecode/iris/generator/genobject/PlacedObject.java b/src/main/java/ninja/bytecode/iris/generator/genobject/PlacedObject.java deleted file mode 100644 index 62cd4b50f..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/genobject/PlacedObject.java +++ /dev/null @@ -1,95 +0,0 @@ -package ninja.bytecode.iris.generator.genobject; - -public class PlacedObject -{ - private int x; - private int y; - private int z; - private String f; - - public PlacedObject(int x, int y, int z, String f) - { - this.x = x; - this.y = y; - this.z = z; - this.f = f; - } - - public int getX() - { - return x; - } - - public void setX(int x) - { - this.x = x; - } - - public int getY() - { - return y; - } - - public void setY(int y) - { - this.y = y; - } - - public int getZ() - { - return z; - } - - public void setZ(int z) - { - this.z = z; - } - - public String getF() - { - return f; - } - - public void setF(String f) - { - this.f = f; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((f == null) ? 0 : f.hashCode()); - result = prime * result + x; - result = prime * result + y; - result = prime * result + z; - return result; - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - return true; - if(obj == null) - return false; - if(getClass() != obj.getClass()) - return false; - PlacedObject other = (PlacedObject) obj; - if(f == null) - { - if(other.f != null) - return false; - } - else if(!f.equals(other.f)) - return false; - if(x != other.x) - return false; - if(y != other.y) - return false; - if(z != other.z) - return false; - return true; - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/layer/BiomeNoiseGenerator.java b/src/main/java/ninja/bytecode/iris/generator/layer/BiomeNoiseGenerator.java deleted file mode 100644 index 125617acd..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/layer/BiomeNoiseGenerator.java +++ /dev/null @@ -1,34 +0,0 @@ -package ninja.bytecode.iris.generator.layer; - -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.RNG; - -public class BiomeNoiseGenerator -{ - protected IrisBiome biome; - protected CNG gen; - private double block = 1D / 255D; - - public BiomeNoiseGenerator(RNG rng, IrisBiome biome) - { - this.biome = biome; - //@builder - gen = new CNG(rng.nextParallelRNG(31289 - biome.getName().length() * biome.getRealBiome().ordinal()), 1D, 1) - .scale(0.0025 * biome.getGenScale()) - .fractureWith(new CNG(rng.nextParallelRNG(2922 * biome.getName().length() - biome.getRealBiome().ordinal()), 1D, 1) - .scale(0.0075 * biome.getGenSwirlScale()), 20D * biome.getGenSwirl()); - //@done - } - - public double getHeight(double x, double z) - { - if(biome.getGenAmplifier() == 0) - { - return 0; - } - - double r = block * 52; - return (gen.noise(x, z) * biome.getGenAmplifier() * r); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerBiome.java b/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerBiome.java deleted file mode 100644 index f2952cc0e..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerBiome.java +++ /dev/null @@ -1,217 +0,0 @@ -package ninja.bytecode.iris.generator.layer; - -import java.util.Random; -import java.util.function.Function; - -import org.bukkit.World; - -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.iris.pack.IrisRegion; -import ninja.bytecode.iris.util.BiomeLayer; -import ninja.bytecode.iris.util.Borders; -import ninja.bytecode.iris.util.GenLayer; -import ninja.bytecode.iris.util.PolygonGenerator; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.RNG; - -public class GenLayerBiome extends GenLayer -{ - private KMap regions; - private Function factory; - private CNG fracture; - private CNG fuzz; - private PolygonGenerator channel; - private PolygonGenerator ocean; - private BiomeLayer master; - - public GenLayerBiome(IrisGenerator iris, World world, Random random, RNG rng, KList biomes) - { - super(iris, world, random, rng); - //@builder - channel = new PolygonGenerator(rng.nextParallelRNG(-12), 2, 0.0005, 1, (g)->g.fractureWith(new CNG(rng.nextParallelRNG(34), 1D, 2) - .scale(0.01), 30)); - ocean = new PolygonGenerator(rng.nextParallelRNG(-11), 6, 0.005, 1, (g)->g.fractureWith(new CNG(rng.nextParallelRNG(34), 1D, 2) - .scale(0.01), 150)); - fuzz = new CNG(rng.nextParallelRNG(9112), 1D * 12 * Iris.settings.gen.biomeEdgeFuzzScale, 1).scale(6.5); - fracture = new CNG(rng.nextParallelRNG(28), 1D, 4).scale(0.0021 * Iris.settings.gen.biomeEdgeScrambleScale) - .fractureWith(new CNG(rng.nextParallelRNG(34), 1D, 2) - .scale(0.01), 12250); - factory = (g) -> g.fractureWith(new CNG(rng.nextParallelRNG(29), 1D, 3) - .scale(0.005 * Iris.settings.gen.biomeScale), 1024D / Iris.settings.gen.biomeScale) - .fractureWith(new CNG(rng.nextParallelRNG(1212), 1D, 2) - .scale(0.04) - .fractureWith(new CNG(rng.nextParallelRNG(1216), 1D, 3).scale(0.0004), 266), 66); - //@done - regions = new KMap<>(); - - for(IrisBiome i : biomes) - { - if(i.getRegionID().equals("default")) - { - continue; - } - - if(!regions.containsKey(i.getRegionID())) - { - regions.put(i.getRegionID(), new IrisRegion(i.getRegionID())); - } - - regions.get(i.getRegionID()).getBiomes().add(i); - } - - for(IrisRegion i : regions.values()) - { - i.load(); - } - - int m = 0; - - for(IrisBiome i : iris.getDimension().getBiomes()) - { - i.seal(iris.getRTerrain().nextParallelRNG(3922 - m++)); - } - - master = BiomeLayer.compile(iris, 0.082 * Iris.settings.gen.biomeScale * 0.189, 1, factory); - - if(Iris.settings.performance.verbose) - { - master.print(2); - } - } - - public IrisBiome getBiome(double wxx, double wzx) - { - return getBiome(wxx, wzx, false); - } - - public boolean isNearAquatic(int wxx, int wzx) - { - double wx = Math.round((double) wxx * (Iris.settings.gen.horizontalZoom / 1.90476190476)) * Iris.settings.gen.biomeScale; - double wz = Math.round((double) wzx * (Iris.settings.gen.horizontalZoom / 1.90476190476)) * Iris.settings.gen.biomeScale; - double xf = wx + ((fracture.noise(wx, wz) / 2D) * 200D * Iris.settings.gen.biomeEdgeScrambleRange); - double zf = wz - ((fracture.noise(wz, wx) / 2D) * 200D * Iris.settings.gen.biomeEdgeScrambleRange); - double x = xf - fuzz.noise(wx, wz); - double z = zf + fuzz.noise(wz, wx); - - if(ocean.getIndex(x, z) == 0) - { - return true; - } - - if(channel.hasBorder(3, 44, xf, zf)) - { - return true; - } - - if(Borders.isBorderWithin(x, z, 3, 24D, (x + z) / 100D, (xx, zz) -> ocean.getIndex(xx, zz))) - { - return true; - } - - if(ocean.getClosestNeighbor(x, z) > 0.2) - { - return true; - } - - if(channel.getClosestNeighbor(x, z) > 0.2) - { - return true; - } - - if(channel.hasBorder(3, 7, xf, zf) || channel.hasBorder(3, 3, xf, zf)) - { - return true; - } - - return false; - } - - public IrisBiome getBiome(double wxx, double wzx, boolean real) - { - double wx = Math.round((double) wxx * (Iris.settings.gen.horizontalZoom / 1.90476190476)) * Iris.settings.gen.biomeScale; - double wz = Math.round((double) wzx * (Iris.settings.gen.horizontalZoom / 1.90476190476)) * Iris.settings.gen.biomeScale; - double xf = wx + ((fracture.noise(wx, wz) / 2D) * 200D * Iris.settings.gen.biomeEdgeScrambleRange); - double zf = wz - ((fracture.noise(wz, wx) / 2D) * 200D * Iris.settings.gen.biomeEdgeScrambleRange); - double x = xf - fuzz.noise(wx, wz); - double z = zf + fuzz.noise(wz, wx); - IrisBiome biome = master.computeBiome(x, z); - - if(real) - { - return biome; - } - - if(ocean.getIndex(x, z) == 0) - { - IrisRegion region = getRegion(biome.getRegionID()); - - if(region == null) - { - L.f(C.YELLOW + "Cannot find Region " + C.RED + biome.getRegionID()); - return biome; - } - - if(!Borders.isBorderWithin(x, z, 7, 45, (x / 10D) + (z / 10D), (a, b) -> ocean.getIndex(a, b))) - { - if(region.getDeepOcean() == null) - { - L.f(C.YELLOW + "Cannot find Deep Ocean in Region" + C.RED + biome.getRegionID()); - return biome; - } - - return getRegion(biome.getRegionID()).getDeepOcean(); - } - - if(region.getOcean() == null) - { - L.f(C.YELLOW + "Cannot find Ocean in Region" + C.RED + biome.getRegionID()); - return biome; - } - - return getRegion(biome.getRegionID()).getOcean(); - } - - if(channel.hasBorder(3, 44, xf, zf)) - { - IrisRegion region = getRegion(biome.getRegionID()); - - if(region == null) - { - L.f(C.YELLOW + "Cannot find Region " + C.RED + biome.getRegionID()); - return biome; - } - - if(region.getChannel() == null) - { - L.f(C.YELLOW + "Cannot find Channel in Region" + C.RED + biome.getRegionID()); - return biome; - } - - return getRegion(biome.getRegionID()).getChannel(); - } - - return biome; - } - - @Override - public double generateLayer(double noise, double dx, double dz) - { - return noise; - } - - public IrisRegion getRegion(String name) - { - return regions.get(name); - } - - public void compileInfo(BiomeLayer l) - { - l.compileChildren(0.082 * Iris.settings.gen.biomeScale * 0.189, 1, factory, true); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCarving.java b/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCarving.java deleted file mode 100644 index fca30aadc..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCarving.java +++ /dev/null @@ -1,64 +0,0 @@ -package ninja.bytecode.iris.generator.layer; - -import java.util.Random; - -import org.bukkit.World; - -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.util.ChunkPlan; -import ninja.bytecode.iris.util.GenLayer; -import ninja.bytecode.iris.util.IrisInterpolation; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.M; -import ninja.bytecode.shuriken.math.RNG; - -public class GenLayerCarving extends GenLayer -{ - private CNG scram; - private CNG cng; - private CNG cngh; - private CNG cngo; - - public GenLayerCarving(IrisGenerator iris, World world, Random random, RNG rng) - { - //@builder - super(iris, world, random, rng); - cng = new CNG(rng.nextParallelRNG(2339234), 1D, 1).scale(0.02); - cngh = new CNG(rng.nextParallelRNG(1939234), 1D, 1).scale(0.027); - cngo = new CNG(rng.nextParallelRNG(8939234), 1D, 1).scale(0.002); - scram = new CNG(rng.nextParallelRNG(2639634), 1D, 1).scale(0.15); - - //@done - } - - @Override - public double generateLayer(double gnoise, double dx, double dz) - { - return gnoise; - } - - public boolean isCarved(double vwxxf, double vwzxf, int x, int z, double hl, AtomicChunkData data, ChunkPlan plan) - { - double a = cngh.noise(vwxxf, vwzxf); - double hmax = 99 + (a * 30); - double hmin = 68 + (a * 30); - - if(hl > hmax || hl < hmin) - { - return false; - } - double wxxf = (scram.noise(vwxxf, vwzxf) * 12) - vwzxf; - double wzxf = (scram.noise(vwzxf, vwxxf) * 12) + vwxxf; - - double downrange = M.lerpInverse(hmin, hmax, hl); - double opacity = IrisInterpolation.sinCenter(downrange); - - if(cng.noise(wxxf, wzxf, hl / 3) < (opacity / 1.4D) * cngo.noise(wxxf, wzxf)) - { - return true; - } - - return false; - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCaves.java b/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCaves.java deleted file mode 100644 index ca23f6d36..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCaves.java +++ /dev/null @@ -1,120 +0,0 @@ -package ninja.bytecode.iris.generator.layer; - -import java.util.Random; - -import org.bukkit.Material; -import org.bukkit.World; - -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.util.Borders; -import ninja.bytecode.iris.util.ChunkPlan; -import ninja.bytecode.iris.util.GenLayer; -import ninja.bytecode.iris.util.PolygonGenerator; -import ninja.bytecode.shuriken.bench.PrecisionStopwatch; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.RNG; - -public class GenLayerCaves extends GenLayer -{ - private PolygonGenerator g; - private CNG gincline; - private CNG scram; - - public GenLayerCaves(IrisGenerator iris, World world, Random random, RNG rng) - { - //@builder - super(iris, world, random, rng); - g = new PolygonGenerator(rng.nextParallelRNG(1111), 3, 0.024, 8, (c) -> c); - gincline = new CNG(rng.nextParallelRNG(1112), 1D, 3).scale(0.00652); - scram = new CNG(rng.nextParallelRNG(2639634), 1D, 1).scale(0.15); - //@done - } - - @Override - public double generateLayer(double gnoise, double dx, double dz) - { - return gnoise; - } - - public void genCaves(double vwxxf, double vwzxf, int x, int z, AtomicChunkData data, ChunkPlan plan) - { - PrecisionStopwatch s = PrecisionStopwatch.start(); - double itr = 2; - double level = 8; - double incline = 187; - double baseWidth = 11; - double drop = 41; - double wxxf = (scram.noise(vwxxf, vwzxf) * 6) - vwzxf; - double wzxf = (scram.noise(vwzxf, vwxxf) * 6) + vwxxf; - - for(double m = 1; m <= itr; m += 0.45) - { - double w = baseWidth / m; - - if(w < 5) - { - break; - } - - int lowest = 325; - - double n = incline * gincline.noise((wxxf + (m * 10000)), (wzxf - (m * 10000))); - for(double i = 1; i <= w / 3D; i++) - { - if(Borders.isBorderWithin((wxxf + (m * 10000)), (wzxf - (m * 10000)), 5, w / 2D / i, (wxxf / 3D) + (wzxf / 3D), (xx, zz) -> g.getIndex(xx, zz))) - { - int h = (int) ((level + n) - drop); - if(dig(x, (int) (h + i), z, data) && h + i < lowest) - { - lowest = (int) (h + i); - } - - if(dig(x, (int) (h - i), z, data) && h - i < lowest) - { - lowest = (int) (h - i); - } - - if(i == 1) - { - if(dig(x, (int) (h), z, data) && h < lowest) - { - lowest = (int) (h); - } - } - } - } - } - - iris.getMetrics().stop("caves:ms:x256:/chunk:..", s); - } - - public boolean dig(int x, int y, int z, AtomicChunkData data) - { - Material a = data.getType(x, y, z); - Material b = data.getType(x, y, z + 1); - Material c = data.getType(x, y + 1, z); - Material d = data.getType(x + 1, y, z); - Material e = data.getType(x, y, z - 1); - Material f = data.getType(x, y - 1, z); - Material g = data.getType(x - 1, y, z); - - if(can(a) && cann(b) && cann(c) && cann(d) && cann(e) && cann(f) && cann(g)) - { - data.setBlock(x, y, z, Material.AIR); - return true; - } - - return false; - } - - public boolean cann(Material m) - { - return m.isSolid() || m.equals(Material.AIR) && !m.equals(Material.BEDROCK); - } - - public boolean can(Material m) - { - return m.isSolid() && !m.equals(Material.BEDROCK); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCliffs.java b/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCliffs.java deleted file mode 100644 index 1dab5f192..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerCliffs.java +++ /dev/null @@ -1,67 +0,0 @@ -package ninja.bytecode.iris.generator.layer; - -import java.util.Random; - -import org.bukkit.World; - -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.util.GenLayer; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.RNG; - -public class GenLayerCliffs extends GenLayer -{ - private double block; - private CNG gen; - private CNG sh; - private CNG ch; - - public GenLayerCliffs(IrisGenerator iris, World world, Random random, RNG rng) - { - //@builder - super(iris, world, random, rng); - block = 1D / 255D; - gen = new CNG(rng.nextParallelRNG(128), 1D, 4).scale(0.02); - sh = new CNG(rng.nextParallelRNG(127), 1D, 1).scale(0.00367); - ch = new CNG(rng.nextParallelRNG(127), 1D, 1).scale(0.00413); - //@done - } - - @Override - public double generateLayer(double gnoise, double dx, double dz) - { - return generateLayer(gnoise, dx, dz, 1D, 0.37D); - } - - public double generateLayer(double gnoise, double dx, double dz, double cliffs, double chance) - { - if(gnoise < block * 66) - { - return gnoise; - } - - double shift = 10.25 + (sh.noise(dx, dz) * 2.25) * cliffs; - double hits = 183D / shift; - double n = gnoise; - - for(int i = (int) hits; i > 0; i--) - { - if(ch.noise(dx + (i * -1000), dz + (i * 1000)) >= chance) - { - continue; - } - - double var = 12.2 * block; - double varCombined = 15.45 * block; - double sep = (shift / 1.8D) * block; - double height = (67 + (i * shift)) * block; - double sh = ((gen.noise(dx + dz, dz - dx) - 0.5D) * 2D) * varCombined; - double shv = ((gen.noise(dz + dx, dx - dz) - 0.5D) * 2D) * varCombined; - double lo = (gen.noise(dx + (i * -1000), dz + (i * 1000)) * var) + height + sh; - double hi = (gen.noise(dz + (i * 1000), dx + (i * -1000)) * var) + height + sep + shv; - n = n > lo && n < hi ? lo : n; - } - - return n; - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerLayeredNoise.java b/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerLayeredNoise.java deleted file mode 100644 index 089cc5aa1..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerLayeredNoise.java +++ /dev/null @@ -1,44 +0,0 @@ -package ninja.bytecode.iris.generator.layer; - -import java.util.Random; - -import org.bukkit.World; - -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.util.GenLayer; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.RNG; - -public class GenLayerLayeredNoise extends GenLayer -{ - private CNG gen; - private CNG fract; - - public GenLayerLayeredNoise(IrisGenerator iris, World world, Random random, RNG rng) - { - //@builder - super(iris, world, random, rng); - fract = new CNG(rng.nextParallelRNG(16), 1D, 9).scale(0.0181); - gen = new CNG(rng.nextParallelRNG(17), 0.19D, 8) - .scale(0.012) - .amp(0.5) - .freq(1.1) - .fractureWith(new CNG(rng.nextParallelRNG(18), 1, 5) - .scale(0.018) - .child(new CNG(rng.nextParallelRNG(19), 0.745, 2) - .scale(0.1)) - .fractureWith(new CNG(rng.nextParallelRNG(20), 1, 3) - .scale(0.15), 24), 44); - } - - public double getHeight(double x, double z) - { - return 0.65* gen.noise(x, z); - } - - @Override - public double generateLayer(double gnoise, double dx, double dz) - { - return 0.65 * gen.noise(gnoise, dx + (fract.noise(gnoise, dx, dz) * 333), dz - (fract.noise(dz, dx, gnoise) * 333)); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerOres.java b/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerOres.java deleted file mode 100644 index 9abb49421..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerOres.java +++ /dev/null @@ -1,145 +0,0 @@ -package ninja.bytecode.iris.generator.layer; - -import java.util.Random; - -import org.bukkit.Material; -import org.bukkit.World; - -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.Settings.OreSettings; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.util.ChunkPlan; -import ninja.bytecode.iris.util.GenLayer; -import ninja.bytecode.iris.util.IrisInterpolation; -import ninja.bytecode.shuriken.bench.PrecisionStopwatch; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.M; -import ninja.bytecode.shuriken.math.RNG; - -public class GenLayerOres extends GenLayer -{ - private CNG ore; - - public GenLayerOres(IrisGenerator iris, World world, Random random, RNG rng) - { - //@builder - super(iris, world, random, rng); - ore = new CNG(rng.nextParallelRNG(12944), 1D, 1).scale(0.1); - //@done - } - - @Override - public double generateLayer(double gnoise, double dx, double dz) - { - return gnoise; - } - - public void genOres(double xxf, double zzf, int x, int z, int h, AtomicChunkData data, ChunkPlan plan) - { - PrecisionStopwatch s = PrecisionStopwatch.start(); - OreSettings o = Iris.settings.ore; - - for(int i = 0; i < h; i++) - { - if(i >= o.ironMinHeight && i <= o.ironMaxHeight && - ore.noise(xxf + 64, i, zzf - 64) < IrisInterpolation.lerpCenterSinBezier( - o.ironMinDispersion, - Iris.settings.ore.ironMaxDispersion, - M.lerpInverse(o.ironMinHeight, o.ironMaxHeight, i))) - { - if(!can(data.getType(x, i, z))) - { - continue; - } - - data.setBlock(x, i, z, Material.IRON_ORE); - } - - if(i >= o.coalMinHeight && i <= o.coalMaxHeight && - ore.noise(xxf + 128, i, zzf - 128) < IrisInterpolation.lerpCenterSinBezier( - o.coalMinDispersion, - Iris.settings.ore.coalMaxDispersion, - M.lerpInverse(o.coalMinHeight, o.coalMaxHeight, i))) - { - if(!can(data.getType(x, i, z))) - { - continue; - } - data.setBlock(x, i, z, Material.COAL_ORE); - } - - if(i >= o.goldMinHeight && i <= o.goldMaxHeight && - ore.noise(xxf + 64, i, zzf - 128) < IrisInterpolation.lerpCenterSinBezier( - o.goldMinDispersion, - Iris.settings.ore.goldMaxDispersion, - M.lerpInverse(o.goldMinHeight, o.goldMaxHeight, i))) - { - if(!can(data.getType(x, i, z))) - { - continue; - } - data.setBlock(x, i, z, Material.GOLD_ORE); - } - - if(i >= o.redstoneMinHeight && i <= o.redstoneMaxHeight && - ore.noise(xxf + 128, i, zzf - 64) < IrisInterpolation.lerpCenterSinBezier( - o.redstoneMinDispersion, - Iris.settings.ore.redstoneMaxDispersion, - M.lerpInverse(o.redstoneMinHeight, o.redstoneMaxHeight, i))) - { - if(!can(data.getType(x, i, z))) - { - continue; - } - data.setBlock(x, i, z, Material.REDSTONE_ORE); - } - - if(i >= o.lapisMinHeight && i <= o.lapisMaxHeight && - ore.noise(xxf + 256, i, zzf - 64) < IrisInterpolation.lerpCenterSinBezier( - o.lapisMinDispersion, - Iris.settings.ore.lapisMaxDispersion, - M.lerpInverse(o.lapisMinHeight, o.lapisMaxHeight, i))) - { - if(!can(data.getType(x, i, z))) - { - continue; - } - data.setBlock(x, i, z, Material.LAPIS_ORE); - } - - if(i >= o.diamondMinHeight && i <= o.diamondMaxHeight && - ore.noise(xxf + 64, i, zzf - 256) < IrisInterpolation.lerpCenterSinBezier( - o.diamondMinDispersion, - Iris.settings.ore.diamondMaxDispersion, - M.lerpInverse(o.diamondMinHeight, o.diamondMaxHeight, i))) - { - if(!can(data.getType(x, i, z))) - { - continue; - } - data.setBlock(x, i, z, Material.DIAMOND_ORE); - } - - if(i >= o.emeraldMinHeight && i <= o.emeraldMaxHeight && - ore.noise(xxf + 128, i, zzf - 256) < IrisInterpolation.lerpCenterSinBezier( - o.emeraldMinDispersion, - Iris.settings.ore.emeraldMaxDispersion, - M.lerpInverse(o.emeraldMinHeight, o.emeraldMaxHeight, i))) - { - if(!can(data.getType(x, i, z))) - { - continue; - } - data.setBlock(x, i, z, Material.EMERALD_ORE); - } - } - - iris.getMetrics().stop("ores:ms:x256:/chunk:..", s); - } - - public boolean can(Material m) - { - return m.equals(Material.STONE) || m.name().endsWith("_ORE"); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerSnow.java b/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerSnow.java deleted file mode 100644 index 10bf2dd9f..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/layer/GenLayerSnow.java +++ /dev/null @@ -1,42 +0,0 @@ -package ninja.bytecode.iris.generator.layer; - -import java.util.Random; - -import org.bukkit.World; - -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.util.GenLayer; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.RNG; - -public class GenLayerSnow extends GenLayer -{ - private CNG gen; - - public GenLayerSnow(IrisGenerator iris, World world, Random random, RNG rng) - { - //@builder - super(iris, world, random, rng); - gen = new CNG(rng.nextParallelRNG(117), 1D, 1) - .scale(0.059) - .amp(0.5) - .freq(1.1) - .fractureWith(new CNG(rng.nextParallelRNG(18), 1, 6) - .scale(0.018) - .child(new CNG(rng.nextParallelRNG(19), 0.745, 2) - .scale(0.1)) - .fractureWith(new CNG(rng.nextParallelRNG(20), 1, 3) - .scale(0.15), 24), 44); - } - - public double getHeight(double x, double z) - { - return gen.noise(x, z); - } - - @Override - public double generateLayer(double gnoise, double dx, double dz) - { - return getHeight(dx, dz); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxAnchor.java b/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxAnchor.java deleted file mode 100644 index b56f51c75..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxAnchor.java +++ /dev/null @@ -1,45 +0,0 @@ -package ninja.bytecode.iris.generator.parallax; - -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.pack.IrisBiome; - -public class ParallaxAnchor -{ - private final int height; - private final int water; - private final IrisBiome biome; - private final AtomicChunkData data; - - public ParallaxAnchor(int height, int water, IrisBiome biome, AtomicChunkData data) - { - this.height = height; - this.water = water; - this.biome = biome; - this.data = data; - } - - public AtomicChunkData getData() - { - return data; - } - - public int getWater() - { - return water; - } - - public int getHeight() - { - return height; - } - - public int getWaterHeight() - { - return water; - } - - public IrisBiome getBiome() - { - return biome; - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxCache.java b/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxCache.java deleted file mode 100644 index cf9331bfc..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxCache.java +++ /dev/null @@ -1,102 +0,0 @@ -package ninja.bytecode.iris.generator.parallax; - -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.iris.util.ChunkPlan; -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.SMCAVector; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.collections.KSet; - -public class ParallaxCache -{ - private KMap cachePlan; - private KMap cacheData; - private KSet contains; - private IrisGenerator gen; - - public ParallaxCache(IrisGenerator gen) - { - this.gen = gen; - cacheData = new KMap<>(); - cachePlan = new KMap<>(); - contains = new KSet<>(); - } - - public MB get(int x, int y, int z) - { - SMCAVector s = new SMCAVector(x, z); - SMCAVector c = new SMCAVector(x >> 4, z >> 4); - - if(contains.contains(s) && cacheData.containsKey(c) && cachePlan.containsKey(c) ) - { - return cacheData.get(c).getMB(x & 15, y, z & 15); - } - - createData(x, z, s, c); - - return cacheData.get(c).getMB(x & 15, y, z & 15); - } - - public IrisBiome getBiome(int x, int z) - { - SMCAVector s = new SMCAVector(x, z); - SMCAVector c = new SMCAVector(x >> 4, z >> 4); - - if(contains.contains(s) && cacheData.containsKey(c) && cachePlan.containsKey(c) ) - { - return cachePlan.get(c).getBiome(x & 15, z & 15); - } - - createData(x, z, s, c); - - return cachePlan.get(c).getBiome(x & 15, z & 15); - } - - public int getWaterHeight(int x, int z) - { - SMCAVector s = new SMCAVector(x, z); - SMCAVector c = new SMCAVector(x >> 4, z >> 4); - - if(contains.contains(s) && cacheData.containsKey(c) && cachePlan.containsKey(c) ) - { - return cachePlan.get(c).getRealWaterHeight(x & 15, z & 15); - } - - createData(x, z, s, c); - - return cachePlan.get(c).getRealWaterHeight(x & 15, z & 15); - } - - public int getHeight(int x, int z) - { - SMCAVector s = new SMCAVector(x, z); - SMCAVector c = new SMCAVector(x >> 4, z >> 4); - - if(contains.contains(s) && cacheData.containsKey(c) && cachePlan.containsKey(c) ) - { - return cachePlan.get(c).getRealHeight(x & 15, z & 15); - } - - createData(x, z, s, c); - - return cachePlan.get(c).getRealHeight(x & 15, z & 15); - } - - private void createData(int x, int z, SMCAVector s, SMCAVector c) - { - if(!cacheData.containsKey(c)) - { - cacheData.put(c, new AtomicChunkData(gen.getWorld())); - } - - if(!cachePlan.containsKey(c)) - { - cachePlan.put(c, new ChunkPlan()); - } - - gen.computeAnchor(x, z, cachePlan.get(c), cacheData.get(c)); - contains.add(s); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxWorldGenerator.java b/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxWorldGenerator.java deleted file mode 100644 index 8e266b133..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/parallax/ParallaxWorldGenerator.java +++ /dev/null @@ -1,194 +0,0 @@ -package ninja.bytecode.iris.generator.parallax; - -import java.util.Random; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.world.ChunkLoadEvent; -import org.bukkit.event.world.WorldSaveEvent; -import org.bukkit.event.world.WorldUnloadEvent; - -import mortar.api.nms.NMP; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.util.ChunkPlan; -import ninja.bytecode.iris.util.IrisWorldData; -import ninja.bytecode.iris.util.ObjectMode; -import ninja.bytecode.iris.util.SChunkVector; -import ninja.bytecode.shuriken.bench.PrecisionStopwatch; -import ninja.bytecode.shuriken.execution.TaskExecutor.TaskGroup; -import ninja.bytecode.shuriken.math.RNG; - -public abstract class ParallaxWorldGenerator extends ParallelChunkGenerator implements Listener -{ - private World world; - private IrisWorldData data; - private RNG rMaster; - private AtomicChunkData buffer; - protected boolean saving; - - @Override - public final void init(World world, Random random) - { - this.world = world; - saving = true; - buffer = new AtomicChunkData(world); - this.data = new IrisWorldData(world); - this.rMaster = new RNG(world.getSeed() + 1); - onInit(world, rMaster.nextParallelRNG(1)); - Bukkit.getPluginManager().registerEvents(this, Iris.instance); - } - - public void disableSaving() - { - saving = false; - data.disableSaving(); - } - - public void enableSaving() - { - saving = true; - data.enableSaving(); - } - - @EventHandler - public void on(ChunkLoadEvent e) - { - if(Iris.settings.performance.objectMode.equals(ObjectMode.PARALLAX) && e.getWorld().equals(world)) - { - NMP.host.relight(e.getChunk()); - } - } - - @EventHandler - public void on(WorldUnloadEvent e) - { - if(e.getWorld().equals(world)) - { - getWorldData().dispose(); - onUnload(); - } - } - - @EventHandler - public void on(WorldSaveEvent e) - { - if(!saving) - { - return; - } - - if(e.getWorld().equals(world)) - { - getWorldData().saveAll(); - } - } - - public ParallaxAnchor computeAnchor(int wx, int wz, ChunkPlan heightBuffer, AtomicChunkData data) - { - onGenColumn(wx, wz, wx & 15, wz & 15, heightBuffer, data, false); - - return new ParallaxAnchor(heightBuffer.getRealHeight(wx & 15, wz & 15), heightBuffer.getRealWaterHeight(wx & 15, wz & 15), heightBuffer.getBiome(wx & 15, wz & 15), data); - } - - public ParallaxAnchor computeAnchor(int wx, int wz) - { - ChunkPlan heightBuffer = new ChunkPlan(); - onGenColumn(wx, wz, wx & 15, wz & 15, heightBuffer, buffer, false); - - return new ParallaxAnchor(heightBuffer.getRealHeight(wx & 15, wz & 15), heightBuffer.getRealWaterHeight(wx & 15, wz & 15), heightBuffer.getBiome(wx & 15, wz & 15), buffer); - } - - public void doGenParallax(int x, int z) - { - onGenParallax(x, z, getRMaster(x, z, -59328)); - getWorldData().getChunk(x, z); - } - - @Override - public final ChunkPlan initChunk(World world, int x, int z, Random random) - { - PrecisionStopwatch ps = PrecisionStopwatch.start(); - TaskGroup g = startWork(); - if(Iris.settings.performance.objectMode.equals(ObjectMode.PARALLAX)) - { - for(int ii = -(getParallaxSize().getX() / 2) - 1; ii < (((getParallaxSize().getX() / 2) + 1)); ii++) - { - int i = ii; - - for(int jj = -(getParallaxSize().getZ() / 2) - 1; jj < (((getParallaxSize().getZ() / 2) + 1)); jj++) - { - int j = jj; - int cx = x + i; - int cz = z + j; - - if(!getWorldData().exists(cx, cz)) - { - g.queue(() -> - { - onGenParallax(cx, cz, getRMaster(cx, cz, -59328)); - getWorldData().getChunk(cx, cz); - }); - } - } - } - - g.execute(); - } - - ((IrisGenerator) this).getMetrics().put("parallax:ms:/chunk", ps.getMillis()); - - return onInitChunk(world, x, z, random); - } - - @Override - public final void postChunk(World world, int x, int z, Random random, AtomicChunkData data, ChunkPlan plan) - { - onPostChunk(world, x, z, random, data, plan); - getWorldData().inject(x, z, data); - } - - @Override - public final Biome genColumn(int wx, int wz, int x, int z, ChunkPlan plan, AtomicChunkData data, boolean surface) - { - return onGenColumn(wx, wz, x, z, plan, data, surface); - } - - public World getWorld() - { - return world; - } - - public IrisWorldData getWorldData() - { - return data; - } - - public RNG getRMaster() - { - return rMaster; - } - - public RNG getRMaster(int x, int z, int signature) - { - return rMaster.nextParallelRNG((int) (signature + x * z + z + x * 2.12)); - } - - protected abstract void onUnload(); - - protected abstract SChunkVector getParallaxSize(); - - public abstract void onGenParallax(int x, int z, Random random); - - public abstract void onInit(World world, Random random); - - public abstract ChunkPlan onInitChunk(World world, int x, int z, Random random); - - public abstract Biome onGenColumn(int wx, int wz, int x, int z, ChunkPlan plan, AtomicChunkData data, boolean surfaceOnly); - - public abstract void onPostChunk(World world, int x, int z, Random random, AtomicChunkData data, ChunkPlan plan); -} diff --git a/src/main/java/ninja/bytecode/iris/generator/parallax/ParallelChunkGenerator.java b/src/main/java/ninja/bytecode/iris/generator/parallax/ParallelChunkGenerator.java deleted file mode 100644 index 27cee34f8..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/parallax/ParallelChunkGenerator.java +++ /dev/null @@ -1,191 +0,0 @@ -package ninja.bytecode.iris.generator.parallax; - -import java.util.Random; - -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.generator.ChunkGenerator; - -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.util.ChunkPlan; -import ninja.bytecode.iris.util.ChunkSpliceListener; -import ninja.bytecode.shuriken.execution.TaskExecutor; -import ninja.bytecode.shuriken.execution.TaskExecutor.TaskGroup; -import ninja.bytecode.shuriken.execution.TaskExecutor.TaskResult; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.math.RollingSequence; -import ninja.bytecode.shuriken.reaction.O; - -public abstract class ParallelChunkGenerator extends ChunkGenerator -{ - private int i; - private int j; - private int wx; - private int wz; - private TaskExecutor backupService; - private TaskGroup tg; - private boolean ready = false; - int cg = 0; - private RollingSequence rs = new RollingSequence(512); - private World world; - private ChunkSpliceListener splicer; - - public void setSplicer(ChunkSpliceListener splicer) - { - this.splicer = splicer; - } - - public World getWorld() - { - return world; - } - - public Biome generateFullColumn(int a, int b, int c, int d, ChunkPlan p, AtomicChunkData data) - { - return genColumn(a, b, c, d, p, data, false); - } - - private TaskGroup work(String n) - { - if(Iris.instance == null || Iris.exec() == null) - { - if(backupService == null) - { - L.f(C.RED + "Cannot contact ExecutionController!" + C.YELLOW + " Did you reload iris?"); - L.w(C.YELLOW + "Spinning up a temporary backup service until the issue resolves..."); - backupService = new TaskExecutor(4, Thread.MAX_PRIORITY, "Iris Backup Handover"); - Iris.instance.reload(); - } - - return backupService.startWork(); - } - - else if(backupService != null) - { - L.i(C.GREEN + "Reconnected to the execution service. Closing backup service now..."); - backupService.close(); - } - - return Iris.exec().getExecutor(world, n).startWork(); - } - - public TaskGroup startParallaxWork() - { - return work("Parallax"); - } - - public TaskGroup startWork() - { - return work("Generator"); - } - - public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome) - { - random = new Random(world.getSeed()); - if(splicer != null) - { - AtomicChunkData d = splicer.onSpliceAvailable(world, random, x, z, biome); - - if(d != null) - { - return d.toChunkData(); - } - } - - AtomicChunkData data = new AtomicChunkData(world); - - try - { - this.world = world; - - if(!ready) - { - init(world, random); - ready = true; - } - - tg = startWork(); - O plan = new O(); - for(i = 0; i < 16; i++) - { - wx = (x << 4) + i; - - for(j = 0; j < 16; j++) - { - wz = (z << 4) + j; - int a = wx; - int b = wz; - int c = i; - int d = j; - tg.queue(() -> - { - Biome f = generateFullColumn(a, b, c, d, plan.get(), data); - biome.setBiome(c, d, f); - }); - } - } - - plan.set(initChunk(world, x, z, random)); - TaskResult r = tg.execute(); - onDecorateChunk(world, x, z, data, plan.get()); - TaskGroup gd = startWork(); - - for(i = 0; i < 16; i++) - { - wx = (x << 4) + i; - - for(j = 0; j < 16; j++) - { - wz = (z << 4) + j; - int a = wx; - int b = wz; - int c = i; - int d = j; - gd.queue(() -> onDecorateColumn(world, c, d, a, b, data, plan.get())); - } - } - - gd.execute(); - postChunk(world, x, z, random, data, plan.get()); - rs.put(r.timeElapsed); - cg++; - } - - catch(Throwable e) - { - try - { - for(int i = 0; i < 16; i++) - { - for(int j = 0; j < 16; j++) - { - data.setBlock(i, 0, j, Material.RED_GLAZED_TERRACOTTA); - } - } - } - - catch(Throwable ex) - { - - } - e.printStackTrace(); - } - - return data.toChunkData(); - } - - protected abstract void onDecorateColumn(World world2, int i2, int j2, int wx2, int wz2, AtomicChunkData data, ChunkPlan chunkPlan); - - protected abstract void onDecorateChunk(World world2, int x, int z, AtomicChunkData data, ChunkPlan chunkPlan); - - public abstract void init(World world, Random random); - - public abstract ChunkPlan initChunk(World world, int x, int z, Random random); - - public abstract void postChunk(World world, int x, int z, Random random, AtomicChunkData data, ChunkPlan plan); - - public abstract Biome genColumn(int wx, int wz, int x, int z, ChunkPlan plan, AtomicChunkData data, boolean surfaceOnly); -} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/generator/placer/AtomicParallaxPlacer.java b/src/main/java/ninja/bytecode/iris/generator/placer/AtomicParallaxPlacer.java deleted file mode 100644 index 3bd7a7a71..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/placer/AtomicParallaxPlacer.java +++ /dev/null @@ -1,47 +0,0 @@ -package ninja.bytecode.iris.generator.placer; - -import org.bukkit.Location; - -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.generator.parallax.ParallaxCache; -import ninja.bytecode.iris.util.IrisWorldData; -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.Placer; - -public class AtomicParallaxPlacer extends Placer -{ - private IrisWorldData data; - private ParallaxCache cache; - - public AtomicParallaxPlacer(IrisGenerator g, ParallaxCache cache) - { - super(g.getWorld()); - this.data = g.getWorldData(); - this.cache = cache; - } - - @Override - public MB get(Location l) - { - return cache.get(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - } - - @SuppressWarnings("deprecation") - @Override - public void set(Location l, MB mb) - { - data.setBlock(l.getBlockX(), l.getBlockY(), l.getBlockZ(), mb.material.getId(), mb.data); - } - - @Override - public int getHighestY(Location l) - { - return cache.getHeight(l.getBlockX(), l.getBlockZ()); - } - - @Override - public int getHighestYUnderwater(Location l) - { - return cache.getWaterHeight(l.getBlockX(), l.getBlockZ()); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/placer/BukkitPlacer.java b/src/main/java/ninja/bytecode/iris/generator/placer/BukkitPlacer.java deleted file mode 100644 index ea9368891..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/placer/BukkitPlacer.java +++ /dev/null @@ -1,63 +0,0 @@ -package ninja.bytecode.iris.generator.placer; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; - -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.Placer; - -public class BukkitPlacer extends Placer -{ - private final boolean applyPhysics; - - public BukkitPlacer(World world, boolean applyPhysics) - { - super(world); - this.applyPhysics = applyPhysics; - } - - @SuppressWarnings("deprecation") - @Override - public MB get(Location l) - { - Block b = world.getBlockAt(l); - return MB.of(b.getType(), b.getData()); - } - - @SuppressWarnings("deprecation") - @Override - public void set(Location l, MB mb) - { - l.getBlock().setTypeIdAndData(mb.material.getId(), mb.data, applyPhysics); - } - - @Override - public int getHighestYUnderwater(Location l) - { - int y = getHighestY(l); - - while(y > 0) - { - y--; - Block b = l.getWorld().getBlockAt(l.getBlockX(), y, l.getBlockZ()); - if(!b.isEmpty()) - { - if(b.isLiquid()) - { - continue; - } - - return y + 1; - } - } - - return y; - } - - @Override - public int getHighestY(Location l) - { - return world.getHighestBlockYAt(l); - } -} diff --git a/src/main/java/ninja/bytecode/iris/generator/placer/NMSPlacer.java b/src/main/java/ninja/bytecode/iris/generator/placer/NMSPlacer.java deleted file mode 100644 index 96b6c4ec8..000000000 --- a/src/main/java/ninja/bytecode/iris/generator/placer/NMSPlacer.java +++ /dev/null @@ -1,92 +0,0 @@ -package ninja.bytecode.iris.generator.placer; - -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import mortar.api.nms.Catalyst; -import mortar.api.nms.NMP; -import mortar.api.world.MaterialBlock; -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.Placer; -import ninja.bytecode.shuriken.collections.KSet; -import ninja.bytecode.shuriken.execution.J; - -public class NMSPlacer extends Placer -{ - private KSet c; - - public NMSPlacer(World world) - { - super(world); - c = new KSet<>(); - } - - @SuppressWarnings("deprecation") - @Override - public MB get(Location l) - { - Block b = world.getBlockAt(l); - return MB.of(b.getType(), b.getData()); - } - - @SuppressWarnings("deprecation") - @Override - public void set(Location l, MB mb) - { - Catalyst.host.setBlock(l, new MaterialBlock(mb.material.getId(), mb.data)); - c.add(l.getChunk()); - } - - @Override - public int getHighestY(Location l) - { - return world.getHighestBlockYAt(l); - } - - @Override - public int getHighestYUnderwater(Location l) - { - int y = getHighestY(l); - - while(y > 0) - { - y--; - Block b = l.getWorld().getBlockAt(l.getBlockX(), y, l.getBlockZ()); - if(!b.isEmpty()) - { - if(b.isLiquid()) - { - continue; - } - - return y + 1; - } - } - - return y; - } - - public void flush() - { - J.attempt(() -> - { - for(Chunk i : c) - { - NMP.host.relight(i); - - J.a(() -> - { - for(Player j : i.getWorld().getPlayers()) - { - NMP.CHUNK.refreshIgnorePosition(j, i); - } - }); - } - - c.clear(); - }); - } -} diff --git a/src/main/java/ninja/bytecode/iris/layer/GenLayerBiome.java b/src/main/java/ninja/bytecode/iris/layer/GenLayerBiome.java new file mode 100644 index 000000000..49ffc187b --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/layer/GenLayerBiome.java @@ -0,0 +1,194 @@ +package ninja.bytecode.iris.layer; + +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.generator.DimensionChunkGenerator; +import ninja.bytecode.iris.object.InferredType; +import ninja.bytecode.iris.object.IrisBiome; +import ninja.bytecode.iris.object.IrisRegion; +import ninja.bytecode.iris.object.IrisRegionRidge; +import ninja.bytecode.iris.object.IrisRegionSpot; +import ninja.bytecode.iris.util.BiomeResult; +import ninja.bytecode.iris.util.CellGenerator; +import ninja.bytecode.iris.util.GenLayer; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; + +public class GenLayerBiome extends GenLayer +{ + private CellGenerator region; + private CellGenerator bridge; + private CellGenerator land; + private CellGenerator shore; + private CellGenerator sea; + private DimensionChunkGenerator iris; + + public GenLayerBiome(DimensionChunkGenerator iris, RNG rng) + { + super(iris, rng); + this.iris = iris; + region = new CellGenerator(rng.nextParallelRNG(1188519)); + bridge = new CellGenerator(rng.nextParallelRNG(1541462)); + land = new CellGenerator(rng.nextParallelRNG(9045162)); + shore = new CellGenerator(rng.nextParallelRNG(2342812)); + sea = new CellGenerator(rng.nextParallelRNG(6135621)); + } + + public IrisRegion getRegion(double bx, double bz) + { + region.setShuffle(8); + region.setCellScale(0.33 / iris.getDimension().getRegionZoom()); + double x = bx / iris.getDimension().getBiomeZoom(); + double z = bz / iris.getDimension().getBiomeZoom(); + String regionId = iris.getDimension().getRegions().get(region.getIndex(x, z, iris.getDimension().getRegions().size())); + + return Iris.data.getRegionLoader().load(regionId); + } + + public BiomeResult generateData(double bx, double bz, int rawX, int rawZ) + { + return generateRegionData(bx, bz, rawX, rawZ, getRegion(bx, bz)); + } + + public boolean isSea(double bx, double bz, IrisRegion regionData) + { + bridge.setShuffle(0); + bridge.setCellScale(0.33 / iris.getDimension().getContinentZoom()); + double x = bx / iris.getDimension().getBiomeZoom(); + double z = bz / iris.getDimension().getBiomeZoom(); + return bridge.getIndex(x, z, 5) == 1; + } + + public BiomeResult generateRegionData(double bx, double bz, int rawX, int rawZ, IrisRegion regionData) + { + if(isSea(bx, bz, regionData)) + { + return generateSeaData(bx, bz, rawX, rawZ, regionData); + } + + else + { + return generateLandData(bx, bz, rawX, rawZ, regionData); + } + } + + public BiomeResult generateBiomeData(double bx, double bz, IrisRegion regionData, CellGenerator cell, KList biomes, InferredType inferredType) + { + double x = bx / iris.getDimension().getBiomeZoom(); + double z = bz / iris.getDimension().getBiomeZoom(); + IrisBiome biome = Iris.data.getBiomeLoader().load(biomes.get(sea.getIndex(x, z, biomes.size()))); + biome.setInferredType(inferredType); + + return implode(bx, bz, regionData, cell, new BiomeResult(biome, cell.getDistance(x, z))); + } + + public BiomeResult generateSeaData(double bx, double bz, int rawX, int rawZ, IrisRegion regionData) + { + for(IrisRegionRidge i : regionData.getRidgeBiomes()) + { + if(i.getType().equals(InferredType.SEA) && i.isRidge(rng, rawX, rawZ)) + { + return new BiomeResult(Iris.data.getBiomeLoader().load(i.getBiome()), 0.5); + } + } + + for(IrisRegionSpot i : regionData.getSpotBiomes()) + { + if(i.getType().equals(InferredType.SEA) && i.isSpot(rng, rawX, rawZ)) + { + return new BiomeResult(Iris.data.getBiomeLoader().load(i.getBiome()), 0.5); + } + } + + sea.setShuffle(42); + sea.setCellScale(0.56 / iris.getDimension().getSeaZoom()); + return generateBiomeData(bx, bz, regionData, sea, regionData.getSeaBiomes(), InferredType.SEA); + } + + public BiomeResult generateLandData(double bx, double bz, int rawX, int rawZ, IrisRegion regionData) + { + for(IrisRegionRidge i : regionData.getRidgeBiomes()) + { + if(i.getType().equals(InferredType.LAND) && i.isRidge(rng, rawX, rawZ)) + { + return new BiomeResult(Iris.data.getBiomeLoader().load(i.getBiome()), 0.5); + } + } + + for(IrisRegionSpot i : regionData.getSpotBiomes()) + { + if(i.getType().equals(InferredType.LAND) && i.isSpot(rng, rawX, rawZ)) + { + return new BiomeResult(Iris.data.getBiomeLoader().load(i.getBiome()), 0.5); + } + } + + land.setShuffle(12); + land.setCellScale(0.6 / iris.getDimension().getLandZoom()); + return generateBiomeData(bx, bz, regionData, land, regionData.getLandBiomes(), InferredType.LAND); + } + + public BiomeResult generateShoreData(double bx, double bz, int rawX, int rawZ, IrisRegion regionData) + { + for(IrisRegionRidge i : regionData.getRidgeBiomes()) + { + if(i.getType().equals(InferredType.SHORE) && i.isRidge(rng, rawX, rawZ)) + { + return new BiomeResult(Iris.data.getBiomeLoader().load(i.getBiome()), 0.5); + } + } + + for(IrisRegionSpot i : regionData.getSpotBiomes()) + { + if(i.getType().equals(InferredType.SHORE) && i.isSpot(rng, rawX, rawZ)) + { + return new BiomeResult(Iris.data.getBiomeLoader().load(i.getBiome()), 0.5); + } + } + + shore.setShuffle(4); + shore.setCellScale(0.8 / iris.getDimension().getShoreZoom()); + return generateBiomeData(bx, bz, regionData, shore, regionData.getShoreBiomes(), InferredType.SHORE); + } + + public BiomeResult implode(double bx, double bz, IrisRegion regionData, CellGenerator parentCell, BiomeResult parent) + { + return implode(bx, bz, regionData, parentCell, parent, 1); + } + + public BiomeResult implode(double bx, double bz, IrisRegion regionData, CellGenerator parentCell, BiomeResult parent, int hits) + { + if(hits > 9) + { + return parent; + } + + double x = bx / iris.getDimension().getBiomeZoom(); + double z = bz / iris.getDimension().getBiomeZoom(); + if(parent.getDistance() > regionData.getBiomeImplosionRatio()) + { + if(!parent.getBiome().getChildren().isEmpty()) + { + CellGenerator childCell = parent.getBiome().getChildrenGenerator(rng, 123, parentCell.getCellScale() * parent.getBiome().getChildShrinkFactor()); + int r = childCell.getIndex(x, z, parent.getBiome().getChildren().size() + 1); + + if(r == parent.getBiome().getChildren().size()) + { + return new BiomeResult(parent.getBiome(), childCell.getDistance(x, z)); + } + + IrisBiome biome = Iris.data.getBiomeLoader().load(parent.getBiome().getChildren().get(r)); + biome.setInferredType(parent.getBiome().getInferredType()); + + return implode(bx, bz, regionData, childCell, new BiomeResult(biome, childCell.getDistance(x, z)), hits + 1); + } + } + + return parent; + } + + @Override + public double generate(double x, double z) + { + return 0; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/Blueprint.java b/src/main/java/ninja/bytecode/iris/object/Blueprint.java new file mode 100644 index 000000000..00ee59e13 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/Blueprint.java @@ -0,0 +1,6 @@ +package ninja.bytecode.iris.object; + +public class Blueprint +{ + +} diff --git a/src/main/java/ninja/bytecode/iris/object/Dispersion.java b/src/main/java/ninja/bytecode/iris/object/Dispersion.java new file mode 100644 index 000000000..51e6e98d3 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/Dispersion.java @@ -0,0 +1,7 @@ +package ninja.bytecode.iris.object; + +public enum Dispersion +{ + SCATTER, + WISPY, +} diff --git a/src/main/java/ninja/bytecode/iris/object/InferredType.java b/src/main/java/ninja/bytecode/iris/object/InferredType.java new file mode 100644 index 000000000..0f9bd0137 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/InferredType.java @@ -0,0 +1,8 @@ +package ninja.bytecode.iris.object; + +public enum InferredType +{ + SHORE, + LAND, + SEA +} diff --git a/src/main/java/ninja/bytecode/iris/object/InterpolationMethod.java b/src/main/java/ninja/bytecode/iris/object/InterpolationMethod.java new file mode 100644 index 000000000..e7e03bcc6 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/InterpolationMethod.java @@ -0,0 +1,9 @@ +package ninja.bytecode.iris.object; + +public enum InterpolationMethod +{ + NONE, + BILINEAR, + BICUBIC, + HERMITE +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisAxisRotationClamp.java b/src/main/java/ninja/bytecode/iris/object/IrisAxisRotationClamp.java new file mode 100644 index 000000000..713ca03a1 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisAxisRotationClamp.java @@ -0,0 +1,50 @@ +package ninja.bytecode.iris.object; + +import lombok.Data; +import ninja.bytecode.iris.util.Desc; + +@Desc("Represents a rotation axis with intervals and maxes") +@Data +public class IrisAxisRotationClamp +{ + @Desc("Should this axis be rotated at all?") + private boolean enabled = false; + + @Desc("The minimum angle (from) or set this and max to zero for any angle degrees") + private double min = 0; + + @Desc("The maximum angle (to) or set this and min to zero for any angle degrees") + private double max = 0; + + @Desc("Iris spins the axis but not freely. For example an interval of 90 would mean 4 possible angles (right angles) degrees") + private double interval = 0; + + public IrisAxisRotationClamp() + { + + } + + public IrisAxisRotationClamp(boolean enabled, double min, double max, double interval) + { + this.enabled = enabled; + this.min = min; + this.max = max; + this.interval = interval; + } + + public boolean isUnlimited() + { + return min == max; + } + + public double getRadians(int rng) + { + if(isUnlimited()) + { + return Math.toRadians((rng * interval) % 360D); + } + + double deg = min + (rng * interval) % (Math.abs(max - min) / 360D); + return Math.toRadians(deg); + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisBiome.java b/src/main/java/ninja/bytecode/iris/object/IrisBiome.java new file mode 100644 index 000000000..21d59eb16 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisBiome.java @@ -0,0 +1,220 @@ +package ninja.bytecode.iris.object; + +import java.util.concurrent.locks.ReentrantLock; + +import org.bukkit.block.Biome; +import org.bukkit.block.data.BlockData; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.CellGenerator; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.logging.L; + +@Desc("Represents a biome in iris.") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisBiome extends IrisRegistrant +{ + @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"; + + @Desc("This changes the dispersion of the biome colors if multiple derivatives are chosen") + private Dispersion biomeDispersion = Dispersion.SCATTER; + + @Desc("This zooms in the biome colors if multiple derivatives are chosen") + private double biomeZoom = 1; + + @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; + + @Desc("You can instead specify multiple biome derivatives to randomly scatter colors in this biome") + private KList biomeScatter = new KList<>(); + + @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<>(); + + @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; + + @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<>(); + + @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()); + + @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") + private KList decorators = new KList(); + + @Desc("Objects define what schematics (iob files) iris will place in this biome") + private KList objects = new KList(); + + @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()); + + private transient ReentrantLock lock = new ReentrantLock(); + private transient CellGenerator childrenCell; + private transient InferredType inferredType; + private transient CNG biomeGenerator; + private transient KList layerHeightGenerators; + private transient KList layerSurfaceGenerators; + + public IrisBiome() + { + + } + + public double getHeight(double x, double z, long seed) + { + double height = 0; + + for(IrisBiomeGeneratorLink i : generators) + { + height += i.getHeight(x, z, seed); + } + + return Math.max(0, Math.min(height, 255)); + } + + public CNG getBiomeGenerator(RNG random) + { + if(biomeGenerator == null) + { + biomeGenerator = CNG.signature(random.nextParallelRNG(213949 + hashCode())).scale(biomeDispersion.equals(Dispersion.SCATTER) ? 1000D : 0.1D); + } + + return biomeGenerator; + } + + public CellGenerator getChildrenGenerator(RNG random, int sig, double scale) + { + if(childrenCell == null) + { + childrenCell = new CellGenerator(random.nextParallelRNG(sig * 213)); + childrenCell.setCellScale(scale); + } + + return childrenCell; + } + + public KList generateLayers(double wx, double wz, RNG random, int maxDepth) + { + KList data = new KList<>(); + + for(int i = 0; i < layers.size(); i++) + { + CNG hgen = getLayerHeightGenerators(random).get(i); + int d = hgen.fit(layers.get(i).getMinHeight(), layers.get(i).getMaxHeight(), wx / layers.get(i).getTerrainZoom(), wz / layers.get(i).getTerrainZoom()); + + 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).getTerrainZoom(), j, (wz - j) / layers.get(i).getTerrainZoom())); + } + + catch(Throwable e) + { + L.ex(e); + } + } + + if(data.size() >= maxDepth) + { + break; + } + } + + return data; + } + + public KList getLayerHeightGenerators(RNG rng) + { + lock.lock(); + if(layerHeightGenerators == null) + { + layerHeightGenerators = new KList<>(); + + int m = 7235; + + for(IrisBiomePaletteLayer i : getLayers()) + { + layerHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m))); + } + } + lock.unlock(); + + return layerHeightGenerators; + } + + 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 isShore() + { + if(inferredType == null) + { + return false; + } + return inferredType.equals(InferredType.SHORE); + } + + public Biome getSkyBiome(RNG rng, double x, double y, double z) + { + if(biomeSkyScatter.isEmpty()) + { + return getGroundBiome(rng, x, y, z); + } + + if(biomeSkyScatter.size() == 1) + { + return biomeSkyScatter.get(0); + } + + return biomeSkyScatter.get(getBiomeGenerator(rng).fit(0, biomeSkyScatter.size() - 1, x, y, z)); + } + + public Biome getGroundBiome(RNG rng, double x, double y, double z) + { + if(biomeSkyScatter.isEmpty()) + { + return getDerivative(); + } + + if(biomeScatter.size() == 1) + { + return biomeScatter.get(0); + } + + return biomeScatter.get(getBiomeGenerator(rng).fit(0, biomeScatter.size() - 1, x, y, z)); + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisBiomeDecorator.java b/src/main/java/ninja/bytecode/iris/object/IrisBiomeDecorator.java new file mode 100644 index 000000000..c674743dd --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisBiomeDecorator.java @@ -0,0 +1,141 @@ +package ninja.bytecode.iris.object; + +import org.bukkit.block.data.BlockData; + +import lombok.Data; +import ninja.bytecode.iris.util.BlockDataTools; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.collections.KMap; + +@Desc("A biome decorator is used for placing flowers, grass, cacti and so on") +@Data +public class IrisBiomeDecorator +{ + @Desc("The varience dispersion is used when multiple blocks are put in the palette. Scatter scrambles them, Wispy shows streak-looking varience") + private Dispersion variance = Dispersion.SCATTER; + + @Desc("Dispersion is used to pick places to spawn. Scatter randomly places them (vanilla) or Wispy for a streak like patch system.") + private Dispersion dispersion = Dispersion.SCATTER; + + @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 Dispersion verticalVariance = Dispersion.SCATTER; + + @Desc("The minimum repeat stack height (setting to 3 would stack 3 of on top of each other") + private int stackMin = 1; + + @Desc("The maximum repeat stack height") + private int stackMax = 1; + + @Desc("The zoom is for zooming in or out wispy dispersions. Makes patches bigger the higher this zoom value is/") + private double zoom = 1; + + @Desc("The vertical zoom is for wispy stack heights. Zooming this in makes stack heights more slowly change over a distance") + private double verticalZoom = 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)") + private double chance = 0.1; + + @Desc("The palette of blocks to pick from when this decorator needs to place.") + private KList palette = new KList().qadd("GRASS"); + + private transient KMap layerGenerators; + private transient CNG heightGenerator; + private transient KList blockData; + + public int getHeight(RNG rng, double x, double z) + { + if(stackMin == stackMax) + { + return stackMin; + } + + return getGenerator(rng).fit(stackMin, stackMax, x * (verticalVariance.equals(Dispersion.SCATTER) ? 1000D : 1D), z * (verticalVariance.equals(Dispersion.SCATTER) ? 1000D : 1D)); + } + + public CNG getHeightGenerator(RNG rng) + { + if(heightGenerator == null) + { + heightGenerator = CNG.signature(rng.nextParallelRNG(getBlockData().size() + stackMax + stackMin)).scale(1D / verticalZoom); + } + + return heightGenerator; + } + + public CNG getGenerator(RNG rng) + { + long key = rng.nextParallelRNG(1).nextLong(); + + if(layerGenerators == null) + { + layerGenerators = new KMap<>(); + } + + if(!layerGenerators.containsKey(key)) + { + layerGenerators.put(key, CNG.signature(rng.nextParallelRNG(getBlockData().size())).scale(1D / zoom)); + } + + return layerGenerators.get(key); + } + + public KList add(String b) + { + palette.add(b); + return palette; + } + + public BlockData getBlockData(RNG rng, double x, double z) + { + if(getGenerator(rng) == null) + { + return null; + } + + if(getBlockData() == null) + { + return null; + } + + if(getBlockData().isEmpty()) + { + return null; + } + + if(getGenerator(rng).fitDoubleD(0D, 1D, x * (dispersion.equals(Dispersion.SCATTER) ? 1000D : 1D), z * (dispersion.equals(Dispersion.SCATTER) ? 1000D : 1D)) <= chance) + { + try + { + return getBlockData().get(getGenerator(rng.nextParallelRNG(53)).fit(0, getBlockData().size() - 1, x * (dispersion.equals(Dispersion.SCATTER) ? 1000D : 1D), z * (dispersion.equals(Dispersion.SCATTER) ? 1000D : 1D))); + } + + catch(Throwable e) + { + + } + } + + return null; + } + + public KList getBlockData() + { + if(blockData == null) + { + blockData = new KList<>(); + for(String i : palette) + { + BlockData bx = BlockDataTools.getBlockData(i); + if(bx != null) + { + blockData.add(bx); + } + } + } + + return blockData; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisBiomeGeneratorLink.java b/src/main/java/ninja/bytecode/iris/object/IrisBiomeGeneratorLink.java new file mode 100644 index 000000000..2d0608c87 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisBiomeGeneratorLink.java @@ -0,0 +1,51 @@ +package ninja.bytecode.iris.object; + +import lombok.Data; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.IrisInterpolation; + +@Desc("This represents a link to a generator for a biome") +@Data +public class IrisBiomeGeneratorLink +{ + @Desc("The generator id") + private String generator = "default"; + + @Desc("The min block value (value + fluidHeight)") + private int min = 0; + + @Desc("The max block value (value + fluidHeight)") + private int max = 0; + + private transient IrisGenerator gen; + + public IrisBiomeGeneratorLink() + { + + } + + public IrisGenerator getCachedGenerator() + { + if(gen == null) + { + gen = Iris.data.getGeneratorLoader().load(getGenerator()); + + if(gen == null) + { + gen = new IrisGenerator(); + } + } + + return gen; + } + + public double getHeight(double x, double z, long seed) + { + double g = getCachedGenerator().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/ninja/bytecode/iris/object/IrisBiomePaletteLayer.java b/src/main/java/ninja/bytecode/iris/object/IrisBiomePaletteLayer.java new file mode 100644 index 000000000..10f039153 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisBiomePaletteLayer.java @@ -0,0 +1,112 @@ +package ninja.bytecode.iris.object; + +import java.util.concurrent.locks.ReentrantLock; + +import org.bukkit.block.data.BlockData; + +import lombok.Data; +import ninja.bytecode.iris.util.BlockDataTools; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; + +@Desc("A layer of surface / subsurface material in biomes") +@Data +public class IrisBiomePaletteLayer +{ + @Desc("The dispersion of materials from the palette") + private Dispersion dispersion = Dispersion.SCATTER; + + @Desc("The min thickness of this layer") + private int minHeight = 1; + + @Desc("The max thickness of this layer") + private int maxHeight = 1; + + @Desc("The terrain zoom mostly for zooming in on a wispy palette") + private double terrainZoom = 5; + + @Desc("The palette of blocks to be used in this layer") + private KList palette = new KList().qadd("GRASS_BLOCK"); + + private transient ReentrantLock lock = new ReentrantLock(); + private transient CNG layerGenerator; + private transient CNG heightGenerator; + private transient KList blockData; + + public CNG getHeightGenerator(RNG rng) + { + if(heightGenerator == null) + { + heightGenerator = CNG.signature(rng.nextParallelRNG(minHeight * maxHeight + getBlockData().size())); + } + + return heightGenerator; + } + + public BlockData get(RNG rng, double x, double y, double z) + { + if(layerGenerator == null) + { + cacheGenerator(rng); + } + + if(layerGenerator != null) + { + if(dispersion.equals(Dispersion.SCATTER)) + { + return getBlockData().get(layerGenerator.fit(0, 30000000, x, y, z) % getBlockData().size()); + } + + else + { + return getBlockData().get(layerGenerator.fit(0, getBlockData().size() - 1, x, y, z)); + } + } + + return getBlockData().get(0); + } + + public void cacheGenerator(RNG rng) + { + RNG rngx = rng.nextParallelRNG(minHeight + maxHeight + getBlockData().size()); + + switch(dispersion) + { + case SCATTER: + layerGenerator = CNG.signature(rngx).freq(1000000); + break; + case WISPY: + layerGenerator = CNG.signature(rngx); + break; + } + } + + public KList add(String b) + { + palette.add(b); + + return palette; + } + + public KList getBlockData() + { + lock.lock(); + if(blockData == null) + { + blockData = new KList<>(); + for(String ix : palette) + { + BlockData bx = BlockDataTools.getBlockData(ix); + if(bx != null) + { + blockData.add(bx); + } + } + } + lock.unlock(); + + return blockData; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisDimension.java b/src/main/java/ninja/bytecode/iris/object/IrisDimension.java new file mode 100644 index 000000000..7700f3e2b --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisDimension.java @@ -0,0 +1,122 @@ +package ninja.bytecode.iris.object; + +import org.bukkit.World.Environment; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; + +@Desc("Represents a dimension") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisDimension extends IrisRegistrant +{ + @Desc("The human readable name of this dimension") + private String name = "A Dimension"; + + @Desc("The interpolation function for splicing noise maxes together") + private InterpolationMethod interpolationFunction = InterpolationMethod.BICUBIC; + + @Desc("The interpolation distance scale. Increase = more smooth, less detail") + private double interpolationScale = 63; + + @Desc("The world environment") + private Environment environment = Environment.NORMAL; + + @Desc("Define all of the regions to include in this dimension. Dimensions -> Regions -> Biomes -> Objects etc") + private KList regions = new KList<>(); + + @Desc("The fluid height for this dimension") + private int fluidHeight = 63; + + @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 = ""; + + @Desc("Zoom in or out the biome size. Higher = bigger biomes") + private double biomeZoom = 5D; + + @Desc("Zoom in or out the terrain. This stretches the terrain. Due to performance improvements, Higher than 2.0 may cause weird rounding artifacts. Lower = more terrain changes per block. Its a true zoom-out.") + private double terrainZoom = 2D; + + @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; + + @Desc("Iris adds a few roughness filters to noise. Increasing this smooths it out. Decreasing this makes it bumpier/scratchy") + private double roughnessZoom = 2D; + + @Desc("The height of the roughness filters") + private int roughnessHeight = 3; + + @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; + + @Desc("Coordinate fracturing zoom. Higher = less frequent warping, Lower = more frequent and rapid warping / swirls.") + private double coordFractureZoom = 8; + + @Desc("This zooms in the land space") + private double landZoom = 1; + + @Desc("This can zoom the shores") + private double shoreZoom = 1; + + @Desc("This zooms oceanic biomes") + private double seaZoom = 1; + + @Desc("Zoom in continents") + private double continentZoom = 1; + + @Desc("Change the size of regions") + private double regionZoom = 1; + + @Desc("Disable this to stop placing schematics in biomes") + private boolean placeObjects = true; + + private transient CNG coordFracture; + private transient Double sinr; + private transient Double cosr; + private transient Double rad; + + public CNG getCoordFracture(RNG rng, int signature) + { + if(coordFracture == null) + { + coordFracture = CNG.signature(rng.nextParallelRNG(signature)); + coordFracture.scale(0.012 / coordFractureZoom); + } + + return coordFracture; + } + + public double getDimensionAngle() + { + if(rad == null) + { + rad = Math.toRadians(dimensionAngleDeg); + } + + return rad; + } + + public double sinRotate() + { + if(sinr == null) + { + sinr = Math.sin(getDimensionAngle()); + } + + return sinr; + } + + public double cosRotate() + { + if(cosr == null) + { + cosr = Math.cos(getDimensionAngle()); + } + + return cosr; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisGenerator.java b/src/main/java/ninja/bytecode/iris/object/IrisGenerator.java new file mode 100644 index 000000000..230053448 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisGenerator.java @@ -0,0 +1,71 @@ +package ninja.bytecode.iris.object; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.shuriken.collections.KList; + +@Desc("Represents a composite generator of noise gens") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisGenerator extends IrisRegistrant +{ + @Desc("The zoom or frequency.") + private double zoom = 1; + + @Desc("The opacity, essentially a multiplier on the output.") + private double opacity = 1; + + @Desc("The offset to shift this noise x") + private double offsetX = 0; + + @Desc("The offset to shift this noise z") + private double offsetZ = 0; + + @Desc("The seed for this generator") + private long seed = 1; + + @Desc("The interpolation method when two biomes use different heights but this same generator") + private InterpolationMethod interpolationFunction = InterpolationMethod.BICUBIC; + + @Desc("The interpolation distance scale (blocks) when two biomes use different heights but this same generator") + private double interpolationScale = 7; + + @Desc("The list of noise gens this gen contains.") + private KList composite = new KList(); + + public double getMax() + { + return opacity; + } + + public double getHeight(double rx, double rz, long superSeed) + { + if(composite.isEmpty()) + { + Iris.warn("Useless Generator: Composite is empty in " + getLoadKey()); + return 0; + } + + int hc = hashCode(); + double h = 0; + double tp = 0; + + for(IrisNoiseGenerator i : composite) + { + tp += i.getOpacity(); + h += i.getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom); + } + + double v = (h / tp) * opacity; + + if(Double.isNaN(v)) + { + Iris.warn("Nan value on gen: " + getLoadKey() + ": H = " + h + " TP = " + tp + " OPACITY = " + opacity + " ZOOM = " + zoom); + } + + return v; + } + +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisNoiseGenerator.java b/src/main/java/ninja/bytecode/iris/object/IrisNoiseGenerator.java new file mode 100644 index 000000000..3c704b3b6 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisNoiseGenerator.java @@ -0,0 +1,117 @@ +package ninja.bytecode.iris.object; + +import java.util.concurrent.locks.ReentrantLock; + +import lombok.Data; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.IrisInterpolation; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; + +@Desc("A noise generator") +@Data +public class IrisNoiseGenerator +{ + @Desc("The coordinate input zoom") + private double zoom = 1; + + @Desc("The output multiplier") + private double opacity = 1; + + @Desc("Coordinate offset x") + private double offsetX = 0; + + @Desc("Height output offset y") + private double offsetY = 0; + + @Desc("Coordinate offset z") + private double offsetZ = 0; + + @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; + + @Desc("If this generator uses the default iris swirly/wispy noise generator. Set to false for pure simplex.") + private boolean irisBased = true; + + @Desc("Multiple octaves for multple generators of changing zooms added together") + private int octaves = 1; + + @Desc("Apply a child noise generator to fracture the input coordinates of this generator") + private KList fracture = new KList<>(); + + private transient ReentrantLock lock; + private transient CNG generator; + + public IrisNoiseGenerator() + { + lock = new ReentrantLock(); + } + + public IrisNoiseGenerator(boolean enabled) + { + this(); + this.enabled = enabled; + } + + protected CNG getGenerator(long superSeed) + { + if(generator == null) + { + lock.lock(); + generator = irisBased ? CNG.signature(new RNG(superSeed + 33955677 - seed)) : new CNG(new RNG(superSeed + 33955677 - seed), 1D, octaves); + lock.unlock(); + } + + return generator; + } + + public double getMax() + { + return getOffsetY() + opacity; + } + + public double getNoise(long superSeed, double xv, double zv) + { + 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); + z -= i.getNoise(superSeed + seed + g, zv, xv); + } + g += 819; + } + + double n = getGenerator(superSeed).fitDoubleD(0, opacity, (x / zoom) + offsetX, (z / zoom) + offsetZ); + 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; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisObject.java b/src/main/java/ninja/bytecode/iris/object/IrisObject.java new file mode 100644 index 000000000..ffaed4e47 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisObject.java @@ -0,0 +1,142 @@ +package ninja.bytecode.iris.object; + +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 org.bukkit.Location; +import org.bukkit.block.data.BlockData; +import org.bukkit.util.BlockVector; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.util.BlockDataTools; +import ninja.bytecode.iris.util.IObjectPlacer; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KMap; + +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisObject extends IrisRegistrant +{ + private KMap blocks; + private int w; + private int d; + private int h; + private transient BlockVector center; + + public IrisObject(int w, int h, int d) + { + blocks = new KMap<>(); + this.w = w; + this.h = h; + this.d = d; + center = new BlockVector(w / 2, h / 2, d / 2); + } + + 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()); + din.close(); + return bv; + } + + public void read(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++) + { + blocks.put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), BlockDataTools.getBlockData(din.readUTF())); + } + } + + public void read(File file) throws IOException + { + FileInputStream fin = new FileInputStream(file); + read(fin); + fin.close(); + } + + public void write(File file) throws IOException + { + file.getParentFile().mkdirs(); + FileOutputStream out = new FileOutputStream(file); + write(out); + out.close(); + } + + public void write(OutputStream o) throws IOException + { + DataOutputStream dos = new DataOutputStream(o); + dos.writeInt(w); + dos.writeInt(h); + dos.writeInt(d); + dos.writeInt(blocks.size()); + for(BlockVector i : blocks.k()) + { + dos.writeShort(i.getBlockX()); + dos.writeShort(i.getBlockY()); + dos.writeShort(i.getBlockZ()); + dos.writeUTF(blocks.get(i).getAsString(true)); + } + } + + public void setUnsigned(int x, int y, int z, BlockData block) + { + if(x >= w || y >= h || z >= d) + { + throw new RuntimeException(x + " " + y + " " + z + " exceeds limit of " + w + " " + h + " " + d); + } + + BlockVector v = new BlockVector(x, y, z).subtract(center).toBlockVector(); + + if(block == null) + { + blocks.remove(v); + } + + else + { + blocks.put(v, block); + } + } + + public void place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng) + { + boolean yf = rng.nextBoolean(); + boolean xf = rng.nextBoolean(); + int spinx = rng.imax() / 1000; + int spiny = rng.imax() / 1000; + int spinz = rng.imax() / 1000; + int y = placer.getHighest(x, z) + config.getRotation().rotate(new BlockVector(0, getCenter().getBlockY(), 0), yf, xf, spinx, spiny, spinz).getBlockY(); + + for(BlockVector g : blocks.k()) + { + BlockVector i = g.clone(); + i = config.getRotation().rotate(i.clone(), yf, xf, spinx, spiny, spinz).clone(); + i = config.getTranslate().translate(i.clone()).clone(); + placer.set(x + i.getBlockX(), y + i.getBlockY(), z + i.getBlockZ(), blocks.get(g)); + } + } + + public void place(Location at) + { + for(BlockVector i : blocks.k()) + { + at.clone().add(0, getCenter().getY(), 0).add(i).getBlock().setBlockData(blocks.get(i), false); + } + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisObjectPlacement.java b/src/main/java/ninja/bytecode/iris/object/IrisObjectPlacement.java new file mode 100644 index 000000000..c49350615 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisObjectPlacement.java @@ -0,0 +1,52 @@ +package ninja.bytecode.iris.object; + +import lombok.Data; +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; + +@Data +public class IrisObjectPlacement +{ + @Desc("List of objects to place") + private KList place = new KList<>(); + @Desc("Translate this object's placement") + private IrisObjectTranslate translate = new IrisObjectTranslate(); + @Desc("Rotate this objects placement") + private IrisObjectRotation rotation = new IrisObjectRotation(); + @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; + @Desc("If the chance check passes, place this many in a single chunk") + private int density = 1; + + public IrisObjectPlacement() + { + + } + + public IrisObject getSchematic(RNG random) + { + if(place.isEmpty()) + { + return null; + } + + return Iris.data.getObjectLoader().load(place.get(random.nextInt(place.size()))); + } + + public int getTriesForChunk(RNG random) + { + if(chance <= 0) + { + return 0; + } + + if(chance >= 1 || random.nextDouble() < chance) + { + return density; + } + + return 0; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisObjectRotation.java b/src/main/java/ninja/bytecode/iris/object/IrisObjectRotation.java new file mode 100644 index 000000000..2addb687e --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisObjectRotation.java @@ -0,0 +1,112 @@ +package ninja.bytecode.iris.object; + +import org.bukkit.util.BlockVector; + +import lombok.Data; +import ninja.bytecode.iris.util.Desc; + +@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, 0, 0, 90); + @Desc("The z axis rotation") + private IrisAxisRotationClamp zAxis = new IrisAxisRotationClamp(); + + public IrisObjectRotation() + { + + } + + 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 double getRotation(int spin, IrisAxisRotationClamp clamp) + { + if(!enabled) + { + return 0; + } + + if(!clamp.isEnabled()) + { + return 0; + } + + return clamp.getRadians(spin); + } + + public BlockVector rotate(BlockVector b, boolean yf, boolean xf, int spinx, int spiny, int spinz) + { + if(!canRotate()) + { + return b; + } + + BlockVector v = b.clone(); + + if(yf && canRotateY()) + { + v.rotateAroundY(getYRotation(spiny)); + } + + if(xf && canRotateX()) + { + v.rotateAroundX(getXRotation(spinx)); + } + + if(canRotateZ()) + { + v.rotateAroundZ(getZRotation(spinz)); + } + + if(!xf && canRotateX()) + { + v.rotateAroundX(getXRotation(spinx)); + } + + if(!yf && canRotateY()) + { + 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(); + } + + public boolean canRotate() + { + return canRotateX() || canRotateY() || canRotateZ(); + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisObjectTranslate.java b/src/main/java/ninja/bytecode/iris/object/IrisObjectTranslate.java new file mode 100644 index 000000000..07d5ff6a5 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisObjectTranslate.java @@ -0,0 +1,42 @@ +package ninja.bytecode.iris.object; + +import org.bukkit.util.BlockVector; + +import lombok.Data; +import ninja.bytecode.iris.util.Desc; + +@Desc("Translate objects") +@Data +public class IrisObjectTranslate +{ + @Desc("The x shift in blocks") + private int x; + + @Desc("The x shift in blocks") + private int y; + + @Desc("The x shift in blocks") + private int z; + + public IrisObjectTranslate() + { + x = 0; + y = 0; + 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; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisRegion.java b/src/main/java/ninja/bytecode/iris/object/IrisRegion.java new file mode 100644 index 000000000..94014b3dd --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisRegion.java @@ -0,0 +1,63 @@ +package ninja.bytecode.iris.object; + +import java.util.concurrent.locks.ReentrantLock; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import ninja.bytecode.iris.util.CNG; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.RNG; +import ninja.bytecode.shuriken.collections.KList; + +@Desc("Represents an iris region") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisRegion extends IrisRegistrant +{ + @Desc("The name of the region") + private String name = "A Region"; + @Desc("The shore ration (How much percent of land should be a shore)") + private double shoreRatio = 0.13; + + @Desc("The min shore height") + private double shoreHeightMin = 1.2; + + @Desc("The the max shore height") + private double shoreHeightMax = 3.2; + + @Desc("The varience of the shore height") + private double shoreHeightZoom = 3.14; + + @Desc("The biome implosion ratio, how much to implode biomes into children (chance)") + private double biomeImplosionRatio = 0.4; + + @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<>(); + + @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<>(); + + @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<>(); + + @Desc("Ridge biomes create a vein-like network like rivers through this region") + private KList ridgeBiomes = new KList<>(); + + @Desc("Spot biomes splotch themselves across this region like lakes") + private KList spotBiomes = new KList<>(); + + private transient CNG shoreHeightGenerator; + private transient ReentrantLock lock = new ReentrantLock(); + + public double getShoreHeight(double x, double z) + { + if(shoreHeightGenerator == null) + { + lock.lock(); + shoreHeightGenerator = CNG.signature(new RNG(hashCode())); + lock.unlock(); + } + + return shoreHeightGenerator.fitDoubleD(shoreHeightMin, shoreHeightMax, x / shoreHeightZoom, z / shoreHeightZoom); + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisRegionRidge.java b/src/main/java/ninja/bytecode/iris/object/IrisRegionRidge.java new file mode 100644 index 000000000..65dd058d9 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisRegionRidge.java @@ -0,0 +1,67 @@ +package ninja.bytecode.iris.object; + +import lombok.Data; +import ninja.bytecode.iris.util.CellGenerator; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.RNG; + +@Desc("A ridge config") +@Data +public class IrisRegionRidge +{ + @Desc("The biome name") + private String biome; + @Desc("The type this biome should override (land sea or shore)") + private InferredType type = InferredType.LAND; + @Desc("The chance this biome will be placed in a given spot") + private double chance = 0.75; + @Desc("The scale of the biome ridge. Higher values = wider veins & bigger connected cells") + private double scale = 5; + @Desc("The chance scale (cell chances)") + private double chanceScale = 4; + @Desc("The shuffle, how 'natural' this looks. Compared to pure polygons") + private double shuffle = 16; + @Desc("The chance shuffle (polygon cell chances)") + private double chanceShuffle = 128; + @Desc("The thickness of the vein") + private double thickness = 0.125; + private transient CellGenerator spot; + private transient CellGenerator ridge; + + public IrisRegionRidge() + { + + } + + public boolean isRidge(RNG rng, double x, double z) + { + if(ridge == null) + { + ridge = new CellGenerator(rng.nextParallelRNG(165583 * hashCode())); + ridge.setCellScale(scale); + ridge.setShuffle(shuffle); + } + + if(spot == null) + { + spot = new CellGenerator(rng.nextParallelRNG(168523 * hashCode())); + spot.setCellScale(chanceScale); + spot.setShuffle(shuffle); + } + + if(chance < 1) + { + if(spot.getIndex(x, z, 1000) > chance * 1000) + { + return false; + } + } + + if(ridge.getDistance(x, z) <= thickness) + { + return true; + } + + return false; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisRegionSpot.java b/src/main/java/ninja/bytecode/iris/object/IrisRegionSpot.java new file mode 100644 index 000000000..8962fafc8 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisRegionSpot.java @@ -0,0 +1,45 @@ +package ninja.bytecode.iris.object; + +import lombok.Data; +import ninja.bytecode.iris.util.CellGenerator; +import ninja.bytecode.iris.util.Desc; +import ninja.bytecode.iris.util.RNG; +@Desc("A spot config") +@Data +public class IrisRegionSpot +{ + @Desc("The biome to be placed") + private String biome; + @Desc("Where this spot overrides. Land sea or shore") + private InferredType type = InferredType.LAND; + @Desc("The scale of splotches") + private double scale = 1; + @Desc("Rarity is how often this splotch appears. higher = less often") + private double rarity = 1; + @Desc("The shuffle or how natural the splotch looks like (anti-polygon)") + private double shuffle = 128; + + private transient CellGenerator spot; + + public IrisRegionSpot() + { + + } + + public boolean isSpot(RNG rng, double x, double z) + { + if(spot == null) + { + spot = new CellGenerator(rng.nextParallelRNG(168583 * hashCode())); + spot.setCellScale(scale); + spot.setShuffle(shuffle); + } + + if(spot.getIndex(x, z, (int) (Math.round(rarity) + 8)) == (int) ((Math.round(rarity) + 8) / 2)) + { + return true; + } + + return false; + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/IrisRegistrant.java b/src/main/java/ninja/bytecode/iris/object/IrisRegistrant.java new file mode 100644 index 000000000..51d608f85 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/IrisRegistrant.java @@ -0,0 +1,9 @@ +package ninja.bytecode.iris.object; + +import lombok.Data; + +@Data +public class IrisRegistrant +{ + private String loadKey; +} diff --git a/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicRegionData.java b/src/main/java/ninja/bytecode/iris/object/atomics/AtomicRegionData.java similarity index 73% rename from src/main/java/ninja/bytecode/iris/generator/atomics/AtomicRegionData.java rename to src/main/java/ninja/bytecode/iris/object/atomics/AtomicRegionData.java index 444869b50..22bf5e558 100644 --- a/src/main/java/ninja/bytecode/iris/generator/atomics/AtomicRegionData.java +++ b/src/main/java/ninja/bytecode/iris/object/atomics/AtomicRegionData.java @@ -1,4 +1,4 @@ -package ninja.bytecode.iris.generator.atomics; +package ninja.bytecode.iris.object.atomics; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -7,12 +7,12 @@ import java.io.InputStream; import java.io.OutputStream; import org.bukkit.World; -import org.jnbt.ByteArrayTag; -import org.jnbt.CompoundTag; -import org.jnbt.NBTInputStream; -import org.jnbt.NBTOutputStream; -import org.jnbt.Tag; +import ninja.bytecode.iris.util.ByteArrayTag; +import ninja.bytecode.iris.util.CompoundTag; +import ninja.bytecode.iris.util.NBTInputStream; +import ninja.bytecode.iris.util.NBTOutputStream; +import ninja.bytecode.iris.util.Tag; import ninja.bytecode.shuriken.collections.KMap; public class AtomicRegionData @@ -51,21 +51,27 @@ public class AtomicRegionData tag.remove(rx + "." + rz); } - public void set(int rx, int rz, AtomicChunkData data) throws IOException + public void set(int rx, int rz, AtomicSliverMap data) throws IOException { + if(data == null) + { + return; + } + ByteArrayOutputStream boas = new ByteArrayOutputStream(); data.write(boas); tag.put(rx + "." + rz, new ByteArrayTag(rx + "." + rz, boas.toByteArray())); } - public AtomicChunkData get(int rx, int rz) throws IOException + public AtomicSliverMap get(int rx, int rz) throws IOException { + AtomicSliverMap data = new AtomicSliverMap(); + if(!contains(rx, rz)) { - return null; + return data; } - AtomicChunkData data = new AtomicChunkData(world); ByteArrayTag btag = (ByteArrayTag) tag.get(rx + "." + rz); ByteArrayInputStream in = new ByteArrayInputStream(btag.getValue()); data.read(in); diff --git a/src/main/java/ninja/bytecode/iris/object/atomics/AtomicSliver.java b/src/main/java/ninja/bytecode/iris/object/atomics/AtomicSliver.java new file mode 100644 index 000000000..7382e2901 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/atomics/AtomicSliver.java @@ -0,0 +1,134 @@ +package ninja.bytecode.iris.object.atomics; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import org.bukkit.block.Biome; +import org.bukkit.block.data.BlockData; +import org.bukkit.generator.ChunkGenerator.BiomeGrid; +import org.bukkit.generator.ChunkGenerator.ChunkData; + +import lombok.Data; +import ninja.bytecode.iris.util.BlockDataTools; +import ninja.bytecode.iris.util.HeightMap; +import ninja.bytecode.shuriken.collections.KMap; + +@Data +public class AtomicSliver +{ + private static final BlockData AIR = BlockDataTools.getBlockData("AIR"); + private KMap block; + private KMap biome; + private int highestBlock = 0; + private int highestBiome = 0; + private int x; + private int z; + + public AtomicSliver(int x, int z) + { + this.x = x; + this.z = z; + this.block = new KMap<>(); + this.biome = new KMap<>(); + } + + public void set(int h, BlockData d) + { + if(d == null) + { + return; + } + + block.put(h, d); + highestBlock = h > highestBlock ? h : highestBlock; + } + + public void set(int h, Biome d) + { + biome.put(h, d); + highestBiome = h > highestBiome ? h : highestBiome; + } + + public void write(ChunkData d) + { + for(int i = 0; i <= highestBlock; i++) + { + if(block.get(i) == null) + { + d.setBlock(x, i, z, AIR); + } + + else + { + d.setBlock(x, i, z, block.get(i)); + } + } + } + + public void write(BiomeGrid d) + { + for(int i = 0; i <= highestBiome; i++) + { + if(biome.get(i) != null) + { + d.setBiome(x, i, z, biome.get(i)); + } + } + } + + public void write(HeightMap height) + { + height.setHeight(x, z, highestBlock); + } + + public void read(DataInputStream din) throws IOException + { + this.block = new KMap(); + int h = din.readByte() - Byte.MIN_VALUE; + for(int i = 0; i <= h; i++) + { + block.put(i, BlockDataTools.getBlockData(din.readUTF())); + } + } + + public void write(DataOutputStream dos) throws IOException + { + dos.writeByte(highestBlock + Byte.MIN_VALUE); + + for(int i = 0; i <= highestBlock; i++) + { + BlockData dat = block.get(i); + dos.writeUTF((dat == null ? AIR : dat).getAsString(true)); + } + } + + public void insert(AtomicSliver atomicSliver) + { + for(int i = 0; i < 256; i++) + { + if(block.get(i) == null || block.get(i).equals(AIR)) + { + BlockData b = atomicSliver.block.get(i); + if(b == null || b.equals(AIR)) + { + continue; + } + + block.put(i, b); + } + } + } + + public void inject(ChunkData currentData) + { + for(int i = 0; i < getHighestBlock(); i++) + { + if(block.get(i) != null && !block.get(i).equals(AIR)) + { + BlockData b = block.get(i); + currentData.setBlock(x, i, z, b); + } + } + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/atomics/AtomicSliverMap.java b/src/main/java/ninja/bytecode/iris/object/atomics/AtomicSliverMap.java new file mode 100644 index 000000000..3111e4c2b --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/atomics/AtomicSliverMap.java @@ -0,0 +1,95 @@ +package ninja.bytecode.iris.object.atomics; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.bukkit.generator.ChunkGenerator.BiomeGrid; +import org.bukkit.generator.ChunkGenerator.ChunkData; + +import lombok.Data; +import ninja.bytecode.iris.util.HeightMap; + +@Data +public class AtomicSliverMap +{ + private final AtomicSliver[] slivers; + private boolean parallaxGenerated; + private boolean worldGenerated; + + public AtomicSliverMap() + { + parallaxGenerated = false; + worldGenerated = false; + slivers = new AtomicSliver[256]; + + for(int i = 0; i < 16; i++) + { + for(int j = 0; j < 16; j++) + { + slivers[i * 16 + j] = new AtomicSliver(i, j); + } + } + } + + public void insert(AtomicSliverMap map) + { + for(int i = 0; i < 256; i++) + { + slivers[i].insert(map.slivers[i]); + } + } + + public void write(OutputStream out) throws IOException + { + DataOutputStream dos = new DataOutputStream(out); + dos.writeBoolean(isParallaxGenerated()); + dos.writeBoolean(isWorldGenerated()); + for(int i = 0; i < 256; i++) + { + slivers[i].write(dos); + } + + dos.flush(); + } + + public void read(InputStream in) throws IOException + { + DataInputStream din = new DataInputStream(in); + parallaxGenerated = din.readBoolean(); + worldGenerated = din.readBoolean(); + + for(int i = 0; i < 256; i++) + { + slivers[i].read(din); + } + } + + public AtomicSliver getSliver(int x, int z) + { + return slivers[x * 16 + z]; + } + + public void write(ChunkData data, BiomeGrid grid, HeightMap height) + { + for(AtomicSliver i : slivers) + { + if(i != null) + { + i.write(data); + i.write(grid); + i.write(height); + } + } + } + + public void inject(ChunkData currentData) + { + for(AtomicSliver i : slivers) + { + i.inject(currentData); + } + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/atomics/AtomicWorldData.java b/src/main/java/ninja/bytecode/iris/object/atomics/AtomicWorldData.java new file mode 100644 index 000000000..a64315a30 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/atomics/AtomicWorldData.java @@ -0,0 +1,257 @@ +package ninja.bytecode.iris.object.atomics; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +import org.bukkit.World; + +import ninja.bytecode.iris.util.ChunkPosition; +import ninja.bytecode.shuriken.collections.KMap; +import ninja.bytecode.shuriken.math.M; + +public class AtomicWorldData +{ + private World world; + private KMap loadedChunks; + private KMap loadedSections; + private KMap lastRegion; + + public AtomicWorldData(World world) + { + this.world = world; + loadedSections = new KMap<>(); + loadedChunks = new KMap<>(); + lastRegion = new KMap<>(); + getSubregionFolder().mkdirs(); + } + + public KMap getLoadedRegions() + { + return loadedSections; + } + + public AtomicRegionData getSubregion(int x, int z) throws IOException + { + lastRegion.put(new ChunkPosition(x, z), M.ms()); + + if(!isSectionLoaded(x, z)) + { + loadedSections.put(new ChunkPosition(x, z), loadSection(x, z)); + } + + AtomicRegionData f = loadedSections.get(new ChunkPosition(x, z)); + + return f; + } + + public void saveAll() throws IOException + { + saveChunks(); + + for(ChunkPosition i : loadedSections.keySet()) + { + saveSection(i); + } + } + + public void unloadAll(boolean save) throws IOException + { + saveChunks(); + + for(ChunkPosition i : loadedSections.keySet()) + { + unloadSection(i, save); + } + + loadedSections.clear(); + loadedChunks.clear(); + lastRegion.clear(); + } + + public void deleteSection(int x, int z) throws IOException + { + unloadSection(x, z, false); + getSubregionFile(x, z).delete(); + } + + public boolean isSectionLoaded(int x, int z) + { + return isSectionLoaded(new ChunkPosition(x, z)); + } + + public boolean isSectionLoaded(ChunkPosition s) + { + return loadedSections.containsKey(s); + } + + public boolean unloadSection(int x, int z, boolean save) throws IOException + { + return unloadSection(new ChunkPosition(x, z), save); + } + + public boolean unloadSection(ChunkPosition s, boolean save) throws IOException + { + if(!isSectionLoaded(s)) + { + return false; + } + + if(save) + { + saveSection(s); + } + + loadedSections.remove(s); + return true; + } + + public boolean saveSection(int x, int z) throws IOException + { + return saveSection(new ChunkPosition(x, z)); + } + + public boolean saveSection(ChunkPosition s) throws IOException + { + if(!isSectionLoaded(s.getX(), s.getZ())) + { + return false; + } + + saveChunks(s); + AtomicRegionData data = loadedSections.get(s); + FileOutputStream fos = new FileOutputStream(getSubregionFile(s.getX(), s.getZ())); + data.write(fos); + fos.close(); + return true; + } + + public void saveChunks() throws IOException + { + for(ChunkPosition i : loadedChunks.k()) + { + saveChunk(i); + } + } + + public void saveChunks(ChunkPosition reg) throws IOException + { + for(ChunkPosition i : loadedChunks.k()) + { + int x = i.getX(); + int z = i.getZ(); + + if(x >> 5 == reg.getX() && z >> 5 == reg.getZ()) + { + saveChunk(i); + } + } + } + + public void saveChunk(ChunkPosition i) throws IOException + { + int x = i.getX(); + int z = i.getZ(); + AtomicRegionData dat = loadSection(x >> 5, z >> 5); + dat.set(x & 31, z & 31, loadedChunks.get(i)); + loadedChunks.remove(i); + } + + public AtomicSliverMap loadChunk(int x, int z) throws IOException + { + ChunkPosition pos = new ChunkPosition(x, z); + + if(loadedChunks.containsKey(pos)) + { + return loadedChunks.get(pos); + } + + AtomicRegionData dat = loadSection(x >> 5, z >> 5); + AtomicSliverMap m = dat.get(x & 31, z & 31); + loadedChunks.put(pos, m); + + return m; + } + + public boolean hasChunk(int x, int z) throws IOException + { + return loadSection(x >> 5, z >> 5).contains(x & 31, z & 31); + } + + public AtomicRegionData loadSection(int x, int z) throws IOException + { + ChunkPosition pos = new ChunkPosition(x, z); + lastRegion.put(pos, M.ms()); + + if(isSectionLoaded(x, z)) + { + return loadedSections.get(pos); + } + + File file = getSubregionFile(x, z); + + if(!file.exists()) + { + AtomicRegionData dat = createSection(x, z); + loadedSections.put(pos, dat); + return dat; + } + + FileInputStream fin = new FileInputStream(file); + AtomicRegionData data = new AtomicRegionData(world); + data.read(fin); + fin.close(); + loadedSections.put(pos, data); + return data; + } + + public AtomicRegionData createSection(int x, int z) + { + if(isSectionLoaded(x, z)) + { + return loadedSections.get(new ChunkPosition(x, z)); + } + + AtomicRegionData data = new AtomicRegionData(world); + loadedSections.put(new ChunkPosition(x, z), data); + + return data; + } + + public File getSubregionFile(int x, int z) + { + return new File(getSubregionFolder(), "sr." + x + "." + z + ".smca"); + } + + public File getSubregionFolder() + { + return new File(world.getWorldFolder(), "subregion"); + } + + public KMap getLoadedChunks() + { + return loadedChunks; + } + + public void clean(int j) + { + for(ChunkPosition i : lastRegion.k()) + { + if(M.ms() - lastRegion.get(i) > 60000) + { + lastRegion.remove(i); + + try + { + unloadSection(i, true); + } + + catch(IOException e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/src/main/java/ninja/bytecode/iris/object/atomics/MasterLock.java b/src/main/java/ninja/bytecode/iris/object/atomics/MasterLock.java new file mode 100644 index 000000000..9c3cedc95 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/object/atomics/MasterLock.java @@ -0,0 +1,48 @@ +package ninja.bytecode.iris.object.atomics; + +import java.util.concurrent.locks.ReentrantLock; + +import ninja.bytecode.shuriken.collections.KMap; + +public class MasterLock +{ + private KMap locks; + private ReentrantLock lock; + + public MasterLock() + { + locks = new KMap<>(); + lock = new ReentrantLock(); + } + + public void clear() + { + locks.clear(); + } + + public void lock(String key) + { + lock.lock(); + if(!locks.containsKey(key)) + { + locks.put(key, new ReentrantLock()); + } + + ReentrantLock l = locks.get(key); + lock.unlock(); + l.lock(); + } + + public void unlock(String key) + { + lock.lock(); + if(!locks.containsKey(key)) + { + locks.put(key, new ReentrantLock()); + } + + ReentrantLock l = locks.get(key); + lock.unlock(); + l.unlock(); + } +} diff --git a/src/main/java/ninja/bytecode/iris/pack/BiomeType.java b/src/main/java/ninja/bytecode/iris/pack/BiomeType.java deleted file mode 100644 index b92610de5..000000000 --- a/src/main/java/ninja/bytecode/iris/pack/BiomeType.java +++ /dev/null @@ -1,8 +0,0 @@ -package ninja.bytecode.iris.pack; - -public enum BiomeType -{ - LAND, - FLUID, - FRONT; -} diff --git a/src/main/java/ninja/bytecode/iris/pack/CompiledDimension.java b/src/main/java/ninja/bytecode/iris/pack/CompiledDimension.java deleted file mode 100644 index e5877f52d..000000000 --- a/src/main/java/ninja/bytecode/iris/pack/CompiledDimension.java +++ /dev/null @@ -1,244 +0,0 @@ -package ninja.bytecode.iris.pack; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.function.Consumer; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -import org.bukkit.World.Environment; -import org.bukkit.block.Biome; - -import net.md_5.bungee.api.ChatColor; -import ninja.bytecode.iris.generator.genobject.GenObject; -import ninja.bytecode.iris.generator.genobject.GenObjectGroup; -import ninja.bytecode.iris.util.SChunkVector; -import ninja.bytecode.iris.util.SBlockVector; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.io.CustomOutputStream; -import ninja.bytecode.shuriken.json.JSONObject; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.math.RNG; -import ninja.bytecode.shuriken.reaction.O; - -public class CompiledDimension -{ - public static IrisBiome theVoid = new IrisBiome("Void", Biome.VOID).height(0).seal(RNG.r); - private IrisDimension dimension; - private KList biomes; - private KMap biomeCache; - private KMap objects; - private SBlockVector maxSize; - private SChunkVector maxChunkSize; - - public CompiledDimension(IrisDimension dimension) - { - this.dimension = dimension; - biomes = new KList<>(); - biomeCache = new KMap<>(); - objects = new KMap<>(); - maxSize = new SBlockVector(0, 0, 0); - maxChunkSize = new SChunkVector(0, 0); - } - - public void read(InputStream in) throws IOException - { - GZIPInputStream gin = new GZIPInputStream(in); - DataInputStream din = new DataInputStream(gin); - dimension = new IrisDimension(); - dimension.fromJSON(new JSONObject(din.readUTF()), false); - int bi = din.readInt(); - int ob = din.readInt(); - - for(int i = 0; i < bi; i++) - { - IrisBiome b = new IrisBiome("Loading", Biome.VOID); - b.fromJSON(new JSONObject(din.readUTF()), false); - } - - for(int i = 0; i < ob; i++) - { - GenObjectGroup g = new GenObjectGroup("Loading"); - g.read(din); - } - } - - public void write(OutputStream out, Consumer progress) throws IOException - { - GZIPOutputStream gzo = new CustomOutputStream(out, 1); - DataOutputStream dos = new DataOutputStream(gzo); - dos.writeUTF(dimension.toJSON().toString(0)); - dos.writeInt(biomes.size()); - dos.writeInt(objects.size()); - - for(IrisBiome i : biomes) - { - dos.writeUTF(i.toJSON().toString(0)); - } - - O tc = new O<>(); - O oc = new O<>(); - O cc = new O<>(); - tc.set(0); - oc.set(0); - cc.set(0); - - for(GenObjectGroup i : objects.v()) - { - tc.set(tc.get() + i.size()); - } - - for(GenObjectGroup i : objects.v().shuffle()) - { - i.write(dos, (o) -> - { - cc.set((int) (o * i.size())); - - if(progress != null) - { - progress.accept((double) (oc.get() + cc.get()) / (double) tc.get()); - } - }); - - oc.set(oc.get() + cc.get()); - cc.set(0); - } - - dos.close(); - } - - public void registerBiome(IrisBiome j) - { - biomes.add(j); - biomeCache.put(j.getName(), j); - } - - public void registerObject(GenObjectGroup g) - { - if(g.getName().startsWith("pack/objects/")) - { - g.setName(g.getName().replaceFirst("\\Qpack/objects/\\E", "")); - } - - objects.put(g.getName(), g); - } - - public String getName() - { - return dimension.getName(); - } - - public KList getBiomes() - { - return biomes; - } - - public Environment getEnvironment() - { - return dimension.getEnvironment(); - } - - public GenObjectGroup getObjectGroup(String j) - { - return objects.get(j); - } - - public int countObjects() - { - int m = 0; - - for(GenObjectGroup i : objects.v()) - { - m += i.size(); - } - - return m; - } - - public void sort() - { - biomes.sort(); - } - - public IrisBiome getBiomeByName(String name) - { - IrisBiome b = biomeCache.get(name); - - if(b == null) - { - L.f(ChatColor.RED + "Cannot Find Biome: " + ChatColor.GOLD + name); - return theVoid; - } - - return b; - } - - public void dispose() - { - biomes.clear(); - biomeCache.clear(); - - for(GenObjectGroup i : objects.values()) - { - i.dispose(); - } - - objects.clear(); - } - - public void computeObjectSize() - { - int maxWidth = 0; - int maxHeight = 0; - int maxDepth = 0; - - for(GenObjectGroup i : objects.values()) - { - for(GenObject j : i.getSchematics().copy()) - { - maxWidth = j.getW() > maxWidth ? j.getW() : maxWidth; - maxHeight = j.getH() > maxHeight ? j.getH() : maxHeight; - maxDepth = j.getD() > maxDepth ? j.getD() : maxDepth; - } - } - - maxSize = new SBlockVector(maxWidth, maxHeight, maxDepth); - maxChunkSize = new SChunkVector(Math.ceil((double) (maxWidth) / 16D), Math.ceil((double) (maxDepth) / 16D)); - L.i("Max Object Bound is " + maxWidth + ", " + maxHeight + ", " + maxDepth); - L.i("Max Object Region is " + maxChunkSize.getX() + " by " + maxChunkSize.getZ() + " Chunks"); - } - - public static IrisBiome getTheVoid() - { - return theVoid; - } - - public IrisDimension getDimension() - { - return dimension; - } - - public KMap getBiomeCache() - { - return biomeCache; - } - - public KMap getObjects() - { - return objects; - } - - public SBlockVector getMaxSize() - { - return maxSize; - } - - public SChunkVector getMaxChunkSize() - { - return maxChunkSize; - } -} diff --git a/src/main/java/ninja/bytecode/iris/pack/IrisBiome.java b/src/main/java/ninja/bytecode/iris/pack/IrisBiome.java deleted file mode 100644 index 261e9bb82..000000000 --- a/src/main/java/ninja/bytecode/iris/pack/IrisBiome.java +++ /dev/null @@ -1,1113 +0,0 @@ -package ninja.bytecode.iris.pack; - -import java.lang.reflect.Field; -import java.util.Objects; - -import org.bukkit.Material; -import org.bukkit.block.Biome; - -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.layer.BiomeNoiseGenerator; -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.ObjectMode; -import ninja.bytecode.iris.util.PolygonGenerator; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.execution.J; -import ninja.bytecode.shuriken.json.JSONArray; -import ninja.bytecode.shuriken.json.JSONObject; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.M; -import ninja.bytecode.shuriken.math.RNG; - -public class IrisBiome -{ - public static final double MAX_HEIGHT = 0.77768; - public static final double IDEAL_HEIGHT = 0.138; - public static final double MIN_HEIGHT = -0.0218; - private static final KMap map = build(); - private String name; - private String parent; - private Biome realBiome; - private double height; - private KList rock; - private MB fluid; - private int rockDepth; - private KList surface; - private KList dirt; - private KMap scatterChance; - private boolean scatterSurface; - private boolean scatterSurfaceRock; - private boolean scatterSurfaceSub; - private boolean core; - private int dirtDepth; - private double surfaceScale; - private double subSurfaceScale; - private double rockScale; - private boolean simplexScatter; - private boolean simplexScatterRock; - private boolean simplexScatterSub; - private double snow; - private double lush; - private double cliffChance; - private double cliffScale; - private double genScale; - private double genAmplifier; - private double genSwirl; - private double genSwirlScale; - private double rarity; - private boolean cliffs; - private BiomeNoiseGenerator bng; - private BiomeType type; - private String region; - private KMap schematicGroups; - private PolygonGenerator.EnumPolygonGenerator poly; - private PolygonGenerator.EnumPolygonGenerator polySub; - private PolygonGenerator.EnumPolygonGenerator polyRock; - - public static double getMaxHeight() - { - return MAX_HEIGHT; - } - - public static double getIdealHeight() - { - return IDEAL_HEIGHT; - } - - public static double getMinHeight() - { - return MIN_HEIGHT; - } - - public static KMap getMap() - { - return map; - } - - public boolean isScatterSurface() - { - return scatterSurface; - } - - public boolean isCore() - { - return core; - } - - public boolean isSimplexScatter() - { - return simplexScatter; - } - - public PolygonGenerator.EnumPolygonGenerator getPoly() - { - return poly; - } - - public IrisBiome(JSONObject json) - { - this("Loading", Biome.OCEAN); - fromJSON(json); - } - - public IrisBiome(String name, Biome realBiome) - { - this.region = "default"; - this.core = false; - this.name = name; - lush = 0; - type = BiomeType.LAND; - cliffs = false; - fluid = MB.of(Material.STATIONARY_WATER); - genScale = 1; - rarity = 1; - genAmplifier = 0.35; - genSwirl = 1; - genSwirlScale = 1; - cliffScale = 1; - cliffChance = 0.37; - parent = ""; - dirtDepth = 19; - this.realBiome = realBiome; - this.height = IDEAL_HEIGHT; - rockDepth = 23; - surfaceScale = 1; - subSurfaceScale = 1; - rockScale = 1; - simplexScatterRock = false; - scatterSurfaceRock = true; - simplexScatterSub = false; - scatterSurfaceSub = true; - scatterChance = new KMap<>(); - schematicGroups = new KMap<>(); - //@builder - surface(new MB(Material.GRASS)) - .dirt(new MB(Material.DIRT), new MB(Material.DIRT, 1)) - .rock(MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5), - MB.of(Material.STONE, 5)); - //@done - } - - public void fromJSON(JSONObject o) - { - fromJSON(o, true); - } - - public IrisBiome seal(RNG rng) - { - if(simplexScatter) - { - poly = new PolygonGenerator.EnumPolygonGenerator(rng, 0.125, 2, getSurface().toArray(new MB[getSurface().size()]), (g) -> - { - return g.scale(0.09 * surfaceScale).fractureWith(new CNG(rng.nextParallelRNG(56), 1D, 2).scale(0.0955), 55); - }); - } - - else - { - poly = new PolygonGenerator.EnumPolygonGenerator(rng, 15.05, 2, getSurface().toArray(new MB[getSurface().size()]), (g) -> - { - return g.scale(surfaceScale).fractureWith(new CNG(rng.nextParallelRNG(55), 1D, 2).scale(0.0155), 224); - }); - } - - if(simplexScatterSub) - { - polySub = new PolygonGenerator.EnumPolygonGenerator(rng, 0.125, 2, getDirt().toArray(new MB[getDirt().size()]), (g) -> - { - return g.scale(0.06 * subSurfaceScale).fractureWith(new CNG(rng.nextParallelRNG(526), 1D, 2).scale(0.0955), 55); - }); - } - - else - { - polySub = new PolygonGenerator.EnumPolygonGenerator(rng, 15.05, 2, getDirt().toArray(new MB[getDirt().size()]), (g) -> - { - return g.scale(subSurfaceScale).fractureWith(new CNG(rng.nextParallelRNG(515), 1D, 2).scale(0.0155), 224); - }); - } - - if(simplexScatterRock) - { - polyRock = new PolygonGenerator.EnumPolygonGenerator(rng, 0.125, 2, getRock().toArray(new MB[getRock().size()]), (g) -> - { - return g.scale(0.08 * rockScale).fractureWith(new CNG(rng.nextParallelRNG(562), 1D, 2).scale(0.0955), 55); - }); - } - - else - { - polyRock = new PolygonGenerator.EnumPolygonGenerator(rng, 15.05, 2, getRock().toArray(new MB[getRock().size()]), (g) -> - { - return g.scale(rockScale).fractureWith(new CNG(rng.nextParallelRNG(551), 1D, 2).scale(0.0155), 224); - }); - } - - bng = new BiomeNoiseGenerator(rng.nextParallelRNG(2077), this); - - return this; - } - - public BiomeNoiseGenerator getGenerator() - { - if(polySub == null) - { - L.w(getName() + " is not sealed!"); - } - - return bng; - } - - public void fromJSON(JSONObject o, boolean chain) - { - name = o.getString("name"); - realBiome = Biome.valueOf(o.getString("derivative").toUpperCase().replaceAll(" ", "_")); - type = BiomeType.valueOf(o.getString("type").toUpperCase().replaceAll(" ", "_")); - J.attempt(() -> region = o.getString("region")); - J.attempt(() -> parent = o.getString("parent")); - J.attempt(() -> height(o.getDouble("height"))); - J.attempt(() -> height(o.getDouble("genHeight"))); - J.attempt(() -> genAmplifier = o.getDouble("genAmplifier")); - J.attempt(() -> genSwirl = o.getDouble("genSwirl")); - J.attempt(() -> genSwirlScale = o.getDouble("genSwirlScale")); - J.attempt(() -> genScale = o.getDouble("genScale")); - J.attempt(() -> snow = o.getDouble("snow")); - J.attempt(() -> lush = o.getDouble("lush")); - J.attempt(() -> rarity = o.getDouble("rarity")); - J.attempt(() -> fluid = MB.of(o.getString("fluid"))); - J.attempt(() -> dirtDepth = o.getInt("subSurfaceDepth")); - J.attempt(() -> dirtDepth = o.getInt("dirtDepth")); - J.attempt(() -> rockDepth = o.getInt("rockDepth")); - J.attempt(() -> cliffScale = o.getDouble("cliffScale")); - J.attempt(() -> rockScale = o.getDouble("rockScale")); - J.attempt(() -> surfaceScale = o.getDouble("surfaceScale")); - J.attempt(() -> subSurfaceScale = o.getDouble("subSurfaceScale")); - J.attempt(() -> cliffChance = o.getDouble("cliffChance")); - J.attempt(() -> cliffs = o.getBoolean("cliffs")); - J.attempt(() -> surface = mbListFromJSON(o.getJSONArray("surface"))); - J.attempt(() -> rock = mbListFromJSON(o.getJSONArray("rock"))); - J.attempt(() -> dirt = mbListFromJSON(o.getJSONArray("subSurface"))); - J.attempt(() -> dirt = mbListFromJSON(o.getJSONArray("dirt"))); - J.attempt(() -> scatterChance = scatterFromJSON(o.getJSONArray("scatter"))); - J.attempt(() -> simplexScatter = o.getString("surfaceType").equalsIgnoreCase("simplex")); - J.attempt(() -> scatterSurface = o.getString("surfaceType").equalsIgnoreCase("scatter")); - J.attempt(() -> simplexScatterRock = o.getString("rockType").equalsIgnoreCase("simplex")); - J.attempt(() -> scatterSurfaceRock = o.getString("rockType").equalsIgnoreCase("scatter")); - J.attempt(() -> simplexScatterSub = o.getString("subSurfaceType").equalsIgnoreCase("simplex")); - J.attempt(() -> scatterSurfaceSub = o.getString("subSurfaceType").equalsIgnoreCase("scatter")); - J.attempt(() -> - { - if(!Iris.settings.performance.objectMode.equals(ObjectMode.NONE)) - { - schematicGroups = strFromJSON(o.getJSONArray("objects")); - } - - else - { - schematicGroups = new KMap<>(); - } - - if(chain) - { - if(!Iris.settings.performance.objectMode.equals(ObjectMode.NONE)) - { - for(String i : schematicGroups.k()) - { - Iris.pack().loadSchematicGroup(i); - } - } - } - }); - } - - public JSONObject toJSON() - { - JSONObject j = new JSONObject(); - j.put("name", name); - J.attempt(() -> j.put("parent", parent)); - J.attempt(() -> j.put("region", region)); - J.attempt(() -> j.put("derivative", realBiome.name().toLowerCase().replaceAll("_", " "))); - J.attempt(() -> j.put("type", type.name().toLowerCase().replaceAll("_", " "))); - J.attempt(() -> j.put("rarity", rarity)); - J.attempt(() -> j.put("fluid", fluid.toString())); - J.attempt(() -> j.put("genHeight", height)); - J.attempt(() -> j.put("genScale", genScale)); - J.attempt(() -> j.put("genSwirl", genSwirl)); - J.attempt(() -> j.put("genSwirlScale", genSwirlScale)); - J.attempt(() -> j.put("genAmplifier", genAmplifier)); - J.attempt(() -> j.put("snow", snow)); - J.attempt(() -> j.put("lush", lush)); - J.attempt(() -> j.put("cliffs", cliffs)); - J.attempt(() -> j.put("cliffScale", cliffScale)); - J.attempt(() -> j.put("rockScale", rockScale)); - J.attempt(() -> j.put("subSurfaceScale", subSurfaceScale)); - J.attempt(() -> j.put("surfaceScale", surfaceScale)); - J.attempt(() -> j.put("cliffChance", cliffChance)); - J.attempt(() -> j.put("surface", mbListToJSON(surface))); - J.attempt(() -> j.put("rock", mbListToJSON(rock))); - J.attempt(() -> j.put("subSurfaceDepth", dirtDepth)); - J.attempt(() -> j.put("rockDepth", rockDepth)); - J.attempt(() -> j.put("subSurface", mbListToJSON(dirt))); - J.attempt(() -> j.put("scatter", scatterToJson(scatterChance))); - J.attempt(() -> j.put("surfaceType", simplexScatter ? "simplex" : scatterSurface ? "scatter" : "na")); - J.attempt(() -> j.put("subSurfaceType", simplexScatterSub ? "simplex" : scatterSurfaceSub ? "scatter" : "na")); - J.attempt(() -> j.put("rockType", simplexScatterRock ? "simplex" : scatterSurfaceRock ? "scatter" : "na")); - J.attempt(() -> j.put("objects", strToJson(schematicGroups))); - - return j; - } - - private KList mbListFromJSON(JSONArray ja) - { - KList mb = new KList<>(); - - for(int i = 0; i < ja.length(); i++) - { - mb.add(MB.of(ja.getString(i))); - } - - return mb; - } - - private JSONArray mbListToJSON(KList mbs) - { - JSONArray ja = new JSONArray(); - - for(MB i : mbs) - { - ja.put(i.toString()); - } - - return ja; - } - - public IrisBiome coreBiome() - { - this.core = true; - return this; - } - - private KMap scatterFromJSON(JSONArray ja) - { - KMap mb = new KMap(); - - for(int i = 0; i < ja.length(); i++) - { - String s = ja.getString(i); - mb.put(MB.of(s.split("\\Q=\\E")[0]), Double.valueOf(s.split("\\Q=\\E")[1])); - } - - return mb; - } - - private JSONArray scatterToJson(KMap mbs) - { - JSONArray ja = new JSONArray(); - - for(MB i : mbs.k()) - { - ja.put(i.toString() + "=" + mbs.get(i)); - } - - return ja; - } - - private KMap strFromJSON(JSONArray ja) - { - KMap mb = new KMap(); - - for(int i = 0; i < ja.length(); i++) - { - String s = ja.getString(i); - mb.put(s.split("\\Q=\\E")[0], Double.valueOf(s.split("\\Q=\\E")[1])); - } - - return mb; - } - - private JSONArray strToJson(KMap mbs) - { - JSONArray ja = new JSONArray(); - - for(String i : mbs.k()) - { - ja.put(i.toString() + "=" + mbs.get(i)); - } - - return ja; - } - - private static KMap build() - { - KMap g = new KMap(); - - for(Field i : IrisBiome.class.getDeclaredFields()) - { - J.attempt(() -> - { - i.setAccessible(true); - - IrisBiome bb = (IrisBiome) i.get(null); - - if(!g.containsKey(bb.realBiome)) - { - g.put(bb.realBiome, bb); - } - }); - } - - return g; - } - - public IrisBiome scatter(MB mb, Double chance) - { - scatterChance.put(mb, chance); - - return this; - } - - public IrisBiome schematic(String t, double chance) - { - schematicGroups.put(t, chance); - - return this; - } - - public IrisBiome simplexSurface() - { - simplexScatter = true; - return this; - } - - public IrisBiome scatterSurface() - { - scatterSurface = true; - return this; - } - - public IrisBiome surface(MB... mbs) - { - surface = new KList<>(mbs); - return this; - } - - public IrisBiome dirt(MB... mbs) - { - dirt = new KList<>(mbs); - return this; - } - - public IrisBiome rock(MB... mbs) - { - rock = new KList<>(mbs); - return this; - } - - public IrisBiome height(double height) - { - if(height >= 0) - { - this.height = M.lerp(IDEAL_HEIGHT, MAX_HEIGHT, M.clip(height, 0D, 1D)); - } - - else - { - this.height = M.lerp(MIN_HEIGHT, IDEAL_HEIGHT, 1d - Math.abs(M.clip(height, -1D, 0D))); - } - - return this; - } - - public String getName() - { - return name; - } - - public Biome getRealBiome() - { - return realBiome; - } - - public double getHeight() - { - return height; - } - - public KList getSurface() - { - return surface; - } - - public KList getRock() - { - return rock; - } - - public KList getDirt() - { - return dirt; - } - - public MB getSurface(double x, double z, RNG rng) - { - double wx = x + 1000D; - double wz = z + 1000D; - - if(polySub == null) - { - L.w(getName() + " is not sealed!"); - } - - if(simplexScatter) - { - return poly.getChoice(wx / 3, wz / 3); - } - - if(scatterSurface) - { - return poly.getChoice(wx * 0.2D, wz * 0.2D); - } - - return getSurface().getRandom(); - } - - public MB getSubSurface(double x, double i, double z, RNG rng) - { - double wx = x + 1000D; - double wz = z + 1000D; - - if(polySub == null) - { - L.w(getName() + " is not sealed!"); - } - - if(simplexScatterSub) - { - return polySub.getChoice(wx / 3, i / 3, wz / 3); - } - - if(scatterSurfaceSub) - { - return polySub.getChoice(wx * 0.2D, i / 3, wz * 0.2D); - } - - return getSurface().getRandom(); - } - - public MB getRock(double x, double i, double z, RNG rng) - { - double wx = x + 1000D; - double wz = z + 1000D; - - if(polySub == null) - { - L.w(getName() + " is not sealed!"); - } - - if(simplexScatterRock) - { - return polyRock.getChoice(wx / 3, i / 3, wz / 3); - } - - if(scatterSurfaceRock) - { - return polyRock.getChoice(wx * 0.2D, i * 0.2D, wz * 0.2D); - } - - return getSurface().getRandom(); - } - - public KMap getScatterChance() - { - return scatterChance; - } - - public MB getScatterChanceSingle(double d, double aux) - { - KList a = new KList<>(); - - for(MB i : getScatterChance().keySet()) - { - if(d < getScatterChance().get(i)) - { - a.add(i); - } - } - - if(a.isEmpty()) - { - return MB.of(Material.AIR); - } - - if(a.size() == 1) - { - return a.get(0); - } - - return a.get((int) (aux * (a.size() - 1))); - } - - public static KList getBiomes() - { - return map.v(); - } - - public static IrisBiome findByBiome(Biome biome) - { - if(map.containsKey(biome)) - { - return map.get(biome); - } - - return null; - } - - public KMap getSchematicGroups() - { - return schematicGroups; - } - - public boolean isSurface(Material t) - { - for(MB i : surface) - { - if(i.material.equals(t)) - { - return true; - } - } - - return false; - } - - public String getRegionID() - { - return region; - } - - public boolean isSnowy() - { - return getSnow() > 0; - } - - public double getSnow() - { - return snow; - } - - public double getCliffScale() - { - return cliffScale; - } - - public boolean hasCliffs() - { - return cliffs; - } - - public int getDirtDepth() - { - return dirtDepth; - } - - public int getRockDepth() - { - return rockDepth; - } - - public boolean isCliffs() - { - return cliffs; - } - - public double getCliffChance() - { - return cliffChance; - } - - public String getParent() - { - return parent; - } - - public KList getParents() - { - KList f = new KList<>(); - - if(getParent().trim().isEmpty()) - { - return f; - } - - if(getParent().contains("&")) - { - for(String i : getParent().split("\\Q&\\E")) - { - f.add(i.trim()); - } - } - - else - { - f.add(getParent().trim()); - } - - return f; - } - - public boolean isScatterSurfaceRock() - { - return scatterSurfaceRock; - } - - public boolean isScatterSurfaceSub() - { - return scatterSurfaceSub; - } - - public double getSurfaceScale() - { - return surfaceScale; - } - - public double getSubSurfaceScale() - { - return subSurfaceScale; - } - - public double getRockScale() - { - return rockScale; - } - - public boolean isSimplexScatterRock() - { - return simplexScatterRock; - } - - public boolean isSimplexScatterSub() - { - return simplexScatterSub; - } - - public BiomeType getType() - { - return type; - } - - public PolygonGenerator.EnumPolygonGenerator getPolySub() - { - return polySub; - } - - public PolygonGenerator.EnumPolygonGenerator getPolyRock() - { - return polyRock; - } - - public double getGenScale() - { - return genScale; - } - - public void setGenScale(double genScale) - { - this.genScale = genScale; - } - - public double getGenAmplifier() - { - return genAmplifier; - } - - public void setGenAmplifier(double genAmplifier) - { - this.genAmplifier = genAmplifier; - } - - public double getGenSwirl() - { - return genSwirl; - } - - public void setGenSwirl(double genSwirl) - { - this.genSwirl = genSwirl; - } - - public void setName(String name) - { - this.name = name; - } - - public void setParent(String parent) - { - this.parent = parent; - } - - public void setRealBiome(Biome realBiome) - { - this.realBiome = realBiome; - } - - public void setHeight(double height) - { - this.height = height; - } - - public void setRock(KList rock) - { - this.rock = rock; - } - - public void setRockDepth(int rockDepth) - { - this.rockDepth = rockDepth; - } - - public void setSurface(KList surface) - { - this.surface = surface; - } - - public void setDirt(KList dirt) - { - this.dirt = dirt; - } - - public void setScatterChance(KMap scatterChance) - { - this.scatterChance = scatterChance; - } - - public void setScatterSurface(boolean scatterSurface) - { - this.scatterSurface = scatterSurface; - } - - public void setScatterSurfaceRock(boolean scatterSurfaceRock) - { - this.scatterSurfaceRock = scatterSurfaceRock; - } - - public void setScatterSurfaceSub(boolean scatterSurfaceSub) - { - this.scatterSurfaceSub = scatterSurfaceSub; - } - - public void setCore(boolean core) - { - this.core = core; - } - - public void setDirtDepth(int dirtDepth) - { - this.dirtDepth = dirtDepth; - } - - public void setSurfaceScale(double surfaceScale) - { - this.surfaceScale = surfaceScale; - } - - public void setSubSurfaceScale(double subSurfaceScale) - { - this.subSurfaceScale = subSurfaceScale; - } - - public void setRockScale(double rockScale) - { - this.rockScale = rockScale; - } - - public void setSimplexScatter(boolean simplexScatter) - { - this.simplexScatter = simplexScatter; - } - - public void setSimplexScatterRock(boolean simplexScatterRock) - { - this.simplexScatterRock = simplexScatterRock; - } - - public void setSimplexScatterSub(boolean simplexScatterSub) - { - this.simplexScatterSub = simplexScatterSub; - } - - public void setSnow(double snow) - { - this.snow = snow; - } - - public void setCliffChance(double cliffChance) - { - this.cliffChance = cliffChance; - } - - public void setCliffScale(double cliffScale) - { - this.cliffScale = cliffScale; - } - - public void setCliffs(boolean cliffs) - { - this.cliffs = cliffs; - } - - public void setType(BiomeType type) - { - this.type = type; - } - - public void setRegion(String region) - { - this.region = region; - } - - public void setSchematicGroups(KMap schematicGroups) - { - this.schematicGroups = schematicGroups; - } - - public void setPoly(PolygonGenerator.EnumPolygonGenerator poly) - { - this.poly = poly; - } - - public void setPolySub(PolygonGenerator.EnumPolygonGenerator polySub) - { - this.polySub = polySub; - } - - public void setPolyRock(PolygonGenerator.EnumPolygonGenerator polyRock) - { - this.polyRock = polyRock; - } - - public double getGenSwirlScale() - { - return genSwirlScale; - } - - public void setGenSwirlScale(double genSwirlScale) - { - this.genSwirlScale = genSwirlScale; - } - - public BiomeNoiseGenerator getBng() - { - return bng; - } - - public void setBng(BiomeNoiseGenerator bng) - { - this.bng = bng; - } - - public double getRarity() - { - return rarity; - } - - public String getRarityString() - { - if(getRarity() <= 0.1) - { - return C.RED + "Literally Everywhere"; - } - - else if(getRarity() < 0.25) - { - return "Overly Abundant"; - } - - else if(getRarity() < 0.4) - { - return "Very Abundant"; - } - - else if(getRarity() < 0.6) - { - return "Abundant"; - } - - else if(getRarity() < 0.75) - { - return "Very Common"; - } - - else if(getRarity() <= 1) - { - return "Common"; - } - - else if(getRarity() <= 2) - { - return "Often"; - } - - else if(getRarity() <= 3) - { - return "Uncommon"; - } - - else if(getRarity() <= 6) - { - return "Rare"; - } - - else if(getRarity() <= 16) - { - return "Very Rare"; - } - - else if(getRarity() <= 50) - { - return "Exceedingly Rare"; - } - - else if(getRarity() <= 100) - { - return "Marvelously Rare"; - } - - else if(getRarity() <= 200) - { - return "Extraordinarily Rare"; - } - - else - { - return "Start Praying"; - } - } - - public MB getFluid() - { - return fluid; - } - - public void setFluid(MB fluid) - { - this.fluid = fluid; - } - - public void setRarity(double rarity) - { - this.rarity = rarity; - } - - public double getLush() - { - return lush; - } - - public String getRegion() - { - return region; - } - - @Override - public int hashCode() - { - return Objects.hash(bng, cliffChance, cliffScale, cliffs, core, dirt, dirtDepth, fluid, genAmplifier, genScale, genSwirl, genSwirlScale, height, lush, name, parent, poly, polyRock, polySub, rarity, realBiome, region, rock, rockDepth, rockScale, scatterChance, scatterSurface, scatterSurfaceRock, scatterSurfaceSub, schematicGroups, simplexScatter, simplexScatterRock, simplexScatterSub, snow, subSurfaceScale, surface, surfaceScale, type); - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - { - return true; - } - if(!(obj instanceof IrisBiome)) - { - return false; - } - IrisBiome other = (IrisBiome) obj; - return Objects.equals(bng, other.bng) && Double.doubleToLongBits(cliffChance) == Double.doubleToLongBits(other.cliffChance) && Double.doubleToLongBits(cliffScale) == Double.doubleToLongBits(other.cliffScale) && cliffs == other.cliffs && core == other.core && Objects.equals(dirt, other.dirt) && dirtDepth == other.dirtDepth && Objects.equals(fluid, other.fluid) && Double.doubleToLongBits(genAmplifier) == Double.doubleToLongBits(other.genAmplifier) && Double.doubleToLongBits(genScale) == Double.doubleToLongBits(other.genScale) && Double.doubleToLongBits(genSwirl) == Double.doubleToLongBits(other.genSwirl) && Double.doubleToLongBits(genSwirlScale) == Double.doubleToLongBits(other.genSwirlScale) && Double.doubleToLongBits(height) == Double.doubleToLongBits(other.height) && Double.doubleToLongBits(lush) == Double.doubleToLongBits(other.lush) && Objects.equals(name, other.name) && Objects.equals(parent, other.parent) && Objects.equals(poly, other.poly) && Objects.equals(polyRock, other.polyRock) && Objects.equals(polySub, other.polySub) && Double.doubleToLongBits(rarity) == Double.doubleToLongBits(other.rarity) && realBiome == other.realBiome && Objects.equals(region, other.region) && Objects.equals(rock, other.rock) && rockDepth == other.rockDepth && Double.doubleToLongBits(rockScale) == Double.doubleToLongBits(other.rockScale) && Objects.equals(scatterChance, other.scatterChance) && scatterSurface == other.scatterSurface && scatterSurfaceRock == other.scatterSurfaceRock && scatterSurfaceSub == other.scatterSurfaceSub && Objects.equals(schematicGroups, other.schematicGroups) && simplexScatter == other.simplexScatter && simplexScatterRock == other.simplexScatterRock && simplexScatterSub == other.simplexScatterSub && Double.doubleToLongBits(snow) == Double.doubleToLongBits(other.snow) && Double.doubleToLongBits(subSurfaceScale) == Double.doubleToLongBits(other.subSurfaceScale) && Objects.equals(surface, other.surface) && Double.doubleToLongBits(surfaceScale) == Double.doubleToLongBits(other.surfaceScale) && type == other.type; - } - - public boolean isLush() - { - return lush > 0; - } -} diff --git a/src/main/java/ninja/bytecode/iris/pack/IrisDimension.java b/src/main/java/ninja/bytecode/iris/pack/IrisDimension.java deleted file mode 100644 index f01cfe739..000000000 --- a/src/main/java/ninja/bytecode/iris/pack/IrisDimension.java +++ /dev/null @@ -1,109 +0,0 @@ -package ninja.bytecode.iris.pack; - -import java.io.IOException; - -import org.bukkit.World.Environment; - -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.execution.J; -import ninja.bytecode.shuriken.json.JSONArray; -import ninja.bytecode.shuriken.json.JSONException; -import ninja.bytecode.shuriken.json.JSONObject; - -public class IrisDimension -{ - private String name; - private Environment environment; - KList biomes; - - public IrisDimension(JSONObject o) throws JSONException, IOException - { - this(); - fromJSON(o); - } - - public IrisDimension() - { - biomes = new KList(); - environment = Environment.NORMAL; - } - - public void fromJSON(JSONObject o) throws JSONException, IOException - { - fromJSON(o, true); - } - - public void fromJSON(JSONObject o, boolean chain) throws JSONException, IOException - { - name = o.getString("name"); - J.attempt(() -> environment = Environment.valueOf(o.getString("environment").toUpperCase().replaceAll(" ", "_"))); - - try - { - biomes = chain ? biomesFromArray(o.getJSONArray("biomes")) : new KList<>(); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - public JSONObject toJSON() - { - JSONObject o = new JSONObject(); - - o.put("name", name); - o.put("environment", environment.name().toLowerCase().replaceAll("_", " ")); - o.put("biomes", biomesToArray(biomes)); - - return o; - } - - private KList biomesFromArray(JSONArray a) throws JSONException, IOException - { - KList b = new KList<>(); - for(int i = 0; i < a.length(); i++) - { - int ii = i; - - IrisBiome bb = Iris.pack().loadBiome(a.getString(ii)); - Iris.pack().registerBiome(a.getString(ii), bb); - b.add(bb); - } - return b; - } - - private JSONArray biomesToArray(KList b) - { - JSONArray a = new JSONArray(); - - for(IrisBiome i : b) - { - a.put(i.getName().toLowerCase().replaceAll(" ", "_")); - } - - return a; - } - - public KList getBiomes() - { - return biomes; - } - - public String getName() - { - return name; - } - - public Environment getEnvironment() - { - return environment; - } - - public void dispose() - { - biomes.clear(); - } -} diff --git a/src/main/java/ninja/bytecode/iris/pack/IrisPack.java b/src/main/java/ninja/bytecode/iris/pack/IrisPack.java deleted file mode 100644 index 783e25a72..000000000 --- a/src/main/java/ninja/bytecode/iris/pack/IrisPack.java +++ /dev/null @@ -1,86 +0,0 @@ -package ninja.bytecode.iris.pack; - -import java.io.IOException; - -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.execution.J; -import ninja.bytecode.shuriken.json.JSONArray; -import ninja.bytecode.shuriken.json.JSONException; -import ninja.bytecode.shuriken.json.JSONObject; - -public class IrisPack -{ - private KList dimensions; - private KList biomes; - private KList objects; - - public IrisPack() - { - this.dimensions = new KList<>(); - this.biomes = new KList<>(); - this.objects = new KList<>(); - } - - public IrisPack(JSONObject o) - { - this(); - fromJSON(o); - } - - public void fromJSON(JSONObject o) - { - J.attempt(() -> dimensions = fromArray(o.getJSONArray("dimensions"))); - J.attempt(() -> biomes = fromArray(o.getJSONArray("biomes"))); - J.attempt(() -> objects = fromArray(o.getJSONArray("objects"))); - } - - public JSONObject toJSON() - { - JSONObject o = new JSONObject(); - o.put("dimensions", toArray(dimensions)); - o.put("biomes", toArray(biomes)); - o.put("objects", toArray(objects)); - - return o; - } - - public KList fromArray(JSONArray ja) - { - KList g = new KList<>(); - - for(int i = 0; i < ja.length(); i++) - { - g.add(ja.getString(i)); - } - - return g; - } - - public JSONArray toArray(KList s) - { - JSONArray ja = new JSONArray(); - - for(String i : s) - { - ja.put(i); - } - - return ja; - } - - public void load() throws JSONException, IOException - { - for(String i : dimensions) - { - IrisDimension d = Iris.pack().loadDimension(i); - Iris.pack().registerDimension(i, d); - } - } - - public void loadBiome(String s) throws JSONException, IOException - { - IrisBiome b = Iris.pack().loadBiome(s); - Iris.pack().registerBiome(s, b); - } -} diff --git a/src/main/java/ninja/bytecode/iris/pack/IrisRegion.java b/src/main/java/ninja/bytecode/iris/pack/IrisRegion.java deleted file mode 100644 index c3ab94851..000000000 --- a/src/main/java/ninja/bytecode/iris/pack/IrisRegion.java +++ /dev/null @@ -1,123 +0,0 @@ -package ninja.bytecode.iris.pack; - -import java.util.Objects; - -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.execution.J; -import ninja.bytecode.shuriken.json.JSONObject; - -public class IrisRegion -{ - private String name; - private KList biomes; - private IrisBiome ocean; - private IrisBiome deepOcean; - private IrisBiome lake; - private IrisBiome lakeBeach; - private IrisBiome channel; - private IrisBiome beach; - - public IrisRegion(String name) - { - this.name = name; - this.biomes = new KList<>(); - beach = null; - ocean = null; - deepOcean = null; - lake = null; - lakeBeach = null; - channel = null; - } - - public void load() - { - J.attempt(() -> - { - JSONObject o = Iris.pack().loadJSON("pack/regions/" + name + ".json"); - J.attempt(() -> name = o.getString("name")); - J.attempt(() -> ocean = Iris.pack().getBiomeById(o.getString("ocean"))); - J.attempt(() -> deepOcean = Iris.pack().getBiomeById(o.getString("deepOcean"))); - J.attempt(() -> beach = Iris.pack().getBiomeById(o.getString("beach"))); - J.attempt(() -> lake = Iris.pack().getBiomeById(o.getString("lake"))); - J.attempt(() -> lakeBeach = Iris.pack().getBiomeById(o.getString("shore"))); - J.attempt(() -> channel = Iris.pack().getBiomeById(o.getString("channel"))); - }); - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public KList getBiomes() - { - return biomes; - } - - public void setBiomes(KList biomes) - { - this.biomes = biomes; - } - - public IrisBiome getBeach() - { - return beach; - } - - public void setBeach(IrisBiome beach) - { - this.beach = beach; - } - - public IrisBiome getOcean() - { - return ocean; - } - - public IrisBiome getDeepOcean() - { - return deepOcean; - } - - public IrisBiome getLake() - { - return lake; - } - - public IrisBiome getShore() - { - return lakeBeach; - } - - public IrisBiome getChannel() - { - return channel; - } - - @Override - public int hashCode() - { - return Objects.hash(beach, biomes, channel, lake, lakeBeach, name, ocean); - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - { - return true; - } - if(!(obj instanceof IrisRegion)) - { - return false; - } - IrisRegion other = (IrisRegion) obj; - return Objects.equals(beach, other.beach) && Objects.equals(biomes, other.biomes) && Objects.equals(channel, other.channel) && Objects.equals(lake, other.lake) && Objects.equals(lakeBeach, other.lakeBeach) && Objects.equals(name, other.name) && Objects.equals(ocean, other.ocean); - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/Average.java b/src/main/java/ninja/bytecode/iris/util/Average.java new file mode 100644 index 000000000..aa00b327d --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/Average.java @@ -0,0 +1,85 @@ +package ninja.bytecode.iris.util; + +/** + * 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 double[] values; + private double average; + private double lastSum; + private boolean dirty; + protected int cursor; + 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/ninja/bytecode/iris/util/BasePerlinNoiseGenerator.java b/src/main/java/ninja/bytecode/iris/util/BasePerlinNoiseGenerator.java new file mode 100644 index 000000000..f353284ad --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BasePerlinNoiseGenerator.java @@ -0,0 +1,219 @@ +package ninja.bytecode.iris.util; + +import java.util.Random; + +/** + * Generates noise using the "classic" perlin generator + * + * @see SimplexNoiseC "Improved" and faster version with slighly + * different results + */ +public class BasePerlinNoiseGenerator extends NoiseGenerator +{ + protected static final int grad3[][] = {{1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1}}; + private static final BasePerlinNoiseGenerator instance = new BasePerlinNoiseGenerator(); + + protected BasePerlinNoiseGenerator() + { + int p[] = {151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}; + + for(int i = 0; i < 512; i++) + { + perm[i] = p[i & 255]; + } + } + + /** + * Creates a seeded perlin noise generator for the given seed + * + * @param seed + * Seed to construct this generator for + */ + public BasePerlinNoiseGenerator(long seed) + { + this(new Random(seed)); + } + + /** + * Creates a seeded perlin noise generator with the given Random + * + * @param rand + * Random to construct with + */ + public BasePerlinNoiseGenerator(Random rand) + { + offsetX = rand.nextDouble() * 256; + offsetY = rand.nextDouble() * 256; + offsetZ = rand.nextDouble() * 256; + + for(int i = 0; i < 256; i++) + { + perm[i] = rand.nextInt(256); + } + + for(int i = 0; i < 256; i++) + { + int pos = rand.nextInt(256 - i) + i; + int old = perm[i]; + + perm[i] = perm[pos]; + perm[pos] = old; + perm[i + 256] = perm[i]; + } + } + + /** + * Computes and returns the 1D unseeded perlin noise for the given coordinates + * in 1D space + * + * @param x + * X coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x) + { + return instance.noise(x); + } + + /** + * Computes and returns the 2D unseeded perlin noise for the given coordinates + * in 2D space + * + * @param x + * X coordinate + * @param y + * Y coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x, double y) + { + return instance.noise(x, y); + } + + /** + * Computes and returns the 3D unseeded perlin noise for the given coordinates + * in 3D space + * + * @param x + * X coordinate + * @param y + * Y coordinate + * @param z + * Z coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x, double y, double z) + { + return instance.noise(x, y, z); + } + + /** + * Gets the singleton unseeded instance of this generator + * + * @return Singleton + */ + public static BasePerlinNoiseGenerator getInstance() + { + return instance; + } + + @Override + public double noise(double x, double y, double z) + { + x += offsetX; + y += offsetY; + z += offsetZ; + + int floorX = floor(x); + int floorY = floor(y); + int floorZ = floor(z); + + // Find unit cube containing the point + int X = floorX & 255; + int Y = floorY & 255; + int Z = floorZ & 255; + + // Get relative xyz coordinates of the point within the cube + x -= floorX; + y -= floorY; + z -= floorZ; + + // Compute fade curves for xyz + double fX = fade(x); + double fY = fade(y); + double fZ = fade(z); + + // Hash coordinates of the cube corners + int A = perm[X] + Y; + int AA = perm[A] + Z; + int AB = perm[A + 1] + Z; + int B = perm[X + 1] + Y; + int BA = perm[B] + Z; + int BB = perm[B + 1] + Z; + + return lerp(fZ, lerp(fY, lerp(fX, grad(perm[AA], x, y, z), grad(perm[BA], x - 1, y, z)), lerp(fX, grad(perm[AB], x, y - 1, z), grad(perm[BB], x - 1, y - 1, z))), lerp(fY, lerp(fX, grad(perm[AA + 1], x, y, z - 1), grad(perm[BA + 1], x - 1, y, z - 1)), lerp(fX, grad(perm[AB + 1], x, y - 1, z - 1), grad(perm[BB + 1], x - 1, y - 1, z - 1)))); + } + + /** + * Generates noise for the 1D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, int octaves, double frequency, double amplitude) + { + return instance.noise(x, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 2D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param y + * Y-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, double y, int octaves, double frequency, double amplitude) + { + return instance.noise(x, y, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 3D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param y + * Y-coordinate + * @param z + * Z-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, double y, double z, int octaves, double frequency, double amplitude) + { + return instance.noise(x, y, z, octaves, frequency, amplitude); + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/BiomeDominance.java b/src/main/java/ninja/bytecode/iris/util/BiomeDominance.java new file mode 100644 index 000000000..e6e9a2664 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BiomeDominance.java @@ -0,0 +1,9 @@ +package ninja.bytecode.iris.util; + +import ninja.bytecode.iris.object.IrisBiome; +import ninja.bytecode.shuriken.collections.KMap; + +public class BiomeDominance extends KMap +{ + private static final long serialVersionUID = 9055245062942178392L; +} diff --git a/src/main/java/ninja/bytecode/iris/util/BiomeLayer.java b/src/main/java/ninja/bytecode/iris/util/BiomeLayer.java deleted file mode 100644 index a2c4754be..000000000 --- a/src/main/java/ninja/bytecode/iris/util/BiomeLayer.java +++ /dev/null @@ -1,219 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.util.function.Function; - -import org.bukkit.Material; -import org.bukkit.block.Biome; - -import mortar.lang.collection.GList; -import mortar.lang.collection.GMap; -import mortar.logic.format.F; -import mortar.util.text.C; -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.iris.pack.BiomeType; -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.iris.util.PolygonGenerator.EnumPolygonGenerator; -import ninja.bytecode.shuriken.collections.KSet; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.math.CNG; -import ninja.bytecode.shuriken.math.RNG; - -public class BiomeLayer -{ - public static final IrisBiome VOID = new IrisBiome("Master", Biome.VOID).height(-1).dirt(MB.of(Material.END_BRICKS)).seal(RNG.r); - private GList children; - private EnumPolygonGenerator gen; - private IrisBiome biome; - private IrisGenerator iris; - - public BiomeLayer(IrisGenerator iris, IrisBiome biome) - { - this.biome = biome == null ? VOID : biome; - this.iris = iris; - this.children = new GList<>(); - } - - public void compileChildren(double scale, int octaves, Function factory, boolean inf) - { - if(gen != null) - { - return; - } - - if(children.isEmpty()) - { - gen = null; - return; - } - - GList b = new GList<>(); - GMap rarities = new GMap<>(); - for(BiomeLayer i : getChildren()) - { - b.add(i); - rarities.put(i, i.getBiome().getRarity()); - } - - if(!getBiome().equals(VOID)) - { - b.add(this); - rarities.put(this, getBiome().getRarity()); - } - - gen = new EnumPolygonGenerator<>(iris.getRTerrain().nextParallelRNG(1022 + getBiome().getRealBiome().ordinal()), scale, octaves, b, rarities, factory).useRarity(); - - for(BiomeLayer i : getChildren()) - { - i.compileChildren(scale, octaves, factory, inf); - } - } - - private IrisBiome computeBiome(double x, double z, GList f) - { - if(gen != null) - { - BiomeLayer b = gen.getChoice(x, z); - - if(b.biome.equals(biome)) - { - return biome; - } - - if(f.contains(b.getBiome().getName())) - { - f.add("..."); - f.add(b.getBiome().getName()); - L.w(C.YELLOW + "Cyclic Biome Heiarchy Detected! " + C.RED + f.toString(C.GRAY + " -> " + C.RED)); - return b.biome; - } - - f.add(b.getBiome().getName()); - - return b.computeBiome(x, z, f); - } - - return getBiome(); - } - - public IrisBiome computeBiome(double x, double z) - { - return computeBiome(x, z, new GList()); - } - - public void addLayer(IrisBiome biome) - { - addLayer(new BiomeLayer(iris, biome)); - } - - public void addLayer(BiomeLayer layer) - { - getChildren().add(layer); - } - - public IrisBiome getBiome() - { - return biome; - } - - public GList getChildren() - { - return children; - } - - public void setChildren(GList children) - { - this.children = children; - } - - public void print(int indent) - { - print(0, F.repeat(" ", indent)); - } - - private void print(int index, String indent) - { - L.i(C.GRAY + F.repeat(indent, index) + "Layer " + C.DARK_GREEN + getBiome().getName() + C.GRAY + "(" + C.GOLD + getBiome().getRarityString() + C.GRAY + ")" + (getBiome().getGenAmplifier() != 0.35 ? C.DARK_AQUA + " A: " + getBiome().getGenAmplifier() : "") + (getBiome().getHeight() != 0.0 ? C.DARK_RED + " H: " + getBiome().getHeight() : "") + (getBiome().hasCliffs() ? C.DARK_PURPLE + " C: " + getBiome().getCliffChance() + " x " + getBiome().getCliffScale() : "")); - L.flush(); - if(!getBiome().getSchematicGroups().isEmpty()) - { - for(String i : getBiome().getSchematicGroups().k()) - { - String f = ""; - double percent = getBiome().getSchematicGroups().get(i); - - if(percent > 1D) - { - f = (int) percent + " + " + F.pc(percent - (int) percent, percent - (int) percent >= 0.01 ? 0 : 3); - } - - else - { - f = F.pc(percent, percent >= 0.01 ? 0 : 3); - } - - L.i(C.GRAY + F.repeat(indent, index + 1) + "Object " + C.GOLD + i + C.GRAY + " at " + C.GOLD + f + C.GRAY + " (" + F.f(iris.getDimension().getObjectGroup(i).size()) + " variants)"); - } - } - - L.flush(); - for(BiomeLayer i : children) - { - i.print(index + 1, indent); - } - } - - public static BiomeLayer compile(IrisGenerator g, double scale, int octaves, Function factory) - { - return compile(g, scale, octaves, factory, false); - } - - public static BiomeLayer compile(IrisGenerator g, double scale, int octaves, Function factory, boolean inf) - { - GMap components = new GMap<>(); - - for(IrisBiome i : g.getDimension().getBiomes()) - { - if(i.getType().equals(BiomeType.LAND)) - { - components.put(i.getName(), new BiomeLayer(g, i)); - } - } - - KSet deject = new KSet<>(); - - for(String i : components.keySet()) - { - BiomeLayer b = components.get(i); - - for(String j : b.getBiome().getParents()) - { - try - { - components.get(j).addLayer(b); - deject.add(i); - } - - catch(Throwable e) - { - L.w(C.YELLOW + "Cannot find Biome " + C.RED + j + C.YELLOW + " (" + C.WHITE + b.getBiome().getName() + C.YELLOW + "'s so-called 'parent'.)"); - } - } - } - - BiomeLayer master = new BiomeLayer(g, null); - - for(String i : components.k()) - { - if(deject.contains(i)) - { - continue; - } - - master.addLayer(components.get(i)); - } - - master.compileChildren(scale, octaves, factory, inf); - - return master; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/BiomeMap.java b/src/main/java/ninja/bytecode/iris/util/BiomeMap.java new file mode 100644 index 000000000..bd915a268 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BiomeMap.java @@ -0,0 +1,23 @@ +package ninja.bytecode.iris.util; + +import ninja.bytecode.iris.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/ninja/bytecode/iris/util/BiomeResult.java b/src/main/java/ninja/bytecode/iris/util/BiomeResult.java new file mode 100644 index 000000000..5d41802b5 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BiomeResult.java @@ -0,0 +1,22 @@ +package ninja.bytecode.iris.util; + +import lombok.Data; +import ninja.bytecode.iris.object.IrisBiome; + +@Data +public class BiomeResult +{ + private IrisBiome biome; + private double distance; + + public BiomeResult(IrisBiome biome, double distance) + { + this.biome = biome; + this.distance = distance; + } + + public boolean is(BiomeResult r) + { + return biome.getName().equals(r.biome.getName()); + } +} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/BlockDataTools.java b/src/main/java/ninja/bytecode/iris/util/BlockDataTools.java new file mode 100644 index 000000000..d9afb5b83 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BlockDataTools.java @@ -0,0 +1,82 @@ +package ninja.bytecode.iris.util; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.block.data.BlockData; + +import ninja.bytecode.iris.Iris; +import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.collections.KMap; + +public class BlockDataTools +{ + private static final KMap bdc = new KMap<>(); + private static final KList nulls = new KList<>(); + + public static BlockData getBlockData(String bd) + { + if(bdc.containsKey(bd)) + { + return bdc.get(bd).clone(); + } + + try + { + BlockData bdx = parseBlockData(bd); + + if(bdx == null) + { + Iris.warn("Unknown Block Data '" + bd + "'"); + nulls.add(bd); + return bdx; + } + + bdc.put(bd, bdx); + + return bdx; + } + + catch(Throwable e) + { + Iris.warn("Unknown Block Data '" + bd + "'"); + } + + return null; + } + + public static BlockData parseBlockData(String ix) + { + try + { + BlockData bx = Bukkit.createBlockData(ix); + + if(bx != null) + { + return bx; + } + } + + catch(Throwable e) + { + + } + + String i = ix.toUpperCase().trim(); + i = i.equals("WOOL") ? "WHITE_WOOL" : i; + i = i.equals("CONCRETE") ? "WHITE_CONCRETE" : i; + + try + { + Material m = Material.valueOf(i); + + return m.createBlockData(); + } + + catch(Throwable e) + { + + } + + return null; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/BlockPosition.java b/src/main/java/ninja/bytecode/iris/util/BlockPosition.java new file mode 100644 index 000000000..3e60ff4fb --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BlockPosition.java @@ -0,0 +1,28 @@ +package ninja.bytecode.iris.util; + +import lombok.Data; + +@Data +public class BlockPosition +{ + 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 int getChunkX() + { + return x >> 4; + } + + public int getChunkZ() + { + return z >> 4; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/Board.java b/src/main/java/ninja/bytecode/iris/util/Board.java new file mode 100644 index 000000000..1649f7749 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/Board.java @@ -0,0 +1,131 @@ +package ninja.bytecode.iris.util; + +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +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 lombok.NonNull; +import lombok.Setter; + +/** + * @author Missionary (missionarymc@gmail.com) + * @since 3/23/2018 + */ +public class Board { + + private static final String[] CACHED_ENTRIES = new String[ChatColor.values().length]; + + private static final Function APPLY_COLOR_TRANSLATION = s -> ChatColor.translateAlternateColorCodes('&', s); + + static { + IntStream.range(0, 15).forEach(i -> CACHED_ENTRIES[i] = ChatColor.values()[i].toString() + ChatColor.RESET); + } + + private final Player player; + private final Objective objective; + private final Team team; + @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); + this.team = this.getScoreboard().getTeam("board") == null ? this.getScoreboard().registerNewTeam("board") : this.getScoreboard().getTeam("board"); + this.team.setAllowFriendlyFire(true); + this.team.setCanSeeFriendlyInvisibles(false); + this.team.setPrefix(""); + this.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(ChatColor.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); + break; + case DOWN: + objective.getScore(team.getName()).setScore(15 - i); + break; + } + } + } + + 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/ninja/bytecode/iris/util/BoardEntry.java b/src/main/java/ninja/bytecode/iris/util/BoardEntry.java new file mode 100644 index 000000000..6448d3847 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BoardEntry.java @@ -0,0 +1,40 @@ +package ninja.bytecode.iris.util; + +import lombok.Getter; +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; + +/** + * @author Missionary (missionarymc@gmail.com) + * @since 3/29/2018 + */ +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(ChatColor.getLastColors(prefix) + suffix + input.substring(16), 16); + return new BoardEntry(prefix, suffix); + } + } +} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/BoardManager.java b/src/main/java/ninja/bytecode/iris/util/BoardManager.java new file mode 100644 index 000000000..d2f8184ec --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BoardManager.java @@ -0,0 +1,86 @@ +package ninja.bytecode.iris.util; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +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; + +/** + * @author Missionary (missionarymc@gmail.com) + * @since 3/23/2018 + */ +public class BoardManager implements Listener { + + private final JavaPlugin plugin; + private BoardSettings boardSettings; + private Map scoreboards; + private BukkitTask updateTask; + + public BoardManager(JavaPlugin plugin, BoardSettings boardSettings) { + this.plugin = plugin; + this.boardSettings = boardSettings; + this.scoreboards = new ConcurrentHashMap<>(); + this.updateTask = new BoardUpdateTask(this).runTaskTimer(plugin, 2L, 2L); + plugin.getServer().getPluginManager().registerEvents(this, plugin); + 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())); + } + + private void setup(Player player) { + Optional.ofNullable(scoreboards.remove(player.getUniqueId())).ifPresent(Board::resetScoreboard); + if (player.getScoreboard() == Bukkit.getScoreboardManager().getMainScoreboard()) { + player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + scoreboards.put(player.getUniqueId(), new Board(player, boardSettings)); + } + + private void remove(Player player) { + Optional.ofNullable(scoreboards.remove(player.getUniqueId())).ifPresent(Board::remove); + } + + public Map getScoreboards() { + return Collections.unmodifiableMap(scoreboards); + } + + @EventHandler + public void onJoin(final PlayerJoinEvent e) { + plugin.getServer().getScheduler().runTaskLater(plugin, () -> { + if (e.getPlayer().isOnline()) { // Set this up 2 ticks later. + setup(e.getPlayer()); + } + }, 2L); + } + + @EventHandler + public void onQuit(final PlayerQuitEvent e) { + this.remove(e.getPlayer()); + } + + public void onDisable() { + updateTask.cancel(); + plugin.getServer().getOnlinePlayers().forEach(this::remove); + scoreboards.clear(); + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/BoardProvider.java b/src/main/java/ninja/bytecode/iris/util/BoardProvider.java new file mode 100644 index 000000000..21b91ebfa --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BoardProvider.java @@ -0,0 +1,25 @@ +package ninja.bytecode.iris.util; + +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Objective; + +import java.util.List; + +public interface BoardProvider { + + /** + * Gets the title for {@link Objective#getDisplayName()} + * + * @param player The {@link Player} to supply + * @return The title for the objective + */ + String getTitle(Player player); + + /** + * Gets the contents to be displayed on the {@link Board} + * + * @param player The {@link Player} to supply + * @return The {@link List} of contents + */ + List getLines(Player player); +} diff --git a/src/main/java/ninja/bytecode/iris/util/BoardSettings.java b/src/main/java/ninja/bytecode/iris/util/BoardSettings.java new file mode 100644 index 000000000..d2a5dd732 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BoardSettings.java @@ -0,0 +1,18 @@ +package ninja.bytecode.iris.util; + +import lombok.Builder; +import lombok.Getter; + +/** + * @author Missionary (missionarymc@gmail.com) + * @since 5/31/2018 + */ +@Getter +@Builder +public class BoardSettings { + + private BoardProvider boardProvider; + + private ScoreDirection scoreDirection; + +} diff --git a/src/main/java/ninja/bytecode/iris/util/BoardUpdateTask.java b/src/main/java/ninja/bytecode/iris/util/BoardUpdateTask.java new file mode 100644 index 000000000..365f64e18 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/BoardUpdateTask.java @@ -0,0 +1,26 @@ +package ninja.bytecode.iris.util; + +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/ninja/bytecode/iris/util/BorderCheck.java b/src/main/java/ninja/bytecode/iris/util/BorderCheck.java deleted file mode 100644 index 28758325e..000000000 --- a/src/main/java/ninja/bytecode/iris/util/BorderCheck.java +++ /dev/null @@ -1,7 +0,0 @@ -package ninja.bytecode.iris.util; - -@FunctionalInterface -public interface BorderCheck -{ - public T get(double x, double z); -} diff --git a/src/main/java/ninja/bytecode/iris/util/Borders.java b/src/main/java/ninja/bytecode/iris/util/Borders.java deleted file mode 100644 index adfe50a03..000000000 --- a/src/main/java/ninja/bytecode/iris/util/Borders.java +++ /dev/null @@ -1,44 +0,0 @@ -package ninja.bytecode.iris.util; - -import ninja.bytecode.shuriken.math.M; - -public class Borders -{ - public static double getDistanceToBorder(double x, double z, int samples, double minRadius, double maxRadius, double jump, BorderCheck check) - { - double offset = 0; - double fract = 1; - - for(double i = minRadius; i < maxRadius; i += jump * fract) - { - offset += jump / 3D; - fract += 0.333; - - if(isBorderWithin(x, z, samples, maxRadius, offset, check)) - { - return minRadius; - } - } - - return maxRadius; - } - - public static boolean isBorderWithin(double x, double z, int samples, double radius, double offset, BorderCheck check) - { - T center = check.get(x, z); - double ajump = Math.toRadians(360D / (double) samples) + offset; - - for(int i = 0; i < samples; i++) - { - double dx = M.sin((float) ajump * i) * radius; - double dz = M.cos((float) ajump * i) * radius; - - if(!center.equals(check.get(x + dx, z + dz))) - { - return true; - } - } - - return false; - } -} diff --git a/src/main/java/org/jnbt/ByteArrayTag.java b/src/main/java/ninja/bytecode/iris/util/ByteArrayTag.java similarity index 98% rename from src/main/java/org/jnbt/ByteArrayTag.java rename to src/main/java/ninja/bytecode/iris/util/ByteArrayTag.java index 9b88ae90e..b73bb8ff4 100644 --- a/src/main/java/org/jnbt/ByteArrayTag.java +++ b/src/main/java/ninja/bytecode/iris/util/ByteArrayTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/org/jnbt/ByteTag.java b/src/main/java/ninja/bytecode/iris/util/ByteTag.java similarity index 98% rename from src/main/java/org/jnbt/ByteTag.java rename to src/main/java/ninja/bytecode/iris/util/ByteTag.java index f259f9b2a..b25fb4ab4 100644 --- a/src/main/java/org/jnbt/ByteTag.java +++ b/src/main/java/ninja/bytecode/iris/util/ByteTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/ninja/bytecode/iris/util/CNG.java b/src/main/java/ninja/bytecode/iris/util/CNG.java new file mode 100644 index 000000000..45e0b5f24 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/CNG.java @@ -0,0 +1,225 @@ +package ninja.bytecode.iris.util; + +import ninja.bytecode.shuriken.collections.KList; + +public class CNG +{ + public static long hits = 0; + public static long creates = 0; + 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}; + private double freq; + private double amp; + private double scale; + private double fscale; + private KList children; + private CNG fracture; + private SNG generator; + private final double opacity; + private NoiseInjector injector; + private RNG rng; + private int oct; + private double patch; + private double up; + private double down; + private double power; + + public static CNG signature(RNG rng) + { + //@builder + return new CNG(rng.nextParallelRNG(17), 1D, 3) + .scale(0.012) + .fractureWith(new CNG(rng.nextParallelRNG(18), 1, 2) + .scale(0.018) + .child(new CNG(rng.nextParallelRNG(19), 1, 2) + .scale(0.1)) + .fractureWith(new CNG(rng.nextParallelRNG(20), 1, 2) + .scale(0.15), 24), 44).down(0.3).patch(2.5); + //@done + } + + 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) + { + creates += octaves; + this.oct = octaves; + this.rng = random; + power = 1; + freq = 1; + amp = 1; + scale = 1; + patch = 1; + fscale = 1; + fracture = null; + generator = new SNG(random); + this.opacity = opacity; + this.injector = ADD; + } + + public CNG child(CNG c) + { + if(children == null) + { + children = new KList<>(); + } + + children.add(c); + return this; + } + + @Deprecated + public RNG nextRNG() + { + return getRNG().nextRNG(); + } + + 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 freq(double c) + { + freq = c; + return this; + } + + public CNG amp(double c) + { + amp = 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 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 fitDouble(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 fitDoubleD(double min, double max, double... dim) + { + if(min == max) + { + return min; + } + + double noise = noise(dim); + + return IrisInterpolation.lerp(min, max, noise); + } + + public int fitDoubleExponent(double min, double max, double exponent, double... dim) + { + if(min == max) + { + return (int) Math.round(min); + } + + double noise = noise(dim); + + return (int) Math.round(IrisInterpolation.lerp(min, max, exponent == 1 ? noise : Math.pow(noise, exponent))); + } + + public double noise(double... dim) + { + double f = fracture != null ? (fracture.noise(dim) - 0.5) * fscale : 0D; + 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; + double n = ((generator.noise(x * scale, y * scale, z * scale, oct, freq, amp, true) / 2D) + 0.5D) * opacity; + n = power != 1D ? 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; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/Callback.java b/src/main/java/ninja/bytecode/iris/util/Callback.java new file mode 100644 index 000000000..9cf3374c1 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/Callback.java @@ -0,0 +1,6 @@ +package ninja.bytecode.iris.util; + +public interface Callback +{ + public void run(T t); +} diff --git a/src/main/java/ninja/bytecode/iris/util/Catalyst12.java b/src/main/java/ninja/bytecode/iris/util/Catalyst12.java deleted file mode 100644 index 7d3e3b49a..000000000 --- a/src/main/java/ninja/bytecode/iris/util/Catalyst12.java +++ /dev/null @@ -1,52 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.craftbukkit.v1_12_R1.CraftWorld; - -import net.minecraft.server.v1_12_R1.IBlockData; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.execution.J; - -public class Catalyst12 -{ - public static void waitForChunk(World w, int x, int z) - { - if(!w.isChunkLoaded(x, z)) - { - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> w.loadChunk(x, z, true)); - } - - int i = 0; - while(!w.isChunkLoaded(x, z) && i < 20) - { - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> w.loadChunk(x, z, true)); - J.sleep(50); - i++; - } - } - - @SuppressWarnings("deprecation") - public static void setBlock(World wo, int x, int y, int z, MB m) - { - if(y > wo.getMaxHeight()) - { - return; - } - - net.minecraft.server.v1_12_R1.World w = ((CraftWorld) wo).getHandle(); - net.minecraft.server.v1_12_R1.Chunk chunk = w.getChunkAt(x >> 4, z >> 4); - int combined = m.material.getId() + (m.data << 12); - IBlockData ibd = net.minecraft.server.v1_12_R1.Block.getByCombinedId(combined); - - if(chunk.getSections()[y >> 4] == null) - { - chunk.getSections()[y >> 4] = new net.minecraft.server.v1_12_R1.ChunkSection(y >> 4 << 4, chunk.world.worldProvider.m()); - } - - net.minecraft.server.v1_12_R1.ChunkSection sec = chunk.getSections()[y >> 4]; - sec.setType(x & 15, y & 15, z & 15, ibd); - } - - -} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/CellGenerator.java b/src/main/java/ninja/bytecode/iris/util/CellGenerator.java new file mode 100644 index 000000000..2745cd21d --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/CellGenerator.java @@ -0,0 +1,54 @@ +package ninja.bytecode.iris.util; + +import lombok.Getter; +import lombok.Setter; +import ninja.bytecode.iris.util.FastNoise.CellularDistanceFunction; +import ninja.bytecode.iris.util.FastNoise.CellularReturnType; +import ninja.bytecode.iris.util.FastNoise.NoiseType; + +public class CellGenerator +{ + private FastNoise fn; + private FastNoise fd; + private 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); + int s = rx.nextInt(); + fn = new FastNoise(s); + fn.SetNoiseType(NoiseType.Cellular); + fn.SetCellularReturnType(CellularReturnType.CellValue); + fn.SetCellularDistanceFunction(CellularDistanceFunction.Natural); + fd = new FastNoise(s); + fd.SetNoiseType(NoiseType.Cellular); + fd.SetCellularReturnType(CellularReturnType.Distance2Sub); + fd.SetCellularDistanceFunction(CellularDistanceFunction.Natural); + } + + public float getDistance(double x, double z) + { + return ((fd.GetCellular((float) ((x * cellScale) + (cng.noise(x, z) * shuffle)), (float) ((z * cellScale) + (cng.noise(z, x) * shuffle)))) + 1f) / 2f; + } + + public float getValue(double x, double z, int possibilities) + { + return ((fn.GetCellular((float) ((x * cellScale) + (cng.noise(x, z) * shuffle)), (float) ((z * cellScale) + (cng.noise(z, x) * shuffle))) + 1f) / 2f) * (possibilities - 1); + } + + public int getIndex(double x, double z, int possibilities) + { + return (int) Math.round(getValue(x, z, possibilities)); + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/ChancedPopulator.java b/src/main/java/ninja/bytecode/iris/util/ChancedPopulator.java deleted file mode 100644 index 0f48586be..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ChancedPopulator.java +++ /dev/null @@ -1,74 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.util.Random; - -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.generator.BlockPopulator; - -import ninja.bytecode.shuriken.math.M; - -public abstract class ChancedPopulator extends BlockPopulator -{ - private final double chance; - - public ChancedPopulator(double chance) - { - this.chance = chance; - } - - @Override - public void populate(World world, Random random, Chunk source) - { - if(chance == 0) - { - return; - } - - if(chance > 0 && chance < 1 && M.r(chance)) - { - doPopulate(world, random, source, (source.getX() << 4) + random.nextInt(16), (source.getZ() << 4) + random.nextInt(16)); - } - - if(chance > 1) - { - for(int i = 0; i < (int) chance; i++) - { - doPopulate(world, random, source, (source.getX() << 4) + random.nextInt(16), (source.getZ() << 4) + random.nextInt(16)); - } - - if(M.r(chance - ((int) chance))) - { - doPopulate(world, random, source, (source.getX() << 4) + random.nextInt(16), (source.getZ() << 4) + random.nextInt(16)); - } - } - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - long temp; - temp = Double.doubleToLongBits(chance); - result = prime * result + (int) (temp ^ (temp >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - return true; - if(obj == null) - return false; - if(getClass() != obj.getClass()) - return false; - ChancedPopulator other = (ChancedPopulator) obj; - if(Double.doubleToLongBits(chance) != Double.doubleToLongBits(other.chance)) - return false; - return true; - } - - public abstract void doPopulate(World world, Random random, Chunk source, int x, int z); -} diff --git a/src/main/java/ninja/bytecode/iris/util/ChronoLatch.java b/src/main/java/ninja/bytecode/iris/util/ChronoLatch.java new file mode 100644 index 000000000..eed55bf8d --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/ChronoLatch.java @@ -0,0 +1,29 @@ +package ninja.bytecode.iris.util; + +public class ChronoLatch +{ + private 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 boolean flip() + { + if(System.currentTimeMillis() - since > interval) + { + since = System.currentTimeMillis(); + return true; + } + + return false; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/ChronoQueue.java b/src/main/java/ninja/bytecode/iris/util/ChronoQueue.java deleted file mode 100644 index 4f07b3025..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ChronoQueue.java +++ /dev/null @@ -1,71 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.Bukkit; - -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.bench.PrecisionStopwatch; -import ninja.bytecode.shuriken.execution.J; -import ninja.bytecode.shuriken.execution.Queue; -import ninja.bytecode.shuriken.execution.ShurikenQueue; -import ninja.bytecode.shuriken.logging.L; - -public class ChronoQueue -{ - private PrecisionStopwatch s; - private Queue q; - private double limit; - private int jobLimit; - private boolean die; - private int j; - - public ChronoQueue(double limit, int jobLimit) - { - die = false; - this.limit = limit; - this.jobLimit = jobLimit; - s = new PrecisionStopwatch(); - j = Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, this::tick, 0, 0); - q = new ShurikenQueue<>(); - } - - public void close() - { - J.attempt(() -> Bukkit.getScheduler().cancelTask(j)); - } - - public void dieSlowly() - { - die = true; - } - - public void queue(Runnable r) - { - q.queue(r); - } - - private void tick() - { - s.reset(); - s.begin(); - - while(q.hasNext() && (s.getMilliseconds() < limit || q.size() > jobLimit)) - { - try - { - q.next().run(); - } - - catch(Throwable e) - { - L.ex(e); - } - } - - s.end(); - - if(q.size() == 0 && die) - { - close(); - } - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/ChunkPlan.java b/src/main/java/ninja/bytecode/iris/util/ChunkPlan.java deleted file mode 100644 index cf59e0ba2..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ChunkPlan.java +++ /dev/null @@ -1,138 +0,0 @@ -package ninja.bytecode.iris.util; - -import ninja.bytecode.iris.pack.IrisBiome; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; - -public class ChunkPlan -{ - private final KMap realHeightCache; - private final KMap> caveHeightCache; - private final KMap realWaterHeightCache; - private final KMap heightCache; - private final KMap biomeCache; - - public ChunkPlan() - { - this.caveHeightCache = new KMap<>(); - this.realHeightCache = new KMap<>(); - this.realWaterHeightCache = new KMap<>(); - this.heightCache = new KMap<>(); - this.biomeCache = new KMap<>(); - } - - public IrisBiome getBiome(int x, int z) - { - return biomeCache.get(new SChunkVector(x, z)); - } - - public void setBiome(int x, int z, IrisBiome cng) - { - biomeCache.put(new SChunkVector(x, z), cng); - } - - public double getHeight(int x, int z) - { - SChunkVector c = new SChunkVector(x, z); - if(hasHeight(c)) - { - return heightCache.get(c); - } - - return -1; - } - - public int getRealHeight(int x, int z) - { - SChunkVector c = new SChunkVector(x, z); - if(realHeightCache.containsKey(c)) - { - return realHeightCache.get(c); - } - - return 0; - } - - public KList getCaveHeights(int x, int z) - { - SChunkVector c = new SChunkVector(x, z); - if(caveHeightCache.containsKey(c)) - { - return caveHeightCache.get(c); - } - - return null; - } - - public int getRealWaterHeight(int x, int z) - { - SChunkVector c = new SChunkVector(x, z); - - if(realWaterHeightCache.containsKey(c)) - { - return realWaterHeightCache.get(c); - } - - return 0; - } - - public boolean hasHeight(SChunkVector c) - { - return heightCache.containsKey(c); - } - - public boolean hasHeight(int x, int z) - { - return hasHeight(new SChunkVector(x, z)); - } - - public void setHeight(SChunkVector c, double h) - { - heightCache.put(c, h); - } - - public void setCaveHeight(SChunkVector c, int h) - { - if(!caveHeightCache.containsKey(c)) - { - caveHeightCache.put(c, new KList<>()); - } - - caveHeightCache.get(c).add(h); - } - - public void setRealHeight(SChunkVector c, int h) - { - realHeightCache.put(c, h); - } - - public void setRealHeight(int x, int z, int h) - { - setRealHeight(new SChunkVector(x, z), h); - } - - public void setCaveHeight(int x, int z, int h) - { - setCaveHeight(new SChunkVector(x, z), h); - } - - public void setRealWaterHeight(SChunkVector c, int h) - { - realWaterHeightCache.put(c, h); - } - - public void setRealWaterHeight(int x, int z, int h) - { - setRealWaterHeight(new SChunkVector(x, z), h); - } - - public void setHeight(int x, int z, double h) - { - setHeight(new SChunkVector(x, z), h); - } - - public int biomeCacheSize() - { - return biomeCache.size(); - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/ChunkPosition.java b/src/main/java/ninja/bytecode/iris/util/ChunkPosition.java new file mode 100644 index 000000000..a3b4e4928 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/ChunkPosition.java @@ -0,0 +1,16 @@ +package ninja.bytecode.iris.util; + +import lombok.Data; + +@Data +public class ChunkPosition +{ + private int x; + private int z; + + public ChunkPosition(int x, int z) + { + this.x = x; + this.z = z; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/ChunkSpliceListener.java b/src/main/java/ninja/bytecode/iris/util/ChunkSpliceListener.java deleted file mode 100644 index 381288cd4..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ChunkSpliceListener.java +++ /dev/null @@ -1,14 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.util.Random; - -import org.bukkit.World; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; - -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; - -@FunctionalInterface -public interface ChunkSpliceListener -{ - public AtomicChunkData onSpliceAvailable(World world, Random random, int x, int z, BiomeGrid biome); -} diff --git a/src/main/java/ninja/bytecode/iris/util/ColoredEffect.java b/src/main/java/ninja/bytecode/iris/util/ColoredEffect.java deleted file mode 100644 index 03005f5f8..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ColoredEffect.java +++ /dev/null @@ -1,10 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.awt.Color; - -public interface ColoredEffect -{ - public ColoredEffect setColor(Color color); - - public Color getColor(); -} diff --git a/src/main/java/org/jnbt/CompoundTag.java b/src/main/java/ninja/bytecode/iris/util/CompoundTag.java similarity index 98% rename from src/main/java/org/jnbt/CompoundTag.java rename to src/main/java/ninja/bytecode/iris/util/CompoundTag.java index 30225f8dd..e51c0637f 100644 --- a/src/main/java/org/jnbt/CompoundTag.java +++ b/src/main/java/ninja/bytecode/iris/util/CompoundTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/ninja/bytecode/iris/util/Consumer2.java b/src/main/java/ninja/bytecode/iris/util/Consumer2.java new file mode 100644 index 000000000..1f6366b26 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/Consumer2.java @@ -0,0 +1,7 @@ +package ninja.bytecode.iris.util; + +@FunctionalInterface +public interface Consumer2 +{ + public void accept(A a, B b); +} diff --git a/src/main/java/ninja/bytecode/iris/util/Consumer3.java b/src/main/java/ninja/bytecode/iris/util/Consumer3.java new file mode 100644 index 000000000..38711feea --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/Consumer3.java @@ -0,0 +1,7 @@ +package ninja.bytecode.iris.util; + +@FunctionalInterface +public interface Consumer3 +{ + public void accept(A a, B b, C c); +} diff --git a/src/main/java/ninja/bytecode/iris/util/Contained.java b/src/main/java/ninja/bytecode/iris/util/Contained.java new file mode 100644 index 000000000..9570b6de6 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/Contained.java @@ -0,0 +1,33 @@ +package ninja.bytecode.iris.util; + +import java.util.function.Function; + +public class Contained +{ + private T t; + + public Contained(T t) + { + set(t); + } + + public Contained() + { + this(null); + } + + 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/ninja/bytecode/iris/util/Cuboid.java b/src/main/java/ninja/bytecode/iris/util/Cuboid.java index a65b13aff..c0e99ad54 100644 --- a/src/main/java/ninja/bytecode/iris/util/Cuboid.java +++ b/src/main/java/ninja/bytecode/iris/util/Cuboid.java @@ -14,8 +14,6 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.material.MaterialData; import ninja.bytecode.shuriken.collections.KList; @@ -55,23 +53,6 @@ public class Cuboid implements Iterable, Cloneable, ConfigurationSerializ z2 = Math.max(l1.getBlockZ(), l2.getBlockZ()); } - public KList getLivingEntities() - { - return new KList(new GListAdapter() - { - @Override - public LivingEntity onAdapt(Entity from) - { - if(from instanceof LivingEntity) - { - return (LivingEntity) from; - } - - return null; - } - }.adapt(getEntities())); - } - public KList getEntities() { KList en = new KList(); @@ -763,24 +744,6 @@ public class Cuboid implements Iterable, Cloneable, ConfigurationSerializ return res; } - /** - * Set all the blocks within the Cuboid to the given block ID and data byte. - * - * @param blockId - * the block ID - * @param data - * the block data - * @deprecated use {@link #fill(MaterialData, MassBlockUpdate)} - */ - @Deprecated - public void fill(int blockId, byte data) - { - for(Block b : this) - { - b.setTypeIdAndData(blockId, data, false); - } - } - /** * Set all the blocks within the Cuboid to the given MaterialData, using a * MassBlockUpdate object for fast updates. diff --git a/src/main/java/ninja/bytecode/iris/util/Desc.java b/src/main/java/ninja/bytecode/iris/util/Desc.java new file mode 100644 index 000000000..1259e38d9 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/Desc.java @@ -0,0 +1,14 @@ +package ninja.bytecode.iris.util; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.*; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target({PARAMETER, TYPE, FIELD}) +public @interface Desc +{ + String value(); +} diff --git a/src/main/java/ninja/bytecode/iris/util/Direction.java b/src/main/java/ninja/bytecode/iris/util/Direction.java index 23ee8287d..1a8388575 100644 --- a/src/main/java/ninja/bytecode/iris/util/Direction.java +++ b/src/main/java/ninja/bytecode/iris/util/Direction.java @@ -1,6 +1,7 @@ package ninja.bytecode.iris.util; +import org.bukkit.Axis; import org.bukkit.block.BlockFace; import org.bukkit.util.Vector; diff --git a/src/main/java/ninja/bytecode/iris/util/DoubleArrayUtils.java b/src/main/java/ninja/bytecode/iris/util/DoubleArrayUtils.java new file mode 100644 index 000000000..d811feff0 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/DoubleArrayUtils.java @@ -0,0 +1,29 @@ +package ninja.bytecode.iris.util; + + +public class DoubleArrayUtils +{ + public static void shiftRight(double[] values, double push) + { + for(int index = values.length - 2; index >= 0; index--) + { + values[index + 1] = values[index]; + } + + 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) + { + for(int i = 0; i < values.length; i++) + { + values[i] = value; + } + } +} diff --git a/src/main/java/org/jnbt/DoubleTag.java b/src/main/java/ninja/bytecode/iris/util/DoubleTag.java similarity index 98% rename from src/main/java/org/jnbt/DoubleTag.java rename to src/main/java/ninja/bytecode/iris/util/DoubleTag.java index 31327f0c7..7e48618e7 100644 --- a/src/main/java/org/jnbt/DoubleTag.java +++ b/src/main/java/ninja/bytecode/iris/util/DoubleTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/org/jnbt/EndTag.java b/src/main/java/ninja/bytecode/iris/util/EndTag.java similarity index 98% rename from src/main/java/org/jnbt/EndTag.java rename to src/main/java/ninja/bytecode/iris/util/EndTag.java index 0420ccf83..db58c6084 100644 --- a/src/main/java/org/jnbt/EndTag.java +++ b/src/main/java/ninja/bytecode/iris/util/EndTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/ninja/bytecode/iris/util/FastNoise.java b/src/main/java/ninja/bytecode/iris/util/FastNoise.java new file mode 100644 index 000000000..822e99bd0 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/FastNoise.java @@ -0,0 +1,2197 @@ +// FastNoise.java +// +// MIT License +// +// Copyright(c) 2017 Jordan Peck +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// The developer's email is jorzixdan.me2@gzixmail.com (for great email, take +// off every 'zix'.) +// +package ninja.bytecode.iris.util; + +import javax.vecmath.Vector2f; +import javax.vecmath.Vector3f; + +public class FastNoise { + 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 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; + } + + // 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; + } + + // 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 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; + } + } + + 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), + }; + + + 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 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; + } + + // 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 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); + } + + 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; + } + } + + // White Noise + + 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(float x, float y, float z) { + int xi = FloatCast2Int(x); + int yi = FloatCast2Int(y); + int zi = FloatCast2Int(z); + + return ValCoord3D(m_seed, xi, yi, zi); + } + + public float GetWhiteNoise(float x, float y) { + int xi = FloatCast2Int(x); + int yi = FloatCast2Int(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 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 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 final static float F2 = (float) (1.0 / 2.0); + private final static float G2 = (float) (1.0 / 4.0); + + 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 + F2; + float y2 = y0 - 1 + F2; + + 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 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 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 final static float CUBIC_3D_BOUNDING = 1 / (float) (1.5 * 1.5 * 1.5); + + 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 final static float CUBIC_2D_BOUNDING = 1 / (float) (1.5 * 1.5); + + 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) { + 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 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; + } + +} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/FastParticle.java b/src/main/java/ninja/bytecode/iris/util/FastParticle.java new file mode 100644 index 000000000..c7ef5bc46 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/FastParticle.java @@ -0,0 +1,161 @@ +package ninja.bytecode.iris.util; + +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/ninja/bytecode/iris/util/FastReflection.java b/src/main/java/ninja/bytecode/iris/util/FastReflection.java new file mode 100644 index 000000000..c330722c7 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/FastReflection.java @@ -0,0 +1,59 @@ +package ninja.bytecode.iris.util; + +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) { + 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/ninja/bytecode/iris/util/FileWatcher.java b/src/main/java/ninja/bytecode/iris/util/FileWatcher.java new file mode 100644 index 000000000..5ef247b78 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/FileWatcher.java @@ -0,0 +1,44 @@ +package ninja.bytecode.iris.util; + +import java.io.File; + +import lombok.Data; +import lombok.Getter; + +@Data +public class FileWatcher +{ + @Getter + private final File file; + private boolean exists; + private long lastModified; + private long size; + + public FileWatcher(File file) + { + this.file = file; + readProperties(); + } + + private void readProperties() + { + exists = file.exists(); + lastModified = exists ? file.lastModified() : -1; + size = exists ? 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/org/jnbt/FloatTag.java b/src/main/java/ninja/bytecode/iris/util/FloatTag.java similarity index 98% rename from src/main/java/org/jnbt/FloatTag.java rename to src/main/java/ninja/bytecode/iris/util/FloatTag.java index fc7e4cb2a..af6cc1057 100644 --- a/src/main/java/org/jnbt/FloatTag.java +++ b/src/main/java/ninja/bytecode/iris/util/FloatTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/ninja/bytecode/iris/util/GRT.java b/src/main/java/ninja/bytecode/iris/util/GRT.java deleted file mode 100644 index 9285a4d9f..000000000 --- a/src/main/java/ninja/bytecode/iris/util/GRT.java +++ /dev/null @@ -1,10 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -@FunctionalInterface -public interface GRT -{ - public Glower getGlower(Entity entity, Player observer); -} diff --git a/src/main/java/ninja/bytecode/iris/util/GenLayer.java b/src/main/java/ninja/bytecode/iris/util/GenLayer.java index c71e88b19..adbb88c7a 100644 --- a/src/main/java/ninja/bytecode/iris/util/GenLayer.java +++ b/src/main/java/ninja/bytecode/iris/util/GenLayer.java @@ -1,32 +1,17 @@ package ninja.bytecode.iris.util; -import java.util.Random; +import ninja.bytecode.iris.generator.DimensionChunkGenerator; -import org.bukkit.World; -import org.bukkit.block.Biome; - -import ninja.bytecode.iris.generator.IrisGenerator; -import ninja.bytecode.shuriken.math.RNG; - -public class GenLayer implements IGenLayer +public abstract class GenLayer { - protected RNG rng; - protected World world; - protected Random random; - protected IrisGenerator iris; - protected Biome biome = Biome.OCEAN; - - public GenLayer(IrisGenerator iris, World world, Random random, RNG rng) + protected final RNG rng; + protected final DimensionChunkGenerator iris; + + public GenLayer(DimensionChunkGenerator iris, RNG rng) { - this.world = world; - this.random = random; - this.rng = rng; this.iris = iris; + this.rng = rng; } - - @Override - public double generateLayer(double noise, double dx, double dz) - { - return 0; - } + + public abstract double generate(double x, double z); } diff --git a/src/main/java/ninja/bytecode/iris/util/GlossGlower.java b/src/main/java/ninja/bytecode/iris/util/GlossGlower.java deleted file mode 100644 index 0d1006e5b..000000000 --- a/src/main/java/ninja/bytecode/iris/util/GlossGlower.java +++ /dev/null @@ -1,106 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.ChatColor; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import mortar.api.nms.NMP; -import mortar.util.text.C; - -public class GlossGlower implements Glower -{ - private final Player observer; - private final Entity entity; - private ChatColor color; - private boolean sentTeam; - - public GlossGlower(Entity entity, Player observer) - { - sentTeam = false; - this.entity = entity; - this.observer = observer; - this.color = ChatColor.WHITE; - } - - @Override - public Entity getEntity() - { - return entity; - } - - @Override - public ChatColor getColor() - { - return color; - } - - @Override - public void setColor(ChatColor color) - { - if(color.isFormat()) - { - throw new UnsupportedOperationException("You cannot use format codes for glow colors"); - } - - this.color = color; - - if(observer == null) - { - for(Player i : entity.getWorld().getPlayers()) - { - NMP.host.sendGlowingColorMeta(i, getEntity(), C.values()[color.ordinal()]); - } - } - - else - { - NMP.host.sendGlowingColorMeta(getObserver(), getEntity(), C.values()[color.ordinal()]); - } - } - - @Override - public void setGlowing(boolean glowing) - { - if(observer == null) - { - for(Player i : entity.getWorld().getPlayers()) - { - NMP.host.sendEntityMetadata(i, getEntity().getEntityId(), NMP.host.getMetaEntityProperties(false, false, false, false, false, glowing, false)); - } - } - - else - { - NMP.host.sendEntityMetadata(observer, getEntity().getEntityId(), NMP.host.getMetaEntityProperties(false, false, false, false, false, glowing, false)); - } - } - - @Override - public void destroy() - { - setGlowing(false); - - if(sentTeam) - { - if(observer == null) - { - for(Player i : entity.getWorld().getPlayers()) - { - NMP.host.sendRemoveGlowingColorMeta(i, getEntity()); - } - } - - else - { - NMP.host.sendRemoveGlowingColorMeta(getObserver(), getEntity()); - } - - } - } - - @Override - public Player getObserver() - { - return observer; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/GlowManager.java b/src/main/java/ninja/bytecode/iris/util/GlowManager.java deleted file mode 100644 index 2933abe26..000000000 --- a/src/main/java/ninja/bytecode/iris/util/GlowManager.java +++ /dev/null @@ -1,14 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -public class GlowManager -{ - public static GRT f = null; - - public static Glower create(Entity e, Player observer) - { - return f.getGlower(e, observer); - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/Glower.java b/src/main/java/ninja/bytecode/iris/util/Glower.java deleted file mode 100644 index c99fd420a..000000000 --- a/src/main/java/ninja/bytecode/iris/util/Glower.java +++ /dev/null @@ -1,20 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.ChatColor; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -public interface Glower -{ - public Player getObserver(); - - public Entity getEntity(); - - public ChatColor getColor(); - - public void setColor(ChatColor color); - - public void setGlowing(boolean glowing); - - public void destroy(); -} diff --git a/src/main/java/ninja/bytecode/iris/util/GlowingBlock.java b/src/main/java/ninja/bytecode/iris/util/GlowingBlock.java deleted file mode 100644 index 1f00bb7cb..000000000 --- a/src/main/java/ninja/bytecode/iris/util/GlowingBlock.java +++ /dev/null @@ -1,178 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.util.UUID; - -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import mortar.api.nms.NMP; -import mortar.api.world.MaterialBlock; -import mortar.compute.math.M; - -public class GlowingBlock -{ - private static int idd = 123456789; - private int id; - private UUID uid; - private Location location; - private Location current; - private Player player; - private double factor; - private Vector velocity; - private boolean active; - private long mv = M.ms(); - private MaterialBlock mb; - private ChatColor c; - - public GlowingBlock(Player player, Location init, MaterialBlock mb, ChatColor c) - { - this.mb = mb; - this.uid = UUID.randomUUID(); - this.id = idd--; - location = init; - current = init.clone(); - this.player = player; - factor = Math.PI; - active = false; - velocity = new Vector(); - this.c = c; - } - - public int getId() - { - return id; - } - - public void sendMetadata(boolean glowing) - { - PacketGate.mark(PacketCategory.EFFECT); - NMP.host.sendEntityMetadata(player, id, NMP.host.getMetaEntityProperties(false, false, false, false, false, glowing, false)); - } - - public void sendMetadata(ChatColor c) - { - PacketGate.mark(PacketCategory.EFFECT); - //NMP.host.sendGlowingColorMetaEntity(getPlayer(), uid, C.values()[c.ordinal()]); - } - - public void update() - { - if(M.ms() - mv < 50) - { - return; - } - - if(location.getX() == current.getX() && location.getY() == current.getY() && location.getZ() == current.getZ()) - { - return; - } - - mv = M.ms(); - - if(location.distanceSquared(current) > 16) - { - if(PacketGate.can(PacketCategory.EFFECT)) - { - sendTeleport(location); - current = location; - } - } - - else - { - if(PacketGate.can(PacketCategory.EFFECT)) - { - double dx = location.getX() - current.getX(); - double dy = location.getY() - current.getY(); - double dz = location.getZ() - current.getZ(); - dx += velocity.getX(); - dy += velocity.getY(); - dz += velocity.getZ(); - dx = M.clip(dx, -8, 8); - dy = M.clip(dy, -8, 8); - dz = M.clip(dz, -8, 8); - sendMove(dx / factor, dy / factor, dz / factor); - current.add(dx / factor, dy / factor, dz / factor); - current.setX(Math.abs(location.getX() - current.getX()) < 0.00001 ? location.getX() : current.getX()); - current.setY(Math.abs(location.getY() - current.getY()) < 0.00001 ? location.getY() : current.getY()); - current.setZ(Math.abs(location.getZ() - current.getZ()) < 0.00001 ? location.getZ() : current.getZ()); - - if(location.getX() == current.getX() && location.getY() == current.getY() && location.getZ() == current.getZ()) - { - if(PacketGate.can(PacketCategory.EFFECT)) - { - sendTeleport(location); - current = location; - } - } - } - } - } - - public Location getPosition() - { - return location.clone(); - } - - public void setPosition(Location l) - { - location = l; - } - - public Player getPlayer() - { - return player; - } - - public void destroy() - { - sendDestroy(); - } - - public void create() - { - sendSpawn(); - } - - public boolean isActive() - { - return active; - } - - public void setFactor(int i) - { - factor = i; - } - - private void sendTeleport(Location l) - { - NMP.host.teleportEntity(id, player, l, false); - } - - private void sendMove(double x, double y, double z) - { - NMP.host.moveEntityRelative(id, player, x, y, z, false); - } - - public void sendDestroy() - { - active = false; - NMP.host.removeEntity(id, player); - NMP.host.sendRemoveGlowingColorMetaEntity(getPlayer(), uid); - sendMetadata(false); - PacketGate.mark(PacketCategory.EFFECT); - PacketGate.mark(PacketCategory.EFFECT); - } - - public void sendSpawn() - { - NMP.host.spawnFallingBlock(id, uid, location, player, mb); - sendMetadata(c); - sendMetadata(true); - active = true; - PacketGate.mark(PacketCategory.EFFECT); - PacketGate.mark(PacketCategory.EFFECT); - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/GroupedExecutor.java b/src/main/java/ninja/bytecode/iris/util/GroupedExecutor.java new file mode 100644 index 000000000..36deb3cca --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/GroupedExecutor.java @@ -0,0 +1,132 @@ +package ninja.bytecode.iris.util; + +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; +import java.util.concurrent.locks.ReentrantLock; + +import ninja.bytecode.shuriken.collections.KMap; +import ninja.bytecode.shuriken.execution.J; +import ninja.bytecode.shuriken.execution.NastyRunnable; + +public class GroupedExecutor +{ + private int xc; + private ExecutorService service; + private ReentrantLock lock; + private KMap mirror; + + public GroupedExecutor(int threadLimit, int priority, String name) + { + xc = 1; + lock = new ReentrantLock(); + 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 = new ForkJoinWorkerThreadFactory() + { + @Override + public ForkJoinWorkerThread newThread(ForkJoinPool 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) + { + J.sleep(1); + + if(mirror.get(g) == 0) + { + break; + } + } + } + + public void queue(String q, NastyRunnable r) + { + lock.lock(); + if(!mirror.containsKey(q)) + { + mirror.put(q, 0); + } + mirror.put(q, mirror.get(q) + 1); + lock.unlock(); + service.execute(() -> + { + try + { + r.run(); + } + + catch(Throwable e) + { + + } + + lock.lock(); + mirror.put(q, mirror.get(q) - 1); + lock.unlock(); + }); + } + + public void close() + { + J.a(() -> + { + J.sleep(10000); + service.shutdown(); + }); + } + + public void closeNow() + { + service.shutdown(); + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/HeightMap.java b/src/main/java/ninja/bytecode/iris/util/HeightMap.java new file mode 100644 index 000000000..37344e2e4 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/HeightMap.java @@ -0,0 +1,24 @@ +package ninja.bytecode.iris.util; + +import java.util.Arrays; + +public class HeightMap +{ + private final byte[] height; + + public HeightMap() + { + height = new byte[256]; + Arrays.fill(height, Byte.MIN_VALUE); + } + + public void setHeight(int x, int z, int h) + { + height[x * 16 + z] = (byte) (h + Byte.MIN_VALUE); + } + + public int getHeight(int x, int z) + { + return height[x * 16 + z] - Byte.MIN_VALUE; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/HotswapGenerator.java b/src/main/java/ninja/bytecode/iris/util/HotswapGenerator.java deleted file mode 100644 index 85abc67b8..000000000 --- a/src/main/java/ninja/bytecode/iris/util/HotswapGenerator.java +++ /dev/null @@ -1,74 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.util.List; -import java.util.Random; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.generator.BlockPopulator; -import org.bukkit.generator.ChunkGenerator; - -import ninja.bytecode.iris.generator.IrisGenerator; - -@SuppressWarnings("deprecation") -public class HotswapGenerator extends ChunkGenerator -{ - private IrisGenerator gen; - - public HotswapGenerator(IrisGenerator gen) - { - setGenerator(gen); - } - - public void setGenerator(IrisGenerator gen) - { - this.gen = gen; - } - - public IrisGenerator getGenerator() - { - return gen; - } - - @Override - public byte[] generate(World world, Random random, int x, int z) - { - return gen.generate(world, random, x, z); - } - - @Override - public short[][] generateExtBlockSections(World world, Random random, int x, int z, BiomeGrid biomes) - { - return gen.generateExtBlockSections(world, random, x, z, biomes); - } - - @Override - public byte[][] generateBlockSections(World world, Random random, int x, int z, BiomeGrid biomes) - { - return gen.generateBlockSections(world, random, x, z, biomes); - } - - @Override - public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome) - { - return gen.generateChunkData(world, random, x, z, biome); - } - - @Override - public boolean canSpawn(World world, int x, int z) - { - return gen.canSpawn(world, x, z); - } - - @Override - public List getDefaultPopulators(World world) - { - return gen.getDefaultPopulators(world); - } - - @Override - public Location getFixedSpawnLocation(World world, Random random) - { - return gen.getFixedSpawnLocation(world, random); - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/IGenLayer.java b/src/main/java/ninja/bytecode/iris/util/IGenLayer.java deleted file mode 100644 index 7ef327491..000000000 --- a/src/main/java/ninja/bytecode/iris/util/IGenLayer.java +++ /dev/null @@ -1,6 +0,0 @@ -package ninja.bytecode.iris.util; - -public interface IGenLayer -{ - public double generateLayer(double noise, double dx, double dz); -} diff --git a/src/main/java/ninja/bytecode/iris/util/ING.java b/src/main/java/ninja/bytecode/iris/util/ING.java new file mode 100644 index 000000000..49e9d35ad --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/ING.java @@ -0,0 +1,9 @@ +package ninja.bytecode.iris.util; + +public class ING +{ + public ING(RNG rng) + { + + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/IO.java b/src/main/java/ninja/bytecode/iris/util/IO.java new file mode 100644 index 000000000..d2ad16dba --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/IO.java @@ -0,0 +1,1910 @@ +package ninja.bytecode.iris.util; + +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.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.ZipException; +import java.util.zip.ZipFile; + +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(); + + 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 new String(boas.toByteArray(), StandardCharsets.UTF_8); + } + + 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) + { + 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(); + } + + /** + * 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 amount + * the buffer and size to use + * @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. + * + * @param in + * @param out + * @return total size transfered + * @throws IOException + */ + 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 write 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 ZipException, 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) + { + 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 + { + PrintWriter pw = new PrintWriter(new FileWriter(f)); + pw.println(c.toString()); + pw.close(); + } + + public static String readAll(File f) throws IOException + { + BufferedReader bu = new BufferedReader(new FileReader(f)); + String c = ""; + String l = ""; + + while((l = bu.readLine()) != null) + { + c += l + "\n"; + } + + bu.close(); + + return c; + } + + public static String readAll(InputStream in) throws IOException + { + BufferedReader bu = new BufferedReader(new InputStreamReader(in)); + String c = ""; + String l = ""; + + while((l = bu.readLine()) != null) + { + c += l + "\n"; + } + + bu.close(); + + return c; + } + + /** + * 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 + * @see #copyFileToDirectory + */ + 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 + * @see #copyFileToDirectory + */ + 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() == false) + { + 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() == false) + { + if(destFile.getParentFile().mkdirs() == false) + { + throw new IOException("Destination '" + destFile + "' directory cannot be created"); + } + } + if(destFile.exists() && destFile.canWrite() == false) + { + 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 ioe) + { + // 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 ioe) + { + // 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 ioe) + { + // ignore + } + } + + /** + * 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 ioe) + { + // ignore + } + } + + // read toByteArray + // ----------------------------------------------------------------------- + /** + * 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. + *

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

+ * 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(); + } + + /** + * 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 + * @throws NullPointerException + * if the input is null + * @throws IOException + * if an I/O error occurs (never occurs) + * @deprecated Use {@link String#getBytes()} + */ + public static byte[] toByteArray(String input) throws IOException + { + return input.getBytes(); + } + + // read char[] + // ----------------------------------------------------------------------- + /** + * 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(); + } + + /** + * 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(); + } + + // read toString + // ----------------------------------------------------------------------- + /** + * 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 + * @throws NullPointerException + * if the input is null + * @throws IOException + * if an I/O error occurs (never occurs) + * @deprecated Use {@link String#String(byte[])} + */ + public static String toString(byte[] input) throws IOException + { + return new String(input); + } + + /** + * 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)} + */ + public static String toString(byte[] input, String encoding) throws IOException + { + if(encoding == null) + { + return new String(input); + } else + { + return new String(input, encoding); + } + } + + // readLines + // ----------------------------------------------------------------------- + /** + * 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); + } + + /** + * 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 + * @throws IOException + * if the encoding is invalid + * @return an input stream + * @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); + } + + // write byte[] + // ----------------------------------------------------------------------- + /** + * Writes bytes from a byte[] to an OutputStream. + * + * @param data + * the byte array to write, do not modify during output, null + * ignored + * @param output + * the OutputStream to write 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 write, do not modify during output, null + * ignored + * @param output + * the Writer to write 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)); + } + } + + /** + * 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 write, do not modify during output, null + * ignored + * @param output + * the Writer to write 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)); + } + } + } + + // write char[] + // ----------------------------------------------------------------------- + /** + * Writes chars from a char[] to a Writer using + * the default character encoding of the platform. + * + * @param data + * the char array to write, do not modify during output, null + * ignored + * @param output + * the Writer to write 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 write, do not modify during output, null + * ignored + * @param output + * the OutputStream to write 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()); + } + } + + /** + * 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 write, do not modify during output, null + * ignored + * @param output + * the OutputStream to write 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)); + } + } + } + + // write String + // ----------------------------------------------------------------------- + /** + * Writes chars from a String to a Writer. + * + * @param data + * the String to write, null ignored + * @param output + * the Writer to write 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 write, null ignored + * @param output + * the OutputStream to write 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()); + } + } + + /** + * 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 write, null ignored + * @param output + * the OutputStream to write 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)); + } + } + } + + // write StringBuffer + // ----------------------------------------------------------------------- + /** + * Writes chars from a StringBuffer to a Writer. + * + * @param data + * the StringBuffer to write, null ignored + * @param output + * the Writer to write 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 write, null ignored + * @param output + * the OutputStream to write 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()); + } + } + + /** + * 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 write, null ignored + * @param output + * the OutputStream to write 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)); + } + } + } + + // writeLines + // ----------------------------------------------------------------------- + /** + * 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 write, null entries produce blank lines + * @param lineEnding + * the line separator to use, null is system default + * @param output + * the OutputStream to write 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 write, null entries produce blank lines + * @param lineEnding + * the line separator to use, null is system default + * @param output + * the OutputStream to write 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)); + } + } + } + + /** + * 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 write, null entries produce blank lines + * @param lineEnding + * the line separator to use, null is system default + * @param writer + * the Writer to write 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 from InputStream + // ----------------------------------------------------------------------- + /** + * 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 write 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 write 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 write 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 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 write 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 from Reader + // ----------------------------------------------------------------------- + /** + * 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 write 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 write 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 write 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(); + } + + /** + * 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 write 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(); + } + } + + // content equals + // ----------------------------------------------------------------------- + /** + * 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); + } + + static + { + // avoid security issues + StringWriter buf = new StringWriter(4); + PrintWriter out = new PrintWriter(buf); + out.println(); + LINE_SEPARATOR = buf.toString(); + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/IObjectPlacer.java b/src/main/java/ninja/bytecode/iris/util/IObjectPlacer.java new file mode 100644 index 000000000..2229cfc1b --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/IObjectPlacer.java @@ -0,0 +1,12 @@ +package ninja.bytecode.iris.util; + +import org.bukkit.block.data.BlockData; + +public interface IObjectPlacer +{ + public int getHighest(int x, int z); + + public void set(int x, int y, int z, BlockData d); + + public BlockData get(int x, int y, int z); +} diff --git a/src/main/java/ninja/bytecode/iris/util/IPlacer.java b/src/main/java/ninja/bytecode/iris/util/IPlacer.java deleted file mode 100644 index 81849c291..000000000 --- a/src/main/java/ninja/bytecode/iris/util/IPlacer.java +++ /dev/null @@ -1,19 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.Location; -import org.bukkit.World; - -public interface IPlacer -{ - public World getWorld(); - - public MB get(Location l); - - public void set(Location l, MB mb); - - public int getHighestY(Location l); - - public int getHighestYUnderwater(Location l); - - public void flush(); -} diff --git a/src/main/java/org/jnbt/IntArrayTag.java b/src/main/java/ninja/bytecode/iris/util/IntArrayTag.java similarity index 98% rename from src/main/java/org/jnbt/IntArrayTag.java rename to src/main/java/ninja/bytecode/iris/util/IntArrayTag.java index d5ef03ebd..3e4a4afea 100644 --- a/src/main/java/org/jnbt/IntArrayTag.java +++ b/src/main/java/ninja/bytecode/iris/util/IntArrayTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; import java.util.Arrays; diff --git a/src/main/java/org/jnbt/IntTag.java b/src/main/java/ninja/bytecode/iris/util/IntTag.java similarity index 98% rename from src/main/java/org/jnbt/IntTag.java rename to src/main/java/ninja/bytecode/iris/util/IntTag.java index 798f8e0e2..8b16f7196 100644 --- a/src/main/java/org/jnbt/IntTag.java +++ b/src/main/java/ninja/bytecode/iris/util/IntTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/ninja/bytecode/iris/util/InterpolationMode.java b/src/main/java/ninja/bytecode/iris/util/InterpolationMode.java deleted file mode 100644 index d9204fd08..000000000 --- a/src/main/java/ninja/bytecode/iris/util/InterpolationMode.java +++ /dev/null @@ -1,9 +0,0 @@ -package ninja.bytecode.iris.util; - -public enum InterpolationMode -{ - NONE, - BILINEAR, - BICUBIC, - HERMITE_BICUBIC -} diff --git a/src/main/java/ninja/bytecode/iris/util/InterpolationType.java b/src/main/java/ninja/bytecode/iris/util/InterpolationType.java index 2b88c0a38..238e0e820 100644 --- a/src/main/java/ninja/bytecode/iris/util/InterpolationType.java +++ b/src/main/java/ninja/bytecode/iris/util/InterpolationType.java @@ -1,5 +1,4 @@ package ninja.bytecode.iris.util; - public enum InterpolationType { LINEAR, @@ -7,4 +6,4 @@ public enum InterpolationType PARAMETRIC_4, BEZIER, NONE; -} +} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/IrisController.java b/src/main/java/ninja/bytecode/iris/util/IrisController.java deleted file mode 100644 index 9d3450a29..000000000 --- a/src/main/java/ninja/bytecode/iris/util/IrisController.java +++ /dev/null @@ -1,10 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.event.Listener; - -public interface IrisController extends Listener -{ - public void onStart(); - - public void onStop(); -} diff --git a/src/main/java/ninja/bytecode/iris/util/IrisControllerSet.java b/src/main/java/ninja/bytecode/iris/util/IrisControllerSet.java deleted file mode 100644 index 8fe9b1830..000000000 --- a/src/main/java/ninja/bytecode/iris/util/IrisControllerSet.java +++ /dev/null @@ -1,73 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.io.File; -import java.io.IOException; - -import org.bukkit.Bukkit; -import org.bukkit.event.HandlerList; - -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.logging.L; -import ninja.bytecode.shuriken.tools.JarScanner; - -public class IrisControllerSet -{ - private KMap, IrisController> controllers; - - public IrisControllerSet() - { - controllers = new KMap<>(); - } - - public void startControllers(File jar) throws IOException - { - JarScanner ja = new JarScanner(jar, "ninja.bytecode.iris.controller"); - ja.scan(); - for(Class i : ja.getClasses()) - { - try - { - IrisController c = (IrisController) i.getConstructor().newInstance(); - Bukkit.getPluginManager().registerEvents(c, Iris.instance); - c.onStart(); - controllers.put(i, c); - } - - catch(Throwable e) - { - L.ex(e); - } - } - } - - public void stopControllers() - { - for(Class i : controllers.k()) - { - try - { - IrisController c = controllers.get(i); - HandlerList.unregisterAll(); - c.onStop(); - } - - catch(Throwable e) - { - L.ex(e); - } - } - - controllers.clear(); - } - - public IrisController get(Class c) - { - return controllers.get(c); - } - - public int size() - { - return controllers.size(); - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/IrisInterpolation.java b/src/main/java/ninja/bytecode/iris/util/IrisInterpolation.java index cd7bf2888..82ada55ab 100644 --- a/src/main/java/ninja/bytecode/iris/util/IrisInterpolation.java +++ b/src/main/java/ninja/bytecode/iris/util/IrisInterpolation.java @@ -1,6 +1,6 @@ package ninja.bytecode.iris.util; -import ninja.bytecode.shuriken.math.M; +import ninja.bytecode.iris.object.InterpolationMethod; public class IrisInterpolation { @@ -20,6 +20,11 @@ public class IrisInterpolation return a + (f * (b - a)); } + 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)); @@ -135,8 +140,8 @@ public class IrisInterpolation 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 = M.rangeScale(0, 1, x1, x2, x); - double pz = M.rangeScale(0, 1, z1, z2, z); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); //@builder return blerpBezier( n.noise(x1, z1), @@ -159,8 +164,8 @@ public class IrisInterpolation 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 = M.rangeScale(0, 1, x1, x2, x); - double pz = M.rangeScale(0, 1, z1, z2, z); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); //@builder return bicubic( n.noise(x0, z0), @@ -195,8 +200,8 @@ public class IrisInterpolation 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 = M.rangeScale(0, 1, x1, x2, x); - double pz = M.rangeScale(0, 1, z1, z2, z); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); //@builder return bihermite( n.noise(x0, z0), @@ -215,7 +220,32 @@ public class IrisInterpolation n.noise(x3, z1), n.noise(x3, z2), n.noise(x3, z3), - px, pz, 0.00001, 0.5); + px, pz, 0.0000000001, 0.5); //@done } -} + + public static double getNoise(InterpolationMethod method, int x, int z, double rad, NoiseProvider n) + { + if(method.equals(InterpolationMethod.BILINEAR)) + { + return getBilinearNoise(x, z, rad, n); + } + + else if(method.equals(InterpolationMethod.BICUBIC)) + { + return getBicubicNoise(x, z, rad, n); + } + + else if(method.equals(InterpolationMethod.HERMITE)) + { + return getHermiteNoise(x, z, rad, n); + } + + 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/ninja/bytecode/iris/util/IrisMetrics.java b/src/main/java/ninja/bytecode/iris/util/IrisMetrics.java deleted file mode 100644 index dabc80a57..000000000 --- a/src/main/java/ninja/bytecode/iris/util/IrisMetrics.java +++ /dev/null @@ -1,233 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.util.function.Consumer; - -import org.bukkit.command.CommandSender; - -import mortar.compute.math.M; -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.bench.PrecisionStopwatch; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.format.Form; -import ninja.bytecode.shuriken.math.RollingSequence; - -public class IrisMetrics -{ - private int size; - private int generators; - private double scale; - private KMap sequences; - - public IrisMetrics(int generators, int size) - { - scale = 1; - this.size = size; - this.generators = generators; - sequences = new KMap<>(); - } - - public String avgMS(String s, int dec) - { - return Form.duration(get(s).getAverage(), dec); - } - - public String avg(String s, int dec) - { - return Form.f(get(s).getAverage(), dec); - } - - public String maxMS(String s, int dec) - { - return Form.duration(get(s).getMax(), dec); - } - - public String max(String s, int dec) - { - return Form.f(get(s).getMax(), dec); - } - - public String minMS(String s, int dec) - { - return Form.duration(get(s).getMin(), dec); - } - - public String min(String s, int dec) - { - return Form.f(get(s).getMin(), dec); - } - - public String medianMS(String s, int dec) - { - return Form.duration(get(s).getMedian(), dec); - } - - public String median(String s, int dec) - { - return Form.f(get(s).getMedian(), dec); - } - - public RollingSequence get(String s) - { - if(!sequences.containsKey(s)) - { - return new RollingSequence(2); - } - - return sequences.get(s); - } - - public PrecisionStopwatch start() - { - return PrecisionStopwatch.start(); - } - - public void stop(String f, PrecisionStopwatch g) - { - put(f, g.getMilliseconds()); - } - - public void put(String f, double t) - { - if(!sequences.containsKey(f)) - { - sequences.put(f, new RollingSequence(size)); - } - - sequences.get(f).put(t); - } - - public int getGenerators() - { - return generators; - } - - public void setGenerators(int generators) - { - this.generators = generators; - } - - public KMap getSequences() - { - return sequences; - } - - public void setSequences(KMap sequences) - { - this.sequences = sequences; - } - - public void send(CommandSender p, Consumer c) - { - send(p, c, null, 0); - } - - public void setParScale(double sf) - { - scale = sf; - } - - public void send(CommandSender p, Consumer c, String parent, int ind) - { - KMap out = new KMap<>(); - - looking: for(String i : getSequences().k()) - { - KList o = new KList<>(); - - if(i.contains(":")) - { - o.add(i.split("\\Q:\\E")); - } - - else - { - o.add(i); - } - - String pf = o.get(0); - o.remove(0); - getSequences().get(i).resetExtremes(); - double vmin = Math.abs(getSequences().get(i).getMin()); - double vmed = Math.abs(getSequences().get(i).getMedian()); - double vavg = Math.abs(getSequences().get(i).getAverage()); - double vmax = Math.abs(getSequences().get(i).getMax()); - - for(String k : o) - { - if(k.startsWith("x")) - { - Double mult = Double.valueOf(k.substring(1)); - vmin *= mult / (scale * 2D); - vmed *= mult / (scale * 2D); - vavg *= mult / (scale * 2D); - vmax *= mult / (scale * 2D); - } - } - - boolean ms = false; - boolean comma = false; - String myparent = null; - int dot = 0; - for(String k : o) - { - if(k.startsWith("/")) - { - myparent = k.substring(1); - } - - if(k.startsWith(".") && k.endsWith(".")) - { - dot = k.length(); - } - - else if(k.equals(",")) - { - comma = true; - } - - if(k.equals("ms")) - { - ms = true; - } - } - - if((parent != null) != (myparent != null)) - { - continue looking; - } - - if(parent != null && !myparent.equals(parent)) - { - continue looking; - } - - if(dot == 0 && vavg >= 1000 && !comma) - { - comma = true; - } - - String af = ms ? Form.duration(vmin, dot) : comma ? Form.f((int) vmin) : Form.f(vmin, dot); - String bf = ms ? Form.duration(vmed, dot) : comma ? Form.f((int) vmed) : Form.f(vmed, dot); - String cf = ms ? Form.duration(vavg, dot) : comma ? Form.f((int) vavg) : Form.f(vavg, dot); - String df = ms ? Form.duration(vmax, dot) : comma ? Form.f((int) vmax) : Form.f(vmax, dot); - - out.put(pf, C.DARK_GREEN.toString() + C.ITALIC + cf + C.RESET + C.GRAY + " (" + C.DARK_AQUA + C.ITALIC + af + C.RESET + C.GRAY + " > " + C.GOLD + C.ITALIC + bf + C.RESET + C.GRAY + " < " + C.DARK_RED + C.ITALIC + df + C.RESET + C.GRAY + ")"); - } - - if(ind == 0) - { - c.accept(C.WHITE.toString() + C.BOLD + "Total Generators: " + C.RESET + C.DARK_AQUA + C.ITALIC + Form.f(generators)); - c.accept(C.WHITE.toString() + C.BOLD + "Parallelism: " + C.RESET + C.DARK_PURPLE + C.ITALIC + Form.pc(scale) + C.WHITE + C.BOLD + " Threads: " + C.RESET + C.BLUE + C.ITALIC + Iris.exec().getTC()); - } - - for(String i : out.k()) - { - String g = Form.capitalizeWords(i.replaceAll("\\Q-\\E", " ").toLowerCase()); - c.accept(Form.repeat(" ", M.iclip(ind, 0, 4)) + C.WHITE + C.BOLD + g + C.RESET + ": " + out.get(i)); - - send(p, c, i, ind + 1); - } - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/IrisWorldData.java b/src/main/java/ninja/bytecode/iris/util/IrisWorldData.java deleted file mode 100644 index 45808e756..000000000 --- a/src/main/java/ninja/bytecode/iris/util/IrisWorldData.java +++ /dev/null @@ -1,274 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.io.IOException; - -import org.bukkit.Bukkit; -import org.bukkit.World; - -import mortar.util.text.C; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; -import ninja.bytecode.iris.generator.atomics.AtomicRegionData; -import ninja.bytecode.iris.generator.atomics.AtomicWorldData; -import ninja.bytecode.shuriken.collections.KList; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.logging.L; - -public class IrisWorldData -{ - private final World world; - private final AtomicWorldData data; - private boolean saving; - private final KMap loadedChunks; - - public IrisWorldData(World world) - { - this.world = world; - saving = true; - data = new AtomicWorldData(world); - loadedChunks = new KMap<>(); - Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, this::softUnloadWorld, 200, 20); - } - - public void disableSaving() - { - saving = false; - } - - public void enableSaving() - { - saving = true; - } - - private void softUnloadWorld() - { - if(!saving) - { - return; - } - - for(SMCAVector i : getLoadedChunks()) - { - try - { - AtomicChunkData d = getChunk(i.getX(), i.getZ()); - if(d.getTimeSinceLastUse() > 15000) - { - unloadChunk(i.getX(), i.getZ(), true); - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - for(SMCAVector i : getLoadedRegions()) - { - softUnloadRegion(i.getX(), i.getZ()); - } - } - - private boolean softUnloadRegion(int rx, int rz) - { - if(!saving) - { - return false; - } - - for(SMCAVector i : loadedChunks.keySet()) - { - if(i.getX() >> 5 == rx && i.getZ() >> 5 == rz) - { - return false; - } - } - - try - { - data.unloadSection(rx, rz, true); - return true; - } - - catch(IOException e) - { - e.printStackTrace(); - L.f(C.RED + "Failed to save Iris Subregion " + C.YELLOW + rx + " " + rz); - } - - return false; - } - - public boolean deleteChunk(int x, int z) - { - if(isChunkLoaded(x, z)) - { - unloadChunk(x, z, false); - } - - try - { - AtomicRegionData region = data.getSubregion(x >> 5, z >> 5); - region.delete(x & 31, z & 31); - return true; - } - - catch(IOException e) - { - L.f(C.RED + "Failed delete chunk " + C.YELLOW + x + " " + z + C.RED.toString() + " -> Failed to get Region " + C.YELLOW + (x >> 5) + " " + (z >> 5)); - e.printStackTrace(); - } - - return false; - } - - public boolean unloadChunk(int x, int z, boolean save) - { - if(!isChunkLoaded(x, z)) - { - return false; - } - - if(save) - { - saveChunk(x, z); - } - - loadedChunks.remove(new SMCAVector(x, z)); - return true; - } - - public boolean saveChunk(int x, int z) - { - if(!isChunkLoaded(x, z)) - { - return false; - } - - try - { - AtomicRegionData region = data.getSubregion(x >> 5, z >> 5); - region.set(x & 31, z & 31, getChunk(x, z)); - return true; - } - - catch(IOException e) - { - L.f(C.RED + "Failed save chunk " + C.YELLOW + x + " " + z + C.RED.toString() + " -> Failed to get Region " + C.YELLOW + (x >> 5) + " " + (z >> 5)); - e.printStackTrace(); - } - - return false; - } - - public AtomicChunkData getOnly(int x, int z) - { - if(!isChunkLoaded(x, z)) - { - return null; - } - - return getChunk(x, z); - } - - public AtomicChunkData getChunk(int x, int z) - { - if(!isChunkLoaded(x, z)) - { - try - { - AtomicRegionData region = data.getSubregion(x >> 5, z >> 5); - - if(region.contains(x & 31, z & 31)) - { - AtomicChunkData chunk = region.get(x & 31, z & 31); - loadedChunks.put(new SMCAVector(x, z), chunk); - } - - else - { - AtomicChunkData data = new AtomicChunkData(world); - loadedChunks.put(new SMCAVector(x, z), data); - } - } - - catch(IOException e) - { - L.f(C.RED + "Failed load chunk " + C.YELLOW + x + " " + z + C.RED.toString() + " -> Failed to get Region " + C.YELLOW + (x >> 5) + " " + (z >> 5)); - e.printStackTrace(); - } - } - - return loadedChunks.get(new SMCAVector(x, z)); - } - - public boolean isChunkLoaded(int x, int z) - { - return loadedChunks.containsKey(new SMCAVector(x, z)); - } - - public void inject(int x, int z, AtomicChunkData data) - { - getChunk(x, z).inject(data); - } - - public boolean exists(int x, int z) - { - try - { - return isChunkLoaded(x, z) || data.getSubregion(x >> 5, z >> 5).contains(x & 31, z & 31); - } - - catch(IOException e) - { - L.f(C.RED + "Failed check chunk " + C.YELLOW + x + " " + z + C.RED.toString() + " -> Failed to get Region " + C.YELLOW + (x >> 5) + " " + (z >> 5)); - e.printStackTrace(); - } - - return false; - } - - public KList getLoadedChunks() - { - return loadedChunks.k(); - } - - public KList getLoadedRegions() - { - return data.getLoadedRegions(); - } - - public void saveAll() - { - for(SMCAVector i : loadedChunks.k()) - { - saveChunk(i.getX(), i.getZ()); - } - - try - { - data.saveAll(); - } - - catch(IOException e) - { - e.printStackTrace(); - } - } - - public void setBlock(int x, int y, int z, int id, byte data) - { - getChunk(x >> 4, z >> 4).setBlock(x & 15, y, z & 15, id, data); - } - - public void dispose() - { - for(SMCAVector i : getLoadedChunks()) - { - unloadChunk(i.getX(), i.getZ(), true); - } - - softUnloadWorld(); - } -} diff --git a/src/main/java/org/jnbt/ListTag.java b/src/main/java/ninja/bytecode/iris/util/ListTag.java similarity index 98% rename from src/main/java/org/jnbt/ListTag.java rename to src/main/java/ninja/bytecode/iris/util/ListTag.java index e12eb54c4..0df76693e 100644 --- a/src/main/java/org/jnbt/ListTag.java +++ b/src/main/java/ninja/bytecode/iris/util/ListTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/org/jnbt/LongTag.java b/src/main/java/ninja/bytecode/iris/util/LongTag.java similarity index 98% rename from src/main/java/org/jnbt/LongTag.java rename to src/main/java/ninja/bytecode/iris/util/LongTag.java index a7d4d7939..828f13e56 100644 --- a/src/main/java/org/jnbt/LongTag.java +++ b/src/main/java/ninja/bytecode/iris/util/LongTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/ninja/bytecode/iris/util/MB.java b/src/main/java/ninja/bytecode/iris/util/MB.java deleted file mode 100644 index a5e4254d2..000000000 --- a/src/main/java/ninja/bytecode/iris/util/MB.java +++ /dev/null @@ -1,102 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.Material; - -public class MB -{ - public final Material material; - public final byte data; - - @SuppressWarnings("deprecation") - public static MB of(String dat) - { - String material = dat; - byte data = 0; - - if(dat.contains(":")) - { - material = dat.split("\\Q:\\E")[0]; - data = Integer.valueOf(dat.split("\\Q:\\E")[1]).byteValue(); - } - - try - { - return new MB(Material.getMaterial(Integer.valueOf(material)), data); - } - - catch(Throwable e) - { - - } - - try - { - return new MB(Material.getMaterial(material), data); - } - - catch(Throwable e) - { - - } - - return MB.of(Material.AIR); - } - - public String toString() - { - if(data == 0) - { - return material.name(); - } - - return material.name() + ":" + data; - } - - public MB(Material material, int data) - { - this.material = material; - this.data = (byte) data; - } - - public MB(Material material) - { - this(material, 0); - } - - public static MB of(Material f) - { - return new MB(f); - } - - public static MB of(Material f, int a) - { - return new MB(f, a); - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + data; - 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; - MB other = (MB) obj; - if(data != other.data) - return false; - if(material != other.material) - return false; - return true; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/MCAPos.java b/src/main/java/ninja/bytecode/iris/util/MCAPos.java deleted file mode 100644 index 60a1d18d9..000000000 --- a/src/main/java/ninja/bytecode/iris/util/MCAPos.java +++ /dev/null @@ -1,102 +0,0 @@ -package ninja.bytecode.iris.util; - -public class MCAPos -{ - private int x; - private int z; - - public static MCAPos fromChunk(int x, int z) - { - return new MCAPos(x >> 5, z >> 5); - } - - public MCAPos(String name) - { - fromFileName(name); - } - - public MCAPos(int x, int z) - { - this.x = x; - this.z = z; - } - - public void fromFileName(String n) - { - String[] f = n.split("\\Q.\\E"); - x = Integer.valueOf(f[0]); - z = Integer.valueOf(f[1]); - } - - public String toFileName() - { - return x + "." + z + ".imc"; - } - - 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 int getMinChunkX() - { - return x << 5; - } - - public int getMinChunkZ() - { - return z << 5; - } - - public int getMaxChunkX() - { - return getMinChunkX() + 32; - } - - public int getMaxChunkZ() - { - return getMinChunkZ() + 32; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + x; - result = prime * result + z; - return result; - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - return true; - if(obj == null) - return false; - if(getClass() != obj.getClass()) - return false; - MCAPos other = (MCAPos) obj; - if(x != other.x) - return false; - if(z != other.z) - return false; - return true; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/MCAState.java b/src/main/java/ninja/bytecode/iris/util/MCAState.java deleted file mode 100644 index d089bf987..000000000 --- a/src/main/java/ninja/bytecode/iris/util/MCAState.java +++ /dev/null @@ -1,80 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import ninja.bytecode.shuriken.math.M; - -public class MCAState -{ - private boolean[] decorated; - private boolean dirty; - private long lastUsed; - - public MCAState() - { - lastUsed = M.ms(); - this.decorated = new boolean[1024]; - } - - public boolean isInUse() - { - return M.ms() - lastUsed < 30000; - } - - public void setDirty() - { - lastUsed = M.ms(); - this.dirty = true; - } - - public void saved() - { - lastUsed = M.ms(); - this.dirty = false; - } - - public boolean isDirty() - { - return dirty; - } - - public boolean isDecorated(int rcx, int rcz) - { - lastUsed = M.ms(); - return decorated[rcx + (32 * rcz)]; - } - - public void setDecorated(int rcx, int rcz, boolean decorated) - { - lastUsed = M.ms(); - this.decorated[rcx + (32 * rcz)] = decorated; - } - - public void read(InputStream in) throws IOException - { - DataInputStream din = new DataInputStream(in); - - for(int i = 0; i < 1024; i++) - { - decorated[i] = din.readBoolean(); - } - - din.close(); - } - - public void write(OutputStream out) throws IOException - { - DataOutputStream dos = new DataOutputStream(out); - - for(int i = 0; i < 1024; i++) - { - dos.writeBoolean(decorated[i]); - } - - dos.close(); - } -} diff --git a/src/main/java/org/jnbt/NBTConstants.java b/src/main/java/ninja/bytecode/iris/util/NBTConstants.java similarity index 98% rename from src/main/java/org/jnbt/NBTConstants.java rename to src/main/java/ninja/bytecode/iris/util/NBTConstants.java index 4696afcc5..3da22a163 100644 --- a/src/main/java/org/jnbt/NBTConstants.java +++ b/src/main/java/ninja/bytecode/iris/util/NBTConstants.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/org/jnbt/NBTInputStream.java b/src/main/java/ninja/bytecode/iris/util/NBTInputStream.java similarity index 99% rename from src/main/java/org/jnbt/NBTInputStream.java rename to src/main/java/ninja/bytecode/iris/util/NBTInputStream.java index 676666bd4..374ee89be 100644 --- a/src/main/java/org/jnbt/NBTInputStream.java +++ b/src/main/java/ninja/bytecode/iris/util/NBTInputStream.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/org/jnbt/NBTOutputStream.java b/src/main/java/ninja/bytecode/iris/util/NBTOutputStream.java similarity index 99% rename from src/main/java/org/jnbt/NBTOutputStream.java rename to src/main/java/ninja/bytecode/iris/util/NBTOutputStream.java index b7db3f745..9de2bb73c 100644 --- a/src/main/java/org/jnbt/NBTOutputStream.java +++ b/src/main/java/ninja/bytecode/iris/util/NBTOutputStream.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/org/jnbt/NBTUtils.java b/src/main/java/ninja/bytecode/iris/util/NBTUtils.java similarity index 99% rename from src/main/java/org/jnbt/NBTUtils.java rename to src/main/java/ninja/bytecode/iris/util/NBTUtils.java index c4879af10..268d1454f 100644 --- a/src/main/java/org/jnbt/NBTUtils.java +++ b/src/main/java/ninja/bytecode/iris/util/NBTUtils.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/ninja/bytecode/iris/util/NoiseGenerator.java b/src/main/java/ninja/bytecode/iris/util/NoiseGenerator.java new file mode 100644 index 000000000..9ec5b32d0 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/NoiseGenerator.java @@ -0,0 +1,231 @@ +package ninja.bytecode.iris.util; + +/** + * Base class for all noise generators + */ +public abstract class NoiseGenerator +{ + protected final int perm[] = new int[512]; + protected double offsetX; + protected double offsetY; + protected double offsetZ; + + /** + * Speedy floor, faster than (int)Math.floor(x) + * + * @param x + * Value to floor + * @return Floored value + */ + public static int floor(double x) + { + return x >= 0 ? (int) x : (int) x - 1; + } + + protected static double fade(double x) + { + return x * x * x * (x * (x * 6 - 15) + 10); + } + + protected static double lerp(double x, double y, double z) + { + return y + x * (z - y); + } + + protected static double grad(int hash, double x, double y, double z) + { + hash &= 15; + double u = hash < 8 ? x : y; + double v = hash < 4 ? y : hash == 12 || hash == 14 ? x : z; + return ((hash & 1) == 0 ? u : -u) + ((hash & 2) == 0 ? v : -v); + } + + /** + * Computes and returns the 1D noise for the given coordinate in 1D space + * + * @param x + * X coordinate + * @return Noise at given location, from range -1 to 1 + */ + public double noise(double x) + { + return noise(x, 0, 0); + } + + /** + * Computes and returns the 2D noise for the given coordinates in 2D space + * + * @param x + * X coordinate + * @param y + * Y coordinate + * @return Noise at given location, from range -1 to 1 + */ + public double noise(double x, double y) + { + return noise(x, y, 0); + } + + /** + * Computes and returns the 3D noise for the given coordinates in 3D space + * + * @param x + * X coordinate + * @param y + * Y coordinate + * @param z + * Z coordinate + * @return Noise at given location, from range -1 to 1 + */ + public abstract double noise(double x, double y, double z); + + /** + * Generates noise for the 1D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, int octaves, double frequency, double amplitude) + { + return noise(x, 0, 0, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 1D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @param normalized + * If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, int octaves, double frequency, double amplitude, boolean normalized) + { + return noise(x, 0, 0, octaves, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 2D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param y + * Y-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, int octaves, double frequency, double amplitude) + { + return noise(x, y, 0, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 2D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param y + * Y-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @param normalized + * If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, int octaves, double frequency, double amplitude, boolean normalized) + { + return noise(x, y, 0, octaves, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 3D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param y + * Y-coordinate + * @param z + * Z-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double z, int octaves, double frequency, double amplitude) + { + return noise(x, y, z, octaves, frequency, amplitude, false); + } + + /** + * Generates noise for the 3D coordinates using the specified number of octaves + * and parameters + * + * @param x + * X-coordinate + * @param y + * Y-coordinate + * @param z + * Z-coordinate + * @param octaves + * Number of octaves to use + * @param frequency + * How much to alter the frequency by each octave + * @param amplitude + * How much to alter the amplitude by each octave + * @param normalized + * If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double z, int octaves, double frequency, double amplitude, boolean normalized) + { + double result = 0; + double amp = 1; + double freq = 1; + double max = 0; + + for(int i = 0; i < octaves; i++) + { + result += noise(x * freq, y * freq, z * freq) * amp; + max += amp; + freq *= frequency; + amp *= amplitude; + } + + if(normalized) + { + result /= max; + } + + return result; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/NoiseInjector.java b/src/main/java/ninja/bytecode/iris/util/NoiseInjector.java new file mode 100644 index 000000000..28e0dfde5 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/NoiseInjector.java @@ -0,0 +1,7 @@ +package ninja.bytecode.iris.util; + +@FunctionalInterface +public interface NoiseInjector +{ + public double[] combine(double src, double value); +} diff --git a/src/main/java/ninja/bytecode/iris/util/NoiseProvider.java b/src/main/java/ninja/bytecode/iris/util/NoiseProvider.java index 33b45b11f..41f5f6e14 100644 --- a/src/main/java/ninja/bytecode/iris/util/NoiseProvider.java +++ b/src/main/java/ninja/bytecode/iris/util/NoiseProvider.java @@ -1,7 +1,6 @@ package ninja.bytecode.iris.util; - @FunctionalInterface public interface NoiseProvider { public double noise(double x, double z); -} +} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/ObjectMode.java b/src/main/java/ninja/bytecode/iris/util/ObjectMode.java deleted file mode 100644 index 1162711ba..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ObjectMode.java +++ /dev/null @@ -1,33 +0,0 @@ -package ninja.bytecode.iris.util; - -public enum ObjectMode -{ - /** - * Technically the fasted mode. I.e. Do nothing - */ - NONE, - - /** - * The fastest placer. Places without updating lighting or physics - * - * Lighting is applied later with packets - */ - QUICK_N_DIRTY, - - /** - * Somewhat slow but produces near-perfect results. Updates lighting. - */ - LIGHTING, - - /** - * Somewhat slow but produces near-perfect results. Updates lighting & physics - */ - LIGHTING_PHYSICS, - - /** - * Somewhat slow but never cascades and is instantly placed with terrain - * - * Lighting is applied later with packets - */ - PARALLAX; -} diff --git a/src/main/java/ninja/bytecode/iris/util/ObjectResourceLoader.java b/src/main/java/ninja/bytecode/iris/util/ObjectResourceLoader.java new file mode 100644 index 000000000..e04d5cf49 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/ObjectResourceLoader.java @@ -0,0 +1,117 @@ +package ninja.bytecode.iris.util; + +import java.io.File; + +import org.bukkit.util.BlockVector; + +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.object.IrisObject; + +public class ObjectResourceLoader extends ResourceLoader +{ + private ChunkPosition parallaxSize; + + public ObjectResourceLoader(File root, String folderName, String resourceTypeName) + { + super(root, folderName, resourceTypeName, IrisObject.class); + } + + public ChunkPosition getParallaxSize() + { + lock.lock(); + if(parallaxSize == null) + { + int x = 0; + int z = 0; + + for(File i : getFolders()) + { + for(File j : i.listFiles()) + { + if(j.isFile() && j.getName().endsWith(".iob")) + { + try + { + BlockVector b = IrisObject.sampleSize(j); + x = b.getBlockX() > x ? b.getBlockX() : x; + z = b.getBlockZ() > z ? b.getBlockZ() : z; + } + + catch(Throwable e) + { + + } + } + } + } + + x = (Math.max(x, 16) + 16) >> 4; + z = (Math.max(z, 16) + 16) >> 4; + x = x % 2 == 0 ? x + 1 : x; + z = z % 2 == 0 ? z + 1 : z; + parallaxSize = new ChunkPosition(x, z); + Iris.info("Parallax View Distance: " + x + "x" + z); + } + + lock.unlock(); + + return parallaxSize; + } + + public IrisObject loadFile(File j, String key, String name) + { + try + { + IrisObject t = new IrisObject(0, 0, 0); + t.read(j); + loadCache.put(key, t); + Iris.hotloader.track(j); + Iris.info("Loading " + resourceTypeName + ": " + j.getPath()); + t.setLoadKey(name); + lock.unlock(); + return t; + } + + catch(Throwable e) + { + lock.unlock(); + Iris.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage()); + return null; + } + } + + public IrisObject load(String name) + { + String key = name + "-" + objectClass.getCanonicalName(); + + if(loadCache.containsKey(key)) + { + IrisObject t = loadCache.get(key); + return t; + } + + lock.lock(); + 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, key, name); + } + } + + File file = new File(i, name + ".iob"); + + if(file.exists()) + { + return loadFile(file, key, name); + } + } + + Iris.warn("Couldn't find " + resourceTypeName + ": " + name); + + lock.unlock(); + return null; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/PacketCategory.java b/src/main/java/ninja/bytecode/iris/util/PacketCategory.java deleted file mode 100644 index cc5be7905..000000000 --- a/src/main/java/ninja/bytecode/iris/util/PacketCategory.java +++ /dev/null @@ -1,9 +0,0 @@ -package ninja.bytecode.iris.util; - -public enum PacketCategory -{ - BOARD, - HOLOGRAM, - EFFECT, - TABLIST; -} diff --git a/src/main/java/ninja/bytecode/iris/util/PacketGate.java b/src/main/java/ninja/bytecode/iris/util/PacketGate.java deleted file mode 100644 index a03026a34..000000000 --- a/src/main/java/ninja/bytecode/iris/util/PacketGate.java +++ /dev/null @@ -1,129 +0,0 @@ -package ninja.bytecode.iris.util; - -import mortar.compute.math.RollingAverage; -import mortar.lang.collection.GMap; - -public class PacketGate -{ - private static final GMap gates = new GMap<>(); - private final RollingAverage average; - private final int pps; - private int sent; - - private PacketGate(int pps) - { - sent = 0; - this.pps = pps; - average = new RollingAverage(100); - } - - public void tick() - { - average.put(sent * 20D); - sent = 0; - } - - public boolean can() - { - if(should()) - { - mark(); - return true; - } - - return false; - } - - public boolean should() - { - if(average.get() < pps) - { - return true; - } - - return false; - } - - public void mark() - { - sent++; - } - - private double getAveragePPS() - { - return average.get(); - } - - public static int getTotalPPS() - { - double m = 0; - - for(PacketCategory i : PacketCategory.values()) - { - m += getAveragePPS(i); - } - - return (int) m; - } - - public static void tickAll() - { - if(gates.isEmpty()) - { - reset(); - } - - for(PacketCategory i : PacketCategory.values()) - { - gates.get(i).tick(); - } - } - - public static double getAveragePPS(PacketCategory cat) - { - if(!gates.containsKey(cat)) - { - reset(); - } - - return gates.get(cat).getAveragePPS(); - } - - public static boolean can(PacketCategory cat) - { - if(!gates.containsKey(cat)) - { - reset(); - } - - return gates.get(cat).can(); - } - - public static void mark(PacketCategory cat) - { - if(!gates.containsKey(cat)) - { - reset(); - } - - gates.get(cat).mark(); - } - - public static boolean should(PacketCategory cat) - { - if(!gates.containsKey(cat)) - { - reset(); - } - - return gates.get(cat).should(); - } - - public static void reset() - { - gates.put(PacketCategory.BOARD, new PacketGate(100)); - gates.put(PacketCategory.EFFECT, new PacketGate(100)); - gates.put(PacketCategory.HOLOGRAM, new PacketGate(100)); - gates.put(PacketCategory.TABLIST, new PacketGate(100)); - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/ParticleBase.java b/src/main/java/ninja/bytecode/iris/util/ParticleBase.java deleted file mode 100644 index e1c50a9ae..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ParticleBase.java +++ /dev/null @@ -1,30 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import ninja.bytecode.shuriken.collections.KList; - -public abstract class ParticleBase implements VisualEffect -{ - @Override - public abstract void play(Location l, double range); - - @Override - public abstract void play(Location l, Player p); - - @Override - public void play(Location l) - { - play(l, 64); - } - - @Override - public void play(Location l, KList p) - { - for(Player i : p) - { - play(l, i); - } - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/ParticleEffect.java b/src/main/java/ninja/bytecode/iris/util/ParticleEffect.java deleted file mode 100644 index ba2f68f5a..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ParticleEffect.java +++ /dev/null @@ -1,2101 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import ninja.bytecode.iris.util.ParticleEffect.ParticleData; -import ninja.bytecode.iris.util.ReflectionUtils.PackageType; - -/** - * ParticleEffect Library - *

- * This library was created by @DarkBlade12 and allows you to display all - * Minecraft particle effects on a Bukkit server - *

- * You are welcome to use it, modify it and redistribute it under the following - * conditions: - *

    - *
  • Don't claim this class as your own - *
  • Don't remove this disclaimer - *
- *

- * Special thanks: - *

    - *
  • @microgeek (original idea, names and packet parameters) - *
  • @ShadyPotato (1.8 names, ids and packet parameters) - *
  • @RingOfStorms (particle behavior) - *
  • @Cybermaxke (particle behavior) - *
  • @JamieSinn (hosting a jenkins server and documentation for - * particleeffect) - *
- *

- * It would be nice if you provide credit to me if you use this class in a - * published project - * - * @author DarkBlade12 - * @version 1.7 - */ -@SuppressWarnings("unused") -public enum ParticleEffect -{ - /** - * A particle effect which is displayed by exploding tnt and creepers: - *

    - *
  • It looks like a white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - EXPLOSION_NORMAL("explode", 0, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by exploding ghast fireballs and wither - * skulls: - *
    - *
  • It looks like a gray ball which is fading away - *
  • The speed value slightly influences the size of this particle effect - *
- */ - EXPLOSION_LARGE("largeexplode", 1, -1), - /** - * A particle effect which is displayed by exploding tnt and creepers: - *
    - *
  • It looks like a crowd of gray balls which are fading away - *
  • The speed value has no influence on this particle effect - *
- */ - EXPLOSION_HUGE("hugeexplosion", 2, -1), - /** - * A particle effect which is displayed by launching fireworks: - *
    - *
  • It looks like a white star which is sparkling - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - FIREWORKS_SPARK("fireworksSpark", 3, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by swimming entities and arrows in - * water: - *
    - *
  • It looks like a bubble - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - WATER_BUBBLE("bubble", 4, -1, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_WATER), - /** - * A particle effect which is displayed by swimming entities and shaking wolves: - *
    - *
  • It looks like a blue drop - *
  • The speed value has no influence on this particle effect - *
- */ - WATER_SPLASH("splash", 5, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed on water when fishing: - *
    - *
  • It looks like a blue droplet - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - WATER_WAKE("wake", 6, 7, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by water: - *
    - *
  • It looks like a tiny blue square - *
  • The speed value has no influence on this particle effect - *
- */ - SUSPENDED("suspended", 7, -1, ParticleProperty.REQUIRES_WATER), - /** - * A particle effect which is displayed by air when close to bedrock and the in - * the void: - *
    - *
  • It looks like a tiny gray square - *
  • The speed value has no influence on this particle effect - *
- */ - SUSPENDED_DEPTH("depthSuspend", 8, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when landing a critical hit and by - * arrows: - *
    - *
  • It looks like a light brown cross - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CRIT("crit", 9, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when landing a hit with an enchanted - * weapon: - *
    - *
  • It looks like a cyan star - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CRIT_MAGIC("magicCrit", 10, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by primed tnt, torches, droppers, - * dispensers, end portals, brewing stands and monster spawners: - *
    - *
  • It looks like a little gray cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SMOKE_NORMAL("smoke", 11, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by fire, minecarts with furnace and - * blazes: - *
    - *
  • It looks like a large gray cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SMOKE_LARGE("largesmoke", 12, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when splash potions or bottles o' - * enchanting hit something: - *
    - *
  • It looks like a white swirl - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and - * z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL("spell", 13, -1), - /** - * A particle effect which is displayed when instant splash potions hit - * something: - *
    - *
  • It looks like a white cross - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and - * z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL_INSTANT("instantSpell", 14, -1), - /** - * A particle effect which is displayed by entities with active potion effects: - *
    - *
  • It looks like a colored swirl - *
  • The speed value causes the particle to be colored black when set to 0 - *
  • The particle color gets lighter when increasing the speed and darker when - * decreasing the speed - *
- */ - SPELL_MOB("mobSpell", 15, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by entities with active potion effects - * applied through a beacon: - *
    - *
  • It looks like a transparent colored swirl - *
  • The speed value causes the particle to be always colored black when set - * to 0 - *
  • The particle color gets lighter when increasing the speed and darker when - * decreasing the speed - *
- */ - SPELL_MOB_AMBIENT("mobSpellAmbient", 16, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by witches: - *
    - *
  • It looks like a purple cross - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and - * z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL_WITCH("witchMagic", 17, -1), - /** - * A particle effect which is displayed by blocks beneath a water source: - *
    - *
  • It looks like a blue drip - *
  • The speed value has no influence on this particle effect - *
- */ - DRIP_WATER("dripWater", 18, -1), - /** - * A particle effect which is displayed by blocks beneath a lava source: - *
    - *
  • It looks like an orange drip - *
  • The speed value has no influence on this particle effect - *
- */ - DRIP_LAVA("dripLava", 19, -1), - /** - * A particle effect which is displayed when attacking a villager in a village: - *
    - *
  • It looks like a cracked gray heart - *
  • The speed value has no influence on this particle effect - *
- */ - VILLAGER_ANGRY("angryVillager", 20, -1), - /** - * A particle effect which is displayed when using bone meal and trading with a - * villager in a village: - *
    - *
  • It looks like a green star - *
  • The speed value has no influence on this particle effect - *
- */ - VILLAGER_HAPPY("happyVillager", 21, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by mycelium: - *
    - *
  • It looks like a tiny gray square - *
  • The speed value has no influence on this particle effect - *
- */ - TOWN_AURA("townaura", 22, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by note blocks: - *
    - *
  • It looks like a colored note - *
  • The speed value causes the particle to be colored green when set to 0 - *
- */ - NOTE("note", 23, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by nether portals, endermen, ender - * pearls, eyes of ender, ender chests and dragon eggs: - *
    - *
  • It looks like a purple cloud - *
  • The speed value influences the spread of this particle effect - *
- */ - PORTAL("portal", 24, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by enchantment tables which are nearby - * bookshelves: - *
    - *
  • It looks like a cryptic white letter - *
  • The speed value influences the spread of this particle effect - *
- */ - ENCHANTMENT_TABLE("enchantmenttable", 25, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by torches, active furnaces, magma cubes - * and monster spawners: - *
    - *
  • It looks like a tiny flame - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - FLAME("flame", 26, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by lava: - *
    - *
  • It looks like a spark - *
  • The speed value has no influence on this particle effect - *
- */ - LAVA("lava", 27, -1), - /** - * A particle effect which is currently unused: - *
    - *
  • It looks like a transparent gray square - *
  • The speed value has no influence on this particle effect - *
- */ - FOOTSTEP("footstep", 28, -1), - /** - * A particle effect which is displayed when a mob dies: - *
    - *
  • It looks like a large white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CLOUD("cloud", 29, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by redstone ore, powered redstone, - * redstone torches and redstone repeaters: - *
    - *
  • It looks like a tiny colored cloud - *
  • The speed value causes the particle to be colored red when set to 0 - *
- */ - REDSTONE("reddust", 30, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed when snowballs hit a block: - *
    - *
  • It looks like a little piece with the snowball texture - *
  • The speed value has no influence on this particle effect - *
- */ - SNOWBALL("snowballpoof", 31, -1), - /** - * A particle effect which is currently unused: - *
    - *
  • It looks like a tiny white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SNOW_SHOVEL("snowshovel", 32, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by slimes: - *
    - *
  • It looks like a tiny part of the slimeball icon - *
  • The speed value has no influence on this particle effect - *
- */ - SLIME("slime", 33, -1), - /** - * A particle effect which is displayed when breeding and taming animals: - *
    - *
  • It looks like a red heart - *
  • The speed value has no influence on this particle effect - *
- */ - HEART("heart", 34, -1), - /** - * A particle effect which is displayed by barriers: - *
    - *
  • It looks like a red box with a slash through it - *
  • The speed value has no influence on this particle effect - *
- */ - BARRIER("barrier", 35, 8), - /** - * A particle effect which is displayed when breaking a tool or eggs hit a - * block: - *
    - *
  • It looks like a little piece with an item texture - *
- */ - ITEM_CRACK("iconcrack", 36, -1, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when breaking blocks or sprinting: - *
    - *
  • It looks like a little piece with a block texture - *
  • The speed value has no influence on this particle effect - *
- */ - BLOCK_CRACK("blockcrack", 37, -1, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when falling: - *
    - *
  • It looks like a little piece with a block texture - *
- */ - BLOCK_DUST("blockdust", 38, 7, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when rain hits the ground: - *
    - *
  • It looks like a blue droplet - *
  • The speed value has no influence on this particle effect - *
- */ - WATER_DROP("droplet", 39, 8), - /** - * A particle effect which is currently unused: - *
    - *
  • It has no visual effect - *
- */ - ITEM_TAKE("take", 40, 8), - - /** - * A particle effect which is displayed by elder guardians: - *
    - *
  • It looks like the shape of the elder guardian - *
  • The speed value has no influence on this particle effect - *
  • The offset values have no influence on this particle effect - *
- */ - MOB_APPEARANCE("mobappearance", 41, 8), - - /** - * A particle effect which is displayed by enderdragons - */ - DRAGON_BREATH("dragonbreath", 42, 9), - - /** - * The end rod particle effect from end rods - */ - END_ROD("endrod", 43, 9), - - /** - * A damage indicator particle effect - */ - DAMAGE_INDICATOR("damageindicator", 44, 9), - - /** - * A swipe sword effect - */ - SWEEP_ATTACK("sweepttack", 45, 9); - - private static final Map NAME_MAP = new HashMap(); - private static final Map ID_MAP = new HashMap(); - private final String name; - private final int id; - private final int requiredVersion; - private final List properties; - - // Initialize map for quick name and id lookup - static - { - for(ParticleEffect effect : values()) - { - NAME_MAP.put(effect.name, effect); - ID_MAP.put(effect.id, effect); - } - } - - /** - * Construct a new particle effect - * - * @param name - * Name of this particle effect - * @param id - * Id of this particle effect - * @param requiredVersion - * Version which is required (1.x) - * @param properties - * Properties of this particle effect - */ - private ParticleEffect(String name, int id, int requiredVersion, ParticleProperty... properties) - { - this.name = name; - this.id = id; - this.requiredVersion = requiredVersion; - this.properties = Arrays.asList(properties); - } - - /** - * Returns the name of this particle effect - * - * @return The name - */ - public String getName() - { - return name; - } - - /** - * Returns the id of this particle effect - * - * @return The id - */ - public int getId() - { - return id; - } - - /** - * Returns the required version for this particle effect (1.x) - * - * @return The required version - */ - public int getRequiredVersion() - { - return requiredVersion; - } - - /** - * Determine if this particle effect has a specific property - * - * @return Whether it has the property or not - */ - public boolean hasProperty(ParticleProperty property) - { - return properties.contains(property); - } - - /** - * Determine if this particle effect is supported by your current server version - * - * @return Whether the particle effect is supported or not - */ - public boolean isSupported() - { - return true; - } - - /** - * Returns the particle effect with the given name - * - * @param name - * Name of the particle effect - * @return The particle effect - */ - public static ParticleEffect fromName(String name) - { - for(Entry entry : NAME_MAP.entrySet()) - { - if(!entry.getKey().equalsIgnoreCase(name)) - { - continue; - } - return entry.getValue(); - } - return null; - } - - /** - * Returns the particle effect with the given id - * - * @param id - * Id of the particle effect - * @return The particle effect - */ - public static ParticleEffect fromId(int id) - { - for(Entry entry : ID_MAP.entrySet()) - { - if(entry.getKey() != id) - { - continue; - } - return entry.getValue(); - } - return null; - } - - /** - * Determine if water is at a certain location - * - * @param location - * Location to check - * @return Whether water is at this location or not - */ - private static boolean isWater(Location location) - { - Material material = location.getBlock().getType(); - return false; - } - - /** - * Determine if the distance between @param location and one of the players - * exceeds 256 - * - * @param location - * Location to check - * @return Whether the distance exceeds 256 or not - */ - private static boolean isLongDistance(Location location, List players) - { - String world = location.getWorld().getName(); - for(Player player : players) - { - Location playerLocation = player.getLocation(); - if(!world.equals(playerLocation.getWorld().getName()) || playerLocation.distanceSquared(location) < 65536) - { - continue; - } - return true; - } - return false; - } - - /** - * Determine if the data type for a particle effect is correct - * - * @param effect - * Particle effect - * @param data - * Particle data - * @return Whether the data type is correct or not - */ - private static boolean isDataCorrect(ParticleEffect effect, ParticleData data) - { - return ((effect == BLOCK_CRACK || effect == BLOCK_DUST) && data instanceof BlockData) || (effect == ITEM_CRACK && data instanceof ItemData); - } - - /** - * Determine if the color type for a particle effect is correct - * - * @param effect - * Particle effect - * @param color - * Particle color - * @return Whether the color type is correct or not - */ - private static boolean isColorCorrect(ParticleEffect effect, ParticleColor color) - { - return ((effect == SPELL_MOB || effect == SPELL_MOB_AMBIENT || effect == REDSTONE) && color instanceof OrdinaryColor) || (effect == NOTE && color instanceof NoteColor); - } - - /** - * Displays a particle effect which is only visible for all players within a - * certain range in the world of @param center - * - * @param offsetX - * Maximum distance particles can fly away from the center on the - * x-axis - * @param offsetY - * Maximum distance particles can fly away from the center on the - * y-axis - * @param offsetZ - * Maximum distance particles can fly away from the center on the - * z-axis - * @param speed - * Display speed of the particles - * @param amount - * Amount of particles - * @param center - * Center location of the effect - * @param range - * Range of the visibility - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect requires additional data - * @throws IllegalArgumentException - * If the particle effect requires water and none is at the center - * location - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException - { - if(!isSupported()) - { - return; - } - - if(hasProperty(ParticleProperty.REQUIRES_DATA)) - { - throw new ParticleDataException("This particle effect requires additional data"); - } - - if(hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) - { - throw new IllegalArgumentException("There is no water at the center location"); - } - - new ParticlePacket(this, 0, 0, 0, speed, amount, range > 256, null).sendTo(center, range); - } - - /** - * Displays a particle effect which is only visible for the specified players - * - * @param offsetX - * Maximum distance particles can fly away from the center on the - * x-axis - * @param offsetY - * Maximum distance particles can fly away from the center on the - * y-axis - * @param offsetZ - * Maximum distance particles can fly away from the center on the - * z-axis - * @param speed - * Display speed of the particles - * @param amount - * Amount of particles - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect requires additional data - * @throws IllegalArgumentException - * If the particle effect requires water and none is at the center - * location - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if(hasProperty(ParticleProperty.REQUIRES_DATA)) - { - throw new ParticleDataException("This particle effect requires additional data"); - } - if(hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) - { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, 0, 0, 0, speed, amount, isLongDistance(center, players), null).sendTo(center, players); - } - - /** - * Displays a particle effect which is only visible for the specified players - * - * @param offsetX - * Maximum distance particles can fly away from the center on the - * x-axis - * @param offsetY - * Maximum distance particles can fly away from the center on the - * y-axis - * @param offsetZ - * Maximum distance particles can fly away from the center on the - * z-axis - * @param speed - * Display speed of the particles - * @param amount - * Amount of particles - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect requires additional data - * @throws IllegalArgumentException - * If the particle effect requires water and none is at the center - * location - * @see #display(float, float, float, float, int, Location, List) - */ - public void display(float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException - { - display(speed, amount, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which flies into a determined direction and is - * only visible for all players within a certain range in the world of @param - * center - * - * @param direction - * Direction of the particle - * @param speed - * Display speed of the particle - * @param center - * Center location of the effect - * @param range - * Range of the visibility - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect requires additional data - * @throws IllegalArgumentException - * If the particle effect is not directional or if it requires water - * and none is at the center location - * @see ParticlePacket#ParticlePacket(ParticleEffect, Vector, float, boolean, - * ParticleData) - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if(hasProperty(ParticleProperty.REQUIRES_DATA)) - { - throw new ParticleDataException("This particle effect requires additional data"); - } - if(!hasProperty(ParticleProperty.DIRECTIONAL)) - { - throw new IllegalArgumentException("This particle effect is not directional"); - } - if(hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) - { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, direction, speed, range > 256, null).sendTo(center, range); - } - - /** - * Displays a single particle which flies into a determined direction and is - * only visible for the specified players - * - * @param direction - * Direction of the particle - * @param speed - * Display speed of the particle - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect requires additional data - * @throws IllegalArgumentException - * If the particle effect is not directional or if it requires water - * and none is at the center location - * @see ParticlePacket#ParticlePacket(ParticleEffect, Vector, float, boolean, - * ParticleData) - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if(hasProperty(ParticleProperty.REQUIRES_DATA)) - { - throw new ParticleDataException("This particle effect requires additional data"); - } - if(!hasProperty(ParticleProperty.DIRECTIONAL)) - { - throw new IllegalArgumentException("This particle effect is not directional"); - } - if(hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) - { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, direction, speed, isLongDistance(center, players), null).sendTo(center, players); - } - - /** - * Displays a single particle which flies into a determined direction and is - * only visible for the specified players - * - * @param direction - * Direction of the particle - * @param speed - * Display speed of the particle - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect requires additional data - * @throws IllegalArgumentException - * If the particle effect is not directional or if it requires water - * and none is at the center location - * @see #display(Vector, float, Location, List) - */ - public void display(Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException - { - display(direction, speed, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which is colored and only visible for all players - * within a certain range in the world of @param center - * - * @param color - * Color of the particle - * @param center - * Center location of the effect - * @param range - * Range of the visibility - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleColorException - * If the particle effect is not colorable or the color type is - * incorrect - * @see ParticlePacket#ParticlePacket(ParticleEffect, ParticleColor, boolean) - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleColor color, Location center, double range) throws ParticleVersionException, ParticleColorException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if(!hasProperty(ParticleProperty.COLORABLE)) - { - throw new ParticleColorException("This particle effect is not colorable"); - } - if(!isColorCorrect(this, color)) - { - throw new ParticleColorException("The particle color type is incorrect"); - } - new ParticlePacket(this, color, range > 256).sendTo(center, range); - } - - /** - * Displays a single particle which is colored and only visible for the - * specified players - * - * @param color - * Color of the particle - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleColorException - * If the particle effect is not colorable or the color type is - * incorrect - * @see ParticlePacket#ParticlePacket(ParticleEffect, ParticleColor, boolean) - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleColor color, Location center, List players) throws ParticleVersionException, ParticleColorException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if(!hasProperty(ParticleProperty.COLORABLE)) - { - throw new ParticleColorException("This particle effect is not colorable"); - } - if(!isColorCorrect(this, color)) - { - throw new ParticleColorException("The particle color type is incorrect"); - } - new ParticlePacket(this, color, isLongDistance(center, players)).sendTo(center, players); - } - - /** - * Displays a single particle which is colored and only visible for the - * specified players - * - * @param color - * Color of the particle - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleColorException - * If the particle effect is not colorable or the color type is - * incorrect - * @see #display(ParticleColor, Location, List) - */ - public void display(ParticleColor color, Location center, Player... players) throws ParticleVersionException, ParticleColorException - { - display(color, center, Arrays.asList(players)); - } - - /** - * Displays a particle effect which requires additional data and is only visible - * for all players within a certain range in the world of @param center - * - * @param data - * Data of the effect - * @param offsetX - * Maximum distance particles can fly away from the center on the - * x-axis - * @param offsetY - * Maximum distance particles can fly away from the center on the - * y-axis - * @param offsetZ - * Maximum distance particles can fly away from the center on the - * z-axis - * @param speed - * Display speed of the particles - * @param amount - * Amount of particles - * @param center - * Center location of the effect - * @param range - * Range of the visibility - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect does not require additional data or if the - * data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleData data, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - - if(!hasProperty(ParticleProperty.REQUIRES_DATA)) - { - throw new ParticleDataException("This particle effect does not require additional data"); - } - - if(!isDataCorrect(this, data)) - { - throw new ParticleDataException("The particle data type is incorrect"); - } - - new ParticlePacket(this, 0, 0, 0, speed, amount, range > 256, data).sendTo(center, range); - } - - /** - * Displays a particle effect which requires additional data and is only visible - * for the specified players - * - * @param data - * Data of the effect - * @param offsetX - * Maximum distance particles can fly away from the center on the - * x-axis - * @param offsetY - * Maximum distance particles can fly away from the center on the - * y-axis - * @param offsetZ - * Maximum distance particles can fly away from the center on the - * z-axis - * @param speed - * Display speed of the particles - * @param amount - * Amount of particles - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect does not require additional data or if the - * data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleData data, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if(!hasProperty(ParticleProperty.REQUIRES_DATA)) - { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if(!isDataCorrect(this, data)) - { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, 0, 0, 0, speed, amount, isLongDistance(center, players), data).sendTo(center, players); - } - - /** - * Displays a particle effect which requires additional data and is only visible - * for the specified players - * - * @param data - * Data of the effect - * @param offsetX - * Maximum distance particles can fly away from the center on the - * x-axis - * @param offsetY - * Maximum distance particles can fly away from the center on the - * y-axis - * @param offsetZ - * Maximum distance particles can fly away from the center on the - * z-axis - * @param speed - * Display speed of the particles - * @param amount - * Amount of particles - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect does not require additional data or if the - * data type is incorrect - * @see #display(ParticleData, float, float, float, float, int, Location, List) - */ - public void display(ParticleData data, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException - { - display(data, speed, amount, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which requires additional data that flies into a - * determined direction and is only visible for all players within a certain - * range in the world of @param center - * - * @param data - * Data of the effect - * @param direction - * Direction of the particle - * @param speed - * Display speed of the particles - * @param center - * Center location of the effect - * @param range - * Range of the visibility - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect does not require additional data or if the - * data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if(!hasProperty(ParticleProperty.REQUIRES_DATA)) - { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if(!isDataCorrect(this, data)) - { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, direction, speed, range > 256, data).sendTo(center, range); - } - - /** - * Displays a single particle which requires additional data that flies into a - * determined direction and is only visible for the specified players - * - * @param data - * Data of the effect - * @param direction - * Direction of the particle - * @param speed - * Display speed of the particles - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect does not require additional data or if the - * data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException - { - if(!isSupported()) - { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if(!hasProperty(ParticleProperty.REQUIRES_DATA)) - { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if(!isDataCorrect(this, data)) - { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, direction, speed, isLongDistance(center, players), data).sendTo(center, players); - } - - /** - * Displays a single particle which requires additional data that flies into a - * determined direction and is only visible for the specified players - * - * @param data - * Data of the effect - * @param direction - * Direction of the particle - * @param speed - * Display speed of the particles - * @param center - * Center location of the effect - * @param players - * Receivers of the effect - * @throws ParticleVersionException - * If the particle effect is not supported by the server version - * @throws ParticleDataException - * If the particle effect does not require additional data or if the - * data type is incorrect - * @see #display(ParticleData, Vector, float, Location, List) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException - { - display(data, direction, speed, center, Arrays.asList(players)); - } - - /** - * Represents the property of a particle effect - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static enum ParticleProperty - { - /** - * The particle effect requires water to be displayed - */ - REQUIRES_WATER, - /** - * The particle effect requires block or item data to be displayed - */ - REQUIRES_DATA, - /** - * The particle effect uses the offsets as direction values - */ - DIRECTIONAL, - /** - * The particle effect uses the offsets as color values - */ - COLORABLE; - } - - /** - * Represents the particle data for effects like - * {@link ParticleEffect#ITEM_CRACK}, {@link ParticleEffect#BLOCK_CRACK} and - * {@link ParticleEffect#BLOCK_DUST} - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static abstract class ParticleData - { - private final Material material; - private final byte data; - private final int[] packetData; - - /** - * Construct a new particle data - * - * @param material - * Material of the item/block - * @param data - * Data value of the item/block - */ - @SuppressWarnings("deprecation") - public ParticleData(Material material, byte data) - { - this.material = material; - this.data = data; - this.packetData = new int[] {material.getId(), data}; - } - - /** - * Returns the material of this data - * - * @return The material - */ - public Material getMaterial() - { - return material; - } - - /** - * Returns the data value of this data - * - * @return The data value - */ - public byte getData() - { - return data; - } - - /** - * Returns the data as an int array for packet construction - * - * @return The data for the packet - */ - public int[] getPacketData() - { - return packetData; - } - - /** - * Returns the data as a string for pre 1.8 versions - * - * @return The data string for the packet - */ - public String getPacketDataString() - { - return "_" + packetData[0] + "_" + packetData[1]; - } - } - - /** - * Represents the item data for the {@link ParticleEffect#ITEM_CRACK} effect - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static final class ItemData extends ParticleData - { - /** - * Construct a new item data - * - * @param material - * Material of the item - * @param data - * Data value of the item - * @see ParticleData#ParticleData(Material, byte) - */ - public ItemData(Material material, byte data) - { - super(material, data); - } - } - - /** - * Represents the block data for the {@link ParticleEffect#BLOCK_CRACK} and - * {@link ParticleEffect#BLOCK_DUST} effects - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static final class BlockData extends ParticleData - { - /** - * Construct a new block data - * - * @param material - * Material of the block - * @param data - * Data value of the block - * @throws IllegalArgumentException - * If the material is not a block - * @see ParticleData#ParticleData(Material, byte) - */ - public BlockData(Material material, byte data) throws IllegalArgumentException - { - super(material, data); - if(!material.isBlock()) - { - throw new IllegalArgumentException("The material is not a block"); - } - } - } - - /** - * Represents the color for effects like {@link ParticleEffect#SPELL_MOB}, - * {@link ParticleEffect#SPELL_MOB_AMBIENT}, {@link ParticleEffect#REDSTONE} and - * {@link ParticleEffect#NOTE} - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static abstract class ParticleColor - { - /** - * Returns the value for the offsetX field - * - * @return The offsetX value - */ - public abstract float getValueX(); - - /** - * Returns the value for the offsetY field - * - * @return The offsetY value - */ - public abstract float getValueY(); - - /** - * Returns the value for the offsetZ field - * - * @return The offsetZ value - */ - public abstract float getValueZ(); - } - - /** - * Represents the color for effects like {@link ParticleEffect#SPELL_MOB}, - * {@link ParticleEffect#SPELL_MOB_AMBIENT} and {@link ParticleEffect#NOTE} - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static final class OrdinaryColor extends ParticleColor - { - private final int red; - private final int green; - private final int blue; - - /** - * Construct a new ordinary color - * - * @param red - * Red value of the RGB format - * @param green - * Green value of the RGB format - * @param blue - * Blue value of the RGB format - * @throws IllegalArgumentException - * If one of the values is lower than 0 or higher than 255 - */ - public OrdinaryColor(int red, int green, int blue) throws IllegalArgumentException - { - if(red < 0) - { - throw new IllegalArgumentException("The red value is lower than 0"); - } - if(red > 255) - { - throw new IllegalArgumentException("The red value is higher than 255"); - } - this.red = red; - if(green < 0) - { - throw new IllegalArgumentException("The green value is lower than 0"); - } - if(green > 255) - { - throw new IllegalArgumentException("The green value is higher than 255"); - } - this.green = green; - if(blue < 0) - { - throw new IllegalArgumentException("The blue value is lower than 0"); - } - if(blue > 255) - { - throw new IllegalArgumentException("The blue value is higher than 255"); - } - this.blue = blue; - } - - /** - * Construct a new ordinary color - * - * @param color - * Bukkit color - */ - public OrdinaryColor(Color color) - { - this(color.getRed(), color.getGreen(), color.getBlue()); - } - - /** - * Returns the red value of the RGB format - * - * @return The red value - */ - public int getRed() - { - return red; - } - - /** - * Returns the green value of the RGB format - * - * @return The green value - */ - public int getGreen() - { - return green; - } - - /** - * Returns the blue value of the RGB format - * - * @return The blue value - */ - public int getBlue() - { - return blue; - } - - /** - * Returns the red value divided by 255 - * - * @return The offsetX value - */ - @Override - public float getValueX() - { - return (float) red / 255F; - } - - /** - * Returns the green value divided by 255 - * - * @return The offsetY value - */ - @Override - public float getValueY() - { - return (float) green / 255F; - } - - /** - * Returns the blue value divided by 255 - * - * @return The offsetZ value - */ - @Override - public float getValueZ() - { - return (float) blue / 255F; - } - } - - /** - * Represents the color for the {@link ParticleEffect#NOTE} effect - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static final class NoteColor extends ParticleColor - { - private final int note; - - /** - * Construct a new note color - * - * @param note - * Note id which determines color - * @throws IllegalArgumentException - * If the note value is lower than 0 or higher than 24 - */ - public NoteColor(int note) throws IllegalArgumentException - { - if(note < 0) - { - throw new IllegalArgumentException("The note value is lower than 0"); - } - if(note > 24) - { - throw new IllegalArgumentException("The note value is higher than 24"); - } - this.note = note; - } - - /** - * Returns the note value divided by 24 - * - * @return The offsetX value - */ - @Override - public float getValueX() - { - return (float) note / 24F; - } - - /** - * Returns zero because the offsetY value is unused - * - * @return zero - */ - @Override - public float getValueY() - { - return 0; - } - - /** - * Returns zero because the offsetZ value is unused - * - * @return zero - */ - @Override - public float getValueZ() - { - return 0; - } - - } - - /** - * Represents a runtime exception that is thrown either if the displayed - * particle effect requires data and has none or vice-versa or if the data type - * is incorrect - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - private static final class ParticleDataException extends RuntimeException - { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle data exception - * - * @param message - * Message that will be logged - */ - public ParticleDataException(String message) - { - super(message); - } - } - - /** - * Represents a runtime exception that is thrown either if the displayed - * particle effect is not colorable or if the particle color type is incorrect - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - private static final class ParticleColorException extends RuntimeException - { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle color exception - * - * @param message - * Message that will be logged - */ - public ParticleColorException(String message) - { - super(message); - } - } - - /** - * Represents a runtime exception that is thrown if the displayed particle - * effect requires a newer version - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - private static final class ParticleVersionException extends RuntimeException - { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle version exception - * - * @param message - * Message that will be logged - */ - public ParticleVersionException(String message) - { - super(message); - } - } - - /** - * Represents a particle effect packet with all attributes which is used for - * sending packets to the players - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.5 - */ - public static final class ParticlePacket - { - private static int version; - private static Class enumParticle; - private static Constructor packetConstructor; - private static Method getHandle; - private static Field playerConnection; - private static Method sendPacket; - private static boolean initialized; - private final ParticleEffect effect; - private float offsetX; - private final float offsetY; - private final float offsetZ; - private final float speed; - private final int amount; - private final boolean longDistance; - private final ParticleData data; - private Object packet; - - /** - * Construct a new particle packet - * - * @param effect - * Particle effect - * @param offsetX - * Maximum distance particles can fly away from the center on the - * x-axis - * @param offsetY - * Maximum distance particles can fly away from the center on the - * y-axis - * @param offsetZ - * Maximum distance particles can fly away from the center on the - * z-axis - * @param speed - * Display speed of the particles - * @param amount - * Amount of particles - * @param longDistance - * Indicates whether the maximum distance is increased from 256 to - * 65536 - * @param data - * Data of the effect - * @throws IllegalArgumentException - * If the speed or amount is lower than 0 - * @see #initialize() - */ - public ParticlePacket(ParticleEffect effect, float offsetX, float offsetY, float offsetZ, float speed, int amount, boolean longDistance, ParticleData data) throws IllegalArgumentException - { - initialize(); - if(speed < 0) - { - throw new IllegalArgumentException("The speed is lower than 0"); - } - if(amount < 0) - { - throw new IllegalArgumentException("The amount is lower than 0"); - } - this.effect = effect; - this.offsetX = offsetX; - this.offsetY = offsetY; - this.offsetZ = offsetZ; - this.speed = speed; - this.amount = amount; - this.longDistance = longDistance; - this.data = data; - } - - /** - * Construct a new particle packet of a single particle flying into a determined - * direction - * - * @param effect - * Particle effect - * @param direction - * Direction of the particle - * @param speed - * Display speed of the particle - * @param longDistance - * Indicates whether the maximum distance is increased from 256 to - * 65536 - * @param data - * Data of the effect - * @throws IllegalArgumentException - * If the speed is lower than 0 - * @see #ParticleEffect(ParticleEffect, float, float, float, float, int, - * boolean, ParticleData) - */ - public ParticlePacket(ParticleEffect effect, Vector direction, float speed, boolean longDistance, ParticleData data) throws IllegalArgumentException - { - this(effect, (float) direction.getX(), (float) direction.getY(), (float) direction.getZ(), speed, 0, longDistance, data); - } - - /** - * Construct a new particle packet of a single colored particle - * - * @param effect - * Particle effect - * @param color - * Color of the particle - * @param longDistance - * Indicates whether the maximum distance is increased from 256 to - * 65536 - * @see #ParticleEffect(ParticleEffect, float, float, float, float, int, - * boolean, ParticleData) - */ - public ParticlePacket(ParticleEffect effect, ParticleColor color, boolean longDistance) - { - this(effect, color.getValueX(), color.getValueY(), color.getValueZ(), 1, 0, longDistance, null); - if(effect == ParticleEffect.REDSTONE && color instanceof OrdinaryColor && ((OrdinaryColor) color).getRed() == 0) - { - offsetX = Float.MIN_NORMAL; - } - } - - /** - * Initializes {@link #packetConstructor}, {@link #getHandle}, - * {@link #playerConnection} and {@link #sendPacket} and sets - * {@link #initialized} to true if it succeeds - *

- * Note: These fields only have to be initialized once, so it will return - * if {@link #initialized} is already set to true - * - * @throws VersionIncompatibleException - * if your bukkit version is not supported by this library - */ - public static void initialize() throws VersionIncompatibleException - { - if(initialized) - { - return; - } - - try - { - String ver = PackageType.getServerVersion(); - int un1 = ver.indexOf("_") + 1; - int un2 = ver.lastIndexOf("_"); - - version = Integer.parseInt(ver.substring(un1, un2)); - - if(version > 7) - { - enumParticle = PackageType.MINECRAFT_SERVER.getClass("EnumParticle"); - } - - Class packetClass = PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles"); - - packetConstructor = ReflectionUtils.getConstructor(packetClass); - getHandle = ReflectionUtils.getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle"); - playerConnection = ReflectionUtils.getField("EntityPlayer", PackageType.MINECRAFT_SERVER, false, "playerConnection"); - sendPacket = ReflectionUtils.getMethod(playerConnection.getType(), "sendPacket", PackageType.MINECRAFT_SERVER.getClass("Packet")); - } - - catch(Exception exception) - { - - } - - initialized = true; - - if(initialized) - { - return; - } - } - - /** - * Returns the version of your server (1.x) - * - * @return The version number - */ - public static int getVersion() - { - if(!initialized) - { - initialize(); - } - return version; - } - - /** - * Determine if {@link #packetConstructor}, {@link #getHandle}, - * {@link #playerConnection} and {@link #sendPacket} are initialized - * - * @return Whether these fields are initialized or not - * @see #initialize() - */ - public static boolean isInitialized() - { - return initialized; - } - - /** - * Initializes {@link #packet} with all set values - * - * @param center - * Center location of the effect - * @throws PacketInstantiationException - * If instantion fails due to an unknown error - */ - private void initializePacket(Location center) throws PacketInstantiationException - { - if(packet != null) - { - return; - } - try - { - packet = packetConstructor.newInstance(); - - if(version < 8) - { - String name = effect.getName(); - if(data != null) - { - name += data.getPacketDataString(); - } - ReflectionUtils.setValue(packet, true, "a", name); - } - else - { - ReflectionUtils.setValue(packet, true, "a", enumParticle.getEnumConstants()[effect.getId()]); - ReflectionUtils.setValue(packet, true, "j", longDistance); - if(data != null) - { - int[] packetData = data.getPacketData(); - ReflectionUtils.setValue(packet, true, "k", effect == ParticleEffect.ITEM_CRACK ? packetData : new int[] {packetData[0] | (packetData[1] << 12)}); - } - } - ReflectionUtils.setValue(packet, true, "b", (float) center.getX()); - ReflectionUtils.setValue(packet, true, "c", (float) center.getY()); - ReflectionUtils.setValue(packet, true, "d", (float) center.getZ()); - ReflectionUtils.setValue(packet, true, "e", offsetX); - ReflectionUtils.setValue(packet, true, "f", offsetY); - ReflectionUtils.setValue(packet, true, "g", offsetZ); - ReflectionUtils.setValue(packet, true, "h", speed); - ReflectionUtils.setValue(packet, true, "i", amount); - } - - catch(Exception exception) - { - - } - } - - /** - * Sends the packet to a single player and caches it - * - * @param center - * Center location of the effect - * @param player - * Receiver of the packet - * @throws PacketInstantiationException - * If instantion fails due to an unknown error - * @throws PacketSendingException - * If sending fails due to an unknown error - * @see #initializePacket(Location) - */ - public void sendTo(Location center, Player player) throws PacketInstantiationException, PacketSendingException - { - initializePacket(center); - try - { - sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet); - } - - catch(Exception exception) - { - } - } - - /** - * Sends the packet to all players in the list - * - * @param center - * Center location of the effect - * @param players - * Receivers of the packet - * @throws IllegalArgumentException - * If the player list is empty - * @see #sendTo(Location center, Player player) - */ - public void sendTo(Location center, List players) throws IllegalArgumentException - { - if(players.isEmpty()) - { - throw new IllegalArgumentException("The player list is empty"); - } - for(Player player : players) - { - sendTo(center, player); - } - } - - /** - * Sends the packet to all players in a certain range - * - * @param center - * Center location of the effect - * @param range - * Range in which players will receive the packet (Maximum range for - * particles is usually 16, but it can differ for some types) - * @throws IllegalArgumentException - * If the range is lower than 1 - * @see #sendTo(Location center, Player player) - */ - public void sendTo(Location center, double range) throws IllegalArgumentException - { - if(range < 1) - { - throw new IllegalArgumentException("The range is lower than 1"); - } - String worldName = center.getWorld().getName(); - double squared = range * range; - for(Player player : Bukkit.getOnlinePlayers()) - { - if(!player.getWorld().getName().equals(worldName) || player.getLocation().distanceSquared(center) > squared) - { - continue; - } - sendTo(center, player); - } - } - - /** - * Represents a runtime exception that is thrown if a bukkit version is not - * compatible with this library - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.5 - */ - private static final class VersionIncompatibleException extends RuntimeException - { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new version incompatible exception - * - * @param message - * Message that will be logged - * @param cause - * Cause of the exception - */ - public VersionIncompatibleException(String message, Throwable cause) - { - super(message, cause); - } - } - - /** - * Represents a runtime exception that is thrown if packet instantiation fails - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.4 - */ - private static final class PacketInstantiationException extends RuntimeException - { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new packet instantiation exception - * - * @param message - * Message that will be logged - * @param cause - * Cause of the exception - */ - public PacketInstantiationException(String message, Throwable cause) - { - super(message, cause); - } - } - - /** - * Represents a runtime exception that is thrown if packet sending fails - *

- * This class is part of the ParticleEffect Library and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.4 - */ - private static final class PacketSendingException extends RuntimeException - { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new packet sending exception - * - * @param message - * Message that will be logged - * @param cause - * Cause of the exception - */ - public PacketSendingException(String message, Throwable cause) - { - super(message, cause); - } - } - } -} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/ParticleRedstone.java b/src/main/java/ninja/bytecode/iris/util/ParticleRedstone.java deleted file mode 100644 index 369b0fb7c..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ParticleRedstone.java +++ /dev/null @@ -1,56 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.awt.Color; - -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import ninja.bytecode.iris.util.ParticleEffect.OrdinaryColor; - -public class ParticleRedstone extends ParticleBase implements ColoredEffect -{ - private Color color; - private float size; - - public ParticleRedstone() - { - this.color = Color.WHITE; - size = 1f; - } - - @Override - public void play(Location l, double range) - { - ParticleEffect.REDSTONE.display(new OrdinaryColor(getColor().getRed(), getColor().getGreen(), getColor().getBlue()), l , range); - } - - @Override - public void play(Location l, Player p) - { - ParticleEffect.REDSTONE.display(new OrdinaryColor(getColor().getRed(), getColor().getGreen(), getColor().getBlue()), l , p); - } - - @Override - public ParticleRedstone setColor(Color color) - { - this.color = color; - return this; - } - - @Override - public Color getColor() - { - return color; - } - - public ParticleRedstone setSize(float size) - { - this.size = size; - return this; - } - - public float getSize() - { - return size; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/ParticleSender.java b/src/main/java/ninja/bytecode/iris/util/ParticleSender.java new file mode 100644 index 000000000..1c725aa1a --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/ParticleSender.java @@ -0,0 +1,130 @@ +package ninja.bytecode.iris.util; + +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) + { + 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/ninja/bytecode/iris/util/ParticleSenderLegacy.java b/src/main/java/ninja/bytecode/iris/util/ParticleSenderLegacy.java new file mode 100644 index 000000000..02f3713f4 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/ParticleSenderLegacy.java @@ -0,0 +1,166 @@ +package ninja.bytecode.iris.util; + +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") +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) { + 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) { + 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)) { + return SERVER_IS_1_8 ? new int[2] : new int[]{1, 0}; + } + + ItemStack itemStack = (ItemStack) data; + return new int[]{itemStack.getType().getId(), itemStack.getDurability()}; + } + + if (dataType == MaterialData.class) { + if (!(data instanceof MaterialData)) { + return SERVER_IS_1_8 ? new int[1] : new int[]{1, 0}; + } + + MaterialData materialData = (MaterialData) data; + 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/ninja/bytecode/iris/util/ParticleType.java b/src/main/java/ninja/bytecode/iris/util/ParticleType.java new file mode 100644 index 000000000..f8429c15c --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/ParticleType.java @@ -0,0 +1,177 @@ +package ninja.bytecode.iris.util; + +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 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() { + switch (this) { + case ITEM_CRACK: + return ItemStack.class; + case BLOCK_CRACK: + case BLOCK_DUST: + case FALLING_DUST: + //noinspection deprecation + return MaterialData.class; + case REDSTONE: + return Color.class; + default: + return Void.class; + } + } + + public static ParticleType getParticle(String particleName) { + try { + return ParticleType.valueOf(particleName.toUpperCase()); + } catch (IllegalArgumentException e) { + for (ParticleType particle : values()) { + if (particle.getName().equalsIgnoreCase(particleName)) { + return particle; + } + + if (particle.hasLegacyName() && particle.getLegacyName().equalsIgnoreCase(particleName)) { + return particle; + } + } + } + return null; + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/PerformanceMode.java b/src/main/java/ninja/bytecode/iris/util/PerformanceMode.java deleted file mode 100644 index 3dfc3279f..000000000 --- a/src/main/java/ninja/bytecode/iris/util/PerformanceMode.java +++ /dev/null @@ -1,11 +0,0 @@ -package ninja.bytecode.iris.util; - -public enum PerformanceMode -{ - SINGLE_THREADED, - UNLIMITED, - MATCH_CPU, - DOUBLE_CPU, - HALF_CPU, - EXPLICIT, -} diff --git a/src/main/java/ninja/bytecode/iris/util/PerlinNoise.java b/src/main/java/ninja/bytecode/iris/util/PerlinNoise.java new file mode 100644 index 000000000..6b74faf34 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/PerlinNoise.java @@ -0,0 +1,175 @@ +package ninja.bytecode.iris.util; + +import java.util.Random; + +public class PerlinNoise extends BasePerlinNoiseGenerator +{ + + /** + * Creates an instance using the given PRNG. + * + * @param rand + * the PRNG used to generate the seed permutation + */ + public PerlinNoise(Random rand) + { + offsetX = rand.nextDouble() * 256; + offsetY = rand.nextDouble() * 256; + offsetZ = rand.nextDouble() * 256; + // The only reason why I'm re-implementing the constructor code is that I've + // read + // on at least 3 different sources that the permutation table should initially + // be + // populated with indices. + // "The permutation table is his answer to the issue of random numbers. + // First take an array of decent length, usually 256 values. Fill it + // sequentially with each + // number in that range: so index 1 gets 1, index 8 gets 8, index 251 gets 251, + // etc... + // Then randomly shuffle the values so you have a table of 256 random values, + // but only + // contains the values between 0 and 255." + // source: https://code.google.com/p/fractalterraingeneration/wiki/Perlin_Noise + for(int i = 0; i < 256; i++) + { + perm[i] = i; + } + for(int i = 0; i < 256; i++) + { + int pos = rand.nextInt(256 - i) + i; + int old = perm[i]; + perm[i] = perm[pos]; + perm[pos] = old; + perm[i + 256] = perm[i]; + } + } + + public static int floor(double x) + { + int floored = (int) x; + return x < floored ? floored - 1 : floored; + } + + /** + * Generates a rectangular section of this generator's noise. + * + * @param noise + * the output of the previous noise layer + * @param x + * the X offset + * @param y + * the Y offset + * @param z + * the Z offset + * @param sizeX + * the size on the X axis + * @param sizeY + * the size on the Y axis + * @param sizeZ + * the size on the Z axis + * @param scaleX + * the X scale parameter + * @param scaleY + * the Y scale parameter + * @param scaleZ + * the Z scale parameter + * @param amplitude + * the amplitude parameter + * @return {@code noise} with this layer of noise added + */ + public double[] getNoise(double[] noise, double x, double y, double z, int sizeX, int sizeY, int sizeZ, double scaleX, double scaleY, double scaleZ, double amplitude) + { + if(sizeY == 1) + { + return get2dNoise(noise, x, z, sizeX, sizeZ, scaleX, scaleZ, amplitude); + } + else + { + return get3dNoise(noise, x, y, z, sizeX, sizeY, sizeZ, scaleX, scaleY, scaleZ, amplitude); + } + } + + protected double[] get2dNoise(double[] noise, double x, double z, int sizeX, int sizeZ, double scaleX, double scaleZ, double amplitude) + { + int index = 0; + for(int i = 0; i < sizeX; i++) + { + double dx = x + offsetX + i * scaleX; + int floorX = floor(dx); + int ix = floorX & 255; + dx -= floorX; + double fx = fade(dx); + for(int j = 0; j < sizeZ; j++) + { + double dz = z + offsetZ + j * scaleZ; + int floorZ = floor(dz); + int iz = floorZ & 255; + dz -= floorZ; + double fz = fade(dz); + // Hash coordinates of the square corners + int a = perm[ix]; + int aa = perm[a] + iz; + int b = perm[ix + 1]; + int ba = perm[b] + iz; + double x1 = lerp(fx, grad(perm[aa], dx, 0, dz), grad(perm[ba], dx - 1, 0, dz)); + double x2 = lerp(fx, grad(perm[aa + 1], dx, 0, dz - 1), grad(perm[ba + 1], dx - 1, 0, dz - 1)); + noise[index++] += lerp(fz, x1, x2) * amplitude; + } + } + return noise; + } + + protected double[] get3dNoise(double[] noise, double x, double y, double z, int sizeX, int sizeY, int sizeZ, double scaleX, double scaleY, double scaleZ, double amplitude) + { + int n = -1; + double x1 = 0; + double x2 = 0; + double x3 = 0; + double x4 = 0; + int index = 0; + for(int i = 0; i < sizeX; i++) + { + double dx = x + offsetX + i * scaleX; + int floorX = floor(dx); + int ix = floorX & 255; + dx -= floorX; + double fx = fade(dx); + for(int j = 0; j < sizeZ; j++) + { + double dz = z + offsetZ + j * scaleZ; + int floorZ = floor(dz); + int iz = floorZ & 255; + dz -= floorZ; + double fz = fade(dz); + for(int k = 0; k < sizeY; k++) + { + double dy = y + offsetY + k * scaleY; + int floorY = floor(dy); + int iy = floorY & 255; + dy -= floorY; + double fy = fade(dy); + if(k == 0 || iy != n) + { + n = iy; + // Hash coordinates of the cube corners + int a = perm[ix] + iy; + int aa = perm[a] + iz; + int ab = perm[a + 1] + iz; + int b = perm[ix + 1] + iy; + int ba = perm[b] + iz; + int bb = perm[b + 1] + iz; + x1 = lerp(fx, grad(perm[aa], dx, dy, dz), grad(perm[ba], dx - 1, dy, dz)); + x2 = lerp(fx, grad(perm[ab], dx, dy - 1, dz), grad(perm[bb], dx - 1, dy - 1, dz)); + x3 = lerp(fx, grad(perm[aa + 1], dx, dy, dz - 1), grad(perm[ba + 1], dx - 1, dy, dz - 1)); + x4 = lerp(fx, grad(perm[ab + 1], dx, dy - 1, dz - 1), grad(perm[bb + 1], dx - 1, dy - 1, dz - 1)); + } + double y1 = lerp(fy, x1, x2); + double y2 = lerp(fy, x3, x4); + + noise[index++] += lerp(fz, y1, y2) * amplitude; + } + } + } + return noise; + } +} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/Placer.java b/src/main/java/ninja/bytecode/iris/util/Placer.java deleted file mode 100644 index d0450fb3e..000000000 --- a/src/main/java/ninja/bytecode/iris/util/Placer.java +++ /dev/null @@ -1,24 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.World; - -public abstract class Placer implements IPlacer -{ - protected final World world; - - public Placer(World world) - { - this.world = world; - } - - @Override - public World getWorld() - { - return world; - } - - public void flush() - { - - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/PolygonGenerator.java b/src/main/java/ninja/bytecode/iris/util/PolygonGenerator.java index 3f8795e76..568c80810 100644 --- a/src/main/java/ninja/bytecode/iris/util/PolygonGenerator.java +++ b/src/main/java/ninja/bytecode/iris/util/PolygonGenerator.java @@ -2,11 +2,9 @@ package ninja.bytecode.iris.util; import java.util.function.Function; -import mortar.lang.collection.GList; -import mortar.lang.collection.GMap; -import ninja.bytecode.shuriken.math.CNG; +import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.collections.KMap; import ninja.bytecode.shuriken.math.M; -import ninja.bytecode.shuriken.math.RNG; public class PolygonGenerator { @@ -174,6 +172,7 @@ public class PolygonGenerator { private T[] choices; + public EnumPolygonGenerator(RNG rng, double scale, int octaves, T[] choices, Function factory) { super(rng, choices.length, scale / (double) choices.length, octaves, factory); @@ -187,7 +186,7 @@ public class PolygonGenerator } @SuppressWarnings("unchecked") - public EnumPolygonGenerator(RNG rng, double scale, int octaves, GList c, GMap choiceRarities, Function factory) + public EnumPolygonGenerator(RNG rng, double scale, int octaves, KList c, KMap choiceRarities, Function factory) { super(rng, choiceRarities.size(), scale / (double) choiceRarities.size(), octaves, factory); this.choices = (T[]) c.toArray(); @@ -216,4 +215,4 @@ public class PolygonGenerator return choices[getIndex(dim)]; } } -} +} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/PrepackagedChunk.java b/src/main/java/ninja/bytecode/iris/util/PrepackagedChunk.java deleted file mode 100644 index da6344608..000000000 --- a/src/main/java/ninja/bytecode/iris/util/PrepackagedChunk.java +++ /dev/null @@ -1,37 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.block.Biome; - -import ninja.bytecode.iris.generator.atomics.AtomicChunkData; - -public class PrepackagedChunk -{ - private AtomicChunkData data; - private Biome[] biome; - - public PrepackagedChunk(AtomicChunkData data, Biome[] biome) - { - this.data = data; - this.biome = biome; - } - - public AtomicChunkData getData() - { - return data; - } - - public void setData(AtomicChunkData data) - { - this.data = data; - } - - public Biome[] getBiome() - { - return biome; - } - - public void setBiome(Biome[] biome) - { - this.biome = biome; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/RNG.java b/src/main/java/ninja/bytecode/iris/util/RNG.java new file mode 100644 index 000000000..f14330f1f --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/RNG.java @@ -0,0 +1,176 @@ +package ninja.bytecode.iris.util; + +import java.nio.charset.StandardCharsets; +import java.util.Random; +import java.util.UUID; + +public class RNG extends Random +{ + private static final char[] CHARGEN = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-=!@#$%^&*()_+`~[];',./<>?:\\\"{}|\\\\".toCharArray(); + private static final long serialVersionUID = 5222938581174415179L; + public static final RNG r = new RNG(); + 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() * 32564)); + } + + public RNG nextParallelRNG(int signature) + { + return new RNG(sx + signature); + } + + @Deprecated + public RNG nextRNG() + { + return new RNG(nextLong()); + } + + 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) + { + return lowerBound + (nextDouble() * ((upperBound - lowerBound))); + } + + 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.round(d(lowerBound, upperBound)); + } + + public int i(int upperBound) + { + return i(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); + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/RealBiome.java b/src/main/java/ninja/bytecode/iris/util/RealBiome.java deleted file mode 100644 index 18aa2c97a..000000000 --- a/src/main/java/ninja/bytecode/iris/util/RealBiome.java +++ /dev/null @@ -1,44 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.Material; -import org.bukkit.block.Biome; - -import net.minecraft.server.v1_12_R1.BiomeBase; -import net.minecraft.server.v1_12_R1.Block; -import net.minecraft.server.v1_12_R1.IBlockData; -import ninja.bytecode.shuriken.format.Form; - -public class RealBiome -{ - private Biome b; - private double temperature; - private double height; - private double humidity; - private MB surface; - private MB dirt; - - public RealBiome(Biome b) - { - this.b = b; - BiomeBase base = BiomeBase.a(b.ordinal()); - surface = toMB(base.q); - dirt = toMB(base.r); - temperature = base.getTemperature(); - humidity = base.getHumidity(); - height = base.j(); - } - - public String toString() - { - return Form.capitalizeWords(b.toString().toLowerCase().replaceAll("\\Q_\\E", " ")) + " Temp: " + temperature + " Humidity: " + humidity + " Height: " + height + " Surf: " + Form.capitalizeWords(surface.material.toString().replaceAll("_", " ").toLowerCase())+ " Dirt: " + Form.capitalizeWords(dirt.material.toString().replaceAll("_", " ").toLowerCase()); - } - - @SuppressWarnings("deprecation") - public MB toMB(IBlockData d) - { - int i = Block.getCombinedId(d); - int j = i & 4095; - int k = i >> 12 & 15; - return new MB(Material.getMaterial(j), k); - } -} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/ReflectionUtils.java b/src/main/java/ninja/bytecode/iris/util/ReflectionUtils.java deleted file mode 100644 index 8df919aea..000000000 --- a/src/main/java/ninja/bytecode/iris/util/ReflectionUtils.java +++ /dev/null @@ -1,822 +0,0 @@ -package ninja.bytecode.iris.util; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -import org.bukkit.Bukkit; - -/** - * ReflectionUtils - *

- * This class provides useful methods which makes dealing with reflection much - * easier, especially when working with Bukkit - *

- * You are welcome to use it, modify it and redistribute it under the following - * conditions: - *

    - *
  • Don't claim this class as your own - *
  • Don't remove this disclaimer - *
- *

- * It would be nice if you provide credit to me if you use this class in a - * published project - * - * @author DarkBlade12 - * @version 1.1 - */ -public final class ReflectionUtils -{ - // Prevent accidental construction - private ReflectionUtils() - { - - } - - /** - * Returns the constructor of a given class with the given parameter types - * - * @param clazz - * Target class - * @param parameterTypes - * Parameter types of the desired constructor - * @return The constructor of the target class with the specified parameter - * types - * @throws NoSuchMethodException - * If the desired constructor with the specified parameter types - * cannot be found - * @see DataType - * @see DataType#getPrimitive(Class[]) - * @see DataType#compare(Class[], Class[]) - */ - public static Constructor getConstructor(Class clazz, Class... parameterTypes) throws NoSuchMethodException - { - Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); - for(Constructor constructor : clazz.getConstructors()) - { - if(!DataType.compare(DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) - { - continue; - } - return constructor; - } - throw new NoSuchMethodException("There is no such constructor in this class with the specified parameter types"); - } - - /** - * Returns the constructor of a desired class with the given parameter types - * - * @param className - * Name of the desired target class - * @param packageType - * Package where the desired target class is located - * @param parameterTypes - * Parameter types of the desired constructor - * @return The constructor of the desired target class with the specified - * parameter types - * @throws NoSuchMethodException - * If the desired constructor with the specified parameter types - * cannot be found - * @throws ClassNotFoundException - * ClassNotFoundException If the desired target class with the - * specified name and package cannot be found - * @see #getConstructor(Class, Class...) - */ - public static Constructor getConstructor(String className, PackageType packageType, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException - { - return getConstructor(packageType.getClass(className), parameterTypes); - } - - /** - * Returns an instance of a class with the given arguments - * - * @param clazz - * Target class - * @param arguments - * Arguments which are used to construct an object of the target - * class - * @return The instance of the target class with the specified arguments - * @throws InstantiationException - * If you cannot create an instance of the target class due to - * certain circumstances - * @throws IllegalAccessException - * If the desired constructor cannot be accessed due to certain - * circumstances - * @throws IllegalArgumentException - * If the types of the arguments do not match the parameter - * types of the constructor (this should not occur since it - * searches for a constructor with the types of the arguments) - * @throws InvocationTargetException - * If the desired constructor cannot be invoked - * @throws NoSuchMethodException - * If the desired constructor with the specified arguments - * cannot be found - */ - public static Object instantiateObject(Class clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException - { - return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments); - } - - /** - * Returns an instance of a desired class with the given arguments - * - * @param className - * Name of the desired target class - * @param packageType - * Package where the desired target class is located - * @param arguments - * Arguments which are used to construct an object of the desired - * target class - * @return The instance of the desired target class with the specified - * arguments - * @throws InstantiationException - * If you cannot create an instance of the desired target class - * due to certain circumstances - * @throws IllegalAccessException - * If the desired constructor cannot be accessed due to certain - * circumstances - * @throws IllegalArgumentException - * If the types of the arguments do not match the parameter - * types of the constructor (this should not occur since it - * searches for a constructor with the types of the arguments) - * @throws InvocationTargetException - * If the desired constructor cannot be invoked - * @throws NoSuchMethodException - * If the desired constructor with the specified arguments - * cannot be found - * @throws ClassNotFoundException - * If the desired target class with the specified name and - * package cannot be found - * @see #instantiateObject(Class, Object...) - */ - public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException - { - return instantiateObject(packageType.getClass(className), arguments); - } - - /** - * Returns a method of a class with the given parameter types - * - * @param clazz - * Target class - * @param methodName - * Name of the desired method - * @param parameterTypes - * Parameter types of the desired method - * @return The method of the target class with the specified name and - * parameter types - * @throws NoSuchMethodException - * If the desired method of the target class with the specified - * name and parameter types cannot be found - * @see DataType#getPrimitive(Class[]) - * @see DataType#compare(Class[], Class[]) - */ - public static Method getMethod(Class clazz, String methodName, Class... parameterTypes) throws NoSuchMethodException - { - Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); - for(Method method : clazz.getMethods()) - { - if(!method.getName().equals(methodName) || !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) - { - continue; - } - return method; - } - throw new NoSuchMethodException("There is no such method in this class with the specified name and parameter types"); - } - - /** - * Returns a method of a desired class with the given parameter types - * - * @param className - * Name of the desired target class - * @param packageType - * Package where the desired target class is located - * @param methodName - * Name of the desired method - * @param parameterTypes - * Parameter types of the desired method - * @return The method of the desired target class with the specified name - * and parameter types - * @throws NoSuchMethodException - * If the desired method of the desired target class with the - * specified name and parameter types cannot be found - * @throws ClassNotFoundException - * If the desired target class with the specified name and - * package cannot be found - * @see #getMethod(Class, String, Class...) - */ - public static Method getMethod(String className, PackageType packageType, String methodName, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException - { - return getMethod(packageType.getClass(className), methodName, parameterTypes); - } - - /** - * Invokes a method on an object with the given arguments - * - * @param instance - * Target object - * @param methodName - * Name of the desired method - * @param arguments - * Arguments which are used to invoke the desired method - * @return The result of invoking the desired method on the target object - * @throws IllegalAccessException - * If the desired method cannot be accessed due to certain - * circumstances - * @throws IllegalArgumentException - * If the types of the arguments do not match the parameter - * types of the method (this should not occur since it searches - * for a method with the types of the arguments) - * @throws InvocationTargetException - * If the desired method cannot be invoked on the target object - * @throws NoSuchMethodException - * If the desired method of the class of the target object with - * the specified name and arguments cannot be found - * @see #getMethod(Class, String, Class...) - * @see DataType#getPrimitive(Object[]) - */ - public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException - { - return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); - } - - /** - * Invokes a method of the target class on an object with the given - * arguments - * - * @param instance - * Target object - * @param clazz - * Target class - * @param methodName - * Name of the desired method - * @param arguments - * Arguments which are used to invoke the desired method - * @return The result of invoking the desired method on the target object - * @throws IllegalAccessException - * If the desired method cannot be accessed due to certain - * circumstances - * @throws IllegalArgumentException - * If the types of the arguments do not match the parameter - * types of the method (this should not occur since it searches - * for a method with the types of the arguments) - * @throws InvocationTargetException - * If the desired method cannot be invoked on the target object - * @throws NoSuchMethodException - * If the desired method of the target class with the specified - * name and arguments cannot be found - * @see #getMethod(Class, String, Class...) - * @see DataType#getPrimitive(Object[]) - */ - public static Object invokeMethod(Object instance, Class clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException - { - return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); - } - - /** - * Invokes a method of a desired class on an object with the given arguments - * - * @param instance - * Target object - * @param className - * Name of the desired target class - * @param packageType - * Package where the desired target class is located - * @param methodName - * Name of the desired method - * @param arguments - * Arguments which are used to invoke the desired method - * @return The result of invoking the desired method on the target object - * @throws IllegalAccessException - * If the desired method cannot be accessed due to certain - * circumstances - * @throws IllegalArgumentException - * If the types of the arguments do not match the parameter - * types of the method (this should not occur since it searches - * for a method with the types of the arguments) - * @throws InvocationTargetException - * If the desired method cannot be invoked on the target object - * @throws NoSuchMethodException - * If the desired method of the desired target class with the - * specified name and arguments cannot be found - * @throws ClassNotFoundException - * If the desired target class with the specified name and - * package cannot be found - * @see #invokeMethod(Object, Class, String, Object...) - */ - public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException - { - return invokeMethod(instance, packageType.getClass(className), methodName, arguments); - } - - /** - * Returns a field of the target class with the given name - * - * @param clazz - * Target class - * @param declared - * Whether the desired field is declared or not - * @param fieldName - * Name of the desired field - * @return The field of the target class with the specified name - * @throws NoSuchFieldException - * If the desired field of the given class cannot be found - * @throws SecurityException - * If the desired field cannot be made accessible - */ - public static Field getField(Class clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException - { - Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); - field.setAccessible(true); - return field; - } - - /** - * Returns a field of a desired class with the given name - * - * @param className - * Name of the desired target class - * @param packageType - * Package where the desired target class is located - * @param declared - * Whether the desired field is declared or not - * @param fieldName - * Name of the desired field - * @return The field of the desired target class with the specified name - * @throws NoSuchFieldException - * If the desired field of the desired class cannot be found - * @throws SecurityException - * If the desired field cannot be made accessible - * @throws ClassNotFoundException - * If the desired target class with the specified name and - * package cannot be found - * @see #getField(Class, boolean, String) - */ - public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException - { - return getField(packageType.getClass(className), declared, fieldName); - } - - /** - * Returns the value of a field of the given class of an object - * - * @param instance - * Target object - * @param clazz - * Target class - * @param declared - * Whether the desired field is declared or not - * @param fieldName - * Name of the desired field - * @return The value of field of the target object - * @throws IllegalArgumentException - * If the target object does not feature the desired field - * @throws IllegalAccessException - * If the desired field cannot be accessed - * @throws NoSuchFieldException - * If the desired field of the target class cannot be found - * @throws SecurityException - * If the desired field cannot be made accessible - * @see #getField(Class, boolean, String) - */ - public static Object getValue(Object instance, Class clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException - { - return getField(clazz, declared, fieldName).get(instance); - } - - /** - * Returns the value of a field of a desired class of an object - * - * @param instance - * Target object - * @param className - * Name of the desired target class - * @param packageType - * Package where the desired target class is located - * @param declared - * Whether the desired field is declared or not - * @param fieldName - * Name of the desired field - * @return The value of field of the target object - * @throws IllegalArgumentException - * If the target object does not feature the desired field - * @throws IllegalAccessException - * If the desired field cannot be accessed - * @throws NoSuchFieldException - * If the desired field of the desired class cannot be found - * @throws SecurityException - * If the desired field cannot be made accessible - * @throws ClassNotFoundException - * If the desired target class with the specified name and - * package cannot be found - * @see #getValue(Object, Class, boolean, String) - */ - public static Object getValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException - { - return getValue(instance, packageType.getClass(className), declared, fieldName); - } - - /** - * Returns the value of a field with the given name of an object - * - * @param instance - * Target object - * @param declared - * Whether the desired field is declared or not - * @param fieldName - * Name of the desired field - * @return The value of field of the target object - * @throws IllegalArgumentException - * If the target object does not feature the desired field - * (should not occur since it searches for a field with the - * given name in the class of the object) - * @throws IllegalAccessException - * If the desired field cannot be accessed - * @throws NoSuchFieldException - * If the desired field of the target object cannot be found - * @throws SecurityException - * If the desired field cannot be made accessible - * @see #getValue(Object, Class, boolean, String) - */ - public static Object getValue(Object instance, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException - { - return getValue(instance, instance.getClass(), declared, fieldName); - } - - /** - * Sets the value of a field of the given class of an object - * - * @param instance - * Target object - * @param clazz - * Target class - * @param declared - * Whether the desired field is declared or not - * @param fieldName - * Name of the desired field - * @param value - * New value - * @throws IllegalArgumentException - * If the type of the value does not match the type of the - * desired field - * @throws IllegalAccessException - * If the desired field cannot be accessed - * @throws NoSuchFieldException - * If the desired field of the target class cannot be found - * @throws SecurityException - * If the desired field cannot be made accessible - * @see #getField(Class, boolean, String) - */ - public static void setValue(Object instance, Class clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException - { - getField(clazz, declared, fieldName).set(instance, value); - } - - /** - * Sets the value of a field of a desired class of an object - * - * @param instance - * Target object - * @param className - * Name of the desired target class - * @param packageType - * Package where the desired target class is located - * @param declared - * Whether the desired field is declared or not - * @param fieldName - * Name of the desired field - * @param value - * New value - * @throws IllegalArgumentException - * If the type of the value does not match the type of the - * desired field - * @throws IllegalAccessException - * If the desired field cannot be accessed - * @throws NoSuchFieldException - * If the desired field of the desired class cannot be found - * @throws SecurityException - * If the desired field cannot be made accessible - * @throws ClassNotFoundException - * If the desired target class with the specified name and - * package cannot be found - * @see #setValue(Object, Class, boolean, String, Object) - */ - public static void setValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException - { - setValue(instance, packageType.getClass(className), declared, fieldName, value); - } - - /** - * Sets the value of a field with the given name of an object - * - * @param instance - * Target object - * @param declared - * Whether the desired field is declared or not - * @param fieldName - * Name of the desired field - * @param value - * New value - * @throws IllegalArgumentException - * If the type of the value does not match the type of the - * desired field - * @throws IllegalAccessException - * If the desired field cannot be accessed - * @throws NoSuchFieldException - * If the desired field of the target object cannot be found - * @throws SecurityException - * If the desired field cannot be made accessible - * @see #setValue(Object, Class, boolean, String, Object) - */ - public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException - { - setValue(instance, instance.getClass(), declared, fieldName, value); - } - - /** - * Represents an enumeration of dynamic packages of NMS and CraftBukkit - *

- * This class is part of the ReflectionUtils and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.0 - */ - public enum PackageType - { - MINECRAFT_SERVER("net.minecraft.server." + getServerVersion()), CRAFTBUKKIT("org.bukkit.craftbukkit." + getServerVersion()), CRAFTBUKKIT_BLOCK(CRAFTBUKKIT, "block"), CRAFTBUKKIT_CHUNKIO(CRAFTBUKKIT, "chunkio"), CRAFTBUKKIT_COMMAND(CRAFTBUKKIT, "command"), CRAFTBUKKIT_CONVERSATIONS(CRAFTBUKKIT, "conversations"), CRAFTBUKKIT_ENCHANTMENS(CRAFTBUKKIT, "enchantments"), CRAFTBUKKIT_ENTITY(CRAFTBUKKIT, "entity"), CRAFTBUKKIT_EVENT(CRAFTBUKKIT, "event"), CRAFTBUKKIT_GENERATOR(CRAFTBUKKIT, "generator"), CRAFTBUKKIT_HELP(CRAFTBUKKIT, "help"), CRAFTBUKKIT_INVENTORY(CRAFTBUKKIT, "inventory"), CRAFTBUKKIT_MAP(CRAFTBUKKIT, "map"), CRAFTBUKKIT_METADATA(CRAFTBUKKIT, "metadata"), CRAFTBUKKIT_POTION(CRAFTBUKKIT, "potion"), CRAFTBUKKIT_PROJECTILES(CRAFTBUKKIT, "projectiles"), CRAFTBUKKIT_SCHEDULER(CRAFTBUKKIT, "scheduler"), CRAFTBUKKIT_SCOREBOARD(CRAFTBUKKIT, "scoreboard"), CRAFTBUKKIT_UPDATER(CRAFTBUKKIT, "updater"), CRAFTBUKKIT_UTIL(CRAFTBUKKIT, "util"); - - private final String path; - - /** - * Construct a new package type - * - * @param path - * Path of the package - */ - private PackageType(String path) - { - this.path = path; - } - - /** - * Construct a new package type - * - * @param parent - * Parent package of the package - * @param path - * Path of the package - */ - private PackageType(PackageType parent, String path) - { - this(parent + "." + path); - } - - /** - * Returns the path of this package type - * - * @return The path - */ - public String getPath() - { - return path; - } - - /** - * Returns the class with the given name - * - * @param className - * Name of the desired class - * @return The class with the specified name - * @throws ClassNotFoundException - * If the desired class with the specified name and package - * cannot be found - */ - public Class getClass(String className) throws ClassNotFoundException - { - return Class.forName(this + "." + className); - } - - // Override for convenience - @Override - public String toString() - { - return path; - } - - /** - * Returns the version of your server - * - * @return The server version - */ - public static String getServerVersion() - { - return Bukkit.getServer().getClass().getPackage().getName().substring(23); - } - } - - /** - * Represents an enumeration of Java data types with corresponding classes - *

- * This class is part of the ReflectionUtils and follows the same - * usage conditions - * - * @author DarkBlade12 - * @since 1.0 - */ - public enum DataType - { - BYTE(byte.class, Byte.class), SHORT(short.class, Short.class), INTEGER(int.class, Integer.class), LONG(long.class, Long.class), CHARACTER(char.class, Character.class), FLOAT(float.class, Float.class), DOUBLE(double.class, Double.class), BOOLEAN(boolean.class, Boolean.class); - - private static final Map, DataType> CLASS_MAP = new HashMap, DataType>(); - private final Class primitive; - private final Class reference; - - // Initialize map for quick class lookup - static - { - for(DataType type : values()) - { - CLASS_MAP.put(type.primitive, type); - CLASS_MAP.put(type.reference, type); - } - } - - /** - * Construct a new data type - * - * @param primitive - * Primitive class of this data type - * @param reference - * Reference class of this data type - */ - private DataType(Class primitive, Class reference) - { - this.primitive = primitive; - this.reference = reference; - } - - /** - * Returns the primitive class of this data type - * - * @return The primitive class - */ - public Class getPrimitive() - { - return primitive; - } - - /** - * Returns the reference class of this data type - * - * @return The reference class - */ - public Class getReference() - { - return reference; - } - - /** - * Returns the data type with the given primitive/reference class - * - * @param clazz - * Primitive/Reference class of the data type - * @return The data type - */ - public static DataType fromClass(Class clazz) - { - return CLASS_MAP.get(clazz); - } - - /** - * Returns the primitive class of the data type with the given reference - * class - * - * @param clazz - * Reference class of the data type - * @return The primitive class - */ - public static Class getPrimitive(Class clazz) - { - DataType type = fromClass(clazz); - return type == null ? clazz : type.getPrimitive(); - } - - /** - * Returns the reference class of the data type with the given primitive - * class - * - * @param clazz - * Primitive class of the data type - * @return The reference class - */ - public static Class getReference(Class clazz) - { - DataType type = fromClass(clazz); - return type == null ? clazz : type.getReference(); - } - - /** - * Returns the primitive class array of the given class array - * - * @param classes - * Given class array - * @return The primitive class array - */ - public static Class[] getPrimitive(Class[] classes) - { - int length = classes == null ? 0 : classes.length; - Class[] types = new Class[length]; - for(int index = 0; index < length; index++) - { - types[index] = getPrimitive(classes[index]); - } - return types; - } - - /** - * Returns the reference class array of the given class array - * - * @param classes - * Given class array - * @return The reference class array - */ - public static Class[] getReference(Class[] classes) - { - int length = classes == null ? 0 : classes.length; - Class[] types = new Class[length]; - for(int index = 0; index < length; index++) - { - types[index] = getReference(classes[index]); - } - return types; - } - - /** - * Returns the primitive class array of the given object array - * - * @param objects - * Given object array - * @return The primitive class array - */ - public static Class[] getPrimitive(Object[] objects) - { - int length = objects == null ? 0 : objects.length; - Class[] types = new Class[length]; - for(int index = 0; index < length; index++) - { - types[index] = getPrimitive(objects[index].getClass()); - } - return types; - } - - /** - * Returns the reference class array of the given object array - * - * @param objects - * Given object array - * @return The reference class array - */ - public static Class[] getReference(Object[] objects) - { - int length = objects == null ? 0 : objects.length; - Class[] types = new Class[length]; - for(int index = 0; index < length; index++) - { - types[index] = getReference(objects[index].getClass()); - } - return types; - } - - /** - * Compares two class arrays on equivalence - * - * @param primary - * Primary class array - * @param secondary - * Class array which is compared to the primary array - * @return Whether these arrays are equal or not - */ - public static boolean compare(Class[] primary, Class[] secondary) - { - if(primary == null || secondary == null || primary.length != secondary.length) - { - return false; - } - for(int index = 0; index < primary.length; index++) - { - Class primaryClass = primary[index]; - Class secondaryClass = secondary[index]; - if(primaryClass.equals(secondaryClass) || primaryClass.isAssignableFrom(secondaryClass)) - { - continue; - } - return false; - } - return true; - } - } -} \ No newline at end of file diff --git a/src/main/java/ninja/bytecode/iris/util/ResourceLoader.java b/src/main/java/ninja/bytecode/iris/util/ResourceLoader.java new file mode 100644 index 000000000..4c2561316 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/ResourceLoader.java @@ -0,0 +1,167 @@ +package ninja.bytecode.iris.util; + +import java.io.File; +import java.util.concurrent.locks.ReentrantLock; + +import com.google.gson.Gson; + +import ninja.bytecode.iris.Iris; +import ninja.bytecode.iris.object.IrisRegistrant; +import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.collections.KMap; + +public class ResourceLoader +{ + protected File root; + protected String folderName; + protected String resourceTypeName; + protected KMap folderMapCache; + protected KMap loadCache; + protected KList folderCache; + protected Class objectClass; + protected ReentrantLock lock; + + public ResourceLoader(File root, String folderName, String resourceTypeName, Class objectClass) + { + lock = new ReentrantLock(); + folderMapCache = new KMap<>(); + this.objectClass = objectClass; + this.resourceTypeName = resourceTypeName; + this.root = root; + this.folderName = folderName; + loadCache = new KMap<>(); + } + + protected T loadFile(File j, String key, String name) + { + try + { + T t = new Gson().fromJson(IO.readAll(j), objectClass); + loadCache.put(key, t); + Iris.hotloader.track(j); + Iris.info("Loading " + resourceTypeName + ": " + j.getPath()); + t.setLoadKey(name); + lock.unlock(); + return t; + } + + catch(Throwable e) + { + lock.unlock(); + Iris.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage()); + return null; + } + } + + public T load(String name) + { + String key = name + "-" + objectClass.getCanonicalName(); + + if(loadCache.containsKey(key)) + { + T t = loadCache.get(key); + return t; + } + + lock.lock(); + 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 loadFile(j, key, name); + } + } + + File file = new File(i, name + ".json"); + + if(file.exists()) + { + return loadFile(file, key, name); + } + } + + Iris.warn("Couldn't find " + resourceTypeName + ": " + name); + + lock.unlock(); + return null; + } + + public KList getFolders() + { + if(folderCache == null) + { + folderCache = new KList<>(); + + for(File i : root.listFiles()) + { + if(i.isDirectory()) + { + for(File j : i.listFiles()) + { + if(j.isDirectory() && j.getName().equals(folderName)) + { + folderCache.add(j); + break; + } + } + } + } + } + + return folderCache; + } + + 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() + { + loadCache.clear(); + folderCache = 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.containsKey(next); + } +} diff --git a/src/main/java/ninja/bytecode/iris/util/SBlockVector.java b/src/main/java/ninja/bytecode/iris/util/SBlockVector.java deleted file mode 100644 index f9cd1e181..000000000 --- a/src/main/java/ninja/bytecode/iris/util/SBlockVector.java +++ /dev/null @@ -1,169 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.configuration.serialization.SerializableAs; -import org.bukkit.util.BlockVector; -import org.bukkit.util.Vector; - -/** - * A vector with a hash function that floors the X, Y, Z components, a la - * BlockVector in WorldEdit. BlockVectors can be used in hash sets and hash - * maps. Be aware that BlockVectors are mutable, but it is important that - * BlockVectors are never changed once put into a hash set or hash map. - */ -@SerializableAs("BlockVector") -public class SBlockVector -{ - private short x; - private short y; - private short z; - - /** - * Construct the vector with all components as 0. - */ - public SBlockVector() - { - this.x = 0; - this.y = 0; - this.z = 0; - } - - /** - * Construct the vector with another vector. - * - * @param vec - * The other vector. - */ - public SBlockVector(Vector vec) - { - this.x = (short) vec.getX(); - this.y = (short) vec.getY(); - this.z = (short) vec.getZ(); - } - - /** - * Construct the vector with provided integer components. - * - * @param x - * X component - * @param y - * Y component - * @param z - * Z component - */ - public SBlockVector(int x, int y, int z) - { - this.x = (short) x; - this.y = (short) y; - this.z = (short) z; - } - - /** - * Construct the vector with provided double components. - * - * @param x - * X component - * @param y - * Y component - * @param z - * Z component - */ - public SBlockVector(double x, double y, double z) - { - this.x = (short) x; - this.y = (short) y; - this.z = (short) z; - } - - /** - * Construct the vector with provided float components. - * - * @param x - * X component - * @param y - * Y component - * @param z - * Z component - */ - public SBlockVector(float x, float y, float z) - { - this.x = (short) x; - this.y = (short) y; - this.z = (short) z; - } - - /** - * Get a new block vector. - * - * @return vector - */ - @Override - public SBlockVector clone() - { - return new SBlockVector(x, y, z); - } - - public double getX() - { - return x; - } - - public void setX(double x) - { - this.x = (short) x; - } - - public double getY() - { - return y; - } - - public void setY(double y) - { - this.y = (short) y; - } - - public double getZ() - { - return z; - } - - public void setZ(double z) - { - this.z = (short) z; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + x; - result = prime * result + y; - result = prime * result + z; - return result; - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - return true; - if(obj == null) - return false; - if(getClass() != obj.getClass()) - return false; - SBlockVector other = (SBlockVector) obj; - if(x != other.x) - return false; - if(y != other.y) - return false; - if(z != other.z) - return false; - return true; - } - - public BlockVector toBlockVector() - { - return new BlockVector(x, y, z); - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/SChunkVector.java b/src/main/java/ninja/bytecode/iris/util/SChunkVector.java deleted file mode 100644 index 31e1c080a..000000000 --- a/src/main/java/ninja/bytecode/iris/util/SChunkVector.java +++ /dev/null @@ -1,76 +0,0 @@ -package ninja.bytecode.iris.util; - -public class SChunkVector -{ - private byte x; - private byte z; - - public SChunkVector(int x, int z) - { - this.x = (byte) (x); - this.z = (byte) (z); - } - - public SChunkVector(byte x, byte z) - { - this.x = x; - this.z = z; - } - - public SChunkVector(double x, double z) - { - this((int) Math.round(x), (int) Math.round(z)); - } - - public SChunkVector() - { - this((byte) 0, (byte) 0); - } - - public int getX() - { - return x; - } - - public void setX(int x) - { - this.x = (byte) x; - } - - public int getZ() - { - return z; - } - - public void setZ(int z) - { - this.z = (byte) z; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + x; - result = prime * result + z; - return result; - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - return true; - if(obj == null) - return false; - if(getClass() != obj.getClass()) - return false; - SChunkVector other = (SChunkVector) obj; - if(x != other.x) - return false; - if(z != other.z) - return false; - return true; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/SChunkVectorShort.java b/src/main/java/ninja/bytecode/iris/util/SChunkVectorShort.java deleted file mode 100644 index 57cae1305..000000000 --- a/src/main/java/ninja/bytecode/iris/util/SChunkVectorShort.java +++ /dev/null @@ -1,72 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.util.Objects; - -public class SChunkVectorShort -{ - private short x; - private short z; - - public SChunkVectorShort(int x, int z) - { - this.x = (short) (x); - this.z = (short) (z); - } - - public SChunkVectorShort(short x, short z) - { - this.x = x; - this.z = z; - } - - public SChunkVectorShort(double x, double z) - { - this((int) Math.round(x), (int) Math.round(z)); - } - - public SChunkVectorShort() - { - this((short) 0, (short) 0); - } - - public int getX() - { - return x; - } - - public void setX(int x) - { - this.x = (short) x; - } - - public int getZ() - { - return z; - } - - public void setZ(int z) - { - this.z = (short) z; - } - - @Override - public int hashCode() - { - return Objects.hash(x, z); - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - { - return true; - } - if(!(obj instanceof SChunkVectorShort)) - { - return false; - } - SChunkVectorShort other = (SChunkVectorShort) obj; - return x == other.x && z == other.z; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/SMCAVector.java b/src/main/java/ninja/bytecode/iris/util/SMCAVector.java deleted file mode 100644 index 1becfc7d1..000000000 --- a/src/main/java/ninja/bytecode/iris/util/SMCAVector.java +++ /dev/null @@ -1,61 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.util.Objects; - -public class SMCAVector -{ - private int x; - private int z; - - public SMCAVector(int x, int z) - { - this.x = x; - this.z = z; - } - - public SMCAVector() - { - this(0, 0); - } - - 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; - } - - @Override - public int hashCode() - { - return Objects.hash(x, z); - } - - @Override - public boolean equals(Object obj) - { - if(this == obj) - { - return true; - } - if(!(obj instanceof SMCAVector)) - { - return false; - } - SMCAVector other = (SMCAVector) obj; - return x == other.x && z == other.z; - } -} diff --git a/src/main/java/ninja/bytecode/iris/util/SNG.java b/src/main/java/ninja/bytecode/iris/util/SNG.java new file mode 100644 index 000000000..fb210cb46 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/SNG.java @@ -0,0 +1,377 @@ +package ninja.bytecode.iris.util; + +import java.util.Random; + +/** + * A speed-improved simplex noise algorithm. + * + *

+ * Based on example code by Stefan Gustavson (stegu@itn.liu.se). Optimisations + * by Peter Eastman (peastman@drizzle.stanford.edu). Better rank ordering method + * by Stefan Gustavson in 2012. + * + *

+ * This could be sped up even further, but it's useful as is. + */ +public class SNG extends PerlinNoise +{ + + protected static final double SQRT_3 = 1.7320508075688772; // Math.sqrt(3) + protected static final double F2 = 0.5 * (SQRT_3 - 1); + protected static final double G2 = (3 - SQRT_3) / 6; + protected static final double G22 = G2 * 2.0 - 1; + protected static final double F3 = 1.0 / 3.0; + protected static final double G3 = 1.0 / 6.0; + protected static final double G32 = G3 * 2.0; + protected static final double G33 = G3 * 3.0 - 1.0; + private static Grad[] grad3 = {new Grad(1, 1, 0), new Grad(-1, 1, 0), new Grad(1, -1, 0), new Grad(-1, -1, 0), new Grad(1, 0, 1), new Grad(-1, 0, 1), new Grad(1, 0, -1), new Grad(-1, 0, -1), new Grad(0, 1, 1), new Grad(0, -1, 1), new Grad(0, 1, -1), new Grad(0, -1, -1)}; + protected final int[] permMod12 = new int[512]; + + /** + * Creates a simplex noise generator. + * + * @param rand + * the PRNG to use + */ + public SNG(Random rand) + { + super(rand); + for(int i = 0; i < 512; i++) + { + permMod12[i] = perm[i] % 12; + } + } + + public static int floor(double x) + { + return x > 0 ? (int) x : (int) x - 1; + } + + protected static double dot(Grad g, double x, double y) + { + return g.x * x + g.y * y; + } + + protected static double dot(Grad g, double x, double y, double z) + { + return g.x * x + g.y * y + g.z * z; + } + + @Override + protected double[] get2dNoise(double[] noise, double x, double z, int sizeX, int sizeY, double scaleX, double scaleY, double amplitude) + { + int index = 0; + for(int i = 0; i < sizeY; i++) + { + double zin = offsetY + (z + i) * scaleY; + for(int j = 0; j < sizeX; j++) + { + double xin = offsetX + (x + j) * scaleX; + noise[index++] += simplex2D(xin, zin) * amplitude; + } + } + return noise; + } + + @Override + protected double[] get3dNoise(double[] noise, double x, double y, double z, int sizeX, int sizeY, int sizeZ, double scaleX, double scaleY, double scaleZ, double amplitude) + { + int index = 0; + for(int i = 0; i < sizeZ; i++) + { + double zin = offsetZ + (z + i) * scaleZ; + for(int j = 0; j < sizeX; j++) + { + double xin = offsetX + (x + j) * scaleX; + for(int k = 0; k < sizeY; k++) + { + double yin = offsetY + (y + k) * scaleY; + noise[index++] += simplex3D(xin, yin, zin) * amplitude; + } + } + } + return noise; + } + + @Override + public double noise(double xin, double yin) + { + xin += offsetX; + yin += offsetY; + return simplex2D(xin, yin); + } + + @Override + public double noise(double xin, double yin, double zin) + { + xin += offsetX; + yin += offsetY; + zin += offsetZ; + return simplex3D(xin, yin, zin); + } + + private double simplex2D(double xin, double yin) + { + // Skew the input space to determine which simplex cell we're in + double s = (xin + yin) * F2; // Hairy factor for 2D + int i = floor(xin + s); + int j = floor(yin + s); + double t = (i + j) * G2; + double dx0 = i - t; // Unskew the cell origin back to (x,y) space + double dy0 = j - t; + double x0 = xin - dx0; // The x,y distances from the cell origin + double y0 = yin - dy0; + + // For the 2D case, the simplex shape is an equilateral triangle. + + // Determine which simplex we are in. + int i1; // Offsets for second (middle) corner of simplex in (i,j) coords + int j1; + if(x0 > y0) + { + i1 = 1; // lower triangle, XY order: (0,0)->(1,0)->(1,1) + j1 = 0; + } + else + { + i1 = 0; // upper triangle, YX order: (0,0)->(0,1)->(1,1) + j1 = 1; + } + + // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and + // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where + // c = (3-sqrt(3))/6 + + double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + double y1 = y0 - j1 + G2; + double x2 = x0 + G22; // Offsets for last corner in (x,y) unskewed coords + double y2 = y0 + G22; + + // Work out the hashed gradient indices of the three simplex corners + int ii = i & 255; + int jj = j & 255; + int gi0 = permMod12[ii + perm[jj]]; + int gi1 = permMod12[ii + i1 + perm[jj + j1]]; + int gi2 = permMod12[ii + 1 + perm[jj + 1]]; + + // Calculate the contribution from the three corners + double t0 = 0.5 - x0 * x0 - y0 * y0; + double n0; + if(t0 < 0) + { + n0 = 0.0; + } + else + { + t0 *= t0; + n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient + } + + double t1 = 0.5 - x1 * x1 - y1 * y1; + double n1; + if(t1 < 0) + { + n1 = 0.0; + } + else + { + t1 *= t1; + n1 = t1 * t1 * dot(grad3[gi1], x1, y1); + } + + double t2 = 0.5 - x2 * x2 - y2 * y2; + double n2; + if(t2 < 0) + { + n2 = 0.0; + } + else + { + t2 *= t2; + n2 = t2 * t2 * dot(grad3[gi2], x2, y2); + } + + // Add contributions from each corner to get the final noise value. + // The result is scaled to return values in the interval [-1,1]. + return 70.0 * (n0 + n1 + n2); + } + + private double simplex3D(double xin, double yin, double zin) + { + // Skew the input space to determine which simplex cell we're in + double s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D + int i = floor(xin + s); + int j = floor(yin + s); + int k = floor(zin + s); + double t = (i + j + k) * G3; + double dx0 = i - t; // Unskew the cell origin back to (x,y,z) space + double dy0 = j - t; + double dz0 = k - t; + + // For the 3D case, the simplex shape is a slightly irregular tetrahedron. + + int i1; // Offsets for second corner of simplex in (i,j,k) coords + int j1; + int k1; + int i2; // Offsets for third corner of simplex in (i,j,k) coords + int j2; + int k2; + + double x0 = xin - dx0; // The x,y,z distances from the cell origin + double y0 = yin - dy0; + double z0 = zin - dz0; + // Determine which simplex we are in + if(x0 >= y0) + { + if(y0 >= z0) + { + i1 = 1; // X Y Z order + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; + } + else if(x0 >= z0) + { + i1 = 1; // X Z Y order + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 0; + k2 = 1; + } + else + { + i1 = 0; // Z X Y order + j1 = 0; + k1 = 1; + i2 = 1; + j2 = 0; + k2 = 1; + } + } + else + { // x0 +{ + 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/org/jnbt/StringTag.java b/src/main/java/ninja/bytecode/iris/util/StringTag.java similarity index 98% rename from src/main/java/org/jnbt/StringTag.java rename to src/main/java/ninja/bytecode/iris/util/StringTag.java index 80e8ba1d6..d8a48ab43 100644 --- a/src/main/java/org/jnbt/StringTag.java +++ b/src/main/java/ninja/bytecode/iris/util/StringTag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/org/jnbt/Tag.java b/src/main/java/ninja/bytecode/iris/util/Tag.java similarity index 98% rename from src/main/java/org/jnbt/Tag.java rename to src/main/java/ninja/bytecode/iris/util/Tag.java index 80c7ff6f9..33f171b09 100644 --- a/src/main/java/org/jnbt/Tag.java +++ b/src/main/java/ninja/bytecode/iris/util/Tag.java @@ -1,4 +1,4 @@ -package org.jnbt; +package ninja.bytecode.iris.util; /* * JNBT License diff --git a/src/main/java/ninja/bytecode/iris/util/VectorMath.java b/src/main/java/ninja/bytecode/iris/util/VectorMath.java index c9e0d05af..99cdf3e87 100644 --- a/src/main/java/ninja/bytecode/iris/util/VectorMath.java +++ b/src/main/java/ninja/bytecode/iris/util/VectorMath.java @@ -1,5 +1,6 @@ package ninja.bytecode.iris.util; +import org.bukkit.Axis; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.BlockFace; diff --git a/src/main/java/ninja/bytecode/iris/util/VisualEffect.java b/src/main/java/ninja/bytecode/iris/util/VisualEffect.java deleted file mode 100644 index 2f619b094..000000000 --- a/src/main/java/ninja/bytecode/iris/util/VisualEffect.java +++ /dev/null @@ -1,17 +0,0 @@ -package ninja.bytecode.iris.util; - -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import ninja.bytecode.shuriken.collections.KList; - -public interface VisualEffect -{ - public void play(Location l); - - public void play(Location l, double r); - - public void play(Location l, Player p); - - public void play(Location l, KList p); -} diff --git a/src/main/java/ninja/bytecode/iris/util/WeightMap.java b/src/main/java/ninja/bytecode/iris/util/WeightMap.java new file mode 100644 index 000000000..322e91201 --- /dev/null +++ b/src/main/java/ninja/bytecode/iris/util/WeightMap.java @@ -0,0 +1,53 @@ +package ninja.bytecode.iris.util; + +import ninja.bytecode.shuriken.collections.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/ninja/bytecode/iris/util/WorldState.java b/src/main/java/ninja/bytecode/iris/util/WorldState.java deleted file mode 100644 index a50485ef3..000000000 --- a/src/main/java/ninja/bytecode/iris/util/WorldState.java +++ /dev/null @@ -1,132 +0,0 @@ -package ninja.bytecode.iris.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.zip.GZIPInputStream; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; - -import net.md_5.bungee.api.ChatColor; -import ninja.bytecode.iris.Iris; -import ninja.bytecode.shuriken.collections.KMap; -import ninja.bytecode.shuriken.io.CustomOutputStream; -import ninja.bytecode.shuriken.logging.L; - -public class WorldState implements Listener -{ - private int taskId; - private KMap stateCache; - private World world; - - @SuppressWarnings("deprecation") - public WorldState(World world) - { - this.world = world; - taskId = Bukkit.getScheduler().scheduleAsyncRepeatingTask(Iris.instance, this::tick, 20, 20 * 18); - Bukkit.getPluginManager().registerEvents(this, Iris.instance); - } - - public void tick() - { - for(MCAPos i : stateCache.k()) - { - MCAState state = stateCache.get(i); - - if(state.isDirty()) - { - try - { - saveMCAState(i, state); - } - - catch(IOException e) - { - L.f(ChatColor.RED + "Failed to save MCA State " + i.toFileName()); - L.ex(e); - } - } - } - } - - public void close() - { - HandlerList.unregisterAll(this); - Bukkit.getScheduler().cancelTask(taskId); - - for(MCAPos i : stateCache.k()) - { - try - { - saveMCAState(i, stateCache.get(i)); - } - - catch(IOException e) - { - e.printStackTrace(); - } - } - } - - public void unloadState(MCAPos pos) - { - stateCache.remove(pos); - L.v(ChatColor.GRAY + "Unloaded MCA State " + pos.toFileName()); - } - - public MCAState getState(MCAPos pos) - { - if(!stateCache.containsKey(pos)) - { - try - { - stateCache.put(pos, loadMCAState(pos)); - } - - catch(IOException e) - { - L.f(ChatColor.RED + "Failed to read MCA State " + pos.toFileName()); - L.ex(e); - L.w(ChatColor.YELLOW + "Created Fallback MCA State " + pos.toString()); - stateCache.put(pos, new MCAState()); - } - } - - return stateCache.get(pos); - } - - private void saveMCAState(MCAPos pos, MCAState state) throws IOException - { - File file = new File(world.getWorldFolder(), "iris/state/" + pos.toFileName()); - file.getParentFile().mkdirs(); - FileOutputStream fos = new FileOutputStream(file); - CustomOutputStream cos = new CustomOutputStream(fos, 9); - state.write(cos); - state.saved(); - L.v(ChatColor.GRAY + "Saved MCA State " + pos.toString()); - } - - private MCAState loadMCAState(MCAPos pos) throws IOException - { - MCAState state = new MCAState(); - File file = new File(world.getWorldFolder(), "iris/state/" + pos.toFileName()); - - if(!file.exists()) - { - file.getParentFile().mkdirs(); - state.setDirty(); - L.v(ChatColor.GRAY + "Created MCA State " + pos.toString()); - return state; - } - - FileInputStream fin = new FileInputStream(file); - GZIPInputStream gzi = new GZIPInputStream(fin); - state.read(gzi); - L.v(ChatColor.GRAY + "Loaded MCA State " + pos.toString()); - return state; - } -} diff --git a/src/main/java/ninja/bytecode/iris/controller/WandController.java b/src/main/java/ninja/bytecode/iris/wand/WandController.java similarity index 80% rename from src/main/java/ninja/bytecode/iris/controller/WandController.java rename to src/main/java/ninja/bytecode/iris/wand/WandController.java index 7bad52843..e1e38529c 100644 --- a/src/main/java/ninja/bytecode/iris/controller/WandController.java +++ b/src/main/java/ninja/bytecode/iris/wand/WandController.java @@ -1,4 +1,4 @@ -package ninja.bytecode.iris.controller; +package ninja.bytecode.iris.wand; import java.awt.Color; import java.util.Iterator; @@ -7,11 +7,13 @@ import org.bukkit.Bukkit; import org.bukkit.ChatColor; 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.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; @@ -21,22 +23,16 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.util.BlockVector; import org.bukkit.util.Vector; -import mortar.bukkit.plugin.Controller; -import mortar.compute.math.M; import ninja.bytecode.iris.Iris; -import ninja.bytecode.iris.generator.genobject.GenObject; +import ninja.bytecode.iris.object.IrisObject; import ninja.bytecode.iris.util.Cuboid; -import ninja.bytecode.iris.util.MB; -import ninja.bytecode.iris.util.ParticleEffect; -import ninja.bytecode.iris.util.ParticleRedstone; import ninja.bytecode.shuriken.collections.KList; +import ninja.bytecode.shuriken.math.M; -public class WandController extends Controller +public class WandController implements Listener { - @Override - public void start() + public WandController() { - // TODO: Optimize Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, () -> { for(Player i : Bukkit.getOnlinePlayers()) @@ -44,21 +40,9 @@ public class WandController extends Controller tick(i); } }, 0, 0); + Bukkit.getPluginManager().registerEvents(this, Iris.instance); } - @Override - public void stop() - { - - } - - @Override - public void tick() - { - - } - - @EventHandler public void tick(Player p) { try @@ -78,8 +62,10 @@ public class WandController extends Controller public void draw(Location[] d, Player p) { - ParticleEffect.CRIT_MAGIC.display(0.1f, 1, d[0].clone().add(0.5, 0.5, 0.5).clone().add(Vector.getRandom().subtract(Vector.getRandom()).normalize().clone().multiply(0.65)), p); - ParticleEffect.CRIT.display(0.1f, 1, d[1].clone().add(0.5, 0.5, 0.5).clone().add(Vector.getRandom().subtract(Vector.getRandom()).normalize().clone().multiply(0.65)), 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())) { @@ -104,7 +90,7 @@ public class WandController extends Controller { for(double l = minz - 1; l < maxz + 1; l += 0.25) { - if(M.r(0.25)) + if(M.r(0.2)) { boolean jj = j == minx || j == maxx; boolean kk = k == miny || k == maxy; @@ -148,8 +134,11 @@ public class WandController extends Controller } Location lv = new Location(d[0].getWorld(), aa, bb, cc).clone().add(0.5, 0.5, 0.5).clone().add(push); - int color = Color.getHSBColor((float) (0.5f + (Math.sin((aa + bb + cc + (p.getTicksLived() / 2)) / 20f) / 2)), 1, 1).getRGB(); - new ParticleRedstone().setColor(new Color(color)).play(lv, p); + Color color = Color.getHSBColor((float) (0.5f + (Math.sin((aa + bb + cc + (p.getTicksLived() / 2)) / 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)); } } } @@ -180,13 +169,12 @@ public class WandController extends Controller } } - public static void pasteSchematic(GenObject s, Location at) + public static void pasteSchematic(IrisObject s, Location at) { s.place(at); } - @SuppressWarnings("deprecation") - public static GenObject createSchematic(ItemStack wand, Location at) + public static IrisObject createSchematic(ItemStack wand) { if(!isWand(wand)) { @@ -197,7 +185,7 @@ public class WandController extends Controller { Location[] f = getCuboid(wand); Cuboid c = new Cuboid(f[0], f[1]); - GenObject s = new GenObject(c.getSizeX(), c.getSizeY(), c.getSizeZ()); + IrisObject s = new IrisObject(c.getSizeX(), c.getSizeY(), c.getSizeZ()); Iterator bb = c.iterator(); while(bb.hasNext()) { @@ -208,12 +196,8 @@ public class WandController extends Controller continue; } - byte data = b.getData(); - - BlockVector bv = b.getLocation().subtract(c.getCenter()).toVector().toBlockVector(); - s.put(bv.getBlockX(), bv.getBlockY(), bv.getBlockZ(), - - new MB(b.getType(), data)); + BlockVector bv = b.getLocation().subtract(c.getLowerNE().toVector()).toVector().toBlockVector(); + s.setUnsigned(bv.getBlockX(), bv.getBlockY(), bv.getBlockZ(), b.getBlockData()); } return s; diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index cf9f2607f..66fe82995 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -2,5 +2,7 @@ name: ${project.name} version: ${project.version} main: ninja.bytecode.iris.Iris load: STARTUP -depend: [Mortar] +commands: + iris: +api-version: 1.15 hotload-dependencies: false \ No newline at end of file